blob: 3f7b64c82216432986e072ec378839c2f7c00aef [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);
Zachary Turnerd08f09c2016-08-30 18:12:11 +0000652 uint32_t ret_val = opcode_extractor.GetHexBytesAvail(dwarf_opcode_bytes);
Zachary Turner54695a32016-08-29 19:58:14 +0000653 assert(dwarf_opcode_len == ret_val);
Nitesh Jain52b6cc52016-08-01 13:45:51 +0000654
Zachary Turner54695a32016-08-29 19:58:14 +0000655 reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data();
Nitesh Jain52b6cc52016-08-01 13:45:51 +0000656 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000657 }
658
Jason Molenda743e86a2010-06-11 23:44:18 +0000659 reg_info.byte_offset = reg_offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000660 assert (reg_info.byte_size != 0);
661 reg_offset += reg_info.byte_size;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000662 if (!value_regs.empty())
663 {
664 value_regs.push_back(LLDB_INVALID_REGNUM);
665 reg_info.value_regs = value_regs.data();
666 }
667 if (!invalidate_regs.empty())
668 {
669 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
670 reg_info.invalidate_regs = invalidate_regs.data();
671 }
672
Jim Ingham7b71c0b2016-02-18 23:58:45 +0000673 // We have to make a temporary ABI here, and not use the GetABI because this code
674 // gets called in DidAttach, when the target architecture (and consequently the ABI we'll get from
675 // the process) may be wrong.
676 ABISP abi_to_use = ABI::FindPlugin(arch_to_use);
677
678 AugmentRegisterInfoViaABI (reg_info, reg_name, abi_to_use);
Jason Molenda21586c82015-09-09 03:36:24 +0000679
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000680 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
681 }
Todd Fiala1a634402014-01-08 07:52:40 +0000682 else
683 {
684 break; // ensure exit before reg_num is incremented
685 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000686 }
687 else
688 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000689 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000690 }
691 }
692
Greg Claytond04f0ed2015-05-26 18:00:51 +0000693 if (m_register_info.GetNumRegisters() > 0)
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000694 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000695 m_register_info.Finalize(GetTarget().GetArchitecture());
696 return;
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000697 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000698
Johnny Chen2fa9de12012-05-14 18:44:23 +0000699 // We didn't get anything if the accumulated reg_num is zero. See if we are
700 // debugging ARM and fill with a hard coded register set until we can get an
701 // updated debugserver down on the devices.
702 // On the other hand, if the accumulated reg_num is positive, see if we can
703 // add composite registers to the existing primordial ones.
Greg Claytond04f0ed2015-05-26 18:00:51 +0000704 bool from_scratch = (m_register_info.GetNumRegisters() == 0);
Johnny Chen2fa9de12012-05-14 18:44:23 +0000705
Johnny Chen2fa9de12012-05-14 18:44:23 +0000706 if (!target_arch.IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000707 {
Jim Ingham7b71c0b2016-02-18 23:58:45 +0000708 if (arch_to_use.IsValid()
709 && (arch_to_use.GetMachine() == llvm::Triple::arm || arch_to_use.GetMachine() == llvm::Triple::thumb)
710 && arch_to_use.GetTriple().getVendor() == llvm::Triple::Apple)
Johnny Chen2fa9de12012-05-14 18:44:23 +0000711 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000712 }
Jason Molenda6d9fe8c2015-08-21 00:13:37 +0000713 else if (target_arch.GetMachine() == llvm::Triple::arm
714 || target_arch.GetMachine() == llvm::Triple::thumb)
Johnny Chen2fa9de12012-05-14 18:44:23 +0000715 {
716 m_register_info.HardcodeARMRegisters(from_scratch);
717 }
718
719 // At this point, we can finalize our register info.
Greg Claytond04f0ed2015-05-26 18:00:51 +0000720 m_register_info.Finalize (GetTarget().GetArchitecture());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000721}
722
723Error
724ProcessGDBRemote::WillLaunch (Module* module)
725{
726 return WillLaunchOrAttach ();
727}
728
729Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000730ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000731{
732 return WillLaunchOrAttach ();
733}
734
735Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000736ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000737{
738 return WillLaunchOrAttach ();
739}
740
741Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000742ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +0000743{
Todd Fialaaf245d12014-06-30 21:05:18 +0000744 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Claytonb766a732011-02-04 01:58:07 +0000745 Error error (WillLaunchOrAttach ());
Ed Maste81b4c5f2016-01-04 01:43:47 +0000746
Greg Claytonb766a732011-02-04 01:58:07 +0000747 if (error.Fail())
748 return error;
749
Greg Clayton2289fa42011-04-30 01:09:13 +0000750 error = ConnectToDebugserver (remote_url);
Greg Claytonb766a732011-02-04 01:58:07 +0000751
752 if (error.Fail())
753 return error;
754 StartAsyncThread ();
755
Greg Claytonc574ede2011-03-10 02:26:48 +0000756 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonb766a732011-02-04 01:58:07 +0000757 if (pid == LLDB_INVALID_PROCESS_ID)
758 {
759 // We don't have a valid process ID, so note that we are connected
Ed Maste81b4c5f2016-01-04 01:43:47 +0000760 // and could now request to launch or attach, or get remote process
Greg Claytonb766a732011-02-04 01:58:07 +0000761 // listings...
762 SetPrivateState (eStateConnected);
763 }
764 else
765 {
766 // We have a valid process
767 SetID (pid);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000768 GetThreadList();
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000769 StringExtractorGDBRemote response;
770 if (m_gdb_comm.GetStopReply(response))
Greg Claytonb766a732011-02-04 01:58:07 +0000771 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000772 SetLastStopPacket(response);
Ewan Crawford78baa192015-05-13 09:18:18 +0000773
774 // '?' Packets must be handled differently in non-stop mode
775 if (GetTarget().GetNonStopModeEnabled())
776 HandleStopReplySequence();
777
Zachary Turner7529df92015-09-01 20:02:29 +0000778 Target &target = GetTarget();
Ed Maste81b4c5f2016-01-04 01:43:47 +0000779 if (!target.GetArchitecture().IsValid())
Jason Molendac62bd7b2013-12-21 05:20:36 +0000780 {
781 if (m_gdb_comm.GetProcessArchitecture().IsValid())
782 {
Zachary Turner7529df92015-09-01 20:02:29 +0000783 target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
Jason Molendac62bd7b2013-12-21 05:20:36 +0000784 }
785 else
786 {
Zachary Turner7529df92015-09-01 20:02:29 +0000787 target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molendac62bd7b2013-12-21 05:20:36 +0000788 }
Carlo Kok74389122013-10-14 07:09:13 +0000789 }
790
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000791 const StateType state = SetThreadStopInfo (response);
Greg Clayton2e309072015-07-17 23:42:28 +0000792 if (state != eStateInvalid)
Greg Claytonb766a732011-02-04 01:58:07 +0000793 {
794 SetPrivateState (state);
795 }
796 else
Daniel Malead01b2952012-11-29 21:49:15 +0000797 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 +0000798 }
799 else
Daniel Malead01b2952012-11-29 21:49:15 +0000800 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 +0000801 }
Jason Molenda16d127c2012-05-03 22:37:30 +0000802
Todd Fialaaf245d12014-06-30 21:05:18 +0000803 if (log)
804 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");
805
806
807 if (error.Success()
Jason Molenda16d127c2012-05-03 22:37:30 +0000808 && !GetTarget().GetArchitecture().IsValid()
809 && m_gdb_comm.GetHostArchitecture().IsValid())
810 {
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000811 // Prefer the *process'* architecture over that of the *host*, if available.
812 if (m_gdb_comm.GetProcessArchitecture().IsValid())
813 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
814 else
815 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molenda16d127c2012-05-03 22:37:30 +0000816 }
817
Todd Fialaaf245d12014-06-30 21:05:18 +0000818 if (log)
819 log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": normalized target architecture triple: %s", __FUNCTION__, GetID (), GetTarget ().GetArchitecture ().GetTriple ().getTriple ().c_str ());
820
Chaoren Lin98d0a4b2015-07-14 01:09:28 +0000821 if (error.Success())
Jaydeep Patil6fc590d2015-07-30 05:06:51 +0000822 {
823 PlatformSP platform_sp = GetTarget().GetPlatform();
824 if (platform_sp && platform_sp->IsConnected())
825 SetUnixSignals(platform_sp->GetUnixSignals());
826 else
827 SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
828 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000829
Greg Claytonb766a732011-02-04 01:58:07 +0000830 return error;
831}
832
833Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000834ProcessGDBRemote::WillLaunchOrAttach ()
835{
836 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000837 m_stdio_communication.Clear ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000838 return error;
839}
840
841//----------------------------------------------------------------------
842// Process Control
843//----------------------------------------------------------------------
844Error
Jean-Daniel Dupas7782de92013-12-09 22:52:50 +0000845ProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000846{
Todd Fiala75f47c32014-10-11 21:42:09 +0000847 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton4957bf62010-09-30 21:49:03 +0000848 Error error;
Greg Clayton982c9762011-11-03 21:22:33 +0000849
Todd Fiala75f47c32014-10-11 21:42:09 +0000850 if (log)
851 log->Printf ("ProcessGDBRemote::%s() entered", __FUNCTION__);
852
Greg Clayton982c9762011-11-03 21:22:33 +0000853 uint32_t launch_flags = launch_info.GetFlags().Get();
Chaoren Lind3173f32015-05-29 19:52:29 +0000854 FileSpec stdin_file_spec{};
855 FileSpec stdout_file_spec{};
856 FileSpec stderr_file_spec{};
857 FileSpec working_dir = launch_info.GetWorkingDirectory();
Greg Clayton982c9762011-11-03 21:22:33 +0000858
Zachary Turner696b5282014-08-14 16:01:25 +0000859 const FileAction *file_action;
Greg Clayton982c9762011-11-03 21:22:33 +0000860 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
861 if (file_action)
862 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000863 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000864 stdin_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000865 }
866 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
867 if (file_action)
868 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000869 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000870 stdout_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000871 }
872 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
873 if (file_action)
874 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000875 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000876 stderr_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000877 }
878
Todd Fiala75f47c32014-10-11 21:42:09 +0000879 if (log)
880 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000881 if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
Vince Harron4a8abd32015-02-13 19:15:24 +0000882 log->Printf ("ProcessGDBRemote::%s provided with STDIO paths via launch_info: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000883 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000884 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
885 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
886 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Todd Fiala75f47c32014-10-11 21:42:09 +0000887 else
888 log->Printf ("ProcessGDBRemote::%s no STDIO paths given via launch_info", __FUNCTION__);
889 }
890
Vince Harrondf3f00f2015-02-10 21:09:04 +0000891 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Chaoren Lind3173f32015-05-29 19:52:29 +0000892 if (stdin_file_spec || disable_stdio)
Vince Harrondf3f00f2015-02-10 21:09:04 +0000893 {
894 // the inferior will be reading stdin from the specified file
895 // or stdio is completely disabled
896 m_stdin_forward = false;
897 }
898 else
899 {
900 m_stdin_forward = true;
901 }
902
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000903 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
904 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
905 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000906
Greg Clayton982c9762011-11-03 21:22:33 +0000907 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000908 if (object_file)
909 {
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +0000910 error = EstablishConnectionIfNeeded (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000911 if (error.Success())
912 {
913 lldb_utility::PseudoTerminal pty;
914 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000915
Zachary Turner7529df92015-09-01 20:02:29 +0000916 PlatformSP platform_sp (GetTarget().GetPlatform());
Vince Harrondf3f00f2015-02-10 21:09:04 +0000917 if (disable_stdio)
Greg Clayton71337622011-02-24 22:24:29 +0000918 {
Vince Harrondf3f00f2015-02-10 21:09:04 +0000919 // set to /dev/null unless redirected to a file above
Chaoren Lind3173f32015-05-29 19:52:29 +0000920 if (!stdin_file_spec)
Zachary Turner4eff2d32015-10-14 21:37:36 +0000921 stdin_file_spec.SetFile(FileSystem::DEV_NULL, false);
Chaoren Lind3173f32015-05-29 19:52:29 +0000922 if (!stdout_file_spec)
Zachary Turner4eff2d32015-10-14 21:37:36 +0000923 stdout_file_spec.SetFile(FileSystem::DEV_NULL, false);
Chaoren Lind3173f32015-05-29 19:52:29 +0000924 if (!stderr_file_spec)
Zachary Turner4eff2d32015-10-14 21:37:36 +0000925 stderr_file_spec.SetFile(FileSystem::DEV_NULL, false);
Vince Harrondf3f00f2015-02-10 21:09:04 +0000926 }
927 else if (platform_sp && platform_sp->IsHost())
928 {
929 // If the debugserver is local and we aren't disabling STDIO, lets use
930 // a pseudo terminal to instead of relying on the 'O' packets for stdio
931 // since 'O' packets can really slow down debugging if the inferior
932 // does a lot of output.
Chaoren Lind3173f32015-05-29 19:52:29 +0000933 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
934 pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000935 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000936 FileSpec slave_name{pty.GetSlaveName(NULL, 0), false};
937
938 if (!stdin_file_spec)
939 stdin_file_spec = slave_name;
940
941 if (!stdout_file_spec)
942 stdout_file_spec = slave_name;
943
944 if (!stderr_file_spec)
945 stderr_file_spec = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000946 }
Todd Fiala75f47c32014-10-11 21:42:09 +0000947 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +0000948 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 +0000949 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000950 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
951 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
952 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Greg Clayton71337622011-02-24 22:24:29 +0000953 }
954
Todd Fiala75f47c32014-10-11 21:42:09 +0000955 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +0000956 log->Printf ("ProcessGDBRemote::%s final STDIO paths after all adjustments: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000957 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000958 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
959 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
960 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Todd Fiala75f47c32014-10-11 21:42:09 +0000961
Chaoren Lind3173f32015-05-29 19:52:29 +0000962 if (stdin_file_spec)
963 m_gdb_comm.SetSTDIN(stdin_file_spec);
964 if (stdout_file_spec)
965 m_gdb_comm.SetSTDOUT(stdout_file_spec);
966 if (stderr_file_spec)
967 m_gdb_comm.SetSTDERR(stderr_file_spec);
Greg Clayton71337622011-02-24 22:24:29 +0000968
969 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
Jim Ingham106d0282014-06-25 02:32:56 +0000970 m_gdb_comm.SetDetachOnError (launch_flags & eLaunchFlagDetachOnError);
Greg Clayton71337622011-02-24 22:24:29 +0000971
Zachary Turner7529df92015-09-01 20:02:29 +0000972 m_gdb_comm.SendLaunchArchPacket (GetTarget().GetArchitecture().GetArchitectureName());
Ed Maste81b4c5f2016-01-04 01:43:47 +0000973
Jason Molendaa3329782014-03-29 18:54:20 +0000974 const char * launch_event_data = launch_info.GetLaunchEventData();
975 if (launch_event_data != NULL && *launch_event_data != '\0')
976 m_gdb_comm.SendLaunchEventDataPacket (launch_event_data);
Ed Maste81b4c5f2016-01-04 01:43:47 +0000977
Chaoren Lind3173f32015-05-29 19:52:29 +0000978 if (working_dir)
Greg Clayton71337622011-02-24 22:24:29 +0000979 {
980 m_gdb_comm.SetWorkingDir (working_dir);
981 }
982
983 // Send the environment and the program + arguments after we connect
Greg Clayton982c9762011-11-03 21:22:33 +0000984 const Args &environment = launch_info.GetEnvironmentEntries();
985 if (environment.GetArgumentCount())
Greg Clayton71337622011-02-24 22:24:29 +0000986 {
Greg Clayton982c9762011-11-03 21:22:33 +0000987 size_t num_environment_entries = environment.GetArgumentCount();
988 for (size_t i=0; i<num_environment_entries; ++i)
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000989 {
Greg Clayton982c9762011-11-03 21:22:33 +0000990 const char *env_entry = environment.GetArgumentAtIndex(i);
991 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Clayton71337622011-02-24 22:24:29 +0000992 break;
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000993 }
Greg Clayton71337622011-02-24 22:24:29 +0000994 }
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000995
Greg Clayton71337622011-02-24 22:24:29 +0000996 {
Tamas Berghammer912800c2015-02-24 10:23:39 +0000997 // Scope for the scoped timeout object
998 GDBRemoteCommunication::ScopedTimeout timeout (m_gdb_comm, 10);
999
1000 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
1001 if (arg_packet_err == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001002 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001003 std::string error_str;
1004 if (m_gdb_comm.GetLaunchSuccess (error_str))
1005 {
1006 SetID (m_gdb_comm.GetCurrentProcessID ());
1007 }
1008 else
1009 {
1010 error.SetErrorString (error_str.c_str());
1011 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001012 }
1013 else
1014 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001015 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001016 }
Greg Clayton71337622011-02-24 22:24:29 +00001017 }
Tamas Berghammer912800c2015-02-24 10:23:39 +00001018
Greg Clayton71337622011-02-24 22:24:29 +00001019 if (GetID() == LLDB_INVALID_PROCESS_ID)
1020 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001021 if (log)
1022 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton71337622011-02-24 22:24:29 +00001023 KillDebugserverProcess ();
1024 return error;
1025 }
1026
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001027 StringExtractorGDBRemote response;
1028 if (m_gdb_comm.GetStopReply(response))
Greg Clayton71337622011-02-24 22:24:29 +00001029 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001030 SetLastStopPacket(response);
Ewan Crawford78baa192015-05-13 09:18:18 +00001031 // '?' Packets must be handled differently in non-stop mode
1032 if (GetTarget().GetNonStopModeEnabled())
1033 HandleStopReplySequence();
1034
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001035 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
1036
1037 if (process_arch.IsValid())
Jason Molendac62bd7b2013-12-21 05:20:36 +00001038 {
Zachary Turner7529df92015-09-01 20:02:29 +00001039 GetTarget().MergeArchitecture(process_arch);
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001040 }
1041 else
1042 {
1043 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
1044 if (host_arch.IsValid())
Zachary Turner7529df92015-09-01 20:02:29 +00001045 GetTarget().MergeArchitecture(host_arch);
Carlo Kok74389122013-10-14 07:09:13 +00001046 }
1047
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001048 SetPrivateState (SetThreadStopInfo (response));
Ed Maste81b4c5f2016-01-04 01:43:47 +00001049
Greg Clayton71337622011-02-24 22:24:29 +00001050 if (!disable_stdio)
1051 {
1052 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Claytonee95ed52011-11-17 22:14:31 +00001053 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Clayton71337622011-02-24 22:24:29 +00001054 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001055 }
1056 }
Greg Claytonc235ac72011-08-09 05:20:29 +00001057 else
1058 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001059 if (log)
1060 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytonc235ac72011-08-09 05:20:29 +00001061 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001062 }
1063 else
1064 {
1065 // Set our user ID to an invalid process ID.
1066 SetID(LLDB_INVALID_PROCESS_ID);
Ed Maste81b4c5f2016-01-04 01:43:47 +00001067 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
1068 exe_module->GetFileSpec().GetFilename().AsCString(),
Greg Clayton982c9762011-11-03 21:22:33 +00001069 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001070 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001071 return error;
Eugene Zelenko0722f082015-10-24 01:28:05 +00001072
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001073}
1074
Eugene Zelenko0722f082015-10-24 01:28:05 +00001075
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001076Error
Greg Claytonb766a732011-02-04 01:58:07 +00001077ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001078{
1079 Error error;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001080 // Only connect if we have a valid connect URL
Vince Harron1b5a74e2015-01-21 22:42:49 +00001081 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Ed Maste81b4c5f2016-01-04 01:43:47 +00001082
Greg Clayton00fe87b2013-12-05 22:58:22 +00001083 if (connect_url && connect_url[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001084 {
Vince Harron1b5a74e2015-01-21 22:42:49 +00001085 if (log)
1086 log->Printf("ProcessGDBRemote::%s Connecting to %s", __FUNCTION__, connect_url);
Greg Clayton00fe87b2013-12-05 22:58:22 +00001087 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
1088 if (conn_ap.get())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001089 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001090 const uint32_t max_retry_count = 50;
1091 uint32_t retry_count = 0;
1092 while (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001093 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001094 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
1095 {
1096 m_gdb_comm.SetConnection (conn_ap.release());
1097 break;
1098 }
1099 else if (error.WasInterrupted())
1100 {
1101 // If we were interrupted, don't keep retrying.
1102 break;
1103 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001104
Greg Clayton00fe87b2013-12-05 22:58:22 +00001105 retry_count++;
Ed Maste81b4c5f2016-01-04 01:43:47 +00001106
Greg Clayton00fe87b2013-12-05 22:58:22 +00001107 if (retry_count >= max_retry_count)
1108 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001109
Greg Clayton00fe87b2013-12-05 22:58:22 +00001110 usleep (100000);
1111 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001112 }
1113 }
1114
1115 if (!m_gdb_comm.IsConnected())
1116 {
1117 if (error.Success())
1118 error.SetErrorString("not connected to remote gdb server");
1119 return error;
1120 }
1121
Eugene Zelenko0722f082015-10-24 01:28:05 +00001122
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001123 // Start the communications read thread so all incoming data can be
1124 // parsed into packets and queued as they arrive.
1125 if (GetTarget().GetNonStopModeEnabled())
1126 m_gdb_comm.StartReadThread();
1127
Greg Clayton32e0a752011-03-30 18:16:51 +00001128 // We always seem to be able to open a connection to a local port
1129 // so we need to make sure we can then send data to it. If we can't
1130 // then we aren't actually connected to anything, so try and do the
Ed Maste81b4c5f2016-01-04 01:43:47 +00001131 // handshake with the remote GDB server and make sure that goes
Greg Clayton32e0a752011-03-30 18:16:51 +00001132 // alright.
Greg Claytonfb909312013-11-23 01:58:15 +00001133 if (!m_gdb_comm.HandshakeWithServer (&error))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001134 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001135 m_gdb_comm.Disconnect();
1136 if (error.Success())
1137 error.SetErrorString("not connected to remote gdb server");
1138 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001139 }
Ewan Crawford78baa192015-05-13 09:18:18 +00001140
1141 // Send $QNonStop:1 packet on startup if required
1142 if (GetTarget().GetNonStopModeEnabled())
Ewan Crawfordaa7eda72015-06-24 15:14:26 +00001143 GetTarget().SetNonStopModeEnabled (m_gdb_comm.SetNonStopMode(true));
Ewan Crawford78baa192015-05-13 09:18:18 +00001144
Greg Claytonb30c50c2015-05-29 00:01:55 +00001145 m_gdb_comm.GetEchoSupported ();
Pavel Labath5c95ee42016-08-30 13:56:11 +00001146 m_gdb_comm.GetThreadSuffixSupported ();
Greg Clayton44633992012-04-10 03:22:03 +00001147 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001148 m_gdb_comm.GetHostInfo ();
1149 m_gdb_comm.GetVContSupported ('c');
Jim Inghamcd16df92012-07-20 21:37:13 +00001150 m_gdb_comm.GetVAttachOrWaitSupported();
Ewan Crawford78baa192015-05-13 09:18:18 +00001151
1152 // Ask the remote server for the default thread id
1153 if (GetTarget().GetNonStopModeEnabled())
1154 m_gdb_comm.GetDefaultThreadId(m_initial_tid);
1155
1156
Jim Ingham03afad82012-07-02 05:40:07 +00001157 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1158 for (size_t idx = 0; idx < num_cmds; idx++)
1159 {
1160 StringExtractorGDBRemote response;
Jim Ingham03afad82012-07-02 05:40:07 +00001161 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1162 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001163 return error;
1164}
1165
1166void
Jim Inghambb006ce2014-08-02 00:33:35 +00001167ProcessGDBRemote::DidLaunchOrAttach (ArchSpec& process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001168{
Greg Clayton5160ce52013-03-27 23:08:40 +00001169 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001170 if (log)
Todd Fiala75930012016-08-19 04:21:48 +00001171 log->Printf ("ProcessGDBRemote::%s()", __FUNCTION__);
Greg Clayton93d3c8332011-02-16 04:46:07 +00001172 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001173 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001174 BuildDynamicRegisterInfo (false);
Greg Clayton3af9ea52010-11-18 05:57:03 +00001175
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001176 // See if the GDB server supports the qHostInfo information
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001177
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001178
1179 // See if the GDB server supports the qProcessInfo packet, if so
1180 // prefer that over the Host information as it will be more specific
1181 // to our process.
1182
Todd Fiala75f47c32014-10-11 21:42:09 +00001183 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1184 if (remote_process_arch.IsValid())
1185 {
1186 process_arch = remote_process_arch;
1187 if (log)
1188 log->Printf ("ProcessGDBRemote::%s gdb-remote had process architecture, using %s %s",
1189 __FUNCTION__,
1190 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1191 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1192 }
Jim Inghambb006ce2014-08-02 00:33:35 +00001193 else
Todd Fiala75f47c32014-10-11 21:42:09 +00001194 {
Jim Inghambb006ce2014-08-02 00:33:35 +00001195 process_arch = m_gdb_comm.GetHostArchitecture();
Todd Fiala75f47c32014-10-11 21:42:09 +00001196 if (log)
1197 log->Printf ("ProcessGDBRemote::%s gdb-remote did not have process architecture, using gdb-remote host architecture %s %s",
1198 __FUNCTION__,
1199 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1200 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1201 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001202
Jim Inghambb006ce2014-08-02 00:33:35 +00001203 if (process_arch.IsValid())
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001204 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001205 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Greg Claytond314e812011-03-23 00:09:55 +00001206 if (target_arch.IsValid())
1207 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001208 if (log)
1209 log->Printf ("ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1210 __FUNCTION__,
1211 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1212 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
1213
1214 // If the remote host is ARM and we have apple as the vendor, then
Greg Claytond314e812011-03-23 00:09:55 +00001215 // ARM executables and shared libraries can have mixed ARM architectures.
1216 // You can have an armv6 executable, and if the host is armv7, then the
1217 // system will load the best possible architecture for all shared libraries
1218 // it has, so we really need to take the remote host architecture as our
1219 // defacto architecture in this case.
1220
Jason Molenda6d9fe8c2015-08-21 00:13:37 +00001221 if ((process_arch.GetMachine() == llvm::Triple::arm || process_arch.GetMachine() == llvm::Triple::thumb)
1222 && process_arch.GetTriple().getVendor() == llvm::Triple::Apple)
Greg Claytond314e812011-03-23 00:09:55 +00001223 {
Jason Molenda921c01b2014-08-03 21:42:52 +00001224 GetTarget().SetArchitecture (process_arch);
Todd Fiala75f47c32014-10-11 21:42:09 +00001225 if (log)
1226 log->Printf ("ProcessGDBRemote::%s remote process is ARM/Apple, setting target arch to %s %s",
1227 __FUNCTION__,
1228 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1229 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001230 }
1231 else
1232 {
1233 // Fill in what is missing in the triple
Jim Inghambb006ce2014-08-02 00:33:35 +00001234 const llvm::Triple &remote_triple = process_arch.GetTriple();
Tamas Berghammere724af12015-03-13 10:32:37 +00001235 llvm::Triple new_target_triple = target_arch.GetTriple();
1236 if (new_target_triple.getVendorName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001237 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001238 new_target_triple.setVendor (remote_triple.getVendor());
Greg Claytond314e812011-03-23 00:09:55 +00001239
Tamas Berghammere724af12015-03-13 10:32:37 +00001240 if (new_target_triple.getOSName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001241 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001242 new_target_triple.setOS (remote_triple.getOS());
Greg Claytond314e812011-03-23 00:09:55 +00001243
Tamas Berghammere724af12015-03-13 10:32:37 +00001244 if (new_target_triple.getEnvironmentName().size() == 0)
1245 new_target_triple.setEnvironment (remote_triple.getEnvironment());
Greg Clayton70b57652011-05-15 01:25:55 +00001246 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001247
Tamas Berghammere724af12015-03-13 10:32:37 +00001248 ArchSpec new_target_arch = target_arch;
1249 new_target_arch.SetTriple(new_target_triple);
1250 GetTarget().SetArchitecture(new_target_arch);
1251 }
Greg Claytond314e812011-03-23 00:09:55 +00001252 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001253
1254 if (log)
1255 log->Printf ("ProcessGDBRemote::%s final target arch after adjustments for remote architecture: %s %s",
1256 __FUNCTION__,
1257 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1258 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001259 }
1260 else
1261 {
1262 // The target doesn't have a valid architecture yet, set it from
1263 // the architecture we got from the remote GDB server
Jason Molenda921c01b2014-08-03 21:42:52 +00001264 GetTarget().SetArchitecture (process_arch);
Greg Claytond314e812011-03-23 00:09:55 +00001265 }
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001266 }
Todd Fiala75930012016-08-19 04:21:48 +00001267
1268 // Find out which StructuredDataPlugins are supported by the
1269 // debug monitor. These plugins transmit data over async $J packets.
1270 auto supported_packets_array =
1271 m_gdb_comm.GetSupportedStructuredDataPlugins();
1272 if (supported_packets_array)
1273 MapSupportedStructuredDataPlugins(*supported_packets_array);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001274 }
1275}
1276
1277void
1278ProcessGDBRemote::DidLaunch ()
1279{
Jim Inghambb006ce2014-08-02 00:33:35 +00001280 ArchSpec process_arch;
1281 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001282}
1283
1284Error
Han Ming Ong84647042012-02-25 01:07:38 +00001285ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1286{
Todd Fiala75f47c32014-10-11 21:42:09 +00001287 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001288 Error error;
Todd Fiala75f47c32014-10-11 21:42:09 +00001289
1290 if (log)
1291 log->Printf ("ProcessGDBRemote::%s()", __FUNCTION__);
1292
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001293 // Clear out and clean up from any current state
1294 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001295 if (attach_pid != LLDB_INVALID_PROCESS_ID)
1296 {
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00001297 error = EstablishConnectionIfNeeded (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001298 if (error.Success())
1299 {
Jim Ingham106d0282014-06-25 02:32:56 +00001300 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
Todd Fiala75f47c32014-10-11 21:42:09 +00001301
Greg Clayton71337622011-02-24 22:24:29 +00001302 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001303 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Ed Maste81b4c5f2016-01-04 01:43:47 +00001304 SetID (attach_pid);
Greg Clayton71337622011-02-24 22:24:29 +00001305 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001306 }
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00001307 else
1308 SetExitStatus (-1, error.AsCString());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001309 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001310
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001311 return error;
1312}
1313
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001314Error
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001315ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001316{
1317 Error error;
1318 // Clear out and clean up from any current state
1319 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001320
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001321 if (process_name && process_name[0])
1322 {
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00001323 error = EstablishConnectionIfNeeded (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001324 if (error.Success())
1325 {
1326 StreamString packet;
Ed Maste81b4c5f2016-01-04 01:43:47 +00001327
Jim Ingham106d0282014-06-25 02:32:56 +00001328 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
Ed Maste81b4c5f2016-01-04 01:43:47 +00001329
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001330 if (attach_info.GetWaitForLaunch())
Jim Inghamcd16df92012-07-20 21:37:13 +00001331 {
1332 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1333 {
1334 packet.PutCString ("vAttachWait");
1335 }
1336 else
1337 {
1338 if (attach_info.GetIgnoreExisting())
1339 packet.PutCString("vAttachWait");
1340 else
1341 packet.PutCString ("vAttachOrWait");
1342 }
1343 }
Greg Clayton71337622011-02-24 22:24:29 +00001344 else
1345 packet.PutCString("vAttachName");
1346 packet.PutChar(';');
Bruce Mitchener9ccb9702015-11-07 04:40:13 +00001347 packet.PutBytesAsRawHex8(process_name, strlen(process_name), endian::InlHostByteOrder(), endian::InlHostByteOrder());
Ed Maste81b4c5f2016-01-04 01:43:47 +00001348
Greg Clayton71337622011-02-24 22:24:29 +00001349 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1350
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001351 }
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00001352 else
1353 SetExitStatus (-1, error.AsCString());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001354 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001355 return error;
1356}
1357
Greg Clayton5df78fa2015-05-23 03:54:53 +00001358void
1359ProcessGDBRemote::DidExit ()
Greg Claytonfbb76342013-11-20 21:07:01 +00001360{
Greg Clayton5df78fa2015-05-23 03:54:53 +00001361 // When we exit, disconnect from the GDB server communications
Greg Claytonfbb76342013-11-20 21:07:01 +00001362 m_gdb_comm.Disconnect();
Greg Claytonfbb76342013-11-20 21:07:01 +00001363}
1364
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001365void
Jim Inghambb006ce2014-08-02 00:33:35 +00001366ProcessGDBRemote::DidAttach (ArchSpec &process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001367{
Jim Inghambb006ce2014-08-02 00:33:35 +00001368 // If you can figure out what the architecture is, fill it in here.
1369 process_arch.Clear();
1370 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001371}
1372
Eugene Zelenko0722f082015-10-24 01:28:05 +00001373
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001374Error
1375ProcessGDBRemote::WillResume ()
1376{
Greg Clayton71fc2a32011-02-12 06:28:37 +00001377 m_continue_c_tids.clear();
1378 m_continue_C_tids.clear();
1379 m_continue_s_tids.clear();
1380 m_continue_S_tids.clear();
Greg Clayton2e309072015-07-17 23:42:28 +00001381 m_jstopinfo_sp.reset();
1382 m_jthreadsinfo_sp.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001383 return Error();
1384}
1385
1386Error
1387ProcessGDBRemote::DoResume ()
1388{
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001389 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001390 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001391 if (log)
1392 log->Printf ("ProcessGDBRemote::Resume()");
Ed Maste81b4c5f2016-01-04 01:43:47 +00001393
Jim Ingham583bbb12016-03-07 21:50:25 +00001394 ListenerSP listener_sp (Listener::MakeListener("gdb-remote.resume-packet-sent"));
1395 if (listener_sp->StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
Greg Claytone5219662010-12-03 06:02:24 +00001396 {
Jim Ingham583bbb12016-03-07 21:50:25 +00001397 listener_sp->StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
Ed Maste81b4c5f2016-01-04 01:43:47 +00001398
Greg Claytond1d06e42013-04-20 00:27:58 +00001399 const size_t num_threads = GetThreadList().GetSize();
1400
Greg Clayton71fc2a32011-02-12 06:28:37 +00001401 StreamString continue_packet;
1402 bool continue_packet_error = false;
1403 if (m_gdb_comm.HasAnyVContSupport ())
1404 {
Ewan Crawford78baa192015-05-13 09:18:18 +00001405 if (!GetTarget().GetNonStopModeEnabled() &&
1406 (m_continue_c_tids.size() == num_threads ||
Greg Claytone98008c2014-02-13 23:34:38 +00001407 (m_continue_c_tids.empty() &&
1408 m_continue_C_tids.empty() &&
1409 m_continue_s_tids.empty() &&
Ewan Crawford78baa192015-05-13 09:18:18 +00001410 m_continue_S_tids.empty())))
Greg Clayton71fc2a32011-02-12 06:28:37 +00001411 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001412 // All threads are continuing, just send a "c" packet
1413 continue_packet.PutCString ("c");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001414 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001415 else
1416 {
1417 continue_packet.PutCString ("vCont");
Ed Maste81b4c5f2016-01-04 01:43:47 +00001418
Greg Claytond1d06e42013-04-20 00:27:58 +00001419 if (!m_continue_c_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001420 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001421 if (m_gdb_comm.GetVContSupported ('c'))
1422 {
1423 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)
1424 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1425 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001426 else
Greg Claytond1d06e42013-04-20 00:27:58 +00001427 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001428 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001429
Greg Claytond1d06e42013-04-20 00:27:58 +00001430 if (!continue_packet_error && !m_continue_C_tids.empty())
1431 {
1432 if (m_gdb_comm.GetVContSupported ('C'))
1433 {
1434 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)
1435 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1436 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001437 else
Greg Claytond1d06e42013-04-20 00:27:58 +00001438 continue_packet_error = true;
1439 }
Greg Claytone5219662010-12-03 06:02:24 +00001440
Greg Claytond1d06e42013-04-20 00:27:58 +00001441 if (!continue_packet_error && !m_continue_s_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001442 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001443 if (m_gdb_comm.GetVContSupported ('s'))
1444 {
1445 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)
1446 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1447 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001448 else
Greg Claytond1d06e42013-04-20 00:27:58 +00001449 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001450 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001451
Greg Claytond1d06e42013-04-20 00:27:58 +00001452 if (!continue_packet_error && !m_continue_S_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001453 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001454 if (m_gdb_comm.GetVContSupported ('S'))
1455 {
1456 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)
1457 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1458 }
1459 else
1460 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001461 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001462
Greg Claytond1d06e42013-04-20 00:27:58 +00001463 if (continue_packet_error)
1464 continue_packet.GetString().clear();
Greg Clayton71fc2a32011-02-12 06:28:37 +00001465 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001466 }
1467 else
1468 continue_packet_error = true;
Ed Maste81b4c5f2016-01-04 01:43:47 +00001469
Greg Clayton71fc2a32011-02-12 06:28:37 +00001470 if (continue_packet_error)
1471 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001472 // Either no vCont support, or we tried to use part of the vCont
1473 // packet that wasn't supported by the remote GDB server.
1474 // We need to try and make a simple packet that can do our continue
Greg Clayton71fc2a32011-02-12 06:28:37 +00001475 const size_t num_continue_c_tids = m_continue_c_tids.size();
1476 const size_t num_continue_C_tids = m_continue_C_tids.size();
1477 const size_t num_continue_s_tids = m_continue_s_tids.size();
1478 const size_t num_continue_S_tids = m_continue_S_tids.size();
1479 if (num_continue_c_tids > 0)
1480 {
1481 if (num_continue_c_tids == num_threads)
1482 {
1483 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001484 m_gdb_comm.SetCurrentThreadForRun (-1);
Ed Maste81b4c5f2016-01-04 01:43:47 +00001485 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001486 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001487 }
1488 else if (num_continue_c_tids == 1 &&
Ed Maste81b4c5f2016-01-04 01:43:47 +00001489 num_continue_C_tids == 0 &&
1490 num_continue_s_tids == 0 &&
Greg Clayton71fc2a32011-02-12 06:28:37 +00001491 num_continue_S_tids == 0 )
1492 {
1493 // Only one thread is continuing
Greg Clayton8b82f082011-04-12 05:54:46 +00001494 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Ed Maste81b4c5f2016-01-04 01:43:47 +00001495 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001496 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001497 }
1498 }
1499
Greg Clayton0c74e782011-06-24 03:21:43 +00001500 if (continue_packet_error && num_continue_C_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001501 {
Ed Maste81b4c5f2016-01-04 01:43:47 +00001502 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1503 num_continue_C_tids > 0 &&
1504 num_continue_s_tids == 0 &&
Greg Clayton0c74e782011-06-24 03:21:43 +00001505 num_continue_S_tids == 0 )
Greg Clayton71fc2a32011-02-12 06:28:37 +00001506 {
1507 const int continue_signo = m_continue_C_tids.front().second;
Greg Clayton0c74e782011-06-24 03:21:43 +00001508 // Only one thread is continuing
Greg Clayton71fc2a32011-02-12 06:28:37 +00001509 if (num_continue_C_tids > 1)
1510 {
Ed Maste81b4c5f2016-01-04 01:43:47 +00001511 // More that one thread with a signal, yet we don't have
Greg Clayton0c74e782011-06-24 03:21:43 +00001512 // vCont support and we are being asked to resume each
1513 // thread with a signal, we need to make sure they are
1514 // all the same signal, or we can't issue the continue
1515 // accurately with the current support...
1516 if (num_continue_C_tids > 1)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001517 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001518 continue_packet_error = false;
1519 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1520 {
1521 if (m_continue_C_tids[i].second != continue_signo)
1522 continue_packet_error = true;
1523 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001524 }
Greg Clayton0c74e782011-06-24 03:21:43 +00001525 if (!continue_packet_error)
1526 m_gdb_comm.SetCurrentThreadForRun (-1);
1527 }
1528 else
1529 {
1530 // Set the continue thread ID
1531 continue_packet_error = false;
1532 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001533 }
1534 if (!continue_packet_error)
1535 {
1536 // Add threads continuing with the same signo...
Greg Clayton71fc2a32011-02-12 06:28:37 +00001537 continue_packet.Printf("C%2.2x", continue_signo);
1538 }
1539 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001540 }
1541
Greg Clayton0c74e782011-06-24 03:21:43 +00001542 if (continue_packet_error && num_continue_s_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001543 {
1544 if (num_continue_s_tids == num_threads)
1545 {
1546 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001547 m_gdb_comm.SetCurrentThreadForRun (-1);
Ewan Crawford76df2882015-06-23 12:32:06 +00001548
1549 // If in Non-Stop-Mode use vCont when stepping
1550 if (GetTarget().GetNonStopModeEnabled())
1551 {
1552 if (m_gdb_comm.GetVContSupported('s'))
1553 continue_packet.PutCString("vCont;s");
1554 else
1555 continue_packet.PutChar('s');
1556 }
1557 else
1558 continue_packet.PutChar('s');
1559
Greg Clayton0c74e782011-06-24 03:21:43 +00001560 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001561 }
1562 else if (num_continue_c_tids == 0 &&
Ed Maste81b4c5f2016-01-04 01:43:47 +00001563 num_continue_C_tids == 0 &&
1564 num_continue_s_tids == 1 &&
Greg Clayton71fc2a32011-02-12 06:28:37 +00001565 num_continue_S_tids == 0 )
1566 {
1567 // Only one thread is stepping
Greg Clayton8b82f082011-04-12 05:54:46 +00001568 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Ed Maste81b4c5f2016-01-04 01:43:47 +00001569 continue_packet.PutChar ('s');
Greg Clayton0c74e782011-06-24 03:21:43 +00001570 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001571 }
1572 }
1573
1574 if (!continue_packet_error && num_continue_S_tids > 0)
1575 {
1576 if (num_continue_S_tids == num_threads)
1577 {
1578 const int step_signo = m_continue_S_tids.front().second;
1579 // Are all threads trying to step with the same signal?
Greg Clayton0c74e782011-06-24 03:21:43 +00001580 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001581 if (num_continue_S_tids > 1)
1582 {
1583 for (size_t i=1; i<num_threads; ++i)
1584 {
1585 if (m_continue_S_tids[i].second != step_signo)
1586 continue_packet_error = true;
1587 }
1588 }
1589 if (!continue_packet_error)
1590 {
1591 // Add threads stepping with the same signo...
Greg Clayton8b82f082011-04-12 05:54:46 +00001592 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001593 continue_packet.Printf("S%2.2x", step_signo);
1594 }
1595 }
1596 else if (num_continue_c_tids == 0 &&
Ed Maste81b4c5f2016-01-04 01:43:47 +00001597 num_continue_C_tids == 0 &&
1598 num_continue_s_tids == 0 &&
Greg Clayton71fc2a32011-02-12 06:28:37 +00001599 num_continue_S_tids == 1 )
1600 {
1601 // Only one thread is stepping with signal
Greg Clayton8b82f082011-04-12 05:54:46 +00001602 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001603 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Clayton0c74e782011-06-24 03:21:43 +00001604 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001605 }
1606 }
1607 }
1608
1609 if (continue_packet_error)
1610 {
1611 error.SetErrorString ("can't make continue packet for this resume");
1612 }
1613 else
1614 {
1615 EventSP event_sp;
Zachary Turneracee96a2014-09-23 18:32:09 +00001616 if (!m_async_thread.IsJoinable())
Jim Inghamb1e2e842012-04-12 18:49:31 +00001617 {
1618 error.SetErrorString ("Trying to resume but the async thread is dead.");
1619 if (log)
1620 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1621 return error;
1622 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001623
Greg Clayton71fc2a32011-02-12 06:28:37 +00001624 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1625
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00001626 if (listener_sp->WaitForEvent(std::chrono::seconds(5), event_sp) == false)
Jim Inghamb1e2e842012-04-12 18:49:31 +00001627 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001628 error.SetErrorString("Resume timed out.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00001629 if (log)
1630 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1631 }
1632 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1633 {
1634 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1635 if (log)
1636 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1637 return error;
1638 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001639 }
Greg Claytone5219662010-12-03 06:02:24 +00001640 }
1641
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001642 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001643}
1644
Greg Clayton9e920902012-04-10 02:25:43 +00001645void
Ewan Crawford78baa192015-05-13 09:18:18 +00001646ProcessGDBRemote::HandleStopReplySequence ()
1647{
1648 while(true)
1649 {
1650 // Send vStopped
1651 StringExtractorGDBRemote response;
1652 m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false);
1653
1654 // OK represents end of signal list
1655 if (response.IsOKResponse())
1656 break;
1657
1658 // If not OK or a normal packet we have a problem
1659 if (!response.IsNormalResponse())
1660 break;
1661
1662 SetLastStopPacket(response);
1663 }
1664}
1665
1666void
Greg Clayton9e920902012-04-10 02:25:43 +00001667ProcessGDBRemote::ClearThreadIDList ()
1668{
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00001669 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001670 m_thread_ids.clear();
Jason Molenda545304d2015-12-18 00:45:35 +00001671 m_thread_pcs.clear();
Greg Clayton9e920902012-04-10 02:25:43 +00001672}
1673
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001674size_t
1675ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue (std::string &value)
1676{
1677 m_thread_ids.clear();
Jason Molenda545304d2015-12-18 00:45:35 +00001678 m_thread_pcs.clear();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001679 size_t comma_pos;
1680 lldb::tid_t tid;
1681 while ((comma_pos = value.find(',')) != std::string::npos)
1682 {
1683 value[comma_pos] = '\0';
1684 // thread in big endian hex
1685 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1686 if (tid != LLDB_INVALID_THREAD_ID)
1687 m_thread_ids.push_back (tid);
1688 value.erase(0, comma_pos + 1);
1689 }
1690 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1691 if (tid != LLDB_INVALID_THREAD_ID)
1692 m_thread_ids.push_back (tid);
1693 return m_thread_ids.size();
1694}
1695
Jason Molenda545304d2015-12-18 00:45:35 +00001696size_t
1697ProcessGDBRemote::UpdateThreadPCsFromStopReplyThreadsValue (std::string &value)
1698{
1699 m_thread_pcs.clear();
1700 size_t comma_pos;
1701 lldb::addr_t pc;
1702 while ((comma_pos = value.find(',')) != std::string::npos)
1703 {
1704 value[comma_pos] = '\0';
1705 pc = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
1706 if (pc != LLDB_INVALID_ADDRESS)
1707 m_thread_pcs.push_back (pc);
1708 value.erase(0, comma_pos + 1);
1709 }
1710 pc = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
1711 if (pc != LLDB_INVALID_THREAD_ID)
1712 m_thread_pcs.push_back (pc);
1713 return m_thread_pcs.size();
1714}
1715
Greg Clayton9e920902012-04-10 02:25:43 +00001716bool
1717ProcessGDBRemote::UpdateThreadIDList ()
1718{
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00001719 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001720
Greg Clayton2e309072015-07-17 23:42:28 +00001721 if (m_jthreadsinfo_sp)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001722 {
1723 // If we have the JSON threads info, we can get the thread list from that
Greg Clayton2e309072015-07-17 23:42:28 +00001724 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001725 if (thread_infos && thread_infos->GetSize() > 0)
1726 {
1727 m_thread_ids.clear();
Jason Molenda545304d2015-12-18 00:45:35 +00001728 m_thread_pcs.clear();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001729 thread_infos->ForEach([this](StructuredData::Object* object) -> bool {
1730 StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1731 if (thread_dict)
1732 {
1733 // Set the thread stop info from the JSON dictionary
1734 SetThreadStopInfo (thread_dict);
1735 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1736 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1737 m_thread_ids.push_back(tid);
1738 }
1739 return true; // Keep iterating through all thread_info objects
1740 });
1741 }
1742 if (!m_thread_ids.empty())
1743 return true;
1744 }
1745 else
1746 {
1747 // See if we can get the thread IDs from the current stop reply packets
1748 // that might contain a "threads" key/value pair
1749
1750 // Lock the thread stack while we access it
Greg Claytonfc1e77a982015-11-03 22:42:04 +00001751 //Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +00001752 std::unique_lock<std::recursive_mutex> stop_stack_lock(m_last_stop_packet_mutex, std::defer_lock);
1753 if (stop_stack_lock.try_lock())
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001754 {
Greg Claytonfc1e77a982015-11-03 22:42:04 +00001755 // Get the number of stop packets on the stack
1756 int nItems = m_stop_packet_stack.size();
1757 // Iterate over them
1758 for (int i = 0; i < nItems; i++)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001759 {
Greg Claytonfc1e77a982015-11-03 22:42:04 +00001760 // Get the thread stop info
1761 StringExtractorGDBRemote &stop_info = m_stop_packet_stack[i];
1762 const std::string &stop_info_str = stop_info.GetStringRef();
Jason Molenda545304d2015-12-18 00:45:35 +00001763
1764 m_thread_pcs.clear();
1765 const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:");
1766 if (thread_pcs_pos != std::string::npos)
1767 {
1768 const size_t start = thread_pcs_pos + strlen(";thread-pcs:");
1769 const size_t end = stop_info_str.find(';', start);
1770 if (end != std::string::npos)
1771 {
1772 std::string value = stop_info_str.substr(start, end - start);
1773 UpdateThreadPCsFromStopReplyThreadsValue(value);
1774 }
1775 }
1776
Greg Claytonfc1e77a982015-11-03 22:42:04 +00001777 const size_t threads_pos = stop_info_str.find(";threads:");
1778 if (threads_pos != std::string::npos)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001779 {
Greg Claytonfc1e77a982015-11-03 22:42:04 +00001780 const size_t start = threads_pos + strlen(";threads:");
1781 const size_t end = stop_info_str.find(';', start);
1782 if (end != std::string::npos)
1783 {
1784 std::string value = stop_info_str.substr(start, end - start);
1785 if (UpdateThreadIDsFromStopReplyThreadsValue(value))
1786 return true;
1787 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001788 }
1789 }
1790 }
1791 }
1792
Greg Clayton9e920902012-04-10 02:25:43 +00001793 bool sequence_mutex_unavailable = false;
1794 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1795 if (sequence_mutex_unavailable)
1796 {
Greg Clayton9e920902012-04-10 02:25:43 +00001797 return false; // We just didn't get the list
1798 }
1799 return true;
1800}
1801
Greg Clayton9fc13552012-04-10 00:18:59 +00001802bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001803ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001804{
1805 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +00001806 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Clayton73b472d2010-10-27 03:32:59 +00001807 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +00001808 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Ed Maste81b4c5f2016-01-04 01:43:47 +00001809
Greg Clayton9e920902012-04-10 02:25:43 +00001810 size_t num_thread_ids = m_thread_ids.size();
1811 // The "m_thread_ids" thread ID list should always be updated after each stop
1812 // reply packet, but in case it isn't, update it here.
1813 if (num_thread_ids == 0)
1814 {
1815 if (!UpdateThreadIDList ())
1816 return false;
1817 num_thread_ids = m_thread_ids.size();
1818 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001819
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001820 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001821 if (num_thread_ids > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001822 {
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001823 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001824 {
Greg Clayton9e920902012-04-10 02:25:43 +00001825 tid_t tid = m_thread_ids[i];
Greg Clayton160c9d82013-05-01 21:54:04 +00001826 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001827 if (!thread_sp)
Jim Inghamdee1bc92013-06-22 00:27:45 +00001828 {
Jim Ingham4f465cf2012-10-10 18:32:14 +00001829 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001830 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1831 log->Printf(
1832 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001833 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001834 thread_sp->GetID());
1835 }
1836 else
1837 {
1838 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1839 log->Printf(
1840 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001841 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001842 thread_sp->GetID());
1843 }
Jason Molenda545304d2015-12-18 00:45:35 +00001844 // The m_thread_pcs vector has pc values in big-endian order, not target-endian, unlike most
Ed Maste81b4c5f2016-01-04 01:43:47 +00001845 // of the register read/write packets in gdb-remote protocol.
Jason Molenda545304d2015-12-18 00:45:35 +00001846 // Early in the process startup, we may not yet have set the process ByteOrder so we ignore these;
1847 // they are a performance improvement over fetching thread register values individually, the
1848 // method we will fall back to if needed.
1849 if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() && GetByteOrder() != eByteOrderInvalid)
1850 {
1851 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1852 RegisterContextSP reg_ctx_sp (thread_sp->GetRegisterContext());
1853 if (reg_ctx_sp)
1854 {
Ed Maste81b4c5f2016-01-04 01:43:47 +00001855 uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber
Jason Molenda545304d2015-12-18 00:45:35 +00001856 (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1857 if (pc_regnum != LLDB_INVALID_REGNUM)
1858 {
1859 gdb_thread->PrivateSetRegisterValue (pc_regnum, m_thread_pcs[i]);
1860 }
1861 }
1862 }
Greg Clayton88f86b62016-06-10 23:23:34 +00001863 new_thread_list.AddThreadSortedByIndexID (thread_sp);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001864 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001865 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001866
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001867 // Whatever that is left in old_thread_list_copy are not
1868 // present in new_thread_list. Remove non-existent threads from internal id table.
1869 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1870 for (size_t i=0; i<old_num_thread_ids; i++)
1871 {
1872 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1873 if (old_thread_sp)
1874 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001875 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001876 m_thread_id_to_index_id_map.erase(old_thread_id);
1877 }
1878 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001879
Greg Clayton9fc13552012-04-10 00:18:59 +00001880 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001881}
1882
Eugene Zelenko0722f082015-10-24 01:28:05 +00001883
Greg Clayton358cf1e2015-06-25 21:46:34 +00001884bool
Greg Clayton2e309072015-07-17 23:42:28 +00001885ProcessGDBRemote::GetThreadStopInfoFromJSON (ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001886{
1887 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet
Greg Clayton2e309072015-07-17 23:42:28 +00001888 if (thread_infos_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001889 {
Greg Clayton2e309072015-07-17 23:42:28 +00001890 StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
Greg Clayton358cf1e2015-06-25 21:46:34 +00001891 if (thread_infos)
1892 {
1893 lldb::tid_t tid;
1894 const size_t n = thread_infos->GetSize();
1895 for (size_t i=0; i<n; ++i)
1896 {
1897 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1898 if (thread_dict)
1899 {
1900 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid, LLDB_INVALID_THREAD_ID))
1901 {
1902 if (tid == thread->GetID())
Greg Clayton2e309072015-07-17 23:42:28 +00001903 return (bool)SetThreadStopInfo(thread_dict);
Greg Clayton358cf1e2015-06-25 21:46:34 +00001904 }
1905 }
1906 }
1907 }
1908 }
Greg Clayton2e309072015-07-17 23:42:28 +00001909 return false;
1910}
1911
1912bool
1913ProcessGDBRemote::CalculateThreadStopInfo (ThreadGDBRemote *thread)
1914{
1915 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet
1916 if (GetThreadStopInfoFromJSON (thread, m_jthreadsinfo_sp))
1917 return true;
1918
1919 // See if we got thread stop info for any threads valid stop info reasons threads
1920 // via the "jstopinfo" packet stop reply packet key/value pair?
1921 if (m_jstopinfo_sp)
1922 {
1923 // If we have "jstopinfo" then we have stop descriptions for all threads
1924 // that have stop reasons, and if there is no entry for a thread, then
1925 // it has no stop reason.
1926 thread->GetRegisterContext()->InvalidateIfNeeded(true);
1927 if (!GetThreadStopInfoFromJSON (thread, m_jstopinfo_sp))
1928 {
1929 thread->SetStopInfo (StopInfoSP());
1930 }
1931 return true;
1932 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00001933
1934 // Fall back to using the qThreadStopInfo packet
1935 StringExtractorGDBRemote stop_packet;
1936 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1937 return SetThreadStopInfo (stop_packet) == eStateStopped;
1938 return false;
1939}
1940
Eugene Zelenko0722f082015-10-24 01:28:05 +00001941
Greg Clayton358cf1e2015-06-25 21:46:34 +00001942ThreadSP
1943ProcessGDBRemote::SetThreadStopInfo (lldb::tid_t tid,
1944 ExpeditedRegisterMap &expedited_register_map,
1945 uint8_t signo,
1946 const std::string &thread_name,
1947 const std::string &reason,
1948 const std::string &description,
1949 uint32_t exc_type,
1950 const std::vector<addr_t> &exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001951 addr_t thread_dispatch_qaddr,
1952 bool queue_vars_valid, // Set to true if queue_name, queue_kind and queue_serial are valid
Jason Molenda77f89352016-01-12 07:09:16 +00001953 LazyBool associated_with_dispatch_queue,
1954 addr_t dispatch_queue_t,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001955 std::string &queue_name,
1956 QueueKind queue_kind,
1957 uint64_t queue_serial)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001958{
1959 ThreadSP thread_sp;
1960 if (tid != LLDB_INVALID_THREAD_ID)
1961 {
1962 // Scope for "locker" below
1963 {
1964 // m_thread_list_real does have its own mutex, but we need to
1965 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1966 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00001967 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
Greg Clayton358cf1e2015-06-25 21:46:34 +00001968 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1969
1970 if (!thread_sp)
1971 {
1972 // Create the thread if we need to
1973 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1974 m_thread_list_real.AddThread(thread_sp);
1975 }
1976 }
1977
1978 if (thread_sp)
1979 {
1980 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1981 gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001982
Greg Clayton358cf1e2015-06-25 21:46:34 +00001983 for (const auto &pair : expedited_register_map)
1984 {
1985 StringExtractor reg_value_extractor;
1986 reg_value_extractor.GetStringRef() = pair.second;
Pavel Labathb42b48e2016-08-19 12:31:49 +00001987 DataBufferSP buffer_sp(new DataBufferHeap(reg_value_extractor.GetStringRef().size() / 2, 0));
Zachary Turnerd08f09c2016-08-30 18:12:11 +00001988 reg_value_extractor.GetHexBytes(buffer_sp->GetData(), '\xcc');
1989 gdb_thread->PrivateSetRegisterValue(pair.first, buffer_sp->GetData());
Greg Clayton358cf1e2015-06-25 21:46:34 +00001990 }
1991
Greg Clayton358cf1e2015-06-25 21:46:34 +00001992 thread_sp->SetName (thread_name.empty() ? NULL : thread_name.c_str());
1993
1994 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001995 // Check if the GDB server was able to provide the queue name, kind and serial number
1996 if (queue_vars_valid)
Jason Molenda77f89352016-01-12 07:09:16 +00001997 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 +00001998 else
1999 gdb_thread->ClearQueueInfo();
2000
Jason Molenda77f89352016-01-12 07:09:16 +00002001 gdb_thread->SetAssociatedWithLibdispatchQueue (associated_with_dispatch_queue);
2002
2003 if (dispatch_queue_t != LLDB_INVALID_ADDRESS)
2004 gdb_thread->SetQueueLibdispatchQueueAddress (dispatch_queue_t);
2005
Greg Clayton2e309072015-07-17 23:42:28 +00002006 // Make sure we update our thread stop reason just once
2007 if (!thread_sp->StopInfoIsUpToDate())
Greg Clayton358cf1e2015-06-25 21:46:34 +00002008 {
Greg Clayton2e309072015-07-17 23:42:28 +00002009 thread_sp->SetStopInfo (StopInfoSP());
Ryan Brown65d4d5c2015-09-16 21:20:44 +00002010 // If there's a memory thread backed by this thread, we need to use it to calcualte StopInfo.
2011 ThreadSP memory_thread_sp = m_thread_list.FindThreadByProtocolID(thread_sp->GetProtocolID());
2012 if (memory_thread_sp)
2013 thread_sp = memory_thread_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002014
Greg Clayton2e309072015-07-17 23:42:28 +00002015 if (exc_type != 0)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002016 {
Greg Clayton2e309072015-07-17 23:42:28 +00002017 const size_t exc_data_size = exc_data.size();
2018
2019 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
2020 exc_type,
2021 exc_data_size,
2022 exc_data_size >= 1 ? exc_data[0] : 0,
2023 exc_data_size >= 2 ? exc_data[1] : 0,
2024 exc_data_size >= 3 ? exc_data[2] : 0));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002025 }
Greg Clayton2e309072015-07-17 23:42:28 +00002026 else
Greg Clayton358cf1e2015-06-25 21:46:34 +00002027 {
Greg Clayton2e309072015-07-17 23:42:28 +00002028 bool handled = false;
2029 bool did_exec = false;
2030 if (!reason.empty())
Greg Clayton358cf1e2015-06-25 21:46:34 +00002031 {
Greg Clayton2e309072015-07-17 23:42:28 +00002032 if (reason.compare("trace") == 0)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002033 {
Pavel Labathef409122016-04-07 08:16:10 +00002034 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
2035 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2036
2037 // If the current pc is a breakpoint site then the StopInfo should be set to Breakpoint
2038 // Otherwise, it will be set to Trace.
2039 if (bp_site_sp && bp_site_sp->ValidForThisThread(thread_sp.get()))
2040 {
2041 thread_sp->SetStopInfo(
2042 StopInfo::CreateStopReasonWithBreakpointSiteID(*thread_sp, bp_site_sp->GetID()));
2043 }
2044 else
2045 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Greg Clayton2e309072015-07-17 23:42:28 +00002046 handled = true;
2047 }
2048 else if (reason.compare("breakpoint") == 0)
2049 {
Pavel Labathef409122016-04-07 08:16:10 +00002050 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
2051 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2052 if (bp_site_sp)
2053 {
2054 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2055 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2056 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2057 handled = true;
2058 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2059 {
2060 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2061 }
2062 else
2063 {
2064 StopInfoSP invalid_stop_info_sp;
2065 thread_sp->SetStopInfo (invalid_stop_info_sp);
2066 }
2067 }
Greg Clayton2e309072015-07-17 23:42:28 +00002068 }
2069 else if (reason.compare("trap") == 0)
2070 {
2071 // Let the trap just use the standard signal stop reason below...
2072 }
2073 else if (reason.compare("watchpoint") == 0)
2074 {
2075 StringExtractor desc_extractor(description.c_str());
2076 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
2077 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
Jaydeep Patil83143502015-08-13 03:44:09 +00002078 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
Greg Clayton2e309072015-07-17 23:42:28 +00002079 watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
2080 if (wp_addr != LLDB_INVALID_ADDRESS)
2081 {
Mohit K. Bhakkad6846bc82015-12-02 17:45:02 +00002082 WatchpointSP wp_sp;
2083 ArchSpec::Core core = GetTarget().GetArchitecture().GetCore();
Omair Javaid43507f52016-06-16 16:41:22 +00002084 if ((core >= ArchSpec::kCore_mips_first && core <= ArchSpec::kCore_mips_last) ||
Omair Javaidc6dc90e2016-06-27 11:18:23 +00002085 (core >= ArchSpec::eCore_arm_generic && core <= ArchSpec::eCore_arm_aarch64))
Mohit K. Bhakkad6846bc82015-12-02 17:45:02 +00002086 wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_hit_addr);
2087 if (!wp_sp)
2088 wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
Greg Clayton2e309072015-07-17 23:42:28 +00002089 if (wp_sp)
2090 {
2091 wp_sp->SetHardwareIndex(wp_index);
2092 watch_id = wp_sp->GetID();
2093 }
2094 }
2095 if (watch_id == LLDB_INVALID_WATCH_ID)
2096 {
2097 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_WATCHPOINTS));
2098 if (log) log->Printf ("failed to find watchpoint");
2099 }
Jaydeep Patil83143502015-08-13 03:44:09 +00002100 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id, wp_hit_addr));
Greg Clayton2e309072015-07-17 23:42:28 +00002101 handled = true;
2102 }
2103 else if (reason.compare("exception") == 0)
2104 {
2105 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
2106 handled = true;
2107 }
2108 else if (reason.compare("exec") == 0)
2109 {
2110 did_exec = true;
2111 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
2112 handled = true;
2113 }
2114 }
Pavel Labath3ce324a2016-04-06 09:10:29 +00002115 else if (!signo)
2116 {
Pavel Labathef409122016-04-07 08:16:10 +00002117 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
2118 lldb::BreakpointSiteSP bp_site_sp =
2119 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2120
Pavel Labath3ce324a2016-04-06 09:10:29 +00002121 // If the current pc is a breakpoint site then the StopInfo should be set to Breakpoint
2122 // even though the remote stub did not set it as such. This can happen when
2123 // the thread is involuntarily interrupted (e.g. due to stops on other
2124 // threads) just as it is about to execute the breakpoint instruction.
Pavel Labathef409122016-04-07 08:16:10 +00002125 if (bp_site_sp && bp_site_sp->ValidForThisThread(thread_sp.get()))
2126 {
2127 thread_sp->SetStopInfo(
2128 StopInfo::CreateStopReasonWithBreakpointSiteID(*thread_sp, bp_site_sp->GetID()));
Pavel Labath3ce324a2016-04-06 09:10:29 +00002129 handled = true;
Pavel Labathef409122016-04-07 08:16:10 +00002130 }
Pavel Labath3ce324a2016-04-06 09:10:29 +00002131 }
Greg Clayton2e309072015-07-17 23:42:28 +00002132
2133 if (!handled && signo && did_exec == false)
2134 {
2135 if (signo == SIGTRAP)
2136 {
2137 // Currently we are going to assume SIGTRAP means we are either
2138 // hitting a breakpoint or hardware single stepping.
2139 handled = true;
2140 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
2141 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2142
2143 if (bp_site_sp)
2144 {
2145 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2146 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2147 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2148 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2149 {
2150 if(m_breakpoint_pc_offset != 0)
2151 thread_sp->GetRegisterContext()->SetPC(pc);
2152 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2153 }
2154 else
2155 {
2156 StopInfoSP invalid_stop_info_sp;
2157 thread_sp->SetStopInfo (invalid_stop_info_sp);
2158 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002159 }
2160 else
2161 {
Greg Clayton2e309072015-07-17 23:42:28 +00002162 // If we were stepping then assume the stop was the result of the trace. If we were
2163 // not stepping then report the SIGTRAP.
2164 // FIXME: We are still missing the case where we single step over a trap instruction.
2165 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
2166 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
2167 else
2168 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo, description.c_str()));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002169 }
2170 }
Greg Clayton2e309072015-07-17 23:42:28 +00002171 if (!handled)
2172 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo, description.c_str()));
2173 }
2174
2175 if (!description.empty())
2176 {
2177 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
2178 if (stop_info_sp)
2179 {
2180 const char *stop_info_desc = stop_info_sp->GetDescription();
2181 if (!stop_info_desc || !stop_info_desc[0])
2182 stop_info_sp->SetDescription (description.c_str());
2183 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002184 else
2185 {
Greg Clayton2e309072015-07-17 23:42:28 +00002186 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002187 }
2188 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002189 }
2190 }
2191 }
2192 }
2193 return thread_sp;
2194}
2195
Greg Clayton2e309072015-07-17 23:42:28 +00002196lldb::ThreadSP
Greg Clayton358cf1e2015-06-25 21:46:34 +00002197ProcessGDBRemote::SetThreadStopInfo (StructuredData::Dictionary *thread_dict)
2198{
2199 static ConstString g_key_tid("tid");
2200 static ConstString g_key_name("name");
2201 static ConstString g_key_reason("reason");
2202 static ConstString g_key_metype("metype");
2203 static ConstString g_key_medata("medata");
2204 static ConstString g_key_qaddr("qaddr");
Jason Molenda77f89352016-01-12 07:09:16 +00002205 static ConstString g_key_dispatch_queue_t("dispatch_queue_t");
2206 static ConstString g_key_associated_with_dispatch_queue("associated_with_dispatch_queue");
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002207 static ConstString g_key_queue_name("qname");
2208 static ConstString g_key_queue_kind("qkind");
Jason Molenda26d84e82016-01-08 00:20:48 +00002209 static ConstString g_key_queue_serial_number("qserialnum");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002210 static ConstString g_key_registers("registers");
2211 static ConstString g_key_memory("memory");
2212 static ConstString g_key_address("address");
2213 static ConstString g_key_bytes("bytes");
2214 static ConstString g_key_description("description");
Pavel Labath4a4bb122015-07-16 14:14:35 +00002215 static ConstString g_key_signal("signal");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002216
2217 // Stop with signal and thread info
2218 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2219 uint8_t signo = 0;
2220 std::string value;
2221 std::string thread_name;
2222 std::string reason;
2223 std::string description;
2224 uint32_t exc_type = 0;
2225 std::vector<addr_t> exc_data;
2226 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2227 ExpeditedRegisterMap expedited_register_map;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002228 bool queue_vars_valid = false;
Jason Molenda77f89352016-01-12 07:09:16 +00002229 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2230 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002231 std::string queue_name;
2232 QueueKind queue_kind = eQueueKindUnknown;
Jason Molenda26d84e82016-01-08 00:20:48 +00002233 uint64_t queue_serial_number = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002234 // Iterate through all of the thread dictionary key/value pairs from the structured data dictionary
2235
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002236 thread_dict->ForEach([this,
2237 &tid,
2238 &expedited_register_map,
2239 &thread_name,
2240 &signo,
2241 &reason,
2242 &description,
2243 &exc_type,
2244 &exc_data,
2245 &thread_dispatch_qaddr,
2246 &queue_vars_valid,
Jason Molenda77f89352016-01-12 07:09:16 +00002247 &associated_with_dispatch_queue,
2248 &dispatch_queue_t,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002249 &queue_name,
2250 &queue_kind,
Jason Molenda26d84e82016-01-08 00:20:48 +00002251 &queue_serial_number]
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002252 (ConstString key, StructuredData::Object* object) -> bool
Greg Clayton358cf1e2015-06-25 21:46:34 +00002253 {
2254 if (key == g_key_tid)
2255 {
2256 // thread in big endian hex
2257 tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
2258 }
2259 else if (key == g_key_metype)
2260 {
2261 // exception type in big endian hex
2262 exc_type = object->GetIntegerValue(0);
2263 }
2264 else if (key == g_key_medata)
2265 {
2266 // exception data in big endian hex
2267 StructuredData::Array *array = object->GetAsArray();
2268 if (array)
2269 {
2270 array->ForEach([&exc_data](StructuredData::Object* object) -> bool {
2271 exc_data.push_back(object->GetIntegerValue());
2272 return true; // Keep iterating through all array items
2273 });
2274 }
2275 }
2276 else if (key == g_key_name)
2277 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002278 thread_name = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002279 }
2280 else if (key == g_key_qaddr)
2281 {
2282 thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
2283 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002284 else if (key == g_key_queue_name)
2285 {
2286 queue_vars_valid = true;
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002287 queue_name = object->GetStringValue();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002288 }
2289 else if (key == g_key_queue_kind)
2290 {
2291 std::string queue_kind_str = object->GetStringValue();
2292 if (queue_kind_str == "serial")
2293 {
2294 queue_vars_valid = true;
2295 queue_kind = eQueueKindSerial;
2296 }
2297 else if (queue_kind_str == "concurrent")
2298 {
2299 queue_vars_valid = true;
2300 queue_kind = eQueueKindConcurrent;
2301 }
2302 }
Jason Molenda26d84e82016-01-08 00:20:48 +00002303 else if (key == g_key_queue_serial_number)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002304 {
Jason Molenda26d84e82016-01-08 00:20:48 +00002305 queue_serial_number = object->GetIntegerValue(0);
2306 if (queue_serial_number != 0)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002307 queue_vars_valid = true;
2308 }
Jason Molenda77f89352016-01-12 07:09:16 +00002309 else if (key == g_key_dispatch_queue_t)
2310 {
2311 dispatch_queue_t = object->GetIntegerValue(0);
2312 if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS)
2313 queue_vars_valid = true;
2314 }
2315 else if (key == g_key_associated_with_dispatch_queue)
2316 {
2317 queue_vars_valid = true;
2318 bool associated = object->GetBooleanValue ();
2319 if (associated)
2320 associated_with_dispatch_queue = eLazyBoolYes;
2321 else
2322 associated_with_dispatch_queue = eLazyBoolNo;
2323 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002324 else if (key == g_key_reason)
2325 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002326 reason = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002327 }
2328 else if (key == g_key_description)
2329 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002330 description = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002331 }
2332 else if (key == g_key_registers)
2333 {
2334 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2335
2336 if (registers_dict)
2337 {
2338 registers_dict->ForEach([&expedited_register_map](ConstString key, StructuredData::Object* object) -> bool {
2339 const uint32_t reg = StringConvert::ToUInt32 (key.GetCString(), UINT32_MAX, 10);
2340 if (reg != UINT32_MAX)
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002341 expedited_register_map[reg] = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002342 return true; // Keep iterating through all array items
2343 });
2344 }
2345 }
2346 else if (key == g_key_memory)
2347 {
2348 StructuredData::Array *array = object->GetAsArray();
2349 if (array)
2350 {
2351 array->ForEach([this](StructuredData::Object* object) -> bool {
2352 StructuredData::Dictionary *mem_cache_dict = object->GetAsDictionary();
2353 if (mem_cache_dict)
2354 {
2355 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2356 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>("address", mem_cache_addr))
2357 {
2358 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
2359 {
2360 StringExtractor bytes;
2361 if (mem_cache_dict->GetValueForKeyAsString("bytes", bytes.GetStringRef()))
2362 {
2363 bytes.SetFilePos(0);
2364
2365 const size_t byte_size = bytes.GetStringRef().size()/2;
2366 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
Zachary Turnerd08f09c2016-08-30 18:12:11 +00002367 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetData(), 0);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002368 if (bytes_copied == byte_size)
2369 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2370 }
2371 }
2372 }
2373 }
2374 return true; // Keep iterating through all array items
2375 });
2376 }
Eugene Zelenko0722f082015-10-24 01:28:05 +00002377
Greg Clayton358cf1e2015-06-25 21:46:34 +00002378 }
Pavel Labath4a4bb122015-07-16 14:14:35 +00002379 else if (key == g_key_signal)
2380 signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002381 return true; // Keep iterating through all dictionary key/value pairs
2382 });
2383
Greg Clayton2e309072015-07-17 23:42:28 +00002384 return SetThreadStopInfo (tid,
2385 expedited_register_map,
2386 signo,
2387 thread_name,
2388 reason,
2389 description,
2390 exc_type,
2391 exc_data,
2392 thread_dispatch_qaddr,
2393 queue_vars_valid,
Jason Molenda77f89352016-01-12 07:09:16 +00002394 associated_with_dispatch_queue,
2395 dispatch_queue_t,
Greg Clayton2e309072015-07-17 23:42:28 +00002396 queue_name,
2397 queue_kind,
Jason Molenda26d84e82016-01-08 00:20:48 +00002398 queue_serial_number);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002399}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002400
2401StateType
2402ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
2403{
Greg Claytondd0e5a52011-06-02 22:22:38 +00002404 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002405 const char stop_type = stop_packet.GetChar();
2406 switch (stop_type)
2407 {
2408 case 'T':
2409 case 'S':
2410 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00002411 // This is a bit of a hack, but is is required. If we did exec, we
2412 // need to clear our thread lists and also know to rebuild our dynamic
2413 // register info before we lookup and threads and populate the expedited
2414 // register values so we need to know this right away so we can cleanup
2415 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00002416 const uint32_t stop_id = GetStopID();
2417 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00002418 {
2419 // Our first stop, make sure we have a process ID, and also make
2420 // sure we know about our registers
2421 if (GetID() == LLDB_INVALID_PROCESS_ID)
2422 {
Greg Claytonc574ede2011-03-10 02:26:48 +00002423 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00002424 if (pid != LLDB_INVALID_PROCESS_ID)
2425 SetID (pid);
2426 }
2427 BuildDynamicRegisterInfo (true);
2428 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002429 // Stop with signal and thread info
Greg Clayton358cf1e2015-06-25 21:46:34 +00002430 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002431 const uint8_t signo = stop_packet.GetHexU8();
Zachary Turner54695a32016-08-29 19:58:14 +00002432 llvm::StringRef key;
2433 llvm::StringRef value;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002434 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00002435 std::string reason;
2436 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002437 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00002438 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002439 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton0b90be12015-06-23 21:27:50 +00002440 bool queue_vars_valid = false; // says if locals below that start with "queue_" are valid
Jason Molenda77f89352016-01-12 07:09:16 +00002441 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2442 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
Greg Clayton0b90be12015-06-23 21:27:50 +00002443 std::string queue_name;
2444 QueueKind queue_kind = eQueueKindUnknown;
Jason Molenda26d84e82016-01-08 00:20:48 +00002445 uint64_t queue_serial_number = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002446 ExpeditedRegisterMap expedited_register_map;
2447 while (stop_packet.GetNameColonValue(key, value))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002448 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002449 if (key.compare("metype") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002450 {
2451 // exception type in big endian hex
Zachary Turner54695a32016-08-29 19:58:14 +00002452 value.getAsInteger(16, exc_type);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002453 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002454 else if (key.compare("medata") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002455 {
2456 // exception data in big endian hex
Zachary Turner54695a32016-08-29 19:58:14 +00002457 uint64_t x;
2458 value.getAsInteger(16, x);
2459 exc_data.push_back(x);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002460 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002461 else if (key.compare("thread") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002462 {
2463 // thread in big endian hex
Zachary Turner54695a32016-08-29 19:58:14 +00002464 if (value.getAsInteger(16, tid))
2465 tid = LLDB_INVALID_THREAD_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002466 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002467 else if (key.compare("threads") == 0)
Greg Clayton9e920902012-04-10 02:25:43 +00002468 {
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00002469 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
2470
Greg Clayton9e920902012-04-10 02:25:43 +00002471 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00002472 // A comma separated list of all threads in the current
2473 // process that includes the thread for this stop reply
2474 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00002475 lldb::tid_t tid;
Zachary Turner54695a32016-08-29 19:58:14 +00002476 while (!value.empty())
Greg Clayton9e920902012-04-10 02:25:43 +00002477 {
Zachary Turner54695a32016-08-29 19:58:14 +00002478 llvm::StringRef tid_str;
2479 std::tie(tid_str, value) = value.split(',');
2480 if (tid_str.getAsInteger(16, tid))
2481 tid = LLDB_INVALID_THREAD_ID;
2482 m_thread_ids.push_back(tid);
Greg Clayton9e920902012-04-10 02:25:43 +00002483 }
Greg Clayton9e920902012-04-10 02:25:43 +00002484 }
Jason Molenda545304d2015-12-18 00:45:35 +00002485 else if (key.compare("thread-pcs") == 0)
2486 {
2487 m_thread_pcs.clear();
2488 // A comma separated list of all threads in the current
2489 // process that includes the thread for this stop reply
2490 // packet
Jason Molenda545304d2015-12-18 00:45:35 +00002491 lldb::addr_t pc;
Zachary Turner54695a32016-08-29 19:58:14 +00002492 while (!value.empty())
Jason Molenda545304d2015-12-18 00:45:35 +00002493 {
Zachary Turner54695a32016-08-29 19:58:14 +00002494 llvm::StringRef pc_str;
2495 std::tie(pc_str, value) = value.split(',');
2496 if (pc_str.getAsInteger(16, pc))
2497 pc = LLDB_INVALID_ADDRESS;
2498 m_thread_pcs.push_back(pc);
Jason Molenda545304d2015-12-18 00:45:35 +00002499 }
Jason Molenda545304d2015-12-18 00:45:35 +00002500 }
Greg Clayton2e309072015-07-17 23:42:28 +00002501 else if (key.compare("jstopinfo") == 0)
Greg Claytona5801ad2015-07-15 22:59:03 +00002502 {
Zachary Turner54695a32016-08-29 19:58:14 +00002503 StringExtractor json_extractor(value);
2504 std::string json;
Greg Claytona5801ad2015-07-15 22:59:03 +00002505 // Now convert the HEX bytes into a string value
Zachary Turner54695a32016-08-29 19:58:14 +00002506 json_extractor.GetHexByteString(json);
Greg Claytona5801ad2015-07-15 22:59:03 +00002507
2508 // This JSON contains thread IDs and thread stop info for all threads.
2509 // It doesn't contain expedited registers, memory or queue info.
Zachary Turner54695a32016-08-29 19:58:14 +00002510 m_jstopinfo_sp = StructuredData::ParseJSON(json);
Greg Claytona5801ad2015-07-15 22:59:03 +00002511 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002512 else if (key.compare("hexname") == 0)
Greg Claytonde9d0492011-01-08 03:17:57 +00002513 {
Zachary Turner54695a32016-08-29 19:58:14 +00002514 StringExtractor name_extractor(value);
2515 std::string name;
Greg Claytonde9d0492011-01-08 03:17:57 +00002516 // Now convert the HEX bytes into a string value
Zachary Turner54695a32016-08-29 19:58:14 +00002517 name_extractor.GetHexByteString(thread_name);
Greg Claytonde9d0492011-01-08 03:17:57 +00002518 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002519 else if (key.compare("name") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002520 {
Zachary Turner54695a32016-08-29 19:58:14 +00002521 thread_name = value;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002522 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002523 else if (key.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002524 {
Zachary Turner54695a32016-08-29 19:58:14 +00002525 value.getAsInteger(16, thread_dispatch_qaddr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002526 }
Jason Molenda77f89352016-01-12 07:09:16 +00002527 else if (key.compare("dispatch_queue_t") == 0)
2528 {
2529 queue_vars_valid = true;
Zachary Turner54695a32016-08-29 19:58:14 +00002530 value.getAsInteger(16, dispatch_queue_t);
Jason Molenda77f89352016-01-12 07:09:16 +00002531 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002532 else if (key.compare("qname") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002533 {
2534 queue_vars_valid = true;
Zachary Turner54695a32016-08-29 19:58:14 +00002535 StringExtractor name_extractor(value);
Greg Clayton0b90be12015-06-23 21:27:50 +00002536 // Now convert the HEX bytes into a string value
Zachary Turner54695a32016-08-29 19:58:14 +00002537 name_extractor.GetHexByteString(queue_name);
Greg Clayton0b90be12015-06-23 21:27:50 +00002538 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002539 else if (key.compare("qkind") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002540 {
Zachary Turner54695a32016-08-29 19:58:14 +00002541 queue_kind = llvm::StringSwitch<QueueKind>(value)
2542 .Case("serial", eQueueKindSerial)
2543 .Case("concurrent", eQueueKindConcurrent)
2544 .Default(eQueueKindUnknown);
2545 queue_vars_valid = queue_kind != eQueueKindUnknown;
Greg Clayton0b90be12015-06-23 21:27:50 +00002546 }
Jason Molenda26d84e82016-01-08 00:20:48 +00002547 else if (key.compare("qserialnum") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002548 {
Zachary Turner54695a32016-08-29 19:58:14 +00002549 if (!value.getAsInteger(0, queue_serial_number))
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002550 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002551 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002552 else if (key.compare("reason") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002553 {
Zachary Turner54695a32016-08-29 19:58:14 +00002554 reason = value;
Greg Claytona658fd22011-06-04 01:26:29 +00002555 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002556 else if (key.compare("description") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002557 {
Zachary Turner54695a32016-08-29 19:58:14 +00002558 StringExtractor desc_extractor(value);
Greg Claytona658fd22011-06-04 01:26:29 +00002559 // Now convert the HEX bytes into a string value
Zachary Turner54695a32016-08-29 19:58:14 +00002560 desc_extractor.GetHexByteString(description);
Greg Claytona658fd22011-06-04 01:26:29 +00002561 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002562 else if (key.compare("memory") == 0)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002563 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002564 // Expedited memory. GDB servers can choose to send back expedited memory
2565 // that can populate the L1 memory cache in the process so that things like
2566 // the frame pointer backchain can be expedited. This will help stack
2567 // backtracing be more efficient by not having to send as many memory read
2568 // requests down the remote GDB server.
Chaoren Lin7a306082015-06-23 03:17:01 +00002569
Greg Clayton358cf1e2015-06-25 21:46:34 +00002570 // Key/value pair format: memory:<addr>=<bytes>;
2571 // <addr> is a number whose base will be interpreted by the prefix:
2572 // "0x[0-9a-fA-F]+" for hex
2573 // "0[0-7]+" for octal
2574 // "[1-9]+" for decimal
2575 // <bytes> is native endian ASCII hex bytes just like the register values
Zachary Turner54695a32016-08-29 19:58:14 +00002576 llvm::StringRef addr_str, bytes_str;
2577 std::tie(addr_str, bytes_str) = value.split('=');
2578 if (!addr_str.empty() && !bytes_str.empty())
Greg Clayton358cf1e2015-06-25 21:46:34 +00002579 {
Zachary Turner54695a32016-08-29 19:58:14 +00002580 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2581 if (!addr_str.getAsInteger(0, mem_cache_addr))
Greg Clayton3e06bd92011-01-09 21:07:35 +00002582 {
Zachary Turner54695a32016-08-29 19:58:14 +00002583 StringExtractor bytes(bytes_str);
2584 const size_t byte_size = bytes.GetBytesLeft() / 2;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002585 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
Zachary Turnerd08f09c2016-08-30 18:12:11 +00002586 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetData(), 0);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002587 if (bytes_copied == byte_size)
2588 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
Greg Clayton3e06bd92011-01-09 21:07:35 +00002589 }
2590 }
2591 }
Jaydeep Patil725666c2015-08-13 03:46:01 +00002592 else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 || key.compare("awatch") == 0)
2593 {
2594 // Support standard GDB remote stop reply packet 'TAAwatch:addr'
Zachary Turner54695a32016-08-29 19:58:14 +00002595 lldb::addr_t wp_addr = LLDB_INVALID_ADDRESS;
2596 value.getAsInteger(16, wp_addr);
2597
Jaydeep Patil725666c2015-08-13 03:46:01 +00002598 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2599 uint32_t wp_index = LLDB_INVALID_INDEX32;
2600
2601 if (wp_sp)
2602 wp_index = wp_sp->GetHardwareIndex();
2603
2604 reason = "watchpoint";
2605 StreamString ostr;
2606 ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
2607 description = ostr.GetString().c_str();
2608 }
Stephane Sezer2618e912015-08-21 16:51:56 +00002609 else if (key.compare("library") == 0)
2610 {
2611 LoadModules();
2612 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002613 else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1]))
2614 {
Zachary Turner54695a32016-08-29 19:58:14 +00002615 uint32_t reg = UINT32_MAX;
2616 if (!key.getAsInteger(16, reg))
Greg Clayton358cf1e2015-06-25 21:46:34 +00002617 expedited_register_map[reg] = std::move(value);
2618 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002619 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002620
Bhushan D. Attarde1e271df2015-07-24 04:06:20 +00002621 if (tid == LLDB_INVALID_THREAD_ID)
2622 {
Ed Maste81b4c5f2016-01-04 01:43:47 +00002623 // 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 +00002624 // thread information. So update the thread list and choose the first one.
2625 UpdateThreadIDList ();
Ed Maste81b4c5f2016-01-04 01:43:47 +00002626
Bhushan D. Attarde1e271df2015-07-24 04:06:20 +00002627 if (!m_thread_ids.empty ())
2628 {
2629 tid = m_thread_ids.front ();
2630 }
2631 }
2632
Greg Clayton358cf1e2015-06-25 21:46:34 +00002633 ThreadSP thread_sp = SetThreadStopInfo (tid,
2634 expedited_register_map,
2635 signo,
2636 thread_name,
2637 reason,
2638 description,
2639 exc_type,
2640 exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002641 thread_dispatch_qaddr,
2642 queue_vars_valid,
Jason Molenda77f89352016-01-12 07:09:16 +00002643 associated_with_dispatch_queue,
2644 dispatch_queue_t,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002645 queue_name,
2646 queue_kind,
Jason Molenda26d84e82016-01-08 00:20:48 +00002647 queue_serial_number);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002648
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002649 return eStateStopped;
2650 }
2651 break;
2652
2653 case 'W':
Todd Fialaff6131a2014-05-19 04:57:23 +00002654 case 'X':
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002655 // process exited
2656 return eStateExited;
2657
2658 default:
2659 break;
2660 }
2661 return eStateInvalid;
2662}
2663
2664void
2665ProcessGDBRemote::RefreshStateAfterStop ()
2666{
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00002667 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
2668
Greg Clayton9e920902012-04-10 02:25:43 +00002669 m_thread_ids.clear();
Jason Molenda545304d2015-12-18 00:45:35 +00002670 m_thread_pcs.clear();
Greg Clayton9e920902012-04-10 02:25:43 +00002671 // Set the thread stop info. It might have a "threads" key whose value is
2672 // a list of all thread IDs in the current process, so m_thread_ids might
2673 // get set.
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002674
2675 // Scope for the lock
2676 {
2677 // Lock the thread stack while we access it
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +00002678 std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002679 // Get the number of stop packets on the stack
2680 int nItems = m_stop_packet_stack.size();
2681 // Iterate over them
2682 for (int i = 0; i < nItems; i++)
2683 {
2684 // Get the thread stop info
2685 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2686 // Process thread stop info
2687 SetThreadStopInfo(stop_info);
2688 }
2689 // Clear the thread stop stack
2690 m_stop_packet_stack.clear();
2691 }
2692
Greg Clayton9e920902012-04-10 02:25:43 +00002693 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2694 if (m_thread_ids.empty())
2695 {
2696 // No, we need to fetch the thread list manually
2697 UpdateThreadIDList();
2698 }
2699
Ewan Crawford78baa192015-05-13 09:18:18 +00002700 // If we have queried for a default thread id
2701 if (m_initial_tid != LLDB_INVALID_THREAD_ID)
2702 {
2703 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2704 m_initial_tid = LLDB_INVALID_THREAD_ID;
2705 }
2706
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002707 // Let all threads recover from stopping and do any clean up based
2708 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002709 m_thread_list_real.RefreshStateAfterStop();
Ed Maste81b4c5f2016-01-04 01:43:47 +00002710
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002711}
2712
2713Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002714ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002715{
2716 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002717
Greg Clayton513c26c2011-01-29 07:10:55 +00002718 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002719 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002720 // We are being asked to halt during an attach. We need to just close
2721 // our file handle and debugserver will go away, and we can be done...
2722 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00002723 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002724 else
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00002725 caused_stop = m_gdb_comm.Interrupt();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002726 return error;
2727}
2728
2729Error
Jim Inghamacff8952013-05-02 00:27:30 +00002730ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002731{
2732 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002733 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00002734 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00002735 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
Ed Maste81b4c5f2016-01-04 01:43:47 +00002736
Jim Inghamacff8952013-05-02 00:27:30 +00002737 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002738 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002739 {
Jim Inghamacff8952013-05-02 00:27:30 +00002740 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002741 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
2742 else
Jim Inghamacff8952013-05-02 00:27:30 +00002743 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00002744 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00002745
Jim Inghamacff8952013-05-02 00:27:30 +00002746 if (!error.Success())
2747 return error;
2748
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002749 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00002750 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002751
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002752 SetPrivateState (eStateDetached);
2753 ResumePrivateStateThread();
2754
2755 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00002756 return error;
2757}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002758
Eugene Zelenko0722f082015-10-24 01:28:05 +00002759
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002760Error
2761ProcessGDBRemote::DoDestroy ()
2762{
2763 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002764 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002765 if (log)
2766 log->Printf ("ProcessGDBRemote::DoDestroy()");
2767
Jim Ingham43c555d2012-07-04 00:35:43 +00002768 // There is a bug in older iOS debugservers where they don't shut down the process
2769 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
2770 // this can cause problems with restarting. So we check to see if any of our threads are stopped
2771 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
2772 // destroy it again.
2773 //
2774 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
2775 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
2776 // the debugservers with this bug are equal. There really should be a better way to test this!
2777 //
2778 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
2779 // get called here to destroy again and we're still at a breakpoint or exception, then we should
2780 // just do the straight-forward kill.
2781 //
2782 // And of course, if we weren't able to stop the process by the time we get here, it isn't
2783 // necessary (or helpful) to do any of this.
2784
2785 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
2786 {
2787 PlatformSP platform_sp = GetTarget().GetPlatform();
Ed Maste81b4c5f2016-01-04 01:43:47 +00002788
Jim Ingham43c555d2012-07-04 00:35:43 +00002789 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2790 if (platform_sp
2791 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00002792 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00002793 {
2794 if (m_destroy_tried_resuming)
2795 {
2796 if (log)
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002797 log->PutCString ("ProcessGDBRemote::DoDestroy() - Tried resuming to destroy once already, not doing it again.");
Jim Ingham43c555d2012-07-04 00:35:43 +00002798 }
2799 else
Ed Maste81b4c5f2016-01-04 01:43:47 +00002800 {
Jim Ingham43c555d2012-07-04 00:35:43 +00002801 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
2802 // but we really need it to happen here and it doesn't matter if we do it twice.
2803 m_thread_list.DiscardThreadPlans();
2804 DisableAllBreakpointSites();
Ed Maste81b4c5f2016-01-04 01:43:47 +00002805
Jim Ingham43c555d2012-07-04 00:35:43 +00002806 bool stop_looks_like_crash = false;
2807 ThreadList &threads = GetThreadList();
Ed Maste81b4c5f2016-01-04 01:43:47 +00002808
Jim Ingham43c555d2012-07-04 00:35:43 +00002809 {
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00002810 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
Ed Maste81b4c5f2016-01-04 01:43:47 +00002811
Jim Ingham43c555d2012-07-04 00:35:43 +00002812 size_t num_threads = threads.GetSize();
2813 for (size_t i = 0; i < num_threads; i++)
2814 {
2815 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002816 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002817 StopReason reason = eStopReasonInvalid;
2818 if (stop_info_sp)
2819 reason = stop_info_sp->GetStopReason();
2820 if (reason == eStopReasonBreakpoint
2821 || reason == eStopReasonException)
2822 {
2823 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002824 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
2825 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00002826 stop_info_sp->GetDescription());
2827 stop_looks_like_crash = true;
2828 break;
2829 }
2830 }
2831 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00002832
Jim Ingham43c555d2012-07-04 00:35:43 +00002833 if (stop_looks_like_crash)
2834 {
2835 if (log)
2836 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
2837 m_destroy_tried_resuming = true;
Ed Maste81b4c5f2016-01-04 01:43:47 +00002838
2839 // 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 +00002840 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
2841 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
2842 // have to run the risk of letting those threads proceed a bit.
Ed Maste81b4c5f2016-01-04 01:43:47 +00002843
Jim Ingham43c555d2012-07-04 00:35:43 +00002844 {
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00002845 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
Ed Maste81b4c5f2016-01-04 01:43:47 +00002846
Jim Ingham43c555d2012-07-04 00:35:43 +00002847 size_t num_threads = threads.GetSize();
2848 for (size_t i = 0; i < num_threads; i++)
2849 {
2850 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002851 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002852 StopReason reason = eStopReasonInvalid;
2853 if (stop_info_sp)
2854 reason = stop_info_sp->GetStopReason();
2855 if (reason != eStopReasonBreakpoint
2856 && reason != eStopReasonException)
2857 {
2858 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002859 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
2860 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00002861 thread_sp->SetResumeState(eStateSuspended);
2862 }
2863 }
2864 }
2865 Resume ();
Jason Molendaede31932015-04-17 05:01:58 +00002866 return Destroy(false);
Jim Ingham43c555d2012-07-04 00:35:43 +00002867 }
2868 }
2869 }
2870 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00002871
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002872 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00002873 int exit_status = SIGABRT;
2874 std::string exit_string;
2875
Greg Clayton6ed95942011-01-22 07:12:45 +00002876 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002877 {
Jim Inghamaab78372011-10-28 01:11:35 +00002878 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00002879 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002880 StringExtractorGDBRemote response;
2881 bool send_async = true;
Tamas Berghammer912800c2015-02-24 10:23:39 +00002882 GDBRemoteCommunication::ScopedTimeout (m_gdb_comm, 3);
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002883
Greg Clayton3dedae12013-12-06 21:45:27 +00002884 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton513c26c2011-01-29 07:10:55 +00002885 {
2886 char packet_cmd = response.GetChar(0);
2887
2888 if (packet_cmd == 'W' || packet_cmd == 'X')
2889 {
Jim Inghameac0aa42014-02-21 22:36:11 +00002890#if defined(__APPLE__)
Jason Molenda17b45392016-06-23 04:24:16 +00002891 // 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 +00002892 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill
Jason Molenda17b45392016-06-23 04:24:16 +00002893 // 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 +00002894 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap
2895 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of
2896 // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2897 // Anyway, so call waitpid here to finally reap it.
2898 PlatformSP platform_sp(GetTarget().GetPlatform());
2899 if (platform_sp && platform_sp->IsHost())
2900 {
2901 int status;
2902 ::pid_t reap_pid;
2903 reap_pid = waitpid (GetID(), &status, WNOHANG);
2904 if (log)
2905 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2906 }
2907#endif
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002908 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002909 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00002910 exit_status = response.GetHexU8();
2911 }
2912 else
2913 {
2914 if (log)
2915 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2916 exit_string.assign("got unexpected response to k packet: ");
2917 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00002918 }
2919 }
2920 else
2921 {
Jim Inghambabfc382012-06-06 00:32:39 +00002922 if (log)
2923 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2924 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00002925 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002926 }
Jim Inghambabfc382012-06-06 00:32:39 +00002927 else
2928 {
2929 if (log)
Ed Masteb3a53332014-03-17 17:05:22 +00002930 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching");
Jim Inghamcfc09352012-07-27 23:57:19 +00002931 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00002932 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002933 }
Jim Inghambabfc382012-06-06 00:32:39 +00002934 else
2935 {
2936 // If we missed setting the exit status on the way out, do it here.
2937 // NB set exit status can be called multiple times, the first one sets the status.
2938 exit_string.assign("destroying when not connected to debugserver");
2939 }
2940
2941 SetExitStatus(exit_status, exit_string.c_str());
2942
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002943 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002944 KillDebugserverProcess ();
2945 return error;
2946}
2947
Greg Clayton8cda7f02013-05-21 21:55:59 +00002948void
2949ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2950{
Greg Clayton8cda7f02013-05-21 21:55:59 +00002951 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2952 if (did_exec)
2953 {
2954 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2955 if (log)
2956 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2957
2958 m_thread_list_real.Clear();
2959 m_thread_list.Clear();
2960 BuildDynamicRegisterInfo (true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002961 m_gdb_comm.ResetDiscoverableSettings (did_exec);
Greg Clayton8cda7f02013-05-21 21:55:59 +00002962 }
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002963
2964 // Scope the lock
2965 {
2966 // Lock the thread stack while we access it
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +00002967 std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
Greg Clayton2e309072015-07-17 23:42:28 +00002968
2969 // We are are not using non-stop mode, there can only be one last stop
2970 // reply packet, so clear the list.
2971 if (GetTarget().GetNonStopModeEnabled() == false)
2972 m_stop_packet_stack.clear();
2973
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002974 // Add this stop packet to the stop packet stack
2975 // This stack will get popped and examined when we switch to the
2976 // Stopped state
2977 m_stop_packet_stack.push_back(response);
2978 }
Greg Clayton8cda7f02013-05-21 21:55:59 +00002979}
2980
Chaoren Linc963a222015-09-01 16:58:45 +00002981void
2982ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp)
2983{
2984 Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
2985}
2986
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002987//------------------------------------------------------------------
2988// Process Queries
2989//------------------------------------------------------------------
2990
2991bool
2992ProcessGDBRemote::IsAlive ()
2993{
Jason Molenda1d3b3562015-11-05 23:54:29 +00002994 return m_gdb_comm.IsConnected() && Process::IsAlive();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002995}
2996
2997addr_t
2998ProcessGDBRemote::GetImageInfoAddress()
2999{
Aidan Doddsc0c83852015-05-08 09:36:31 +00003000 // request the link map address via the $qShlibInfoAddr packet
3001 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
3002
3003 // the loaded module list can also provides a link map address
3004 if (addr == LLDB_INVALID_ADDRESS)
3005 {
Stephane Sezer87b0fe02016-01-12 19:02:41 +00003006 LoadedModuleInfoList list;
Aidan Doddsc0c83852015-05-08 09:36:31 +00003007 if (GetLoadedModuleList (list).Success())
3008 addr = list.m_link_map;
3009 }
3010
3011 return addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003012}
3013
Greg Clayton2e309072015-07-17 23:42:28 +00003014void
3015ProcessGDBRemote::WillPublicStop ()
3016{
3017 // See if the GDB remote client supports the JSON threads info.
3018 // If so, we gather stop info for all threads, expedited registers,
3019 // expedited memory, runtime queue information (iOS and MacOSX only),
3020 // and more. Expediting memory will help stack backtracing be much
3021 // faster. Expediting registers will make sure we don't have to read
3022 // the thread registers for GPRs.
3023 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
3024
3025 if (m_jthreadsinfo_sp)
3026 {
3027 // Now set the stop info for each thread and also expedite any registers
3028 // and memory that was in the jThreadsInfo response.
3029 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
3030 if (thread_infos)
3031 {
3032 const size_t n = thread_infos->GetSize();
3033 for (size_t i=0; i<n; ++i)
3034 {
3035 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
3036 if (thread_dict)
3037 SetThreadStopInfo(thread_dict);
3038 }
3039 }
3040 }
3041}
3042
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003043//------------------------------------------------------------------
3044// Process Memory
3045//------------------------------------------------------------------
3046size_t
3047ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
3048{
Jason Molenda6076bf42014-05-06 04:34:52 +00003049 GetMaxMemorySize ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003050 if (size > m_max_memory_size)
3051 {
3052 // Keep memory read sizes down to a sane limit. This function will be
Ed Maste81b4c5f2016-01-04 01:43:47 +00003053 // called multiple times in order to complete the task by
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003054 // lldb_private::Process so it is ok to do this.
3055 size = m_max_memory_size;
3056 }
3057
3058 char packet[64];
Jason Molenda6076bf42014-05-06 04:34:52 +00003059 int packet_len;
3060 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
Pavel Labath3bf11252015-10-14 12:59:37 +00003061 packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64,
3062 binary_memory_read ? 'x' : 'm', (uint64_t)addr, (uint64_t)size);
Andy Gibbsa297a972013-06-19 19:04:53 +00003063 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003064 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003065 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003066 {
Greg Clayton576d8832011-03-22 04:00:09 +00003067 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003068 {
3069 error.Clear();
Jason Molenda6076bf42014-05-06 04:34:52 +00003070 if (binary_memory_read)
3071 {
3072 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any
3073 // 0x7d character escaping that was present in the packet
3074
3075 size_t data_received_size = response.GetBytesLeft();
3076 if (data_received_size > size)
3077 {
3078 // Don't write past the end of BUF if the remote debug server gave us too
3079 // much data for some reason.
3080 data_received_size = size;
3081 }
3082 memcpy (buf, response.GetStringRef().data(), data_received_size);
3083 return data_received_size;
3084 }
3085 else
3086 {
Zachary Turnerd08f09c2016-08-30 18:12:11 +00003087 return response.GetHexBytes(llvm::MutableArrayRef<uint8_t>((uint8_t*)buf, size), '\xdd');
Jason Molenda6076bf42014-05-06 04:34:52 +00003088 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003089 }
Greg Clayton576d8832011-03-22 04:00:09 +00003090 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00003091 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00003092 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00003093 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003094 else
Greg Clayton9944cd72012-09-19 01:46:31 +00003095 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003096 }
3097 else
3098 {
Jim Ingham35579dd2013-06-03 19:34:01 +00003099 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003100 }
3101 return 0;
3102}
3103
3104size_t
3105ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
3106{
Jason Molenda6076bf42014-05-06 04:34:52 +00003107 GetMaxMemorySize ();
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00003108 if (size > m_max_memory_size)
3109 {
3110 // Keep memory read sizes down to a sane limit. This function will be
Ed Maste81b4c5f2016-01-04 01:43:47 +00003111 // called multiple times in order to complete the task by
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00003112 // lldb_private::Process so it is ok to do this.
3113 size = m_max_memory_size;
3114 }
3115
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003116 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00003117 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Bruce Mitchener9ccb9702015-11-07 04:40:13 +00003118 packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(), endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003119 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003120 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003121 {
Greg Clayton576d8832011-03-22 04:00:09 +00003122 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003123 {
3124 error.Clear();
3125 return size;
3126 }
Greg Clayton576d8832011-03-22 04:00:09 +00003127 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00003128 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00003129 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00003130 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003131 else
Greg Clayton9944cd72012-09-19 01:46:31 +00003132 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 +00003133 }
3134 else
3135 {
Jim Ingham35579dd2013-06-03 19:34:01 +00003136 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003137 }
3138 return 0;
3139}
3140
3141lldb::addr_t
3142ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
3143{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003144 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_EXPRESSIONS));
Greg Clayton2a48f522011-05-14 01:50:35 +00003145 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
Ed Maste81b4c5f2016-01-04 01:43:47 +00003146
Greg Claytoncec91ef2016-02-26 01:20:20 +00003147 if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo)
Greg Clayton2a48f522011-05-14 01:50:35 +00003148 {
Greg Claytoncec91ef2016-02-26 01:20:20 +00003149 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
3150 if (allocated_addr != LLDB_INVALID_ADDRESS || m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes)
3151 return allocated_addr;
3152 }
Greg Clayton2a48f522011-05-14 01:50:35 +00003153
Greg Claytoncec91ef2016-02-26 01:20:20 +00003154 if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo)
3155 {
3156 // Call mmap() to create memory in the inferior..
3157 unsigned prot = 0;
3158 if (permissions & lldb::ePermissionsReadable)
3159 prot |= eMmapProtRead;
3160 if (permissions & lldb::ePermissionsWritable)
3161 prot |= eMmapProtWrite;
3162 if (permissions & lldb::ePermissionsExecutable)
3163 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00003164
Greg Claytoncec91ef2016-02-26 01:20:20 +00003165 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
3166 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
3167 m_addr_to_mmap_size[allocated_addr] = size;
3168 else
3169 {
3170 allocated_addr = LLDB_INVALID_ADDRESS;
3171 if (log)
3172 log->Printf ("ProcessGDBRemote::%s no direct stub support for memory allocation, and InferiorCallMmap also failed - is stub missing register context save/restore capability?", __FUNCTION__);
3173 }
Greg Clayton2a48f522011-05-14 01:50:35 +00003174 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00003175
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003176 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00003177 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003178 else
3179 error.Clear();
3180 return allocated_addr;
3181}
3182
3183Error
Ed Maste81b4c5f2016-01-04 01:43:47 +00003184ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
Greg Clayton46fb5582011-11-18 07:03:08 +00003185 MemoryRegionInfo &region_info)
3186{
Ed Maste81b4c5f2016-01-04 01:43:47 +00003187
Greg Clayton46fb5582011-11-18 07:03:08 +00003188 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
3189 return error;
3190}
3191
3192Error
Johnny Chen64637202012-05-23 21:09:52 +00003193ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
3194{
Ed Maste81b4c5f2016-01-04 01:43:47 +00003195
Johnny Chen64637202012-05-23 21:09:52 +00003196 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
3197 return error;
3198}
3199
3200Error
Enrico Granataf04a2192012-07-13 23:18:48 +00003201ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
3202{
Jaydeep Patil725666c2015-08-13 03:46:01 +00003203 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after, GetTarget().GetArchitecture()));
Enrico Granataf04a2192012-07-13 23:18:48 +00003204 return error;
3205}
3206
3207Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003208ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
3209{
Ed Maste81b4c5f2016-01-04 01:43:47 +00003210 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00003211 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
3212
3213 switch (supported)
3214 {
3215 case eLazyBoolCalculate:
Ed Maste81b4c5f2016-01-04 01:43:47 +00003216 // We should never be deallocating memory without allocating memory
Greg Clayton70b57652011-05-15 01:25:55 +00003217 // first so we should never get eLazyBoolCalculate
3218 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
3219 break;
3220
3221 case eLazyBoolYes:
3222 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00003223 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003224 break;
Ed Maste81b4c5f2016-01-04 01:43:47 +00003225
Greg Clayton70b57652011-05-15 01:25:55 +00003226 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003227 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00003228 {
3229 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003230 if (pos != m_addr_to_mmap_size.end() &&
3231 InferiorCallMunmap(this, addr, pos->second))
3232 m_addr_to_mmap_size.erase (pos);
3233 else
Daniel Malead01b2952012-11-29 21:49:15 +00003234 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003235 }
3236 break;
3237 }
3238
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003239 return error;
3240}
3241
Eugene Zelenko0722f082015-10-24 01:28:05 +00003242
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003243//------------------------------------------------------------------
3244// Process STDIO
3245//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003246size_t
3247ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
3248{
3249 if (m_stdio_communication.IsConnected())
3250 {
3251 ConnectionStatus status;
3252 m_stdio_communication.Write(src, src_len, status, NULL);
3253 }
Vince Harrondf3f00f2015-02-10 21:09:04 +00003254 else if (m_stdin_forward)
Vince Harrone0be4252015-02-06 18:32:57 +00003255 {
3256 m_gdb_comm.SendStdinNotification(src, src_len);
3257 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003258 return 0;
3259}
3260
3261Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003262ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003263{
3264 Error error;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003265 assert(bp_site != NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003266
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003267 // Get logging info
3268 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003269 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003270
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003271 // Get the breakpoint address
3272 const addr_t addr = bp_site->GetLoadAddress();
3273
3274 // Log that a breakpoint was requested
3275 if (log)
3276 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
3277
3278 // Breakpoint already exists and is enabled
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003279 if (bp_site->IsEnabled())
3280 {
3281 if (log)
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003282 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 +00003283 return error;
3284 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003285
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003286 // Get the software breakpoint trap opcode size
3287 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3288
3289 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
3290 // is supported by the remote stub. These are set to true by default, and later set to false
3291 // only after we receive an unimplemented response when sending a breakpoint packet. This means
3292 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
3293 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
3294 // indicates if the user specifically asked for hardware breakpoints. If true then we will
3295 // skip over software breakpoints.
3296 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
3297 {
3298 // Try to send off a software breakpoint packet ($Z0)
Jim Ingham906d91e2016-05-19 02:13:44 +00003299 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size);
3300 if (error_no == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003301 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003302 // The breakpoint was placed successfully
3303 bp_site->SetEnabled(true);
3304 bp_site->SetType(BreakpointSite::eExternal);
Greg Claytoneb023e72013-10-11 19:48:25 +00003305 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003306 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003307
3308 // SendGDBStoppointTypePacket() will return an error if it was unable to set this
3309 // breakpoint. We need to differentiate between a error specific to placing this breakpoint
3310 // or if we have learned that this breakpoint type is unsupported. To do this, we
3311 // must test the support boolean for this breakpoint type to see if it now indicates that
3312 // this breakpoint type is unsupported. If they are still supported then we should return
3313 // with the error code. If they are now unsupported, then we would like to fall through
3314 // and try another form of breakpoint.
3315 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
Jim Ingham906d91e2016-05-19 02:13:44 +00003316 {
3317 if (error_no != UINT8_MAX)
3318 error.SetErrorStringWithFormat("error: %d sending the breakpoint request", errno);
3319 else
3320 error.SetErrorString("error sending the breakpoint request");
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003321 return error;
Jim Ingham906d91e2016-05-19 02:13:44 +00003322 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003323
3324 // We reach here when software breakpoints have been found to be unsupported. For future
3325 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
3326 // known not to be supported.
3327 if (log)
3328 log->Printf("Software breakpoints are unsupported");
3329
3330 // So we will fall through and try a hardware breakpoint
3331 }
3332
3333 // The process of setting a hardware breakpoint is much the same as above. We check the
3334 // supported boolean for this breakpoint type, and if it is thought to be supported then we
3335 // will try to set this breakpoint with a hardware breakpoint.
3336 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3337 {
3338 // Try to send off a hardware breakpoint packet ($Z1)
Jim Ingham906d91e2016-05-19 02:13:44 +00003339 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size);
3340 if (error_no == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003341 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003342 // The breakpoint was placed successfully
3343 bp_site->SetEnabled(true);
3344 bp_site->SetType(BreakpointSite::eHardware);
3345 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003346 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003347
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003348 // Check if the error was something other then an unsupported breakpoint type
3349 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3350 {
3351 // Unable to set this hardware breakpoint
Jim Ingham906d91e2016-05-19 02:13:44 +00003352 if (error_no != UINT8_MAX)
3353 error.SetErrorStringWithFormat("error: %d sending the hardware breakpoint request "
3354 "(hardware breakpoint resources might be exhausted or unavailable)",
3355 error_no);
3356 else
3357 error.SetErrorString("error sending the hardware breakpoint request (hardware breakpoint resources "
3358 "might be exhausted or unavailable)");
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003359 return error;
3360 }
3361
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003362 // We will reach here when the stub gives an unsupported response to a hardware breakpoint
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003363 if (log)
3364 log->Printf("Hardware breakpoints are unsupported");
3365
3366 // Finally we will falling through to a #trap style breakpoint
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003367 }
3368
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003369 // Don't fall through when hardware breakpoints were specifically requested
3370 if (bp_site->HardwareRequired())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003371 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003372 error.SetErrorString("hardware breakpoints are not supported");
3373 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003374 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003375
3376 // As a last resort we want to place a manual breakpoint. An instruction
3377 // is placed into the process memory using memory write packets.
3378 return EnableSoftwareBreakpoint(bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003379}
3380
3381Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003382ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003383{
3384 Error error;
3385 assert (bp_site != NULL);
3386 addr_t addr = bp_site->GetLoadAddress();
3387 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00003388 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003389 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003390 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003391
3392 if (bp_site->IsEnabled())
3393 {
3394 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
3395
Greg Clayton8b82f082011-04-12 05:54:46 +00003396 BreakpointSite::Type bp_type = bp_site->GetType();
3397 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003398 {
Greg Clayton8b82f082011-04-12 05:54:46 +00003399 case BreakpointSite::eSoftware:
3400 error = DisableSoftwareBreakpoint (bp_site);
3401 break;
3402
3403 case BreakpointSite::eHardware:
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003404 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003405 error.SetErrorToGenericError();
3406 break;
3407
3408 case BreakpointSite::eExternal:
Jim Inghama04ef752014-03-07 11:18:02 +00003409 {
3410 GDBStoppointType stoppoint_type;
3411 if (bp_site->IsHardware())
3412 stoppoint_type = eBreakpointHardware;
3413 else
3414 stoppoint_type = eBreakpointSoftware;
Ed Maste81b4c5f2016-01-04 01:43:47 +00003415
Jim Inghama04ef752014-03-07 11:18:02 +00003416 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003417 error.SetErrorToGenericError();
Jim Inghama04ef752014-03-07 11:18:02 +00003418 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003419 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003420 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003421 if (error.Success())
3422 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003423 }
3424 else
3425 {
3426 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003427 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 +00003428 return error;
3429 }
3430
3431 if (error.Success())
3432 error.SetErrorToGenericError();
3433 return error;
3434}
3435
Johnny Chen11309a32011-09-06 22:38:36 +00003436// Pre-requisite: wp != NULL.
3437static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00003438GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00003439{
3440 assert(wp);
3441 bool watch_read = wp->WatchpointRead();
3442 bool watch_write = wp->WatchpointWrite();
3443
3444 // watch_read and watch_write cannot both be false.
3445 assert(watch_read || watch_write);
3446 if (watch_read && watch_write)
3447 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00003448 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00003449 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00003450 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00003451 return eWatchpointWrite;
3452}
3453
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003454Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003455ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003456{
3457 Error error;
3458 if (wp)
3459 {
3460 user_id_t watchID = wp->GetID();
3461 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00003462 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003463 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003464 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003465 if (wp->IsEnabled())
3466 {
3467 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003468 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 +00003469 return error;
3470 }
Johnny Chen11309a32011-09-06 22:38:36 +00003471
3472 GDBStoppointType type = GetGDBStoppointType(wp);
3473 // Pass down an appropriate z/Z packet...
3474 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003475 {
Johnny Chen11309a32011-09-06 22:38:36 +00003476 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
3477 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003478 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003479 return error;
3480 }
3481 else
3482 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003483 }
Johnny Chen11309a32011-09-06 22:38:36 +00003484 else
3485 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003486 }
3487 else
3488 {
Johnny Chen01a67862011-10-14 00:42:25 +00003489 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003490 }
3491 if (error.Success())
3492 error.SetErrorToGenericError();
3493 return error;
3494}
3495
3496Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003497ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003498{
3499 Error error;
3500 if (wp)
3501 {
3502 user_id_t watchID = wp->GetID();
3503
Greg Clayton5160ce52013-03-27 23:08:40 +00003504 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003505
3506 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00003507
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003508 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003509 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003510
Johnny Chen11309a32011-09-06 22:38:36 +00003511 if (!wp->IsEnabled())
3512 {
3513 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003514 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 +00003515 // See also 'class WatchpointSentry' within StopInfo.cpp.
3516 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
3517 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00003518 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003519 return error;
3520 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00003521
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003522 if (wp->IsHardware())
3523 {
Johnny Chen11309a32011-09-06 22:38:36 +00003524 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003525 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00003526 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
3527 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003528 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003529 return error;
3530 }
3531 else
Ed Maste81b4c5f2016-01-04 01:43:47 +00003532 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003533 }
3534 // TODO: clear software watchpoints if we implement them
3535 }
3536 else
3537 {
Johnny Chen01a67862011-10-14 00:42:25 +00003538 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003539 }
3540 if (error.Success())
3541 error.SetErrorToGenericError();
3542 return error;
3543}
3544
3545void
3546ProcessGDBRemote::Clear()
3547{
3548 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00003549 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003550 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003551}
3552
3553Error
3554ProcessGDBRemote::DoSignal (int signo)
3555{
3556 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00003557 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003558 if (log)
3559 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
3560
3561 if (!m_gdb_comm.SendAsyncSignal (signo))
3562 error.SetErrorStringWithFormat("failed to send signal %i", signo);
3563 return error;
3564}
3565
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003566Error
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00003567ProcessGDBRemote::EstablishConnectionIfNeeded (const ProcessInfo &process_info)
3568{
3569 // Make sure we aren't already connected?
3570 if (m_gdb_comm.IsConnected())
3571 return Error();
3572
3573 PlatformSP platform_sp (GetTarget ().GetPlatform ());
3574 if (platform_sp && !platform_sp->IsHost ())
3575 return Error("Lost debug server connection");
3576
3577 auto error = LaunchAndConnectToDebugserver (process_info);
3578 if (error.Fail())
3579 {
3580 const char *error_string = error.AsCString();
3581 if (error_string == nullptr)
3582 error_string = "unable to launch " DEBUGSERVER_BASENAME;
3583 }
3584 return error;
3585}
Greg Claytonc6c420f2016-08-12 16:46:18 +00003586#if defined (__APPLE__)
3587#define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1
3588#endif
3589
3590#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3591static bool SetCloexecFlag(int fd)
3592{
3593#if defined(FD_CLOEXEC)
3594 int flags = ::fcntl(fd, F_GETFD);
3595 if (flags == -1)
3596 return false;
3597 return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0);
3598#else
3599 return false;
3600#endif
3601}
3602#endif
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00003603
3604Error
Greg Clayton91a9b2472013-12-04 19:19:12 +00003605ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003606{
Pavel Labath998bdc52016-05-11 16:59:04 +00003607 using namespace std::placeholders; // For _1, _2, etc.
3608
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003609 Error error;
3610 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
3611 {
3612 // If we locate debugserver, keep that located version around
3613 static FileSpec g_debugserver_file_spec;
3614
Han Ming Ong84647042012-02-25 01:07:38 +00003615 ProcessLaunchInfo debugserver_launch_info;
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00003616 // Make debugserver run in its own session so signals generated by
3617 // special terminal key sequences (^C) don't affect debugserver.
3618 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3619
Pavel Labath194357c2016-05-12 11:10:01 +00003620 const std::weak_ptr<ProcessGDBRemote> this_wp = std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
3621 debugserver_launch_info.SetMonitorProcessCallback(std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3, _4),
Pavel Labath998bdc52016-05-11 16:59:04 +00003622 false);
Greg Clayton91a9b2472013-12-04 19:19:12 +00003623 debugserver_launch_info.SetUserID(process_info.GetUserID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003624
Greg Claytonfda4fab2014-01-10 22:24:11 +00003625
Greg Claytonc6c420f2016-08-12 16:46:18 +00003626 int communication_fd = -1;
3627#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3628 // Auto close the sockets we might open up unless everything goes OK. This
3629 // helps us not leak file descriptors when things go wrong.
3630 lldb_utility::CleanUp <int, int> our_socket(-1, -1, close);
3631 lldb_utility::CleanUp <int, int> gdb_socket(-1, -1, close);
3632
3633 // Use a socketpair on Apple for now until other platforms can verify it
3634 // works and is fast enough
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003635 {
Greg Claytonc6c420f2016-08-12 16:46:18 +00003636 int sockets[2]; /* the pair of socket descriptors */
3637 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1)
3638 {
3639 error.SetErrorToErrno();
3640 return error;
3641 }
3642
3643 our_socket.set(sockets[0]);
3644 gdb_socket.set(sockets[1]);
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003645 }
3646
Greg Claytonc6c420f2016-08-12 16:46:18 +00003647 // Don't let any child processes inherit our communication socket
3648 SetCloexecFlag(our_socket.get());
3649 communication_fd = gdb_socket.get();
3650#endif
3651
3652 error = m_gdb_comm.StartDebugserverProcess(nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info, nullptr, nullptr, communication_fd);
Greg Clayton91a9b2472013-12-04 19:19:12 +00003653
3654 if (error.Success ())
3655 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003656 else
Greg Clayton91a9b2472013-12-04 19:19:12 +00003657 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003658
3659 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytonc6c420f2016-08-12 16:46:18 +00003660 {
3661#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3662 // Our process spawned correctly, we can now set our connection to use our
3663 // end of the socket pair
3664 m_gdb_comm.SetConnection(new ConnectionFileDescriptor(our_socket.release(), true));
3665#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003666 StartAsyncThread ();
Greg Claytonc6c420f2016-08-12 16:46:18 +00003667 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00003668
Greg Clayton91a9b2472013-12-04 19:19:12 +00003669 if (error.Fail())
3670 {
3671 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
3672
3673 if (log)
3674 log->Printf("failed to start debugserver process: %s", error.AsCString());
3675 return error;
3676 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00003677
Greg Clayton00fe87b2013-12-05 22:58:22 +00003678 if (m_gdb_comm.IsConnected())
3679 {
3680 // Finish the connection process by doing the handshake without connecting (send NULL URL)
Greg Claytonc6c420f2016-08-12 16:46:18 +00003681 ConnectToDebugserver(NULL);
Greg Clayton00fe87b2013-12-05 22:58:22 +00003682 }
3683 else
3684 {
Greg Claytonc6c420f2016-08-12 16:46:18 +00003685 error.SetErrorString("connection failed");
Greg Clayton00fe87b2013-12-05 22:58:22 +00003686 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00003687
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003688 }
3689 return error;
3690}
3691
3692bool
Pavel Labath194357c2016-05-12 11:10:01 +00003693ProcessGDBRemote::MonitorDebugserverProcess(std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid,
Pavel Labath998bdc52016-05-11 16:59:04 +00003694 bool exited, // True if the process did exit
3695 int signo, // Zero for no signal
3696 int exit_status // Exit value of process if signal is zero
3697 )
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003698{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003699 // "debugserver_pid" argument passed in is the process ID for
3700 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00003701 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Pavel Labath194357c2016-05-12 11:10:01 +00003702 const bool handled = true;
Greg Claytone4e45922011-11-16 05:37:56 +00003703
Greg Clayton6779606a2011-01-22 23:43:18 +00003704 if (log)
Pavel Labath194357c2016-05-12 11:10:01 +00003705 log->Printf("ProcessGDBRemote::%s(process_wp, pid=%" PRIu64 ", signo=%i (0x%x), exit_status=%i)", __FUNCTION__,
3706 debugserver_pid, signo, signo, exit_status);
Greg Clayton6779606a2011-01-22 23:43:18 +00003707
Pavel Labath194357c2016-05-12 11:10:01 +00003708 std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
3709 if (log)
Saleem Abdulrasoolabdfc212016-05-15 18:18:13 +00003710 log->Printf("ProcessGDBRemote::%s(process = %p)", __FUNCTION__, static_cast<void *>(process_sp.get()));
Pavel Labath194357c2016-05-12 11:10:01 +00003711 if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
3712 return handled;
3713
3714 // Sleep for a half a second to make sure our inferior process has
3715 // time to set its exit status before we set it incorrectly when
3716 // both the debugserver and the inferior process shut down.
3717 usleep(500000);
3718 // If our process hasn't yet exited, debugserver might have died.
3719 // If the process did exit, then we are reaping it.
3720 const StateType state = process_sp->GetState();
3721
3722 if (state != eStateInvalid && state != eStateUnloaded && state != eStateExited && state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003723 {
Pavel Labath194357c2016-05-12 11:10:01 +00003724 char error_str[1024];
3725 if (signo)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003726 {
Pavel Labath194357c2016-05-12 11:10:01 +00003727 const char *signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
3728 if (signal_cstr)
3729 ::snprintf(error_str, sizeof(error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3730 else
3731 ::snprintf(error_str, sizeof(error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003732 }
Pavel Labath194357c2016-05-12 11:10:01 +00003733 else
3734 {
3735 ::snprintf(error_str, sizeof(error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x",
3736 exit_status);
3737 }
3738
3739 process_sp->SetExitStatus(-1, error_str);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003740 }
Pavel Labath194357c2016-05-12 11:10:01 +00003741 // Debugserver has exited we need to let our ProcessGDBRemote
3742 // know that it no longer has a debugserver instance
3743 process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3744 return handled;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003745}
3746
3747void
3748ProcessGDBRemote::KillDebugserverProcess ()
3749{
Greg Claytonfbb76342013-11-20 21:07:01 +00003750 m_gdb_comm.Disconnect();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003751 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3752 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003753 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003754 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3755 }
3756}
3757
3758void
3759ProcessGDBRemote::Initialize()
3760{
Davide Italianoc8d69822015-04-03 04:24:32 +00003761 static std::once_flag g_once_flag;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003762
Davide Italianoc8d69822015-04-03 04:24:32 +00003763 std::call_once(g_once_flag, []()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003764 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003765 PluginManager::RegisterPlugin (GetPluginNameStatic(),
3766 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00003767 CreateInstance,
3768 DebuggerInitialize);
Davide Italianoc8d69822015-04-03 04:24:32 +00003769 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003770}
3771
Greg Clayton7f982402013-07-15 22:54:20 +00003772void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003773ProcessGDBRemote::DebuggerInitialize (Debugger &debugger)
Greg Clayton7f982402013-07-15 22:54:20 +00003774{
3775 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
3776 {
3777 const bool is_global_setting = true;
3778 PluginManager::CreateSettingForProcessPlugin (debugger,
3779 GetGlobalPluginProperties()->GetValueProperties(),
3780 ConstString ("Properties for the gdb-remote process plug-in."),
3781 is_global_setting);
3782 }
3783}
3784
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003785bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003786ProcessGDBRemote::StartAsyncThread ()
3787{
Greg Clayton5160ce52013-03-27 23:08:40 +00003788 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003789
3790 if (log)
3791 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Ed Maste81b4c5f2016-01-04 01:43:47 +00003792
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +00003793 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003794 if (!m_async_thread.IsJoinable())
Jim Ingham455fa5c2012-11-01 01:15:33 +00003795 {
3796 // Create a thread that watches our internal state and controls which
3797 // events make it to clients (into the DCProcess event queue).
Zachary Turner39de3112014-09-09 20:54:56 +00003798
3799 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003800 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003801 else if (log)
3802 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was already running.", __FUNCTION__);
Zachary Turner39de3112014-09-09 20:54:56 +00003803
Zachary Turneracee96a2014-09-23 18:32:09 +00003804 return m_async_thread.IsJoinable();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003805}
3806
3807void
3808ProcessGDBRemote::StopAsyncThread ()
3809{
Greg Clayton5160ce52013-03-27 23:08:40 +00003810 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003811
3812 if (log)
3813 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
3814
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +00003815 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003816 if (m_async_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003817 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00003818 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
Ed Maste81b4c5f2016-01-04 01:43:47 +00003819
Jim Ingham455fa5c2012-11-01 01:15:33 +00003820 // This will shut down the async thread.
3821 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3822
3823 // Stop the stdio thread
Zachary Turner39de3112014-09-09 20:54:56 +00003824 m_async_thread.Join(nullptr);
Pavel Labatha55a9532015-03-11 09:53:42 +00003825 m_async_thread.Reset();
Jim Ingham455fa5c2012-11-01 01:15:33 +00003826 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003827 else if (log)
3828 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003829}
3830
Ewan Crawford76df2882015-06-23 12:32:06 +00003831bool
3832ProcessGDBRemote::HandleNotifyPacket (StringExtractorGDBRemote &packet)
3833{
3834 // get the packet at a string
3835 const std::string &pkt = packet.GetStringRef();
3836 // skip %stop:
3837 StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
3838
3839 // pass as a thread stop info packet
3840 SetLastStopPacket(stop_info);
3841
3842 // check for more stop reasons
3843 HandleStopReplySequence();
3844
3845 // if the process is stopped then we need to fake a resume
3846 // so that we can stop properly with the new break. This
3847 // is possible due to SetPrivateState() broadcasting the
3848 // state change as a side effect.
3849 if (GetPrivateState() == lldb::StateType::eStateStopped)
3850 {
3851 SetPrivateState(lldb::StateType::eStateRunning);
3852 }
3853
3854 // since we have some stopped packets we can halt the process
3855 SetPrivateState(lldb::StateType::eStateStopped);
3856
3857 return true;
3858}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003859
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003860thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003861ProcessGDBRemote::AsyncThread (void *arg)
3862{
3863 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
3864
Greg Clayton5160ce52013-03-27 23:08:40 +00003865 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003866 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003867 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003868
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003869 EventSP event_sp;
Pavel Labath50556852015-09-03 09:36:22 +00003870 bool done = false;
3871 while (!done)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003872 {
Pavel Labath50556852015-09-03 09:36:22 +00003873 if (log)
3874 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003875 if (process->m_async_listener_sp->WaitForEvent(std::chrono::microseconds(0), event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003876 {
Pavel Labath50556852015-09-03 09:36:22 +00003877 const uint32_t event_type = event_sp->GetType();
3878 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003879 {
3880 if (log)
Pavel Labath50556852015-09-03 09:36:22 +00003881 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
3882
3883 switch (event_type)
3884 {
3885 case eBroadcastBitAsyncContinue:
3886 {
3887 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
3888
3889 if (continue_packet)
3890 {
3891 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
3892 const size_t continue_cstr_len = continue_packet->GetByteSize ();
3893 if (log)
3894 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
3895
3896 if (::strstr (continue_cstr, "vAttach") == NULL)
3897 process->SetPrivateState(eStateRunning);
3898 StringExtractorGDBRemote response;
3899
3900 // If in Non-Stop-Mode
3901 if (process->GetTarget().GetNonStopModeEnabled())
3902 {
3903 // send the vCont packet
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00003904 if (!process->GetGDBRemote().SendvContPacket(
3905 llvm::StringRef(continue_cstr, continue_cstr_len), response))
Pavel Labath50556852015-09-03 09:36:22 +00003906 {
3907 // Something went wrong
3908 done = true;
3909 break;
3910 }
3911 }
3912 // If in All-Stop-Mode
3913 else
3914 {
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00003915 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse(
3916 *process, *process->GetUnixSignals(),
3917 llvm::StringRef(continue_cstr, continue_cstr_len), response);
Pavel Labath50556852015-09-03 09:36:22 +00003918
3919 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
3920 // The thread ID list might be contained within the "response", or the stop reply packet that
3921 // caused the stop. So clear it now before we give the stop reply packet to the process
3922 // using the process->SetLastStopPacket()...
3923 process->ClearThreadIDList ();
3924
3925 switch (stop_state)
3926 {
3927 case eStateStopped:
3928 case eStateCrashed:
3929 case eStateSuspended:
3930 process->SetLastStopPacket (response);
3931 process->SetPrivateState (stop_state);
3932 break;
3933
3934 case eStateExited:
3935 {
3936 process->SetLastStopPacket (response);
3937 process->ClearThreadIDList();
3938 response.SetFilePos(1);
Ed Maste81b4c5f2016-01-04 01:43:47 +00003939
Pavel Labath50556852015-09-03 09:36:22 +00003940 int exit_status = response.GetHexU8();
Pavel Labath50556852015-09-03 09:36:22 +00003941 std::string desc_string;
3942 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';')
3943 {
Zachary Turner54695a32016-08-29 19:58:14 +00003944 llvm::StringRef desc_str;
3945 llvm::StringRef desc_token;
3946 while (response.GetNameColonValue(desc_token, desc_str))
Pavel Labath50556852015-09-03 09:36:22 +00003947 {
Zachary Turner54695a32016-08-29 19:58:14 +00003948 if (desc_token != "description")
3949 continue;
3950 StringExtractor extractor(desc_str);
3951 extractor.GetHexByteString(desc_string);
Pavel Labath50556852015-09-03 09:36:22 +00003952 }
3953 }
Zachary Turner54695a32016-08-29 19:58:14 +00003954 process->SetExitStatus(exit_status, desc_string.c_str());
Pavel Labath50556852015-09-03 09:36:22 +00003955 done = true;
3956 break;
3957 }
3958 case eStateInvalid:
3959 {
3960 // Check to see if we were trying to attach and if we got back
3961 // the "E87" error code from debugserver -- this indicates that
3962 // the process is not debuggable. Return a slightly more helpful
3963 // error message about why the attach failed.
3964 if (::strstr (continue_cstr, "vAttach") != NULL
3965 && response.GetError() == 0x87)
3966 {
3967 process->SetExitStatus(-1, "cannot attach to process due to System Integrity Protection");
3968 }
3969 // E01 code from vAttach means that the attach failed
3970 if (::strstr (continue_cstr, "vAttach") != NULL
3971 && response.GetError() == 0x1)
3972 {
3973 process->SetExitStatus(-1, "unable to attach");
3974 }
3975 else
3976 {
3977 process->SetExitStatus(-1, "lost connection");
3978 }
3979 break;
3980 }
3981
3982 default:
3983 process->SetPrivateState (stop_state);
3984 break;
3985 } // switch(stop_state)
3986 } // else // if in All-stop-mode
3987 } // if (continue_packet)
3988 } // case eBroadcastBitAysncContinue
3989 break;
3990
3991 case eBroadcastBitAsyncThreadShouldExit:
3992 if (log)
3993 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
3994 done = true;
3995 break;
3996
3997 default:
3998 if (log)
3999 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
4000 done = true;
4001 break;
4002 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004003 }
Pavel Labath50556852015-09-03 09:36:22 +00004004 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
4005 {
4006 switch (event_type)
4007 {
4008 case Communication::eBroadcastBitReadThreadDidExit:
4009 process->SetExitStatus (-1, "lost connection");
4010 done = true;
4011 break;
4012
4013 case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify:
4014 {
4015 lldb_private::Event *event = event_sp.get();
4016 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event);
4017 StringExtractorGDBRemote notify((const char*)continue_packet->GetBytes());
4018 // Hand this over to the process to handle
4019 process->HandleNotifyPacket(notify);
4020 break;
4021 }
4022
4023 default:
4024 if (log)
4025 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
4026 done = true;
4027 break;
4028 }
4029 }
4030 }
4031 else
4032 {
4033 if (log)
4034 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
4035 done = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004036 }
4037 }
4038
4039 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004040 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004041
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004042 return NULL;
4043}
4044
Greg Claytone996fd32011-03-08 22:40:15 +00004045//uint32_t
4046//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4047//{
4048// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
4049// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
4050// if (m_local_debugserver)
4051// {
4052// return Host::ListProcessesMatchingName (name, matches, pids);
4053// }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004054// else
Greg Claytone996fd32011-03-08 22:40:15 +00004055// {
4056// // FIXME: Implement talking to the remote debugserver.
4057// return 0;
4058// }
4059//
4060//}
4061//
Jim Ingham1c823b42011-01-22 01:33:44 +00004062bool
4063ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004064 StoppointCallbackContext *context,
Jim Ingham1c823b42011-01-22 01:33:44 +00004065 lldb::user_id_t break_id,
4066 lldb::user_id_t break_loc_id)
4067{
Ed Maste81b4c5f2016-01-04 01:43:47 +00004068 // 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 +00004069 // run so I can stop it if that's what I want to do.
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004070 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00004071 if (log)
4072 log->Printf("Hit New Thread Notification breakpoint.");
4073 return false;
4074}
4075
Eugene Zelenko0722f082015-10-24 01:28:05 +00004076
Jim Ingham1c823b42011-01-22 01:33:44 +00004077bool
4078ProcessGDBRemote::StartNoticingNewThreads()
4079{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004080 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00004081 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00004082 {
Greg Clayton4116e932012-05-15 02:33:01 +00004083 if (log && log->GetVerbose())
4084 log->Printf("Enabled noticing new thread breakpoint.");
4085 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00004086 }
Greg Clayton4116e932012-05-15 02:33:01 +00004087 else
Jim Ingham1c823b42011-01-22 01:33:44 +00004088 {
Zachary Turner7529df92015-09-01 20:02:29 +00004089 PlatformSP platform_sp (GetTarget().GetPlatform());
Greg Clayton4116e932012-05-15 02:33:01 +00004090 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00004091 {
Zachary Turner7529df92015-09-01 20:02:29 +00004092 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(GetTarget());
Greg Clayton4116e932012-05-15 02:33:01 +00004093 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00004094 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00004095 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00004096 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
4097 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00004098 }
4099 else
4100 {
4101 if (log)
4102 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00004103 }
4104 }
4105 }
Greg Clayton4116e932012-05-15 02:33:01 +00004106 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00004107}
4108
4109bool
4110ProcessGDBRemote::StopNoticingNewThreads()
Ed Maste81b4c5f2016-01-04 01:43:47 +00004111{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004112 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00004113 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00004114 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00004115
4116 if (m_thread_create_bp_sp)
4117 m_thread_create_bp_sp->SetEnabled(false);
4118
Jim Ingham1c823b42011-01-22 01:33:44 +00004119 return true;
4120}
Ed Maste81b4c5f2016-01-04 01:43:47 +00004121
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004122DynamicLoader *
Jason Molenda5e8534e2012-10-03 01:29:34 +00004123ProcessGDBRemote::GetDynamicLoader ()
4124{
4125 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00004126 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00004127 return m_dyld_ap.get();
4128}
Jim Ingham1c823b42011-01-22 01:33:44 +00004129
Jason Molendaa3329782014-03-29 18:54:20 +00004130Error
4131ProcessGDBRemote::SendEventData(const char *data)
4132{
4133 int return_value;
4134 bool was_supported;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004135
Jason Molendaa3329782014-03-29 18:54:20 +00004136 Error error;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004137
Jason Molendaa3329782014-03-29 18:54:20 +00004138 return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported);
4139 if (return_value != 0)
4140 {
4141 if (!was_supported)
4142 error.SetErrorString("Sending events is not supported for this process.");
4143 else
4144 error.SetErrorStringWithFormat("Error sending event data: %d.", return_value);
4145 }
4146 return error;
4147}
4148
Steve Pucci03904ac2014-03-04 23:18:46 +00004149const DataBufferSP
4150ProcessGDBRemote::GetAuxvData()
4151{
4152 DataBufferSP buf;
4153 if (m_gdb_comm.GetQXferAuxvReadSupported())
4154 {
4155 std::string response_string;
4156 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success)
4157 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length()));
4158 }
4159 return buf;
4160}
4161
Jason Molenda705b1802014-06-13 02:37:02 +00004162StructuredData::ObjectSP
4163ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid)
4164{
4165 StructuredData::ObjectSP object_sp;
4166
4167 if (m_gdb_comm.GetThreadExtendedInfoSupported())
4168 {
4169 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4170 SystemRuntime *runtime = GetSystemRuntime();
4171 if (runtime)
4172 {
4173 runtime->AddThreadExtendedInfoPacketHints (args_dict);
4174 }
4175 args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid);
4176
4177 StreamString packet;
4178 packet << "jThreadExtendedInfo:";
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004179 args_dict->Dump (packet, false);
Jason Molenda705b1802014-06-13 02:37:02 +00004180
4181 // FIXME the final character of a JSON dictionary, '}', is the escape
4182 // character in gdb-remote binary mode. lldb currently doesn't escape
4183 // these characters in its packet output -- so we add the quoted version
4184 // of the } character here manually in case we talk to a debugserver which
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004185 // un-escapes the characters at packet read time.
Jason Molenda705b1802014-06-13 02:37:02 +00004186 packet << (char) (0x7d ^ 0x20);
4187
4188 StringExtractorGDBRemote response;
Greg Clayton830c81d2016-04-01 00:41:29 +00004189 response.SetResponseValidatorToJSON();
Jason Molenda705b1802014-06-13 02:37:02 +00004190 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4191 {
4192 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4193 if (response_type == StringExtractorGDBRemote::eResponse)
4194 {
4195 if (!response.Empty())
4196 {
Jason Molenda20ee21b2015-07-10 23:15:22 +00004197 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4198 }
4199 }
4200 }
4201 }
4202 return object_sp;
4203}
4204
4205StructuredData::ObjectSP
4206ProcessGDBRemote::GetLoadedDynamicLibrariesInfos (lldb::addr_t image_list_address, lldb::addr_t image_count)
4207{
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004208
4209 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4210 args_dict->GetAsDictionary()->AddIntegerItem ("image_list_address", image_list_address);
4211 args_dict->GetAsDictionary()->AddIntegerItem ("image_count", image_count);
4212
4213 return GetLoadedDynamicLibrariesInfos_sender (args_dict);
4214}
4215
4216StructuredData::ObjectSP
4217ProcessGDBRemote::GetLoadedDynamicLibrariesInfos ()
4218{
4219 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4220
4221 args_dict->GetAsDictionary()->AddBooleanItem ("fetch_all_solibs", true);
4222
4223 return GetLoadedDynamicLibrariesInfos_sender (args_dict);
4224}
4225
4226StructuredData::ObjectSP
4227ProcessGDBRemote::GetLoadedDynamicLibrariesInfos (const std::vector<lldb::addr_t> &load_addresses)
4228{
4229 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4230 StructuredData::ArraySP addresses(new StructuredData::Array);
4231
4232 for (auto addr : load_addresses)
4233 {
4234 StructuredData::ObjectSP addr_sp (new StructuredData::Integer (addr));
4235 addresses->AddItem (addr_sp);
4236 }
4237
4238 args_dict->GetAsDictionary()->AddItem ("solib_addresses", addresses);
4239
4240 return GetLoadedDynamicLibrariesInfos_sender (args_dict);
4241}
4242
4243StructuredData::ObjectSP
4244ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender (StructuredData::ObjectSP args_dict)
4245{
Jason Molenda20ee21b2015-07-10 23:15:22 +00004246 StructuredData::ObjectSP object_sp;
4247
4248 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported())
4249 {
Jason Molenda1d3b3562015-11-05 23:54:29 +00004250 // Scope for the scoped timeout object
4251 GDBRemoteCommunication::ScopedTimeout timeout (m_gdb_comm, 10);
4252
Jason Molenda20ee21b2015-07-10 23:15:22 +00004253 StreamString packet;
4254 packet << "jGetLoadedDynamicLibrariesInfos:";
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004255 args_dict->Dump (packet, false);
Jason Molenda20ee21b2015-07-10 23:15:22 +00004256
4257 // FIXME the final character of a JSON dictionary, '}', is the escape
4258 // character in gdb-remote binary mode. lldb currently doesn't escape
4259 // these characters in its packet output -- so we add the quoted version
4260 // of the } character here manually in case we talk to a debugserver which
4261 // un-escapes the characters at packet read time.
4262 packet << (char) (0x7d ^ 0x20);
4263
4264 StringExtractorGDBRemote response;
Greg Clayton830c81d2016-04-01 00:41:29 +00004265 response.SetResponseValidatorToJSON();
Jason Molenda20ee21b2015-07-10 23:15:22 +00004266 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4267 {
4268 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4269 if (response_type == StringExtractorGDBRemote::eResponse)
4270 {
4271 if (!response.Empty())
4272 {
Jason Molenda705b1802014-06-13 02:37:02 +00004273 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4274 }
4275 }
4276 }
4277 }
4278 return object_sp;
4279}
4280
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004281
4282
4283
Jason Molenda37397352016-07-22 00:17:55 +00004284StructuredData::ObjectSP
4285ProcessGDBRemote::GetSharedCacheInfo ()
4286{
4287 StructuredData::ObjectSP object_sp;
4288 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4289
4290 if (m_gdb_comm.GetSharedCacheInfoSupported())
4291 {
4292 StreamString packet;
4293 packet << "jGetSharedCacheInfo:";
4294 args_dict->Dump (packet, false);
4295
4296 // FIXME the final character of a JSON dictionary, '}', is the escape
4297 // character in gdb-remote binary mode. lldb currently doesn't escape
4298 // these characters in its packet output -- so we add the quoted version
4299 // of the } character here manually in case we talk to a debugserver which
4300 // un-escapes the characters at packet read time.
4301 packet << (char) (0x7d ^ 0x20);
4302
4303 StringExtractorGDBRemote response;
4304 response.SetResponseValidatorToJSON();
4305 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4306 {
4307 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4308 if (response_type == StringExtractorGDBRemote::eResponse)
4309 {
4310 if (!response.Empty())
4311 {
4312 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4313 }
4314 }
4315 }
4316 }
4317 return object_sp;
4318}
4319
Todd Fiala75930012016-08-19 04:21:48 +00004320Error
4321ProcessGDBRemote::ConfigureStructuredData(const ConstString &type_name,
4322 const StructuredData::ObjectSP
4323 &config_sp)
4324{
4325 return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp);
4326}
Jason Molenda37397352016-07-22 00:17:55 +00004327
Jason Molenda6076bf42014-05-06 04:34:52 +00004328// Establish the largest memory read/write payloads we should use.
4329// If the remote stub has a max packet size, stay under that size.
Ed Maste81b4c5f2016-01-04 01:43:47 +00004330//
4331// If the remote stub's max packet size is crazy large, use a
Jason Molenda6076bf42014-05-06 04:34:52 +00004332// reasonable largeish default.
4333//
4334// If the remote stub doesn't advertise a max packet size, use a
4335// conservative default.
4336
4337void
4338ProcessGDBRemote::GetMaxMemorySize()
4339{
4340 const uint64_t reasonable_largeish_default = 128 * 1024;
4341 const uint64_t conservative_default = 512;
4342
4343 if (m_max_memory_size == 0)
4344 {
4345 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4346 if (stub_max_size != UINT64_MAX && stub_max_size != 0)
4347 {
4348 // Save the stub's claimed maximum packet size
4349 m_remote_stub_max_memory_size = stub_max_size;
4350
4351 // Even if the stub says it can support ginormous packets,
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004352 // don't exceed our reasonable largeish default packet size.
Jason Molenda6076bf42014-05-06 04:34:52 +00004353 if (stub_max_size > reasonable_largeish_default)
4354 {
4355 stub_max_size = reasonable_largeish_default;
4356 }
4357
4358 m_max_memory_size = stub_max_size;
4359 }
4360 else
4361 {
4362 m_max_memory_size = conservative_default;
4363 }
4364 }
4365}
4366
4367void
4368ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max)
4369{
4370 if (user_specified_max != 0)
4371 {
4372 GetMaxMemorySize ();
4373
4374 if (m_remote_stub_max_memory_size != 0)
4375 {
4376 if (m_remote_stub_max_memory_size < user_specified_max)
4377 {
4378 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a packet size too big, go as big
4379 // as the remote stub says we can go.
4380 }
4381 else
4382 {
4383 m_max_memory_size = user_specified_max; // user's packet size is good
4384 }
4385 }
4386 else
4387 {
4388 m_max_memory_size = user_specified_max; // user's packet size is probably fine
4389 }
4390 }
4391}
4392
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004393bool
4394ProcessGDBRemote::GetModuleSpec(const FileSpec& module_file_spec,
4395 const ArchSpec& arch,
4396 ModuleSpec &module_spec)
4397{
4398 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PLATFORM);
4399
4400 if (!m_gdb_comm.GetModuleInfo (module_file_spec, arch, module_spec))
4401 {
4402 if (log)
4403 log->Printf ("ProcessGDBRemote::%s - failed to get module info for %s:%s",
4404 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4405 arch.GetTriple ().getTriple ().c_str ());
4406 return false;
4407 }
4408
4409 if (log)
4410 {
4411 StreamString stream;
4412 module_spec.Dump (stream);
4413 log->Printf ("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4414 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4415 arch.GetTriple ().getTriple ().c_str (), stream.GetString ().c_str ());
4416 }
4417
4418 return true;
4419}
4420
Jim Ingham13c30d22015-11-05 22:33:17 +00004421bool
4422ProcessGDBRemote::GetHostOSVersion(uint32_t &major,
4423 uint32_t &minor,
4424 uint32_t &update)
4425{
4426 if (m_gdb_comm.GetOSVersion(major, minor, update))
4427 return true;
4428 // We failed to get the host OS version, defer to the base
4429 // implementation to correctly invalidate the arguments.
4430 return Process::GetHostOSVersion(major, minor, update);
4431}
4432
Colin Rileyc3c95b22015-04-16 15:51:33 +00004433namespace {
4434
4435typedef std::vector<std::string> stringVec;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004436
4437typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004438struct RegisterSetInfo
4439{
4440 ConstString name;
4441};
Colin Rileyc3c95b22015-04-16 15:51:33 +00004442
Greg Claytond04f0ed2015-05-26 18:00:51 +00004443typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004444
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004445struct GdbServerTargetInfo
4446{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004447 std::string arch;
4448 std::string osabi;
4449 stringVec includes;
4450 RegisterSetMap reg_set_map;
4451 XMLNode feature_node;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004452};
Ed Maste81b4c5f2016-01-04 01:43:47 +00004453
Colin Rileyc3c95b22015-04-16 15:51:33 +00004454bool
Francis Ricci55954ae2016-04-25 21:03:55 +00004455ParseRegisters (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 +00004456{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004457 if (!feature_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004458 return false;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004459
Jason Molenda63bd0db2015-09-15 23:20:34 +00004460 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 +00004461 std::string gdb_group;
4462 std::string gdb_type;
4463 ConstString reg_name;
4464 ConstString alt_name;
4465 ConstString set_name;
4466 std::vector<uint32_t> value_regs;
4467 std::vector<uint32_t> invalidate_regs;
Nitesh Jain52b6cc52016-08-01 13:45:51 +00004468 std::vector<uint8_t> dwarf_opcode_bytes;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004469 bool encoding_set = false;
4470 bool format_set = false;
4471 RegisterInfo reg_info = { NULL, // Name
4472 NULL, // Alt name
4473 0, // byte size
4474 reg_offset, // offset
4475 eEncodingUint, // encoding
Jason Molendabf67a302015-09-01 05:17:01 +00004476 eFormatHex, // format
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004477 {
Jason Molendabf67a302015-09-01 05:17:01 +00004478 LLDB_INVALID_REGNUM, // eh_frame reg num
Greg Claytond04f0ed2015-05-26 18:00:51 +00004479 LLDB_INVALID_REGNUM, // DWARF reg num
4480 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda63bd0db2015-09-15 23:20:34 +00004481 cur_reg_num, // process plugin reg num
4482 cur_reg_num // native register number
Greg Claytond04f0ed2015-05-26 18:00:51 +00004483 },
4484 NULL,
Nitesh Jain52b6cc52016-08-01 13:45:51 +00004485 NULL,
4486 NULL, // Dwarf Expression opcode bytes pointer
4487 0 // Dwarf Expression opcode bytes length
Greg Claytond04f0ed2015-05-26 18:00:51 +00004488 };
Ed Maste81b4c5f2016-01-04 01:43:47 +00004489
Nitesh Jain52b6cc52016-08-01 13:45:51 +00004490 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 +00004491 if (name == "name")
4492 {
4493 reg_name.SetString(value);
4494 }
4495 else if (name == "bitsize")
4496 {
4497 reg_info.byte_size = StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
4498 }
4499 else if (name == "type")
4500 {
4501 gdb_type = value.str();
4502 }
4503 else if (name == "group")
4504 {
4505 gdb_group = value.str();
4506 }
4507 else if (name == "regnum")
4508 {
4509 const uint32_t regnum = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4510 if (regnum != LLDB_INVALID_REGNUM)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004511 {
Jason Molenda63bd0db2015-09-15 23:20:34 +00004512 reg_info.kinds[eRegisterKindProcessPlugin] = regnum;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004513 }
4514 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004515 else if (name == "offset")
4516 {
4517 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4518 }
4519 else if (name == "altname")
4520 {
4521 alt_name.SetString(value);
4522 }
4523 else if (name == "encoding")
4524 {
4525 encoding_set = true;
4526 reg_info.encoding = Args::StringToEncoding (value.data(), eEncodingUint);
4527 }
4528 else if (name == "format")
4529 {
4530 format_set = true;
4531 Format format = eFormatInvalid;
4532 if (Args::StringToFormat (value.data(), format, NULL).Success())
4533 reg_info.format = format;
4534 else if (value == "vector-sint8")
4535 reg_info.format = eFormatVectorOfSInt8;
4536 else if (value == "vector-uint8")
4537 reg_info.format = eFormatVectorOfUInt8;
4538 else if (value == "vector-sint16")
4539 reg_info.format = eFormatVectorOfSInt16;
4540 else if (value == "vector-uint16")
4541 reg_info.format = eFormatVectorOfUInt16;
4542 else if (value == "vector-sint32")
4543 reg_info.format = eFormatVectorOfSInt32;
4544 else if (value == "vector-uint32")
4545 reg_info.format = eFormatVectorOfUInt32;
4546 else if (value == "vector-float32")
4547 reg_info.format = eFormatVectorOfFloat32;
4548 else if (value == "vector-uint128")
4549 reg_info.format = eFormatVectorOfUInt128;
4550 }
4551 else if (name == "group_id")
4552 {
4553 const uint32_t set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4554 RegisterSetMap::const_iterator pos = target_info.reg_set_map.find(set_id);
4555 if (pos != target_info.reg_set_map.end())
4556 set_name = pos->second.name;
4557 }
Jason Molendaa18f7072015-08-15 01:21:01 +00004558 else if (name == "gcc_regnum" || name == "ehframe_regnum")
Greg Claytond04f0ed2015-05-26 18:00:51 +00004559 {
Jason Molendaa18f7072015-08-15 01:21:01 +00004560 reg_info.kinds[eRegisterKindEHFrame] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004561 }
4562 else if (name == "dwarf_regnum")
4563 {
4564 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4565 }
4566 else if (name == "generic")
4567 {
4568 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister(value.data());
4569 }
4570 else if (name == "value_regnums")
4571 {
4572 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
4573 }
4574 else if (name == "invalidate_regnums")
4575 {
4576 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
4577 }
Nitesh Jain52b6cc52016-08-01 13:45:51 +00004578 else if (name == "dynamic_size_dwarf_expr_bytes")
4579 {
4580 StringExtractor opcode_extractor;
4581 std::string opcode_string = value.str ();
4582 size_t dwarf_opcode_len = opcode_string.length () / 2;
4583 assert (dwarf_opcode_len > 0);
4584
4585 dwarf_opcode_bytes.resize (dwarf_opcode_len);
4586 reg_info.dynamic_size_dwarf_len = dwarf_opcode_len;
4587 opcode_extractor.GetStringRef ().swap (opcode_string);
Zachary Turnerd08f09c2016-08-30 18:12:11 +00004588 uint32_t ret_val = opcode_extractor.GetHexBytesAvail (dwarf_opcode_bytes);
Nitesh Jain52b6cc52016-08-01 13:45:51 +00004589 assert (dwarf_opcode_len == ret_val);
4590
4591 reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data ();
4592 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004593 else
4594 {
4595 printf("unhandled attribute %s = %s\n", name.data(), value.data());
4596 }
4597 return true; // Keep iterating through all attributes
4598 });
Ed Maste81b4c5f2016-01-04 01:43:47 +00004599
Greg Claytond04f0ed2015-05-26 18:00:51 +00004600 if (!gdb_type.empty() && !(encoding_set || format_set))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004601 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004602 if (gdb_type.find("int") == 0)
4603 {
4604 reg_info.format = eFormatHex;
4605 reg_info.encoding = eEncodingUint;
4606 }
4607 else if (gdb_type == "data_ptr" || gdb_type == "code_ptr")
4608 {
4609 reg_info.format = eFormatAddressInfo;
4610 reg_info.encoding = eEncodingUint;
4611 }
4612 else if (gdb_type == "i387_ext" || gdb_type == "float")
4613 {
4614 reg_info.format = eFormatFloat;
4615 reg_info.encoding = eEncodingIEEE754;
4616 }
Colin Rileyc3c95b22015-04-16 15:51:33 +00004617 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004618
Greg Claytond04f0ed2015-05-26 18:00:51 +00004619 // Only update the register set name if we didn't get a "reg_set" attribute.
4620 // "set_name" will be empty if we didn't have a "reg_set" attribute.
4621 if (!set_name && !gdb_group.empty())
4622 set_name.SetCString(gdb_group.c_str());
Ed Maste81b4c5f2016-01-04 01:43:47 +00004623
Greg Claytond04f0ed2015-05-26 18:00:51 +00004624 reg_info.byte_offset = reg_offset;
4625 assert (reg_info.byte_size != 0);
4626 reg_offset += reg_info.byte_size;
4627 if (!value_regs.empty())
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004628 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004629 value_regs.push_back(LLDB_INVALID_REGNUM);
4630 reg_info.value_regs = value_regs.data();
Colin Rileyc3c95b22015-04-16 15:51:33 +00004631 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004632 if (!invalidate_regs.empty())
4633 {
4634 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
4635 reg_info.invalidate_regs = invalidate_regs.data();
4636 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004637
Jason Molenda63bd0db2015-09-15 23:20:34 +00004638 ++cur_reg_num;
Jason Molenda21586c82015-09-09 03:36:24 +00004639 AugmentRegisterInfoViaABI (reg_info, reg_name, abi_sp);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004640 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
Ed Maste81b4c5f2016-01-04 01:43:47 +00004641
Greg Claytond04f0ed2015-05-26 18:00:51 +00004642 return true; // Keep iterating through all "reg" elements
4643 });
Colin Rileyc3c95b22015-04-16 15:51:33 +00004644 return true;
4645}
Ed Maste81b4c5f2016-01-04 01:43:47 +00004646
Eugene Zelenko0722f082015-10-24 01:28:05 +00004647} // namespace {}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004648
Colin Rileyc3c95b22015-04-16 15:51:33 +00004649
4650// query the target of gdb-remote for extended target information
4651// return: 'true' on success
4652// 'false' on failure
4653bool
Jim Ingham7b71c0b2016-02-18 23:58:45 +00004654ProcessGDBRemote::GetGDBServerRegisterInfo (ArchSpec &arch_to_use)
Colin Rileyc3c95b22015-04-16 15:51:33 +00004655{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004656 // Make sure LLDB has an XML parser it can use first
4657 if (!XMLDocument::XMLEnabled())
4658 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004659
4660 // redirect libxml2's error handler since the default prints to stdout
Colin Rileyc3c95b22015-04-16 15:51:33 +00004661
4662 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004663
4664 // check that we have extended feature read support
4665 if ( !comm.GetQXferFeaturesReadSupported( ) )
4666 return false;
4667
4668 // request the target xml file
4669 std::string raw;
4670 lldb_private::Error lldberr;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004671 if (!comm.ReadExtFeature(ConstString("features"),
4672 ConstString("target.xml"),
4673 raw,
4674 lldberr))
4675 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00004676 return false;
4677 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004678
Colin Rileyc3c95b22015-04-16 15:51:33 +00004679
Greg Claytond04f0ed2015-05-26 18:00:51 +00004680 XMLDocument xml_document;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004681
Greg Claytond04f0ed2015-05-26 18:00:51 +00004682 if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml"))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004683 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004684 GdbServerTargetInfo target_info;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004685
Greg Claytond04f0ed2015-05-26 18:00:51 +00004686 XMLNode target_node = xml_document.GetRootElement("target");
4687 if (target_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004688 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004689 XMLNode feature_node;
4690 target_node.ForEachChildElement([&target_info, this, &feature_node](const XMLNode &node) -> bool
4691 {
4692 llvm::StringRef name = node.GetName();
4693 if (name == "architecture")
4694 {
4695 node.GetElementText(target_info.arch);
4696 }
4697 else if (name == "osabi")
4698 {
4699 node.GetElementText(target_info.osabi);
4700 }
Ewan Crawford682e8422015-06-26 09:38:27 +00004701 else if (name == "xi:include" || name == "include")
Greg Claytond04f0ed2015-05-26 18:00:51 +00004702 {
4703 llvm::StringRef href = node.GetAttributeValue("href");
4704 if (!href.empty())
4705 target_info.includes.push_back(href.str());
4706 }
4707 else if (name == "feature")
4708 {
4709 feature_node = node;
4710 }
4711 else if (name == "groups")
4712 {
4713 node.ForEachChildElementWithName("group", [&target_info](const XMLNode &node) -> bool {
4714 uint32_t set_id = UINT32_MAX;
4715 RegisterSetInfo set_info;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004716
Greg Claytond04f0ed2015-05-26 18:00:51 +00004717 node.ForEachAttribute([&set_id, &set_info](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
4718 if (name == "id")
4719 set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4720 if (name == "name")
4721 set_info.name = ConstString(value);
4722 return true; // Keep iterating through all attributes
4723 });
Ed Maste81b4c5f2016-01-04 01:43:47 +00004724
Greg Claytond04f0ed2015-05-26 18:00:51 +00004725 if (set_id != UINT32_MAX)
4726 target_info.reg_set_map[set_id] = set_info;
4727 return true; // Keep iterating through all "group" elements
4728 });
4729 }
4730 return true; // Keep iterating through all children of the target_node
4731 });
Ed Maste81b4c5f2016-01-04 01:43:47 +00004732
Francis Ricci55954ae2016-04-25 21:03:55 +00004733 // Initialize these outside of ParseRegisters, since they should not be reset inside each include feature
4734 uint32_t cur_reg_num = 0;
4735 uint32_t reg_offset = 0;
4736
Jim Ingham7b71c0b2016-02-18 23:58:45 +00004737 // Don't use Process::GetABI, this code gets called from DidAttach, and in that context we haven't
4738 // set the Target's architecture yet, so the ABI is also potentially incorrect.
4739 ABISP abi_to_use_sp = ABI::FindPlugin(arch_to_use);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004740 if (feature_node)
4741 {
Francis Ricci55954ae2016-04-25 21:03:55 +00004742 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 +00004743 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004744
Greg Claytond04f0ed2015-05-26 18:00:51 +00004745 for (const auto &include : target_info.includes)
4746 {
4747 // request register file
4748 std::string xml_data;
4749 if (!comm.ReadExtFeature(ConstString("features"),
4750 ConstString(include),
4751 xml_data,
4752 lldberr))
4753 continue;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004754
Greg Claytond04f0ed2015-05-26 18:00:51 +00004755 XMLDocument include_xml_document;
4756 include_xml_document.ParseMemory(xml_data.data(), xml_data.size(), include.c_str());
4757 XMLNode include_feature_node = include_xml_document.GetRootElement("feature");
4758 if (include_feature_node)
4759 {
Francis Ricci55954ae2016-04-25 21:03:55 +00004760 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 +00004761 }
4762 }
Jim Ingham7b71c0b2016-02-18 23:58:45 +00004763 this->m_register_info.Finalize(arch_to_use);
Colin Rileyc3c95b22015-04-16 15:51:33 +00004764 }
4765 }
4766
Greg Claytond04f0ed2015-05-26 18:00:51 +00004767 return m_register_info.GetNumRegisters() > 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004768}
4769
Aidan Doddsc0c83852015-05-08 09:36:31 +00004770Error
Stephane Sezer87b0fe02016-01-12 19:02:41 +00004771ProcessGDBRemote::GetLoadedModuleList (LoadedModuleInfoList & list)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004772{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004773 // Make sure LLDB has an XML parser it can use first
4774 if (!XMLDocument::XMLEnabled())
4775 return Error (0, ErrorType::eErrorTypeGeneric);
4776
Aidan Doddsc0c83852015-05-08 09:36:31 +00004777 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS);
4778 if (log)
4779 log->Printf ("ProcessGDBRemote::%s", __FUNCTION__);
4780
Aidan Doddsc0c83852015-05-08 09:36:31 +00004781 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004782
4783 // check that we have extended feature read support
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004784 if (comm.GetQXferLibrariesSVR4ReadSupported ()) {
4785 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004786
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004787 // request the loaded library list
4788 std::string raw;
4789 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004790
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004791 if (!comm.ReadExtFeature (ConstString ("libraries-svr4"), ConstString (""), raw, lldberr))
4792 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004793
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004794 // parse the xml file in memory
4795 if (log)
4796 log->Printf ("parsing: %s", raw.c_str());
4797 XMLDocument doc;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004798
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004799 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4800 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004801
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004802 XMLNode root_element = doc.GetRootElement("library-list-svr4");
4803 if (!root_element)
4804 return Error();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004805
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004806 // main link map structure
4807 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4808 if (!main_lm.empty())
4809 {
4810 list.m_link_map = StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
4811 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004812
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004813 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
Aidan Doddsc0c83852015-05-08 09:36:31 +00004814
Stephane Sezer87b0fe02016-01-12 19:02:41 +00004815 LoadedModuleInfoList::LoadedModuleInfo module;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004816
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004817 library.ForEachAttribute([log, &module](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
Ed Maste81b4c5f2016-01-04 01:43:47 +00004818
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004819 if (name == "name")
4820 module.set_name (value.str());
4821 else if (name == "lm")
4822 {
4823 // the address of the link_map struct.
4824 module.set_link_map(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4825 }
4826 else if (name == "l_addr")
4827 {
4828 // the displacement as read from the field 'l_addr' of the link_map struct.
4829 module.set_base(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
Stephane Sezerc6845a02015-08-20 22:07:48 +00004830 // base address is always a displacement, not an absolute value.
4831 module.set_base_is_offset(true);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004832 }
4833 else if (name == "l_ld")
4834 {
4835 // the memory address of the libraries PT_DYAMIC section.
4836 module.set_dynamic(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4837 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004838
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004839 return true; // Keep iterating over all properties of "library"
4840 });
4841
4842 if (log)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004843 {
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004844 std::string name;
4845 lldb::addr_t lm=0, base=0, ld=0;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004846 bool base_is_offset;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004847
4848 module.get_name (name);
4849 module.get_link_map (lm);
4850 module.get_base (base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004851 module.get_base_is_offset (base_is_offset);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004852 module.get_dynamic (ld);
4853
Stephane Sezerc6845a02015-08-20 22:07:48 +00004854 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 +00004855 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004856
4857 list.add (module);
4858 return true; // Keep iterating over all "library" elements in the root node
Greg Claytond04f0ed2015-05-26 18:00:51 +00004859 });
Aidan Doddsc0c83852015-05-08 09:36:31 +00004860
4861 if (log)
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004862 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4863 } else if (comm.GetQXferLibrariesReadSupported ()) {
4864 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004865
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004866 // request the loaded library list
4867 std::string raw;
4868 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004869
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004870 if (!comm.ReadExtFeature (ConstString ("libraries"), ConstString (""), raw, lldberr))
4871 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004872
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004873 if (log)
4874 log->Printf ("parsing: %s", raw.c_str());
4875 XMLDocument doc;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004876
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004877 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4878 return Error (0, ErrorType::eErrorTypeGeneric);
4879
4880 XMLNode root_element = doc.GetRootElement("library-list");
4881 if (!root_element)
4882 return Error();
4883
4884 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
Stephane Sezer87b0fe02016-01-12 19:02:41 +00004885 LoadedModuleInfoList::LoadedModuleInfo module;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004886
4887 llvm::StringRef name = library.GetAttributeValue("name");
4888 module.set_name(name.str());
4889
4890 // The base address of a given library will be the address of its
4891 // first section. Most remotes send only one section for Windows
4892 // targets for example.
4893 const XMLNode &section = library.FindFirstChildElementWithName("section");
4894 llvm::StringRef address = section.GetAttributeValue("address");
4895 module.set_base(StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0));
Stephane Sezerc6845a02015-08-20 22:07:48 +00004896 // These addresses are absolute values.
4897 module.set_base_is_offset(false);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004898
4899 if (log)
4900 {
4901 std::string name;
4902 lldb::addr_t base = 0;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004903 bool base_is_offset;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004904 module.get_name (name);
4905 module.get_base (base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004906 module.get_base_is_offset (base_is_offset);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004907
Stephane Sezerc6845a02015-08-20 22:07:48 +00004908 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 +00004909 }
4910
4911 list.add (module);
4912 return true; // Keep iterating over all "library" elements in the root node
4913 });
4914
4915 if (log)
4916 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4917 } else {
4918 return Error (0, ErrorType::eErrorTypeGeneric);
4919 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004920
4921 return Error();
4922}
4923
Aidan Doddsc0c83852015-05-08 09:36:31 +00004924lldb::ModuleSP
Stephane Sezer3553c0e2016-04-05 17:25:32 +00004925ProcessGDBRemote::LoadModuleAtAddress (const FileSpec &file, lldb::addr_t link_map,
4926 lldb::addr_t base_addr, bool value_is_offset)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004927{
Stephane Sezer3553c0e2016-04-05 17:25:32 +00004928 DynamicLoader *loader = GetDynamicLoader();
4929 if (!loader)
4930 return nullptr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004931
Stephane Sezer3553c0e2016-04-05 17:25:32 +00004932 return loader->LoadModuleAtAddress(file, link_map, base_addr, value_is_offset);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004933}
4934
4935size_t
Stephane Sezer87b0fe02016-01-12 19:02:41 +00004936ProcessGDBRemote::LoadModules (LoadedModuleInfoList &module_list)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004937{
4938 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4939
4940 // request a list of loaded libraries from GDBServer
Aidan Doddsc0c83852015-05-08 09:36:31 +00004941 if (GetLoadedModuleList (module_list).Fail())
4942 return 0;
4943
4944 // get a list of all the modules
4945 ModuleList new_modules;
4946
Stephane Sezer87b0fe02016-01-12 19:02:41 +00004947 for (LoadedModuleInfoList::LoadedModuleInfo & modInfo : module_list.m_list)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004948 {
4949 std::string mod_name;
4950 lldb::addr_t mod_base;
Stephane Sezer3553c0e2016-04-05 17:25:32 +00004951 lldb::addr_t link_map;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004952 bool mod_base_is_offset;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004953
4954 bool valid = true;
4955 valid &= modInfo.get_name (mod_name);
4956 valid &= modInfo.get_base (mod_base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004957 valid &= modInfo.get_base_is_offset (mod_base_is_offset);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004958 if (!valid)
4959 continue;
4960
Stephane Sezer3553c0e2016-04-05 17:25:32 +00004961 if (!modInfo.get_link_map (link_map))
4962 link_map = LLDB_INVALID_ADDRESS;
4963
Francis Riccia0300612016-04-27 17:10:15 +00004964 FileSpec file (mod_name.c_str(), true);
Stephane Sezer3553c0e2016-04-05 17:25:32 +00004965 lldb::ModuleSP module_sp = LoadModuleAtAddress (file, link_map, mod_base,
4966 mod_base_is_offset);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004967
4968 if (module_sp.get())
4969 new_modules.Append (module_sp);
4970 }
4971
4972 if (new_modules.GetSize() > 0)
4973 {
Francis Riccibe8cab72016-04-25 21:02:24 +00004974 ModuleList removed_modules;
Zachary Turner7529df92015-09-01 20:02:29 +00004975 Target &target = GetTarget();
Francis Riccibe8cab72016-04-25 21:02:24 +00004976 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4977
4978 for (size_t i = 0; i < loaded_modules.GetSize(); ++i)
4979 {
4980 const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i);
4981
4982 bool found = false;
4983 for (size_t j = 0; j < new_modules.GetSize(); ++j)
4984 {
4985 if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get())
4986 found = true;
4987 }
4988
Francis Ricci80dbd152016-06-06 15:00:50 +00004989 // The main executable will never be included in libraries-svr4, don't remove it
4990 if (!found && loaded_module.get() != target.GetExecutableModulePointer())
Francis Riccibe8cab72016-04-25 21:02:24 +00004991 {
Francis Ricci80dbd152016-06-06 15:00:50 +00004992 removed_modules.Append (loaded_module);
Francis Riccibe8cab72016-04-25 21:02:24 +00004993 }
4994 }
4995
4996 loaded_modules.Remove (removed_modules);
4997 m_process->GetTarget().ModulesDidUnload (removed_modules, false);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004998
4999 new_modules.ForEach ([&target](const lldb::ModuleSP module_sp) -> bool
5000 {
5001 lldb_private::ObjectFile * obj = module_sp->GetObjectFile ();
5002 if (!obj)
5003 return true;
5004
5005 if (obj->GetType () != ObjectFile::Type::eTypeExecutable)
5006 return true;
5007
5008 lldb::ModuleSP module_copy_sp = module_sp;
5009 target.SetExecutableModule (module_copy_sp, false);
5010 return false;
5011 });
5012
Aidan Doddsc0c83852015-05-08 09:36:31 +00005013 loaded_modules.AppendIfNeeded (new_modules);
5014 m_process->GetTarget().ModulesDidLoad (new_modules);
5015 }
5016
5017 return new_modules.GetSize();
Stephane Sezer87b0fe02016-01-12 19:02:41 +00005018}
5019
5020size_t
5021ProcessGDBRemote::LoadModules ()
5022{
5023 LoadedModuleInfoList module_list;
5024 return LoadModules (module_list);
Aidan Doddsc0c83852015-05-08 09:36:31 +00005025}
Colin Rileyc3c95b22015-04-16 15:51:33 +00005026
Tamas Berghammer783bfc82015-06-18 20:43:56 +00005027Error
5028ProcessGDBRemote::GetFileLoadAddress(const FileSpec& file, bool& is_loaded, lldb::addr_t& load_addr)
5029{
5030 is_loaded = false;
5031 load_addr = LLDB_INVALID_ADDRESS;
5032
5033 std::string file_path = file.GetPath(false);
5034 if (file_path.empty ())
5035 return Error("Empty file name specified");
5036
5037 StreamString packet;
5038 packet.PutCString("qFileLoadAddress:");
5039 packet.PutCStringAsRawHex8(file_path.c_str());
5040
5041 StringExtractorGDBRemote response;
5042 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString().c_str(), response, false) != GDBRemoteCommunication::PacketResult::Success)
5043 return Error("Sending qFileLoadAddress packet failed");
5044
5045 if (response.IsErrorResponse())
5046 {
5047 if (response.GetError() == 1)
5048 {
5049 // The file is not loaded into the inferior
5050 is_loaded = false;
5051 load_addr = LLDB_INVALID_ADDRESS;
5052 return Error();
5053 }
5054
5055 return Error("Fetching file load address from remote server returned an error");
5056 }
5057
5058 if (response.IsNormalResponse())
5059 {
5060 is_loaded = true;
5061 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
5062 return Error();
5063 }
5064
5065 return Error("Unknown error happened during sending the load address packet");
5066}
5067
Eugene Zelenko0722f082015-10-24 01:28:05 +00005068
Greg Clayton0b90be12015-06-23 21:27:50 +00005069void
5070ProcessGDBRemote::ModulesDidLoad (ModuleList &module_list)
5071{
5072 // We must call the lldb_private::Process::ModulesDidLoad () first before we do anything
5073 Process::ModulesDidLoad (module_list);
5074
5075 // After loading shared libraries, we can ask our remote GDB server if
5076 // it needs any symbols.
5077 m_gdb_comm.ServeSymbolLookups(this);
5078}
5079
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005080void
5081ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out)
5082{
5083 AppendSTDOUT(out.data(), out.size());
5084}
5085
5086static const char *end_delimiter = "--end--;";
5087static const int end_delimiter_len = 8;
5088
5089void
5090ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data)
5091{
5092 std::string input = data.str(); // '1' to move beyond 'A'
5093 if (m_partial_profile_data.length() > 0)
5094 {
5095 m_partial_profile_data.append(input);
5096 input = m_partial_profile_data;
5097 m_partial_profile_data.clear();
5098 }
5099
5100 size_t found, pos = 0, len = input.length();
5101 while ((found = input.find(end_delimiter, pos)) != std::string::npos)
5102 {
5103 StringExtractorGDBRemote profileDataExtractor(input.substr(pos, found).c_str());
5104 std::string profile_data = HarmonizeThreadIdsForProfileData(profileDataExtractor);
5105 BroadcastAsyncProfileData(profile_data);
5106
5107 pos = found + end_delimiter_len;
5108 }
5109
5110 if (pos < len)
5111 {
5112 // Last incomplete chunk.
5113 m_partial_profile_data = input.substr(pos);
5114 }
5115}
5116
5117std::string
5118ProcessGDBRemote::HarmonizeThreadIdsForProfileData(StringExtractorGDBRemote &profileDataExtractor)
5119{
5120 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
Zachary Turner54695a32016-08-29 19:58:14 +00005121 std::string output;
5122 llvm::raw_string_ostream output_stream(output);
5123 llvm::StringRef name, value;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005124
5125 // Going to assuming thread_used_usec comes first, else bail out.
5126 while (profileDataExtractor.GetNameColonValue(name, value))
5127 {
5128 if (name.compare("thread_used_id") == 0)
5129 {
Zachary Turner54695a32016-08-29 19:58:14 +00005130 StringExtractor threadIDHexExtractor(value);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005131 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
5132
5133 bool has_used_usec = false;
5134 uint32_t curr_used_usec = 0;
Zachary Turner54695a32016-08-29 19:58:14 +00005135 llvm::StringRef usec_name, usec_value;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005136 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
5137 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value))
5138 {
Zachary Turner54695a32016-08-29 19:58:14 +00005139 if (usec_name.equals("thread_used_usec"))
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005140 {
5141 has_used_usec = true;
Zachary Turner54695a32016-08-29 19:58:14 +00005142 usec_value.getAsInteger(0, curr_used_usec);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005143 }
5144 else
5145 {
5146 // We didn't find what we want, it is probably
5147 // an older version. Bail out.
5148 profileDataExtractor.SetFilePos(input_file_pos);
5149 }
5150 }
5151
5152 if (has_used_usec)
5153 {
5154 uint32_t prev_used_usec = 0;
5155 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_used_usec_map.find(thread_id);
5156 if (iterator != m_thread_id_to_used_usec_map.end())
5157 {
5158 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
5159 }
5160
5161 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
5162 // A good first time record is one that runs for at least 0.25 sec
5163 bool good_first_time = (prev_used_usec == 0) && (real_used_usec > 250000);
5164 bool good_subsequent_time =
5165 (prev_used_usec > 0) && ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id)));
5166
5167 if (good_first_time || good_subsequent_time)
5168 {
5169 // We try to avoid doing too many index id reservation,
5170 // resulting in fast increase of index ids.
5171
Zachary Turner54695a32016-08-29 19:58:14 +00005172 output_stream << name << ":";
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005173 int32_t index_id = AssignIndexIDToThread(thread_id);
Zachary Turner54695a32016-08-29 19:58:14 +00005174 output_stream << index_id << ";";
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005175
Zachary Turner54695a32016-08-29 19:58:14 +00005176 output_stream << usec_name << ":" << usec_value << ";";
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005177 }
5178 else
5179 {
5180 // Skip past 'thread_used_name'.
Zachary Turner54695a32016-08-29 19:58:14 +00005181 llvm::StringRef local_name, local_value;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005182 profileDataExtractor.GetNameColonValue(local_name, local_value);
5183 }
5184
5185 // Store current time as previous time so that they can be compared later.
5186 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
5187 }
5188 else
5189 {
5190 // Bail out and use old string.
Zachary Turner54695a32016-08-29 19:58:14 +00005191 output_stream << name << ":" << value << ";";
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005192 }
5193 }
5194 else
5195 {
Zachary Turner54695a32016-08-29 19:58:14 +00005196 output_stream << name << ":" << value << ";";
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005197 }
5198 }
Zachary Turner54695a32016-08-29 19:58:14 +00005199 output_stream << end_delimiter;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005200 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
5201
Zachary Turner54695a32016-08-29 19:58:14 +00005202 return output_stream.str();
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005203}
5204
5205void
5206ProcessGDBRemote::HandleStopReply()
5207{
5208 if (GetStopID() != 0)
5209 return;
5210
5211 if (GetID() == LLDB_INVALID_PROCESS_ID)
5212 {
5213 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
5214 if (pid != LLDB_INVALID_PROCESS_ID)
5215 SetID(pid);
5216 }
5217 BuildDynamicRegisterInfo(true);
5218}
Eugene Zelenko0722f082015-10-24 01:28:05 +00005219
Todd Fiala75930012016-08-19 04:21:48 +00005220bool
5221ProcessGDBRemote::HandleAsyncStructuredData(const StructuredData::ObjectSP
5222 &object_sp)
5223{
5224 return RouteAsyncStructuredData(object_sp);
5225}
5226
Greg Claytone034a042015-05-21 20:52:06 +00005227class CommandObjectProcessGDBRemoteSpeedTest: public CommandObjectParsed
5228{
5229public:
5230 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter) :
5231 CommandObjectParsed (interpreter,
5232 "process plugin packet speed-test",
5233 "Tests packet speeds of various sizes to determine the performance characteristics of the GDB remote connection. ",
5234 NULL),
Todd Fialae1cfbc72016-08-11 23:51:28 +00005235 m_option_group (),
Greg Claytone034a042015-05-21 20:52:06 +00005236 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),
5237 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),
5238 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),
5239 m_json (LLDB_OPT_SET_1, false, "json", 'j', "Print the output as JSON data for easy parsing.", false, true)
5240 {
5241 m_option_group.Append (&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5242 m_option_group.Append (&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5243 m_option_group.Append (&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5244 m_option_group.Append (&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5245 m_option_group.Finalize();
5246 }
5247
Eugene Zelenko0722f082015-10-24 01:28:05 +00005248 ~CommandObjectProcessGDBRemoteSpeedTest ()
5249 {
5250 }
5251
Greg Claytone034a042015-05-21 20:52:06 +00005252
5253 Options *
5254 GetOptions () override
5255 {
5256 return &m_option_group;
5257 }
5258
5259 bool
5260 DoExecute (Args& command, CommandReturnObject &result) override
5261 {
5262 const size_t argc = command.GetArgumentCount();
5263 if (argc == 0)
5264 {
5265 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5266 if (process)
5267 {
5268 StreamSP output_stream_sp (m_interpreter.GetDebugger().GetAsyncOutputStream());
5269 result.SetImmediateOutputStream (output_stream_sp);
5270
5271 const uint32_t num_packets = (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
5272 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
5273 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
5274 const bool json = m_json.GetOptionValue().GetCurrentValue();
5275 if (output_stream_sp)
5276 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, *output_stream_sp);
5277 else
5278 {
5279 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, result.GetOutputStream());
5280 }
5281 result.SetStatus (eReturnStatusSuccessFinishResult);
5282 return true;
5283 }
5284 }
5285 else
5286 {
5287 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
5288 }
5289 result.SetStatus (eReturnStatusFailed);
5290 return false;
5291 }
5292protected:
5293 OptionGroupOptions m_option_group;
5294 OptionGroupUInt64 m_num_packets;
5295 OptionGroupUInt64 m_max_send;
5296 OptionGroupUInt64 m_max_recv;
5297 OptionGroupBoolean m_json;
Eugene Zelenko0722f082015-10-24 01:28:05 +00005298
Greg Claytone034a042015-05-21 20:52:06 +00005299};
5300
Greg Clayton02686b82012-10-15 22:42:16 +00005301class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00005302{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005303private:
Ed Maste81b4c5f2016-01-04 01:43:47 +00005304
Greg Clayton998255b2012-10-13 02:07:45 +00005305public:
Greg Clayton02686b82012-10-15 22:42:16 +00005306 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00005307 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00005308 "process plugin packet history",
5309 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00005310 NULL)
5311 {
5312 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005313
Eugene Zelenko0722f082015-10-24 01:28:05 +00005314 ~CommandObjectProcessGDBRemotePacketHistory ()
5315 {
5316 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005317
Greg Clayton998255b2012-10-13 02:07:45 +00005318 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005319 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton998255b2012-10-13 02:07:45 +00005320 {
Greg Clayton02686b82012-10-15 22:42:16 +00005321 const size_t argc = command.GetArgumentCount();
5322 if (argc == 0)
5323 {
5324 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5325 if (process)
5326 {
5327 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
5328 result.SetStatus (eReturnStatusSuccessFinishResult);
5329 return true;
5330 }
5331 }
5332 else
5333 {
5334 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
5335 }
5336 result.SetStatus (eReturnStatusFailed);
5337 return false;
5338 }
5339};
5340
Jason Molenda6076bf42014-05-06 04:34:52 +00005341class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed
5342{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005343private:
Ed Maste81b4c5f2016-01-04 01:43:47 +00005344
Jason Molenda6076bf42014-05-06 04:34:52 +00005345public:
5346 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) :
5347 CommandObjectParsed (interpreter,
5348 "process plugin packet xfer-size",
5349 "Maximum size that lldb will try to read/write one one chunk.",
5350 NULL)
5351 {
5352 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005353
Eugene Zelenko0722f082015-10-24 01:28:05 +00005354 ~CommandObjectProcessGDBRemotePacketXferSize ()
5355 {
5356 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005357
Jason Molenda6076bf42014-05-06 04:34:52 +00005358 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005359 DoExecute (Args& command, CommandReturnObject &result) override
Jason Molenda6076bf42014-05-06 04:34:52 +00005360 {
5361 const size_t argc = command.GetArgumentCount();
5362 if (argc == 0)
5363 {
5364 result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str());
5365 result.SetStatus (eReturnStatusFailed);
5366 return false;
5367 }
5368
5369 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5370 if (process)
5371 {
5372 const char *packet_size = command.GetArgumentAtIndex(0);
5373 errno = 0;
5374 uint64_t user_specified_max = strtoul (packet_size, NULL, 10);
5375 if (errno == 0 && user_specified_max != 0)
5376 {
5377 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max);
5378 result.SetStatus (eReturnStatusSuccessFinishResult);
5379 return true;
5380 }
5381 }
5382 result.SetStatus (eReturnStatusFailed);
5383 return false;
5384 }
5385};
5386
Eugene Zelenko0722f082015-10-24 01:28:05 +00005387
Greg Clayton02686b82012-10-15 22:42:16 +00005388class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
5389{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005390private:
Ed Maste81b4c5f2016-01-04 01:43:47 +00005391
Greg Clayton02686b82012-10-15 22:42:16 +00005392public:
5393 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
5394 CommandObjectParsed (interpreter,
5395 "process plugin packet send",
5396 "Send a custom packet through the GDB remote protocol and print the answer. "
5397 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
5398 NULL)
5399 {
5400 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005401
Eugene Zelenko0722f082015-10-24 01:28:05 +00005402 ~CommandObjectProcessGDBRemotePacketSend ()
5403 {
5404 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005405
Greg Clayton02686b82012-10-15 22:42:16 +00005406 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005407 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton02686b82012-10-15 22:42:16 +00005408 {
5409 const size_t argc = command.GetArgumentCount();
5410 if (argc == 0)
5411 {
5412 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
5413 result.SetStatus (eReturnStatusFailed);
5414 return false;
5415 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005416
Greg Clayton02686b82012-10-15 22:42:16 +00005417 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5418 if (process)
5419 {
Han Ming Ong84145852012-11-26 20:42:03 +00005420 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00005421 {
Han Ming Ong84145852012-11-26 20:42:03 +00005422 const char *packet_cstr = command.GetArgumentAtIndex(0);
5423 bool send_async = true;
5424 StringExtractorGDBRemote response;
5425 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
5426 result.SetStatus (eReturnStatusSuccessFinishResult);
5427 Stream &output_strm = result.GetOutputStream();
5428 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00005429 std::string &response_str = response.GetStringRef();
Ed Maste81b4c5f2016-01-04 01:43:47 +00005430
Han Ming Ong399289e2013-06-21 19:56:59 +00005431 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00005432 {
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005433 response_str = process->HarmonizeThreadIdsForProfileData(response);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00005434 }
5435
Han Ming Ong84145852012-11-26 20:42:03 +00005436 if (response_str.empty())
5437 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
5438 else
5439 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00005440 }
Greg Clayton02686b82012-10-15 22:42:16 +00005441 }
Greg Clayton998255b2012-10-13 02:07:45 +00005442 return true;
5443 }
5444};
5445
Greg Claytonba4a0a52013-02-01 23:03:47 +00005446class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
5447{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005448private:
Ed Maste81b4c5f2016-01-04 01:43:47 +00005449
Greg Claytonba4a0a52013-02-01 23:03:47 +00005450public:
5451 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
5452 CommandObjectRaw (interpreter,
5453 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00005454 "Send a qRcmd packet through the GDB remote protocol and print the response."
5455 "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 +00005456 NULL)
5457 {
5458 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005459
Eugene Zelenko0722f082015-10-24 01:28:05 +00005460 ~CommandObjectProcessGDBRemotePacketMonitor ()
5461 {
5462 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005463
Greg Claytonba4a0a52013-02-01 23:03:47 +00005464 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005465 DoExecute (const char *command, CommandReturnObject &result) override
Greg Claytonba4a0a52013-02-01 23:03:47 +00005466 {
5467 if (command == NULL || command[0] == '\0')
5468 {
5469 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
5470 result.SetStatus (eReturnStatusFailed);
5471 return false;
5472 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005473
Greg Claytonba4a0a52013-02-01 23:03:47 +00005474 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5475 if (process)
5476 {
5477 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00005478 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00005479 packet.PutBytesAsRawHex8(command, strlen(command));
5480 const char *packet_cstr = packet.GetString().c_str();
Ed Maste81b4c5f2016-01-04 01:43:47 +00005481
Greg Claytonba4a0a52013-02-01 23:03:47 +00005482 bool send_async = true;
5483 StringExtractorGDBRemote response;
5484 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
5485 result.SetStatus (eReturnStatusSuccessFinishResult);
5486 Stream &output_strm = result.GetOutputStream();
5487 output_strm.Printf (" packet: %s\n", packet_cstr);
5488 const std::string &response_str = response.GetStringRef();
Ed Maste81b4c5f2016-01-04 01:43:47 +00005489
Greg Claytonba4a0a52013-02-01 23:03:47 +00005490 if (response_str.empty())
5491 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
5492 else
5493 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
5494 }
5495 return true;
5496 }
5497};
5498
Greg Clayton02686b82012-10-15 22:42:16 +00005499class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
5500{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005501private:
Ed Maste81b4c5f2016-01-04 01:43:47 +00005502
Greg Clayton02686b82012-10-15 22:42:16 +00005503public:
5504 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
5505 CommandObjectMultiword (interpreter,
5506 "process plugin packet",
5507 "Commands that deal with GDB remote packets.",
5508 NULL)
5509 {
5510 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
5511 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00005512 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Jason Molenda6076bf42014-05-06 04:34:52 +00005513 LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter)));
Greg Claytone034a042015-05-21 20:52:06 +00005514 LoadSubCommand ("speed-test", CommandObjectSP (new CommandObjectProcessGDBRemoteSpeedTest (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00005515 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005516
Eugene Zelenko0722f082015-10-24 01:28:05 +00005517 ~CommandObjectProcessGDBRemotePacket ()
5518 {
Ed Maste81b4c5f2016-01-04 01:43:47 +00005519 }
Greg Clayton02686b82012-10-15 22:42:16 +00005520};
Greg Clayton998255b2012-10-13 02:07:45 +00005521
5522class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
5523{
5524public:
Kate Stone7428a182016-07-14 22:03:10 +00005525 CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter)
5526 : CommandObjectMultiword(interpreter, "process plugin", "Commands for operating on a ProcessGDBRemote process.",
5527 "process plugin <subcommand> [<subcommand-options>]")
Greg Clayton998255b2012-10-13 02:07:45 +00005528 {
5529 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
5530 }
5531
Eugene Zelenko0722f082015-10-24 01:28:05 +00005532 ~CommandObjectMultiwordProcessGDBRemote ()
5533 {
5534 }
Greg Clayton998255b2012-10-13 02:07:45 +00005535};
5536
Greg Clayton998255b2012-10-13 02:07:45 +00005537CommandObject *
5538ProcessGDBRemote::GetPluginCommandObject()
5539{
5540 if (!m_command_sp)
5541 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
5542 return m_command_sp.get();
5543}