blob: 169d69e1b5185a672c024a42ec74490d0463e9b5 [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>
Greg Clayton2a48f522011-05-14 01:50:35 +000017#include <sys/mman.h> // for mmap
Greg Claytonc6c420f2016-08-12 16:46:18 +000018#include <sys/socket.h>
Zachary Turnerbd22bf22016-08-12 16:52:31 +000019#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include <sys/stat.h>
Greg Clayton2a48f522011-05-14 01:50:35 +000021#include <sys/types.h>
Stephen Wilsondc916862011-03-30 00:12:40 +000022#include <time.h>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000023
24// C++ Includes
25#include <algorithm>
26#include <map>
Benjamin Kramer3f69fa62015-04-03 10:55:00 +000027#include <mutex>
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000028#include <sstream>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000029
Johnny Chen01a67862011-10-14 00:42:25 +000030#include "lldb/Breakpoint/Watchpoint.h"
Jim Ingham40af72e2010-06-15 19:49:27 +000031#include "lldb/Interpreter/Args.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000032#include "lldb/Core/ArchSpec.h"
33#include "lldb/Core/Debugger.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000034#include "lldb/Host/ConnectionFileDescriptor.h"
Greg Clayton53239f02011-02-08 05:05:52 +000035#include "lldb/Host/FileSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000036#include "lldb/Core/Module.h"
Greg Clayton1f746072012-08-29 21:13:06 +000037#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000038#include "lldb/Core/PluginManager.h"
39#include "lldb/Core/State.h"
Greg Claytond451c1a2012-04-13 21:24:18 +000040#include "lldb/Core/StreamFile.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000041#include "lldb/Core/StreamString.h"
42#include "lldb/Core/Timer.h"
Greg Clayton70b57652011-05-15 01:25:55 +000043#include "lldb/Core/Value.h"
Greg Claytond04f0ed2015-05-26 18:00:51 +000044#include "lldb/DataFormatters/FormatManager.h"
Zachary Turner4eff2d32015-10-14 21:37:36 +000045#include "lldb/Host/FileSystem.h"
Zachary Turner39de3112014-09-09 20:54:56 +000046#include "lldb/Host/HostThread.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000047#include "lldb/Host/StringConvert.h"
Jason Molendad1fae142012-09-29 08:03:33 +000048#include "lldb/Host/Symbols.h"
Zachary Turner39de3112014-09-09 20:54:56 +000049#include "lldb/Host/ThreadLauncher.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000050#include "lldb/Host/TimeValue.h"
Greg Claytond04f0ed2015-05-26 18:00:51 +000051#include "lldb/Host/XML.h"
Greg Clayton02686b82012-10-15 22:42:16 +000052#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton1d19a2f2012-10-19 22:22:57 +000053#include "lldb/Interpreter/CommandObject.h"
54#include "lldb/Interpreter/CommandObjectMultiword.h"
Greg Clayton02686b82012-10-15 22:42:16 +000055#include "lldb/Interpreter/CommandReturnObject.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000056#include "lldb/Interpreter/OptionValueProperties.h"
Greg Claytone034a042015-05-21 20:52:06 +000057#include "lldb/Interpreter/Options.h"
58#include "lldb/Interpreter/OptionGroupBoolean.h"
59#include "lldb/Interpreter/OptionGroupUInt64.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"
64#include "lldb/Target/Target.h"
65#include "lldb/Target/TargetList.h"
Greg Clayton2a48f522011-05-14 01:50:35 +000066#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molenda705b1802014-06-13 02:37:02 +000067#include "lldb/Target/SystemRuntime.h"
Greg Claytonc6c420f2016-08-12 16:46:18 +000068#include "lldb/Utility/CleanUp.h"
Jason Molendaa34a0c62010-06-09 21:28:42 +000069#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000070
Eugene Zelenko0722f082015-10-24 01:28:05 +000071// Project includes
Chris Lattner30fdc8d2010-06-08 16:52:24 +000072#include "lldb/Host/Host.h"
Chaoren Lin98d0a4b2015-07-14 01:09:28 +000073#include "Plugins/Process/Utility/GDBRemoteSignals.h"
Peter Collingbourne99f9aa02011-06-03 20:40:38 +000074#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Jason Molendac42d2432012-07-25 03:40:06 +000075#include "Plugins/Process/Utility/StopInfoMachException.h"
Jim Ingham43c555d2012-07-04 00:35:43 +000076#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
Greg Claytonc982c762010-07-09 20:39:50 +000077#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000078#include "GDBRemoteRegisterContext.h"
79#include "ProcessGDBRemote.h"
80#include "ProcessGDBRemoteLog.h"
81#include "ThreadGDBRemote.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000082
Zachary Turner54695a32016-08-29 19:58:14 +000083#include "llvm/ADT/StringSwitch.h"
84#include "llvm/Support/raw_ostream.h"
85
Tamas Berghammerdb264a62015-03-31 09:52:22 +000086#define DEBUGSERVER_BASENAME "debugserver"
87using namespace lldb;
88using namespace lldb_private;
89using namespace lldb_private::process_gdb_remote;
Jason Molenda5e8534e2012-10-03 01:29:34 +000090
Greg Claytonc1422c12012-04-09 22:46:21 +000091namespace lldb
92{
93 // Provide a function that can easily dump the packet history if we know a
94 // ProcessGDBRemote * value (which we can get from logs or from debugging).
95 // We need the function in the lldb namespace so it makes it into the final
96 // executable since the LLDB shared library only exports stuff in the lldb
97 // namespace. This allows you to attach with a debugger and call this
98 // function and get the packet history dumped to a file.
99 void
100 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
101 {
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000102 StreamFile strm;
103 Error error (strm.GetFile().Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate));
Greg Claytond451c1a2012-04-13 21:24:18 +0000104 if (error.Success())
105 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
Greg Claytonc1422c12012-04-09 22:46:21 +0000106 }
Eugene Zelenko0722f082015-10-24 01:28:05 +0000107}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000108
Greg Clayton7f982402013-07-15 22:54:20 +0000109namespace {
Steve Pucci5ec012d2014-01-16 22:18:14 +0000110
Greg Clayton7f982402013-07-15 22:54:20 +0000111 static PropertyDefinition
112 g_properties[] =
113 {
114 { "packet-timeout" , OptionValue::eTypeUInt64 , true , 1, NULL, NULL, "Specify the default packet timeout in seconds." },
Greg Claytonef8180a2013-10-15 00:14:28 +0000115 { "target-definition-file" , OptionValue::eTypeFileSpec , true, 0 , NULL, NULL, "The file that provides the description for remote target registers." },
Greg Clayton7f982402013-07-15 22:54:20 +0000116 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
117 };
Ed Maste81b4c5f2016-01-04 01:43:47 +0000118
Greg Clayton7f982402013-07-15 22:54:20 +0000119 enum
120 {
Greg Claytonef8180a2013-10-15 00:14:28 +0000121 ePropertyPacketTimeout,
122 ePropertyTargetDefinitionFile
Greg Clayton7f982402013-07-15 22:54:20 +0000123 };
Ed Maste81b4c5f2016-01-04 01:43:47 +0000124
Greg Clayton7f982402013-07-15 22:54:20 +0000125 class PluginProperties : public Properties
126 {
127 public:
Ed Maste81b4c5f2016-01-04 01:43:47 +0000128
Greg Clayton7f982402013-07-15 22:54:20 +0000129 static ConstString
130 GetSettingName ()
131 {
132 return ProcessGDBRemote::GetPluginNameStatic();
133 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000134
Greg Clayton7f982402013-07-15 22:54:20 +0000135 PluginProperties() :
136 Properties ()
137 {
138 m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
139 m_collection_sp->Initialize(g_properties);
140 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000141
Eugene Zelenko0722f082015-10-24 01:28:05 +0000142 virtual
143 ~PluginProperties()
144 {
145 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000146
Greg Clayton7f982402013-07-15 22:54:20 +0000147 uint64_t
148 GetPacketTimeout()
149 {
150 const uint32_t idx = ePropertyPacketTimeout;
151 return m_collection_sp->GetPropertyAtIndexAsUInt64(NULL, idx, g_properties[idx].default_uint_value);
152 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000153
154 bool
155 SetPacketTimeout(uint64_t timeout)
156 {
157 const uint32_t idx = ePropertyPacketTimeout;
158 return m_collection_sp->SetPropertyAtIndexAsUInt64(NULL, idx, timeout);
159 }
160
Greg Claytonef8180a2013-10-15 00:14:28 +0000161 FileSpec
162 GetTargetDefinitionFile () const
163 {
164 const uint32_t idx = ePropertyTargetDefinitionFile;
165 return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
166 }
Greg Clayton7f982402013-07-15 22:54:20 +0000167 };
Ed Maste81b4c5f2016-01-04 01:43:47 +0000168
Greg Clayton7f982402013-07-15 22:54:20 +0000169 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
Ed Maste81b4c5f2016-01-04 01:43:47 +0000170
Greg Clayton7f982402013-07-15 22:54:20 +0000171 static const ProcessKDPPropertiesSP &
172 GetGlobalPluginProperties()
173 {
174 static ProcessKDPPropertiesSP g_settings_sp;
175 if (!g_settings_sp)
176 g_settings_sp.reset (new PluginProperties ());
177 return g_settings_sp;
178 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000179
Eugene Zelenko0722f082015-10-24 01:28:05 +0000180} // anonymous namespace end
Greg Clayton7f982402013-07-15 22:54:20 +0000181
Greg Claytonfda4fab2014-01-10 22:24:11 +0000182// TODO Randomly assigning a port is unsafe. We should get an unused
183// ephemeral port from the kernel and make sure we reserve it before passing
184// it to debugserver.
185
186#if defined (__APPLE__)
187#define LOW_PORT (IPPORT_RESERVED)
188#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
189#else
190#define LOW_PORT (1024u)
191#define HIGH_PORT (49151u)
192#endif
193
Todd Fiala013434e2014-07-09 01:29:05 +0000194#if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000195static bool rand_initialized = false;
196
Greg Claytonfda4fab2014-01-10 22:24:11 +0000197static inline uint16_t
198get_random_port ()
199{
200 if (!rand_initialized)
201 {
202 time_t seed = time(NULL);
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000203
Greg Claytonfda4fab2014-01-10 22:24:11 +0000204 rand_initialized = true;
205 srand(seed);
206 }
207 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
208}
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000209#endif
Greg Claytonfda4fab2014-01-10 22:24:11 +0000210
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000211ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000212ProcessGDBRemote::GetPluginNameStatic()
213{
Greg Clayton57abc5d2013-05-10 21:47:16 +0000214 static ConstString g_name("gdb-remote");
215 return g_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000216}
217
218const char *
219ProcessGDBRemote::GetPluginDescriptionStatic()
220{
221 return "GDB Remote protocol based debugging plug-in.";
222}
223
224void
225ProcessGDBRemote::Terminate()
226{
227 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
228}
229
Eugene Zelenko0722f082015-10-24 01:28:05 +0000230
Greg Claytonc3776bf2012-02-09 06:16:32 +0000231lldb::ProcessSP
Jim Ingham583bbb12016-03-07 21:50:25 +0000232ProcessGDBRemote::CreateInstance (lldb::TargetSP target_sp, ListenerSP listener_sp, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000233{
Greg Claytonc3776bf2012-02-09 06:16:32 +0000234 lldb::ProcessSP process_sp;
235 if (crash_file_path == NULL)
Jim Ingham583bbb12016-03-07 21:50:25 +0000236 process_sp.reset (new ProcessGDBRemote (target_sp, listener_sp));
Greg Claytonc3776bf2012-02-09 06:16:32 +0000237 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000238}
239
240bool
Zachary Turner7529df92015-09-01 20:02:29 +0000241ProcessGDBRemote::CanDebug (lldb::TargetSP target_sp, bool plugin_specified_by_name)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000242{
Greg Clayton596ed242011-10-21 21:41:45 +0000243 if (plugin_specified_by_name)
244 return true;
245
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000246 // For now we are just making sure the file exists for a given module
Zachary Turner7529df92015-09-01 20:02:29 +0000247 Module *exe_module = target_sp->GetExecutableModulePointer();
Greg Claytonaa149cb2011-08-11 02:48:45 +0000248 if (exe_module)
Greg Claytonc3776bf2012-02-09 06:16:32 +0000249 {
250 ObjectFile *exe_objfile = exe_module->GetObjectFile();
251 // We can't debug core files...
252 switch (exe_objfile->GetType())
253 {
254 case ObjectFile::eTypeInvalid:
255 case ObjectFile::eTypeCoreFile:
256 case ObjectFile::eTypeDebugInfo:
257 case ObjectFile::eTypeObjectFile:
258 case ObjectFile::eTypeSharedLibrary:
259 case ObjectFile::eTypeStubLibrary:
Greg Clayton23f8c952014-03-24 23:10:19 +0000260 case ObjectFile::eTypeJIT:
Greg Claytonc3776bf2012-02-09 06:16:32 +0000261 return false;
262 case ObjectFile::eTypeExecutable:
263 case ObjectFile::eTypeDynamicLinker:
264 case ObjectFile::eTypeUnknown:
265 break;
266 }
Greg Claytonaa149cb2011-08-11 02:48:45 +0000267 return exe_module->GetFileSpec().Exists();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000268 }
Jim Ingham5aee1622010-08-09 23:31:02 +0000269 // However, if there is no executable module, we return true since we might be preparing to attach.
270 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000271}
272
Eugene Zelenko0722f082015-10-24 01:28:05 +0000273//----------------------------------------------------------------------
274// ProcessGDBRemote constructor
275//----------------------------------------------------------------------
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000276ProcessGDBRemote::ProcessGDBRemote(lldb::TargetSP target_sp, ListenerSP listener_sp)
277 : Process(target_sp, listener_sp),
278 m_flags(0),
279 m_gdb_comm(),
280 m_debugserver_pid(LLDB_INVALID_PROCESS_ID),
281 m_last_stop_packet_mutex(),
282 m_register_info(),
283 m_async_broadcaster(NULL, "lldb.process.gdb-remote.async-broadcaster"),
284 m_async_listener_sp(Listener::MakeListener("lldb.process.gdb-remote.async-listener")),
285 m_async_thread_state_mutex(),
286 m_thread_ids(),
287 m_thread_pcs(),
288 m_jstopinfo_sp(),
289 m_jthreadsinfo_sp(),
290 m_continue_c_tids(),
291 m_continue_C_tids(),
292 m_continue_s_tids(),
293 m_continue_S_tids(),
294 m_max_memory_size(0),
295 m_remote_stub_max_memory_size(0),
296 m_addr_to_mmap_size(),
297 m_thread_create_bp_sp(),
298 m_waiting_for_attach(false),
299 m_destroy_tried_resuming(false),
300 m_command_sp(),
301 m_breakpoint_pc_offset(0),
302 m_initial_tid(LLDB_INVALID_THREAD_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000303{
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000304 m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
305 m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue, "async thread continue");
306 m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Pavel Labath50556852015-09-03 09:36:22 +0000307
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000308 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_ASYNC));
Pavel Labath50556852015-09-03 09:36:22 +0000309
310 const uint32_t async_event_mask = eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
311
Jim Ingham583bbb12016-03-07 21:50:25 +0000312 if (m_async_listener_sp->StartListeningForEvents(&m_async_broadcaster, async_event_mask) != async_event_mask)
Pavel Labath50556852015-09-03 09:36:22 +0000313 {
314 if (log)
315 log->Printf("ProcessGDBRemote::%s failed to listen for m_async_broadcaster events", __FUNCTION__);
316 }
317
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000318 const uint32_t gdb_event_mask =
319 Communication::eBroadcastBitReadThreadDidExit | GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify;
Jim Ingham583bbb12016-03-07 21:50:25 +0000320 if (m_async_listener_sp->StartListeningForEvents(&m_gdb_comm, gdb_event_mask) != gdb_event_mask)
Pavel Labath50556852015-09-03 09:36:22 +0000321 {
322 if (log)
323 log->Printf("ProcessGDBRemote::%s failed to listen for m_gdb_comm events", __FUNCTION__);
324 }
325
Greg Clayton7f982402013-07-15 22:54:20 +0000326 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
327 if (timeout_seconds > 0)
328 m_gdb_comm.SetPacketTimeout(timeout_seconds);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000329}
330
Eugene Zelenko0722f082015-10-24 01:28:05 +0000331//----------------------------------------------------------------------
332// Destructor
333//----------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000334ProcessGDBRemote::~ProcessGDBRemote()
335{
336 // m_mach_process.UnregisterNotificationCallbacks (this);
337 Clear();
Greg Clayton1ed54f52011-10-01 00:45:15 +0000338 // We need to call finalize on the process before destroying ourselves
339 // to make sure all of the broadcaster cleanup goes as planned. If we
340 // destruct this class, then Process::~Process() might have problems
341 // trying to fully destroy the broadcaster.
342 Finalize();
Ed Maste81b4c5f2016-01-04 01:43:47 +0000343
Jim Ingham455fa5c2012-11-01 01:15:33 +0000344 // The general Finalize is going to try to destroy the process and that SHOULD
345 // shut down the async thread. However, if we don't kill it it will get stranded and
346 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
347 StopAsyncThread();
348 KillDebugserverProcess();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000349}
350
351//----------------------------------------------------------------------
352// PluginInterface
353//----------------------------------------------------------------------
Greg Clayton57abc5d2013-05-10 21:47:16 +0000354ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000355ProcessGDBRemote::GetPluginName()
356{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000357 return GetPluginNameStatic();
358}
359
360uint32_t
361ProcessGDBRemote::GetPluginVersion()
362{
363 return 1;
364}
365
Greg Claytonef8180a2013-10-15 00:14:28 +0000366bool
367ProcessGDBRemote::ParsePythonTargetDefinition(const FileSpec &target_definition_fspec)
368{
369 ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
370 Error error;
Zachary Turner0641ca12015-03-17 20:04:04 +0000371 StructuredData::ObjectSP module_object_sp(interpreter->LoadPluginModule(target_definition_fspec, error));
Greg Claytonef8180a2013-10-15 00:14:28 +0000372 if (module_object_sp)
373 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000374 StructuredData::DictionarySP target_definition_sp(
375 interpreter->GetDynamicSettings(module_object_sp, &GetTarget(), "gdb-server-target-definition", error));
Greg Claytonef8180a2013-10-15 00:14:28 +0000376
Zachary Turner0641ca12015-03-17 20:04:04 +0000377 if (target_definition_sp)
Greg Claytonef8180a2013-10-15 00:14:28 +0000378 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000379 StructuredData::ObjectSP target_object(target_definition_sp->GetValueForKey("host-info"));
380 if (target_object)
Greg Clayton312bcbe2013-10-17 01:10:23 +0000381 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000382 if (auto host_info_dict = target_object->GetAsDictionary())
Greg Clayton312bcbe2013-10-17 01:10:23 +0000383 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000384 StructuredData::ObjectSP triple_value = host_info_dict->GetValueForKey("triple");
385 if (auto triple_string_value = triple_value->GetAsString())
386 {
387 std::string triple_string = triple_string_value->GetValue();
388 ArchSpec host_arch(triple_string.c_str());
389 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture()))
390 {
391 GetTarget().SetArchitecture(host_arch);
392 }
393 }
Greg Clayton312bcbe2013-10-17 01:10:23 +0000394 }
Greg Clayton312bcbe2013-10-17 01:10:23 +0000395 }
Zachary Turner0641ca12015-03-17 20:04:04 +0000396 m_breakpoint_pc_offset = 0;
397 StructuredData::ObjectSP breakpoint_pc_offset_value = target_definition_sp->GetValueForKey("breakpoint-pc-offset");
398 if (breakpoint_pc_offset_value)
399 {
400 if (auto breakpoint_pc_int_value = breakpoint_pc_offset_value->GetAsInteger())
401 m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
402 }
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000403
Greg Claytond04f0ed2015-05-26 18:00:51 +0000404 if (m_register_info.SetRegisterInfo(*target_definition_sp, GetTarget().GetArchitecture()) > 0)
Greg Claytonef8180a2013-10-15 00:14:28 +0000405 {
406 return true;
407 }
408 }
409 }
410 return false;
411}
412
Jason Molenda21586c82015-09-09 03:36:24 +0000413// If the remote stub didn't give us eh_frame or DWARF register numbers for a register,
414// see if the ABI can provide them.
415// DWARF and eh_frame register numbers are defined as a part of the ABI.
416static void
417AugmentRegisterInfoViaABI (RegisterInfo &reg_info, ConstString reg_name, ABISP abi_sp)
418{
419 if (reg_info.kinds[eRegisterKindEHFrame] == LLDB_INVALID_REGNUM
420 || reg_info.kinds[eRegisterKindDWARF] == LLDB_INVALID_REGNUM)
421 {
422 if (abi_sp)
423 {
424 RegisterInfo abi_reg_info;
425 if (abi_sp->GetRegisterInfoByName (reg_name, abi_reg_info))
426 {
Greg Claytonb1583dc2015-12-04 18:37:48 +0000427 if (reg_info.kinds[eRegisterKindEHFrame] == LLDB_INVALID_REGNUM &&
428 abi_reg_info.kinds[eRegisterKindEHFrame] != LLDB_INVALID_REGNUM)
Jason Molenda21586c82015-09-09 03:36:24 +0000429 {
430 reg_info.kinds[eRegisterKindEHFrame] = abi_reg_info.kinds[eRegisterKindEHFrame];
431 }
Greg Claytonb1583dc2015-12-04 18:37:48 +0000432 if (reg_info.kinds[eRegisterKindDWARF] == LLDB_INVALID_REGNUM &&
433 abi_reg_info.kinds[eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
Jason Molenda21586c82015-09-09 03:36:24 +0000434 {
435 reg_info.kinds[eRegisterKindDWARF] = abi_reg_info.kinds[eRegisterKindDWARF];
436 }
Greg Claytonb1583dc2015-12-04 18:37:48 +0000437 if (reg_info.kinds[eRegisterKindGeneric] == LLDB_INVALID_REGNUM &&
438 abi_reg_info.kinds[eRegisterKindGeneric] != LLDB_INVALID_REGNUM)
439 {
440 reg_info.kinds[eRegisterKindGeneric] = abi_reg_info.kinds[eRegisterKindGeneric];
441 }
Jason Molenda21586c82015-09-09 03:36:24 +0000442 }
443 }
444 }
445}
446
Greg Claytond04f0ed2015-05-26 18:00:51 +0000447static size_t
448SplitCommaSeparatedRegisterNumberString(const llvm::StringRef &comma_separated_regiter_numbers, std::vector<uint32_t> &regnums, int base)
449{
450 regnums.clear();
451 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
452 value_pair.second = comma_separated_regiter_numbers;
453 do
454 {
455 value_pair = value_pair.second.split(',');
456 if (!value_pair.first.empty())
457 {
458 uint32_t reg = StringConvert::ToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, base);
459 if (reg != LLDB_INVALID_REGNUM)
460 regnums.push_back (reg);
461 }
462 } while (!value_pair.second.empty());
463 return regnums.size();
464}
465
Eugene Zelenko0722f082015-10-24 01:28:05 +0000466
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000467void
Greg Clayton513c26c2011-01-29 07:10:55 +0000468ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000469{
Greg Clayton513c26c2011-01-29 07:10:55 +0000470 if (!force && m_register_info.GetNumRegisters() > 0)
471 return;
472
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000473 m_register_info.Clear();
Greg Claytond04f0ed2015-05-26 18:00:51 +0000474
475 // Check if qHostInfo specified a specific packet timeout for this connection.
476 // If so then lets update our setting so the user knows what the timeout is
477 // and can see it.
478 const uint32_t host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
479 if (host_packet_timeout)
480 {
481 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout);
482 }
483
Ed Maste81b4c5f2016-01-04 01:43:47 +0000484 // Register info search order:
Ewan Crawford0c996a92015-06-30 13:08:44 +0000485 // 1 - Use the target definition python file if one is specified.
486 // 2 - If the target definition doesn't have any of the info from the target.xml (registers) then proceed to read the target.xml.
487 // 3 - Fall back on the qRegisterInfo packets.
488
489 FileSpec target_definition_fspec = GetGlobalPluginProperties()->GetTargetDefinitionFile ();
Jason Molenda91e468c2015-08-20 04:29:46 +0000490 if (!target_definition_fspec.Exists())
491 {
492 // If the filename doesn't exist, it may be a ~ not having been expanded - try to resolve it.
493 target_definition_fspec.ResolvePath();
494 }
Ewan Crawford0c996a92015-06-30 13:08:44 +0000495 if (target_definition_fspec)
496 {
497 // See if we can get register definitions from a python file
498 if (ParsePythonTargetDefinition (target_definition_fspec))
Jason Molenda5543abb2015-08-20 03:05:09 +0000499 {
Ewan Crawford0c996a92015-06-30 13:08:44 +0000500 return;
Jason Molenda5543abb2015-08-20 03:05:09 +0000501 }
502 else
503 {
504 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
505 stream_sp->Printf ("ERROR: target description file %s failed to parse.\n", target_definition_fspec.GetPath().c_str());
506 }
Ewan Crawford0c996a92015-06-30 13:08:44 +0000507 }
508
Jim Ingham7b71c0b2016-02-18 23:58:45 +0000509 const ArchSpec &target_arch = GetTarget().GetArchitecture();
510 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
511 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
512
513 // Use the process' architecture instead of the host arch, if available
514 ArchSpec arch_to_use;
515 if (remote_process_arch.IsValid ())
516 arch_to_use = remote_process_arch;
517 else
518 arch_to_use = remote_host_arch;
519
520 if (!arch_to_use.IsValid())
521 arch_to_use = target_arch;
522
523 if (GetGDBServerRegisterInfo (arch_to_use))
Greg Claytond04f0ed2015-05-26 18:00:51 +0000524 return;
Ed Maste81b4c5f2016-01-04 01:43:47 +0000525
Greg Claytond04f0ed2015-05-26 18:00:51 +0000526 char packet[128];
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000527 uint32_t reg_offset = 0;
528 uint32_t reg_num = 0;
Greg Clayton23f59502012-07-17 03:23:13 +0000529 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Ed Maste81b4c5f2016-01-04 01:43:47 +0000530 response_type == StringExtractorGDBRemote::eResponse;
Greg Clayton576d8832011-03-22 04:00:09 +0000531 ++reg_num)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000532 {
Greg Clayton513c26c2011-01-29 07:10:55 +0000533 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
Andy Gibbsa297a972013-06-19 19:04:53 +0000534 assert (packet_len < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000535 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000536 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000537 {
Greg Clayton576d8832011-03-22 04:00:09 +0000538 response_type = response.GetResponseType();
539 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000540 {
Zachary Turner54695a32016-08-29 19:58:14 +0000541 llvm::StringRef name;
542 llvm::StringRef value;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000543 ConstString reg_name;
544 ConstString alt_name;
545 ConstString set_name;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000546 std::vector<uint32_t> value_regs;
547 std::vector<uint32_t> invalidate_regs;
Nitesh Jain52b6cc52016-08-01 13:45:51 +0000548 std::vector<uint8_t> dwarf_opcode_bytes;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000549 RegisterInfo reg_info = { NULL, // Name
550 NULL, // Alt name
551 0, // byte size
552 reg_offset, // offset
553 eEncodingUint, // encoding
Jason Molendabf67a302015-09-01 05:17:01 +0000554 eFormatHex, // format
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000555 {
Jason Molendabf67a302015-09-01 05:17:01 +0000556 LLDB_INVALID_REGNUM, // eh_frame reg num
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000557 LLDB_INVALID_REGNUM, // DWARF reg num
558 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda63bd0db2015-09-15 23:20:34 +0000559 reg_num, // process plugin reg num
Jason Molendafbcb7f22010-09-10 07:49:16 +0000560 reg_num // native register number
Greg Clayton435d85a2012-02-29 19:27:27 +0000561 },
562 NULL,
Nitesh Jain52b6cc52016-08-01 13:45:51 +0000563 NULL,
564 NULL, // Dwarf expression opcode bytes pointer
565 0 // Dwarf expression opcode bytes length
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000566 };
567
568 while (response.GetNameColonValue(name, value))
569 {
Zachary Turner54695a32016-08-29 19:58:14 +0000570 if (name.equals("name"))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000571 {
Zachary Turner54695a32016-08-29 19:58:14 +0000572 reg_name.SetString(value);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000573 }
Zachary Turner54695a32016-08-29 19:58:14 +0000574 else if (name.equals("alt-name"))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000575 {
Zachary Turner54695a32016-08-29 19:58:14 +0000576 alt_name.SetString(value);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000577 }
Zachary Turner54695a32016-08-29 19:58:14 +0000578 else if (name.equals("bitsize"))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000579 {
Zachary Turner54695a32016-08-29 19:58:14 +0000580 value.getAsInteger(0, reg_info.byte_size);
581 reg_info.byte_size /= CHAR_BIT;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000582 }
Zachary Turner54695a32016-08-29 19:58:14 +0000583 else if (name.equals("offset"))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000584 {
Zachary Turner54695a32016-08-29 19:58:14 +0000585 if (value.getAsInteger(0, reg_offset))
586 reg_offset = UINT32_MAX;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000587 }
Zachary Turner54695a32016-08-29 19:58:14 +0000588 else if (name.equals("encoding"))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000589 {
Zachary Turner54695a32016-08-29 19:58:14 +0000590 const Encoding encoding = Args::StringToEncoding(value);
Greg Clayton2443cbd2012-08-24 01:42:50 +0000591 if (encoding != eEncodingInvalid)
592 reg_info.encoding = encoding;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000593 }
Zachary Turner54695a32016-08-29 19:58:14 +0000594 else if (name.equals("format"))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000595 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000596 Format format = eFormatInvalid;
Zachary Turner54695a32016-08-29 19:58:14 +0000597 if (Args::StringToFormat(value.str().c_str(), format, NULL).Success())
Greg Clayton2443cbd2012-08-24 01:42:50 +0000598 reg_info.format = format;
Zachary Turner54695a32016-08-29 19:58:14 +0000599 else
600 {
601 reg_info.format = llvm::StringSwitch<Format>(value)
602 .Case("binary", eFormatBinary)
603 .Case("decimal", eFormatDecimal)
604 .Case("hex", eFormatHex)
605 .Case("float", eFormatFloat)
606 .Case("vector-sint8", eFormatVectorOfSInt8)
607 .Case("vector-uint8", eFormatVectorOfUInt8)
608 .Case("vector-sint16", eFormatVectorOfSInt16)
609 .Case("vector-uint16", eFormatVectorOfUInt16)
610 .Case("vector-sint32", eFormatVectorOfSInt32)
611 .Case("vector-uint32", eFormatVectorOfUInt32)
612 .Case("vector-float32", eFormatVectorOfFloat32)
613 .Case("vector-uint128", eFormatVectorOfUInt128)
614 .Default(eFormatInvalid);
615 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000616 }
Zachary Turner54695a32016-08-29 19:58:14 +0000617 else if (name.equals("set"))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000618 {
Zachary Turner54695a32016-08-29 19:58:14 +0000619 set_name.SetString(value);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000620 }
Zachary Turner54695a32016-08-29 19:58:14 +0000621 else if (name.equals("gcc") || name.equals("ehframe"))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000622 {
Zachary Turner54695a32016-08-29 19:58:14 +0000623 if (value.getAsInteger(0, reg_info.kinds[eRegisterKindEHFrame]))
624 reg_info.kinds[eRegisterKindEHFrame] = LLDB_INVALID_REGNUM;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000625 }
Zachary Turner54695a32016-08-29 19:58:14 +0000626 else if (name.equals("dwarf"))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000627 {
Zachary Turner54695a32016-08-29 19:58:14 +0000628 if (value.getAsInteger(0, reg_info.kinds[eRegisterKindDWARF]))
629 reg_info.kinds[eRegisterKindDWARF] = LLDB_INVALID_REGNUM;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000630 }
Zachary Turner54695a32016-08-29 19:58:14 +0000631 else if (name.equals("generic"))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000632 {
Zachary Turner54695a32016-08-29 19:58:14 +0000633 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister(value);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000634 }
Zachary Turner54695a32016-08-29 19:58:14 +0000635 else if (name.equals("container-regs"))
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000636 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000637 SplitCommaSeparatedRegisterNumberString(value, value_regs, 16);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000638 }
Zachary Turner54695a32016-08-29 19:58:14 +0000639 else if (name.equals("invalidate-regs"))
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000640 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000641 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 16);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000642 }
Zachary Turner54695a32016-08-29 19:58:14 +0000643 else if (name.equals("dynamic_size_dwarf_expr_bytes"))
Nitesh Jain52b6cc52016-08-01 13:45:51 +0000644 {
Zachary Turner54695a32016-08-29 19:58:14 +0000645 size_t dwarf_opcode_len = value.size() / 2;
646 assert(dwarf_opcode_len > 0);
Nitesh Jain52b6cc52016-08-01 13:45:51 +0000647
Zachary Turner54695a32016-08-29 19:58:14 +0000648 dwarf_opcode_bytes.resize(dwarf_opcode_len);
649 reg_info.dynamic_size_dwarf_len = dwarf_opcode_len;
Nitesh Jain52b6cc52016-08-01 13:45:51 +0000650
Zachary Turner54695a32016-08-29 19:58:14 +0000651 StringExtractor opcode_extractor(value);
652 uint32_t ret_val =
653 opcode_extractor.GetHexBytesAvail(dwarf_opcode_bytes.data(), dwarf_opcode_len);
654 assert(dwarf_opcode_len == ret_val);
Nitesh Jain52b6cc52016-08-01 13:45:51 +0000655
Zachary Turner54695a32016-08-29 19:58:14 +0000656 reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data();
Nitesh Jain52b6cc52016-08-01 13:45:51 +0000657 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000658 }
659
Jason Molenda743e86a2010-06-11 23:44:18 +0000660 reg_info.byte_offset = reg_offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000661 assert (reg_info.byte_size != 0);
662 reg_offset += reg_info.byte_size;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000663 if (!value_regs.empty())
664 {
665 value_regs.push_back(LLDB_INVALID_REGNUM);
666 reg_info.value_regs = value_regs.data();
667 }
668 if (!invalidate_regs.empty())
669 {
670 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
671 reg_info.invalidate_regs = invalidate_regs.data();
672 }
673
Jim Ingham7b71c0b2016-02-18 23:58:45 +0000674 // We have to make a temporary ABI here, and not use the GetABI because this code
675 // gets called in DidAttach, when the target architecture (and consequently the ABI we'll get from
676 // the process) may be wrong.
677 ABISP abi_to_use = ABI::FindPlugin(arch_to_use);
678
679 AugmentRegisterInfoViaABI (reg_info, reg_name, abi_to_use);
Jason Molenda21586c82015-09-09 03:36:24 +0000680
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000681 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
682 }
Todd Fiala1a634402014-01-08 07:52:40 +0000683 else
684 {
685 break; // ensure exit before reg_num is incremented
686 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000687 }
688 else
689 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000690 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000691 }
692 }
693
Greg Claytond04f0ed2015-05-26 18:00:51 +0000694 if (m_register_info.GetNumRegisters() > 0)
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000695 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000696 m_register_info.Finalize(GetTarget().GetArchitecture());
697 return;
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000698 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000699
Johnny Chen2fa9de12012-05-14 18:44:23 +0000700 // We didn't get anything if the accumulated reg_num is zero. See if we are
701 // debugging ARM and fill with a hard coded register set until we can get an
702 // updated debugserver down on the devices.
703 // On the other hand, if the accumulated reg_num is positive, see if we can
704 // add composite registers to the existing primordial ones.
Greg Claytond04f0ed2015-05-26 18:00:51 +0000705 bool from_scratch = (m_register_info.GetNumRegisters() == 0);
Johnny Chen2fa9de12012-05-14 18:44:23 +0000706
Johnny Chen2fa9de12012-05-14 18:44:23 +0000707 if (!target_arch.IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000708 {
Jim Ingham7b71c0b2016-02-18 23:58:45 +0000709 if (arch_to_use.IsValid()
710 && (arch_to_use.GetMachine() == llvm::Triple::arm || arch_to_use.GetMachine() == llvm::Triple::thumb)
711 && arch_to_use.GetTriple().getVendor() == llvm::Triple::Apple)
Johnny Chen2fa9de12012-05-14 18:44:23 +0000712 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000713 }
Jason Molenda6d9fe8c2015-08-21 00:13:37 +0000714 else if (target_arch.GetMachine() == llvm::Triple::arm
715 || target_arch.GetMachine() == llvm::Triple::thumb)
Johnny Chen2fa9de12012-05-14 18:44:23 +0000716 {
717 m_register_info.HardcodeARMRegisters(from_scratch);
718 }
719
720 // At this point, we can finalize our register info.
Greg Claytond04f0ed2015-05-26 18:00:51 +0000721 m_register_info.Finalize (GetTarget().GetArchitecture());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000722}
723
724Error
725ProcessGDBRemote::WillLaunch (Module* module)
726{
727 return WillLaunchOrAttach ();
728}
729
730Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000731ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000732{
733 return WillLaunchOrAttach ();
734}
735
736Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000737ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000738{
739 return WillLaunchOrAttach ();
740}
741
742Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000743ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +0000744{
Todd Fialaaf245d12014-06-30 21:05:18 +0000745 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Claytonb766a732011-02-04 01:58:07 +0000746 Error error (WillLaunchOrAttach ());
Ed Maste81b4c5f2016-01-04 01:43:47 +0000747
Greg Claytonb766a732011-02-04 01:58:07 +0000748 if (error.Fail())
749 return error;
750
Greg Clayton2289fa42011-04-30 01:09:13 +0000751 error = ConnectToDebugserver (remote_url);
Greg Claytonb766a732011-02-04 01:58:07 +0000752
753 if (error.Fail())
754 return error;
755 StartAsyncThread ();
756
Greg Claytonc574ede2011-03-10 02:26:48 +0000757 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonb766a732011-02-04 01:58:07 +0000758 if (pid == LLDB_INVALID_PROCESS_ID)
759 {
760 // We don't have a valid process ID, so note that we are connected
Ed Maste81b4c5f2016-01-04 01:43:47 +0000761 // and could now request to launch or attach, or get remote process
Greg Claytonb766a732011-02-04 01:58:07 +0000762 // listings...
763 SetPrivateState (eStateConnected);
764 }
765 else
766 {
767 // We have a valid process
768 SetID (pid);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000769 GetThreadList();
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000770 StringExtractorGDBRemote response;
771 if (m_gdb_comm.GetStopReply(response))
Greg Claytonb766a732011-02-04 01:58:07 +0000772 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000773 SetLastStopPacket(response);
Ewan Crawford78baa192015-05-13 09:18:18 +0000774
775 // '?' Packets must be handled differently in non-stop mode
776 if (GetTarget().GetNonStopModeEnabled())
777 HandleStopReplySequence();
778
Zachary Turner7529df92015-09-01 20:02:29 +0000779 Target &target = GetTarget();
Ed Maste81b4c5f2016-01-04 01:43:47 +0000780 if (!target.GetArchitecture().IsValid())
Jason Molendac62bd7b2013-12-21 05:20:36 +0000781 {
782 if (m_gdb_comm.GetProcessArchitecture().IsValid())
783 {
Zachary Turner7529df92015-09-01 20:02:29 +0000784 target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
Jason Molendac62bd7b2013-12-21 05:20:36 +0000785 }
786 else
787 {
Zachary Turner7529df92015-09-01 20:02:29 +0000788 target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molendac62bd7b2013-12-21 05:20:36 +0000789 }
Carlo Kok74389122013-10-14 07:09:13 +0000790 }
791
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000792 const StateType state = SetThreadStopInfo (response);
Greg Clayton2e309072015-07-17 23:42:28 +0000793 if (state != eStateInvalid)
Greg Claytonb766a732011-02-04 01:58:07 +0000794 {
795 SetPrivateState (state);
796 }
797 else
Daniel Malead01b2952012-11-29 21:49:15 +0000798 error.SetErrorStringWithFormat ("Process %" PRIu64 " was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
Greg Claytonb766a732011-02-04 01:58:07 +0000799 }
800 else
Daniel Malead01b2952012-11-29 21:49:15 +0000801 error.SetErrorStringWithFormat ("Process %" PRIu64 " was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
Greg Claytonb766a732011-02-04 01:58:07 +0000802 }
Jason Molenda16d127c2012-05-03 22:37:30 +0000803
Todd Fialaaf245d12014-06-30 21:05:18 +0000804 if (log)
805 log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": normalizing target architecture initial triple: %s (GetTarget().GetArchitecture().IsValid() %s, m_gdb_comm.GetHostArchitecture().IsValid(): %s)", __FUNCTION__, GetID (), GetTarget ().GetArchitecture ().GetTriple ().getTriple ().c_str (), GetTarget ().GetArchitecture ().IsValid () ? "true" : "false", m_gdb_comm.GetHostArchitecture ().IsValid () ? "true" : "false");
806
807
808 if (error.Success()
Jason Molenda16d127c2012-05-03 22:37:30 +0000809 && !GetTarget().GetArchitecture().IsValid()
810 && m_gdb_comm.GetHostArchitecture().IsValid())
811 {
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000812 // Prefer the *process'* architecture over that of the *host*, if available.
813 if (m_gdb_comm.GetProcessArchitecture().IsValid())
814 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
815 else
816 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molenda16d127c2012-05-03 22:37:30 +0000817 }
818
Todd Fialaaf245d12014-06-30 21:05:18 +0000819 if (log)
820 log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": normalized target architecture triple: %s", __FUNCTION__, GetID (), GetTarget ().GetArchitecture ().GetTriple ().getTriple ().c_str ());
821
Chaoren Lin98d0a4b2015-07-14 01:09:28 +0000822 if (error.Success())
Jaydeep Patil6fc590d2015-07-30 05:06:51 +0000823 {
824 PlatformSP platform_sp = GetTarget().GetPlatform();
825 if (platform_sp && platform_sp->IsConnected())
826 SetUnixSignals(platform_sp->GetUnixSignals());
827 else
828 SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
829 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000830
Greg Claytonb766a732011-02-04 01:58:07 +0000831 return error;
832}
833
834Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000835ProcessGDBRemote::WillLaunchOrAttach ()
836{
837 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000838 m_stdio_communication.Clear ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000839 return error;
840}
841
842//----------------------------------------------------------------------
843// Process Control
844//----------------------------------------------------------------------
845Error
Jean-Daniel Dupas7782de92013-12-09 22:52:50 +0000846ProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000847{
Todd Fiala75f47c32014-10-11 21:42:09 +0000848 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton4957bf62010-09-30 21:49:03 +0000849 Error error;
Greg Clayton982c9762011-11-03 21:22:33 +0000850
Todd Fiala75f47c32014-10-11 21:42:09 +0000851 if (log)
852 log->Printf ("ProcessGDBRemote::%s() entered", __FUNCTION__);
853
Greg Clayton982c9762011-11-03 21:22:33 +0000854 uint32_t launch_flags = launch_info.GetFlags().Get();
Chaoren Lind3173f32015-05-29 19:52:29 +0000855 FileSpec stdin_file_spec{};
856 FileSpec stdout_file_spec{};
857 FileSpec stderr_file_spec{};
858 FileSpec working_dir = launch_info.GetWorkingDirectory();
Greg Clayton982c9762011-11-03 21:22:33 +0000859
Zachary Turner696b5282014-08-14 16:01:25 +0000860 const FileAction *file_action;
Greg Clayton982c9762011-11-03 21:22:33 +0000861 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
862 if (file_action)
863 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000864 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000865 stdin_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000866 }
867 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
868 if (file_action)
869 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000870 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000871 stdout_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000872 }
873 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
874 if (file_action)
875 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000876 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000877 stderr_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000878 }
879
Todd Fiala75f47c32014-10-11 21:42:09 +0000880 if (log)
881 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000882 if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
Vince Harron4a8abd32015-02-13 19:15:24 +0000883 log->Printf ("ProcessGDBRemote::%s provided with STDIO paths via launch_info: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000884 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000885 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
886 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
887 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Todd Fiala75f47c32014-10-11 21:42:09 +0000888 else
889 log->Printf ("ProcessGDBRemote::%s no STDIO paths given via launch_info", __FUNCTION__);
890 }
891
Vince Harrondf3f00f2015-02-10 21:09:04 +0000892 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Chaoren Lind3173f32015-05-29 19:52:29 +0000893 if (stdin_file_spec || disable_stdio)
Vince Harrondf3f00f2015-02-10 21:09:04 +0000894 {
895 // the inferior will be reading stdin from the specified file
896 // or stdio is completely disabled
897 m_stdin_forward = false;
898 }
899 else
900 {
901 m_stdin_forward = true;
902 }
903
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000904 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
905 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
906 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000907
Greg Clayton982c9762011-11-03 21:22:33 +0000908 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000909 if (object_file)
910 {
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +0000911 error = EstablishConnectionIfNeeded (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000912 if (error.Success())
913 {
914 lldb_utility::PseudoTerminal pty;
915 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000916
Zachary Turner7529df92015-09-01 20:02:29 +0000917 PlatformSP platform_sp (GetTarget().GetPlatform());
Vince Harrondf3f00f2015-02-10 21:09:04 +0000918 if (disable_stdio)
Greg Clayton71337622011-02-24 22:24:29 +0000919 {
Vince Harrondf3f00f2015-02-10 21:09:04 +0000920 // set to /dev/null unless redirected to a file above
Chaoren Lind3173f32015-05-29 19:52:29 +0000921 if (!stdin_file_spec)
Zachary Turner4eff2d32015-10-14 21:37:36 +0000922 stdin_file_spec.SetFile(FileSystem::DEV_NULL, false);
Chaoren Lind3173f32015-05-29 19:52:29 +0000923 if (!stdout_file_spec)
Zachary Turner4eff2d32015-10-14 21:37:36 +0000924 stdout_file_spec.SetFile(FileSystem::DEV_NULL, false);
Chaoren Lind3173f32015-05-29 19:52:29 +0000925 if (!stderr_file_spec)
Zachary Turner4eff2d32015-10-14 21:37:36 +0000926 stderr_file_spec.SetFile(FileSystem::DEV_NULL, false);
Vince Harrondf3f00f2015-02-10 21:09:04 +0000927 }
928 else if (platform_sp && platform_sp->IsHost())
929 {
930 // If the debugserver is local and we aren't disabling STDIO, lets use
931 // a pseudo terminal to instead of relying on the 'O' packets for stdio
932 // since 'O' packets can really slow down debugging if the inferior
933 // does a lot of output.
Chaoren Lind3173f32015-05-29 19:52:29 +0000934 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
935 pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000936 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000937 FileSpec slave_name{pty.GetSlaveName(NULL, 0), false};
938
939 if (!stdin_file_spec)
940 stdin_file_spec = slave_name;
941
942 if (!stdout_file_spec)
943 stdout_file_spec = slave_name;
944
945 if (!stderr_file_spec)
946 stderr_file_spec = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000947 }
Todd Fiala75f47c32014-10-11 21:42:09 +0000948 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +0000949 log->Printf ("ProcessGDBRemote::%s adjusted STDIO paths for local platform (IsHost() is true) using slave: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000950 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000951 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
952 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
953 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Greg Clayton71337622011-02-24 22:24:29 +0000954 }
955
Todd Fiala75f47c32014-10-11 21:42:09 +0000956 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +0000957 log->Printf ("ProcessGDBRemote::%s final STDIO paths after all adjustments: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000958 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000959 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
960 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
961 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Todd Fiala75f47c32014-10-11 21:42:09 +0000962
Chaoren Lind3173f32015-05-29 19:52:29 +0000963 if (stdin_file_spec)
964 m_gdb_comm.SetSTDIN(stdin_file_spec);
965 if (stdout_file_spec)
966 m_gdb_comm.SetSTDOUT(stdout_file_spec);
967 if (stderr_file_spec)
968 m_gdb_comm.SetSTDERR(stderr_file_spec);
Greg Clayton71337622011-02-24 22:24:29 +0000969
970 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
Jim Ingham106d0282014-06-25 02:32:56 +0000971 m_gdb_comm.SetDetachOnError (launch_flags & eLaunchFlagDetachOnError);
Greg Clayton71337622011-02-24 22:24:29 +0000972
Zachary Turner7529df92015-09-01 20:02:29 +0000973 m_gdb_comm.SendLaunchArchPacket (GetTarget().GetArchitecture().GetArchitectureName());
Ed Maste81b4c5f2016-01-04 01:43:47 +0000974
Jason Molendaa3329782014-03-29 18:54:20 +0000975 const char * launch_event_data = launch_info.GetLaunchEventData();
976 if (launch_event_data != NULL && *launch_event_data != '\0')
977 m_gdb_comm.SendLaunchEventDataPacket (launch_event_data);
Ed Maste81b4c5f2016-01-04 01:43:47 +0000978
Chaoren Lind3173f32015-05-29 19:52:29 +0000979 if (working_dir)
Greg Clayton71337622011-02-24 22:24:29 +0000980 {
981 m_gdb_comm.SetWorkingDir (working_dir);
982 }
983
984 // Send the environment and the program + arguments after we connect
Greg Clayton982c9762011-11-03 21:22:33 +0000985 const Args &environment = launch_info.GetEnvironmentEntries();
986 if (environment.GetArgumentCount())
Greg Clayton71337622011-02-24 22:24:29 +0000987 {
Greg Clayton982c9762011-11-03 21:22:33 +0000988 size_t num_environment_entries = environment.GetArgumentCount();
989 for (size_t i=0; i<num_environment_entries; ++i)
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000990 {
Greg Clayton982c9762011-11-03 21:22:33 +0000991 const char *env_entry = environment.GetArgumentAtIndex(i);
992 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Clayton71337622011-02-24 22:24:29 +0000993 break;
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000994 }
Greg Clayton71337622011-02-24 22:24:29 +0000995 }
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000996
Greg Clayton71337622011-02-24 22:24:29 +0000997 {
Tamas Berghammer912800c2015-02-24 10:23:39 +0000998 // Scope for the scoped timeout object
999 GDBRemoteCommunication::ScopedTimeout timeout (m_gdb_comm, 10);
1000
1001 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
1002 if (arg_packet_err == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001003 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001004 std::string error_str;
1005 if (m_gdb_comm.GetLaunchSuccess (error_str))
1006 {
1007 SetID (m_gdb_comm.GetCurrentProcessID ());
1008 }
1009 else
1010 {
1011 error.SetErrorString (error_str.c_str());
1012 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001013 }
1014 else
1015 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001016 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001017 }
Greg Clayton71337622011-02-24 22:24:29 +00001018 }
Tamas Berghammer912800c2015-02-24 10:23:39 +00001019
Greg Clayton71337622011-02-24 22:24:29 +00001020 if (GetID() == LLDB_INVALID_PROCESS_ID)
1021 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001022 if (log)
1023 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton71337622011-02-24 22:24:29 +00001024 KillDebugserverProcess ();
1025 return error;
1026 }
1027
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001028 StringExtractorGDBRemote response;
1029 if (m_gdb_comm.GetStopReply(response))
Greg Clayton71337622011-02-24 22:24:29 +00001030 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001031 SetLastStopPacket(response);
Ewan Crawford78baa192015-05-13 09:18:18 +00001032 // '?' Packets must be handled differently in non-stop mode
1033 if (GetTarget().GetNonStopModeEnabled())
1034 HandleStopReplySequence();
1035
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001036 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
1037
1038 if (process_arch.IsValid())
Jason Molendac62bd7b2013-12-21 05:20:36 +00001039 {
Zachary Turner7529df92015-09-01 20:02:29 +00001040 GetTarget().MergeArchitecture(process_arch);
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001041 }
1042 else
1043 {
1044 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
1045 if (host_arch.IsValid())
Zachary Turner7529df92015-09-01 20:02:29 +00001046 GetTarget().MergeArchitecture(host_arch);
Carlo Kok74389122013-10-14 07:09:13 +00001047 }
1048
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001049 SetPrivateState (SetThreadStopInfo (response));
Ed Maste81b4c5f2016-01-04 01:43:47 +00001050
Greg Clayton71337622011-02-24 22:24:29 +00001051 if (!disable_stdio)
1052 {
1053 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Claytonee95ed52011-11-17 22:14:31 +00001054 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Clayton71337622011-02-24 22:24:29 +00001055 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001056 }
1057 }
Greg Claytonc235ac72011-08-09 05:20:29 +00001058 else
1059 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001060 if (log)
1061 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytonc235ac72011-08-09 05:20:29 +00001062 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001063 }
1064 else
1065 {
1066 // Set our user ID to an invalid process ID.
1067 SetID(LLDB_INVALID_PROCESS_ID);
Ed Maste81b4c5f2016-01-04 01:43:47 +00001068 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
1069 exe_module->GetFileSpec().GetFilename().AsCString(),
Greg Clayton982c9762011-11-03 21:22:33 +00001070 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001071 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001072 return error;
Eugene Zelenko0722f082015-10-24 01:28:05 +00001073
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001074}
1075
Eugene Zelenko0722f082015-10-24 01:28:05 +00001076
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001077Error
Greg Claytonb766a732011-02-04 01:58:07 +00001078ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001079{
1080 Error error;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001081 // Only connect if we have a valid connect URL
Vince Harron1b5a74e2015-01-21 22:42:49 +00001082 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Ed Maste81b4c5f2016-01-04 01:43:47 +00001083
Greg Clayton00fe87b2013-12-05 22:58:22 +00001084 if (connect_url && connect_url[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001085 {
Vince Harron1b5a74e2015-01-21 22:42:49 +00001086 if (log)
1087 log->Printf("ProcessGDBRemote::%s Connecting to %s", __FUNCTION__, connect_url);
Greg Clayton00fe87b2013-12-05 22:58:22 +00001088 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
1089 if (conn_ap.get())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001090 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001091 const uint32_t max_retry_count = 50;
1092 uint32_t retry_count = 0;
1093 while (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001094 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001095 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
1096 {
1097 m_gdb_comm.SetConnection (conn_ap.release());
1098 break;
1099 }
1100 else if (error.WasInterrupted())
1101 {
1102 // If we were interrupted, don't keep retrying.
1103 break;
1104 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001105
Greg Clayton00fe87b2013-12-05 22:58:22 +00001106 retry_count++;
Ed Maste81b4c5f2016-01-04 01:43:47 +00001107
Greg Clayton00fe87b2013-12-05 22:58:22 +00001108 if (retry_count >= max_retry_count)
1109 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001110
Greg Clayton00fe87b2013-12-05 22:58:22 +00001111 usleep (100000);
1112 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001113 }
1114 }
1115
1116 if (!m_gdb_comm.IsConnected())
1117 {
1118 if (error.Success())
1119 error.SetErrorString("not connected to remote gdb server");
1120 return error;
1121 }
1122
Eugene Zelenko0722f082015-10-24 01:28:05 +00001123
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001124 // Start the communications read thread so all incoming data can be
1125 // parsed into packets and queued as they arrive.
1126 if (GetTarget().GetNonStopModeEnabled())
1127 m_gdb_comm.StartReadThread();
1128
Greg Clayton32e0a752011-03-30 18:16:51 +00001129 // We always seem to be able to open a connection to a local port
1130 // so we need to make sure we can then send data to it. If we can't
1131 // then we aren't actually connected to anything, so try and do the
Ed Maste81b4c5f2016-01-04 01:43:47 +00001132 // handshake with the remote GDB server and make sure that goes
Greg Clayton32e0a752011-03-30 18:16:51 +00001133 // alright.
Greg Claytonfb909312013-11-23 01:58:15 +00001134 if (!m_gdb_comm.HandshakeWithServer (&error))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001135 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001136 m_gdb_comm.Disconnect();
1137 if (error.Success())
1138 error.SetErrorString("not connected to remote gdb server");
1139 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001140 }
Ewan Crawford78baa192015-05-13 09:18:18 +00001141
1142 // Send $QNonStop:1 packet on startup if required
1143 if (GetTarget().GetNonStopModeEnabled())
Ewan Crawfordaa7eda72015-06-24 15:14:26 +00001144 GetTarget().SetNonStopModeEnabled (m_gdb_comm.SetNonStopMode(true));
Ewan Crawford78baa192015-05-13 09:18:18 +00001145
Greg Claytonb30c50c2015-05-29 00:01:55 +00001146 m_gdb_comm.GetEchoSupported ();
Pavel Labath5c95ee42016-08-30 13:56:11 +00001147 m_gdb_comm.GetThreadSuffixSupported ();
Greg Clayton44633992012-04-10 03:22:03 +00001148 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001149 m_gdb_comm.GetHostInfo ();
1150 m_gdb_comm.GetVContSupported ('c');
Jim Inghamcd16df92012-07-20 21:37:13 +00001151 m_gdb_comm.GetVAttachOrWaitSupported();
Ewan Crawford78baa192015-05-13 09:18:18 +00001152
1153 // Ask the remote server for the default thread id
1154 if (GetTarget().GetNonStopModeEnabled())
1155 m_gdb_comm.GetDefaultThreadId(m_initial_tid);
1156
1157
Jim Ingham03afad82012-07-02 05:40:07 +00001158 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1159 for (size_t idx = 0; idx < num_cmds; idx++)
1160 {
1161 StringExtractorGDBRemote response;
Jim Ingham03afad82012-07-02 05:40:07 +00001162 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1163 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001164 return error;
1165}
1166
1167void
Jim Inghambb006ce2014-08-02 00:33:35 +00001168ProcessGDBRemote::DidLaunchOrAttach (ArchSpec& process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001169{
Greg Clayton5160ce52013-03-27 23:08:40 +00001170 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001171 if (log)
Todd Fiala75930012016-08-19 04:21:48 +00001172 log->Printf ("ProcessGDBRemote::%s()", __FUNCTION__);
Greg Clayton93d3c8332011-02-16 04:46:07 +00001173 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001174 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001175 BuildDynamicRegisterInfo (false);
Greg Clayton3af9ea52010-11-18 05:57:03 +00001176
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001177 // See if the GDB server supports the qHostInfo information
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001178
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001179
1180 // See if the GDB server supports the qProcessInfo packet, if so
1181 // prefer that over the Host information as it will be more specific
1182 // to our process.
1183
Todd Fiala75f47c32014-10-11 21:42:09 +00001184 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1185 if (remote_process_arch.IsValid())
1186 {
1187 process_arch = remote_process_arch;
1188 if (log)
1189 log->Printf ("ProcessGDBRemote::%s gdb-remote had process architecture, using %s %s",
1190 __FUNCTION__,
1191 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1192 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1193 }
Jim Inghambb006ce2014-08-02 00:33:35 +00001194 else
Todd Fiala75f47c32014-10-11 21:42:09 +00001195 {
Jim Inghambb006ce2014-08-02 00:33:35 +00001196 process_arch = m_gdb_comm.GetHostArchitecture();
Todd Fiala75f47c32014-10-11 21:42:09 +00001197 if (log)
1198 log->Printf ("ProcessGDBRemote::%s gdb-remote did not have process architecture, using gdb-remote host architecture %s %s",
1199 __FUNCTION__,
1200 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1201 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1202 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001203
Jim Inghambb006ce2014-08-02 00:33:35 +00001204 if (process_arch.IsValid())
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001205 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001206 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Greg Claytond314e812011-03-23 00:09:55 +00001207 if (target_arch.IsValid())
1208 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001209 if (log)
1210 log->Printf ("ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1211 __FUNCTION__,
1212 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1213 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
1214
1215 // If the remote host is ARM and we have apple as the vendor, then
Greg Claytond314e812011-03-23 00:09:55 +00001216 // ARM executables and shared libraries can have mixed ARM architectures.
1217 // You can have an armv6 executable, and if the host is armv7, then the
1218 // system will load the best possible architecture for all shared libraries
1219 // it has, so we really need to take the remote host architecture as our
1220 // defacto architecture in this case.
1221
Jason Molenda6d9fe8c2015-08-21 00:13:37 +00001222 if ((process_arch.GetMachine() == llvm::Triple::arm || process_arch.GetMachine() == llvm::Triple::thumb)
1223 && process_arch.GetTriple().getVendor() == llvm::Triple::Apple)
Greg Claytond314e812011-03-23 00:09:55 +00001224 {
Jason Molenda921c01b2014-08-03 21:42:52 +00001225 GetTarget().SetArchitecture (process_arch);
Todd Fiala75f47c32014-10-11 21:42:09 +00001226 if (log)
1227 log->Printf ("ProcessGDBRemote::%s remote process is ARM/Apple, setting target arch to %s %s",
1228 __FUNCTION__,
1229 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1230 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001231 }
1232 else
1233 {
1234 // Fill in what is missing in the triple
Jim Inghambb006ce2014-08-02 00:33:35 +00001235 const llvm::Triple &remote_triple = process_arch.GetTriple();
Tamas Berghammere724af12015-03-13 10:32:37 +00001236 llvm::Triple new_target_triple = target_arch.GetTriple();
1237 if (new_target_triple.getVendorName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001238 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001239 new_target_triple.setVendor (remote_triple.getVendor());
Greg Claytond314e812011-03-23 00:09:55 +00001240
Tamas Berghammere724af12015-03-13 10:32:37 +00001241 if (new_target_triple.getOSName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001242 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001243 new_target_triple.setOS (remote_triple.getOS());
Greg Claytond314e812011-03-23 00:09:55 +00001244
Tamas Berghammere724af12015-03-13 10:32:37 +00001245 if (new_target_triple.getEnvironmentName().size() == 0)
1246 new_target_triple.setEnvironment (remote_triple.getEnvironment());
Greg Clayton70b57652011-05-15 01:25:55 +00001247 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001248
Tamas Berghammere724af12015-03-13 10:32:37 +00001249 ArchSpec new_target_arch = target_arch;
1250 new_target_arch.SetTriple(new_target_triple);
1251 GetTarget().SetArchitecture(new_target_arch);
1252 }
Greg Claytond314e812011-03-23 00:09:55 +00001253 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001254
1255 if (log)
1256 log->Printf ("ProcessGDBRemote::%s final target arch after adjustments for remote architecture: %s %s",
1257 __FUNCTION__,
1258 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1259 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001260 }
1261 else
1262 {
1263 // The target doesn't have a valid architecture yet, set it from
1264 // the architecture we got from the remote GDB server
Jason Molenda921c01b2014-08-03 21:42:52 +00001265 GetTarget().SetArchitecture (process_arch);
Greg Claytond314e812011-03-23 00:09:55 +00001266 }
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001267 }
Todd Fiala75930012016-08-19 04:21:48 +00001268
1269 // Find out which StructuredDataPlugins are supported by the
1270 // debug monitor. These plugins transmit data over async $J packets.
1271 auto supported_packets_array =
1272 m_gdb_comm.GetSupportedStructuredDataPlugins();
1273 if (supported_packets_array)
1274 MapSupportedStructuredDataPlugins(*supported_packets_array);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001275 }
1276}
1277
1278void
1279ProcessGDBRemote::DidLaunch ()
1280{
Jim Inghambb006ce2014-08-02 00:33:35 +00001281 ArchSpec process_arch;
1282 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001283}
1284
1285Error
Han Ming Ong84647042012-02-25 01:07:38 +00001286ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1287{
Todd Fiala75f47c32014-10-11 21:42:09 +00001288 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001289 Error error;
Todd Fiala75f47c32014-10-11 21:42:09 +00001290
1291 if (log)
1292 log->Printf ("ProcessGDBRemote::%s()", __FUNCTION__);
1293
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001294 // Clear out and clean up from any current state
1295 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001296 if (attach_pid != LLDB_INVALID_PROCESS_ID)
1297 {
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00001298 error = EstablishConnectionIfNeeded (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001299 if (error.Success())
1300 {
Jim Ingham106d0282014-06-25 02:32:56 +00001301 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
Todd Fiala75f47c32014-10-11 21:42:09 +00001302
Greg Clayton71337622011-02-24 22:24:29 +00001303 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001304 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Ed Maste81b4c5f2016-01-04 01:43:47 +00001305 SetID (attach_pid);
Greg Clayton71337622011-02-24 22:24:29 +00001306 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001307 }
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00001308 else
1309 SetExitStatus (-1, error.AsCString());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001310 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001311
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001312 return error;
1313}
1314
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001315Error
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001316ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001317{
1318 Error error;
1319 // Clear out and clean up from any current state
1320 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001321
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001322 if (process_name && process_name[0])
1323 {
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00001324 error = EstablishConnectionIfNeeded (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001325 if (error.Success())
1326 {
1327 StreamString packet;
Ed Maste81b4c5f2016-01-04 01:43:47 +00001328
Jim Ingham106d0282014-06-25 02:32:56 +00001329 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
Ed Maste81b4c5f2016-01-04 01:43:47 +00001330
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001331 if (attach_info.GetWaitForLaunch())
Jim Inghamcd16df92012-07-20 21:37:13 +00001332 {
1333 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1334 {
1335 packet.PutCString ("vAttachWait");
1336 }
1337 else
1338 {
1339 if (attach_info.GetIgnoreExisting())
1340 packet.PutCString("vAttachWait");
1341 else
1342 packet.PutCString ("vAttachOrWait");
1343 }
1344 }
Greg Clayton71337622011-02-24 22:24:29 +00001345 else
1346 packet.PutCString("vAttachName");
1347 packet.PutChar(';');
Bruce Mitchener9ccb9702015-11-07 04:40:13 +00001348 packet.PutBytesAsRawHex8(process_name, strlen(process_name), endian::InlHostByteOrder(), endian::InlHostByteOrder());
Ed Maste81b4c5f2016-01-04 01:43:47 +00001349
Greg Clayton71337622011-02-24 22:24:29 +00001350 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1351
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001352 }
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00001353 else
1354 SetExitStatus (-1, error.AsCString());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001355 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001356 return error;
1357}
1358
Greg Clayton5df78fa2015-05-23 03:54:53 +00001359void
1360ProcessGDBRemote::DidExit ()
Greg Claytonfbb76342013-11-20 21:07:01 +00001361{
Greg Clayton5df78fa2015-05-23 03:54:53 +00001362 // When we exit, disconnect from the GDB server communications
Greg Claytonfbb76342013-11-20 21:07:01 +00001363 m_gdb_comm.Disconnect();
Greg Claytonfbb76342013-11-20 21:07:01 +00001364}
1365
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001366void
Jim Inghambb006ce2014-08-02 00:33:35 +00001367ProcessGDBRemote::DidAttach (ArchSpec &process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001368{
Jim Inghambb006ce2014-08-02 00:33:35 +00001369 // If you can figure out what the architecture is, fill it in here.
1370 process_arch.Clear();
1371 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001372}
1373
Eugene Zelenko0722f082015-10-24 01:28:05 +00001374
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001375Error
1376ProcessGDBRemote::WillResume ()
1377{
Greg Clayton71fc2a32011-02-12 06:28:37 +00001378 m_continue_c_tids.clear();
1379 m_continue_C_tids.clear();
1380 m_continue_s_tids.clear();
1381 m_continue_S_tids.clear();
Greg Clayton2e309072015-07-17 23:42:28 +00001382 m_jstopinfo_sp.reset();
1383 m_jthreadsinfo_sp.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001384 return Error();
1385}
1386
1387Error
1388ProcessGDBRemote::DoResume ()
1389{
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001390 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001391 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001392 if (log)
1393 log->Printf ("ProcessGDBRemote::Resume()");
Ed Maste81b4c5f2016-01-04 01:43:47 +00001394
Jim Ingham583bbb12016-03-07 21:50:25 +00001395 ListenerSP listener_sp (Listener::MakeListener("gdb-remote.resume-packet-sent"));
1396 if (listener_sp->StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
Greg Claytone5219662010-12-03 06:02:24 +00001397 {
Jim Ingham583bbb12016-03-07 21:50:25 +00001398 listener_sp->StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
Ed Maste81b4c5f2016-01-04 01:43:47 +00001399
Greg Claytond1d06e42013-04-20 00:27:58 +00001400 const size_t num_threads = GetThreadList().GetSize();
1401
Greg Clayton71fc2a32011-02-12 06:28:37 +00001402 StreamString continue_packet;
1403 bool continue_packet_error = false;
1404 if (m_gdb_comm.HasAnyVContSupport ())
1405 {
Ewan Crawford78baa192015-05-13 09:18:18 +00001406 if (!GetTarget().GetNonStopModeEnabled() &&
1407 (m_continue_c_tids.size() == num_threads ||
Greg Claytone98008c2014-02-13 23:34:38 +00001408 (m_continue_c_tids.empty() &&
1409 m_continue_C_tids.empty() &&
1410 m_continue_s_tids.empty() &&
Ewan Crawford78baa192015-05-13 09:18:18 +00001411 m_continue_S_tids.empty())))
Greg Clayton71fc2a32011-02-12 06:28:37 +00001412 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001413 // All threads are continuing, just send a "c" packet
1414 continue_packet.PutCString ("c");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001415 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001416 else
1417 {
1418 continue_packet.PutCString ("vCont");
Ed Maste81b4c5f2016-01-04 01:43:47 +00001419
Greg Claytond1d06e42013-04-20 00:27:58 +00001420 if (!m_continue_c_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001421 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001422 if (m_gdb_comm.GetVContSupported ('c'))
1423 {
1424 for (tid_collection::const_iterator t_pos = m_continue_c_tids.begin(), t_end = m_continue_c_tids.end(); t_pos != t_end; ++t_pos)
1425 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1426 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001427 else
Greg Claytond1d06e42013-04-20 00:27:58 +00001428 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001429 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001430
Greg Claytond1d06e42013-04-20 00:27:58 +00001431 if (!continue_packet_error && !m_continue_C_tids.empty())
1432 {
1433 if (m_gdb_comm.GetVContSupported ('C'))
1434 {
1435 for (tid_sig_collection::const_iterator s_pos = m_continue_C_tids.begin(), s_end = m_continue_C_tids.end(); s_pos != s_end; ++s_pos)
1436 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1437 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001438 else
Greg Claytond1d06e42013-04-20 00:27:58 +00001439 continue_packet_error = true;
1440 }
Greg Claytone5219662010-12-03 06:02:24 +00001441
Greg Claytond1d06e42013-04-20 00:27:58 +00001442 if (!continue_packet_error && !m_continue_s_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001443 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001444 if (m_gdb_comm.GetVContSupported ('s'))
1445 {
1446 for (tid_collection::const_iterator t_pos = m_continue_s_tids.begin(), t_end = m_continue_s_tids.end(); t_pos != t_end; ++t_pos)
1447 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1448 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001449 else
Greg Claytond1d06e42013-04-20 00:27:58 +00001450 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001451 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001452
Greg Claytond1d06e42013-04-20 00:27:58 +00001453 if (!continue_packet_error && !m_continue_S_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001454 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001455 if (m_gdb_comm.GetVContSupported ('S'))
1456 {
1457 for (tid_sig_collection::const_iterator s_pos = m_continue_S_tids.begin(), s_end = m_continue_S_tids.end(); s_pos != s_end; ++s_pos)
1458 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1459 }
1460 else
1461 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001462 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001463
Greg Claytond1d06e42013-04-20 00:27:58 +00001464 if (continue_packet_error)
1465 continue_packet.GetString().clear();
Greg Clayton71fc2a32011-02-12 06:28:37 +00001466 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001467 }
1468 else
1469 continue_packet_error = true;
Ed Maste81b4c5f2016-01-04 01:43:47 +00001470
Greg Clayton71fc2a32011-02-12 06:28:37 +00001471 if (continue_packet_error)
1472 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001473 // Either no vCont support, or we tried to use part of the vCont
1474 // packet that wasn't supported by the remote GDB server.
1475 // We need to try and make a simple packet that can do our continue
Greg Clayton71fc2a32011-02-12 06:28:37 +00001476 const size_t num_continue_c_tids = m_continue_c_tids.size();
1477 const size_t num_continue_C_tids = m_continue_C_tids.size();
1478 const size_t num_continue_s_tids = m_continue_s_tids.size();
1479 const size_t num_continue_S_tids = m_continue_S_tids.size();
1480 if (num_continue_c_tids > 0)
1481 {
1482 if (num_continue_c_tids == num_threads)
1483 {
1484 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001485 m_gdb_comm.SetCurrentThreadForRun (-1);
Ed Maste81b4c5f2016-01-04 01:43:47 +00001486 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001487 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001488 }
1489 else if (num_continue_c_tids == 1 &&
Ed Maste81b4c5f2016-01-04 01:43:47 +00001490 num_continue_C_tids == 0 &&
1491 num_continue_s_tids == 0 &&
Greg Clayton71fc2a32011-02-12 06:28:37 +00001492 num_continue_S_tids == 0 )
1493 {
1494 // Only one thread is continuing
Greg Clayton8b82f082011-04-12 05:54:46 +00001495 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Ed Maste81b4c5f2016-01-04 01:43:47 +00001496 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001497 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001498 }
1499 }
1500
Greg Clayton0c74e782011-06-24 03:21:43 +00001501 if (continue_packet_error && num_continue_C_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001502 {
Ed Maste81b4c5f2016-01-04 01:43:47 +00001503 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1504 num_continue_C_tids > 0 &&
1505 num_continue_s_tids == 0 &&
Greg Clayton0c74e782011-06-24 03:21:43 +00001506 num_continue_S_tids == 0 )
Greg Clayton71fc2a32011-02-12 06:28:37 +00001507 {
1508 const int continue_signo = m_continue_C_tids.front().second;
Greg Clayton0c74e782011-06-24 03:21:43 +00001509 // Only one thread is continuing
Greg Clayton71fc2a32011-02-12 06:28:37 +00001510 if (num_continue_C_tids > 1)
1511 {
Ed Maste81b4c5f2016-01-04 01:43:47 +00001512 // More that one thread with a signal, yet we don't have
Greg Clayton0c74e782011-06-24 03:21:43 +00001513 // vCont support and we are being asked to resume each
1514 // thread with a signal, we need to make sure they are
1515 // all the same signal, or we can't issue the continue
1516 // accurately with the current support...
1517 if (num_continue_C_tids > 1)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001518 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001519 continue_packet_error = false;
1520 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1521 {
1522 if (m_continue_C_tids[i].second != continue_signo)
1523 continue_packet_error = true;
1524 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001525 }
Greg Clayton0c74e782011-06-24 03:21:43 +00001526 if (!continue_packet_error)
1527 m_gdb_comm.SetCurrentThreadForRun (-1);
1528 }
1529 else
1530 {
1531 // Set the continue thread ID
1532 continue_packet_error = false;
1533 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001534 }
1535 if (!continue_packet_error)
1536 {
1537 // Add threads continuing with the same signo...
Greg Clayton71fc2a32011-02-12 06:28:37 +00001538 continue_packet.Printf("C%2.2x", continue_signo);
1539 }
1540 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001541 }
1542
Greg Clayton0c74e782011-06-24 03:21:43 +00001543 if (continue_packet_error && num_continue_s_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001544 {
1545 if (num_continue_s_tids == num_threads)
1546 {
1547 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001548 m_gdb_comm.SetCurrentThreadForRun (-1);
Ewan Crawford76df2882015-06-23 12:32:06 +00001549
1550 // If in Non-Stop-Mode use vCont when stepping
1551 if (GetTarget().GetNonStopModeEnabled())
1552 {
1553 if (m_gdb_comm.GetVContSupported('s'))
1554 continue_packet.PutCString("vCont;s");
1555 else
1556 continue_packet.PutChar('s');
1557 }
1558 else
1559 continue_packet.PutChar('s');
1560
Greg Clayton0c74e782011-06-24 03:21:43 +00001561 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001562 }
1563 else if (num_continue_c_tids == 0 &&
Ed Maste81b4c5f2016-01-04 01:43:47 +00001564 num_continue_C_tids == 0 &&
1565 num_continue_s_tids == 1 &&
Greg Clayton71fc2a32011-02-12 06:28:37 +00001566 num_continue_S_tids == 0 )
1567 {
1568 // Only one thread is stepping
Greg Clayton8b82f082011-04-12 05:54:46 +00001569 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Ed Maste81b4c5f2016-01-04 01:43:47 +00001570 continue_packet.PutChar ('s');
Greg Clayton0c74e782011-06-24 03:21:43 +00001571 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001572 }
1573 }
1574
1575 if (!continue_packet_error && num_continue_S_tids > 0)
1576 {
1577 if (num_continue_S_tids == num_threads)
1578 {
1579 const int step_signo = m_continue_S_tids.front().second;
1580 // Are all threads trying to step with the same signal?
Greg Clayton0c74e782011-06-24 03:21:43 +00001581 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001582 if (num_continue_S_tids > 1)
1583 {
1584 for (size_t i=1; i<num_threads; ++i)
1585 {
1586 if (m_continue_S_tids[i].second != step_signo)
1587 continue_packet_error = true;
1588 }
1589 }
1590 if (!continue_packet_error)
1591 {
1592 // Add threads stepping with the same signo...
Greg Clayton8b82f082011-04-12 05:54:46 +00001593 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001594 continue_packet.Printf("S%2.2x", step_signo);
1595 }
1596 }
1597 else if (num_continue_c_tids == 0 &&
Ed Maste81b4c5f2016-01-04 01:43:47 +00001598 num_continue_C_tids == 0 &&
1599 num_continue_s_tids == 0 &&
Greg Clayton71fc2a32011-02-12 06:28:37 +00001600 num_continue_S_tids == 1 )
1601 {
1602 // Only one thread is stepping with signal
Greg Clayton8b82f082011-04-12 05:54:46 +00001603 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001604 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Clayton0c74e782011-06-24 03:21:43 +00001605 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001606 }
1607 }
1608 }
1609
1610 if (continue_packet_error)
1611 {
1612 error.SetErrorString ("can't make continue packet for this resume");
1613 }
1614 else
1615 {
1616 EventSP event_sp;
Zachary Turneracee96a2014-09-23 18:32:09 +00001617 if (!m_async_thread.IsJoinable())
Jim Inghamb1e2e842012-04-12 18:49:31 +00001618 {
1619 error.SetErrorString ("Trying to resume but the async thread is dead.");
1620 if (log)
1621 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1622 return error;
1623 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001624
Greg Clayton71fc2a32011-02-12 06:28:37 +00001625 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1626
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00001627 if (listener_sp->WaitForEvent(std::chrono::seconds(5), event_sp) == false)
Jim Inghamb1e2e842012-04-12 18:49:31 +00001628 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001629 error.SetErrorString("Resume timed out.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00001630 if (log)
1631 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1632 }
1633 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1634 {
1635 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1636 if (log)
1637 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1638 return error;
1639 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001640 }
Greg Claytone5219662010-12-03 06:02:24 +00001641 }
1642
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001643 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001644}
1645
Greg Clayton9e920902012-04-10 02:25:43 +00001646void
Ewan Crawford78baa192015-05-13 09:18:18 +00001647ProcessGDBRemote::HandleStopReplySequence ()
1648{
1649 while(true)
1650 {
1651 // Send vStopped
1652 StringExtractorGDBRemote response;
1653 m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false);
1654
1655 // OK represents end of signal list
1656 if (response.IsOKResponse())
1657 break;
1658
1659 // If not OK or a normal packet we have a problem
1660 if (!response.IsNormalResponse())
1661 break;
1662
1663 SetLastStopPacket(response);
1664 }
1665}
1666
1667void
Greg Clayton9e920902012-04-10 02:25:43 +00001668ProcessGDBRemote::ClearThreadIDList ()
1669{
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00001670 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001671 m_thread_ids.clear();
Jason Molenda545304d2015-12-18 00:45:35 +00001672 m_thread_pcs.clear();
Greg Clayton9e920902012-04-10 02:25:43 +00001673}
1674
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001675size_t
1676ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue (std::string &value)
1677{
1678 m_thread_ids.clear();
Jason Molenda545304d2015-12-18 00:45:35 +00001679 m_thread_pcs.clear();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001680 size_t comma_pos;
1681 lldb::tid_t tid;
1682 while ((comma_pos = value.find(',')) != std::string::npos)
1683 {
1684 value[comma_pos] = '\0';
1685 // thread in big endian hex
1686 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1687 if (tid != LLDB_INVALID_THREAD_ID)
1688 m_thread_ids.push_back (tid);
1689 value.erase(0, comma_pos + 1);
1690 }
1691 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1692 if (tid != LLDB_INVALID_THREAD_ID)
1693 m_thread_ids.push_back (tid);
1694 return m_thread_ids.size();
1695}
1696
Jason Molenda545304d2015-12-18 00:45:35 +00001697size_t
1698ProcessGDBRemote::UpdateThreadPCsFromStopReplyThreadsValue (std::string &value)
1699{
1700 m_thread_pcs.clear();
1701 size_t comma_pos;
1702 lldb::addr_t pc;
1703 while ((comma_pos = value.find(',')) != std::string::npos)
1704 {
1705 value[comma_pos] = '\0';
1706 pc = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
1707 if (pc != LLDB_INVALID_ADDRESS)
1708 m_thread_pcs.push_back (pc);
1709 value.erase(0, comma_pos + 1);
1710 }
1711 pc = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
1712 if (pc != LLDB_INVALID_THREAD_ID)
1713 m_thread_pcs.push_back (pc);
1714 return m_thread_pcs.size();
1715}
1716
Greg Clayton9e920902012-04-10 02:25:43 +00001717bool
1718ProcessGDBRemote::UpdateThreadIDList ()
1719{
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00001720 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001721
Greg Clayton2e309072015-07-17 23:42:28 +00001722 if (m_jthreadsinfo_sp)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001723 {
1724 // If we have the JSON threads info, we can get the thread list from that
Greg Clayton2e309072015-07-17 23:42:28 +00001725 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001726 if (thread_infos && thread_infos->GetSize() > 0)
1727 {
1728 m_thread_ids.clear();
Jason Molenda545304d2015-12-18 00:45:35 +00001729 m_thread_pcs.clear();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001730 thread_infos->ForEach([this](StructuredData::Object* object) -> bool {
1731 StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1732 if (thread_dict)
1733 {
1734 // Set the thread stop info from the JSON dictionary
1735 SetThreadStopInfo (thread_dict);
1736 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1737 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1738 m_thread_ids.push_back(tid);
1739 }
1740 return true; // Keep iterating through all thread_info objects
1741 });
1742 }
1743 if (!m_thread_ids.empty())
1744 return true;
1745 }
1746 else
1747 {
1748 // See if we can get the thread IDs from the current stop reply packets
1749 // that might contain a "threads" key/value pair
1750
1751 // Lock the thread stack while we access it
Greg Claytonfc1e77a982015-11-03 22:42:04 +00001752 //Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +00001753 std::unique_lock<std::recursive_mutex> stop_stack_lock(m_last_stop_packet_mutex, std::defer_lock);
1754 if (stop_stack_lock.try_lock())
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001755 {
Greg Claytonfc1e77a982015-11-03 22:42:04 +00001756 // Get the number of stop packets on the stack
1757 int nItems = m_stop_packet_stack.size();
1758 // Iterate over them
1759 for (int i = 0; i < nItems; i++)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001760 {
Greg Claytonfc1e77a982015-11-03 22:42:04 +00001761 // Get the thread stop info
1762 StringExtractorGDBRemote &stop_info = m_stop_packet_stack[i];
1763 const std::string &stop_info_str = stop_info.GetStringRef();
Jason Molenda545304d2015-12-18 00:45:35 +00001764
1765 m_thread_pcs.clear();
1766 const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:");
1767 if (thread_pcs_pos != std::string::npos)
1768 {
1769 const size_t start = thread_pcs_pos + strlen(";thread-pcs:");
1770 const size_t end = stop_info_str.find(';', start);
1771 if (end != std::string::npos)
1772 {
1773 std::string value = stop_info_str.substr(start, end - start);
1774 UpdateThreadPCsFromStopReplyThreadsValue(value);
1775 }
1776 }
1777
Greg Claytonfc1e77a982015-11-03 22:42:04 +00001778 const size_t threads_pos = stop_info_str.find(";threads:");
1779 if (threads_pos != std::string::npos)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001780 {
Greg Claytonfc1e77a982015-11-03 22:42:04 +00001781 const size_t start = threads_pos + strlen(";threads:");
1782 const size_t end = stop_info_str.find(';', start);
1783 if (end != std::string::npos)
1784 {
1785 std::string value = stop_info_str.substr(start, end - start);
1786 if (UpdateThreadIDsFromStopReplyThreadsValue(value))
1787 return true;
1788 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001789 }
1790 }
1791 }
1792 }
1793
Greg Clayton9e920902012-04-10 02:25:43 +00001794 bool sequence_mutex_unavailable = false;
1795 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1796 if (sequence_mutex_unavailable)
1797 {
Greg Clayton9e920902012-04-10 02:25:43 +00001798 return false; // We just didn't get the list
1799 }
1800 return true;
1801}
1802
Greg Clayton9fc13552012-04-10 00:18:59 +00001803bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001804ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001805{
1806 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +00001807 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Clayton73b472d2010-10-27 03:32:59 +00001808 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +00001809 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Ed Maste81b4c5f2016-01-04 01:43:47 +00001810
Greg Clayton9e920902012-04-10 02:25:43 +00001811 size_t num_thread_ids = m_thread_ids.size();
1812 // The "m_thread_ids" thread ID list should always be updated after each stop
1813 // reply packet, but in case it isn't, update it here.
1814 if (num_thread_ids == 0)
1815 {
1816 if (!UpdateThreadIDList ())
1817 return false;
1818 num_thread_ids = m_thread_ids.size();
1819 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001820
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001821 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001822 if (num_thread_ids > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001823 {
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001824 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001825 {
Greg Clayton9e920902012-04-10 02:25:43 +00001826 tid_t tid = m_thread_ids[i];
Greg Clayton160c9d82013-05-01 21:54:04 +00001827 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001828 if (!thread_sp)
Jim Inghamdee1bc92013-06-22 00:27:45 +00001829 {
Jim Ingham4f465cf2012-10-10 18:32:14 +00001830 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001831 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1832 log->Printf(
1833 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001834 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001835 thread_sp->GetID());
1836 }
1837 else
1838 {
1839 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1840 log->Printf(
1841 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001842 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001843 thread_sp->GetID());
1844 }
Jason Molenda545304d2015-12-18 00:45:35 +00001845 // The m_thread_pcs vector has pc values in big-endian order, not target-endian, unlike most
Ed Maste81b4c5f2016-01-04 01:43:47 +00001846 // of the register read/write packets in gdb-remote protocol.
Jason Molenda545304d2015-12-18 00:45:35 +00001847 // Early in the process startup, we may not yet have set the process ByteOrder so we ignore these;
1848 // they are a performance improvement over fetching thread register values individually, the
1849 // method we will fall back to if needed.
1850 if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() && GetByteOrder() != eByteOrderInvalid)
1851 {
1852 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1853 RegisterContextSP reg_ctx_sp (thread_sp->GetRegisterContext());
1854 if (reg_ctx_sp)
1855 {
Ed Maste81b4c5f2016-01-04 01:43:47 +00001856 uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber
Jason Molenda545304d2015-12-18 00:45:35 +00001857 (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1858 if (pc_regnum != LLDB_INVALID_REGNUM)
1859 {
1860 gdb_thread->PrivateSetRegisterValue (pc_regnum, m_thread_pcs[i]);
1861 }
1862 }
1863 }
Greg Clayton88f86b62016-06-10 23:23:34 +00001864 new_thread_list.AddThreadSortedByIndexID (thread_sp);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001865 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001866 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001867
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001868 // Whatever that is left in old_thread_list_copy are not
1869 // present in new_thread_list. Remove non-existent threads from internal id table.
1870 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1871 for (size_t i=0; i<old_num_thread_ids; i++)
1872 {
1873 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1874 if (old_thread_sp)
1875 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001876 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001877 m_thread_id_to_index_id_map.erase(old_thread_id);
1878 }
1879 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001880
Greg Clayton9fc13552012-04-10 00:18:59 +00001881 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001882}
1883
Eugene Zelenko0722f082015-10-24 01:28:05 +00001884
Greg Clayton358cf1e2015-06-25 21:46:34 +00001885bool
Greg Clayton2e309072015-07-17 23:42:28 +00001886ProcessGDBRemote::GetThreadStopInfoFromJSON (ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001887{
1888 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet
Greg Clayton2e309072015-07-17 23:42:28 +00001889 if (thread_infos_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001890 {
Greg Clayton2e309072015-07-17 23:42:28 +00001891 StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
Greg Clayton358cf1e2015-06-25 21:46:34 +00001892 if (thread_infos)
1893 {
1894 lldb::tid_t tid;
1895 const size_t n = thread_infos->GetSize();
1896 for (size_t i=0; i<n; ++i)
1897 {
1898 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1899 if (thread_dict)
1900 {
1901 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid, LLDB_INVALID_THREAD_ID))
1902 {
1903 if (tid == thread->GetID())
Greg Clayton2e309072015-07-17 23:42:28 +00001904 return (bool)SetThreadStopInfo(thread_dict);
Greg Clayton358cf1e2015-06-25 21:46:34 +00001905 }
1906 }
1907 }
1908 }
1909 }
Greg Clayton2e309072015-07-17 23:42:28 +00001910 return false;
1911}
1912
1913bool
1914ProcessGDBRemote::CalculateThreadStopInfo (ThreadGDBRemote *thread)
1915{
1916 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet
1917 if (GetThreadStopInfoFromJSON (thread, m_jthreadsinfo_sp))
1918 return true;
1919
1920 // See if we got thread stop info for any threads valid stop info reasons threads
1921 // via the "jstopinfo" packet stop reply packet key/value pair?
1922 if (m_jstopinfo_sp)
1923 {
1924 // If we have "jstopinfo" then we have stop descriptions for all threads
1925 // that have stop reasons, and if there is no entry for a thread, then
1926 // it has no stop reason.
1927 thread->GetRegisterContext()->InvalidateIfNeeded(true);
1928 if (!GetThreadStopInfoFromJSON (thread, m_jstopinfo_sp))
1929 {
1930 thread->SetStopInfo (StopInfoSP());
1931 }
1932 return true;
1933 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00001934
1935 // Fall back to using the qThreadStopInfo packet
1936 StringExtractorGDBRemote stop_packet;
1937 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1938 return SetThreadStopInfo (stop_packet) == eStateStopped;
1939 return false;
1940}
1941
Eugene Zelenko0722f082015-10-24 01:28:05 +00001942
Greg Clayton358cf1e2015-06-25 21:46:34 +00001943ThreadSP
1944ProcessGDBRemote::SetThreadStopInfo (lldb::tid_t tid,
1945 ExpeditedRegisterMap &expedited_register_map,
1946 uint8_t signo,
1947 const std::string &thread_name,
1948 const std::string &reason,
1949 const std::string &description,
1950 uint32_t exc_type,
1951 const std::vector<addr_t> &exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001952 addr_t thread_dispatch_qaddr,
1953 bool queue_vars_valid, // Set to true if queue_name, queue_kind and queue_serial are valid
Jason Molenda77f89352016-01-12 07:09:16 +00001954 LazyBool associated_with_dispatch_queue,
1955 addr_t dispatch_queue_t,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001956 std::string &queue_name,
1957 QueueKind queue_kind,
1958 uint64_t queue_serial)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001959{
1960 ThreadSP thread_sp;
1961 if (tid != LLDB_INVALID_THREAD_ID)
1962 {
1963 // Scope for "locker" below
1964 {
1965 // m_thread_list_real does have its own mutex, but we need to
1966 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1967 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00001968 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
Greg Clayton358cf1e2015-06-25 21:46:34 +00001969 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1970
1971 if (!thread_sp)
1972 {
1973 // Create the thread if we need to
1974 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1975 m_thread_list_real.AddThread(thread_sp);
1976 }
1977 }
1978
1979 if (thread_sp)
1980 {
1981 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1982 gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001983
Greg Clayton358cf1e2015-06-25 21:46:34 +00001984 for (const auto &pair : expedited_register_map)
1985 {
1986 StringExtractor reg_value_extractor;
1987 reg_value_extractor.GetStringRef() = pair.second;
Pavel Labathb42b48e2016-08-19 12:31:49 +00001988 DataBufferSP buffer_sp(new DataBufferHeap(reg_value_extractor.GetStringRef().size() / 2, 0));
1989 reg_value_extractor.GetHexBytes(buffer_sp->GetBytes(), buffer_sp->GetByteSize(), '\xcc');
1990 gdb_thread->PrivateSetRegisterValue(
1991 pair.first, llvm::ArrayRef<uint8_t>(buffer_sp->GetBytes(), buffer_sp->GetByteSize()));
Greg Clayton358cf1e2015-06-25 21:46:34 +00001992 }
1993
Greg Clayton358cf1e2015-06-25 21:46:34 +00001994 thread_sp->SetName (thread_name.empty() ? NULL : thread_name.c_str());
1995
1996 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001997 // Check if the GDB server was able to provide the queue name, kind and serial number
1998 if (queue_vars_valid)
Jason Molenda77f89352016-01-12 07:09:16 +00001999 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind, queue_serial, dispatch_queue_t, associated_with_dispatch_queue);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002000 else
2001 gdb_thread->ClearQueueInfo();
2002
Jason Molenda77f89352016-01-12 07:09:16 +00002003 gdb_thread->SetAssociatedWithLibdispatchQueue (associated_with_dispatch_queue);
2004
2005 if (dispatch_queue_t != LLDB_INVALID_ADDRESS)
2006 gdb_thread->SetQueueLibdispatchQueueAddress (dispatch_queue_t);
2007
Greg Clayton2e309072015-07-17 23:42:28 +00002008 // Make sure we update our thread stop reason just once
2009 if (!thread_sp->StopInfoIsUpToDate())
Greg Clayton358cf1e2015-06-25 21:46:34 +00002010 {
Greg Clayton2e309072015-07-17 23:42:28 +00002011 thread_sp->SetStopInfo (StopInfoSP());
Ryan Brown65d4d5c2015-09-16 21:20:44 +00002012 // If there's a memory thread backed by this thread, we need to use it to calcualte StopInfo.
2013 ThreadSP memory_thread_sp = m_thread_list.FindThreadByProtocolID(thread_sp->GetProtocolID());
2014 if (memory_thread_sp)
2015 thread_sp = memory_thread_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002016
Greg Clayton2e309072015-07-17 23:42:28 +00002017 if (exc_type != 0)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002018 {
Greg Clayton2e309072015-07-17 23:42:28 +00002019 const size_t exc_data_size = exc_data.size();
2020
2021 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
2022 exc_type,
2023 exc_data_size,
2024 exc_data_size >= 1 ? exc_data[0] : 0,
2025 exc_data_size >= 2 ? exc_data[1] : 0,
2026 exc_data_size >= 3 ? exc_data[2] : 0));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002027 }
Greg Clayton2e309072015-07-17 23:42:28 +00002028 else
Greg Clayton358cf1e2015-06-25 21:46:34 +00002029 {
Greg Clayton2e309072015-07-17 23:42:28 +00002030 bool handled = false;
2031 bool did_exec = false;
2032 if (!reason.empty())
Greg Clayton358cf1e2015-06-25 21:46:34 +00002033 {
Greg Clayton2e309072015-07-17 23:42:28 +00002034 if (reason.compare("trace") == 0)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002035 {
Pavel Labathef409122016-04-07 08:16:10 +00002036 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
2037 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2038
2039 // If the current pc is a breakpoint site then the StopInfo should be set to Breakpoint
2040 // Otherwise, it will be set to Trace.
2041 if (bp_site_sp && bp_site_sp->ValidForThisThread(thread_sp.get()))
2042 {
2043 thread_sp->SetStopInfo(
2044 StopInfo::CreateStopReasonWithBreakpointSiteID(*thread_sp, bp_site_sp->GetID()));
2045 }
2046 else
2047 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Greg Clayton2e309072015-07-17 23:42:28 +00002048 handled = true;
2049 }
2050 else if (reason.compare("breakpoint") == 0)
2051 {
Pavel Labathef409122016-04-07 08:16:10 +00002052 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
2053 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2054 if (bp_site_sp)
2055 {
2056 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2057 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2058 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2059 handled = true;
2060 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2061 {
2062 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2063 }
2064 else
2065 {
2066 StopInfoSP invalid_stop_info_sp;
2067 thread_sp->SetStopInfo (invalid_stop_info_sp);
2068 }
2069 }
Greg Clayton2e309072015-07-17 23:42:28 +00002070 }
2071 else if (reason.compare("trap") == 0)
2072 {
2073 // Let the trap just use the standard signal stop reason below...
2074 }
2075 else if (reason.compare("watchpoint") == 0)
2076 {
2077 StringExtractor desc_extractor(description.c_str());
2078 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
2079 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
Jaydeep Patil83143502015-08-13 03:44:09 +00002080 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
Greg Clayton2e309072015-07-17 23:42:28 +00002081 watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
2082 if (wp_addr != LLDB_INVALID_ADDRESS)
2083 {
Mohit K. Bhakkad6846bc82015-12-02 17:45:02 +00002084 WatchpointSP wp_sp;
2085 ArchSpec::Core core = GetTarget().GetArchitecture().GetCore();
Omair Javaid43507f52016-06-16 16:41:22 +00002086 if ((core >= ArchSpec::kCore_mips_first && core <= ArchSpec::kCore_mips_last) ||
Omair Javaidc6dc90e2016-06-27 11:18:23 +00002087 (core >= ArchSpec::eCore_arm_generic && core <= ArchSpec::eCore_arm_aarch64))
Mohit K. Bhakkad6846bc82015-12-02 17:45:02 +00002088 wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_hit_addr);
2089 if (!wp_sp)
2090 wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
Greg Clayton2e309072015-07-17 23:42:28 +00002091 if (wp_sp)
2092 {
2093 wp_sp->SetHardwareIndex(wp_index);
2094 watch_id = wp_sp->GetID();
2095 }
2096 }
2097 if (watch_id == LLDB_INVALID_WATCH_ID)
2098 {
2099 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_WATCHPOINTS));
2100 if (log) log->Printf ("failed to find watchpoint");
2101 }
Jaydeep Patil83143502015-08-13 03:44:09 +00002102 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id, wp_hit_addr));
Greg Clayton2e309072015-07-17 23:42:28 +00002103 handled = true;
2104 }
2105 else if (reason.compare("exception") == 0)
2106 {
2107 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
2108 handled = true;
2109 }
2110 else if (reason.compare("exec") == 0)
2111 {
2112 did_exec = true;
2113 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
2114 handled = true;
2115 }
2116 }
Pavel Labath3ce324a2016-04-06 09:10:29 +00002117 else if (!signo)
2118 {
Pavel Labathef409122016-04-07 08:16:10 +00002119 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
2120 lldb::BreakpointSiteSP bp_site_sp =
2121 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2122
Pavel Labath3ce324a2016-04-06 09:10:29 +00002123 // If the current pc is a breakpoint site then the StopInfo should be set to Breakpoint
2124 // even though the remote stub did not set it as such. This can happen when
2125 // the thread is involuntarily interrupted (e.g. due to stops on other
2126 // threads) just as it is about to execute the breakpoint instruction.
Pavel Labathef409122016-04-07 08:16:10 +00002127 if (bp_site_sp && bp_site_sp->ValidForThisThread(thread_sp.get()))
2128 {
2129 thread_sp->SetStopInfo(
2130 StopInfo::CreateStopReasonWithBreakpointSiteID(*thread_sp, bp_site_sp->GetID()));
Pavel Labath3ce324a2016-04-06 09:10:29 +00002131 handled = true;
Pavel Labathef409122016-04-07 08:16:10 +00002132 }
Pavel Labath3ce324a2016-04-06 09:10:29 +00002133 }
Greg Clayton2e309072015-07-17 23:42:28 +00002134
2135 if (!handled && signo && did_exec == false)
2136 {
2137 if (signo == SIGTRAP)
2138 {
2139 // Currently we are going to assume SIGTRAP means we are either
2140 // hitting a breakpoint or hardware single stepping.
2141 handled = true;
2142 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
2143 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2144
2145 if (bp_site_sp)
2146 {
2147 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2148 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2149 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2150 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2151 {
2152 if(m_breakpoint_pc_offset != 0)
2153 thread_sp->GetRegisterContext()->SetPC(pc);
2154 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2155 }
2156 else
2157 {
2158 StopInfoSP invalid_stop_info_sp;
2159 thread_sp->SetStopInfo (invalid_stop_info_sp);
2160 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002161 }
2162 else
2163 {
Greg Clayton2e309072015-07-17 23:42:28 +00002164 // If we were stepping then assume the stop was the result of the trace. If we were
2165 // not stepping then report the SIGTRAP.
2166 // FIXME: We are still missing the case where we single step over a trap instruction.
2167 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
2168 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
2169 else
2170 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo, description.c_str()));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002171 }
2172 }
Greg Clayton2e309072015-07-17 23:42:28 +00002173 if (!handled)
2174 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo, description.c_str()));
2175 }
2176
2177 if (!description.empty())
2178 {
2179 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
2180 if (stop_info_sp)
2181 {
2182 const char *stop_info_desc = stop_info_sp->GetDescription();
2183 if (!stop_info_desc || !stop_info_desc[0])
2184 stop_info_sp->SetDescription (description.c_str());
2185 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002186 else
2187 {
Greg Clayton2e309072015-07-17 23:42:28 +00002188 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002189 }
2190 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002191 }
2192 }
2193 }
2194 }
2195 return thread_sp;
2196}
2197
Greg Clayton2e309072015-07-17 23:42:28 +00002198lldb::ThreadSP
Greg Clayton358cf1e2015-06-25 21:46:34 +00002199ProcessGDBRemote::SetThreadStopInfo (StructuredData::Dictionary *thread_dict)
2200{
2201 static ConstString g_key_tid("tid");
2202 static ConstString g_key_name("name");
2203 static ConstString g_key_reason("reason");
2204 static ConstString g_key_metype("metype");
2205 static ConstString g_key_medata("medata");
2206 static ConstString g_key_qaddr("qaddr");
Jason Molenda77f89352016-01-12 07:09:16 +00002207 static ConstString g_key_dispatch_queue_t("dispatch_queue_t");
2208 static ConstString g_key_associated_with_dispatch_queue("associated_with_dispatch_queue");
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002209 static ConstString g_key_queue_name("qname");
2210 static ConstString g_key_queue_kind("qkind");
Jason Molenda26d84e82016-01-08 00:20:48 +00002211 static ConstString g_key_queue_serial_number("qserialnum");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002212 static ConstString g_key_registers("registers");
2213 static ConstString g_key_memory("memory");
2214 static ConstString g_key_address("address");
2215 static ConstString g_key_bytes("bytes");
2216 static ConstString g_key_description("description");
Pavel Labath4a4bb122015-07-16 14:14:35 +00002217 static ConstString g_key_signal("signal");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002218
2219 // Stop with signal and thread info
2220 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2221 uint8_t signo = 0;
2222 std::string value;
2223 std::string thread_name;
2224 std::string reason;
2225 std::string description;
2226 uint32_t exc_type = 0;
2227 std::vector<addr_t> exc_data;
2228 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2229 ExpeditedRegisterMap expedited_register_map;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002230 bool queue_vars_valid = false;
Jason Molenda77f89352016-01-12 07:09:16 +00002231 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2232 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002233 std::string queue_name;
2234 QueueKind queue_kind = eQueueKindUnknown;
Jason Molenda26d84e82016-01-08 00:20:48 +00002235 uint64_t queue_serial_number = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002236 // Iterate through all of the thread dictionary key/value pairs from the structured data dictionary
2237
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002238 thread_dict->ForEach([this,
2239 &tid,
2240 &expedited_register_map,
2241 &thread_name,
2242 &signo,
2243 &reason,
2244 &description,
2245 &exc_type,
2246 &exc_data,
2247 &thread_dispatch_qaddr,
2248 &queue_vars_valid,
Jason Molenda77f89352016-01-12 07:09:16 +00002249 &associated_with_dispatch_queue,
2250 &dispatch_queue_t,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002251 &queue_name,
2252 &queue_kind,
Jason Molenda26d84e82016-01-08 00:20:48 +00002253 &queue_serial_number]
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002254 (ConstString key, StructuredData::Object* object) -> bool
Greg Clayton358cf1e2015-06-25 21:46:34 +00002255 {
2256 if (key == g_key_tid)
2257 {
2258 // thread in big endian hex
2259 tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
2260 }
2261 else if (key == g_key_metype)
2262 {
2263 // exception type in big endian hex
2264 exc_type = object->GetIntegerValue(0);
2265 }
2266 else if (key == g_key_medata)
2267 {
2268 // exception data in big endian hex
2269 StructuredData::Array *array = object->GetAsArray();
2270 if (array)
2271 {
2272 array->ForEach([&exc_data](StructuredData::Object* object) -> bool {
2273 exc_data.push_back(object->GetIntegerValue());
2274 return true; // Keep iterating through all array items
2275 });
2276 }
2277 }
2278 else if (key == g_key_name)
2279 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002280 thread_name = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002281 }
2282 else if (key == g_key_qaddr)
2283 {
2284 thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
2285 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002286 else if (key == g_key_queue_name)
2287 {
2288 queue_vars_valid = true;
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002289 queue_name = object->GetStringValue();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002290 }
2291 else if (key == g_key_queue_kind)
2292 {
2293 std::string queue_kind_str = object->GetStringValue();
2294 if (queue_kind_str == "serial")
2295 {
2296 queue_vars_valid = true;
2297 queue_kind = eQueueKindSerial;
2298 }
2299 else if (queue_kind_str == "concurrent")
2300 {
2301 queue_vars_valid = true;
2302 queue_kind = eQueueKindConcurrent;
2303 }
2304 }
Jason Molenda26d84e82016-01-08 00:20:48 +00002305 else if (key == g_key_queue_serial_number)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002306 {
Jason Molenda26d84e82016-01-08 00:20:48 +00002307 queue_serial_number = object->GetIntegerValue(0);
2308 if (queue_serial_number != 0)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002309 queue_vars_valid = true;
2310 }
Jason Molenda77f89352016-01-12 07:09:16 +00002311 else if (key == g_key_dispatch_queue_t)
2312 {
2313 dispatch_queue_t = object->GetIntegerValue(0);
2314 if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS)
2315 queue_vars_valid = true;
2316 }
2317 else if (key == g_key_associated_with_dispatch_queue)
2318 {
2319 queue_vars_valid = true;
2320 bool associated = object->GetBooleanValue ();
2321 if (associated)
2322 associated_with_dispatch_queue = eLazyBoolYes;
2323 else
2324 associated_with_dispatch_queue = eLazyBoolNo;
2325 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002326 else if (key == g_key_reason)
2327 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002328 reason = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002329 }
2330 else if (key == g_key_description)
2331 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002332 description = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002333 }
2334 else if (key == g_key_registers)
2335 {
2336 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2337
2338 if (registers_dict)
2339 {
2340 registers_dict->ForEach([&expedited_register_map](ConstString key, StructuredData::Object* object) -> bool {
2341 const uint32_t reg = StringConvert::ToUInt32 (key.GetCString(), UINT32_MAX, 10);
2342 if (reg != UINT32_MAX)
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002343 expedited_register_map[reg] = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002344 return true; // Keep iterating through all array items
2345 });
2346 }
2347 }
2348 else if (key == g_key_memory)
2349 {
2350 StructuredData::Array *array = object->GetAsArray();
2351 if (array)
2352 {
2353 array->ForEach([this](StructuredData::Object* object) -> bool {
2354 StructuredData::Dictionary *mem_cache_dict = object->GetAsDictionary();
2355 if (mem_cache_dict)
2356 {
2357 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2358 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>("address", mem_cache_addr))
2359 {
2360 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
2361 {
2362 StringExtractor bytes;
2363 if (mem_cache_dict->GetValueForKeyAsString("bytes", bytes.GetStringRef()))
2364 {
2365 bytes.SetFilePos(0);
2366
2367 const size_t byte_size = bytes.GetStringRef().size()/2;
2368 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2369 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2370 if (bytes_copied == byte_size)
2371 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2372 }
2373 }
2374 }
2375 }
2376 return true; // Keep iterating through all array items
2377 });
2378 }
Eugene Zelenko0722f082015-10-24 01:28:05 +00002379
Greg Clayton358cf1e2015-06-25 21:46:34 +00002380 }
Pavel Labath4a4bb122015-07-16 14:14:35 +00002381 else if (key == g_key_signal)
2382 signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002383 return true; // Keep iterating through all dictionary key/value pairs
2384 });
2385
Greg Clayton2e309072015-07-17 23:42:28 +00002386 return SetThreadStopInfo (tid,
2387 expedited_register_map,
2388 signo,
2389 thread_name,
2390 reason,
2391 description,
2392 exc_type,
2393 exc_data,
2394 thread_dispatch_qaddr,
2395 queue_vars_valid,
Jason Molenda77f89352016-01-12 07:09:16 +00002396 associated_with_dispatch_queue,
2397 dispatch_queue_t,
Greg Clayton2e309072015-07-17 23:42:28 +00002398 queue_name,
2399 queue_kind,
Jason Molenda26d84e82016-01-08 00:20:48 +00002400 queue_serial_number);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002401}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002402
2403StateType
2404ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
2405{
Greg Claytondd0e5a52011-06-02 22:22:38 +00002406 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002407 const char stop_type = stop_packet.GetChar();
2408 switch (stop_type)
2409 {
2410 case 'T':
2411 case 'S':
2412 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00002413 // This is a bit of a hack, but is is required. If we did exec, we
2414 // need to clear our thread lists and also know to rebuild our dynamic
2415 // register info before we lookup and threads and populate the expedited
2416 // register values so we need to know this right away so we can cleanup
2417 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00002418 const uint32_t stop_id = GetStopID();
2419 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00002420 {
2421 // Our first stop, make sure we have a process ID, and also make
2422 // sure we know about our registers
2423 if (GetID() == LLDB_INVALID_PROCESS_ID)
2424 {
Greg Claytonc574ede2011-03-10 02:26:48 +00002425 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00002426 if (pid != LLDB_INVALID_PROCESS_ID)
2427 SetID (pid);
2428 }
2429 BuildDynamicRegisterInfo (true);
2430 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002431 // Stop with signal and thread info
Greg Clayton358cf1e2015-06-25 21:46:34 +00002432 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002433 const uint8_t signo = stop_packet.GetHexU8();
Zachary Turner54695a32016-08-29 19:58:14 +00002434 llvm::StringRef key;
2435 llvm::StringRef value;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002436 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00002437 std::string reason;
2438 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002439 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00002440 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002441 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton0b90be12015-06-23 21:27:50 +00002442 bool queue_vars_valid = false; // says if locals below that start with "queue_" are valid
Jason Molenda77f89352016-01-12 07:09:16 +00002443 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2444 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
Greg Clayton0b90be12015-06-23 21:27:50 +00002445 std::string queue_name;
2446 QueueKind queue_kind = eQueueKindUnknown;
Jason Molenda26d84e82016-01-08 00:20:48 +00002447 uint64_t queue_serial_number = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002448 ExpeditedRegisterMap expedited_register_map;
2449 while (stop_packet.GetNameColonValue(key, value))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002450 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002451 if (key.compare("metype") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002452 {
2453 // exception type in big endian hex
Zachary Turner54695a32016-08-29 19:58:14 +00002454 value.getAsInteger(16, exc_type);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002455 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002456 else if (key.compare("medata") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002457 {
2458 // exception data in big endian hex
Zachary Turner54695a32016-08-29 19:58:14 +00002459 uint64_t x;
2460 value.getAsInteger(16, x);
2461 exc_data.push_back(x);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002462 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002463 else if (key.compare("thread") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002464 {
2465 // thread in big endian hex
Zachary Turner54695a32016-08-29 19:58:14 +00002466 if (value.getAsInteger(16, tid))
2467 tid = LLDB_INVALID_THREAD_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002468 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002469 else if (key.compare("threads") == 0)
Greg Clayton9e920902012-04-10 02:25:43 +00002470 {
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00002471 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
2472
Greg Clayton9e920902012-04-10 02:25:43 +00002473 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00002474 // A comma separated list of all threads in the current
2475 // process that includes the thread for this stop reply
2476 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00002477 lldb::tid_t tid;
Zachary Turner54695a32016-08-29 19:58:14 +00002478 while (!value.empty())
Greg Clayton9e920902012-04-10 02:25:43 +00002479 {
Zachary Turner54695a32016-08-29 19:58:14 +00002480 llvm::StringRef tid_str;
2481 std::tie(tid_str, value) = value.split(',');
2482 if (tid_str.getAsInteger(16, tid))
2483 tid = LLDB_INVALID_THREAD_ID;
2484 m_thread_ids.push_back(tid);
Greg Clayton9e920902012-04-10 02:25:43 +00002485 }
Greg Clayton9e920902012-04-10 02:25:43 +00002486 }
Jason Molenda545304d2015-12-18 00:45:35 +00002487 else if (key.compare("thread-pcs") == 0)
2488 {
2489 m_thread_pcs.clear();
2490 // A comma separated list of all threads in the current
2491 // process that includes the thread for this stop reply
2492 // packet
Jason Molenda545304d2015-12-18 00:45:35 +00002493 lldb::addr_t pc;
Zachary Turner54695a32016-08-29 19:58:14 +00002494 while (!value.empty())
Jason Molenda545304d2015-12-18 00:45:35 +00002495 {
Zachary Turner54695a32016-08-29 19:58:14 +00002496 llvm::StringRef pc_str;
2497 std::tie(pc_str, value) = value.split(',');
2498 if (pc_str.getAsInteger(16, pc))
2499 pc = LLDB_INVALID_ADDRESS;
2500 m_thread_pcs.push_back(pc);
Jason Molenda545304d2015-12-18 00:45:35 +00002501 }
Jason Molenda545304d2015-12-18 00:45:35 +00002502 }
Greg Clayton2e309072015-07-17 23:42:28 +00002503 else if (key.compare("jstopinfo") == 0)
Greg Claytona5801ad2015-07-15 22:59:03 +00002504 {
Zachary Turner54695a32016-08-29 19:58:14 +00002505 StringExtractor json_extractor(value);
2506 std::string json;
Greg Claytona5801ad2015-07-15 22:59:03 +00002507 // Now convert the HEX bytes into a string value
Zachary Turner54695a32016-08-29 19:58:14 +00002508 json_extractor.GetHexByteString(json);
Greg Claytona5801ad2015-07-15 22:59:03 +00002509
2510 // This JSON contains thread IDs and thread stop info for all threads.
2511 // It doesn't contain expedited registers, memory or queue info.
Zachary Turner54695a32016-08-29 19:58:14 +00002512 m_jstopinfo_sp = StructuredData::ParseJSON(json);
Greg Claytona5801ad2015-07-15 22:59:03 +00002513 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002514 else if (key.compare("hexname") == 0)
Greg Claytonde9d0492011-01-08 03:17:57 +00002515 {
Zachary Turner54695a32016-08-29 19:58:14 +00002516 StringExtractor name_extractor(value);
2517 std::string name;
Greg Claytonde9d0492011-01-08 03:17:57 +00002518 // Now convert the HEX bytes into a string value
Zachary Turner54695a32016-08-29 19:58:14 +00002519 name_extractor.GetHexByteString(thread_name);
Greg Claytonde9d0492011-01-08 03:17:57 +00002520 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002521 else if (key.compare("name") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002522 {
Zachary Turner54695a32016-08-29 19:58:14 +00002523 thread_name = value;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002524 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002525 else if (key.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002526 {
Zachary Turner54695a32016-08-29 19:58:14 +00002527 value.getAsInteger(16, thread_dispatch_qaddr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002528 }
Jason Molenda77f89352016-01-12 07:09:16 +00002529 else if (key.compare("dispatch_queue_t") == 0)
2530 {
2531 queue_vars_valid = true;
Zachary Turner54695a32016-08-29 19:58:14 +00002532 value.getAsInteger(16, dispatch_queue_t);
Jason Molenda77f89352016-01-12 07:09:16 +00002533 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002534 else if (key.compare("qname") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002535 {
2536 queue_vars_valid = true;
Zachary Turner54695a32016-08-29 19:58:14 +00002537 StringExtractor name_extractor(value);
Greg Clayton0b90be12015-06-23 21:27:50 +00002538 // Now convert the HEX bytes into a string value
Zachary Turner54695a32016-08-29 19:58:14 +00002539 name_extractor.GetHexByteString(queue_name);
Greg Clayton0b90be12015-06-23 21:27:50 +00002540 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002541 else if (key.compare("qkind") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002542 {
Zachary Turner54695a32016-08-29 19:58:14 +00002543 queue_kind = llvm::StringSwitch<QueueKind>(value)
2544 .Case("serial", eQueueKindSerial)
2545 .Case("concurrent", eQueueKindConcurrent)
2546 .Default(eQueueKindUnknown);
2547 queue_vars_valid = queue_kind != eQueueKindUnknown;
Greg Clayton0b90be12015-06-23 21:27:50 +00002548 }
Jason Molenda26d84e82016-01-08 00:20:48 +00002549 else if (key.compare("qserialnum") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002550 {
Zachary Turner54695a32016-08-29 19:58:14 +00002551 if (!value.getAsInteger(0, queue_serial_number))
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002552 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002553 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002554 else if (key.compare("reason") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002555 {
Zachary Turner54695a32016-08-29 19:58:14 +00002556 reason = value;
Greg Claytona658fd22011-06-04 01:26:29 +00002557 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002558 else if (key.compare("description") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002559 {
Zachary Turner54695a32016-08-29 19:58:14 +00002560 StringExtractor desc_extractor(value);
Greg Claytona658fd22011-06-04 01:26:29 +00002561 // Now convert the HEX bytes into a string value
Zachary Turner54695a32016-08-29 19:58:14 +00002562 desc_extractor.GetHexByteString(description);
Greg Claytona658fd22011-06-04 01:26:29 +00002563 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002564 else if (key.compare("memory") == 0)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002565 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002566 // Expedited memory. GDB servers can choose to send back expedited memory
2567 // that can populate the L1 memory cache in the process so that things like
2568 // the frame pointer backchain can be expedited. This will help stack
2569 // backtracing be more efficient by not having to send as many memory read
2570 // requests down the remote GDB server.
Chaoren Lin7a306082015-06-23 03:17:01 +00002571
Greg Clayton358cf1e2015-06-25 21:46:34 +00002572 // Key/value pair format: memory:<addr>=<bytes>;
2573 // <addr> is a number whose base will be interpreted by the prefix:
2574 // "0x[0-9a-fA-F]+" for hex
2575 // "0[0-7]+" for octal
2576 // "[1-9]+" for decimal
2577 // <bytes> is native endian ASCII hex bytes just like the register values
Zachary Turner54695a32016-08-29 19:58:14 +00002578 llvm::StringRef addr_str, bytes_str;
2579 std::tie(addr_str, bytes_str) = value.split('=');
2580 if (!addr_str.empty() && !bytes_str.empty())
Greg Clayton358cf1e2015-06-25 21:46:34 +00002581 {
Zachary Turner54695a32016-08-29 19:58:14 +00002582 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2583 if (!addr_str.getAsInteger(0, mem_cache_addr))
Greg Clayton3e06bd92011-01-09 21:07:35 +00002584 {
Zachary Turner54695a32016-08-29 19:58:14 +00002585 StringExtractor bytes(bytes_str);
2586 const size_t byte_size = bytes.GetBytesLeft() / 2;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002587 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2588 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2589 if (bytes_copied == byte_size)
2590 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
Greg Clayton3e06bd92011-01-09 21:07:35 +00002591 }
2592 }
2593 }
Jaydeep Patil725666c2015-08-13 03:46:01 +00002594 else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 || key.compare("awatch") == 0)
2595 {
2596 // Support standard GDB remote stop reply packet 'TAAwatch:addr'
Zachary Turner54695a32016-08-29 19:58:14 +00002597 lldb::addr_t wp_addr = LLDB_INVALID_ADDRESS;
2598 value.getAsInteger(16, wp_addr);
2599
Jaydeep Patil725666c2015-08-13 03:46:01 +00002600 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2601 uint32_t wp_index = LLDB_INVALID_INDEX32;
2602
2603 if (wp_sp)
2604 wp_index = wp_sp->GetHardwareIndex();
2605
2606 reason = "watchpoint";
2607 StreamString ostr;
2608 ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
2609 description = ostr.GetString().c_str();
2610 }
Stephane Sezer2618e912015-08-21 16:51:56 +00002611 else if (key.compare("library") == 0)
2612 {
2613 LoadModules();
2614 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002615 else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1]))
2616 {
Zachary Turner54695a32016-08-29 19:58:14 +00002617 uint32_t reg = UINT32_MAX;
2618 if (!key.getAsInteger(16, reg))
Greg Clayton358cf1e2015-06-25 21:46:34 +00002619 expedited_register_map[reg] = std::move(value);
2620 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002621 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002622
Bhushan D. Attarde1e271df2015-07-24 04:06:20 +00002623 if (tid == LLDB_INVALID_THREAD_ID)
2624 {
Ed Maste81b4c5f2016-01-04 01:43:47 +00002625 // A thread id may be invalid if the response is old style 'S' packet which does not provide the
Bhushan D. Attarde1e271df2015-07-24 04:06:20 +00002626 // thread information. So update the thread list and choose the first one.
2627 UpdateThreadIDList ();
Ed Maste81b4c5f2016-01-04 01:43:47 +00002628
Bhushan D. Attarde1e271df2015-07-24 04:06:20 +00002629 if (!m_thread_ids.empty ())
2630 {
2631 tid = m_thread_ids.front ();
2632 }
2633 }
2634
Greg Clayton358cf1e2015-06-25 21:46:34 +00002635 ThreadSP thread_sp = SetThreadStopInfo (tid,
2636 expedited_register_map,
2637 signo,
2638 thread_name,
2639 reason,
2640 description,
2641 exc_type,
2642 exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002643 thread_dispatch_qaddr,
2644 queue_vars_valid,
Jason Molenda77f89352016-01-12 07:09:16 +00002645 associated_with_dispatch_queue,
2646 dispatch_queue_t,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002647 queue_name,
2648 queue_kind,
Jason Molenda26d84e82016-01-08 00:20:48 +00002649 queue_serial_number);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002650
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002651 return eStateStopped;
2652 }
2653 break;
2654
2655 case 'W':
Todd Fialaff6131a2014-05-19 04:57:23 +00002656 case 'X':
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002657 // process exited
2658 return eStateExited;
2659
2660 default:
2661 break;
2662 }
2663 return eStateInvalid;
2664}
2665
2666void
2667ProcessGDBRemote::RefreshStateAfterStop ()
2668{
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00002669 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
2670
Greg Clayton9e920902012-04-10 02:25:43 +00002671 m_thread_ids.clear();
Jason Molenda545304d2015-12-18 00:45:35 +00002672 m_thread_pcs.clear();
Greg Clayton9e920902012-04-10 02:25:43 +00002673 // Set the thread stop info. It might have a "threads" key whose value is
2674 // a list of all thread IDs in the current process, so m_thread_ids might
2675 // get set.
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002676
2677 // Scope for the lock
2678 {
2679 // Lock the thread stack while we access it
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +00002680 std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002681 // Get the number of stop packets on the stack
2682 int nItems = m_stop_packet_stack.size();
2683 // Iterate over them
2684 for (int i = 0; i < nItems; i++)
2685 {
2686 // Get the thread stop info
2687 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2688 // Process thread stop info
2689 SetThreadStopInfo(stop_info);
2690 }
2691 // Clear the thread stop stack
2692 m_stop_packet_stack.clear();
2693 }
2694
Greg Clayton9e920902012-04-10 02:25:43 +00002695 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2696 if (m_thread_ids.empty())
2697 {
2698 // No, we need to fetch the thread list manually
2699 UpdateThreadIDList();
2700 }
2701
Ewan Crawford78baa192015-05-13 09:18:18 +00002702 // If we have queried for a default thread id
2703 if (m_initial_tid != LLDB_INVALID_THREAD_ID)
2704 {
2705 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2706 m_initial_tid = LLDB_INVALID_THREAD_ID;
2707 }
2708
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002709 // Let all threads recover from stopping and do any clean up based
2710 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002711 m_thread_list_real.RefreshStateAfterStop();
Ed Maste81b4c5f2016-01-04 01:43:47 +00002712
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002713}
2714
2715Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002716ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002717{
2718 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002719
Greg Clayton513c26c2011-01-29 07:10:55 +00002720 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002721 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002722 // We are being asked to halt during an attach. We need to just close
2723 // our file handle and debugserver will go away, and we can be done...
2724 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00002725 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002726 else
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00002727 caused_stop = m_gdb_comm.Interrupt();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002728 return error;
2729}
2730
2731Error
Jim Inghamacff8952013-05-02 00:27:30 +00002732ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002733{
2734 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002735 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00002736 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00002737 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
Ed Maste81b4c5f2016-01-04 01:43:47 +00002738
Jim Inghamacff8952013-05-02 00:27:30 +00002739 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002740 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002741 {
Jim Inghamacff8952013-05-02 00:27:30 +00002742 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002743 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
2744 else
Jim Inghamacff8952013-05-02 00:27:30 +00002745 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00002746 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00002747
Jim Inghamacff8952013-05-02 00:27:30 +00002748 if (!error.Success())
2749 return error;
2750
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002751 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00002752 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002753
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002754 SetPrivateState (eStateDetached);
2755 ResumePrivateStateThread();
2756
2757 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00002758 return error;
2759}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002760
Eugene Zelenko0722f082015-10-24 01:28:05 +00002761
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002762Error
2763ProcessGDBRemote::DoDestroy ()
2764{
2765 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002766 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002767 if (log)
2768 log->Printf ("ProcessGDBRemote::DoDestroy()");
2769
Jim Ingham43c555d2012-07-04 00:35:43 +00002770 // There is a bug in older iOS debugservers where they don't shut down the process
2771 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
2772 // this can cause problems with restarting. So we check to see if any of our threads are stopped
2773 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
2774 // destroy it again.
2775 //
2776 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
2777 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
2778 // the debugservers with this bug are equal. There really should be a better way to test this!
2779 //
2780 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
2781 // get called here to destroy again and we're still at a breakpoint or exception, then we should
2782 // just do the straight-forward kill.
2783 //
2784 // And of course, if we weren't able to stop the process by the time we get here, it isn't
2785 // necessary (or helpful) to do any of this.
2786
2787 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
2788 {
2789 PlatformSP platform_sp = GetTarget().GetPlatform();
Ed Maste81b4c5f2016-01-04 01:43:47 +00002790
Jim Ingham43c555d2012-07-04 00:35:43 +00002791 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2792 if (platform_sp
2793 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00002794 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00002795 {
2796 if (m_destroy_tried_resuming)
2797 {
2798 if (log)
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002799 log->PutCString ("ProcessGDBRemote::DoDestroy() - Tried resuming to destroy once already, not doing it again.");
Jim Ingham43c555d2012-07-04 00:35:43 +00002800 }
2801 else
Ed Maste81b4c5f2016-01-04 01:43:47 +00002802 {
Jim Ingham43c555d2012-07-04 00:35:43 +00002803 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
2804 // but we really need it to happen here and it doesn't matter if we do it twice.
2805 m_thread_list.DiscardThreadPlans();
2806 DisableAllBreakpointSites();
Ed Maste81b4c5f2016-01-04 01:43:47 +00002807
Jim Ingham43c555d2012-07-04 00:35:43 +00002808 bool stop_looks_like_crash = false;
2809 ThreadList &threads = GetThreadList();
Ed Maste81b4c5f2016-01-04 01:43:47 +00002810
Jim Ingham43c555d2012-07-04 00:35:43 +00002811 {
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00002812 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
Ed Maste81b4c5f2016-01-04 01:43:47 +00002813
Jim Ingham43c555d2012-07-04 00:35:43 +00002814 size_t num_threads = threads.GetSize();
2815 for (size_t i = 0; i < num_threads; i++)
2816 {
2817 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002818 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002819 StopReason reason = eStopReasonInvalid;
2820 if (stop_info_sp)
2821 reason = stop_info_sp->GetStopReason();
2822 if (reason == eStopReasonBreakpoint
2823 || reason == eStopReasonException)
2824 {
2825 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002826 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
2827 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00002828 stop_info_sp->GetDescription());
2829 stop_looks_like_crash = true;
2830 break;
2831 }
2832 }
2833 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00002834
Jim Ingham43c555d2012-07-04 00:35:43 +00002835 if (stop_looks_like_crash)
2836 {
2837 if (log)
2838 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
2839 m_destroy_tried_resuming = true;
Ed Maste81b4c5f2016-01-04 01:43:47 +00002840
2841 // If we are going to run again before killing, it would be good to suspend all the threads
Jim Ingham43c555d2012-07-04 00:35:43 +00002842 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
2843 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
2844 // have to run the risk of letting those threads proceed a bit.
Ed Maste81b4c5f2016-01-04 01:43:47 +00002845
Jim Ingham43c555d2012-07-04 00:35:43 +00002846 {
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00002847 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
Ed Maste81b4c5f2016-01-04 01:43:47 +00002848
Jim Ingham43c555d2012-07-04 00:35:43 +00002849 size_t num_threads = threads.GetSize();
2850 for (size_t i = 0; i < num_threads; i++)
2851 {
2852 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002853 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002854 StopReason reason = eStopReasonInvalid;
2855 if (stop_info_sp)
2856 reason = stop_info_sp->GetStopReason();
2857 if (reason != eStopReasonBreakpoint
2858 && reason != eStopReasonException)
2859 {
2860 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002861 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
2862 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00002863 thread_sp->SetResumeState(eStateSuspended);
2864 }
2865 }
2866 }
2867 Resume ();
Jason Molendaede31932015-04-17 05:01:58 +00002868 return Destroy(false);
Jim Ingham43c555d2012-07-04 00:35:43 +00002869 }
2870 }
2871 }
2872 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00002873
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002874 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00002875 int exit_status = SIGABRT;
2876 std::string exit_string;
2877
Greg Clayton6ed95942011-01-22 07:12:45 +00002878 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002879 {
Jim Inghamaab78372011-10-28 01:11:35 +00002880 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00002881 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002882 StringExtractorGDBRemote response;
2883 bool send_async = true;
Tamas Berghammer912800c2015-02-24 10:23:39 +00002884 GDBRemoteCommunication::ScopedTimeout (m_gdb_comm, 3);
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002885
Greg Clayton3dedae12013-12-06 21:45:27 +00002886 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton513c26c2011-01-29 07:10:55 +00002887 {
2888 char packet_cmd = response.GetChar(0);
2889
2890 if (packet_cmd == 'W' || packet_cmd == 'X')
2891 {
Jim Inghameac0aa42014-02-21 22:36:11 +00002892#if defined(__APPLE__)
Jason Molenda17b45392016-06-23 04:24:16 +00002893 // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off
Jim Ingham9d67cc52014-02-21 22:35:29 +00002894 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill
Jason Molenda17b45392016-06-23 04:24:16 +00002895 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns
Jim Ingham9d67cc52014-02-21 22:35:29 +00002896 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap
2897 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of
2898 // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2899 // Anyway, so call waitpid here to finally reap it.
2900 PlatformSP platform_sp(GetTarget().GetPlatform());
2901 if (platform_sp && platform_sp->IsHost())
2902 {
2903 int status;
2904 ::pid_t reap_pid;
2905 reap_pid = waitpid (GetID(), &status, WNOHANG);
2906 if (log)
2907 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2908 }
2909#endif
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002910 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002911 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00002912 exit_status = response.GetHexU8();
2913 }
2914 else
2915 {
2916 if (log)
2917 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2918 exit_string.assign("got unexpected response to k packet: ");
2919 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00002920 }
2921 }
2922 else
2923 {
Jim Inghambabfc382012-06-06 00:32:39 +00002924 if (log)
2925 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2926 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00002927 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002928 }
Jim Inghambabfc382012-06-06 00:32:39 +00002929 else
2930 {
2931 if (log)
Ed Masteb3a53332014-03-17 17:05:22 +00002932 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching");
Jim Inghamcfc09352012-07-27 23:57:19 +00002933 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00002934 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002935 }
Jim Inghambabfc382012-06-06 00:32:39 +00002936 else
2937 {
2938 // If we missed setting the exit status on the way out, do it here.
2939 // NB set exit status can be called multiple times, the first one sets the status.
2940 exit_string.assign("destroying when not connected to debugserver");
2941 }
2942
2943 SetExitStatus(exit_status, exit_string.c_str());
2944
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002945 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002946 KillDebugserverProcess ();
2947 return error;
2948}
2949
Greg Clayton8cda7f02013-05-21 21:55:59 +00002950void
2951ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2952{
Greg Clayton8cda7f02013-05-21 21:55:59 +00002953 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2954 if (did_exec)
2955 {
2956 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2957 if (log)
2958 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2959
2960 m_thread_list_real.Clear();
2961 m_thread_list.Clear();
2962 BuildDynamicRegisterInfo (true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002963 m_gdb_comm.ResetDiscoverableSettings (did_exec);
Greg Clayton8cda7f02013-05-21 21:55:59 +00002964 }
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002965
2966 // Scope the lock
2967 {
2968 // Lock the thread stack while we access it
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +00002969 std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
Greg Clayton2e309072015-07-17 23:42:28 +00002970
2971 // We are are not using non-stop mode, there can only be one last stop
2972 // reply packet, so clear the list.
2973 if (GetTarget().GetNonStopModeEnabled() == false)
2974 m_stop_packet_stack.clear();
2975
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002976 // Add this stop packet to the stop packet stack
2977 // This stack will get popped and examined when we switch to the
2978 // Stopped state
2979 m_stop_packet_stack.push_back(response);
2980 }
Greg Clayton8cda7f02013-05-21 21:55:59 +00002981}
2982
Chaoren Linc963a222015-09-01 16:58:45 +00002983void
2984ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp)
2985{
2986 Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
2987}
2988
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002989//------------------------------------------------------------------
2990// Process Queries
2991//------------------------------------------------------------------
2992
2993bool
2994ProcessGDBRemote::IsAlive ()
2995{
Jason Molenda1d3b3562015-11-05 23:54:29 +00002996 return m_gdb_comm.IsConnected() && Process::IsAlive();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002997}
2998
2999addr_t
3000ProcessGDBRemote::GetImageInfoAddress()
3001{
Aidan Doddsc0c83852015-05-08 09:36:31 +00003002 // request the link map address via the $qShlibInfoAddr packet
3003 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
3004
3005 // the loaded module list can also provides a link map address
3006 if (addr == LLDB_INVALID_ADDRESS)
3007 {
Stephane Sezer87b0fe02016-01-12 19:02:41 +00003008 LoadedModuleInfoList list;
Aidan Doddsc0c83852015-05-08 09:36:31 +00003009 if (GetLoadedModuleList (list).Success())
3010 addr = list.m_link_map;
3011 }
3012
3013 return addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003014}
3015
Greg Clayton2e309072015-07-17 23:42:28 +00003016void
3017ProcessGDBRemote::WillPublicStop ()
3018{
3019 // See if the GDB remote client supports the JSON threads info.
3020 // If so, we gather stop info for all threads, expedited registers,
3021 // expedited memory, runtime queue information (iOS and MacOSX only),
3022 // and more. Expediting memory will help stack backtracing be much
3023 // faster. Expediting registers will make sure we don't have to read
3024 // the thread registers for GPRs.
3025 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
3026
3027 if (m_jthreadsinfo_sp)
3028 {
3029 // Now set the stop info for each thread and also expedite any registers
3030 // and memory that was in the jThreadsInfo response.
3031 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
3032 if (thread_infos)
3033 {
3034 const size_t n = thread_infos->GetSize();
3035 for (size_t i=0; i<n; ++i)
3036 {
3037 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
3038 if (thread_dict)
3039 SetThreadStopInfo(thread_dict);
3040 }
3041 }
3042 }
3043}
3044
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003045//------------------------------------------------------------------
3046// Process Memory
3047//------------------------------------------------------------------
3048size_t
3049ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
3050{
Jason Molenda6076bf42014-05-06 04:34:52 +00003051 GetMaxMemorySize ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003052 if (size > m_max_memory_size)
3053 {
3054 // Keep memory read sizes down to a sane limit. This function will be
Ed Maste81b4c5f2016-01-04 01:43:47 +00003055 // called multiple times in order to complete the task by
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003056 // lldb_private::Process so it is ok to do this.
3057 size = m_max_memory_size;
3058 }
3059
3060 char packet[64];
Jason Molenda6076bf42014-05-06 04:34:52 +00003061 int packet_len;
3062 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
Pavel Labath3bf11252015-10-14 12:59:37 +00003063 packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64,
3064 binary_memory_read ? 'x' : 'm', (uint64_t)addr, (uint64_t)size);
Andy Gibbsa297a972013-06-19 19:04:53 +00003065 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003066 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003067 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003068 {
Greg Clayton576d8832011-03-22 04:00:09 +00003069 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003070 {
3071 error.Clear();
Jason Molenda6076bf42014-05-06 04:34:52 +00003072 if (binary_memory_read)
3073 {
3074 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any
3075 // 0x7d character escaping that was present in the packet
3076
3077 size_t data_received_size = response.GetBytesLeft();
3078 if (data_received_size > size)
3079 {
3080 // Don't write past the end of BUF if the remote debug server gave us too
3081 // much data for some reason.
3082 data_received_size = size;
3083 }
3084 memcpy (buf, response.GetStringRef().data(), data_received_size);
3085 return data_received_size;
3086 }
3087 else
3088 {
3089 return response.GetHexBytes(buf, size, '\xdd');
3090 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003091 }
Greg Clayton576d8832011-03-22 04:00:09 +00003092 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00003093 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00003094 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00003095 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003096 else
Greg Clayton9944cd72012-09-19 01:46:31 +00003097 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003098 }
3099 else
3100 {
Jim Ingham35579dd2013-06-03 19:34:01 +00003101 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003102 }
3103 return 0;
3104}
3105
3106size_t
3107ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
3108{
Jason Molenda6076bf42014-05-06 04:34:52 +00003109 GetMaxMemorySize ();
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00003110 if (size > m_max_memory_size)
3111 {
3112 // Keep memory read sizes down to a sane limit. This function will be
Ed Maste81b4c5f2016-01-04 01:43:47 +00003113 // called multiple times in order to complete the task by
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00003114 // lldb_private::Process so it is ok to do this.
3115 size = m_max_memory_size;
3116 }
3117
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003118 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00003119 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Bruce Mitchener9ccb9702015-11-07 04:40:13 +00003120 packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(), endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003121 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003122 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003123 {
Greg Clayton576d8832011-03-22 04:00:09 +00003124 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003125 {
3126 error.Clear();
3127 return size;
3128 }
Greg Clayton576d8832011-03-22 04:00:09 +00003129 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00003130 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00003131 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00003132 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003133 else
Greg Clayton9944cd72012-09-19 01:46:31 +00003134 error.SetErrorStringWithFormat("unexpected response to GDB server memory write packet '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003135 }
3136 else
3137 {
Jim Ingham35579dd2013-06-03 19:34:01 +00003138 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003139 }
3140 return 0;
3141}
3142
3143lldb::addr_t
3144ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
3145{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003146 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_EXPRESSIONS));
Greg Clayton2a48f522011-05-14 01:50:35 +00003147 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
Ed Maste81b4c5f2016-01-04 01:43:47 +00003148
Greg Claytoncec91ef2016-02-26 01:20:20 +00003149 if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo)
Greg Clayton2a48f522011-05-14 01:50:35 +00003150 {
Greg Claytoncec91ef2016-02-26 01:20:20 +00003151 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
3152 if (allocated_addr != LLDB_INVALID_ADDRESS || m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes)
3153 return allocated_addr;
3154 }
Greg Clayton2a48f522011-05-14 01:50:35 +00003155
Greg Claytoncec91ef2016-02-26 01:20:20 +00003156 if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo)
3157 {
3158 // Call mmap() to create memory in the inferior..
3159 unsigned prot = 0;
3160 if (permissions & lldb::ePermissionsReadable)
3161 prot |= eMmapProtRead;
3162 if (permissions & lldb::ePermissionsWritable)
3163 prot |= eMmapProtWrite;
3164 if (permissions & lldb::ePermissionsExecutable)
3165 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00003166
Greg Claytoncec91ef2016-02-26 01:20:20 +00003167 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
3168 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
3169 m_addr_to_mmap_size[allocated_addr] = size;
3170 else
3171 {
3172 allocated_addr = LLDB_INVALID_ADDRESS;
3173 if (log)
3174 log->Printf ("ProcessGDBRemote::%s no direct stub support for memory allocation, and InferiorCallMmap also failed - is stub missing register context save/restore capability?", __FUNCTION__);
3175 }
Greg Clayton2a48f522011-05-14 01:50:35 +00003176 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00003177
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003178 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00003179 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003180 else
3181 error.Clear();
3182 return allocated_addr;
3183}
3184
3185Error
Ed Maste81b4c5f2016-01-04 01:43:47 +00003186ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
Greg Clayton46fb5582011-11-18 07:03:08 +00003187 MemoryRegionInfo &region_info)
3188{
Ed Maste81b4c5f2016-01-04 01:43:47 +00003189
Greg Clayton46fb5582011-11-18 07:03:08 +00003190 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
3191 return error;
3192}
3193
3194Error
Johnny Chen64637202012-05-23 21:09:52 +00003195ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
3196{
Ed Maste81b4c5f2016-01-04 01:43:47 +00003197
Johnny Chen64637202012-05-23 21:09:52 +00003198 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
3199 return error;
3200}
3201
3202Error
Enrico Granataf04a2192012-07-13 23:18:48 +00003203ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
3204{
Jaydeep Patil725666c2015-08-13 03:46:01 +00003205 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after, GetTarget().GetArchitecture()));
Enrico Granataf04a2192012-07-13 23:18:48 +00003206 return error;
3207}
3208
3209Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003210ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
3211{
Ed Maste81b4c5f2016-01-04 01:43:47 +00003212 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00003213 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
3214
3215 switch (supported)
3216 {
3217 case eLazyBoolCalculate:
Ed Maste81b4c5f2016-01-04 01:43:47 +00003218 // We should never be deallocating memory without allocating memory
Greg Clayton70b57652011-05-15 01:25:55 +00003219 // first so we should never get eLazyBoolCalculate
3220 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
3221 break;
3222
3223 case eLazyBoolYes:
3224 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00003225 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003226 break;
Ed Maste81b4c5f2016-01-04 01:43:47 +00003227
Greg Clayton70b57652011-05-15 01:25:55 +00003228 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003229 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00003230 {
3231 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003232 if (pos != m_addr_to_mmap_size.end() &&
3233 InferiorCallMunmap(this, addr, pos->second))
3234 m_addr_to_mmap_size.erase (pos);
3235 else
Daniel Malead01b2952012-11-29 21:49:15 +00003236 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003237 }
3238 break;
3239 }
3240
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003241 return error;
3242}
3243
Eugene Zelenko0722f082015-10-24 01:28:05 +00003244
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003245//------------------------------------------------------------------
3246// Process STDIO
3247//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003248size_t
3249ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
3250{
3251 if (m_stdio_communication.IsConnected())
3252 {
3253 ConnectionStatus status;
3254 m_stdio_communication.Write(src, src_len, status, NULL);
3255 }
Vince Harrondf3f00f2015-02-10 21:09:04 +00003256 else if (m_stdin_forward)
Vince Harrone0be4252015-02-06 18:32:57 +00003257 {
3258 m_gdb_comm.SendStdinNotification(src, src_len);
3259 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003260 return 0;
3261}
3262
3263Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003264ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003265{
3266 Error error;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003267 assert(bp_site != NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003268
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003269 // Get logging info
3270 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003271 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003272
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003273 // Get the breakpoint address
3274 const addr_t addr = bp_site->GetLoadAddress();
3275
3276 // Log that a breakpoint was requested
3277 if (log)
3278 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
3279
3280 // Breakpoint already exists and is enabled
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003281 if (bp_site->IsEnabled())
3282 {
3283 if (log)
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003284 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003285 return error;
3286 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003287
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003288 // Get the software breakpoint trap opcode size
3289 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3290
3291 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
3292 // is supported by the remote stub. These are set to true by default, and later set to false
3293 // only after we receive an unimplemented response when sending a breakpoint packet. This means
3294 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
3295 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
3296 // indicates if the user specifically asked for hardware breakpoints. If true then we will
3297 // skip over software breakpoints.
3298 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
3299 {
3300 // Try to send off a software breakpoint packet ($Z0)
Jim Ingham906d91e2016-05-19 02:13:44 +00003301 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size);
3302 if (error_no == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003303 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003304 // The breakpoint was placed successfully
3305 bp_site->SetEnabled(true);
3306 bp_site->SetType(BreakpointSite::eExternal);
Greg Claytoneb023e72013-10-11 19:48:25 +00003307 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003308 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003309
3310 // SendGDBStoppointTypePacket() will return an error if it was unable to set this
3311 // breakpoint. We need to differentiate between a error specific to placing this breakpoint
3312 // or if we have learned that this breakpoint type is unsupported. To do this, we
3313 // must test the support boolean for this breakpoint type to see if it now indicates that
3314 // this breakpoint type is unsupported. If they are still supported then we should return
3315 // with the error code. If they are now unsupported, then we would like to fall through
3316 // and try another form of breakpoint.
3317 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
Jim Ingham906d91e2016-05-19 02:13:44 +00003318 {
3319 if (error_no != UINT8_MAX)
3320 error.SetErrorStringWithFormat("error: %d sending the breakpoint request", errno);
3321 else
3322 error.SetErrorString("error sending the breakpoint request");
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003323 return error;
Jim Ingham906d91e2016-05-19 02:13:44 +00003324 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003325
3326 // We reach here when software breakpoints have been found to be unsupported. For future
3327 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
3328 // known not to be supported.
3329 if (log)
3330 log->Printf("Software breakpoints are unsupported");
3331
3332 // So we will fall through and try a hardware breakpoint
3333 }
3334
3335 // The process of setting a hardware breakpoint is much the same as above. We check the
3336 // supported boolean for this breakpoint type, and if it is thought to be supported then we
3337 // will try to set this breakpoint with a hardware breakpoint.
3338 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3339 {
3340 // Try to send off a hardware breakpoint packet ($Z1)
Jim Ingham906d91e2016-05-19 02:13:44 +00003341 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size);
3342 if (error_no == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003343 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003344 // The breakpoint was placed successfully
3345 bp_site->SetEnabled(true);
3346 bp_site->SetType(BreakpointSite::eHardware);
3347 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003348 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003349
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003350 // Check if the error was something other then an unsupported breakpoint type
3351 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3352 {
3353 // Unable to set this hardware breakpoint
Jim Ingham906d91e2016-05-19 02:13:44 +00003354 if (error_no != UINT8_MAX)
3355 error.SetErrorStringWithFormat("error: %d sending the hardware breakpoint request "
3356 "(hardware breakpoint resources might be exhausted or unavailable)",
3357 error_no);
3358 else
3359 error.SetErrorString("error sending the hardware breakpoint request (hardware breakpoint resources "
3360 "might be exhausted or unavailable)");
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003361 return error;
3362 }
3363
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003364 // We will reach here when the stub gives an unsupported response to a hardware breakpoint
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003365 if (log)
3366 log->Printf("Hardware breakpoints are unsupported");
3367
3368 // Finally we will falling through to a #trap style breakpoint
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003369 }
3370
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003371 // Don't fall through when hardware breakpoints were specifically requested
3372 if (bp_site->HardwareRequired())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003373 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003374 error.SetErrorString("hardware breakpoints are not supported");
3375 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003376 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003377
3378 // As a last resort we want to place a manual breakpoint. An instruction
3379 // is placed into the process memory using memory write packets.
3380 return EnableSoftwareBreakpoint(bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003381}
3382
3383Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003384ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003385{
3386 Error error;
3387 assert (bp_site != NULL);
3388 addr_t addr = bp_site->GetLoadAddress();
3389 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00003390 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003391 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003392 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003393
3394 if (bp_site->IsEnabled())
3395 {
3396 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
3397
Greg Clayton8b82f082011-04-12 05:54:46 +00003398 BreakpointSite::Type bp_type = bp_site->GetType();
3399 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003400 {
Greg Clayton8b82f082011-04-12 05:54:46 +00003401 case BreakpointSite::eSoftware:
3402 error = DisableSoftwareBreakpoint (bp_site);
3403 break;
3404
3405 case BreakpointSite::eHardware:
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003406 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003407 error.SetErrorToGenericError();
3408 break;
3409
3410 case BreakpointSite::eExternal:
Jim Inghama04ef752014-03-07 11:18:02 +00003411 {
3412 GDBStoppointType stoppoint_type;
3413 if (bp_site->IsHardware())
3414 stoppoint_type = eBreakpointHardware;
3415 else
3416 stoppoint_type = eBreakpointSoftware;
Ed Maste81b4c5f2016-01-04 01:43:47 +00003417
Jim Inghama04ef752014-03-07 11:18:02 +00003418 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003419 error.SetErrorToGenericError();
Jim Inghama04ef752014-03-07 11:18:02 +00003420 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003421 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003422 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003423 if (error.Success())
3424 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003425 }
3426 else
3427 {
3428 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003429 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003430 return error;
3431 }
3432
3433 if (error.Success())
3434 error.SetErrorToGenericError();
3435 return error;
3436}
3437
Johnny Chen11309a32011-09-06 22:38:36 +00003438// Pre-requisite: wp != NULL.
3439static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00003440GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00003441{
3442 assert(wp);
3443 bool watch_read = wp->WatchpointRead();
3444 bool watch_write = wp->WatchpointWrite();
3445
3446 // watch_read and watch_write cannot both be false.
3447 assert(watch_read || watch_write);
3448 if (watch_read && watch_write)
3449 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00003450 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00003451 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00003452 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00003453 return eWatchpointWrite;
3454}
3455
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003456Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003457ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003458{
3459 Error error;
3460 if (wp)
3461 {
3462 user_id_t watchID = wp->GetID();
3463 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00003464 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003465 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003466 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003467 if (wp->IsEnabled())
3468 {
3469 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003470 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.", watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003471 return error;
3472 }
Johnny Chen11309a32011-09-06 22:38:36 +00003473
3474 GDBStoppointType type = GetGDBStoppointType(wp);
3475 // Pass down an appropriate z/Z packet...
3476 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003477 {
Johnny Chen11309a32011-09-06 22:38:36 +00003478 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
3479 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003480 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003481 return error;
3482 }
3483 else
3484 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003485 }
Johnny Chen11309a32011-09-06 22:38:36 +00003486 else
3487 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003488 }
3489 else
3490 {
Johnny Chen01a67862011-10-14 00:42:25 +00003491 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003492 }
3493 if (error.Success())
3494 error.SetErrorToGenericError();
3495 return error;
3496}
3497
3498Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003499ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003500{
3501 Error error;
3502 if (wp)
3503 {
3504 user_id_t watchID = wp->GetID();
3505
Greg Clayton5160ce52013-03-27 23:08:40 +00003506 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003507
3508 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00003509
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003510 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003511 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003512
Johnny Chen11309a32011-09-06 22:38:36 +00003513 if (!wp->IsEnabled())
3514 {
3515 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003516 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
Johnny Chen892943f2012-08-23 22:28:26 +00003517 // See also 'class WatchpointSentry' within StopInfo.cpp.
3518 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
3519 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00003520 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003521 return error;
3522 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00003523
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003524 if (wp->IsHardware())
3525 {
Johnny Chen11309a32011-09-06 22:38:36 +00003526 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003527 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00003528 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
3529 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003530 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003531 return error;
3532 }
3533 else
Ed Maste81b4c5f2016-01-04 01:43:47 +00003534 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003535 }
3536 // TODO: clear software watchpoints if we implement them
3537 }
3538 else
3539 {
Johnny Chen01a67862011-10-14 00:42:25 +00003540 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003541 }
3542 if (error.Success())
3543 error.SetErrorToGenericError();
3544 return error;
3545}
3546
3547void
3548ProcessGDBRemote::Clear()
3549{
3550 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00003551 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003552 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003553}
3554
3555Error
3556ProcessGDBRemote::DoSignal (int signo)
3557{
3558 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00003559 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003560 if (log)
3561 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
3562
3563 if (!m_gdb_comm.SendAsyncSignal (signo))
3564 error.SetErrorStringWithFormat("failed to send signal %i", signo);
3565 return error;
3566}
3567
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003568Error
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00003569ProcessGDBRemote::EstablishConnectionIfNeeded (const ProcessInfo &process_info)
3570{
3571 // Make sure we aren't already connected?
3572 if (m_gdb_comm.IsConnected())
3573 return Error();
3574
3575 PlatformSP platform_sp (GetTarget ().GetPlatform ());
3576 if (platform_sp && !platform_sp->IsHost ())
3577 return Error("Lost debug server connection");
3578
3579 auto error = LaunchAndConnectToDebugserver (process_info);
3580 if (error.Fail())
3581 {
3582 const char *error_string = error.AsCString();
3583 if (error_string == nullptr)
3584 error_string = "unable to launch " DEBUGSERVER_BASENAME;
3585 }
3586 return error;
3587}
Greg Claytonc6c420f2016-08-12 16:46:18 +00003588#if defined (__APPLE__)
3589#define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1
3590#endif
3591
3592#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3593static bool SetCloexecFlag(int fd)
3594{
3595#if defined(FD_CLOEXEC)
3596 int flags = ::fcntl(fd, F_GETFD);
3597 if (flags == -1)
3598 return false;
3599 return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0);
3600#else
3601 return false;
3602#endif
3603}
3604#endif
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00003605
3606Error
Greg Clayton91a9b2472013-12-04 19:19:12 +00003607ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003608{
Pavel Labath998bdc52016-05-11 16:59:04 +00003609 using namespace std::placeholders; // For _1, _2, etc.
3610
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003611 Error error;
3612 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
3613 {
3614 // If we locate debugserver, keep that located version around
3615 static FileSpec g_debugserver_file_spec;
3616
Han Ming Ong84647042012-02-25 01:07:38 +00003617 ProcessLaunchInfo debugserver_launch_info;
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00003618 // Make debugserver run in its own session so signals generated by
3619 // special terminal key sequences (^C) don't affect debugserver.
3620 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3621
Pavel Labath194357c2016-05-12 11:10:01 +00003622 const std::weak_ptr<ProcessGDBRemote> this_wp = std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
3623 debugserver_launch_info.SetMonitorProcessCallback(std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3, _4),
Pavel Labath998bdc52016-05-11 16:59:04 +00003624 false);
Greg Clayton91a9b2472013-12-04 19:19:12 +00003625 debugserver_launch_info.SetUserID(process_info.GetUserID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003626
Greg Claytonfda4fab2014-01-10 22:24:11 +00003627
Greg Claytonc6c420f2016-08-12 16:46:18 +00003628 int communication_fd = -1;
3629#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3630 // Auto close the sockets we might open up unless everything goes OK. This
3631 // helps us not leak file descriptors when things go wrong.
3632 lldb_utility::CleanUp <int, int> our_socket(-1, -1, close);
3633 lldb_utility::CleanUp <int, int> gdb_socket(-1, -1, close);
3634
3635 // Use a socketpair on Apple for now until other platforms can verify it
3636 // works and is fast enough
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003637 {
Greg Claytonc6c420f2016-08-12 16:46:18 +00003638 int sockets[2]; /* the pair of socket descriptors */
3639 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1)
3640 {
3641 error.SetErrorToErrno();
3642 return error;
3643 }
3644
3645 our_socket.set(sockets[0]);
3646 gdb_socket.set(sockets[1]);
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003647 }
3648
Greg Claytonc6c420f2016-08-12 16:46:18 +00003649 // Don't let any child processes inherit our communication socket
3650 SetCloexecFlag(our_socket.get());
3651 communication_fd = gdb_socket.get();
3652#endif
3653
3654 error = m_gdb_comm.StartDebugserverProcess(nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info, nullptr, nullptr, communication_fd);
Greg Clayton91a9b2472013-12-04 19:19:12 +00003655
3656 if (error.Success ())
3657 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003658 else
Greg Clayton91a9b2472013-12-04 19:19:12 +00003659 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003660
3661 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytonc6c420f2016-08-12 16:46:18 +00003662 {
3663#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3664 // Our process spawned correctly, we can now set our connection to use our
3665 // end of the socket pair
3666 m_gdb_comm.SetConnection(new ConnectionFileDescriptor(our_socket.release(), true));
3667#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003668 StartAsyncThread ();
Greg Claytonc6c420f2016-08-12 16:46:18 +00003669 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00003670
Greg Clayton91a9b2472013-12-04 19:19:12 +00003671 if (error.Fail())
3672 {
3673 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
3674
3675 if (log)
3676 log->Printf("failed to start debugserver process: %s", error.AsCString());
3677 return error;
3678 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00003679
Greg Clayton00fe87b2013-12-05 22:58:22 +00003680 if (m_gdb_comm.IsConnected())
3681 {
3682 // Finish the connection process by doing the handshake without connecting (send NULL URL)
Greg Claytonc6c420f2016-08-12 16:46:18 +00003683 ConnectToDebugserver(NULL);
Greg Clayton00fe87b2013-12-05 22:58:22 +00003684 }
3685 else
3686 {
Greg Claytonc6c420f2016-08-12 16:46:18 +00003687 error.SetErrorString("connection failed");
Greg Clayton00fe87b2013-12-05 22:58:22 +00003688 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00003689
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003690 }
3691 return error;
3692}
3693
3694bool
Pavel Labath194357c2016-05-12 11:10:01 +00003695ProcessGDBRemote::MonitorDebugserverProcess(std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid,
Pavel Labath998bdc52016-05-11 16:59:04 +00003696 bool exited, // True if the process did exit
3697 int signo, // Zero for no signal
3698 int exit_status // Exit value of process if signal is zero
3699 )
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003700{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003701 // "debugserver_pid" argument passed in is the process ID for
3702 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00003703 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Pavel Labath194357c2016-05-12 11:10:01 +00003704 const bool handled = true;
Greg Claytone4e45922011-11-16 05:37:56 +00003705
Greg Clayton6779606a2011-01-22 23:43:18 +00003706 if (log)
Pavel Labath194357c2016-05-12 11:10:01 +00003707 log->Printf("ProcessGDBRemote::%s(process_wp, pid=%" PRIu64 ", signo=%i (0x%x), exit_status=%i)", __FUNCTION__,
3708 debugserver_pid, signo, signo, exit_status);
Greg Clayton6779606a2011-01-22 23:43:18 +00003709
Pavel Labath194357c2016-05-12 11:10:01 +00003710 std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
3711 if (log)
Saleem Abdulrasoolabdfc212016-05-15 18:18:13 +00003712 log->Printf("ProcessGDBRemote::%s(process = %p)", __FUNCTION__, static_cast<void *>(process_sp.get()));
Pavel Labath194357c2016-05-12 11:10:01 +00003713 if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
3714 return handled;
3715
3716 // Sleep for a half a second to make sure our inferior process has
3717 // time to set its exit status before we set it incorrectly when
3718 // both the debugserver and the inferior process shut down.
3719 usleep(500000);
3720 // If our process hasn't yet exited, debugserver might have died.
3721 // If the process did exit, then we are reaping it.
3722 const StateType state = process_sp->GetState();
3723
3724 if (state != eStateInvalid && state != eStateUnloaded && state != eStateExited && state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003725 {
Pavel Labath194357c2016-05-12 11:10:01 +00003726 char error_str[1024];
3727 if (signo)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003728 {
Pavel Labath194357c2016-05-12 11:10:01 +00003729 const char *signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
3730 if (signal_cstr)
3731 ::snprintf(error_str, sizeof(error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3732 else
3733 ::snprintf(error_str, sizeof(error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003734 }
Pavel Labath194357c2016-05-12 11:10:01 +00003735 else
3736 {
3737 ::snprintf(error_str, sizeof(error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x",
3738 exit_status);
3739 }
3740
3741 process_sp->SetExitStatus(-1, error_str);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003742 }
Pavel Labath194357c2016-05-12 11:10:01 +00003743 // Debugserver has exited we need to let our ProcessGDBRemote
3744 // know that it no longer has a debugserver instance
3745 process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3746 return handled;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003747}
3748
3749void
3750ProcessGDBRemote::KillDebugserverProcess ()
3751{
Greg Claytonfbb76342013-11-20 21:07:01 +00003752 m_gdb_comm.Disconnect();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003753 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3754 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003755 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003756 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3757 }
3758}
3759
3760void
3761ProcessGDBRemote::Initialize()
3762{
Davide Italianoc8d69822015-04-03 04:24:32 +00003763 static std::once_flag g_once_flag;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003764
Davide Italianoc8d69822015-04-03 04:24:32 +00003765 std::call_once(g_once_flag, []()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003766 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003767 PluginManager::RegisterPlugin (GetPluginNameStatic(),
3768 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00003769 CreateInstance,
3770 DebuggerInitialize);
Davide Italianoc8d69822015-04-03 04:24:32 +00003771 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003772}
3773
Greg Clayton7f982402013-07-15 22:54:20 +00003774void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003775ProcessGDBRemote::DebuggerInitialize (Debugger &debugger)
Greg Clayton7f982402013-07-15 22:54:20 +00003776{
3777 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
3778 {
3779 const bool is_global_setting = true;
3780 PluginManager::CreateSettingForProcessPlugin (debugger,
3781 GetGlobalPluginProperties()->GetValueProperties(),
3782 ConstString ("Properties for the gdb-remote process plug-in."),
3783 is_global_setting);
3784 }
3785}
3786
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003787bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003788ProcessGDBRemote::StartAsyncThread ()
3789{
Greg Clayton5160ce52013-03-27 23:08:40 +00003790 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003791
3792 if (log)
3793 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Ed Maste81b4c5f2016-01-04 01:43:47 +00003794
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +00003795 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003796 if (!m_async_thread.IsJoinable())
Jim Ingham455fa5c2012-11-01 01:15:33 +00003797 {
3798 // Create a thread that watches our internal state and controls which
3799 // events make it to clients (into the DCProcess event queue).
Zachary Turner39de3112014-09-09 20:54:56 +00003800
3801 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003802 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003803 else if (log)
3804 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was already running.", __FUNCTION__);
Zachary Turner39de3112014-09-09 20:54:56 +00003805
Zachary Turneracee96a2014-09-23 18:32:09 +00003806 return m_async_thread.IsJoinable();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003807}
3808
3809void
3810ProcessGDBRemote::StopAsyncThread ()
3811{
Greg Clayton5160ce52013-03-27 23:08:40 +00003812 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003813
3814 if (log)
3815 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
3816
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +00003817 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003818 if (m_async_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003819 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00003820 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
Ed Maste81b4c5f2016-01-04 01:43:47 +00003821
Jim Ingham455fa5c2012-11-01 01:15:33 +00003822 // This will shut down the async thread.
3823 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3824
3825 // Stop the stdio thread
Zachary Turner39de3112014-09-09 20:54:56 +00003826 m_async_thread.Join(nullptr);
Pavel Labatha55a9532015-03-11 09:53:42 +00003827 m_async_thread.Reset();
Jim Ingham455fa5c2012-11-01 01:15:33 +00003828 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003829 else if (log)
3830 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003831}
3832
Ewan Crawford76df2882015-06-23 12:32:06 +00003833bool
3834ProcessGDBRemote::HandleNotifyPacket (StringExtractorGDBRemote &packet)
3835{
3836 // get the packet at a string
3837 const std::string &pkt = packet.GetStringRef();
3838 // skip %stop:
3839 StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
3840
3841 // pass as a thread stop info packet
3842 SetLastStopPacket(stop_info);
3843
3844 // check for more stop reasons
3845 HandleStopReplySequence();
3846
3847 // if the process is stopped then we need to fake a resume
3848 // so that we can stop properly with the new break. This
3849 // is possible due to SetPrivateState() broadcasting the
3850 // state change as a side effect.
3851 if (GetPrivateState() == lldb::StateType::eStateStopped)
3852 {
3853 SetPrivateState(lldb::StateType::eStateRunning);
3854 }
3855
3856 // since we have some stopped packets we can halt the process
3857 SetPrivateState(lldb::StateType::eStateStopped);
3858
3859 return true;
3860}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003861
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003862thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003863ProcessGDBRemote::AsyncThread (void *arg)
3864{
3865 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
3866
Greg Clayton5160ce52013-03-27 23:08:40 +00003867 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003868 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003869 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003870
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003871 EventSP event_sp;
Pavel Labath50556852015-09-03 09:36:22 +00003872 bool done = false;
3873 while (!done)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003874 {
Pavel Labath50556852015-09-03 09:36:22 +00003875 if (log)
3876 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003877 if (process->m_async_listener_sp->WaitForEvent(std::chrono::microseconds(0), event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003878 {
Pavel Labath50556852015-09-03 09:36:22 +00003879 const uint32_t event_type = event_sp->GetType();
3880 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003881 {
3882 if (log)
Pavel Labath50556852015-09-03 09:36:22 +00003883 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
3884
3885 switch (event_type)
3886 {
3887 case eBroadcastBitAsyncContinue:
3888 {
3889 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
3890
3891 if (continue_packet)
3892 {
3893 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
3894 const size_t continue_cstr_len = continue_packet->GetByteSize ();
3895 if (log)
3896 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
3897
3898 if (::strstr (continue_cstr, "vAttach") == NULL)
3899 process->SetPrivateState(eStateRunning);
3900 StringExtractorGDBRemote response;
3901
3902 // If in Non-Stop-Mode
3903 if (process->GetTarget().GetNonStopModeEnabled())
3904 {
3905 // send the vCont packet
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00003906 if (!process->GetGDBRemote().SendvContPacket(
3907 llvm::StringRef(continue_cstr, continue_cstr_len), response))
Pavel Labath50556852015-09-03 09:36:22 +00003908 {
3909 // Something went wrong
3910 done = true;
3911 break;
3912 }
3913 }
3914 // If in All-Stop-Mode
3915 else
3916 {
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00003917 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse(
3918 *process, *process->GetUnixSignals(),
3919 llvm::StringRef(continue_cstr, continue_cstr_len), response);
Pavel Labath50556852015-09-03 09:36:22 +00003920
3921 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
3922 // The thread ID list might be contained within the "response", or the stop reply packet that
3923 // caused the stop. So clear it now before we give the stop reply packet to the process
3924 // using the process->SetLastStopPacket()...
3925 process->ClearThreadIDList ();
3926
3927 switch (stop_state)
3928 {
3929 case eStateStopped:
3930 case eStateCrashed:
3931 case eStateSuspended:
3932 process->SetLastStopPacket (response);
3933 process->SetPrivateState (stop_state);
3934 break;
3935
3936 case eStateExited:
3937 {
3938 process->SetLastStopPacket (response);
3939 process->ClearThreadIDList();
3940 response.SetFilePos(1);
Ed Maste81b4c5f2016-01-04 01:43:47 +00003941
Pavel Labath50556852015-09-03 09:36:22 +00003942 int exit_status = response.GetHexU8();
Pavel Labath50556852015-09-03 09:36:22 +00003943 std::string desc_string;
3944 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';')
3945 {
Zachary Turner54695a32016-08-29 19:58:14 +00003946 llvm::StringRef desc_str;
3947 llvm::StringRef desc_token;
3948 while (response.GetNameColonValue(desc_token, desc_str))
Pavel Labath50556852015-09-03 09:36:22 +00003949 {
Zachary Turner54695a32016-08-29 19:58:14 +00003950 if (desc_token != "description")
3951 continue;
3952 StringExtractor extractor(desc_str);
3953 extractor.GetHexByteString(desc_string);
Pavel Labath50556852015-09-03 09:36:22 +00003954 }
3955 }
Zachary Turner54695a32016-08-29 19:58:14 +00003956 process->SetExitStatus(exit_status, desc_string.c_str());
Pavel Labath50556852015-09-03 09:36:22 +00003957 done = true;
3958 break;
3959 }
3960 case eStateInvalid:
3961 {
3962 // Check to see if we were trying to attach and if we got back
3963 // the "E87" error code from debugserver -- this indicates that
3964 // the process is not debuggable. Return a slightly more helpful
3965 // error message about why the attach failed.
3966 if (::strstr (continue_cstr, "vAttach") != NULL
3967 && response.GetError() == 0x87)
3968 {
3969 process->SetExitStatus(-1, "cannot attach to process due to System Integrity Protection");
3970 }
3971 // E01 code from vAttach means that the attach failed
3972 if (::strstr (continue_cstr, "vAttach") != NULL
3973 && response.GetError() == 0x1)
3974 {
3975 process->SetExitStatus(-1, "unable to attach");
3976 }
3977 else
3978 {
3979 process->SetExitStatus(-1, "lost connection");
3980 }
3981 break;
3982 }
3983
3984 default:
3985 process->SetPrivateState (stop_state);
3986 break;
3987 } // switch(stop_state)
3988 } // else // if in All-stop-mode
3989 } // if (continue_packet)
3990 } // case eBroadcastBitAysncContinue
3991 break;
3992
3993 case eBroadcastBitAsyncThreadShouldExit:
3994 if (log)
3995 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
3996 done = true;
3997 break;
3998
3999 default:
4000 if (log)
4001 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
4002 done = true;
4003 break;
4004 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004005 }
Pavel Labath50556852015-09-03 09:36:22 +00004006 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
4007 {
4008 switch (event_type)
4009 {
4010 case Communication::eBroadcastBitReadThreadDidExit:
4011 process->SetExitStatus (-1, "lost connection");
4012 done = true;
4013 break;
4014
4015 case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify:
4016 {
4017 lldb_private::Event *event = event_sp.get();
4018 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event);
4019 StringExtractorGDBRemote notify((const char*)continue_packet->GetBytes());
4020 // Hand this over to the process to handle
4021 process->HandleNotifyPacket(notify);
4022 break;
4023 }
4024
4025 default:
4026 if (log)
4027 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
4028 done = true;
4029 break;
4030 }
4031 }
4032 }
4033 else
4034 {
4035 if (log)
4036 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
4037 done = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004038 }
4039 }
4040
4041 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004042 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004043
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004044 return NULL;
4045}
4046
Greg Claytone996fd32011-03-08 22:40:15 +00004047//uint32_t
4048//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4049//{
4050// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
4051// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
4052// if (m_local_debugserver)
4053// {
4054// return Host::ListProcessesMatchingName (name, matches, pids);
4055// }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004056// else
Greg Claytone996fd32011-03-08 22:40:15 +00004057// {
4058// // FIXME: Implement talking to the remote debugserver.
4059// return 0;
4060// }
4061//
4062//}
4063//
Jim Ingham1c823b42011-01-22 01:33:44 +00004064bool
4065ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004066 StoppointCallbackContext *context,
Jim Ingham1c823b42011-01-22 01:33:44 +00004067 lldb::user_id_t break_id,
4068 lldb::user_id_t break_loc_id)
4069{
Ed Maste81b4c5f2016-01-04 01:43:47 +00004070 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
Jim Ingham1c823b42011-01-22 01:33:44 +00004071 // run so I can stop it if that's what I want to do.
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004072 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00004073 if (log)
4074 log->Printf("Hit New Thread Notification breakpoint.");
4075 return false;
4076}
4077
Eugene Zelenko0722f082015-10-24 01:28:05 +00004078
Jim Ingham1c823b42011-01-22 01:33:44 +00004079bool
4080ProcessGDBRemote::StartNoticingNewThreads()
4081{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004082 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00004083 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00004084 {
Greg Clayton4116e932012-05-15 02:33:01 +00004085 if (log && log->GetVerbose())
4086 log->Printf("Enabled noticing new thread breakpoint.");
4087 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00004088 }
Greg Clayton4116e932012-05-15 02:33:01 +00004089 else
Jim Ingham1c823b42011-01-22 01:33:44 +00004090 {
Zachary Turner7529df92015-09-01 20:02:29 +00004091 PlatformSP platform_sp (GetTarget().GetPlatform());
Greg Clayton4116e932012-05-15 02:33:01 +00004092 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00004093 {
Zachary Turner7529df92015-09-01 20:02:29 +00004094 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(GetTarget());
Greg Clayton4116e932012-05-15 02:33:01 +00004095 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00004096 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00004097 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00004098 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
4099 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00004100 }
4101 else
4102 {
4103 if (log)
4104 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00004105 }
4106 }
4107 }
Greg Clayton4116e932012-05-15 02:33:01 +00004108 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00004109}
4110
4111bool
4112ProcessGDBRemote::StopNoticingNewThreads()
Ed Maste81b4c5f2016-01-04 01:43:47 +00004113{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004114 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00004115 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00004116 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00004117
4118 if (m_thread_create_bp_sp)
4119 m_thread_create_bp_sp->SetEnabled(false);
4120
Jim Ingham1c823b42011-01-22 01:33:44 +00004121 return true;
4122}
Ed Maste81b4c5f2016-01-04 01:43:47 +00004123
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004124DynamicLoader *
Jason Molenda5e8534e2012-10-03 01:29:34 +00004125ProcessGDBRemote::GetDynamicLoader ()
4126{
4127 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00004128 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00004129 return m_dyld_ap.get();
4130}
Jim Ingham1c823b42011-01-22 01:33:44 +00004131
Jason Molendaa3329782014-03-29 18:54:20 +00004132Error
4133ProcessGDBRemote::SendEventData(const char *data)
4134{
4135 int return_value;
4136 bool was_supported;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004137
Jason Molendaa3329782014-03-29 18:54:20 +00004138 Error error;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004139
Jason Molendaa3329782014-03-29 18:54:20 +00004140 return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported);
4141 if (return_value != 0)
4142 {
4143 if (!was_supported)
4144 error.SetErrorString("Sending events is not supported for this process.");
4145 else
4146 error.SetErrorStringWithFormat("Error sending event data: %d.", return_value);
4147 }
4148 return error;
4149}
4150
Steve Pucci03904ac2014-03-04 23:18:46 +00004151const DataBufferSP
4152ProcessGDBRemote::GetAuxvData()
4153{
4154 DataBufferSP buf;
4155 if (m_gdb_comm.GetQXferAuxvReadSupported())
4156 {
4157 std::string response_string;
4158 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success)
4159 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length()));
4160 }
4161 return buf;
4162}
4163
Jason Molenda705b1802014-06-13 02:37:02 +00004164StructuredData::ObjectSP
4165ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid)
4166{
4167 StructuredData::ObjectSP object_sp;
4168
4169 if (m_gdb_comm.GetThreadExtendedInfoSupported())
4170 {
4171 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4172 SystemRuntime *runtime = GetSystemRuntime();
4173 if (runtime)
4174 {
4175 runtime->AddThreadExtendedInfoPacketHints (args_dict);
4176 }
4177 args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid);
4178
4179 StreamString packet;
4180 packet << "jThreadExtendedInfo:";
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004181 args_dict->Dump (packet, false);
Jason Molenda705b1802014-06-13 02:37:02 +00004182
4183 // FIXME the final character of a JSON dictionary, '}', is the escape
4184 // character in gdb-remote binary mode. lldb currently doesn't escape
4185 // these characters in its packet output -- so we add the quoted version
4186 // of the } character here manually in case we talk to a debugserver which
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004187 // un-escapes the characters at packet read time.
Jason Molenda705b1802014-06-13 02:37:02 +00004188 packet << (char) (0x7d ^ 0x20);
4189
4190 StringExtractorGDBRemote response;
Greg Clayton830c81d2016-04-01 00:41:29 +00004191 response.SetResponseValidatorToJSON();
Jason Molenda705b1802014-06-13 02:37:02 +00004192 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4193 {
4194 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4195 if (response_type == StringExtractorGDBRemote::eResponse)
4196 {
4197 if (!response.Empty())
4198 {
Jason Molenda20ee21b2015-07-10 23:15:22 +00004199 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4200 }
4201 }
4202 }
4203 }
4204 return object_sp;
4205}
4206
4207StructuredData::ObjectSP
4208ProcessGDBRemote::GetLoadedDynamicLibrariesInfos (lldb::addr_t image_list_address, lldb::addr_t image_count)
4209{
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004210
4211 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4212 args_dict->GetAsDictionary()->AddIntegerItem ("image_list_address", image_list_address);
4213 args_dict->GetAsDictionary()->AddIntegerItem ("image_count", image_count);
4214
4215 return GetLoadedDynamicLibrariesInfos_sender (args_dict);
4216}
4217
4218StructuredData::ObjectSP
4219ProcessGDBRemote::GetLoadedDynamicLibrariesInfos ()
4220{
4221 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4222
4223 args_dict->GetAsDictionary()->AddBooleanItem ("fetch_all_solibs", true);
4224
4225 return GetLoadedDynamicLibrariesInfos_sender (args_dict);
4226}
4227
4228StructuredData::ObjectSP
4229ProcessGDBRemote::GetLoadedDynamicLibrariesInfos (const std::vector<lldb::addr_t> &load_addresses)
4230{
4231 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4232 StructuredData::ArraySP addresses(new StructuredData::Array);
4233
4234 for (auto addr : load_addresses)
4235 {
4236 StructuredData::ObjectSP addr_sp (new StructuredData::Integer (addr));
4237 addresses->AddItem (addr_sp);
4238 }
4239
4240 args_dict->GetAsDictionary()->AddItem ("solib_addresses", addresses);
4241
4242 return GetLoadedDynamicLibrariesInfos_sender (args_dict);
4243}
4244
4245StructuredData::ObjectSP
4246ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender (StructuredData::ObjectSP args_dict)
4247{
Jason Molenda20ee21b2015-07-10 23:15:22 +00004248 StructuredData::ObjectSP object_sp;
4249
4250 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported())
4251 {
Jason Molenda1d3b3562015-11-05 23:54:29 +00004252 // Scope for the scoped timeout object
4253 GDBRemoteCommunication::ScopedTimeout timeout (m_gdb_comm, 10);
4254
Jason Molenda20ee21b2015-07-10 23:15:22 +00004255 StreamString packet;
4256 packet << "jGetLoadedDynamicLibrariesInfos:";
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004257 args_dict->Dump (packet, false);
Jason Molenda20ee21b2015-07-10 23:15:22 +00004258
4259 // FIXME the final character of a JSON dictionary, '}', is the escape
4260 // character in gdb-remote binary mode. lldb currently doesn't escape
4261 // these characters in its packet output -- so we add the quoted version
4262 // of the } character here manually in case we talk to a debugserver which
4263 // un-escapes the characters at packet read time.
4264 packet << (char) (0x7d ^ 0x20);
4265
4266 StringExtractorGDBRemote response;
Greg Clayton830c81d2016-04-01 00:41:29 +00004267 response.SetResponseValidatorToJSON();
Jason Molenda20ee21b2015-07-10 23:15:22 +00004268 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4269 {
4270 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4271 if (response_type == StringExtractorGDBRemote::eResponse)
4272 {
4273 if (!response.Empty())
4274 {
Jason Molenda705b1802014-06-13 02:37:02 +00004275 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4276 }
4277 }
4278 }
4279 }
4280 return object_sp;
4281}
4282
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004283
4284
4285
Jason Molenda37397352016-07-22 00:17:55 +00004286StructuredData::ObjectSP
4287ProcessGDBRemote::GetSharedCacheInfo ()
4288{
4289 StructuredData::ObjectSP object_sp;
4290 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4291
4292 if (m_gdb_comm.GetSharedCacheInfoSupported())
4293 {
4294 StreamString packet;
4295 packet << "jGetSharedCacheInfo:";
4296 args_dict->Dump (packet, false);
4297
4298 // FIXME the final character of a JSON dictionary, '}', is the escape
4299 // character in gdb-remote binary mode. lldb currently doesn't escape
4300 // these characters in its packet output -- so we add the quoted version
4301 // of the } character here manually in case we talk to a debugserver which
4302 // un-escapes the characters at packet read time.
4303 packet << (char) (0x7d ^ 0x20);
4304
4305 StringExtractorGDBRemote response;
4306 response.SetResponseValidatorToJSON();
4307 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4308 {
4309 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4310 if (response_type == StringExtractorGDBRemote::eResponse)
4311 {
4312 if (!response.Empty())
4313 {
4314 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4315 }
4316 }
4317 }
4318 }
4319 return object_sp;
4320}
4321
Todd Fiala75930012016-08-19 04:21:48 +00004322Error
4323ProcessGDBRemote::ConfigureStructuredData(const ConstString &type_name,
4324 const StructuredData::ObjectSP
4325 &config_sp)
4326{
4327 return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp);
4328}
Jason Molenda37397352016-07-22 00:17:55 +00004329
Jason Molenda6076bf42014-05-06 04:34:52 +00004330// Establish the largest memory read/write payloads we should use.
4331// If the remote stub has a max packet size, stay under that size.
Ed Maste81b4c5f2016-01-04 01:43:47 +00004332//
4333// If the remote stub's max packet size is crazy large, use a
Jason Molenda6076bf42014-05-06 04:34:52 +00004334// reasonable largeish default.
4335//
4336// If the remote stub doesn't advertise a max packet size, use a
4337// conservative default.
4338
4339void
4340ProcessGDBRemote::GetMaxMemorySize()
4341{
4342 const uint64_t reasonable_largeish_default = 128 * 1024;
4343 const uint64_t conservative_default = 512;
4344
4345 if (m_max_memory_size == 0)
4346 {
4347 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4348 if (stub_max_size != UINT64_MAX && stub_max_size != 0)
4349 {
4350 // Save the stub's claimed maximum packet size
4351 m_remote_stub_max_memory_size = stub_max_size;
4352
4353 // Even if the stub says it can support ginormous packets,
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004354 // don't exceed our reasonable largeish default packet size.
Jason Molenda6076bf42014-05-06 04:34:52 +00004355 if (stub_max_size > reasonable_largeish_default)
4356 {
4357 stub_max_size = reasonable_largeish_default;
4358 }
4359
4360 m_max_memory_size = stub_max_size;
4361 }
4362 else
4363 {
4364 m_max_memory_size = conservative_default;
4365 }
4366 }
4367}
4368
4369void
4370ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max)
4371{
4372 if (user_specified_max != 0)
4373 {
4374 GetMaxMemorySize ();
4375
4376 if (m_remote_stub_max_memory_size != 0)
4377 {
4378 if (m_remote_stub_max_memory_size < user_specified_max)
4379 {
4380 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a packet size too big, go as big
4381 // as the remote stub says we can go.
4382 }
4383 else
4384 {
4385 m_max_memory_size = user_specified_max; // user's packet size is good
4386 }
4387 }
4388 else
4389 {
4390 m_max_memory_size = user_specified_max; // user's packet size is probably fine
4391 }
4392 }
4393}
4394
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004395bool
4396ProcessGDBRemote::GetModuleSpec(const FileSpec& module_file_spec,
4397 const ArchSpec& arch,
4398 ModuleSpec &module_spec)
4399{
4400 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PLATFORM);
4401
4402 if (!m_gdb_comm.GetModuleInfo (module_file_spec, arch, module_spec))
4403 {
4404 if (log)
4405 log->Printf ("ProcessGDBRemote::%s - failed to get module info for %s:%s",
4406 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4407 arch.GetTriple ().getTriple ().c_str ());
4408 return false;
4409 }
4410
4411 if (log)
4412 {
4413 StreamString stream;
4414 module_spec.Dump (stream);
4415 log->Printf ("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4416 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4417 arch.GetTriple ().getTriple ().c_str (), stream.GetString ().c_str ());
4418 }
4419
4420 return true;
4421}
4422
Jim Ingham13c30d22015-11-05 22:33:17 +00004423bool
4424ProcessGDBRemote::GetHostOSVersion(uint32_t &major,
4425 uint32_t &minor,
4426 uint32_t &update)
4427{
4428 if (m_gdb_comm.GetOSVersion(major, minor, update))
4429 return true;
4430 // We failed to get the host OS version, defer to the base
4431 // implementation to correctly invalidate the arguments.
4432 return Process::GetHostOSVersion(major, minor, update);
4433}
4434
Colin Rileyc3c95b22015-04-16 15:51:33 +00004435namespace {
4436
4437typedef std::vector<std::string> stringVec;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004438
4439typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004440struct RegisterSetInfo
4441{
4442 ConstString name;
4443};
Colin Rileyc3c95b22015-04-16 15:51:33 +00004444
Greg Claytond04f0ed2015-05-26 18:00:51 +00004445typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004446
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004447struct GdbServerTargetInfo
4448{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004449 std::string arch;
4450 std::string osabi;
4451 stringVec includes;
4452 RegisterSetMap reg_set_map;
4453 XMLNode feature_node;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004454};
Ed Maste81b4c5f2016-01-04 01:43:47 +00004455
Colin Rileyc3c95b22015-04-16 15:51:33 +00004456bool
Francis Ricci55954ae2016-04-25 21:03:55 +00004457ParseRegisters (XMLNode feature_node, GdbServerTargetInfo &target_info, GDBRemoteDynamicRegisterInfo &dyn_reg_info, ABISP abi_sp, uint32_t &cur_reg_num, uint32_t &reg_offset)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004458{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004459 if (!feature_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004460 return false;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004461
Jason Molenda63bd0db2015-09-15 23:20:34 +00004462 feature_node.ForEachChildElementWithName("reg", [&target_info, &dyn_reg_info, &cur_reg_num, &reg_offset, &abi_sp](const XMLNode &reg_node) -> bool {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004463 std::string gdb_group;
4464 std::string gdb_type;
4465 ConstString reg_name;
4466 ConstString alt_name;
4467 ConstString set_name;
4468 std::vector<uint32_t> value_regs;
4469 std::vector<uint32_t> invalidate_regs;
Nitesh Jain52b6cc52016-08-01 13:45:51 +00004470 std::vector<uint8_t> dwarf_opcode_bytes;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004471 bool encoding_set = false;
4472 bool format_set = false;
4473 RegisterInfo reg_info = { NULL, // Name
4474 NULL, // Alt name
4475 0, // byte size
4476 reg_offset, // offset
4477 eEncodingUint, // encoding
Jason Molendabf67a302015-09-01 05:17:01 +00004478 eFormatHex, // format
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004479 {
Jason Molendabf67a302015-09-01 05:17:01 +00004480 LLDB_INVALID_REGNUM, // eh_frame reg num
Greg Claytond04f0ed2015-05-26 18:00:51 +00004481 LLDB_INVALID_REGNUM, // DWARF reg num
4482 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda63bd0db2015-09-15 23:20:34 +00004483 cur_reg_num, // process plugin reg num
4484 cur_reg_num // native register number
Greg Claytond04f0ed2015-05-26 18:00:51 +00004485 },
4486 NULL,
Nitesh Jain52b6cc52016-08-01 13:45:51 +00004487 NULL,
4488 NULL, // Dwarf Expression opcode bytes pointer
4489 0 // Dwarf Expression opcode bytes length
Greg Claytond04f0ed2015-05-26 18:00:51 +00004490 };
Ed Maste81b4c5f2016-01-04 01:43:47 +00004491
Nitesh Jain52b6cc52016-08-01 13:45:51 +00004492 reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type, &reg_name, &alt_name, &set_name, &value_regs, &invalidate_regs, &encoding_set, &format_set, &reg_info, &cur_reg_num, &reg_offset, &dwarf_opcode_bytes](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004493 if (name == "name")
4494 {
4495 reg_name.SetString(value);
4496 }
4497 else if (name == "bitsize")
4498 {
4499 reg_info.byte_size = StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
4500 }
4501 else if (name == "type")
4502 {
4503 gdb_type = value.str();
4504 }
4505 else if (name == "group")
4506 {
4507 gdb_group = value.str();
4508 }
4509 else if (name == "regnum")
4510 {
4511 const uint32_t regnum = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4512 if (regnum != LLDB_INVALID_REGNUM)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004513 {
Jason Molenda63bd0db2015-09-15 23:20:34 +00004514 reg_info.kinds[eRegisterKindProcessPlugin] = regnum;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004515 }
4516 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004517 else if (name == "offset")
4518 {
4519 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4520 }
4521 else if (name == "altname")
4522 {
4523 alt_name.SetString(value);
4524 }
4525 else if (name == "encoding")
4526 {
4527 encoding_set = true;
4528 reg_info.encoding = Args::StringToEncoding (value.data(), eEncodingUint);
4529 }
4530 else if (name == "format")
4531 {
4532 format_set = true;
4533 Format format = eFormatInvalid;
4534 if (Args::StringToFormat (value.data(), format, NULL).Success())
4535 reg_info.format = format;
4536 else if (value == "vector-sint8")
4537 reg_info.format = eFormatVectorOfSInt8;
4538 else if (value == "vector-uint8")
4539 reg_info.format = eFormatVectorOfUInt8;
4540 else if (value == "vector-sint16")
4541 reg_info.format = eFormatVectorOfSInt16;
4542 else if (value == "vector-uint16")
4543 reg_info.format = eFormatVectorOfUInt16;
4544 else if (value == "vector-sint32")
4545 reg_info.format = eFormatVectorOfSInt32;
4546 else if (value == "vector-uint32")
4547 reg_info.format = eFormatVectorOfUInt32;
4548 else if (value == "vector-float32")
4549 reg_info.format = eFormatVectorOfFloat32;
4550 else if (value == "vector-uint128")
4551 reg_info.format = eFormatVectorOfUInt128;
4552 }
4553 else if (name == "group_id")
4554 {
4555 const uint32_t set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4556 RegisterSetMap::const_iterator pos = target_info.reg_set_map.find(set_id);
4557 if (pos != target_info.reg_set_map.end())
4558 set_name = pos->second.name;
4559 }
Jason Molendaa18f7072015-08-15 01:21:01 +00004560 else if (name == "gcc_regnum" || name == "ehframe_regnum")
Greg Claytond04f0ed2015-05-26 18:00:51 +00004561 {
Jason Molendaa18f7072015-08-15 01:21:01 +00004562 reg_info.kinds[eRegisterKindEHFrame] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004563 }
4564 else if (name == "dwarf_regnum")
4565 {
4566 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4567 }
4568 else if (name == "generic")
4569 {
4570 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister(value.data());
4571 }
4572 else if (name == "value_regnums")
4573 {
4574 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
4575 }
4576 else if (name == "invalidate_regnums")
4577 {
4578 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
4579 }
Nitesh Jain52b6cc52016-08-01 13:45:51 +00004580 else if (name == "dynamic_size_dwarf_expr_bytes")
4581 {
4582 StringExtractor opcode_extractor;
4583 std::string opcode_string = value.str ();
4584 size_t dwarf_opcode_len = opcode_string.length () / 2;
4585 assert (dwarf_opcode_len > 0);
4586
4587 dwarf_opcode_bytes.resize (dwarf_opcode_len);
4588 reg_info.dynamic_size_dwarf_len = dwarf_opcode_len;
4589 opcode_extractor.GetStringRef ().swap (opcode_string);
4590 uint32_t ret_val = opcode_extractor.GetHexBytesAvail (dwarf_opcode_bytes.data (),
4591 dwarf_opcode_len);
4592 assert (dwarf_opcode_len == ret_val);
4593
4594 reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data ();
4595 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004596 else
4597 {
4598 printf("unhandled attribute %s = %s\n", name.data(), value.data());
4599 }
4600 return true; // Keep iterating through all attributes
4601 });
Ed Maste81b4c5f2016-01-04 01:43:47 +00004602
Greg Claytond04f0ed2015-05-26 18:00:51 +00004603 if (!gdb_type.empty() && !(encoding_set || format_set))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004604 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004605 if (gdb_type.find("int") == 0)
4606 {
4607 reg_info.format = eFormatHex;
4608 reg_info.encoding = eEncodingUint;
4609 }
4610 else if (gdb_type == "data_ptr" || gdb_type == "code_ptr")
4611 {
4612 reg_info.format = eFormatAddressInfo;
4613 reg_info.encoding = eEncodingUint;
4614 }
4615 else if (gdb_type == "i387_ext" || gdb_type == "float")
4616 {
4617 reg_info.format = eFormatFloat;
4618 reg_info.encoding = eEncodingIEEE754;
4619 }
Colin Rileyc3c95b22015-04-16 15:51:33 +00004620 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004621
Greg Claytond04f0ed2015-05-26 18:00:51 +00004622 // Only update the register set name if we didn't get a "reg_set" attribute.
4623 // "set_name" will be empty if we didn't have a "reg_set" attribute.
4624 if (!set_name && !gdb_group.empty())
4625 set_name.SetCString(gdb_group.c_str());
Ed Maste81b4c5f2016-01-04 01:43:47 +00004626
Greg Claytond04f0ed2015-05-26 18:00:51 +00004627 reg_info.byte_offset = reg_offset;
4628 assert (reg_info.byte_size != 0);
4629 reg_offset += reg_info.byte_size;
4630 if (!value_regs.empty())
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004631 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004632 value_regs.push_back(LLDB_INVALID_REGNUM);
4633 reg_info.value_regs = value_regs.data();
Colin Rileyc3c95b22015-04-16 15:51:33 +00004634 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004635 if (!invalidate_regs.empty())
4636 {
4637 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
4638 reg_info.invalidate_regs = invalidate_regs.data();
4639 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004640
Jason Molenda63bd0db2015-09-15 23:20:34 +00004641 ++cur_reg_num;
Jason Molenda21586c82015-09-09 03:36:24 +00004642 AugmentRegisterInfoViaABI (reg_info, reg_name, abi_sp);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004643 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
Ed Maste81b4c5f2016-01-04 01:43:47 +00004644
Greg Claytond04f0ed2015-05-26 18:00:51 +00004645 return true; // Keep iterating through all "reg" elements
4646 });
Colin Rileyc3c95b22015-04-16 15:51:33 +00004647 return true;
4648}
Ed Maste81b4c5f2016-01-04 01:43:47 +00004649
Eugene Zelenko0722f082015-10-24 01:28:05 +00004650} // namespace {}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004651
Colin Rileyc3c95b22015-04-16 15:51:33 +00004652
4653// query the target of gdb-remote for extended target information
4654// return: 'true' on success
4655// 'false' on failure
4656bool
Jim Ingham7b71c0b2016-02-18 23:58:45 +00004657ProcessGDBRemote::GetGDBServerRegisterInfo (ArchSpec &arch_to_use)
Colin Rileyc3c95b22015-04-16 15:51:33 +00004658{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004659 // Make sure LLDB has an XML parser it can use first
4660 if (!XMLDocument::XMLEnabled())
4661 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004662
4663 // redirect libxml2's error handler since the default prints to stdout
Colin Rileyc3c95b22015-04-16 15:51:33 +00004664
4665 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004666
4667 // check that we have extended feature read support
4668 if ( !comm.GetQXferFeaturesReadSupported( ) )
4669 return false;
4670
4671 // request the target xml file
4672 std::string raw;
4673 lldb_private::Error lldberr;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004674 if (!comm.ReadExtFeature(ConstString("features"),
4675 ConstString("target.xml"),
4676 raw,
4677 lldberr))
4678 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00004679 return false;
4680 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004681
Colin Rileyc3c95b22015-04-16 15:51:33 +00004682
Greg Claytond04f0ed2015-05-26 18:00:51 +00004683 XMLDocument xml_document;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004684
Greg Claytond04f0ed2015-05-26 18:00:51 +00004685 if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml"))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004686 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004687 GdbServerTargetInfo target_info;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004688
Greg Claytond04f0ed2015-05-26 18:00:51 +00004689 XMLNode target_node = xml_document.GetRootElement("target");
4690 if (target_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004691 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004692 XMLNode feature_node;
4693 target_node.ForEachChildElement([&target_info, this, &feature_node](const XMLNode &node) -> bool
4694 {
4695 llvm::StringRef name = node.GetName();
4696 if (name == "architecture")
4697 {
4698 node.GetElementText(target_info.arch);
4699 }
4700 else if (name == "osabi")
4701 {
4702 node.GetElementText(target_info.osabi);
4703 }
Ewan Crawford682e8422015-06-26 09:38:27 +00004704 else if (name == "xi:include" || name == "include")
Greg Claytond04f0ed2015-05-26 18:00:51 +00004705 {
4706 llvm::StringRef href = node.GetAttributeValue("href");
4707 if (!href.empty())
4708 target_info.includes.push_back(href.str());
4709 }
4710 else if (name == "feature")
4711 {
4712 feature_node = node;
4713 }
4714 else if (name == "groups")
4715 {
4716 node.ForEachChildElementWithName("group", [&target_info](const XMLNode &node) -> bool {
4717 uint32_t set_id = UINT32_MAX;
4718 RegisterSetInfo set_info;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004719
Greg Claytond04f0ed2015-05-26 18:00:51 +00004720 node.ForEachAttribute([&set_id, &set_info](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
4721 if (name == "id")
4722 set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4723 if (name == "name")
4724 set_info.name = ConstString(value);
4725 return true; // Keep iterating through all attributes
4726 });
Ed Maste81b4c5f2016-01-04 01:43:47 +00004727
Greg Claytond04f0ed2015-05-26 18:00:51 +00004728 if (set_id != UINT32_MAX)
4729 target_info.reg_set_map[set_id] = set_info;
4730 return true; // Keep iterating through all "group" elements
4731 });
4732 }
4733 return true; // Keep iterating through all children of the target_node
4734 });
Ed Maste81b4c5f2016-01-04 01:43:47 +00004735
Francis Ricci55954ae2016-04-25 21:03:55 +00004736 // Initialize these outside of ParseRegisters, since they should not be reset inside each include feature
4737 uint32_t cur_reg_num = 0;
4738 uint32_t reg_offset = 0;
4739
Jim Ingham7b71c0b2016-02-18 23:58:45 +00004740 // Don't use Process::GetABI, this code gets called from DidAttach, and in that context we haven't
4741 // set the Target's architecture yet, so the ABI is also potentially incorrect.
4742 ABISP abi_to_use_sp = ABI::FindPlugin(arch_to_use);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004743 if (feature_node)
4744 {
Francis Ricci55954ae2016-04-25 21:03:55 +00004745 ParseRegisters(feature_node, target_info, this->m_register_info, abi_to_use_sp, cur_reg_num, reg_offset);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004746 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004747
Greg Claytond04f0ed2015-05-26 18:00:51 +00004748 for (const auto &include : target_info.includes)
4749 {
4750 // request register file
4751 std::string xml_data;
4752 if (!comm.ReadExtFeature(ConstString("features"),
4753 ConstString(include),
4754 xml_data,
4755 lldberr))
4756 continue;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004757
Greg Claytond04f0ed2015-05-26 18:00:51 +00004758 XMLDocument include_xml_document;
4759 include_xml_document.ParseMemory(xml_data.data(), xml_data.size(), include.c_str());
4760 XMLNode include_feature_node = include_xml_document.GetRootElement("feature");
4761 if (include_feature_node)
4762 {
Francis Ricci55954ae2016-04-25 21:03:55 +00004763 ParseRegisters(include_feature_node, target_info, this->m_register_info, abi_to_use_sp, cur_reg_num, reg_offset);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004764 }
4765 }
Jim Ingham7b71c0b2016-02-18 23:58:45 +00004766 this->m_register_info.Finalize(arch_to_use);
Colin Rileyc3c95b22015-04-16 15:51:33 +00004767 }
4768 }
4769
Greg Claytond04f0ed2015-05-26 18:00:51 +00004770 return m_register_info.GetNumRegisters() > 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004771}
4772
Aidan Doddsc0c83852015-05-08 09:36:31 +00004773Error
Stephane Sezer87b0fe02016-01-12 19:02:41 +00004774ProcessGDBRemote::GetLoadedModuleList (LoadedModuleInfoList & list)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004775{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004776 // Make sure LLDB has an XML parser it can use first
4777 if (!XMLDocument::XMLEnabled())
4778 return Error (0, ErrorType::eErrorTypeGeneric);
4779
Aidan Doddsc0c83852015-05-08 09:36:31 +00004780 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS);
4781 if (log)
4782 log->Printf ("ProcessGDBRemote::%s", __FUNCTION__);
4783
Aidan Doddsc0c83852015-05-08 09:36:31 +00004784 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004785
4786 // check that we have extended feature read support
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004787 if (comm.GetQXferLibrariesSVR4ReadSupported ()) {
4788 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004789
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004790 // request the loaded library list
4791 std::string raw;
4792 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004793
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004794 if (!comm.ReadExtFeature (ConstString ("libraries-svr4"), ConstString (""), raw, lldberr))
4795 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004796
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004797 // parse the xml file in memory
4798 if (log)
4799 log->Printf ("parsing: %s", raw.c_str());
4800 XMLDocument doc;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004801
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004802 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4803 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004804
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004805 XMLNode root_element = doc.GetRootElement("library-list-svr4");
4806 if (!root_element)
4807 return Error();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004808
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004809 // main link map structure
4810 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4811 if (!main_lm.empty())
4812 {
4813 list.m_link_map = StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
4814 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004815
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004816 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
Aidan Doddsc0c83852015-05-08 09:36:31 +00004817
Stephane Sezer87b0fe02016-01-12 19:02:41 +00004818 LoadedModuleInfoList::LoadedModuleInfo module;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004819
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004820 library.ForEachAttribute([log, &module](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
Ed Maste81b4c5f2016-01-04 01:43:47 +00004821
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004822 if (name == "name")
4823 module.set_name (value.str());
4824 else if (name == "lm")
4825 {
4826 // the address of the link_map struct.
4827 module.set_link_map(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4828 }
4829 else if (name == "l_addr")
4830 {
4831 // the displacement as read from the field 'l_addr' of the link_map struct.
4832 module.set_base(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
Stephane Sezerc6845a02015-08-20 22:07:48 +00004833 // base address is always a displacement, not an absolute value.
4834 module.set_base_is_offset(true);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004835 }
4836 else if (name == "l_ld")
4837 {
4838 // the memory address of the libraries PT_DYAMIC section.
4839 module.set_dynamic(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4840 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004841
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004842 return true; // Keep iterating over all properties of "library"
4843 });
4844
4845 if (log)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004846 {
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004847 std::string name;
4848 lldb::addr_t lm=0, base=0, ld=0;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004849 bool base_is_offset;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004850
4851 module.get_name (name);
4852 module.get_link_map (lm);
4853 module.get_base (base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004854 module.get_base_is_offset (base_is_offset);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004855 module.get_dynamic (ld);
4856
Stephane Sezerc6845a02015-08-20 22:07:48 +00004857 log->Printf ("found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64 "[%s], ld:0x%08" PRIx64 ", name:'%s')", lm, base, (base_is_offset ? "offset" : "absolute"), ld, name.c_str());
Aidan Doddsc0c83852015-05-08 09:36:31 +00004858 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004859
4860 list.add (module);
4861 return true; // Keep iterating over all "library" elements in the root node
Greg Claytond04f0ed2015-05-26 18:00:51 +00004862 });
Aidan Doddsc0c83852015-05-08 09:36:31 +00004863
4864 if (log)
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004865 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4866 } else if (comm.GetQXferLibrariesReadSupported ()) {
4867 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004868
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004869 // request the loaded library list
4870 std::string raw;
4871 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004872
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004873 if (!comm.ReadExtFeature (ConstString ("libraries"), ConstString (""), raw, lldberr))
4874 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004875
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004876 if (log)
4877 log->Printf ("parsing: %s", raw.c_str());
4878 XMLDocument doc;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004879
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004880 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4881 return Error (0, ErrorType::eErrorTypeGeneric);
4882
4883 XMLNode root_element = doc.GetRootElement("library-list");
4884 if (!root_element)
4885 return Error();
4886
4887 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
Stephane Sezer87b0fe02016-01-12 19:02:41 +00004888 LoadedModuleInfoList::LoadedModuleInfo module;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004889
4890 llvm::StringRef name = library.GetAttributeValue("name");
4891 module.set_name(name.str());
4892
4893 // The base address of a given library will be the address of its
4894 // first section. Most remotes send only one section for Windows
4895 // targets for example.
4896 const XMLNode &section = library.FindFirstChildElementWithName("section");
4897 llvm::StringRef address = section.GetAttributeValue("address");
4898 module.set_base(StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0));
Stephane Sezerc6845a02015-08-20 22:07:48 +00004899 // These addresses are absolute values.
4900 module.set_base_is_offset(false);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004901
4902 if (log)
4903 {
4904 std::string name;
4905 lldb::addr_t base = 0;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004906 bool base_is_offset;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004907 module.get_name (name);
4908 module.get_base (base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004909 module.get_base_is_offset (base_is_offset);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004910
Stephane Sezerc6845a02015-08-20 22:07:48 +00004911 log->Printf ("found (base:0x%08" PRIx64 "[%s], name:'%s')", base, (base_is_offset ? "offset" : "absolute"), name.c_str());
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004912 }
4913
4914 list.add (module);
4915 return true; // Keep iterating over all "library" elements in the root node
4916 });
4917
4918 if (log)
4919 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4920 } else {
4921 return Error (0, ErrorType::eErrorTypeGeneric);
4922 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004923
4924 return Error();
4925}
4926
Aidan Doddsc0c83852015-05-08 09:36:31 +00004927lldb::ModuleSP
Stephane Sezer3553c0e2016-04-05 17:25:32 +00004928ProcessGDBRemote::LoadModuleAtAddress (const FileSpec &file, lldb::addr_t link_map,
4929 lldb::addr_t base_addr, bool value_is_offset)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004930{
Stephane Sezer3553c0e2016-04-05 17:25:32 +00004931 DynamicLoader *loader = GetDynamicLoader();
4932 if (!loader)
4933 return nullptr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004934
Stephane Sezer3553c0e2016-04-05 17:25:32 +00004935 return loader->LoadModuleAtAddress(file, link_map, base_addr, value_is_offset);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004936}
4937
4938size_t
Stephane Sezer87b0fe02016-01-12 19:02:41 +00004939ProcessGDBRemote::LoadModules (LoadedModuleInfoList &module_list)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004940{
4941 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4942
4943 // request a list of loaded libraries from GDBServer
Aidan Doddsc0c83852015-05-08 09:36:31 +00004944 if (GetLoadedModuleList (module_list).Fail())
4945 return 0;
4946
4947 // get a list of all the modules
4948 ModuleList new_modules;
4949
Stephane Sezer87b0fe02016-01-12 19:02:41 +00004950 for (LoadedModuleInfoList::LoadedModuleInfo & modInfo : module_list.m_list)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004951 {
4952 std::string mod_name;
4953 lldb::addr_t mod_base;
Stephane Sezer3553c0e2016-04-05 17:25:32 +00004954 lldb::addr_t link_map;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004955 bool mod_base_is_offset;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004956
4957 bool valid = true;
4958 valid &= modInfo.get_name (mod_name);
4959 valid &= modInfo.get_base (mod_base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004960 valid &= modInfo.get_base_is_offset (mod_base_is_offset);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004961 if (!valid)
4962 continue;
4963
Stephane Sezer3553c0e2016-04-05 17:25:32 +00004964 if (!modInfo.get_link_map (link_map))
4965 link_map = LLDB_INVALID_ADDRESS;
4966
Francis Riccia0300612016-04-27 17:10:15 +00004967 FileSpec file (mod_name.c_str(), true);
Stephane Sezer3553c0e2016-04-05 17:25:32 +00004968 lldb::ModuleSP module_sp = LoadModuleAtAddress (file, link_map, mod_base,
4969 mod_base_is_offset);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004970
4971 if (module_sp.get())
4972 new_modules.Append (module_sp);
4973 }
4974
4975 if (new_modules.GetSize() > 0)
4976 {
Francis Riccibe8cab72016-04-25 21:02:24 +00004977 ModuleList removed_modules;
Zachary Turner7529df92015-09-01 20:02:29 +00004978 Target &target = GetTarget();
Francis Riccibe8cab72016-04-25 21:02:24 +00004979 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4980
4981 for (size_t i = 0; i < loaded_modules.GetSize(); ++i)
4982 {
4983 const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i);
4984
4985 bool found = false;
4986 for (size_t j = 0; j < new_modules.GetSize(); ++j)
4987 {
4988 if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get())
4989 found = true;
4990 }
4991
Francis Ricci80dbd152016-06-06 15:00:50 +00004992 // The main executable will never be included in libraries-svr4, don't remove it
4993 if (!found && loaded_module.get() != target.GetExecutableModulePointer())
Francis Riccibe8cab72016-04-25 21:02:24 +00004994 {
Francis Ricci80dbd152016-06-06 15:00:50 +00004995 removed_modules.Append (loaded_module);
Francis Riccibe8cab72016-04-25 21:02:24 +00004996 }
4997 }
4998
4999 loaded_modules.Remove (removed_modules);
5000 m_process->GetTarget().ModulesDidUnload (removed_modules, false);
Aidan Doddsc0c83852015-05-08 09:36:31 +00005001
5002 new_modules.ForEach ([&target](const lldb::ModuleSP module_sp) -> bool
5003 {
5004 lldb_private::ObjectFile * obj = module_sp->GetObjectFile ();
5005 if (!obj)
5006 return true;
5007
5008 if (obj->GetType () != ObjectFile::Type::eTypeExecutable)
5009 return true;
5010
5011 lldb::ModuleSP module_copy_sp = module_sp;
5012 target.SetExecutableModule (module_copy_sp, false);
5013 return false;
5014 });
5015
Aidan Doddsc0c83852015-05-08 09:36:31 +00005016 loaded_modules.AppendIfNeeded (new_modules);
5017 m_process->GetTarget().ModulesDidLoad (new_modules);
5018 }
5019
5020 return new_modules.GetSize();
Stephane Sezer87b0fe02016-01-12 19:02:41 +00005021}
5022
5023size_t
5024ProcessGDBRemote::LoadModules ()
5025{
5026 LoadedModuleInfoList module_list;
5027 return LoadModules (module_list);
Aidan Doddsc0c83852015-05-08 09:36:31 +00005028}
Colin Rileyc3c95b22015-04-16 15:51:33 +00005029
Tamas Berghammer783bfc82015-06-18 20:43:56 +00005030Error
5031ProcessGDBRemote::GetFileLoadAddress(const FileSpec& file, bool& is_loaded, lldb::addr_t& load_addr)
5032{
5033 is_loaded = false;
5034 load_addr = LLDB_INVALID_ADDRESS;
5035
5036 std::string file_path = file.GetPath(false);
5037 if (file_path.empty ())
5038 return Error("Empty file name specified");
5039
5040 StreamString packet;
5041 packet.PutCString("qFileLoadAddress:");
5042 packet.PutCStringAsRawHex8(file_path.c_str());
5043
5044 StringExtractorGDBRemote response;
5045 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString().c_str(), response, false) != GDBRemoteCommunication::PacketResult::Success)
5046 return Error("Sending qFileLoadAddress packet failed");
5047
5048 if (response.IsErrorResponse())
5049 {
5050 if (response.GetError() == 1)
5051 {
5052 // The file is not loaded into the inferior
5053 is_loaded = false;
5054 load_addr = LLDB_INVALID_ADDRESS;
5055 return Error();
5056 }
5057
5058 return Error("Fetching file load address from remote server returned an error");
5059 }
5060
5061 if (response.IsNormalResponse())
5062 {
5063 is_loaded = true;
5064 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
5065 return Error();
5066 }
5067
5068 return Error("Unknown error happened during sending the load address packet");
5069}
5070
Eugene Zelenko0722f082015-10-24 01:28:05 +00005071
Greg Clayton0b90be12015-06-23 21:27:50 +00005072void
5073ProcessGDBRemote::ModulesDidLoad (ModuleList &module_list)
5074{
5075 // We must call the lldb_private::Process::ModulesDidLoad () first before we do anything
5076 Process::ModulesDidLoad (module_list);
5077
5078 // After loading shared libraries, we can ask our remote GDB server if
5079 // it needs any symbols.
5080 m_gdb_comm.ServeSymbolLookups(this);
5081}
5082
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005083void
5084ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out)
5085{
5086 AppendSTDOUT(out.data(), out.size());
5087}
5088
5089static const char *end_delimiter = "--end--;";
5090static const int end_delimiter_len = 8;
5091
5092void
5093ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data)
5094{
5095 std::string input = data.str(); // '1' to move beyond 'A'
5096 if (m_partial_profile_data.length() > 0)
5097 {
5098 m_partial_profile_data.append(input);
5099 input = m_partial_profile_data;
5100 m_partial_profile_data.clear();
5101 }
5102
5103 size_t found, pos = 0, len = input.length();
5104 while ((found = input.find(end_delimiter, pos)) != std::string::npos)
5105 {
5106 StringExtractorGDBRemote profileDataExtractor(input.substr(pos, found).c_str());
5107 std::string profile_data = HarmonizeThreadIdsForProfileData(profileDataExtractor);
5108 BroadcastAsyncProfileData(profile_data);
5109
5110 pos = found + end_delimiter_len;
5111 }
5112
5113 if (pos < len)
5114 {
5115 // Last incomplete chunk.
5116 m_partial_profile_data = input.substr(pos);
5117 }
5118}
5119
5120std::string
5121ProcessGDBRemote::HarmonizeThreadIdsForProfileData(StringExtractorGDBRemote &profileDataExtractor)
5122{
5123 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
Zachary Turner54695a32016-08-29 19:58:14 +00005124 std::string output;
5125 llvm::raw_string_ostream output_stream(output);
5126 llvm::StringRef name, value;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005127
5128 // Going to assuming thread_used_usec comes first, else bail out.
5129 while (profileDataExtractor.GetNameColonValue(name, value))
5130 {
5131 if (name.compare("thread_used_id") == 0)
5132 {
Zachary Turner54695a32016-08-29 19:58:14 +00005133 StringExtractor threadIDHexExtractor(value);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005134 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
5135
5136 bool has_used_usec = false;
5137 uint32_t curr_used_usec = 0;
Zachary Turner54695a32016-08-29 19:58:14 +00005138 llvm::StringRef usec_name, usec_value;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005139 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
5140 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value))
5141 {
Zachary Turner54695a32016-08-29 19:58:14 +00005142 if (usec_name.equals("thread_used_usec"))
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005143 {
5144 has_used_usec = true;
Zachary Turner54695a32016-08-29 19:58:14 +00005145 usec_value.getAsInteger(0, curr_used_usec);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005146 }
5147 else
5148 {
5149 // We didn't find what we want, it is probably
5150 // an older version. Bail out.
5151 profileDataExtractor.SetFilePos(input_file_pos);
5152 }
5153 }
5154
5155 if (has_used_usec)
5156 {
5157 uint32_t prev_used_usec = 0;
5158 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_used_usec_map.find(thread_id);
5159 if (iterator != m_thread_id_to_used_usec_map.end())
5160 {
5161 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
5162 }
5163
5164 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
5165 // A good first time record is one that runs for at least 0.25 sec
5166 bool good_first_time = (prev_used_usec == 0) && (real_used_usec > 250000);
5167 bool good_subsequent_time =
5168 (prev_used_usec > 0) && ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id)));
5169
5170 if (good_first_time || good_subsequent_time)
5171 {
5172 // We try to avoid doing too many index id reservation,
5173 // resulting in fast increase of index ids.
5174
Zachary Turner54695a32016-08-29 19:58:14 +00005175 output_stream << name << ":";
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005176 int32_t index_id = AssignIndexIDToThread(thread_id);
Zachary Turner54695a32016-08-29 19:58:14 +00005177 output_stream << index_id << ";";
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005178
Zachary Turner54695a32016-08-29 19:58:14 +00005179 output_stream << usec_name << ":" << usec_value << ";";
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005180 }
5181 else
5182 {
5183 // Skip past 'thread_used_name'.
Zachary Turner54695a32016-08-29 19:58:14 +00005184 llvm::StringRef local_name, local_value;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005185 profileDataExtractor.GetNameColonValue(local_name, local_value);
5186 }
5187
5188 // Store current time as previous time so that they can be compared later.
5189 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
5190 }
5191 else
5192 {
5193 // Bail out and use old string.
Zachary Turner54695a32016-08-29 19:58:14 +00005194 output_stream << name << ":" << value << ";";
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005195 }
5196 }
5197 else
5198 {
Zachary Turner54695a32016-08-29 19:58:14 +00005199 output_stream << name << ":" << value << ";";
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005200 }
5201 }
Zachary Turner54695a32016-08-29 19:58:14 +00005202 output_stream << end_delimiter;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005203 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
5204
Zachary Turner54695a32016-08-29 19:58:14 +00005205 return output_stream.str();
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005206}
5207
5208void
5209ProcessGDBRemote::HandleStopReply()
5210{
5211 if (GetStopID() != 0)
5212 return;
5213
5214 if (GetID() == LLDB_INVALID_PROCESS_ID)
5215 {
5216 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
5217 if (pid != LLDB_INVALID_PROCESS_ID)
5218 SetID(pid);
5219 }
5220 BuildDynamicRegisterInfo(true);
5221}
Eugene Zelenko0722f082015-10-24 01:28:05 +00005222
Todd Fiala75930012016-08-19 04:21:48 +00005223bool
5224ProcessGDBRemote::HandleAsyncStructuredData(const StructuredData::ObjectSP
5225 &object_sp)
5226{
5227 return RouteAsyncStructuredData(object_sp);
5228}
5229
Greg Claytone034a042015-05-21 20:52:06 +00005230class CommandObjectProcessGDBRemoteSpeedTest: public CommandObjectParsed
5231{
5232public:
5233 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter) :
5234 CommandObjectParsed (interpreter,
5235 "process plugin packet speed-test",
5236 "Tests packet speeds of various sizes to determine the performance characteristics of the GDB remote connection. ",
5237 NULL),
Todd Fialae1cfbc72016-08-11 23:51:28 +00005238 m_option_group (),
Greg Claytone034a042015-05-21 20:52:06 +00005239 m_num_packets (LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount, "The number of packets to send of each varying size (default is 1000).", 1000),
5240 m_max_send (LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount, "The maximum number of bytes to send in a packet. Sizes increase in powers of 2 while the size is less than or equal to this option value. (default 1024).", 1024),
5241 m_max_recv (LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount, "The maximum number of bytes to receive in a packet. Sizes increase in powers of 2 while the size is less than or equal to this option value. (default 1024).", 1024),
5242 m_json (LLDB_OPT_SET_1, false, "json", 'j', "Print the output as JSON data for easy parsing.", false, true)
5243 {
5244 m_option_group.Append (&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5245 m_option_group.Append (&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5246 m_option_group.Append (&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5247 m_option_group.Append (&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5248 m_option_group.Finalize();
5249 }
5250
Eugene Zelenko0722f082015-10-24 01:28:05 +00005251 ~CommandObjectProcessGDBRemoteSpeedTest ()
5252 {
5253 }
5254
Greg Claytone034a042015-05-21 20:52:06 +00005255
5256 Options *
5257 GetOptions () override
5258 {
5259 return &m_option_group;
5260 }
5261
5262 bool
5263 DoExecute (Args& command, CommandReturnObject &result) override
5264 {
5265 const size_t argc = command.GetArgumentCount();
5266 if (argc == 0)
5267 {
5268 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5269 if (process)
5270 {
5271 StreamSP output_stream_sp (m_interpreter.GetDebugger().GetAsyncOutputStream());
5272 result.SetImmediateOutputStream (output_stream_sp);
5273
5274 const uint32_t num_packets = (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
5275 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
5276 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
5277 const bool json = m_json.GetOptionValue().GetCurrentValue();
5278 if (output_stream_sp)
5279 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, *output_stream_sp);
5280 else
5281 {
5282 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, result.GetOutputStream());
5283 }
5284 result.SetStatus (eReturnStatusSuccessFinishResult);
5285 return true;
5286 }
5287 }
5288 else
5289 {
5290 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
5291 }
5292 result.SetStatus (eReturnStatusFailed);
5293 return false;
5294 }
5295protected:
5296 OptionGroupOptions m_option_group;
5297 OptionGroupUInt64 m_num_packets;
5298 OptionGroupUInt64 m_max_send;
5299 OptionGroupUInt64 m_max_recv;
5300 OptionGroupBoolean m_json;
Eugene Zelenko0722f082015-10-24 01:28:05 +00005301
Greg Claytone034a042015-05-21 20:52:06 +00005302};
5303
Greg Clayton02686b82012-10-15 22:42:16 +00005304class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00005305{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005306private:
Ed Maste81b4c5f2016-01-04 01:43:47 +00005307
Greg Clayton998255b2012-10-13 02:07:45 +00005308public:
Greg Clayton02686b82012-10-15 22:42:16 +00005309 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00005310 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00005311 "process plugin packet history",
5312 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00005313 NULL)
5314 {
5315 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005316
Eugene Zelenko0722f082015-10-24 01:28:05 +00005317 ~CommandObjectProcessGDBRemotePacketHistory ()
5318 {
5319 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005320
Greg Clayton998255b2012-10-13 02:07:45 +00005321 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005322 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton998255b2012-10-13 02:07:45 +00005323 {
Greg Clayton02686b82012-10-15 22:42:16 +00005324 const size_t argc = command.GetArgumentCount();
5325 if (argc == 0)
5326 {
5327 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5328 if (process)
5329 {
5330 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
5331 result.SetStatus (eReturnStatusSuccessFinishResult);
5332 return true;
5333 }
5334 }
5335 else
5336 {
5337 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
5338 }
5339 result.SetStatus (eReturnStatusFailed);
5340 return false;
5341 }
5342};
5343
Jason Molenda6076bf42014-05-06 04:34:52 +00005344class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed
5345{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005346private:
Ed Maste81b4c5f2016-01-04 01:43:47 +00005347
Jason Molenda6076bf42014-05-06 04:34:52 +00005348public:
5349 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) :
5350 CommandObjectParsed (interpreter,
5351 "process plugin packet xfer-size",
5352 "Maximum size that lldb will try to read/write one one chunk.",
5353 NULL)
5354 {
5355 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005356
Eugene Zelenko0722f082015-10-24 01:28:05 +00005357 ~CommandObjectProcessGDBRemotePacketXferSize ()
5358 {
5359 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005360
Jason Molenda6076bf42014-05-06 04:34:52 +00005361 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005362 DoExecute (Args& command, CommandReturnObject &result) override
Jason Molenda6076bf42014-05-06 04:34:52 +00005363 {
5364 const size_t argc = command.GetArgumentCount();
5365 if (argc == 0)
5366 {
5367 result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str());
5368 result.SetStatus (eReturnStatusFailed);
5369 return false;
5370 }
5371
5372 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5373 if (process)
5374 {
5375 const char *packet_size = command.GetArgumentAtIndex(0);
5376 errno = 0;
5377 uint64_t user_specified_max = strtoul (packet_size, NULL, 10);
5378 if (errno == 0 && user_specified_max != 0)
5379 {
5380 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max);
5381 result.SetStatus (eReturnStatusSuccessFinishResult);
5382 return true;
5383 }
5384 }
5385 result.SetStatus (eReturnStatusFailed);
5386 return false;
5387 }
5388};
5389
Eugene Zelenko0722f082015-10-24 01:28:05 +00005390
Greg Clayton02686b82012-10-15 22:42:16 +00005391class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
5392{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005393private:
Ed Maste81b4c5f2016-01-04 01:43:47 +00005394
Greg Clayton02686b82012-10-15 22:42:16 +00005395public:
5396 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
5397 CommandObjectParsed (interpreter,
5398 "process plugin packet send",
5399 "Send a custom packet through the GDB remote protocol and print the answer. "
5400 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
5401 NULL)
5402 {
5403 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005404
Eugene Zelenko0722f082015-10-24 01:28:05 +00005405 ~CommandObjectProcessGDBRemotePacketSend ()
5406 {
5407 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005408
Greg Clayton02686b82012-10-15 22:42:16 +00005409 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005410 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton02686b82012-10-15 22:42:16 +00005411 {
5412 const size_t argc = command.GetArgumentCount();
5413 if (argc == 0)
5414 {
5415 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
5416 result.SetStatus (eReturnStatusFailed);
5417 return false;
5418 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005419
Greg Clayton02686b82012-10-15 22:42:16 +00005420 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5421 if (process)
5422 {
Han Ming Ong84145852012-11-26 20:42:03 +00005423 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00005424 {
Han Ming Ong84145852012-11-26 20:42:03 +00005425 const char *packet_cstr = command.GetArgumentAtIndex(0);
5426 bool send_async = true;
5427 StringExtractorGDBRemote response;
5428 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
5429 result.SetStatus (eReturnStatusSuccessFinishResult);
5430 Stream &output_strm = result.GetOutputStream();
5431 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00005432 std::string &response_str = response.GetStringRef();
Ed Maste81b4c5f2016-01-04 01:43:47 +00005433
Han Ming Ong399289e2013-06-21 19:56:59 +00005434 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00005435 {
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005436 response_str = process->HarmonizeThreadIdsForProfileData(response);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00005437 }
5438
Han Ming Ong84145852012-11-26 20:42:03 +00005439 if (response_str.empty())
5440 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
5441 else
5442 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00005443 }
Greg Clayton02686b82012-10-15 22:42:16 +00005444 }
Greg Clayton998255b2012-10-13 02:07:45 +00005445 return true;
5446 }
5447};
5448
Greg Claytonba4a0a52013-02-01 23:03:47 +00005449class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
5450{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005451private:
Ed Maste81b4c5f2016-01-04 01:43:47 +00005452
Greg Claytonba4a0a52013-02-01 23:03:47 +00005453public:
5454 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
5455 CommandObjectRaw (interpreter,
5456 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00005457 "Send a qRcmd packet through the GDB remote protocol and print the response."
5458 "The argument passed to this command will be hex encoded into a valid 'qRcmd' packet, sent and the response will be printed.",
Greg Claytonba4a0a52013-02-01 23:03:47 +00005459 NULL)
5460 {
5461 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005462
Eugene Zelenko0722f082015-10-24 01:28:05 +00005463 ~CommandObjectProcessGDBRemotePacketMonitor ()
5464 {
5465 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005466
Greg Claytonba4a0a52013-02-01 23:03:47 +00005467 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005468 DoExecute (const char *command, CommandReturnObject &result) override
Greg Claytonba4a0a52013-02-01 23:03:47 +00005469 {
5470 if (command == NULL || command[0] == '\0')
5471 {
5472 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
5473 result.SetStatus (eReturnStatusFailed);
5474 return false;
5475 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005476
Greg Claytonba4a0a52013-02-01 23:03:47 +00005477 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5478 if (process)
5479 {
5480 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00005481 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00005482 packet.PutBytesAsRawHex8(command, strlen(command));
5483 const char *packet_cstr = packet.GetString().c_str();
Ed Maste81b4c5f2016-01-04 01:43:47 +00005484
Greg Claytonba4a0a52013-02-01 23:03:47 +00005485 bool send_async = true;
5486 StringExtractorGDBRemote response;
5487 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
5488 result.SetStatus (eReturnStatusSuccessFinishResult);
5489 Stream &output_strm = result.GetOutputStream();
5490 output_strm.Printf (" packet: %s\n", packet_cstr);
5491 const std::string &response_str = response.GetStringRef();
Ed Maste81b4c5f2016-01-04 01:43:47 +00005492
Greg Claytonba4a0a52013-02-01 23:03:47 +00005493 if (response_str.empty())
5494 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
5495 else
5496 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
5497 }
5498 return true;
5499 }
5500};
5501
Greg Clayton02686b82012-10-15 22:42:16 +00005502class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
5503{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005504private:
Ed Maste81b4c5f2016-01-04 01:43:47 +00005505
Greg Clayton02686b82012-10-15 22:42:16 +00005506public:
5507 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
5508 CommandObjectMultiword (interpreter,
5509 "process plugin packet",
5510 "Commands that deal with GDB remote packets.",
5511 NULL)
5512 {
5513 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
5514 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00005515 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Jason Molenda6076bf42014-05-06 04:34:52 +00005516 LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter)));
Greg Claytone034a042015-05-21 20:52:06 +00005517 LoadSubCommand ("speed-test", CommandObjectSP (new CommandObjectProcessGDBRemoteSpeedTest (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00005518 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005519
Eugene Zelenko0722f082015-10-24 01:28:05 +00005520 ~CommandObjectProcessGDBRemotePacket ()
5521 {
Ed Maste81b4c5f2016-01-04 01:43:47 +00005522 }
Greg Clayton02686b82012-10-15 22:42:16 +00005523};
Greg Clayton998255b2012-10-13 02:07:45 +00005524
5525class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
5526{
5527public:
Kate Stone7428a182016-07-14 22:03:10 +00005528 CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter)
5529 : CommandObjectMultiword(interpreter, "process plugin", "Commands for operating on a ProcessGDBRemote process.",
5530 "process plugin <subcommand> [<subcommand-options>]")
Greg Clayton998255b2012-10-13 02:07:45 +00005531 {
5532 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
5533 }
5534
Eugene Zelenko0722f082015-10-24 01:28:05 +00005535 ~CommandObjectMultiwordProcessGDBRemote ()
5536 {
5537 }
Greg Clayton998255b2012-10-13 02:07:45 +00005538};
5539
Greg Clayton998255b2012-10-13 02:07:45 +00005540CommandObject *
5541ProcessGDBRemote::GetPluginCommandObject()
5542{
5543 if (!m_command_sp)
5544 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
5545 return m_command_sp.get();
5546}