blob: a14c82540412a07d122626a0abec99d6a1f6718f [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
Virgile Bellob2f1fb22013-08-23 12:44:05 +000018#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000019#include <sys/stat.h>
Greg Clayton2a48f522011-05-14 01:50:35 +000020#include <sys/types.h>
Stephen Wilsondc916862011-03-30 00:12:40 +000021#include <time.h>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000022
23// C++ Includes
24#include <algorithm>
25#include <map>
Benjamin Kramer3f69fa62015-04-03 10:55:00 +000026#include <mutex>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000027
Johnny Chen01a67862011-10-14 00:42:25 +000028#include "lldb/Breakpoint/Watchpoint.h"
Jim Ingham40af72e2010-06-15 19:49:27 +000029#include "lldb/Interpreter/Args.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000030#include "lldb/Core/ArchSpec.h"
31#include "lldb/Core/Debugger.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000032#include "lldb/Host/ConnectionFileDescriptor.h"
Greg Clayton53239f02011-02-08 05:05:52 +000033#include "lldb/Host/FileSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000034#include "lldb/Core/Module.h"
Greg Clayton1f746072012-08-29 21:13:06 +000035#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000036#include "lldb/Core/PluginManager.h"
37#include "lldb/Core/State.h"
Greg Claytond451c1a2012-04-13 21:24:18 +000038#include "lldb/Core/StreamFile.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000039#include "lldb/Core/StreamString.h"
40#include "lldb/Core/Timer.h"
Greg Clayton70b57652011-05-15 01:25:55 +000041#include "lldb/Core/Value.h"
Greg Claytond04f0ed2015-05-26 18:00:51 +000042#include "lldb/DataFormatters/FormatManager.h"
Zachary Turner4eff2d32015-10-14 21:37:36 +000043#include "lldb/Host/FileSystem.h"
Zachary Turner39de3112014-09-09 20:54:56 +000044#include "lldb/Host/HostThread.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000045#include "lldb/Host/StringConvert.h"
Jason Molendad1fae142012-09-29 08:03:33 +000046#include "lldb/Host/Symbols.h"
Zachary Turner39de3112014-09-09 20:54:56 +000047#include "lldb/Host/ThreadLauncher.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000048#include "lldb/Host/TimeValue.h"
Greg Claytond04f0ed2015-05-26 18:00:51 +000049#include "lldb/Host/XML.h"
Greg Clayton02686b82012-10-15 22:42:16 +000050#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton1d19a2f2012-10-19 22:22:57 +000051#include "lldb/Interpreter/CommandObject.h"
52#include "lldb/Interpreter/CommandObjectMultiword.h"
Greg Clayton02686b82012-10-15 22:42:16 +000053#include "lldb/Interpreter/CommandReturnObject.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000054#include "lldb/Interpreter/OptionValueProperties.h"
Greg Claytone034a042015-05-21 20:52:06 +000055#include "lldb/Interpreter/Options.h"
56#include "lldb/Interpreter/OptionGroupBoolean.h"
57#include "lldb/Interpreter/OptionGroupUInt64.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000058#include "lldb/Interpreter/Property.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000059#include "lldb/Symbol/ObjectFile.h"
Jason Molenda21586c82015-09-09 03:36:24 +000060#include "lldb/Target/ABI.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000061#include "lldb/Target/DynamicLoader.h"
62#include "lldb/Target/Target.h"
63#include "lldb/Target/TargetList.h"
Greg Clayton2a48f522011-05-14 01:50:35 +000064#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molenda705b1802014-06-13 02:37:02 +000065#include "lldb/Target/SystemRuntime.h"
Jason Molendaa34a0c62010-06-09 21:28:42 +000066#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000067
Eugene Zelenko0722f082015-10-24 01:28:05 +000068// Project includes
Chris Lattner30fdc8d2010-06-08 16:52:24 +000069#include "lldb/Host/Host.h"
Chaoren Lin98d0a4b2015-07-14 01:09:28 +000070#include "Plugins/Process/Utility/GDBRemoteSignals.h"
Peter Collingbourne99f9aa02011-06-03 20:40:38 +000071#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Jason Molendac42d2432012-07-25 03:40:06 +000072#include "Plugins/Process/Utility/StopInfoMachException.h"
Jim Ingham43c555d2012-07-04 00:35:43 +000073#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
Greg Claytonc982c762010-07-09 20:39:50 +000074#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000075#include "GDBRemoteRegisterContext.h"
76#include "ProcessGDBRemote.h"
77#include "ProcessGDBRemoteLog.h"
78#include "ThreadGDBRemote.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000079
Tamas Berghammerdb264a62015-03-31 09:52:22 +000080#define DEBUGSERVER_BASENAME "debugserver"
81using namespace lldb;
82using namespace lldb_private;
83using namespace lldb_private::process_gdb_remote;
Jason Molenda5e8534e2012-10-03 01:29:34 +000084
Greg Claytonc1422c12012-04-09 22:46:21 +000085namespace lldb
86{
87 // Provide a function that can easily dump the packet history if we know a
88 // ProcessGDBRemote * value (which we can get from logs or from debugging).
89 // We need the function in the lldb namespace so it makes it into the final
90 // executable since the LLDB shared library only exports stuff in the lldb
91 // namespace. This allows you to attach with a debugger and call this
92 // function and get the packet history dumped to a file.
93 void
94 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
95 {
Tamas Berghammerdb264a62015-03-31 09:52:22 +000096 StreamFile strm;
97 Error error (strm.GetFile().Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate));
Greg Claytond451c1a2012-04-13 21:24:18 +000098 if (error.Success())
99 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
Greg Claytonc1422c12012-04-09 22:46:21 +0000100 }
Eugene Zelenko0722f082015-10-24 01:28:05 +0000101}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000102
Greg Clayton7f982402013-07-15 22:54:20 +0000103namespace {
Steve Pucci5ec012d2014-01-16 22:18:14 +0000104
Greg Clayton7f982402013-07-15 22:54:20 +0000105 static PropertyDefinition
106 g_properties[] =
107 {
108 { "packet-timeout" , OptionValue::eTypeUInt64 , true , 1, NULL, NULL, "Specify the default packet timeout in seconds." },
Greg Claytonef8180a2013-10-15 00:14:28 +0000109 { "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 +0000110 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
111 };
Ed Maste81b4c5f2016-01-04 01:43:47 +0000112
Greg Clayton7f982402013-07-15 22:54:20 +0000113 enum
114 {
Greg Claytonef8180a2013-10-15 00:14:28 +0000115 ePropertyPacketTimeout,
116 ePropertyTargetDefinitionFile
Greg Clayton7f982402013-07-15 22:54:20 +0000117 };
Ed Maste81b4c5f2016-01-04 01:43:47 +0000118
Greg Clayton7f982402013-07-15 22:54:20 +0000119 class PluginProperties : public Properties
120 {
121 public:
Ed Maste81b4c5f2016-01-04 01:43:47 +0000122
Greg Clayton7f982402013-07-15 22:54:20 +0000123 static ConstString
124 GetSettingName ()
125 {
126 return ProcessGDBRemote::GetPluginNameStatic();
127 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000128
Greg Clayton7f982402013-07-15 22:54:20 +0000129 PluginProperties() :
130 Properties ()
131 {
132 m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
133 m_collection_sp->Initialize(g_properties);
134 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000135
Eugene Zelenko0722f082015-10-24 01:28:05 +0000136 virtual
137 ~PluginProperties()
138 {
139 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000140
Greg Clayton7f982402013-07-15 22:54:20 +0000141 uint64_t
142 GetPacketTimeout()
143 {
144 const uint32_t idx = ePropertyPacketTimeout;
145 return m_collection_sp->GetPropertyAtIndexAsUInt64(NULL, idx, g_properties[idx].default_uint_value);
146 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000147
148 bool
149 SetPacketTimeout(uint64_t timeout)
150 {
151 const uint32_t idx = ePropertyPacketTimeout;
152 return m_collection_sp->SetPropertyAtIndexAsUInt64(NULL, idx, timeout);
153 }
154
Greg Claytonef8180a2013-10-15 00:14:28 +0000155 FileSpec
156 GetTargetDefinitionFile () const
157 {
158 const uint32_t idx = ePropertyTargetDefinitionFile;
159 return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
160 }
Greg Clayton7f982402013-07-15 22:54:20 +0000161 };
Ed Maste81b4c5f2016-01-04 01:43:47 +0000162
Greg Clayton7f982402013-07-15 22:54:20 +0000163 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
Ed Maste81b4c5f2016-01-04 01:43:47 +0000164
Greg Clayton7f982402013-07-15 22:54:20 +0000165 static const ProcessKDPPropertiesSP &
166 GetGlobalPluginProperties()
167 {
168 static ProcessKDPPropertiesSP g_settings_sp;
169 if (!g_settings_sp)
170 g_settings_sp.reset (new PluginProperties ());
171 return g_settings_sp;
172 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000173
Eugene Zelenko0722f082015-10-24 01:28:05 +0000174} // anonymous namespace end
Greg Clayton7f982402013-07-15 22:54:20 +0000175
Greg Claytonfda4fab2014-01-10 22:24:11 +0000176// TODO Randomly assigning a port is unsafe. We should get an unused
177// ephemeral port from the kernel and make sure we reserve it before passing
178// it to debugserver.
179
180#if defined (__APPLE__)
181#define LOW_PORT (IPPORT_RESERVED)
182#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
183#else
184#define LOW_PORT (1024u)
185#define HIGH_PORT (49151u)
186#endif
187
Todd Fiala013434e2014-07-09 01:29:05 +0000188#if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000189static bool rand_initialized = false;
190
Greg Claytonfda4fab2014-01-10 22:24:11 +0000191static inline uint16_t
192get_random_port ()
193{
194 if (!rand_initialized)
195 {
196 time_t seed = time(NULL);
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000197
Greg Claytonfda4fab2014-01-10 22:24:11 +0000198 rand_initialized = true;
199 srand(seed);
200 }
201 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
202}
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000203#endif
Greg Claytonfda4fab2014-01-10 22:24:11 +0000204
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000205ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000206ProcessGDBRemote::GetPluginNameStatic()
207{
Greg Clayton57abc5d2013-05-10 21:47:16 +0000208 static ConstString g_name("gdb-remote");
209 return g_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000210}
211
212const char *
213ProcessGDBRemote::GetPluginDescriptionStatic()
214{
215 return "GDB Remote protocol based debugging plug-in.";
216}
217
218void
219ProcessGDBRemote::Terminate()
220{
221 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
222}
223
Eugene Zelenko0722f082015-10-24 01:28:05 +0000224
Greg Claytonc3776bf2012-02-09 06:16:32 +0000225lldb::ProcessSP
Jim Ingham583bbb12016-03-07 21:50:25 +0000226ProcessGDBRemote::CreateInstance (lldb::TargetSP target_sp, ListenerSP listener_sp, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000227{
Greg Claytonc3776bf2012-02-09 06:16:32 +0000228 lldb::ProcessSP process_sp;
229 if (crash_file_path == NULL)
Jim Ingham583bbb12016-03-07 21:50:25 +0000230 process_sp.reset (new ProcessGDBRemote (target_sp, listener_sp));
Greg Claytonc3776bf2012-02-09 06:16:32 +0000231 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000232}
233
234bool
Zachary Turner7529df92015-09-01 20:02:29 +0000235ProcessGDBRemote::CanDebug (lldb::TargetSP target_sp, bool plugin_specified_by_name)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000236{
Greg Clayton596ed242011-10-21 21:41:45 +0000237 if (plugin_specified_by_name)
238 return true;
239
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000240 // For now we are just making sure the file exists for a given module
Zachary Turner7529df92015-09-01 20:02:29 +0000241 Module *exe_module = target_sp->GetExecutableModulePointer();
Greg Claytonaa149cb2011-08-11 02:48:45 +0000242 if (exe_module)
Greg Claytonc3776bf2012-02-09 06:16:32 +0000243 {
244 ObjectFile *exe_objfile = exe_module->GetObjectFile();
245 // We can't debug core files...
246 switch (exe_objfile->GetType())
247 {
248 case ObjectFile::eTypeInvalid:
249 case ObjectFile::eTypeCoreFile:
250 case ObjectFile::eTypeDebugInfo:
251 case ObjectFile::eTypeObjectFile:
252 case ObjectFile::eTypeSharedLibrary:
253 case ObjectFile::eTypeStubLibrary:
Greg Clayton23f8c952014-03-24 23:10:19 +0000254 case ObjectFile::eTypeJIT:
Greg Claytonc3776bf2012-02-09 06:16:32 +0000255 return false;
256 case ObjectFile::eTypeExecutable:
257 case ObjectFile::eTypeDynamicLinker:
258 case ObjectFile::eTypeUnknown:
259 break;
260 }
Greg Claytonaa149cb2011-08-11 02:48:45 +0000261 return exe_module->GetFileSpec().Exists();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000262 }
Jim Ingham5aee1622010-08-09 23:31:02 +0000263 // However, if there is no executable module, we return true since we might be preparing to attach.
264 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000265}
266
Eugene Zelenko0722f082015-10-24 01:28:05 +0000267//----------------------------------------------------------------------
268// ProcessGDBRemote constructor
269//----------------------------------------------------------------------
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000270ProcessGDBRemote::ProcessGDBRemote(lldb::TargetSP target_sp, ListenerSP listener_sp)
271 : Process(target_sp, listener_sp),
272 m_flags(0),
273 m_gdb_comm(),
274 m_debugserver_pid(LLDB_INVALID_PROCESS_ID),
275 m_last_stop_packet_mutex(),
276 m_register_info(),
277 m_async_broadcaster(NULL, "lldb.process.gdb-remote.async-broadcaster"),
278 m_async_listener_sp(Listener::MakeListener("lldb.process.gdb-remote.async-listener")),
279 m_async_thread_state_mutex(),
280 m_thread_ids(),
281 m_thread_pcs(),
282 m_jstopinfo_sp(),
283 m_jthreadsinfo_sp(),
284 m_continue_c_tids(),
285 m_continue_C_tids(),
286 m_continue_s_tids(),
287 m_continue_S_tids(),
288 m_max_memory_size(0),
289 m_remote_stub_max_memory_size(0),
290 m_addr_to_mmap_size(),
291 m_thread_create_bp_sp(),
292 m_waiting_for_attach(false),
293 m_destroy_tried_resuming(false),
294 m_command_sp(),
295 m_breakpoint_pc_offset(0),
296 m_initial_tid(LLDB_INVALID_THREAD_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000297{
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000298 m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
299 m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue, "async thread continue");
300 m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Pavel Labath50556852015-09-03 09:36:22 +0000301
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000302 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_ASYNC));
Pavel Labath50556852015-09-03 09:36:22 +0000303
304 const uint32_t async_event_mask = eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
305
Jim Ingham583bbb12016-03-07 21:50:25 +0000306 if (m_async_listener_sp->StartListeningForEvents(&m_async_broadcaster, async_event_mask) != async_event_mask)
Pavel Labath50556852015-09-03 09:36:22 +0000307 {
308 if (log)
309 log->Printf("ProcessGDBRemote::%s failed to listen for m_async_broadcaster events", __FUNCTION__);
310 }
311
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000312 const uint32_t gdb_event_mask =
313 Communication::eBroadcastBitReadThreadDidExit | GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify;
Jim Ingham583bbb12016-03-07 21:50:25 +0000314 if (m_async_listener_sp->StartListeningForEvents(&m_gdb_comm, gdb_event_mask) != gdb_event_mask)
Pavel Labath50556852015-09-03 09:36:22 +0000315 {
316 if (log)
317 log->Printf("ProcessGDBRemote::%s failed to listen for m_gdb_comm events", __FUNCTION__);
318 }
319
Greg Clayton7f982402013-07-15 22:54:20 +0000320 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
321 if (timeout_seconds > 0)
322 m_gdb_comm.SetPacketTimeout(timeout_seconds);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000323}
324
Eugene Zelenko0722f082015-10-24 01:28:05 +0000325//----------------------------------------------------------------------
326// Destructor
327//----------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000328ProcessGDBRemote::~ProcessGDBRemote()
329{
330 // m_mach_process.UnregisterNotificationCallbacks (this);
331 Clear();
Greg Clayton1ed54f52011-10-01 00:45:15 +0000332 // We need to call finalize on the process before destroying ourselves
333 // to make sure all of the broadcaster cleanup goes as planned. If we
334 // destruct this class, then Process::~Process() might have problems
335 // trying to fully destroy the broadcaster.
336 Finalize();
Ed Maste81b4c5f2016-01-04 01:43:47 +0000337
Jim Ingham455fa5c2012-11-01 01:15:33 +0000338 // The general Finalize is going to try to destroy the process and that SHOULD
339 // shut down the async thread. However, if we don't kill it it will get stranded and
340 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
341 StopAsyncThread();
342 KillDebugserverProcess();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000343}
344
345//----------------------------------------------------------------------
346// PluginInterface
347//----------------------------------------------------------------------
Greg Clayton57abc5d2013-05-10 21:47:16 +0000348ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000349ProcessGDBRemote::GetPluginName()
350{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000351 return GetPluginNameStatic();
352}
353
354uint32_t
355ProcessGDBRemote::GetPluginVersion()
356{
357 return 1;
358}
359
Greg Claytonef8180a2013-10-15 00:14:28 +0000360bool
361ProcessGDBRemote::ParsePythonTargetDefinition(const FileSpec &target_definition_fspec)
362{
363 ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
364 Error error;
Zachary Turner0641ca12015-03-17 20:04:04 +0000365 StructuredData::ObjectSP module_object_sp(interpreter->LoadPluginModule(target_definition_fspec, error));
Greg Claytonef8180a2013-10-15 00:14:28 +0000366 if (module_object_sp)
367 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000368 StructuredData::DictionarySP target_definition_sp(
369 interpreter->GetDynamicSettings(module_object_sp, &GetTarget(), "gdb-server-target-definition", error));
Greg Claytonef8180a2013-10-15 00:14:28 +0000370
Zachary Turner0641ca12015-03-17 20:04:04 +0000371 if (target_definition_sp)
Greg Claytonef8180a2013-10-15 00:14:28 +0000372 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000373 StructuredData::ObjectSP target_object(target_definition_sp->GetValueForKey("host-info"));
374 if (target_object)
Greg Clayton312bcbe2013-10-17 01:10:23 +0000375 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000376 if (auto host_info_dict = target_object->GetAsDictionary())
Greg Clayton312bcbe2013-10-17 01:10:23 +0000377 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000378 StructuredData::ObjectSP triple_value = host_info_dict->GetValueForKey("triple");
379 if (auto triple_string_value = triple_value->GetAsString())
380 {
381 std::string triple_string = triple_string_value->GetValue();
382 ArchSpec host_arch(triple_string.c_str());
383 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture()))
384 {
385 GetTarget().SetArchitecture(host_arch);
386 }
387 }
Greg Clayton312bcbe2013-10-17 01:10:23 +0000388 }
Greg Clayton312bcbe2013-10-17 01:10:23 +0000389 }
Zachary Turner0641ca12015-03-17 20:04:04 +0000390 m_breakpoint_pc_offset = 0;
391 StructuredData::ObjectSP breakpoint_pc_offset_value = target_definition_sp->GetValueForKey("breakpoint-pc-offset");
392 if (breakpoint_pc_offset_value)
393 {
394 if (auto breakpoint_pc_int_value = breakpoint_pc_offset_value->GetAsInteger())
395 m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
396 }
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000397
Greg Claytond04f0ed2015-05-26 18:00:51 +0000398 if (m_register_info.SetRegisterInfo(*target_definition_sp, GetTarget().GetArchitecture()) > 0)
Greg Claytonef8180a2013-10-15 00:14:28 +0000399 {
400 return true;
401 }
402 }
403 }
404 return false;
405}
406
Jason Molenda21586c82015-09-09 03:36:24 +0000407// If the remote stub didn't give us eh_frame or DWARF register numbers for a register,
408// see if the ABI can provide them.
409// DWARF and eh_frame register numbers are defined as a part of the ABI.
410static void
411AugmentRegisterInfoViaABI (RegisterInfo &reg_info, ConstString reg_name, ABISP abi_sp)
412{
413 if (reg_info.kinds[eRegisterKindEHFrame] == LLDB_INVALID_REGNUM
414 || reg_info.kinds[eRegisterKindDWARF] == LLDB_INVALID_REGNUM)
415 {
416 if (abi_sp)
417 {
418 RegisterInfo abi_reg_info;
419 if (abi_sp->GetRegisterInfoByName (reg_name, abi_reg_info))
420 {
Greg Claytonb1583dc2015-12-04 18:37:48 +0000421 if (reg_info.kinds[eRegisterKindEHFrame] == LLDB_INVALID_REGNUM &&
422 abi_reg_info.kinds[eRegisterKindEHFrame] != LLDB_INVALID_REGNUM)
Jason Molenda21586c82015-09-09 03:36:24 +0000423 {
424 reg_info.kinds[eRegisterKindEHFrame] = abi_reg_info.kinds[eRegisterKindEHFrame];
425 }
Greg Claytonb1583dc2015-12-04 18:37:48 +0000426 if (reg_info.kinds[eRegisterKindDWARF] == LLDB_INVALID_REGNUM &&
427 abi_reg_info.kinds[eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
Jason Molenda21586c82015-09-09 03:36:24 +0000428 {
429 reg_info.kinds[eRegisterKindDWARF] = abi_reg_info.kinds[eRegisterKindDWARF];
430 }
Greg Claytonb1583dc2015-12-04 18:37:48 +0000431 if (reg_info.kinds[eRegisterKindGeneric] == LLDB_INVALID_REGNUM &&
432 abi_reg_info.kinds[eRegisterKindGeneric] != LLDB_INVALID_REGNUM)
433 {
434 reg_info.kinds[eRegisterKindGeneric] = abi_reg_info.kinds[eRegisterKindGeneric];
435 }
Jason Molenda21586c82015-09-09 03:36:24 +0000436 }
437 }
438 }
439}
440
Greg Claytond04f0ed2015-05-26 18:00:51 +0000441static size_t
442SplitCommaSeparatedRegisterNumberString(const llvm::StringRef &comma_separated_regiter_numbers, std::vector<uint32_t> &regnums, int base)
443{
444 regnums.clear();
445 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
446 value_pair.second = comma_separated_regiter_numbers;
447 do
448 {
449 value_pair = value_pair.second.split(',');
450 if (!value_pair.first.empty())
451 {
452 uint32_t reg = StringConvert::ToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, base);
453 if (reg != LLDB_INVALID_REGNUM)
454 regnums.push_back (reg);
455 }
456 } while (!value_pair.second.empty());
457 return regnums.size();
458}
459
Eugene Zelenko0722f082015-10-24 01:28:05 +0000460
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000461void
Greg Clayton513c26c2011-01-29 07:10:55 +0000462ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000463{
Greg Clayton513c26c2011-01-29 07:10:55 +0000464 if (!force && m_register_info.GetNumRegisters() > 0)
465 return;
466
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000467 m_register_info.Clear();
Greg Claytond04f0ed2015-05-26 18:00:51 +0000468
469 // Check if qHostInfo specified a specific packet timeout for this connection.
470 // If so then lets update our setting so the user knows what the timeout is
471 // and can see it.
472 const uint32_t host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
473 if (host_packet_timeout)
474 {
475 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout);
476 }
477
Ed Maste81b4c5f2016-01-04 01:43:47 +0000478 // Register info search order:
Ewan Crawford0c996a92015-06-30 13:08:44 +0000479 // 1 - Use the target definition python file if one is specified.
480 // 2 - If the target definition doesn't have any of the info from the target.xml (registers) then proceed to read the target.xml.
481 // 3 - Fall back on the qRegisterInfo packets.
482
483 FileSpec target_definition_fspec = GetGlobalPluginProperties()->GetTargetDefinitionFile ();
Jason Molenda91e468c2015-08-20 04:29:46 +0000484 if (!target_definition_fspec.Exists())
485 {
486 // If the filename doesn't exist, it may be a ~ not having been expanded - try to resolve it.
487 target_definition_fspec.ResolvePath();
488 }
Ewan Crawford0c996a92015-06-30 13:08:44 +0000489 if (target_definition_fspec)
490 {
491 // See if we can get register definitions from a python file
492 if (ParsePythonTargetDefinition (target_definition_fspec))
Jason Molenda5543abb2015-08-20 03:05:09 +0000493 {
Ewan Crawford0c996a92015-06-30 13:08:44 +0000494 return;
Jason Molenda5543abb2015-08-20 03:05:09 +0000495 }
496 else
497 {
498 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
499 stream_sp->Printf ("ERROR: target description file %s failed to parse.\n", target_definition_fspec.GetPath().c_str());
500 }
Ewan Crawford0c996a92015-06-30 13:08:44 +0000501 }
502
Jim Ingham7b71c0b2016-02-18 23:58:45 +0000503 const ArchSpec &target_arch = GetTarget().GetArchitecture();
504 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
505 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
506
507 // Use the process' architecture instead of the host arch, if available
508 ArchSpec arch_to_use;
509 if (remote_process_arch.IsValid ())
510 arch_to_use = remote_process_arch;
511 else
512 arch_to_use = remote_host_arch;
513
514 if (!arch_to_use.IsValid())
515 arch_to_use = target_arch;
516
517 if (GetGDBServerRegisterInfo (arch_to_use))
Greg Claytond04f0ed2015-05-26 18:00:51 +0000518 return;
Ed Maste81b4c5f2016-01-04 01:43:47 +0000519
Greg Claytond04f0ed2015-05-26 18:00:51 +0000520 char packet[128];
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000521 uint32_t reg_offset = 0;
522 uint32_t reg_num = 0;
Greg Clayton23f59502012-07-17 03:23:13 +0000523 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Ed Maste81b4c5f2016-01-04 01:43:47 +0000524 response_type == StringExtractorGDBRemote::eResponse;
Greg Clayton576d8832011-03-22 04:00:09 +0000525 ++reg_num)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000526 {
Greg Clayton513c26c2011-01-29 07:10:55 +0000527 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
Andy Gibbsa297a972013-06-19 19:04:53 +0000528 assert (packet_len < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000529 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000530 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000531 {
Greg Clayton576d8832011-03-22 04:00:09 +0000532 response_type = response.GetResponseType();
533 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000534 {
535 std::string name;
536 std::string value;
537 ConstString reg_name;
538 ConstString alt_name;
539 ConstString set_name;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000540 std::vector<uint32_t> value_regs;
541 std::vector<uint32_t> invalidate_regs;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000542 RegisterInfo reg_info = { NULL, // Name
543 NULL, // Alt name
544 0, // byte size
545 reg_offset, // offset
546 eEncodingUint, // encoding
Jason Molendabf67a302015-09-01 05:17:01 +0000547 eFormatHex, // format
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000548 {
Jason Molendabf67a302015-09-01 05:17:01 +0000549 LLDB_INVALID_REGNUM, // eh_frame reg num
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000550 LLDB_INVALID_REGNUM, // DWARF reg num
551 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda63bd0db2015-09-15 23:20:34 +0000552 reg_num, // process plugin reg num
Jason Molendafbcb7f22010-09-10 07:49:16 +0000553 reg_num // native register number
Greg Clayton435d85a2012-02-29 19:27:27 +0000554 },
555 NULL,
556 NULL
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000557 };
558
559 while (response.GetNameColonValue(name, value))
560 {
561 if (name.compare("name") == 0)
562 {
563 reg_name.SetCString(value.c_str());
564 }
565 else if (name.compare("alt-name") == 0)
566 {
567 alt_name.SetCString(value.c_str());
568 }
569 else if (name.compare("bitsize") == 0)
570 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000571 reg_info.byte_size = StringConvert::ToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000572 }
573 else if (name.compare("offset") == 0)
574 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000575 uint32_t offset = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda743e86a2010-06-11 23:44:18 +0000576 if (reg_offset != offset)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000577 {
578 reg_offset = offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000579 }
580 }
581 else if (name.compare("encoding") == 0)
582 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000583 const Encoding encoding = Args::StringToEncoding (value.c_str());
584 if (encoding != eEncodingInvalid)
585 reg_info.encoding = encoding;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000586 }
587 else if (name.compare("format") == 0)
588 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000589 Format format = eFormatInvalid;
590 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
591 reg_info.format = format;
592 else if (value.compare("binary") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000593 reg_info.format = eFormatBinary;
594 else if (value.compare("decimal") == 0)
595 reg_info.format = eFormatDecimal;
596 else if (value.compare("hex") == 0)
597 reg_info.format = eFormatHex;
598 else if (value.compare("float") == 0)
599 reg_info.format = eFormatFloat;
600 else if (value.compare("vector-sint8") == 0)
601 reg_info.format = eFormatVectorOfSInt8;
602 else if (value.compare("vector-uint8") == 0)
603 reg_info.format = eFormatVectorOfUInt8;
604 else if (value.compare("vector-sint16") == 0)
605 reg_info.format = eFormatVectorOfSInt16;
606 else if (value.compare("vector-uint16") == 0)
607 reg_info.format = eFormatVectorOfUInt16;
608 else if (value.compare("vector-sint32") == 0)
609 reg_info.format = eFormatVectorOfSInt32;
610 else if (value.compare("vector-uint32") == 0)
611 reg_info.format = eFormatVectorOfUInt32;
612 else if (value.compare("vector-float32") == 0)
613 reg_info.format = eFormatVectorOfFloat32;
614 else if (value.compare("vector-uint128") == 0)
615 reg_info.format = eFormatVectorOfUInt128;
616 }
617 else if (name.compare("set") == 0)
618 {
619 set_name.SetCString(value.c_str());
620 }
Jason Molendaa18f7072015-08-15 01:21:01 +0000621 else if (name.compare("gcc") == 0 || name.compare("ehframe") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000622 {
Jason Molendaa18f7072015-08-15 01:21:01 +0000623 reg_info.kinds[eRegisterKindEHFrame] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000624 }
625 else if (name.compare("dwarf") == 0)
626 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000627 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000628 }
629 else if (name.compare("generic") == 0)
630 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000631 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000632 }
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000633 else if (name.compare("container-regs") == 0)
634 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000635 SplitCommaSeparatedRegisterNumberString(value, value_regs, 16);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000636 }
637 else if (name.compare("invalidate-regs") == 0)
638 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000639 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 16);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000640 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000641 }
642
Jason Molenda743e86a2010-06-11 23:44:18 +0000643 reg_info.byte_offset = reg_offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000644 assert (reg_info.byte_size != 0);
645 reg_offset += reg_info.byte_size;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000646 if (!value_regs.empty())
647 {
648 value_regs.push_back(LLDB_INVALID_REGNUM);
649 reg_info.value_regs = value_regs.data();
650 }
651 if (!invalidate_regs.empty())
652 {
653 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
654 reg_info.invalidate_regs = invalidate_regs.data();
655 }
656
Jim Ingham7b71c0b2016-02-18 23:58:45 +0000657 // We have to make a temporary ABI here, and not use the GetABI because this code
658 // gets called in DidAttach, when the target architecture (and consequently the ABI we'll get from
659 // the process) may be wrong.
660 ABISP abi_to_use = ABI::FindPlugin(arch_to_use);
661
662 AugmentRegisterInfoViaABI (reg_info, reg_name, abi_to_use);
Jason Molenda21586c82015-09-09 03:36:24 +0000663
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000664 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
665 }
Todd Fiala1a634402014-01-08 07:52:40 +0000666 else
667 {
668 break; // ensure exit before reg_num is incremented
669 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000670 }
671 else
672 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000673 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000674 }
675 }
676
Greg Claytond04f0ed2015-05-26 18:00:51 +0000677 if (m_register_info.GetNumRegisters() > 0)
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000678 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000679 m_register_info.Finalize(GetTarget().GetArchitecture());
680 return;
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000681 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000682
Johnny Chen2fa9de12012-05-14 18:44:23 +0000683 // We didn't get anything if the accumulated reg_num is zero. See if we are
684 // debugging ARM and fill with a hard coded register set until we can get an
685 // updated debugserver down on the devices.
686 // On the other hand, if the accumulated reg_num is positive, see if we can
687 // add composite registers to the existing primordial ones.
Greg Claytond04f0ed2015-05-26 18:00:51 +0000688 bool from_scratch = (m_register_info.GetNumRegisters() == 0);
Johnny Chen2fa9de12012-05-14 18:44:23 +0000689
Johnny Chen2fa9de12012-05-14 18:44:23 +0000690 if (!target_arch.IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000691 {
Jim Ingham7b71c0b2016-02-18 23:58:45 +0000692 if (arch_to_use.IsValid()
693 && (arch_to_use.GetMachine() == llvm::Triple::arm || arch_to_use.GetMachine() == llvm::Triple::thumb)
694 && arch_to_use.GetTriple().getVendor() == llvm::Triple::Apple)
Johnny Chen2fa9de12012-05-14 18:44:23 +0000695 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000696 }
Jason Molenda6d9fe8c2015-08-21 00:13:37 +0000697 else if (target_arch.GetMachine() == llvm::Triple::arm
698 || target_arch.GetMachine() == llvm::Triple::thumb)
Johnny Chen2fa9de12012-05-14 18:44:23 +0000699 {
700 m_register_info.HardcodeARMRegisters(from_scratch);
701 }
702
703 // At this point, we can finalize our register info.
Greg Claytond04f0ed2015-05-26 18:00:51 +0000704 m_register_info.Finalize (GetTarget().GetArchitecture());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000705}
706
707Error
708ProcessGDBRemote::WillLaunch (Module* module)
709{
710 return WillLaunchOrAttach ();
711}
712
713Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000714ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000715{
716 return WillLaunchOrAttach ();
717}
718
719Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000720ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000721{
722 return WillLaunchOrAttach ();
723}
724
725Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000726ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +0000727{
Todd Fialaaf245d12014-06-30 21:05:18 +0000728 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Claytonb766a732011-02-04 01:58:07 +0000729 Error error (WillLaunchOrAttach ());
Ed Maste81b4c5f2016-01-04 01:43:47 +0000730
Greg Claytonb766a732011-02-04 01:58:07 +0000731 if (error.Fail())
732 return error;
733
Greg Clayton2289fa42011-04-30 01:09:13 +0000734 error = ConnectToDebugserver (remote_url);
Greg Claytonb766a732011-02-04 01:58:07 +0000735
736 if (error.Fail())
737 return error;
738 StartAsyncThread ();
739
Greg Claytonc574ede2011-03-10 02:26:48 +0000740 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonb766a732011-02-04 01:58:07 +0000741 if (pid == LLDB_INVALID_PROCESS_ID)
742 {
743 // We don't have a valid process ID, so note that we are connected
Ed Maste81b4c5f2016-01-04 01:43:47 +0000744 // and could now request to launch or attach, or get remote process
Greg Claytonb766a732011-02-04 01:58:07 +0000745 // listings...
746 SetPrivateState (eStateConnected);
747 }
748 else
749 {
750 // We have a valid process
751 SetID (pid);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000752 GetThreadList();
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000753 StringExtractorGDBRemote response;
754 if (m_gdb_comm.GetStopReply(response))
Greg Claytonb766a732011-02-04 01:58:07 +0000755 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000756 SetLastStopPacket(response);
Ewan Crawford78baa192015-05-13 09:18:18 +0000757
758 // '?' Packets must be handled differently in non-stop mode
759 if (GetTarget().GetNonStopModeEnabled())
760 HandleStopReplySequence();
761
Zachary Turner7529df92015-09-01 20:02:29 +0000762 Target &target = GetTarget();
Ed Maste81b4c5f2016-01-04 01:43:47 +0000763 if (!target.GetArchitecture().IsValid())
Jason Molendac62bd7b2013-12-21 05:20:36 +0000764 {
765 if (m_gdb_comm.GetProcessArchitecture().IsValid())
766 {
Zachary Turner7529df92015-09-01 20:02:29 +0000767 target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
Jason Molendac62bd7b2013-12-21 05:20:36 +0000768 }
769 else
770 {
Zachary Turner7529df92015-09-01 20:02:29 +0000771 target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molendac62bd7b2013-12-21 05:20:36 +0000772 }
Carlo Kok74389122013-10-14 07:09:13 +0000773 }
774
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000775 const StateType state = SetThreadStopInfo (response);
Greg Clayton2e309072015-07-17 23:42:28 +0000776 if (state != eStateInvalid)
Greg Claytonb766a732011-02-04 01:58:07 +0000777 {
778 SetPrivateState (state);
779 }
780 else
Daniel Malead01b2952012-11-29 21:49:15 +0000781 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 +0000782 }
783 else
Daniel Malead01b2952012-11-29 21:49:15 +0000784 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 +0000785 }
Jason Molenda16d127c2012-05-03 22:37:30 +0000786
Todd Fialaaf245d12014-06-30 21:05:18 +0000787 if (log)
788 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");
789
790
791 if (error.Success()
Jason Molenda16d127c2012-05-03 22:37:30 +0000792 && !GetTarget().GetArchitecture().IsValid()
793 && m_gdb_comm.GetHostArchitecture().IsValid())
794 {
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000795 // Prefer the *process'* architecture over that of the *host*, if available.
796 if (m_gdb_comm.GetProcessArchitecture().IsValid())
797 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
798 else
799 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molenda16d127c2012-05-03 22:37:30 +0000800 }
801
Todd Fialaaf245d12014-06-30 21:05:18 +0000802 if (log)
803 log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": normalized target architecture triple: %s", __FUNCTION__, GetID (), GetTarget ().GetArchitecture ().GetTriple ().getTriple ().c_str ());
804
Chaoren Lin98d0a4b2015-07-14 01:09:28 +0000805 if (error.Success())
Jaydeep Patil6fc590d2015-07-30 05:06:51 +0000806 {
807 PlatformSP platform_sp = GetTarget().GetPlatform();
808 if (platform_sp && platform_sp->IsConnected())
809 SetUnixSignals(platform_sp->GetUnixSignals());
810 else
811 SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
812 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000813
Greg Claytonb766a732011-02-04 01:58:07 +0000814 return error;
815}
816
817Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000818ProcessGDBRemote::WillLaunchOrAttach ()
819{
820 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000821 m_stdio_communication.Clear ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000822 return error;
823}
824
825//----------------------------------------------------------------------
826// Process Control
827//----------------------------------------------------------------------
828Error
Jean-Daniel Dupas7782de92013-12-09 22:52:50 +0000829ProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000830{
Todd Fiala75f47c32014-10-11 21:42:09 +0000831 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton4957bf62010-09-30 21:49:03 +0000832 Error error;
Greg Clayton982c9762011-11-03 21:22:33 +0000833
Todd Fiala75f47c32014-10-11 21:42:09 +0000834 if (log)
835 log->Printf ("ProcessGDBRemote::%s() entered", __FUNCTION__);
836
Greg Clayton982c9762011-11-03 21:22:33 +0000837 uint32_t launch_flags = launch_info.GetFlags().Get();
Chaoren Lind3173f32015-05-29 19:52:29 +0000838 FileSpec stdin_file_spec{};
839 FileSpec stdout_file_spec{};
840 FileSpec stderr_file_spec{};
841 FileSpec working_dir = launch_info.GetWorkingDirectory();
Greg Clayton982c9762011-11-03 21:22:33 +0000842
Zachary Turner696b5282014-08-14 16:01:25 +0000843 const FileAction *file_action;
Greg Clayton982c9762011-11-03 21:22:33 +0000844 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
845 if (file_action)
846 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000847 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000848 stdin_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000849 }
850 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
851 if (file_action)
852 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000853 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000854 stdout_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000855 }
856 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
857 if (file_action)
858 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000859 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000860 stderr_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000861 }
862
Todd Fiala75f47c32014-10-11 21:42:09 +0000863 if (log)
864 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000865 if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
Vince Harron4a8abd32015-02-13 19:15:24 +0000866 log->Printf ("ProcessGDBRemote::%s provided with STDIO paths via launch_info: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000867 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000868 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
869 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
870 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Todd Fiala75f47c32014-10-11 21:42:09 +0000871 else
872 log->Printf ("ProcessGDBRemote::%s no STDIO paths given via launch_info", __FUNCTION__);
873 }
874
Vince Harrondf3f00f2015-02-10 21:09:04 +0000875 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Chaoren Lind3173f32015-05-29 19:52:29 +0000876 if (stdin_file_spec || disable_stdio)
Vince Harrondf3f00f2015-02-10 21:09:04 +0000877 {
878 // the inferior will be reading stdin from the specified file
879 // or stdio is completely disabled
880 m_stdin_forward = false;
881 }
882 else
883 {
884 m_stdin_forward = true;
885 }
886
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000887 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
888 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
889 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000890
Greg Clayton982c9762011-11-03 21:22:33 +0000891 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000892 if (object_file)
893 {
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +0000894 error = EstablishConnectionIfNeeded (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000895 if (error.Success())
896 {
897 lldb_utility::PseudoTerminal pty;
898 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000899
Zachary Turner7529df92015-09-01 20:02:29 +0000900 PlatformSP platform_sp (GetTarget().GetPlatform());
Vince Harrondf3f00f2015-02-10 21:09:04 +0000901 if (disable_stdio)
Greg Clayton71337622011-02-24 22:24:29 +0000902 {
Vince Harrondf3f00f2015-02-10 21:09:04 +0000903 // set to /dev/null unless redirected to a file above
Chaoren Lind3173f32015-05-29 19:52:29 +0000904 if (!stdin_file_spec)
Zachary Turner4eff2d32015-10-14 21:37:36 +0000905 stdin_file_spec.SetFile(FileSystem::DEV_NULL, false);
Chaoren Lind3173f32015-05-29 19:52:29 +0000906 if (!stdout_file_spec)
Zachary Turner4eff2d32015-10-14 21:37:36 +0000907 stdout_file_spec.SetFile(FileSystem::DEV_NULL, false);
Chaoren Lind3173f32015-05-29 19:52:29 +0000908 if (!stderr_file_spec)
Zachary Turner4eff2d32015-10-14 21:37:36 +0000909 stderr_file_spec.SetFile(FileSystem::DEV_NULL, false);
Vince Harrondf3f00f2015-02-10 21:09:04 +0000910 }
911 else if (platform_sp && platform_sp->IsHost())
912 {
913 // If the debugserver is local and we aren't disabling STDIO, lets use
914 // a pseudo terminal to instead of relying on the 'O' packets for stdio
915 // since 'O' packets can really slow down debugging if the inferior
916 // does a lot of output.
Chaoren Lind3173f32015-05-29 19:52:29 +0000917 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
918 pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000919 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000920 FileSpec slave_name{pty.GetSlaveName(NULL, 0), false};
921
922 if (!stdin_file_spec)
923 stdin_file_spec = slave_name;
924
925 if (!stdout_file_spec)
926 stdout_file_spec = slave_name;
927
928 if (!stderr_file_spec)
929 stderr_file_spec = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000930 }
Todd Fiala75f47c32014-10-11 21:42:09 +0000931 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +0000932 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 +0000933 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000934 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
935 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
936 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Greg Clayton71337622011-02-24 22:24:29 +0000937 }
938
Todd Fiala75f47c32014-10-11 21:42:09 +0000939 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +0000940 log->Printf ("ProcessGDBRemote::%s final STDIO paths after all adjustments: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000941 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000942 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
943 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
944 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Todd Fiala75f47c32014-10-11 21:42:09 +0000945
Chaoren Lind3173f32015-05-29 19:52:29 +0000946 if (stdin_file_spec)
947 m_gdb_comm.SetSTDIN(stdin_file_spec);
948 if (stdout_file_spec)
949 m_gdb_comm.SetSTDOUT(stdout_file_spec);
950 if (stderr_file_spec)
951 m_gdb_comm.SetSTDERR(stderr_file_spec);
Greg Clayton71337622011-02-24 22:24:29 +0000952
953 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
Jim Ingham106d0282014-06-25 02:32:56 +0000954 m_gdb_comm.SetDetachOnError (launch_flags & eLaunchFlagDetachOnError);
Greg Clayton71337622011-02-24 22:24:29 +0000955
Zachary Turner7529df92015-09-01 20:02:29 +0000956 m_gdb_comm.SendLaunchArchPacket (GetTarget().GetArchitecture().GetArchitectureName());
Ed Maste81b4c5f2016-01-04 01:43:47 +0000957
Jason Molendaa3329782014-03-29 18:54:20 +0000958 const char * launch_event_data = launch_info.GetLaunchEventData();
959 if (launch_event_data != NULL && *launch_event_data != '\0')
960 m_gdb_comm.SendLaunchEventDataPacket (launch_event_data);
Ed Maste81b4c5f2016-01-04 01:43:47 +0000961
Chaoren Lind3173f32015-05-29 19:52:29 +0000962 if (working_dir)
Greg Clayton71337622011-02-24 22:24:29 +0000963 {
964 m_gdb_comm.SetWorkingDir (working_dir);
965 }
966
967 // Send the environment and the program + arguments after we connect
Greg Clayton982c9762011-11-03 21:22:33 +0000968 const Args &environment = launch_info.GetEnvironmentEntries();
969 if (environment.GetArgumentCount())
Greg Clayton71337622011-02-24 22:24:29 +0000970 {
Greg Clayton982c9762011-11-03 21:22:33 +0000971 size_t num_environment_entries = environment.GetArgumentCount();
972 for (size_t i=0; i<num_environment_entries; ++i)
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000973 {
Greg Clayton982c9762011-11-03 21:22:33 +0000974 const char *env_entry = environment.GetArgumentAtIndex(i);
975 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Clayton71337622011-02-24 22:24:29 +0000976 break;
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000977 }
Greg Clayton71337622011-02-24 22:24:29 +0000978 }
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000979
Greg Clayton71337622011-02-24 22:24:29 +0000980 {
Tamas Berghammer912800c2015-02-24 10:23:39 +0000981 // Scope for the scoped timeout object
982 GDBRemoteCommunication::ScopedTimeout timeout (m_gdb_comm, 10);
983
984 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
985 if (arg_packet_err == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000986 {
Tamas Berghammer912800c2015-02-24 10:23:39 +0000987 std::string error_str;
988 if (m_gdb_comm.GetLaunchSuccess (error_str))
989 {
990 SetID (m_gdb_comm.GetCurrentProcessID ());
991 }
992 else
993 {
994 error.SetErrorString (error_str.c_str());
995 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000996 }
997 else
998 {
Tamas Berghammer912800c2015-02-24 10:23:39 +0000999 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001000 }
Greg Clayton71337622011-02-24 22:24:29 +00001001 }
Tamas Berghammer912800c2015-02-24 10:23:39 +00001002
Greg Clayton71337622011-02-24 22:24:29 +00001003 if (GetID() == LLDB_INVALID_PROCESS_ID)
1004 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001005 if (log)
1006 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton71337622011-02-24 22:24:29 +00001007 KillDebugserverProcess ();
1008 return error;
1009 }
1010
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001011 StringExtractorGDBRemote response;
1012 if (m_gdb_comm.GetStopReply(response))
Greg Clayton71337622011-02-24 22:24:29 +00001013 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001014 SetLastStopPacket(response);
Ewan Crawford78baa192015-05-13 09:18:18 +00001015 // '?' Packets must be handled differently in non-stop mode
1016 if (GetTarget().GetNonStopModeEnabled())
1017 HandleStopReplySequence();
1018
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001019 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
1020
1021 if (process_arch.IsValid())
Jason Molendac62bd7b2013-12-21 05:20:36 +00001022 {
Zachary Turner7529df92015-09-01 20:02:29 +00001023 GetTarget().MergeArchitecture(process_arch);
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001024 }
1025 else
1026 {
1027 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
1028 if (host_arch.IsValid())
Zachary Turner7529df92015-09-01 20:02:29 +00001029 GetTarget().MergeArchitecture(host_arch);
Carlo Kok74389122013-10-14 07:09:13 +00001030 }
1031
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001032 SetPrivateState (SetThreadStopInfo (response));
Ed Maste81b4c5f2016-01-04 01:43:47 +00001033
Greg Clayton71337622011-02-24 22:24:29 +00001034 if (!disable_stdio)
1035 {
1036 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Claytonee95ed52011-11-17 22:14:31 +00001037 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Clayton71337622011-02-24 22:24:29 +00001038 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001039 }
1040 }
Greg Claytonc235ac72011-08-09 05:20:29 +00001041 else
1042 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001043 if (log)
1044 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytonc235ac72011-08-09 05:20:29 +00001045 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001046 }
1047 else
1048 {
1049 // Set our user ID to an invalid process ID.
1050 SetID(LLDB_INVALID_PROCESS_ID);
Ed Maste81b4c5f2016-01-04 01:43:47 +00001051 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
1052 exe_module->GetFileSpec().GetFilename().AsCString(),
Greg Clayton982c9762011-11-03 21:22:33 +00001053 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001054 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001055 return error;
Eugene Zelenko0722f082015-10-24 01:28:05 +00001056
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001057}
1058
Eugene Zelenko0722f082015-10-24 01:28:05 +00001059
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001060Error
Greg Claytonb766a732011-02-04 01:58:07 +00001061ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001062{
1063 Error error;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001064 // Only connect if we have a valid connect URL
Vince Harron1b5a74e2015-01-21 22:42:49 +00001065 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Ed Maste81b4c5f2016-01-04 01:43:47 +00001066
Greg Clayton00fe87b2013-12-05 22:58:22 +00001067 if (connect_url && connect_url[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001068 {
Vince Harron1b5a74e2015-01-21 22:42:49 +00001069 if (log)
1070 log->Printf("ProcessGDBRemote::%s Connecting to %s", __FUNCTION__, connect_url);
Greg Clayton00fe87b2013-12-05 22:58:22 +00001071 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
1072 if (conn_ap.get())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001073 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001074 const uint32_t max_retry_count = 50;
1075 uint32_t retry_count = 0;
1076 while (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001077 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001078 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
1079 {
1080 m_gdb_comm.SetConnection (conn_ap.release());
1081 break;
1082 }
1083 else if (error.WasInterrupted())
1084 {
1085 // If we were interrupted, don't keep retrying.
1086 break;
1087 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001088
Greg Clayton00fe87b2013-12-05 22:58:22 +00001089 retry_count++;
Ed Maste81b4c5f2016-01-04 01:43:47 +00001090
Greg Clayton00fe87b2013-12-05 22:58:22 +00001091 if (retry_count >= max_retry_count)
1092 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001093
Greg Clayton00fe87b2013-12-05 22:58:22 +00001094 usleep (100000);
1095 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001096 }
1097 }
1098
1099 if (!m_gdb_comm.IsConnected())
1100 {
1101 if (error.Success())
1102 error.SetErrorString("not connected to remote gdb server");
1103 return error;
1104 }
1105
Eugene Zelenko0722f082015-10-24 01:28:05 +00001106
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001107 // Start the communications read thread so all incoming data can be
1108 // parsed into packets and queued as they arrive.
1109 if (GetTarget().GetNonStopModeEnabled())
1110 m_gdb_comm.StartReadThread();
1111
Greg Clayton32e0a752011-03-30 18:16:51 +00001112 // We always seem to be able to open a connection to a local port
1113 // so we need to make sure we can then send data to it. If we can't
1114 // then we aren't actually connected to anything, so try and do the
Ed Maste81b4c5f2016-01-04 01:43:47 +00001115 // handshake with the remote GDB server and make sure that goes
Greg Clayton32e0a752011-03-30 18:16:51 +00001116 // alright.
Greg Claytonfb909312013-11-23 01:58:15 +00001117 if (!m_gdb_comm.HandshakeWithServer (&error))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001118 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001119 m_gdb_comm.Disconnect();
1120 if (error.Success())
1121 error.SetErrorString("not connected to remote gdb server");
1122 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001123 }
Ewan Crawford78baa192015-05-13 09:18:18 +00001124
1125 // Send $QNonStop:1 packet on startup if required
1126 if (GetTarget().GetNonStopModeEnabled())
Ewan Crawfordaa7eda72015-06-24 15:14:26 +00001127 GetTarget().SetNonStopModeEnabled (m_gdb_comm.SetNonStopMode(true));
Ewan Crawford78baa192015-05-13 09:18:18 +00001128
Greg Claytonb30c50c2015-05-29 00:01:55 +00001129 m_gdb_comm.GetEchoSupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001130 m_gdb_comm.GetThreadSuffixSupported ();
Greg Clayton44633992012-04-10 03:22:03 +00001131 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001132 m_gdb_comm.GetHostInfo ();
1133 m_gdb_comm.GetVContSupported ('c');
Jim Inghamcd16df92012-07-20 21:37:13 +00001134 m_gdb_comm.GetVAttachOrWaitSupported();
Ewan Crawford78baa192015-05-13 09:18:18 +00001135
1136 // Ask the remote server for the default thread id
1137 if (GetTarget().GetNonStopModeEnabled())
1138 m_gdb_comm.GetDefaultThreadId(m_initial_tid);
1139
1140
Jim Ingham03afad82012-07-02 05:40:07 +00001141 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1142 for (size_t idx = 0; idx < num_cmds; idx++)
1143 {
1144 StringExtractorGDBRemote response;
Jim Ingham03afad82012-07-02 05:40:07 +00001145 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1146 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001147 return error;
1148}
1149
1150void
Jim Inghambb006ce2014-08-02 00:33:35 +00001151ProcessGDBRemote::DidLaunchOrAttach (ArchSpec& process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001152{
Greg Clayton5160ce52013-03-27 23:08:40 +00001153 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001154 if (log)
1155 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton93d3c8332011-02-16 04:46:07 +00001156 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001157 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001158 BuildDynamicRegisterInfo (false);
Greg Clayton3af9ea52010-11-18 05:57:03 +00001159
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001160 // See if the GDB server supports the qHostInfo information
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001161
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001162
1163 // See if the GDB server supports the qProcessInfo packet, if so
1164 // prefer that over the Host information as it will be more specific
1165 // to our process.
1166
Todd Fiala75f47c32014-10-11 21:42:09 +00001167 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1168 if (remote_process_arch.IsValid())
1169 {
1170 process_arch = remote_process_arch;
1171 if (log)
1172 log->Printf ("ProcessGDBRemote::%s gdb-remote had process architecture, using %s %s",
1173 __FUNCTION__,
1174 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1175 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1176 }
Jim Inghambb006ce2014-08-02 00:33:35 +00001177 else
Todd Fiala75f47c32014-10-11 21:42:09 +00001178 {
Jim Inghambb006ce2014-08-02 00:33:35 +00001179 process_arch = m_gdb_comm.GetHostArchitecture();
Todd Fiala75f47c32014-10-11 21:42:09 +00001180 if (log)
1181 log->Printf ("ProcessGDBRemote::%s gdb-remote did not have process architecture, using gdb-remote host architecture %s %s",
1182 __FUNCTION__,
1183 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1184 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1185 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001186
Jim Inghambb006ce2014-08-02 00:33:35 +00001187 if (process_arch.IsValid())
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001188 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001189 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Greg Claytond314e812011-03-23 00:09:55 +00001190 if (target_arch.IsValid())
1191 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001192 if (log)
1193 log->Printf ("ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1194 __FUNCTION__,
1195 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1196 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
1197
1198 // If the remote host is ARM and we have apple as the vendor, then
Greg Claytond314e812011-03-23 00:09:55 +00001199 // ARM executables and shared libraries can have mixed ARM architectures.
1200 // You can have an armv6 executable, and if the host is armv7, then the
1201 // system will load the best possible architecture for all shared libraries
1202 // it has, so we really need to take the remote host architecture as our
1203 // defacto architecture in this case.
1204
Jason Molenda6d9fe8c2015-08-21 00:13:37 +00001205 if ((process_arch.GetMachine() == llvm::Triple::arm || process_arch.GetMachine() == llvm::Triple::thumb)
1206 && process_arch.GetTriple().getVendor() == llvm::Triple::Apple)
Greg Claytond314e812011-03-23 00:09:55 +00001207 {
Jason Molenda921c01b2014-08-03 21:42:52 +00001208 GetTarget().SetArchitecture (process_arch);
Todd Fiala75f47c32014-10-11 21:42:09 +00001209 if (log)
1210 log->Printf ("ProcessGDBRemote::%s remote process is ARM/Apple, setting target arch to %s %s",
1211 __FUNCTION__,
1212 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1213 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001214 }
1215 else
1216 {
1217 // Fill in what is missing in the triple
Jim Inghambb006ce2014-08-02 00:33:35 +00001218 const llvm::Triple &remote_triple = process_arch.GetTriple();
Tamas Berghammere724af12015-03-13 10:32:37 +00001219 llvm::Triple new_target_triple = target_arch.GetTriple();
1220 if (new_target_triple.getVendorName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001221 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001222 new_target_triple.setVendor (remote_triple.getVendor());
Greg Claytond314e812011-03-23 00:09:55 +00001223
Tamas Berghammere724af12015-03-13 10:32:37 +00001224 if (new_target_triple.getOSName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001225 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001226 new_target_triple.setOS (remote_triple.getOS());
Greg Claytond314e812011-03-23 00:09:55 +00001227
Tamas Berghammere724af12015-03-13 10:32:37 +00001228 if (new_target_triple.getEnvironmentName().size() == 0)
1229 new_target_triple.setEnvironment (remote_triple.getEnvironment());
Greg Clayton70b57652011-05-15 01:25:55 +00001230 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001231
Tamas Berghammere724af12015-03-13 10:32:37 +00001232 ArchSpec new_target_arch = target_arch;
1233 new_target_arch.SetTriple(new_target_triple);
1234 GetTarget().SetArchitecture(new_target_arch);
1235 }
Greg Claytond314e812011-03-23 00:09:55 +00001236 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001237
1238 if (log)
1239 log->Printf ("ProcessGDBRemote::%s final target arch after adjustments for remote architecture: %s %s",
1240 __FUNCTION__,
1241 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1242 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001243 }
1244 else
1245 {
1246 // The target doesn't have a valid architecture yet, set it from
1247 // the architecture we got from the remote GDB server
Jason Molenda921c01b2014-08-03 21:42:52 +00001248 GetTarget().SetArchitecture (process_arch);
Greg Claytond314e812011-03-23 00:09:55 +00001249 }
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001250 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001251 }
1252}
1253
1254void
1255ProcessGDBRemote::DidLaunch ()
1256{
Jim Inghambb006ce2014-08-02 00:33:35 +00001257 ArchSpec process_arch;
1258 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001259}
1260
1261Error
Han Ming Ong84647042012-02-25 01:07:38 +00001262ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1263{
Todd Fiala75f47c32014-10-11 21:42:09 +00001264 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001265 Error error;
Todd Fiala75f47c32014-10-11 21:42:09 +00001266
1267 if (log)
1268 log->Printf ("ProcessGDBRemote::%s()", __FUNCTION__);
1269
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001270 // Clear out and clean up from any current state
1271 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001272 if (attach_pid != LLDB_INVALID_PROCESS_ID)
1273 {
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00001274 error = EstablishConnectionIfNeeded (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001275 if (error.Success())
1276 {
Jim Ingham106d0282014-06-25 02:32:56 +00001277 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
Todd Fiala75f47c32014-10-11 21:42:09 +00001278
Greg Clayton71337622011-02-24 22:24:29 +00001279 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001280 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Ed Maste81b4c5f2016-01-04 01:43:47 +00001281 SetID (attach_pid);
Greg Clayton71337622011-02-24 22:24:29 +00001282 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001283 }
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00001284 else
1285 SetExitStatus (-1, error.AsCString());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001286 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001287
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001288 return error;
1289}
1290
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001291Error
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001292ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001293{
1294 Error error;
1295 // Clear out and clean up from any current state
1296 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001297
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001298 if (process_name && process_name[0])
1299 {
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00001300 error = EstablishConnectionIfNeeded (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001301 if (error.Success())
1302 {
1303 StreamString packet;
Ed Maste81b4c5f2016-01-04 01:43:47 +00001304
Jim Ingham106d0282014-06-25 02:32:56 +00001305 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
Ed Maste81b4c5f2016-01-04 01:43:47 +00001306
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001307 if (attach_info.GetWaitForLaunch())
Jim Inghamcd16df92012-07-20 21:37:13 +00001308 {
1309 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1310 {
1311 packet.PutCString ("vAttachWait");
1312 }
1313 else
1314 {
1315 if (attach_info.GetIgnoreExisting())
1316 packet.PutCString("vAttachWait");
1317 else
1318 packet.PutCString ("vAttachOrWait");
1319 }
1320 }
Greg Clayton71337622011-02-24 22:24:29 +00001321 else
1322 packet.PutCString("vAttachName");
1323 packet.PutChar(';');
Bruce Mitchener9ccb9702015-11-07 04:40:13 +00001324 packet.PutBytesAsRawHex8(process_name, strlen(process_name), endian::InlHostByteOrder(), endian::InlHostByteOrder());
Ed Maste81b4c5f2016-01-04 01:43:47 +00001325
Greg Clayton71337622011-02-24 22:24:29 +00001326 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1327
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001328 }
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00001329 else
1330 SetExitStatus (-1, error.AsCString());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001331 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001332 return error;
1333}
1334
Greg Clayton5df78fa2015-05-23 03:54:53 +00001335void
1336ProcessGDBRemote::DidExit ()
Greg Claytonfbb76342013-11-20 21:07:01 +00001337{
Greg Clayton5df78fa2015-05-23 03:54:53 +00001338 // When we exit, disconnect from the GDB server communications
Greg Claytonfbb76342013-11-20 21:07:01 +00001339 m_gdb_comm.Disconnect();
Greg Claytonfbb76342013-11-20 21:07:01 +00001340}
1341
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001342void
Jim Inghambb006ce2014-08-02 00:33:35 +00001343ProcessGDBRemote::DidAttach (ArchSpec &process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001344{
Jim Inghambb006ce2014-08-02 00:33:35 +00001345 // If you can figure out what the architecture is, fill it in here.
1346 process_arch.Clear();
1347 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001348}
1349
Eugene Zelenko0722f082015-10-24 01:28:05 +00001350
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001351Error
1352ProcessGDBRemote::WillResume ()
1353{
Greg Clayton71fc2a32011-02-12 06:28:37 +00001354 m_continue_c_tids.clear();
1355 m_continue_C_tids.clear();
1356 m_continue_s_tids.clear();
1357 m_continue_S_tids.clear();
Greg Clayton2e309072015-07-17 23:42:28 +00001358 m_jstopinfo_sp.reset();
1359 m_jthreadsinfo_sp.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001360 return Error();
1361}
1362
1363Error
1364ProcessGDBRemote::DoResume ()
1365{
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001366 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001367 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001368 if (log)
1369 log->Printf ("ProcessGDBRemote::Resume()");
Ed Maste81b4c5f2016-01-04 01:43:47 +00001370
Jim Ingham583bbb12016-03-07 21:50:25 +00001371 ListenerSP listener_sp (Listener::MakeListener("gdb-remote.resume-packet-sent"));
1372 if (listener_sp->StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
Greg Claytone5219662010-12-03 06:02:24 +00001373 {
Jim Ingham583bbb12016-03-07 21:50:25 +00001374 listener_sp->StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
Ed Maste81b4c5f2016-01-04 01:43:47 +00001375
Greg Claytond1d06e42013-04-20 00:27:58 +00001376 const size_t num_threads = GetThreadList().GetSize();
1377
Greg Clayton71fc2a32011-02-12 06:28:37 +00001378 StreamString continue_packet;
1379 bool continue_packet_error = false;
1380 if (m_gdb_comm.HasAnyVContSupport ())
1381 {
Ewan Crawford78baa192015-05-13 09:18:18 +00001382 if (!GetTarget().GetNonStopModeEnabled() &&
1383 (m_continue_c_tids.size() == num_threads ||
Greg Claytone98008c2014-02-13 23:34:38 +00001384 (m_continue_c_tids.empty() &&
1385 m_continue_C_tids.empty() &&
1386 m_continue_s_tids.empty() &&
Ewan Crawford78baa192015-05-13 09:18:18 +00001387 m_continue_S_tids.empty())))
Greg Clayton71fc2a32011-02-12 06:28:37 +00001388 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001389 // All threads are continuing, just send a "c" packet
1390 continue_packet.PutCString ("c");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001391 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001392 else
1393 {
1394 continue_packet.PutCString ("vCont");
Ed Maste81b4c5f2016-01-04 01:43:47 +00001395
Greg Claytond1d06e42013-04-20 00:27:58 +00001396 if (!m_continue_c_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001397 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001398 if (m_gdb_comm.GetVContSupported ('c'))
1399 {
1400 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)
1401 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1402 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001403 else
Greg Claytond1d06e42013-04-20 00:27:58 +00001404 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001405 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001406
Greg Claytond1d06e42013-04-20 00:27:58 +00001407 if (!continue_packet_error && !m_continue_C_tids.empty())
1408 {
1409 if (m_gdb_comm.GetVContSupported ('C'))
1410 {
1411 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)
1412 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1413 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001414 else
Greg Claytond1d06e42013-04-20 00:27:58 +00001415 continue_packet_error = true;
1416 }
Greg Claytone5219662010-12-03 06:02:24 +00001417
Greg Claytond1d06e42013-04-20 00:27:58 +00001418 if (!continue_packet_error && !m_continue_s_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001419 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001420 if (m_gdb_comm.GetVContSupported ('s'))
1421 {
1422 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)
1423 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1424 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001425 else
Greg Claytond1d06e42013-04-20 00:27:58 +00001426 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001427 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001428
Greg Claytond1d06e42013-04-20 00:27:58 +00001429 if (!continue_packet_error && !m_continue_S_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001430 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001431 if (m_gdb_comm.GetVContSupported ('S'))
1432 {
1433 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)
1434 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1435 }
1436 else
1437 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001438 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001439
Greg Claytond1d06e42013-04-20 00:27:58 +00001440 if (continue_packet_error)
1441 continue_packet.GetString().clear();
Greg Clayton71fc2a32011-02-12 06:28:37 +00001442 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001443 }
1444 else
1445 continue_packet_error = true;
Ed Maste81b4c5f2016-01-04 01:43:47 +00001446
Greg Clayton71fc2a32011-02-12 06:28:37 +00001447 if (continue_packet_error)
1448 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001449 // Either no vCont support, or we tried to use part of the vCont
1450 // packet that wasn't supported by the remote GDB server.
1451 // We need to try and make a simple packet that can do our continue
Greg Clayton71fc2a32011-02-12 06:28:37 +00001452 const size_t num_continue_c_tids = m_continue_c_tids.size();
1453 const size_t num_continue_C_tids = m_continue_C_tids.size();
1454 const size_t num_continue_s_tids = m_continue_s_tids.size();
1455 const size_t num_continue_S_tids = m_continue_S_tids.size();
1456 if (num_continue_c_tids > 0)
1457 {
1458 if (num_continue_c_tids == num_threads)
1459 {
1460 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001461 m_gdb_comm.SetCurrentThreadForRun (-1);
Ed Maste81b4c5f2016-01-04 01:43:47 +00001462 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001463 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001464 }
1465 else if (num_continue_c_tids == 1 &&
Ed Maste81b4c5f2016-01-04 01:43:47 +00001466 num_continue_C_tids == 0 &&
1467 num_continue_s_tids == 0 &&
Greg Clayton71fc2a32011-02-12 06:28:37 +00001468 num_continue_S_tids == 0 )
1469 {
1470 // Only one thread is continuing
Greg Clayton8b82f082011-04-12 05:54:46 +00001471 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Ed Maste81b4c5f2016-01-04 01:43:47 +00001472 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001473 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001474 }
1475 }
1476
Greg Clayton0c74e782011-06-24 03:21:43 +00001477 if (continue_packet_error && num_continue_C_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001478 {
Ed Maste81b4c5f2016-01-04 01:43:47 +00001479 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1480 num_continue_C_tids > 0 &&
1481 num_continue_s_tids == 0 &&
Greg Clayton0c74e782011-06-24 03:21:43 +00001482 num_continue_S_tids == 0 )
Greg Clayton71fc2a32011-02-12 06:28:37 +00001483 {
1484 const int continue_signo = m_continue_C_tids.front().second;
Greg Clayton0c74e782011-06-24 03:21:43 +00001485 // Only one thread is continuing
Greg Clayton71fc2a32011-02-12 06:28:37 +00001486 if (num_continue_C_tids > 1)
1487 {
Ed Maste81b4c5f2016-01-04 01:43:47 +00001488 // More that one thread with a signal, yet we don't have
Greg Clayton0c74e782011-06-24 03:21:43 +00001489 // vCont support and we are being asked to resume each
1490 // thread with a signal, we need to make sure they are
1491 // all the same signal, or we can't issue the continue
1492 // accurately with the current support...
1493 if (num_continue_C_tids > 1)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001494 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001495 continue_packet_error = false;
1496 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1497 {
1498 if (m_continue_C_tids[i].second != continue_signo)
1499 continue_packet_error = true;
1500 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001501 }
Greg Clayton0c74e782011-06-24 03:21:43 +00001502 if (!continue_packet_error)
1503 m_gdb_comm.SetCurrentThreadForRun (-1);
1504 }
1505 else
1506 {
1507 // Set the continue thread ID
1508 continue_packet_error = false;
1509 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001510 }
1511 if (!continue_packet_error)
1512 {
1513 // Add threads continuing with the same signo...
Greg Clayton71fc2a32011-02-12 06:28:37 +00001514 continue_packet.Printf("C%2.2x", continue_signo);
1515 }
1516 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001517 }
1518
Greg Clayton0c74e782011-06-24 03:21:43 +00001519 if (continue_packet_error && num_continue_s_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001520 {
1521 if (num_continue_s_tids == num_threads)
1522 {
1523 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001524 m_gdb_comm.SetCurrentThreadForRun (-1);
Ewan Crawford76df2882015-06-23 12:32:06 +00001525
1526 // If in Non-Stop-Mode use vCont when stepping
1527 if (GetTarget().GetNonStopModeEnabled())
1528 {
1529 if (m_gdb_comm.GetVContSupported('s'))
1530 continue_packet.PutCString("vCont;s");
1531 else
1532 continue_packet.PutChar('s');
1533 }
1534 else
1535 continue_packet.PutChar('s');
1536
Greg Clayton0c74e782011-06-24 03:21:43 +00001537 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001538 }
1539 else if (num_continue_c_tids == 0 &&
Ed Maste81b4c5f2016-01-04 01:43:47 +00001540 num_continue_C_tids == 0 &&
1541 num_continue_s_tids == 1 &&
Greg Clayton71fc2a32011-02-12 06:28:37 +00001542 num_continue_S_tids == 0 )
1543 {
1544 // Only one thread is stepping
Greg Clayton8b82f082011-04-12 05:54:46 +00001545 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Ed Maste81b4c5f2016-01-04 01:43:47 +00001546 continue_packet.PutChar ('s');
Greg Clayton0c74e782011-06-24 03:21:43 +00001547 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001548 }
1549 }
1550
1551 if (!continue_packet_error && num_continue_S_tids > 0)
1552 {
1553 if (num_continue_S_tids == num_threads)
1554 {
1555 const int step_signo = m_continue_S_tids.front().second;
1556 // Are all threads trying to step with the same signal?
Greg Clayton0c74e782011-06-24 03:21:43 +00001557 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001558 if (num_continue_S_tids > 1)
1559 {
1560 for (size_t i=1; i<num_threads; ++i)
1561 {
1562 if (m_continue_S_tids[i].second != step_signo)
1563 continue_packet_error = true;
1564 }
1565 }
1566 if (!continue_packet_error)
1567 {
1568 // Add threads stepping with the same signo...
Greg Clayton8b82f082011-04-12 05:54:46 +00001569 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001570 continue_packet.Printf("S%2.2x", step_signo);
1571 }
1572 }
1573 else if (num_continue_c_tids == 0 &&
Ed Maste81b4c5f2016-01-04 01:43:47 +00001574 num_continue_C_tids == 0 &&
1575 num_continue_s_tids == 0 &&
Greg Clayton71fc2a32011-02-12 06:28:37 +00001576 num_continue_S_tids == 1 )
1577 {
1578 // Only one thread is stepping with signal
Greg Clayton8b82f082011-04-12 05:54:46 +00001579 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001580 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Clayton0c74e782011-06-24 03:21:43 +00001581 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001582 }
1583 }
1584 }
1585
1586 if (continue_packet_error)
1587 {
1588 error.SetErrorString ("can't make continue packet for this resume");
1589 }
1590 else
1591 {
1592 EventSP event_sp;
Zachary Turneracee96a2014-09-23 18:32:09 +00001593 if (!m_async_thread.IsJoinable())
Jim Inghamb1e2e842012-04-12 18:49:31 +00001594 {
1595 error.SetErrorString ("Trying to resume but the async thread is dead.");
1596 if (log)
1597 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1598 return error;
1599 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001600
Greg Clayton71fc2a32011-02-12 06:28:37 +00001601 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1602
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00001603 if (listener_sp->WaitForEvent(std::chrono::seconds(5), event_sp) == false)
Jim Inghamb1e2e842012-04-12 18:49:31 +00001604 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001605 error.SetErrorString("Resume timed out.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00001606 if (log)
1607 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1608 }
1609 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1610 {
1611 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1612 if (log)
1613 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1614 return error;
1615 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001616 }
Greg Claytone5219662010-12-03 06:02:24 +00001617 }
1618
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001619 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001620}
1621
Greg Clayton9e920902012-04-10 02:25:43 +00001622void
Ewan Crawford78baa192015-05-13 09:18:18 +00001623ProcessGDBRemote::HandleStopReplySequence ()
1624{
1625 while(true)
1626 {
1627 // Send vStopped
1628 StringExtractorGDBRemote response;
1629 m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false);
1630
1631 // OK represents end of signal list
1632 if (response.IsOKResponse())
1633 break;
1634
1635 // If not OK or a normal packet we have a problem
1636 if (!response.IsNormalResponse())
1637 break;
1638
1639 SetLastStopPacket(response);
1640 }
1641}
1642
1643void
Greg Clayton9e920902012-04-10 02:25:43 +00001644ProcessGDBRemote::ClearThreadIDList ()
1645{
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00001646 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001647 m_thread_ids.clear();
Jason Molenda545304d2015-12-18 00:45:35 +00001648 m_thread_pcs.clear();
Greg Clayton9e920902012-04-10 02:25:43 +00001649}
1650
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001651size_t
1652ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue (std::string &value)
1653{
1654 m_thread_ids.clear();
Jason Molenda545304d2015-12-18 00:45:35 +00001655 m_thread_pcs.clear();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001656 size_t comma_pos;
1657 lldb::tid_t tid;
1658 while ((comma_pos = value.find(',')) != std::string::npos)
1659 {
1660 value[comma_pos] = '\0';
1661 // thread in big endian hex
1662 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1663 if (tid != LLDB_INVALID_THREAD_ID)
1664 m_thread_ids.push_back (tid);
1665 value.erase(0, comma_pos + 1);
1666 }
1667 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1668 if (tid != LLDB_INVALID_THREAD_ID)
1669 m_thread_ids.push_back (tid);
1670 return m_thread_ids.size();
1671}
1672
Jason Molenda545304d2015-12-18 00:45:35 +00001673size_t
1674ProcessGDBRemote::UpdateThreadPCsFromStopReplyThreadsValue (std::string &value)
1675{
1676 m_thread_pcs.clear();
1677 size_t comma_pos;
1678 lldb::addr_t pc;
1679 while ((comma_pos = value.find(',')) != std::string::npos)
1680 {
1681 value[comma_pos] = '\0';
1682 pc = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
1683 if (pc != LLDB_INVALID_ADDRESS)
1684 m_thread_pcs.push_back (pc);
1685 value.erase(0, comma_pos + 1);
1686 }
1687 pc = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
1688 if (pc != LLDB_INVALID_THREAD_ID)
1689 m_thread_pcs.push_back (pc);
1690 return m_thread_pcs.size();
1691}
1692
Greg Clayton9e920902012-04-10 02:25:43 +00001693bool
1694ProcessGDBRemote::UpdateThreadIDList ()
1695{
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00001696 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001697
Greg Clayton2e309072015-07-17 23:42:28 +00001698 if (m_jthreadsinfo_sp)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001699 {
1700 // If we have the JSON threads info, we can get the thread list from that
Greg Clayton2e309072015-07-17 23:42:28 +00001701 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001702 if (thread_infos && thread_infos->GetSize() > 0)
1703 {
1704 m_thread_ids.clear();
Jason Molenda545304d2015-12-18 00:45:35 +00001705 m_thread_pcs.clear();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001706 thread_infos->ForEach([this](StructuredData::Object* object) -> bool {
1707 StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1708 if (thread_dict)
1709 {
1710 // Set the thread stop info from the JSON dictionary
1711 SetThreadStopInfo (thread_dict);
1712 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1713 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1714 m_thread_ids.push_back(tid);
1715 }
1716 return true; // Keep iterating through all thread_info objects
1717 });
1718 }
1719 if (!m_thread_ids.empty())
1720 return true;
1721 }
1722 else
1723 {
1724 // See if we can get the thread IDs from the current stop reply packets
1725 // that might contain a "threads" key/value pair
1726
1727 // Lock the thread stack while we access it
Greg Claytonfc1e77a982015-11-03 22:42:04 +00001728 //Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +00001729 std::unique_lock<std::recursive_mutex> stop_stack_lock(m_last_stop_packet_mutex, std::defer_lock);
1730 if (stop_stack_lock.try_lock())
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001731 {
Greg Claytonfc1e77a982015-11-03 22:42:04 +00001732 // Get the number of stop packets on the stack
1733 int nItems = m_stop_packet_stack.size();
1734 // Iterate over them
1735 for (int i = 0; i < nItems; i++)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001736 {
Greg Claytonfc1e77a982015-11-03 22:42:04 +00001737 // Get the thread stop info
1738 StringExtractorGDBRemote &stop_info = m_stop_packet_stack[i];
1739 const std::string &stop_info_str = stop_info.GetStringRef();
Jason Molenda545304d2015-12-18 00:45:35 +00001740
1741 m_thread_pcs.clear();
1742 const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:");
1743 if (thread_pcs_pos != std::string::npos)
1744 {
1745 const size_t start = thread_pcs_pos + strlen(";thread-pcs:");
1746 const size_t end = stop_info_str.find(';', start);
1747 if (end != std::string::npos)
1748 {
1749 std::string value = stop_info_str.substr(start, end - start);
1750 UpdateThreadPCsFromStopReplyThreadsValue(value);
1751 }
1752 }
1753
Greg Claytonfc1e77a982015-11-03 22:42:04 +00001754 const size_t threads_pos = stop_info_str.find(";threads:");
1755 if (threads_pos != std::string::npos)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001756 {
Greg Claytonfc1e77a982015-11-03 22:42:04 +00001757 const size_t start = threads_pos + strlen(";threads:");
1758 const size_t end = stop_info_str.find(';', start);
1759 if (end != std::string::npos)
1760 {
1761 std::string value = stop_info_str.substr(start, end - start);
1762 if (UpdateThreadIDsFromStopReplyThreadsValue(value))
1763 return true;
1764 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001765 }
1766 }
1767 }
1768 }
1769
Greg Clayton9e920902012-04-10 02:25:43 +00001770 bool sequence_mutex_unavailable = false;
1771 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1772 if (sequence_mutex_unavailable)
1773 {
Greg Clayton9e920902012-04-10 02:25:43 +00001774 return false; // We just didn't get the list
1775 }
1776 return true;
1777}
1778
Greg Clayton9fc13552012-04-10 00:18:59 +00001779bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001780ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001781{
1782 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +00001783 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Clayton73b472d2010-10-27 03:32:59 +00001784 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +00001785 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Ed Maste81b4c5f2016-01-04 01:43:47 +00001786
Greg Clayton9e920902012-04-10 02:25:43 +00001787 size_t num_thread_ids = m_thread_ids.size();
1788 // The "m_thread_ids" thread ID list should always be updated after each stop
1789 // reply packet, but in case it isn't, update it here.
1790 if (num_thread_ids == 0)
1791 {
1792 if (!UpdateThreadIDList ())
1793 return false;
1794 num_thread_ids = m_thread_ids.size();
1795 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001796
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001797 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001798 if (num_thread_ids > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001799 {
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001800 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001801 {
Greg Clayton9e920902012-04-10 02:25:43 +00001802 tid_t tid = m_thread_ids[i];
Greg Clayton160c9d82013-05-01 21:54:04 +00001803 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001804 if (!thread_sp)
Jim Inghamdee1bc92013-06-22 00:27:45 +00001805 {
Jim Ingham4f465cf2012-10-10 18:32:14 +00001806 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001807 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1808 log->Printf(
1809 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001810 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001811 thread_sp->GetID());
1812 }
1813 else
1814 {
1815 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1816 log->Printf(
1817 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001818 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001819 thread_sp->GetID());
1820 }
Jason Molenda545304d2015-12-18 00:45:35 +00001821 // The m_thread_pcs vector has pc values in big-endian order, not target-endian, unlike most
Ed Maste81b4c5f2016-01-04 01:43:47 +00001822 // of the register read/write packets in gdb-remote protocol.
Jason Molenda545304d2015-12-18 00:45:35 +00001823 // Early in the process startup, we may not yet have set the process ByteOrder so we ignore these;
1824 // they are a performance improvement over fetching thread register values individually, the
1825 // method we will fall back to if needed.
1826 if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() && GetByteOrder() != eByteOrderInvalid)
1827 {
1828 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1829 RegisterContextSP reg_ctx_sp (thread_sp->GetRegisterContext());
1830 if (reg_ctx_sp)
1831 {
Ed Maste81b4c5f2016-01-04 01:43:47 +00001832 uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber
Jason Molenda545304d2015-12-18 00:45:35 +00001833 (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1834 if (pc_regnum != LLDB_INVALID_REGNUM)
1835 {
1836 gdb_thread->PrivateSetRegisterValue (pc_regnum, m_thread_pcs[i]);
1837 }
1838 }
1839 }
Greg Clayton88f86b62016-06-10 23:23:34 +00001840 new_thread_list.AddThreadSortedByIndexID (thread_sp);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001841 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001842 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001843
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001844 // Whatever that is left in old_thread_list_copy are not
1845 // present in new_thread_list. Remove non-existent threads from internal id table.
1846 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1847 for (size_t i=0; i<old_num_thread_ids; i++)
1848 {
1849 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1850 if (old_thread_sp)
1851 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001852 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001853 m_thread_id_to_index_id_map.erase(old_thread_id);
1854 }
1855 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001856
Greg Clayton9fc13552012-04-10 00:18:59 +00001857 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001858}
1859
Eugene Zelenko0722f082015-10-24 01:28:05 +00001860
Greg Clayton358cf1e2015-06-25 21:46:34 +00001861bool
Greg Clayton2e309072015-07-17 23:42:28 +00001862ProcessGDBRemote::GetThreadStopInfoFromJSON (ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001863{
1864 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet
Greg Clayton2e309072015-07-17 23:42:28 +00001865 if (thread_infos_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001866 {
Greg Clayton2e309072015-07-17 23:42:28 +00001867 StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
Greg Clayton358cf1e2015-06-25 21:46:34 +00001868 if (thread_infos)
1869 {
1870 lldb::tid_t tid;
1871 const size_t n = thread_infos->GetSize();
1872 for (size_t i=0; i<n; ++i)
1873 {
1874 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1875 if (thread_dict)
1876 {
1877 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid, LLDB_INVALID_THREAD_ID))
1878 {
1879 if (tid == thread->GetID())
Greg Clayton2e309072015-07-17 23:42:28 +00001880 return (bool)SetThreadStopInfo(thread_dict);
Greg Clayton358cf1e2015-06-25 21:46:34 +00001881 }
1882 }
1883 }
1884 }
1885 }
Greg Clayton2e309072015-07-17 23:42:28 +00001886 return false;
1887}
1888
1889bool
1890ProcessGDBRemote::CalculateThreadStopInfo (ThreadGDBRemote *thread)
1891{
1892 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet
1893 if (GetThreadStopInfoFromJSON (thread, m_jthreadsinfo_sp))
1894 return true;
1895
1896 // See if we got thread stop info for any threads valid stop info reasons threads
1897 // via the "jstopinfo" packet stop reply packet key/value pair?
1898 if (m_jstopinfo_sp)
1899 {
1900 // If we have "jstopinfo" then we have stop descriptions for all threads
1901 // that have stop reasons, and if there is no entry for a thread, then
1902 // it has no stop reason.
1903 thread->GetRegisterContext()->InvalidateIfNeeded(true);
1904 if (!GetThreadStopInfoFromJSON (thread, m_jstopinfo_sp))
1905 {
1906 thread->SetStopInfo (StopInfoSP());
1907 }
1908 return true;
1909 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00001910
1911 // Fall back to using the qThreadStopInfo packet
1912 StringExtractorGDBRemote stop_packet;
1913 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1914 return SetThreadStopInfo (stop_packet) == eStateStopped;
1915 return false;
1916}
1917
Eugene Zelenko0722f082015-10-24 01:28:05 +00001918
Greg Clayton358cf1e2015-06-25 21:46:34 +00001919ThreadSP
1920ProcessGDBRemote::SetThreadStopInfo (lldb::tid_t tid,
1921 ExpeditedRegisterMap &expedited_register_map,
1922 uint8_t signo,
1923 const std::string &thread_name,
1924 const std::string &reason,
1925 const std::string &description,
1926 uint32_t exc_type,
1927 const std::vector<addr_t> &exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001928 addr_t thread_dispatch_qaddr,
1929 bool queue_vars_valid, // Set to true if queue_name, queue_kind and queue_serial are valid
Jason Molenda77f89352016-01-12 07:09:16 +00001930 LazyBool associated_with_dispatch_queue,
1931 addr_t dispatch_queue_t,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001932 std::string &queue_name,
1933 QueueKind queue_kind,
1934 uint64_t queue_serial)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001935{
1936 ThreadSP thread_sp;
1937 if (tid != LLDB_INVALID_THREAD_ID)
1938 {
1939 // Scope for "locker" below
1940 {
1941 // m_thread_list_real does have its own mutex, but we need to
1942 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1943 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00001944 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
Greg Clayton358cf1e2015-06-25 21:46:34 +00001945 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1946
1947 if (!thread_sp)
1948 {
1949 // Create the thread if we need to
1950 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1951 m_thread_list_real.AddThread(thread_sp);
1952 }
1953 }
1954
1955 if (thread_sp)
1956 {
1957 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1958 gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001959
Greg Clayton358cf1e2015-06-25 21:46:34 +00001960 for (const auto &pair : expedited_register_map)
1961 {
1962 StringExtractor reg_value_extractor;
1963 reg_value_extractor.GetStringRef() = pair.second;
1964 gdb_thread->PrivateSetRegisterValue (pair.first, reg_value_extractor);
1965 }
1966
Greg Clayton358cf1e2015-06-25 21:46:34 +00001967 thread_sp->SetName (thread_name.empty() ? NULL : thread_name.c_str());
1968
1969 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001970 // Check if the GDB server was able to provide the queue name, kind and serial number
1971 if (queue_vars_valid)
Jason Molenda77f89352016-01-12 07:09:16 +00001972 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 +00001973 else
1974 gdb_thread->ClearQueueInfo();
1975
Jason Molenda77f89352016-01-12 07:09:16 +00001976 gdb_thread->SetAssociatedWithLibdispatchQueue (associated_with_dispatch_queue);
1977
1978 if (dispatch_queue_t != LLDB_INVALID_ADDRESS)
1979 gdb_thread->SetQueueLibdispatchQueueAddress (dispatch_queue_t);
1980
Greg Clayton2e309072015-07-17 23:42:28 +00001981 // Make sure we update our thread stop reason just once
1982 if (!thread_sp->StopInfoIsUpToDate())
Greg Clayton358cf1e2015-06-25 21:46:34 +00001983 {
Greg Clayton2e309072015-07-17 23:42:28 +00001984 thread_sp->SetStopInfo (StopInfoSP());
Ryan Brown65d4d5c2015-09-16 21:20:44 +00001985 // If there's a memory thread backed by this thread, we need to use it to calcualte StopInfo.
1986 ThreadSP memory_thread_sp = m_thread_list.FindThreadByProtocolID(thread_sp->GetProtocolID());
1987 if (memory_thread_sp)
1988 thread_sp = memory_thread_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +00001989
Greg Clayton2e309072015-07-17 23:42:28 +00001990 if (exc_type != 0)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001991 {
Greg Clayton2e309072015-07-17 23:42:28 +00001992 const size_t exc_data_size = exc_data.size();
1993
1994 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1995 exc_type,
1996 exc_data_size,
1997 exc_data_size >= 1 ? exc_data[0] : 0,
1998 exc_data_size >= 2 ? exc_data[1] : 0,
1999 exc_data_size >= 3 ? exc_data[2] : 0));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002000 }
Greg Clayton2e309072015-07-17 23:42:28 +00002001 else
Greg Clayton358cf1e2015-06-25 21:46:34 +00002002 {
Greg Clayton2e309072015-07-17 23:42:28 +00002003 bool handled = false;
2004 bool did_exec = false;
2005 if (!reason.empty())
Greg Clayton358cf1e2015-06-25 21:46:34 +00002006 {
Greg Clayton2e309072015-07-17 23:42:28 +00002007 if (reason.compare("trace") == 0)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002008 {
Pavel Labathef409122016-04-07 08:16:10 +00002009 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
2010 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2011
2012 // If the current pc is a breakpoint site then the StopInfo should be set to Breakpoint
2013 // Otherwise, it will be set to Trace.
2014 if (bp_site_sp && bp_site_sp->ValidForThisThread(thread_sp.get()))
2015 {
2016 thread_sp->SetStopInfo(
2017 StopInfo::CreateStopReasonWithBreakpointSiteID(*thread_sp, bp_site_sp->GetID()));
2018 }
2019 else
2020 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Greg Clayton2e309072015-07-17 23:42:28 +00002021 handled = true;
2022 }
2023 else if (reason.compare("breakpoint") == 0)
2024 {
Pavel Labathef409122016-04-07 08:16:10 +00002025 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
2026 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2027 if (bp_site_sp)
2028 {
2029 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2030 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2031 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2032 handled = true;
2033 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2034 {
2035 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2036 }
2037 else
2038 {
2039 StopInfoSP invalid_stop_info_sp;
2040 thread_sp->SetStopInfo (invalid_stop_info_sp);
2041 }
2042 }
Greg Clayton2e309072015-07-17 23:42:28 +00002043 }
2044 else if (reason.compare("trap") == 0)
2045 {
2046 // Let the trap just use the standard signal stop reason below...
2047 }
2048 else if (reason.compare("watchpoint") == 0)
2049 {
2050 StringExtractor desc_extractor(description.c_str());
2051 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
2052 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
Jaydeep Patil83143502015-08-13 03:44:09 +00002053 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
Greg Clayton2e309072015-07-17 23:42:28 +00002054 watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
2055 if (wp_addr != LLDB_INVALID_ADDRESS)
2056 {
Mohit K. Bhakkad6846bc82015-12-02 17:45:02 +00002057 WatchpointSP wp_sp;
2058 ArchSpec::Core core = GetTarget().GetArchitecture().GetCore();
Omair Javaid43507f52016-06-16 16:41:22 +00002059 if ((core >= ArchSpec::kCore_mips_first && core <= ArchSpec::kCore_mips_last) ||
Omair Javaidc6dc90e2016-06-27 11:18:23 +00002060 (core >= ArchSpec::eCore_arm_generic && core <= ArchSpec::eCore_arm_aarch64))
Mohit K. Bhakkad6846bc82015-12-02 17:45:02 +00002061 wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_hit_addr);
2062 if (!wp_sp)
2063 wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
Greg Clayton2e309072015-07-17 23:42:28 +00002064 if (wp_sp)
2065 {
2066 wp_sp->SetHardwareIndex(wp_index);
2067 watch_id = wp_sp->GetID();
2068 }
2069 }
2070 if (watch_id == LLDB_INVALID_WATCH_ID)
2071 {
2072 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_WATCHPOINTS));
2073 if (log) log->Printf ("failed to find watchpoint");
2074 }
Jaydeep Patil83143502015-08-13 03:44:09 +00002075 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id, wp_hit_addr));
Greg Clayton2e309072015-07-17 23:42:28 +00002076 handled = true;
2077 }
2078 else if (reason.compare("exception") == 0)
2079 {
2080 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
2081 handled = true;
2082 }
2083 else if (reason.compare("exec") == 0)
2084 {
2085 did_exec = true;
2086 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
2087 handled = true;
2088 }
2089 }
Pavel Labath3ce324a2016-04-06 09:10:29 +00002090 else if (!signo)
2091 {
Pavel Labathef409122016-04-07 08:16:10 +00002092 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
2093 lldb::BreakpointSiteSP bp_site_sp =
2094 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2095
Pavel Labath3ce324a2016-04-06 09:10:29 +00002096 // If the current pc is a breakpoint site then the StopInfo should be set to Breakpoint
2097 // even though the remote stub did not set it as such. This can happen when
2098 // the thread is involuntarily interrupted (e.g. due to stops on other
2099 // threads) just as it is about to execute the breakpoint instruction.
Pavel Labathef409122016-04-07 08:16:10 +00002100 if (bp_site_sp && bp_site_sp->ValidForThisThread(thread_sp.get()))
2101 {
2102 thread_sp->SetStopInfo(
2103 StopInfo::CreateStopReasonWithBreakpointSiteID(*thread_sp, bp_site_sp->GetID()));
Pavel Labath3ce324a2016-04-06 09:10:29 +00002104 handled = true;
Pavel Labathef409122016-04-07 08:16:10 +00002105 }
Pavel Labath3ce324a2016-04-06 09:10:29 +00002106 }
Greg Clayton2e309072015-07-17 23:42:28 +00002107
2108 if (!handled && signo && did_exec == false)
2109 {
2110 if (signo == SIGTRAP)
2111 {
2112 // Currently we are going to assume SIGTRAP means we are either
2113 // hitting a breakpoint or hardware single stepping.
2114 handled = true;
2115 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
2116 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2117
2118 if (bp_site_sp)
2119 {
2120 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2121 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2122 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2123 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2124 {
2125 if(m_breakpoint_pc_offset != 0)
2126 thread_sp->GetRegisterContext()->SetPC(pc);
2127 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2128 }
2129 else
2130 {
2131 StopInfoSP invalid_stop_info_sp;
2132 thread_sp->SetStopInfo (invalid_stop_info_sp);
2133 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002134 }
2135 else
2136 {
Greg Clayton2e309072015-07-17 23:42:28 +00002137 // If we were stepping then assume the stop was the result of the trace. If we were
2138 // not stepping then report the SIGTRAP.
2139 // FIXME: We are still missing the case where we single step over a trap instruction.
2140 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
2141 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
2142 else
2143 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo, description.c_str()));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002144 }
2145 }
Greg Clayton2e309072015-07-17 23:42:28 +00002146 if (!handled)
2147 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo, description.c_str()));
2148 }
2149
2150 if (!description.empty())
2151 {
2152 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
2153 if (stop_info_sp)
2154 {
2155 const char *stop_info_desc = stop_info_sp->GetDescription();
2156 if (!stop_info_desc || !stop_info_desc[0])
2157 stop_info_sp->SetDescription (description.c_str());
2158 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002159 else
2160 {
Greg Clayton2e309072015-07-17 23:42:28 +00002161 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002162 }
2163 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002164 }
2165 }
2166 }
2167 }
2168 return thread_sp;
2169}
2170
Greg Clayton2e309072015-07-17 23:42:28 +00002171lldb::ThreadSP
Greg Clayton358cf1e2015-06-25 21:46:34 +00002172ProcessGDBRemote::SetThreadStopInfo (StructuredData::Dictionary *thread_dict)
2173{
2174 static ConstString g_key_tid("tid");
2175 static ConstString g_key_name("name");
2176 static ConstString g_key_reason("reason");
2177 static ConstString g_key_metype("metype");
2178 static ConstString g_key_medata("medata");
2179 static ConstString g_key_qaddr("qaddr");
Jason Molenda77f89352016-01-12 07:09:16 +00002180 static ConstString g_key_dispatch_queue_t("dispatch_queue_t");
2181 static ConstString g_key_associated_with_dispatch_queue("associated_with_dispatch_queue");
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002182 static ConstString g_key_queue_name("qname");
2183 static ConstString g_key_queue_kind("qkind");
Jason Molenda26d84e82016-01-08 00:20:48 +00002184 static ConstString g_key_queue_serial_number("qserialnum");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002185 static ConstString g_key_registers("registers");
2186 static ConstString g_key_memory("memory");
2187 static ConstString g_key_address("address");
2188 static ConstString g_key_bytes("bytes");
2189 static ConstString g_key_description("description");
Pavel Labath4a4bb122015-07-16 14:14:35 +00002190 static ConstString g_key_signal("signal");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002191
2192 // Stop with signal and thread info
2193 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2194 uint8_t signo = 0;
2195 std::string value;
2196 std::string thread_name;
2197 std::string reason;
2198 std::string description;
2199 uint32_t exc_type = 0;
2200 std::vector<addr_t> exc_data;
2201 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2202 ExpeditedRegisterMap expedited_register_map;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002203 bool queue_vars_valid = false;
Jason Molenda77f89352016-01-12 07:09:16 +00002204 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2205 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002206 std::string queue_name;
2207 QueueKind queue_kind = eQueueKindUnknown;
Jason Molenda26d84e82016-01-08 00:20:48 +00002208 uint64_t queue_serial_number = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002209 // Iterate through all of the thread dictionary key/value pairs from the structured data dictionary
2210
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002211 thread_dict->ForEach([this,
2212 &tid,
2213 &expedited_register_map,
2214 &thread_name,
2215 &signo,
2216 &reason,
2217 &description,
2218 &exc_type,
2219 &exc_data,
2220 &thread_dispatch_qaddr,
2221 &queue_vars_valid,
Jason Molenda77f89352016-01-12 07:09:16 +00002222 &associated_with_dispatch_queue,
2223 &dispatch_queue_t,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002224 &queue_name,
2225 &queue_kind,
Jason Molenda26d84e82016-01-08 00:20:48 +00002226 &queue_serial_number]
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002227 (ConstString key, StructuredData::Object* object) -> bool
Greg Clayton358cf1e2015-06-25 21:46:34 +00002228 {
2229 if (key == g_key_tid)
2230 {
2231 // thread in big endian hex
2232 tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
2233 }
2234 else if (key == g_key_metype)
2235 {
2236 // exception type in big endian hex
2237 exc_type = object->GetIntegerValue(0);
2238 }
2239 else if (key == g_key_medata)
2240 {
2241 // exception data in big endian hex
2242 StructuredData::Array *array = object->GetAsArray();
2243 if (array)
2244 {
2245 array->ForEach([&exc_data](StructuredData::Object* object) -> bool {
2246 exc_data.push_back(object->GetIntegerValue());
2247 return true; // Keep iterating through all array items
2248 });
2249 }
2250 }
2251 else if (key == g_key_name)
2252 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002253 thread_name = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002254 }
2255 else if (key == g_key_qaddr)
2256 {
2257 thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
2258 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002259 else if (key == g_key_queue_name)
2260 {
2261 queue_vars_valid = true;
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002262 queue_name = object->GetStringValue();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002263 }
2264 else if (key == g_key_queue_kind)
2265 {
2266 std::string queue_kind_str = object->GetStringValue();
2267 if (queue_kind_str == "serial")
2268 {
2269 queue_vars_valid = true;
2270 queue_kind = eQueueKindSerial;
2271 }
2272 else if (queue_kind_str == "concurrent")
2273 {
2274 queue_vars_valid = true;
2275 queue_kind = eQueueKindConcurrent;
2276 }
2277 }
Jason Molenda26d84e82016-01-08 00:20:48 +00002278 else if (key == g_key_queue_serial_number)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002279 {
Jason Molenda26d84e82016-01-08 00:20:48 +00002280 queue_serial_number = object->GetIntegerValue(0);
2281 if (queue_serial_number != 0)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002282 queue_vars_valid = true;
2283 }
Jason Molenda77f89352016-01-12 07:09:16 +00002284 else if (key == g_key_dispatch_queue_t)
2285 {
2286 dispatch_queue_t = object->GetIntegerValue(0);
2287 if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS)
2288 queue_vars_valid = true;
2289 }
2290 else if (key == g_key_associated_with_dispatch_queue)
2291 {
2292 queue_vars_valid = true;
2293 bool associated = object->GetBooleanValue ();
2294 if (associated)
2295 associated_with_dispatch_queue = eLazyBoolYes;
2296 else
2297 associated_with_dispatch_queue = eLazyBoolNo;
2298 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002299 else if (key == g_key_reason)
2300 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002301 reason = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002302 }
2303 else if (key == g_key_description)
2304 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002305 description = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002306 }
2307 else if (key == g_key_registers)
2308 {
2309 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2310
2311 if (registers_dict)
2312 {
2313 registers_dict->ForEach([&expedited_register_map](ConstString key, StructuredData::Object* object) -> bool {
2314 const uint32_t reg = StringConvert::ToUInt32 (key.GetCString(), UINT32_MAX, 10);
2315 if (reg != UINT32_MAX)
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002316 expedited_register_map[reg] = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002317 return true; // Keep iterating through all array items
2318 });
2319 }
2320 }
2321 else if (key == g_key_memory)
2322 {
2323 StructuredData::Array *array = object->GetAsArray();
2324 if (array)
2325 {
2326 array->ForEach([this](StructuredData::Object* object) -> bool {
2327 StructuredData::Dictionary *mem_cache_dict = object->GetAsDictionary();
2328 if (mem_cache_dict)
2329 {
2330 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2331 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>("address", mem_cache_addr))
2332 {
2333 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
2334 {
2335 StringExtractor bytes;
2336 if (mem_cache_dict->GetValueForKeyAsString("bytes", bytes.GetStringRef()))
2337 {
2338 bytes.SetFilePos(0);
2339
2340 const size_t byte_size = bytes.GetStringRef().size()/2;
2341 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2342 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2343 if (bytes_copied == byte_size)
2344 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2345 }
2346 }
2347 }
2348 }
2349 return true; // Keep iterating through all array items
2350 });
2351 }
Eugene Zelenko0722f082015-10-24 01:28:05 +00002352
Greg Clayton358cf1e2015-06-25 21:46:34 +00002353 }
Pavel Labath4a4bb122015-07-16 14:14:35 +00002354 else if (key == g_key_signal)
2355 signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002356 return true; // Keep iterating through all dictionary key/value pairs
2357 });
2358
Greg Clayton2e309072015-07-17 23:42:28 +00002359 return SetThreadStopInfo (tid,
2360 expedited_register_map,
2361 signo,
2362 thread_name,
2363 reason,
2364 description,
2365 exc_type,
2366 exc_data,
2367 thread_dispatch_qaddr,
2368 queue_vars_valid,
Jason Molenda77f89352016-01-12 07:09:16 +00002369 associated_with_dispatch_queue,
2370 dispatch_queue_t,
Greg Clayton2e309072015-07-17 23:42:28 +00002371 queue_name,
2372 queue_kind,
Jason Molenda26d84e82016-01-08 00:20:48 +00002373 queue_serial_number);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002374}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002375
2376StateType
2377ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
2378{
Greg Claytondd0e5a52011-06-02 22:22:38 +00002379 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002380 const char stop_type = stop_packet.GetChar();
2381 switch (stop_type)
2382 {
2383 case 'T':
2384 case 'S':
2385 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00002386 // This is a bit of a hack, but is is required. If we did exec, we
2387 // need to clear our thread lists and also know to rebuild our dynamic
2388 // register info before we lookup and threads and populate the expedited
2389 // register values so we need to know this right away so we can cleanup
2390 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00002391 const uint32_t stop_id = GetStopID();
2392 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00002393 {
2394 // Our first stop, make sure we have a process ID, and also make
2395 // sure we know about our registers
2396 if (GetID() == LLDB_INVALID_PROCESS_ID)
2397 {
Greg Claytonc574ede2011-03-10 02:26:48 +00002398 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00002399 if (pid != LLDB_INVALID_PROCESS_ID)
2400 SetID (pid);
2401 }
2402 BuildDynamicRegisterInfo (true);
2403 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002404 // Stop with signal and thread info
Greg Clayton358cf1e2015-06-25 21:46:34 +00002405 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002406 const uint8_t signo = stop_packet.GetHexU8();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002407 std::string key;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002408 std::string value;
2409 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00002410 std::string reason;
2411 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002412 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00002413 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002414 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton0b90be12015-06-23 21:27:50 +00002415 bool queue_vars_valid = false; // says if locals below that start with "queue_" are valid
Jason Molenda77f89352016-01-12 07:09:16 +00002416 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2417 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
Greg Clayton0b90be12015-06-23 21:27:50 +00002418 std::string queue_name;
2419 QueueKind queue_kind = eQueueKindUnknown;
Jason Molenda26d84e82016-01-08 00:20:48 +00002420 uint64_t queue_serial_number = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002421 ExpeditedRegisterMap expedited_register_map;
2422 while (stop_packet.GetNameColonValue(key, value))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002423 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002424 if (key.compare("metype") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002425 {
2426 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002427 exc_type = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002428 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002429 else if (key.compare("medata") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002430 {
2431 // exception data in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002432 exc_data.push_back(StringConvert::ToUInt64 (value.c_str(), 0, 16));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002433 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002434 else if (key.compare("thread") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002435 {
2436 // thread in big endian hex
Greg Clayton358cf1e2015-06-25 21:46:34 +00002437 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002438 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002439 else if (key.compare("threads") == 0)
Greg Clayton9e920902012-04-10 02:25:43 +00002440 {
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00002441 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
2442
Greg Clayton9e920902012-04-10 02:25:43 +00002443 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00002444 // A comma separated list of all threads in the current
2445 // process that includes the thread for this stop reply
2446 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00002447 size_t comma_pos;
2448 lldb::tid_t tid;
2449 while ((comma_pos = value.find(',')) != std::string::npos)
2450 {
2451 value[comma_pos] = '\0';
2452 // thread in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002453 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00002454 if (tid != LLDB_INVALID_THREAD_ID)
2455 m_thread_ids.push_back (tid);
2456 value.erase(0, comma_pos + 1);
Greg Clayton9e920902012-04-10 02:25:43 +00002457 }
Vince Harron5275aaa2015-01-15 20:08:35 +00002458 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00002459 if (tid != LLDB_INVALID_THREAD_ID)
2460 m_thread_ids.push_back (tid);
2461 }
Jason Molenda545304d2015-12-18 00:45:35 +00002462 else if (key.compare("thread-pcs") == 0)
2463 {
2464 m_thread_pcs.clear();
2465 // A comma separated list of all threads in the current
2466 // process that includes the thread for this stop reply
2467 // packet
2468 size_t comma_pos;
2469 lldb::addr_t pc;
2470 while ((comma_pos = value.find(',')) != std::string::npos)
2471 {
2472 value[comma_pos] = '\0';
2473 // thread in big endian hex
2474 pc = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
2475 if (pc != LLDB_INVALID_ADDRESS)
2476 m_thread_pcs.push_back (pc);
2477 value.erase(0, comma_pos + 1);
2478 }
2479 pc = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
2480 if (pc != LLDB_INVALID_ADDRESS)
2481 m_thread_pcs.push_back (pc);
2482 }
Greg Clayton2e309072015-07-17 23:42:28 +00002483 else if (key.compare("jstopinfo") == 0)
Greg Claytona5801ad2015-07-15 22:59:03 +00002484 {
2485 StringExtractor json_extractor;
2486 // Swap "value" over into "name_extractor"
2487 json_extractor.GetStringRef().swap(value);
2488 // Now convert the HEX bytes into a string value
2489 json_extractor.GetHexByteString (value);
2490
2491 // This JSON contains thread IDs and thread stop info for all threads.
2492 // It doesn't contain expedited registers, memory or queue info.
Greg Clayton2e309072015-07-17 23:42:28 +00002493 m_jstopinfo_sp = StructuredData::ParseJSON (value);
Greg Claytona5801ad2015-07-15 22:59:03 +00002494 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002495 else if (key.compare("hexname") == 0)
Greg Claytonde9d0492011-01-08 03:17:57 +00002496 {
2497 StringExtractor name_extractor;
2498 // Swap "value" over into "name_extractor"
2499 name_extractor.GetStringRef().swap(value);
2500 // Now convert the HEX bytes into a string value
2501 name_extractor.GetHexByteString (value);
2502 thread_name.swap (value);
2503 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002504 else if (key.compare("name") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002505 {
2506 thread_name.swap (value);
2507 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002508 else if (key.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002509 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002510 thread_dispatch_qaddr = StringConvert::ToUInt64 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002511 }
Jason Molenda77f89352016-01-12 07:09:16 +00002512 else if (key.compare("dispatch_queue_t") == 0)
2513 {
2514 queue_vars_valid = true;
2515 dispatch_queue_t = StringConvert::ToUInt64 (value.c_str(), 0, 16);
2516 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002517 else if (key.compare("qname") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002518 {
2519 queue_vars_valid = true;
2520 StringExtractor name_extractor;
2521 // Swap "value" over into "name_extractor"
2522 name_extractor.GetStringRef().swap(value);
2523 // Now convert the HEX bytes into a string value
2524 name_extractor.GetHexByteString (value);
2525 queue_name.swap (value);
2526 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002527 else if (key.compare("qkind") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002528 {
Greg Clayton0b90be12015-06-23 21:27:50 +00002529 if (value == "serial")
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002530 {
2531 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002532 queue_kind = eQueueKindSerial;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002533 }
Greg Clayton0b90be12015-06-23 21:27:50 +00002534 else if (value == "concurrent")
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002535 {
2536 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002537 queue_kind = eQueueKindConcurrent;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002538 }
Greg Clayton0b90be12015-06-23 21:27:50 +00002539 }
Jason Molenda26d84e82016-01-08 00:20:48 +00002540 else if (key.compare("qserialnum") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002541 {
Jason Molenda26d84e82016-01-08 00:20:48 +00002542 queue_serial_number = StringConvert::ToUInt64 (value.c_str(), 0, 0);
2543 if (queue_serial_number != 0)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002544 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002545 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002546 else if (key.compare("reason") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002547 {
2548 reason.swap(value);
2549 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002550 else if (key.compare("description") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002551 {
2552 StringExtractor desc_extractor;
2553 // Swap "value" over into "name_extractor"
2554 desc_extractor.GetStringRef().swap(value);
2555 // Now convert the HEX bytes into a string value
Chaoren Lin28e57422015-02-03 01:51:25 +00002556 desc_extractor.GetHexByteString (value);
2557 description.swap(value);
Greg Claytona658fd22011-06-04 01:26:29 +00002558 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002559 else if (key.compare("memory") == 0)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002560 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002561 // Expedited memory. GDB servers can choose to send back expedited memory
2562 // that can populate the L1 memory cache in the process so that things like
2563 // the frame pointer backchain can be expedited. This will help stack
2564 // backtracing be more efficient by not having to send as many memory read
2565 // requests down the remote GDB server.
Chaoren Lin7a306082015-06-23 03:17:01 +00002566
Greg Clayton358cf1e2015-06-25 21:46:34 +00002567 // Key/value pair format: memory:<addr>=<bytes>;
2568 // <addr> is a number whose base will be interpreted by the prefix:
2569 // "0x[0-9a-fA-F]+" for hex
2570 // "0[0-7]+" for octal
2571 // "[1-9]+" for decimal
2572 // <bytes> is native endian ASCII hex bytes just like the register values
2573 llvm::StringRef value_ref(value);
2574 std::pair<llvm::StringRef, llvm::StringRef> pair;
2575 pair = value_ref.split('=');
2576 if (!pair.first.empty() && !pair.second.empty())
2577 {
2578 std::string addr_str(pair.first.str());
2579 const lldb::addr_t mem_cache_addr = StringConvert::ToUInt64(addr_str.c_str(), LLDB_INVALID_ADDRESS, 0);
2580 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002581 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002582 StringExtractor bytes;
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002583 bytes.GetStringRef() = pair.second.str();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002584 const size_t byte_size = bytes.GetStringRef().size()/2;
2585 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2586 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2587 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'
2595 lldb::addr_t wp_addr = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
2596 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2597 uint32_t wp_index = LLDB_INVALID_INDEX32;
2598
2599 if (wp_sp)
2600 wp_index = wp_sp->GetHardwareIndex();
2601
2602 reason = "watchpoint";
2603 StreamString ostr;
2604 ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
2605 description = ostr.GetString().c_str();
2606 }
Stephane Sezer2618e912015-08-21 16:51:56 +00002607 else if (key.compare("library") == 0)
2608 {
2609 LoadModules();
2610 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002611 else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1]))
2612 {
2613 uint32_t reg = StringConvert::ToUInt32 (key.c_str(), UINT32_MAX, 16);
2614 if (reg != UINT32_MAX)
2615 expedited_register_map[reg] = std::move(value);
2616 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002617 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002618
Bhushan D. Attarde1e271df2015-07-24 04:06:20 +00002619 if (tid == LLDB_INVALID_THREAD_ID)
2620 {
Ed Maste81b4c5f2016-01-04 01:43:47 +00002621 // 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 +00002622 // thread information. So update the thread list and choose the first one.
2623 UpdateThreadIDList ();
Ed Maste81b4c5f2016-01-04 01:43:47 +00002624
Bhushan D. Attarde1e271df2015-07-24 04:06:20 +00002625 if (!m_thread_ids.empty ())
2626 {
2627 tid = m_thread_ids.front ();
2628 }
2629 }
2630
Greg Clayton358cf1e2015-06-25 21:46:34 +00002631 ThreadSP thread_sp = SetThreadStopInfo (tid,
2632 expedited_register_map,
2633 signo,
2634 thread_name,
2635 reason,
2636 description,
2637 exc_type,
2638 exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002639 thread_dispatch_qaddr,
2640 queue_vars_valid,
Jason Molenda77f89352016-01-12 07:09:16 +00002641 associated_with_dispatch_queue,
2642 dispatch_queue_t,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002643 queue_name,
2644 queue_kind,
Jason Molenda26d84e82016-01-08 00:20:48 +00002645 queue_serial_number);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002646
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002647 return eStateStopped;
2648 }
2649 break;
2650
2651 case 'W':
Todd Fialaff6131a2014-05-19 04:57:23 +00002652 case 'X':
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002653 // process exited
2654 return eStateExited;
2655
2656 default:
2657 break;
2658 }
2659 return eStateInvalid;
2660}
2661
2662void
2663ProcessGDBRemote::RefreshStateAfterStop ()
2664{
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00002665 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
2666
Greg Clayton9e920902012-04-10 02:25:43 +00002667 m_thread_ids.clear();
Jason Molenda545304d2015-12-18 00:45:35 +00002668 m_thread_pcs.clear();
Greg Clayton9e920902012-04-10 02:25:43 +00002669 // Set the thread stop info. It might have a "threads" key whose value is
2670 // a list of all thread IDs in the current process, so m_thread_ids might
2671 // get set.
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002672
2673 // Scope for the lock
2674 {
2675 // Lock the thread stack while we access it
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +00002676 std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002677 // Get the number of stop packets on the stack
2678 int nItems = m_stop_packet_stack.size();
2679 // Iterate over them
2680 for (int i = 0; i < nItems; i++)
2681 {
2682 // Get the thread stop info
2683 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2684 // Process thread stop info
2685 SetThreadStopInfo(stop_info);
2686 }
2687 // Clear the thread stop stack
2688 m_stop_packet_stack.clear();
2689 }
2690
Greg Clayton9e920902012-04-10 02:25:43 +00002691 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2692 if (m_thread_ids.empty())
2693 {
2694 // No, we need to fetch the thread list manually
2695 UpdateThreadIDList();
2696 }
2697
Ewan Crawford78baa192015-05-13 09:18:18 +00002698 // If we have queried for a default thread id
2699 if (m_initial_tid != LLDB_INVALID_THREAD_ID)
2700 {
2701 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2702 m_initial_tid = LLDB_INVALID_THREAD_ID;
2703 }
2704
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002705 // Let all threads recover from stopping and do any clean up based
2706 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002707 m_thread_list_real.RefreshStateAfterStop();
Ed Maste81b4c5f2016-01-04 01:43:47 +00002708
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002709}
2710
2711Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002712ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002713{
2714 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002715
Pavel Labath4cb69922016-07-29 15:41:52 +00002716 bool timed_out = false;
2717 std::unique_lock<std::recursive_mutex> lock;
2718
Greg Clayton513c26c2011-01-29 07:10:55 +00002719 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002720 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002721 // We are being asked to halt during an attach. We need to just close
2722 // our file handle and debugserver will go away, and we can be done...
2723 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00002724 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002725 else
Pavel Labath4cb69922016-07-29 15:41:52 +00002726 {
2727 if (!m_gdb_comm.SendInterrupt(lock, 2, timed_out))
2728 {
2729 if (timed_out)
2730 error.SetErrorString("timed out sending interrupt packet");
2731 else
2732 error.SetErrorString("unknown error sending interrupt packet");
2733 }
2734
2735 caused_stop = m_gdb_comm.GetInterruptWasSent ();
2736 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002737 return error;
2738}
2739
2740Error
Jim Inghamacff8952013-05-02 00:27:30 +00002741ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002742{
2743 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002744 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00002745 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00002746 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
Ed Maste81b4c5f2016-01-04 01:43:47 +00002747
Jim Inghamacff8952013-05-02 00:27:30 +00002748 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002749 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002750 {
Jim Inghamacff8952013-05-02 00:27:30 +00002751 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002752 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
2753 else
Jim Inghamacff8952013-05-02 00:27:30 +00002754 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00002755 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00002756
Jim Inghamacff8952013-05-02 00:27:30 +00002757 if (!error.Success())
2758 return error;
2759
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002760 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00002761 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002762
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002763 SetPrivateState (eStateDetached);
2764 ResumePrivateStateThread();
2765
2766 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00002767 return error;
2768}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002769
Eugene Zelenko0722f082015-10-24 01:28:05 +00002770
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002771Error
2772ProcessGDBRemote::DoDestroy ()
2773{
2774 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002775 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002776 if (log)
2777 log->Printf ("ProcessGDBRemote::DoDestroy()");
2778
Jim Ingham43c555d2012-07-04 00:35:43 +00002779 // There is a bug in older iOS debugservers where they don't shut down the process
2780 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
2781 // this can cause problems with restarting. So we check to see if any of our threads are stopped
2782 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
2783 // destroy it again.
2784 //
2785 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
2786 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
2787 // the debugservers with this bug are equal. There really should be a better way to test this!
2788 //
2789 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
2790 // get called here to destroy again and we're still at a breakpoint or exception, then we should
2791 // just do the straight-forward kill.
2792 //
2793 // And of course, if we weren't able to stop the process by the time we get here, it isn't
2794 // necessary (or helpful) to do any of this.
2795
2796 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
2797 {
2798 PlatformSP platform_sp = GetTarget().GetPlatform();
Ed Maste81b4c5f2016-01-04 01:43:47 +00002799
Jim Ingham43c555d2012-07-04 00:35:43 +00002800 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2801 if (platform_sp
2802 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00002803 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00002804 {
2805 if (m_destroy_tried_resuming)
2806 {
2807 if (log)
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002808 log->PutCString ("ProcessGDBRemote::DoDestroy() - Tried resuming to destroy once already, not doing it again.");
Jim Ingham43c555d2012-07-04 00:35:43 +00002809 }
2810 else
Ed Maste81b4c5f2016-01-04 01:43:47 +00002811 {
Jim Ingham43c555d2012-07-04 00:35:43 +00002812 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
2813 // but we really need it to happen here and it doesn't matter if we do it twice.
2814 m_thread_list.DiscardThreadPlans();
2815 DisableAllBreakpointSites();
Ed Maste81b4c5f2016-01-04 01:43:47 +00002816
Jim Ingham43c555d2012-07-04 00:35:43 +00002817 bool stop_looks_like_crash = false;
2818 ThreadList &threads = GetThreadList();
Ed Maste81b4c5f2016-01-04 01:43:47 +00002819
Jim Ingham43c555d2012-07-04 00:35:43 +00002820 {
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00002821 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
Ed Maste81b4c5f2016-01-04 01:43:47 +00002822
Jim Ingham43c555d2012-07-04 00:35:43 +00002823 size_t num_threads = threads.GetSize();
2824 for (size_t i = 0; i < num_threads; i++)
2825 {
2826 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002827 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002828 StopReason reason = eStopReasonInvalid;
2829 if (stop_info_sp)
2830 reason = stop_info_sp->GetStopReason();
2831 if (reason == eStopReasonBreakpoint
2832 || reason == eStopReasonException)
2833 {
2834 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002835 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
2836 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00002837 stop_info_sp->GetDescription());
2838 stop_looks_like_crash = true;
2839 break;
2840 }
2841 }
2842 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00002843
Jim Ingham43c555d2012-07-04 00:35:43 +00002844 if (stop_looks_like_crash)
2845 {
2846 if (log)
2847 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
2848 m_destroy_tried_resuming = true;
Ed Maste81b4c5f2016-01-04 01:43:47 +00002849
2850 // 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 +00002851 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
2852 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
2853 // have to run the risk of letting those threads proceed a bit.
Ed Maste81b4c5f2016-01-04 01:43:47 +00002854
Jim Ingham43c555d2012-07-04 00:35:43 +00002855 {
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00002856 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
Ed Maste81b4c5f2016-01-04 01:43:47 +00002857
Jim Ingham43c555d2012-07-04 00:35:43 +00002858 size_t num_threads = threads.GetSize();
2859 for (size_t i = 0; i < num_threads; i++)
2860 {
2861 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002862 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002863 StopReason reason = eStopReasonInvalid;
2864 if (stop_info_sp)
2865 reason = stop_info_sp->GetStopReason();
2866 if (reason != eStopReasonBreakpoint
2867 && reason != eStopReasonException)
2868 {
2869 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002870 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
2871 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00002872 thread_sp->SetResumeState(eStateSuspended);
2873 }
2874 }
2875 }
2876 Resume ();
Jason Molendaede31932015-04-17 05:01:58 +00002877 return Destroy(false);
Jim Ingham43c555d2012-07-04 00:35:43 +00002878 }
2879 }
2880 }
2881 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00002882
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002883 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00002884 int exit_status = SIGABRT;
2885 std::string exit_string;
2886
Greg Clayton6ed95942011-01-22 07:12:45 +00002887 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002888 {
Jim Inghamaab78372011-10-28 01:11:35 +00002889 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00002890 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002891 StringExtractorGDBRemote response;
2892 bool send_async = true;
Tamas Berghammer912800c2015-02-24 10:23:39 +00002893 GDBRemoteCommunication::ScopedTimeout (m_gdb_comm, 3);
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002894
Greg Clayton3dedae12013-12-06 21:45:27 +00002895 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton513c26c2011-01-29 07:10:55 +00002896 {
2897 char packet_cmd = response.GetChar(0);
2898
2899 if (packet_cmd == 'W' || packet_cmd == 'X')
2900 {
Jim Inghameac0aa42014-02-21 22:36:11 +00002901#if defined(__APPLE__)
Jason Molenda17b45392016-06-23 04:24:16 +00002902 // 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 +00002903 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill
Jason Molenda17b45392016-06-23 04:24:16 +00002904 // 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 +00002905 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap
2906 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of
2907 // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2908 // Anyway, so call waitpid here to finally reap it.
2909 PlatformSP platform_sp(GetTarget().GetPlatform());
2910 if (platform_sp && platform_sp->IsHost())
2911 {
2912 int status;
2913 ::pid_t reap_pid;
2914 reap_pid = waitpid (GetID(), &status, WNOHANG);
2915 if (log)
2916 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2917 }
2918#endif
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002919 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002920 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00002921 exit_status = response.GetHexU8();
2922 }
2923 else
2924 {
2925 if (log)
2926 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2927 exit_string.assign("got unexpected response to k packet: ");
2928 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00002929 }
2930 }
2931 else
2932 {
Jim Inghambabfc382012-06-06 00:32:39 +00002933 if (log)
2934 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2935 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00002936 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002937 }
Jim Inghambabfc382012-06-06 00:32:39 +00002938 else
2939 {
2940 if (log)
Ed Masteb3a53332014-03-17 17:05:22 +00002941 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching");
Jim Inghamcfc09352012-07-27 23:57:19 +00002942 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00002943 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002944 }
Jim Inghambabfc382012-06-06 00:32:39 +00002945 else
2946 {
2947 // If we missed setting the exit status on the way out, do it here.
2948 // NB set exit status can be called multiple times, the first one sets the status.
2949 exit_string.assign("destroying when not connected to debugserver");
2950 }
2951
2952 SetExitStatus(exit_status, exit_string.c_str());
2953
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002954 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002955 KillDebugserverProcess ();
2956 return error;
2957}
2958
Greg Clayton8cda7f02013-05-21 21:55:59 +00002959void
2960ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2961{
Greg Clayton8cda7f02013-05-21 21:55:59 +00002962 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2963 if (did_exec)
2964 {
2965 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2966 if (log)
2967 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2968
2969 m_thread_list_real.Clear();
2970 m_thread_list.Clear();
2971 BuildDynamicRegisterInfo (true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002972 m_gdb_comm.ResetDiscoverableSettings (did_exec);
Greg Clayton8cda7f02013-05-21 21:55:59 +00002973 }
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002974
2975 // Scope the lock
2976 {
2977 // Lock the thread stack while we access it
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +00002978 std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
Greg Clayton2e309072015-07-17 23:42:28 +00002979
2980 // We are are not using non-stop mode, there can only be one last stop
2981 // reply packet, so clear the list.
2982 if (GetTarget().GetNonStopModeEnabled() == false)
2983 m_stop_packet_stack.clear();
2984
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002985 // Add this stop packet to the stop packet stack
2986 // This stack will get popped and examined when we switch to the
2987 // Stopped state
2988 m_stop_packet_stack.push_back(response);
2989 }
Greg Clayton8cda7f02013-05-21 21:55:59 +00002990}
2991
Chaoren Linc963a222015-09-01 16:58:45 +00002992void
2993ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp)
2994{
2995 Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
2996}
2997
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002998//------------------------------------------------------------------
2999// Process Queries
3000//------------------------------------------------------------------
3001
3002bool
3003ProcessGDBRemote::IsAlive ()
3004{
Jason Molenda1d3b3562015-11-05 23:54:29 +00003005 return m_gdb_comm.IsConnected() && Process::IsAlive();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003006}
3007
3008addr_t
3009ProcessGDBRemote::GetImageInfoAddress()
3010{
Aidan Doddsc0c83852015-05-08 09:36:31 +00003011 // request the link map address via the $qShlibInfoAddr packet
3012 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
3013
3014 // the loaded module list can also provides a link map address
3015 if (addr == LLDB_INVALID_ADDRESS)
3016 {
Stephane Sezer87b0fe02016-01-12 19:02:41 +00003017 LoadedModuleInfoList list;
Aidan Doddsc0c83852015-05-08 09:36:31 +00003018 if (GetLoadedModuleList (list).Success())
3019 addr = list.m_link_map;
3020 }
3021
3022 return addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003023}
3024
Greg Clayton2e309072015-07-17 23:42:28 +00003025void
3026ProcessGDBRemote::WillPublicStop ()
3027{
3028 // See if the GDB remote client supports the JSON threads info.
3029 // If so, we gather stop info for all threads, expedited registers,
3030 // expedited memory, runtime queue information (iOS and MacOSX only),
3031 // and more. Expediting memory will help stack backtracing be much
3032 // faster. Expediting registers will make sure we don't have to read
3033 // the thread registers for GPRs.
3034 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
3035
3036 if (m_jthreadsinfo_sp)
3037 {
3038 // Now set the stop info for each thread and also expedite any registers
3039 // and memory that was in the jThreadsInfo response.
3040 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
3041 if (thread_infos)
3042 {
3043 const size_t n = thread_infos->GetSize();
3044 for (size_t i=0; i<n; ++i)
3045 {
3046 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
3047 if (thread_dict)
3048 SetThreadStopInfo(thread_dict);
3049 }
3050 }
3051 }
3052}
3053
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003054//------------------------------------------------------------------
3055// Process Memory
3056//------------------------------------------------------------------
3057size_t
3058ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
3059{
Jason Molenda6076bf42014-05-06 04:34:52 +00003060 GetMaxMemorySize ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003061 if (size > m_max_memory_size)
3062 {
3063 // Keep memory read sizes down to a sane limit. This function will be
Ed Maste81b4c5f2016-01-04 01:43:47 +00003064 // called multiple times in order to complete the task by
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003065 // lldb_private::Process so it is ok to do this.
3066 size = m_max_memory_size;
3067 }
3068
3069 char packet[64];
Jason Molenda6076bf42014-05-06 04:34:52 +00003070 int packet_len;
3071 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
Pavel Labath3bf11252015-10-14 12:59:37 +00003072 packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64,
3073 binary_memory_read ? 'x' : 'm', (uint64_t)addr, (uint64_t)size);
Andy Gibbsa297a972013-06-19 19:04:53 +00003074 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003075 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003076 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003077 {
Greg Clayton576d8832011-03-22 04:00:09 +00003078 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003079 {
3080 error.Clear();
Jason Molenda6076bf42014-05-06 04:34:52 +00003081 if (binary_memory_read)
3082 {
3083 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any
3084 // 0x7d character escaping that was present in the packet
3085
3086 size_t data_received_size = response.GetBytesLeft();
3087 if (data_received_size > size)
3088 {
3089 // Don't write past the end of BUF if the remote debug server gave us too
3090 // much data for some reason.
3091 data_received_size = size;
3092 }
3093 memcpy (buf, response.GetStringRef().data(), data_received_size);
3094 return data_received_size;
3095 }
3096 else
3097 {
3098 return response.GetHexBytes(buf, size, '\xdd');
3099 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003100 }
Greg Clayton576d8832011-03-22 04:00:09 +00003101 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00003102 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00003103 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00003104 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003105 else
Greg Clayton9944cd72012-09-19 01:46:31 +00003106 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003107 }
3108 else
3109 {
Jim Ingham35579dd2013-06-03 19:34:01 +00003110 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003111 }
3112 return 0;
3113}
3114
3115size_t
3116ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
3117{
Jason Molenda6076bf42014-05-06 04:34:52 +00003118 GetMaxMemorySize ();
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00003119 if (size > m_max_memory_size)
3120 {
3121 // Keep memory read sizes down to a sane limit. This function will be
Ed Maste81b4c5f2016-01-04 01:43:47 +00003122 // called multiple times in order to complete the task by
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00003123 // lldb_private::Process so it is ok to do this.
3124 size = m_max_memory_size;
3125 }
3126
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003127 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00003128 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Bruce Mitchener9ccb9702015-11-07 04:40:13 +00003129 packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(), endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003130 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003131 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003132 {
Greg Clayton576d8832011-03-22 04:00:09 +00003133 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003134 {
3135 error.Clear();
3136 return size;
3137 }
Greg Clayton576d8832011-03-22 04:00:09 +00003138 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00003139 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00003140 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00003141 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003142 else
Greg Clayton9944cd72012-09-19 01:46:31 +00003143 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 +00003144 }
3145 else
3146 {
Jim Ingham35579dd2013-06-03 19:34:01 +00003147 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003148 }
3149 return 0;
3150}
3151
3152lldb::addr_t
3153ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
3154{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003155 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_EXPRESSIONS));
Greg Clayton2a48f522011-05-14 01:50:35 +00003156 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
Ed Maste81b4c5f2016-01-04 01:43:47 +00003157
Greg Claytoncec91ef2016-02-26 01:20:20 +00003158 if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo)
Greg Clayton2a48f522011-05-14 01:50:35 +00003159 {
Greg Claytoncec91ef2016-02-26 01:20:20 +00003160 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
3161 if (allocated_addr != LLDB_INVALID_ADDRESS || m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes)
3162 return allocated_addr;
3163 }
Greg Clayton2a48f522011-05-14 01:50:35 +00003164
Greg Claytoncec91ef2016-02-26 01:20:20 +00003165 if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo)
3166 {
3167 // Call mmap() to create memory in the inferior..
3168 unsigned prot = 0;
3169 if (permissions & lldb::ePermissionsReadable)
3170 prot |= eMmapProtRead;
3171 if (permissions & lldb::ePermissionsWritable)
3172 prot |= eMmapProtWrite;
3173 if (permissions & lldb::ePermissionsExecutable)
3174 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00003175
Greg Claytoncec91ef2016-02-26 01:20:20 +00003176 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
3177 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
3178 m_addr_to_mmap_size[allocated_addr] = size;
3179 else
3180 {
3181 allocated_addr = LLDB_INVALID_ADDRESS;
3182 if (log)
3183 log->Printf ("ProcessGDBRemote::%s no direct stub support for memory allocation, and InferiorCallMmap also failed - is stub missing register context save/restore capability?", __FUNCTION__);
3184 }
Greg Clayton2a48f522011-05-14 01:50:35 +00003185 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00003186
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003187 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00003188 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003189 else
3190 error.Clear();
3191 return allocated_addr;
3192}
3193
3194Error
Ed Maste81b4c5f2016-01-04 01:43:47 +00003195ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
Greg Clayton46fb5582011-11-18 07:03:08 +00003196 MemoryRegionInfo &region_info)
3197{
Ed Maste81b4c5f2016-01-04 01:43:47 +00003198
Greg Clayton46fb5582011-11-18 07:03:08 +00003199 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
3200 return error;
3201}
3202
3203Error
Johnny Chen64637202012-05-23 21:09:52 +00003204ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
3205{
Ed Maste81b4c5f2016-01-04 01:43:47 +00003206
Johnny Chen64637202012-05-23 21:09:52 +00003207 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
3208 return error;
3209}
3210
3211Error
Enrico Granataf04a2192012-07-13 23:18:48 +00003212ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
3213{
Jaydeep Patil725666c2015-08-13 03:46:01 +00003214 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after, GetTarget().GetArchitecture()));
Enrico Granataf04a2192012-07-13 23:18:48 +00003215 return error;
3216}
3217
3218Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003219ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
3220{
Ed Maste81b4c5f2016-01-04 01:43:47 +00003221 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00003222 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
3223
3224 switch (supported)
3225 {
3226 case eLazyBoolCalculate:
Ed Maste81b4c5f2016-01-04 01:43:47 +00003227 // We should never be deallocating memory without allocating memory
Greg Clayton70b57652011-05-15 01:25:55 +00003228 // first so we should never get eLazyBoolCalculate
3229 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
3230 break;
3231
3232 case eLazyBoolYes:
3233 if (!m_gdb_comm.DeallocateMemory (addr))
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 break;
Ed Maste81b4c5f2016-01-04 01:43:47 +00003236
Greg Clayton70b57652011-05-15 01:25:55 +00003237 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003238 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00003239 {
3240 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003241 if (pos != m_addr_to_mmap_size.end() &&
3242 InferiorCallMunmap(this, addr, pos->second))
3243 m_addr_to_mmap_size.erase (pos);
3244 else
Daniel Malead01b2952012-11-29 21:49:15 +00003245 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003246 }
3247 break;
3248 }
3249
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003250 return error;
3251}
3252
Eugene Zelenko0722f082015-10-24 01:28:05 +00003253
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003254//------------------------------------------------------------------
3255// Process STDIO
3256//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003257size_t
3258ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
3259{
3260 if (m_stdio_communication.IsConnected())
3261 {
3262 ConnectionStatus status;
3263 m_stdio_communication.Write(src, src_len, status, NULL);
3264 }
Vince Harrondf3f00f2015-02-10 21:09:04 +00003265 else if (m_stdin_forward)
Vince Harrone0be4252015-02-06 18:32:57 +00003266 {
3267 m_gdb_comm.SendStdinNotification(src, src_len);
3268 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003269 return 0;
3270}
3271
3272Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003273ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003274{
3275 Error error;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003276 assert(bp_site != NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003277
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003278 // Get logging info
3279 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003280 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003281
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003282 // Get the breakpoint address
3283 const addr_t addr = bp_site->GetLoadAddress();
3284
3285 // Log that a breakpoint was requested
3286 if (log)
3287 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
3288
3289 // Breakpoint already exists and is enabled
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003290 if (bp_site->IsEnabled())
3291 {
3292 if (log)
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003293 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 +00003294 return error;
3295 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003296
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003297 // Get the software breakpoint trap opcode size
3298 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3299
3300 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
3301 // is supported by the remote stub. These are set to true by default, and later set to false
3302 // only after we receive an unimplemented response when sending a breakpoint packet. This means
3303 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
3304 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
3305 // indicates if the user specifically asked for hardware breakpoints. If true then we will
3306 // skip over software breakpoints.
3307 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
3308 {
3309 // Try to send off a software breakpoint packet ($Z0)
Jim Ingham906d91e2016-05-19 02:13:44 +00003310 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size);
3311 if (error_no == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003312 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003313 // The breakpoint was placed successfully
3314 bp_site->SetEnabled(true);
3315 bp_site->SetType(BreakpointSite::eExternal);
Greg Claytoneb023e72013-10-11 19:48:25 +00003316 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003317 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003318
3319 // SendGDBStoppointTypePacket() will return an error if it was unable to set this
3320 // breakpoint. We need to differentiate between a error specific to placing this breakpoint
3321 // or if we have learned that this breakpoint type is unsupported. To do this, we
3322 // must test the support boolean for this breakpoint type to see if it now indicates that
3323 // this breakpoint type is unsupported. If they are still supported then we should return
3324 // with the error code. If they are now unsupported, then we would like to fall through
3325 // and try another form of breakpoint.
3326 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
Jim Ingham906d91e2016-05-19 02:13:44 +00003327 {
3328 if (error_no != UINT8_MAX)
3329 error.SetErrorStringWithFormat("error: %d sending the breakpoint request", errno);
3330 else
3331 error.SetErrorString("error sending the breakpoint request");
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003332 return error;
Jim Ingham906d91e2016-05-19 02:13:44 +00003333 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003334
3335 // We reach here when software breakpoints have been found to be unsupported. For future
3336 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
3337 // known not to be supported.
3338 if (log)
3339 log->Printf("Software breakpoints are unsupported");
3340
3341 // So we will fall through and try a hardware breakpoint
3342 }
3343
3344 // The process of setting a hardware breakpoint is much the same as above. We check the
3345 // supported boolean for this breakpoint type, and if it is thought to be supported then we
3346 // will try to set this breakpoint with a hardware breakpoint.
3347 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3348 {
3349 // Try to send off a hardware breakpoint packet ($Z1)
Jim Ingham906d91e2016-05-19 02:13:44 +00003350 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size);
3351 if (error_no == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003352 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003353 // The breakpoint was placed successfully
3354 bp_site->SetEnabled(true);
3355 bp_site->SetType(BreakpointSite::eHardware);
3356 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003357 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003358
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003359 // Check if the error was something other then an unsupported breakpoint type
3360 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3361 {
3362 // Unable to set this hardware breakpoint
Jim Ingham906d91e2016-05-19 02:13:44 +00003363 if (error_no != UINT8_MAX)
3364 error.SetErrorStringWithFormat("error: %d sending the hardware breakpoint request "
3365 "(hardware breakpoint resources might be exhausted or unavailable)",
3366 error_no);
3367 else
3368 error.SetErrorString("error sending the hardware breakpoint request (hardware breakpoint resources "
3369 "might be exhausted or unavailable)");
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003370 return error;
3371 }
3372
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003373 // We will reach here when the stub gives an unsupported response to a hardware breakpoint
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003374 if (log)
3375 log->Printf("Hardware breakpoints are unsupported");
3376
3377 // Finally we will falling through to a #trap style breakpoint
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003378 }
3379
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003380 // Don't fall through when hardware breakpoints were specifically requested
3381 if (bp_site->HardwareRequired())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003382 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003383 error.SetErrorString("hardware breakpoints are not supported");
3384 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003385 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003386
3387 // As a last resort we want to place a manual breakpoint. An instruction
3388 // is placed into the process memory using memory write packets.
3389 return EnableSoftwareBreakpoint(bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003390}
3391
3392Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003393ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003394{
3395 Error error;
3396 assert (bp_site != NULL);
3397 addr_t addr = bp_site->GetLoadAddress();
3398 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00003399 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003400 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003401 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003402
3403 if (bp_site->IsEnabled())
3404 {
3405 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
3406
Greg Clayton8b82f082011-04-12 05:54:46 +00003407 BreakpointSite::Type bp_type = bp_site->GetType();
3408 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003409 {
Greg Clayton8b82f082011-04-12 05:54:46 +00003410 case BreakpointSite::eSoftware:
3411 error = DisableSoftwareBreakpoint (bp_site);
3412 break;
3413
3414 case BreakpointSite::eHardware:
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003415 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003416 error.SetErrorToGenericError();
3417 break;
3418
3419 case BreakpointSite::eExternal:
Jim Inghama04ef752014-03-07 11:18:02 +00003420 {
3421 GDBStoppointType stoppoint_type;
3422 if (bp_site->IsHardware())
3423 stoppoint_type = eBreakpointHardware;
3424 else
3425 stoppoint_type = eBreakpointSoftware;
Ed Maste81b4c5f2016-01-04 01:43:47 +00003426
Jim Inghama04ef752014-03-07 11:18:02 +00003427 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003428 error.SetErrorToGenericError();
Jim Inghama04ef752014-03-07 11:18:02 +00003429 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003430 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003431 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003432 if (error.Success())
3433 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003434 }
3435 else
3436 {
3437 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003438 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 +00003439 return error;
3440 }
3441
3442 if (error.Success())
3443 error.SetErrorToGenericError();
3444 return error;
3445}
3446
Johnny Chen11309a32011-09-06 22:38:36 +00003447// Pre-requisite: wp != NULL.
3448static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00003449GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00003450{
3451 assert(wp);
3452 bool watch_read = wp->WatchpointRead();
3453 bool watch_write = wp->WatchpointWrite();
3454
3455 // watch_read and watch_write cannot both be false.
3456 assert(watch_read || watch_write);
3457 if (watch_read && watch_write)
3458 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00003459 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00003460 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00003461 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00003462 return eWatchpointWrite;
3463}
3464
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003465Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003466ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003467{
3468 Error error;
3469 if (wp)
3470 {
3471 user_id_t watchID = wp->GetID();
3472 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00003473 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003474 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003475 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003476 if (wp->IsEnabled())
3477 {
3478 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003479 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 +00003480 return error;
3481 }
Johnny Chen11309a32011-09-06 22:38:36 +00003482
3483 GDBStoppointType type = GetGDBStoppointType(wp);
3484 // Pass down an appropriate z/Z packet...
3485 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003486 {
Johnny Chen11309a32011-09-06 22:38:36 +00003487 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
3488 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003489 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003490 return error;
3491 }
3492 else
3493 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003494 }
Johnny Chen11309a32011-09-06 22:38:36 +00003495 else
3496 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003497 }
3498 else
3499 {
Johnny Chen01a67862011-10-14 00:42:25 +00003500 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003501 }
3502 if (error.Success())
3503 error.SetErrorToGenericError();
3504 return error;
3505}
3506
3507Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003508ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003509{
3510 Error error;
3511 if (wp)
3512 {
3513 user_id_t watchID = wp->GetID();
3514
Greg Clayton5160ce52013-03-27 23:08:40 +00003515 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003516
3517 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00003518
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003519 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003520 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003521
Johnny Chen11309a32011-09-06 22:38:36 +00003522 if (!wp->IsEnabled())
3523 {
3524 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003525 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 +00003526 // See also 'class WatchpointSentry' within StopInfo.cpp.
3527 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
3528 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00003529 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003530 return error;
3531 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00003532
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003533 if (wp->IsHardware())
3534 {
Johnny Chen11309a32011-09-06 22:38:36 +00003535 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003536 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00003537 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
3538 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003539 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003540 return error;
3541 }
3542 else
Ed Maste81b4c5f2016-01-04 01:43:47 +00003543 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003544 }
3545 // TODO: clear software watchpoints if we implement them
3546 }
3547 else
3548 {
Johnny Chen01a67862011-10-14 00:42:25 +00003549 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003550 }
3551 if (error.Success())
3552 error.SetErrorToGenericError();
3553 return error;
3554}
3555
3556void
3557ProcessGDBRemote::Clear()
3558{
3559 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00003560 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003561 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003562}
3563
3564Error
3565ProcessGDBRemote::DoSignal (int signo)
3566{
3567 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00003568 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003569 if (log)
3570 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
3571
3572 if (!m_gdb_comm.SendAsyncSignal (signo))
3573 error.SetErrorStringWithFormat("failed to send signal %i", signo);
3574 return error;
3575}
3576
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003577Error
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00003578ProcessGDBRemote::EstablishConnectionIfNeeded (const ProcessInfo &process_info)
3579{
3580 // Make sure we aren't already connected?
3581 if (m_gdb_comm.IsConnected())
3582 return Error();
3583
3584 PlatformSP platform_sp (GetTarget ().GetPlatform ());
3585 if (platform_sp && !platform_sp->IsHost ())
3586 return Error("Lost debug server connection");
3587
3588 auto error = LaunchAndConnectToDebugserver (process_info);
3589 if (error.Fail())
3590 {
3591 const char *error_string = error.AsCString();
3592 if (error_string == nullptr)
3593 error_string = "unable to launch " DEBUGSERVER_BASENAME;
3594 }
3595 return error;
3596}
3597
3598Error
Greg Clayton91a9b2472013-12-04 19:19:12 +00003599ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003600{
Pavel Labath998bdc52016-05-11 16:59:04 +00003601 using namespace std::placeholders; // For _1, _2, etc.
3602
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003603 Error error;
3604 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
3605 {
3606 // If we locate debugserver, keep that located version around
3607 static FileSpec g_debugserver_file_spec;
3608
Han Ming Ong84647042012-02-25 01:07:38 +00003609 ProcessLaunchInfo debugserver_launch_info;
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00003610 // Make debugserver run in its own session so signals generated by
3611 // special terminal key sequences (^C) don't affect debugserver.
3612 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3613
Pavel Labath194357c2016-05-12 11:10:01 +00003614 const std::weak_ptr<ProcessGDBRemote> this_wp = std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
3615 debugserver_launch_info.SetMonitorProcessCallback(std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3, _4),
Pavel Labath998bdc52016-05-11 16:59:04 +00003616 false);
Greg Clayton91a9b2472013-12-04 19:19:12 +00003617 debugserver_launch_info.SetUserID(process_info.GetUserID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003618
Todd Fiala013434e2014-07-09 01:29:05 +00003619#if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__) || defined (__aarch64__))
Greg Claytonfda4fab2014-01-10 22:24:11 +00003620 // On iOS, still do a local connection using a random port
Greg Clayton16810922014-02-27 19:38:18 +00003621 const char *hostname = "127.0.0.1";
Greg Claytonfda4fab2014-01-10 22:24:11 +00003622 uint16_t port = get_random_port ();
3623#else
3624 // Set hostname being NULL to do the reverse connect where debugserver
3625 // will bind to port zero and it will communicate back to us the port
3626 // that we will connect to
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003627 const char *hostname = nullptr;
Greg Claytonfda4fab2014-01-10 22:24:11 +00003628 uint16_t port = 0;
3629#endif
3630
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003631 StreamString url_str;
3632 const char* url = nullptr;
3633 if (hostname != nullptr)
3634 {
3635 url_str.Printf("%s:%u", hostname, port);
3636 url = url_str.GetData();
3637 }
3638
3639 error = m_gdb_comm.StartDebugserverProcess (url,
Greg Clayton6988abc2015-10-19 20:44:01 +00003640 GetTarget().GetPlatform().get(),
Greg Clayton00fe87b2013-12-05 22:58:22 +00003641 debugserver_launch_info,
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003642 &port);
Greg Clayton91a9b2472013-12-04 19:19:12 +00003643
3644 if (error.Success ())
3645 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003646 else
Greg Clayton91a9b2472013-12-04 19:19:12 +00003647 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003648
3649 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3650 StartAsyncThread ();
Ed Maste81b4c5f2016-01-04 01:43:47 +00003651
Greg Clayton91a9b2472013-12-04 19:19:12 +00003652 if (error.Fail())
3653 {
3654 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
3655
3656 if (log)
3657 log->Printf("failed to start debugserver process: %s", error.AsCString());
3658 return error;
3659 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00003660
Greg Clayton00fe87b2013-12-05 22:58:22 +00003661 if (m_gdb_comm.IsConnected())
3662 {
3663 // Finish the connection process by doing the handshake without connecting (send NULL URL)
3664 ConnectToDebugserver (NULL);
3665 }
3666 else
3667 {
Greg Claytonfda4fab2014-01-10 22:24:11 +00003668 StreamString connect_url;
3669 connect_url.Printf("connect://%s:%u", hostname, port);
3670 error = ConnectToDebugserver (connect_url.GetString().c_str());
Greg Clayton00fe87b2013-12-05 22:58:22 +00003671 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00003672
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003673 }
3674 return error;
3675}
3676
3677bool
Pavel Labath194357c2016-05-12 11:10:01 +00003678ProcessGDBRemote::MonitorDebugserverProcess(std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid,
Pavel Labath998bdc52016-05-11 16:59:04 +00003679 bool exited, // True if the process did exit
3680 int signo, // Zero for no signal
3681 int exit_status // Exit value of process if signal is zero
3682 )
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003683{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003684 // "debugserver_pid" argument passed in is the process ID for
3685 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00003686 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Pavel Labath194357c2016-05-12 11:10:01 +00003687 const bool handled = true;
Greg Claytone4e45922011-11-16 05:37:56 +00003688
Greg Clayton6779606a2011-01-22 23:43:18 +00003689 if (log)
Pavel Labath194357c2016-05-12 11:10:01 +00003690 log->Printf("ProcessGDBRemote::%s(process_wp, pid=%" PRIu64 ", signo=%i (0x%x), exit_status=%i)", __FUNCTION__,
3691 debugserver_pid, signo, signo, exit_status);
Greg Clayton6779606a2011-01-22 23:43:18 +00003692
Pavel Labath194357c2016-05-12 11:10:01 +00003693 std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
3694 if (log)
Saleem Abdulrasoolabdfc212016-05-15 18:18:13 +00003695 log->Printf("ProcessGDBRemote::%s(process = %p)", __FUNCTION__, static_cast<void *>(process_sp.get()));
Pavel Labath194357c2016-05-12 11:10:01 +00003696 if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
3697 return handled;
3698
3699 // Sleep for a half a second to make sure our inferior process has
3700 // time to set its exit status before we set it incorrectly when
3701 // both the debugserver and the inferior process shut down.
3702 usleep(500000);
3703 // If our process hasn't yet exited, debugserver might have died.
3704 // If the process did exit, then we are reaping it.
3705 const StateType state = process_sp->GetState();
3706
3707 if (state != eStateInvalid && state != eStateUnloaded && state != eStateExited && state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003708 {
Pavel Labath194357c2016-05-12 11:10:01 +00003709 char error_str[1024];
3710 if (signo)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003711 {
Pavel Labath194357c2016-05-12 11:10:01 +00003712 const char *signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
3713 if (signal_cstr)
3714 ::snprintf(error_str, sizeof(error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3715 else
3716 ::snprintf(error_str, sizeof(error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003717 }
Pavel Labath194357c2016-05-12 11:10:01 +00003718 else
3719 {
3720 ::snprintf(error_str, sizeof(error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x",
3721 exit_status);
3722 }
3723
3724 process_sp->SetExitStatus(-1, error_str);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003725 }
Pavel Labath194357c2016-05-12 11:10:01 +00003726 // Debugserver has exited we need to let our ProcessGDBRemote
3727 // know that it no longer has a debugserver instance
3728 process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3729 return handled;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003730}
3731
3732void
3733ProcessGDBRemote::KillDebugserverProcess ()
3734{
Greg Claytonfbb76342013-11-20 21:07:01 +00003735 m_gdb_comm.Disconnect();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003736 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3737 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003738 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003739 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3740 }
3741}
3742
3743void
3744ProcessGDBRemote::Initialize()
3745{
Davide Italianoc8d69822015-04-03 04:24:32 +00003746 static std::once_flag g_once_flag;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003747
Davide Italianoc8d69822015-04-03 04:24:32 +00003748 std::call_once(g_once_flag, []()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003749 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003750 PluginManager::RegisterPlugin (GetPluginNameStatic(),
3751 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00003752 CreateInstance,
3753 DebuggerInitialize);
Davide Italianoc8d69822015-04-03 04:24:32 +00003754 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003755}
3756
Greg Clayton7f982402013-07-15 22:54:20 +00003757void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003758ProcessGDBRemote::DebuggerInitialize (Debugger &debugger)
Greg Clayton7f982402013-07-15 22:54:20 +00003759{
3760 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
3761 {
3762 const bool is_global_setting = true;
3763 PluginManager::CreateSettingForProcessPlugin (debugger,
3764 GetGlobalPluginProperties()->GetValueProperties(),
3765 ConstString ("Properties for the gdb-remote process plug-in."),
3766 is_global_setting);
3767 }
3768}
3769
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003770bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003771ProcessGDBRemote::StartAsyncThread ()
3772{
Greg Clayton5160ce52013-03-27 23:08:40 +00003773 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003774
3775 if (log)
3776 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Ed Maste81b4c5f2016-01-04 01:43:47 +00003777
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +00003778 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003779 if (!m_async_thread.IsJoinable())
Jim Ingham455fa5c2012-11-01 01:15:33 +00003780 {
3781 // Create a thread that watches our internal state and controls which
3782 // events make it to clients (into the DCProcess event queue).
Zachary Turner39de3112014-09-09 20:54:56 +00003783
3784 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003785 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003786 else if (log)
3787 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was already running.", __FUNCTION__);
Zachary Turner39de3112014-09-09 20:54:56 +00003788
Zachary Turneracee96a2014-09-23 18:32:09 +00003789 return m_async_thread.IsJoinable();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003790}
3791
3792void
3793ProcessGDBRemote::StopAsyncThread ()
3794{
Greg Clayton5160ce52013-03-27 23:08:40 +00003795 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003796
3797 if (log)
3798 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
3799
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +00003800 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003801 if (m_async_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003802 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00003803 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
Ed Maste81b4c5f2016-01-04 01:43:47 +00003804
Jim Ingham455fa5c2012-11-01 01:15:33 +00003805 // This will shut down the async thread.
3806 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3807
3808 // Stop the stdio thread
Zachary Turner39de3112014-09-09 20:54:56 +00003809 m_async_thread.Join(nullptr);
Pavel Labatha55a9532015-03-11 09:53:42 +00003810 m_async_thread.Reset();
Jim Ingham455fa5c2012-11-01 01:15:33 +00003811 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003812 else if (log)
3813 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003814}
3815
Ewan Crawford76df2882015-06-23 12:32:06 +00003816bool
3817ProcessGDBRemote::HandleNotifyPacket (StringExtractorGDBRemote &packet)
3818{
3819 // get the packet at a string
3820 const std::string &pkt = packet.GetStringRef();
3821 // skip %stop:
3822 StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
3823
3824 // pass as a thread stop info packet
3825 SetLastStopPacket(stop_info);
3826
3827 // check for more stop reasons
3828 HandleStopReplySequence();
3829
3830 // if the process is stopped then we need to fake a resume
3831 // so that we can stop properly with the new break. This
3832 // is possible due to SetPrivateState() broadcasting the
3833 // state change as a side effect.
3834 if (GetPrivateState() == lldb::StateType::eStateStopped)
3835 {
3836 SetPrivateState(lldb::StateType::eStateRunning);
3837 }
3838
3839 // since we have some stopped packets we can halt the process
3840 SetPrivateState(lldb::StateType::eStateStopped);
3841
3842 return true;
3843}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003844
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003845thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003846ProcessGDBRemote::AsyncThread (void *arg)
3847{
3848 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
3849
Greg Clayton5160ce52013-03-27 23:08:40 +00003850 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003851 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003852 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003853
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003854 EventSP event_sp;
Pavel Labath50556852015-09-03 09:36:22 +00003855 bool done = false;
3856 while (!done)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003857 {
Pavel Labath50556852015-09-03 09:36:22 +00003858 if (log)
3859 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003860 if (process->m_async_listener_sp->WaitForEvent(std::chrono::microseconds(0), event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003861 {
Pavel Labath50556852015-09-03 09:36:22 +00003862 const uint32_t event_type = event_sp->GetType();
3863 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003864 {
3865 if (log)
Pavel Labath50556852015-09-03 09:36:22 +00003866 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
3867
3868 switch (event_type)
3869 {
3870 case eBroadcastBitAsyncContinue:
3871 {
3872 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
3873
3874 if (continue_packet)
3875 {
3876 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
3877 const size_t continue_cstr_len = continue_packet->GetByteSize ();
3878 if (log)
3879 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
3880
3881 if (::strstr (continue_cstr, "vAttach") == NULL)
3882 process->SetPrivateState(eStateRunning);
3883 StringExtractorGDBRemote response;
3884
3885 // If in Non-Stop-Mode
3886 if (process->GetTarget().GetNonStopModeEnabled())
3887 {
3888 // send the vCont packet
Pavel Labath4cb69922016-07-29 15:41:52 +00003889 if (!process->GetGDBRemote().SendvContPacket(process, continue_cstr, continue_cstr_len, response))
Pavel Labath50556852015-09-03 09:36:22 +00003890 {
3891 // Something went wrong
3892 done = true;
3893 break;
3894 }
3895 }
3896 // If in All-Stop-Mode
3897 else
3898 {
Pavel Labath4cb69922016-07-29 15:41:52 +00003899 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Pavel Labath50556852015-09-03 09:36:22 +00003900
3901 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
3902 // The thread ID list might be contained within the "response", or the stop reply packet that
3903 // caused the stop. So clear it now before we give the stop reply packet to the process
3904 // using the process->SetLastStopPacket()...
3905 process->ClearThreadIDList ();
3906
3907 switch (stop_state)
3908 {
3909 case eStateStopped:
3910 case eStateCrashed:
3911 case eStateSuspended:
3912 process->SetLastStopPacket (response);
3913 process->SetPrivateState (stop_state);
3914 break;
3915
3916 case eStateExited:
3917 {
3918 process->SetLastStopPacket (response);
3919 process->ClearThreadIDList();
3920 response.SetFilePos(1);
Ed Maste81b4c5f2016-01-04 01:43:47 +00003921
Pavel Labath50556852015-09-03 09:36:22 +00003922 int exit_status = response.GetHexU8();
3923 const char *desc_cstr = NULL;
3924 StringExtractor extractor;
3925 std::string desc_string;
3926 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';')
3927 {
3928 std::string desc_token;
3929 while (response.GetNameColonValue (desc_token, desc_string))
3930 {
3931 if (desc_token == "description")
3932 {
3933 extractor.GetStringRef().swap(desc_string);
3934 extractor.SetFilePos(0);
3935 extractor.GetHexByteString (desc_string);
3936 desc_cstr = desc_string.c_str();
3937 }
3938 }
3939 }
3940 process->SetExitStatus(exit_status, desc_cstr);
3941 done = true;
3942 break;
3943 }
3944 case eStateInvalid:
3945 {
3946 // Check to see if we were trying to attach and if we got back
3947 // the "E87" error code from debugserver -- this indicates that
3948 // the process is not debuggable. Return a slightly more helpful
3949 // error message about why the attach failed.
3950 if (::strstr (continue_cstr, "vAttach") != NULL
3951 && response.GetError() == 0x87)
3952 {
3953 process->SetExitStatus(-1, "cannot attach to process due to System Integrity Protection");
3954 }
3955 // E01 code from vAttach means that the attach failed
3956 if (::strstr (continue_cstr, "vAttach") != NULL
3957 && response.GetError() == 0x1)
3958 {
3959 process->SetExitStatus(-1, "unable to attach");
3960 }
3961 else
3962 {
3963 process->SetExitStatus(-1, "lost connection");
3964 }
3965 break;
3966 }
3967
3968 default:
3969 process->SetPrivateState (stop_state);
3970 break;
3971 } // switch(stop_state)
3972 } // else // if in All-stop-mode
3973 } // if (continue_packet)
3974 } // case eBroadcastBitAysncContinue
3975 break;
3976
3977 case eBroadcastBitAsyncThreadShouldExit:
3978 if (log)
3979 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
3980 done = true;
3981 break;
3982
3983 default:
3984 if (log)
3985 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
3986 done = true;
3987 break;
3988 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003989 }
Pavel Labath50556852015-09-03 09:36:22 +00003990 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
3991 {
3992 switch (event_type)
3993 {
3994 case Communication::eBroadcastBitReadThreadDidExit:
3995 process->SetExitStatus (-1, "lost connection");
3996 done = true;
3997 break;
3998
3999 case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify:
4000 {
4001 lldb_private::Event *event = event_sp.get();
4002 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event);
4003 StringExtractorGDBRemote notify((const char*)continue_packet->GetBytes());
4004 // Hand this over to the process to handle
4005 process->HandleNotifyPacket(notify);
4006 break;
4007 }
4008
4009 default:
4010 if (log)
4011 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
4012 done = true;
4013 break;
4014 }
4015 }
4016 }
4017 else
4018 {
4019 if (log)
4020 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
4021 done = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004022 }
4023 }
4024
4025 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004026 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004027
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004028 return NULL;
4029}
4030
Greg Claytone996fd32011-03-08 22:40:15 +00004031//uint32_t
4032//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4033//{
4034// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
4035// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
4036// if (m_local_debugserver)
4037// {
4038// return Host::ListProcessesMatchingName (name, matches, pids);
4039// }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004040// else
Greg Claytone996fd32011-03-08 22:40:15 +00004041// {
4042// // FIXME: Implement talking to the remote debugserver.
4043// return 0;
4044// }
4045//
4046//}
4047//
Jim Ingham1c823b42011-01-22 01:33:44 +00004048bool
4049ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004050 StoppointCallbackContext *context,
Jim Ingham1c823b42011-01-22 01:33:44 +00004051 lldb::user_id_t break_id,
4052 lldb::user_id_t break_loc_id)
4053{
Ed Maste81b4c5f2016-01-04 01:43:47 +00004054 // 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 +00004055 // run so I can stop it if that's what I want to do.
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004056 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00004057 if (log)
4058 log->Printf("Hit New Thread Notification breakpoint.");
4059 return false;
4060}
4061
Eugene Zelenko0722f082015-10-24 01:28:05 +00004062
Jim Ingham1c823b42011-01-22 01:33:44 +00004063bool
4064ProcessGDBRemote::StartNoticingNewThreads()
4065{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004066 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00004067 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00004068 {
Greg Clayton4116e932012-05-15 02:33:01 +00004069 if (log && log->GetVerbose())
4070 log->Printf("Enabled noticing new thread breakpoint.");
4071 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00004072 }
Greg Clayton4116e932012-05-15 02:33:01 +00004073 else
Jim Ingham1c823b42011-01-22 01:33:44 +00004074 {
Zachary Turner7529df92015-09-01 20:02:29 +00004075 PlatformSP platform_sp (GetTarget().GetPlatform());
Greg Clayton4116e932012-05-15 02:33:01 +00004076 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00004077 {
Zachary Turner7529df92015-09-01 20:02:29 +00004078 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(GetTarget());
Greg Clayton4116e932012-05-15 02:33:01 +00004079 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00004080 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00004081 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00004082 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
4083 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00004084 }
4085 else
4086 {
4087 if (log)
4088 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00004089 }
4090 }
4091 }
Greg Clayton4116e932012-05-15 02:33:01 +00004092 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00004093}
4094
4095bool
4096ProcessGDBRemote::StopNoticingNewThreads()
Ed Maste81b4c5f2016-01-04 01:43:47 +00004097{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004098 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00004099 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00004100 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00004101
4102 if (m_thread_create_bp_sp)
4103 m_thread_create_bp_sp->SetEnabled(false);
4104
Jim Ingham1c823b42011-01-22 01:33:44 +00004105 return true;
4106}
Ed Maste81b4c5f2016-01-04 01:43:47 +00004107
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004108DynamicLoader *
Jason Molenda5e8534e2012-10-03 01:29:34 +00004109ProcessGDBRemote::GetDynamicLoader ()
4110{
4111 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00004112 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00004113 return m_dyld_ap.get();
4114}
Jim Ingham1c823b42011-01-22 01:33:44 +00004115
Jason Molendaa3329782014-03-29 18:54:20 +00004116Error
4117ProcessGDBRemote::SendEventData(const char *data)
4118{
4119 int return_value;
4120 bool was_supported;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004121
Jason Molendaa3329782014-03-29 18:54:20 +00004122 Error error;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004123
Jason Molendaa3329782014-03-29 18:54:20 +00004124 return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported);
4125 if (return_value != 0)
4126 {
4127 if (!was_supported)
4128 error.SetErrorString("Sending events is not supported for this process.");
4129 else
4130 error.SetErrorStringWithFormat("Error sending event data: %d.", return_value);
4131 }
4132 return error;
4133}
4134
Steve Pucci03904ac2014-03-04 23:18:46 +00004135const DataBufferSP
4136ProcessGDBRemote::GetAuxvData()
4137{
4138 DataBufferSP buf;
4139 if (m_gdb_comm.GetQXferAuxvReadSupported())
4140 {
4141 std::string response_string;
4142 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success)
4143 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length()));
4144 }
4145 return buf;
4146}
4147
Jason Molenda705b1802014-06-13 02:37:02 +00004148StructuredData::ObjectSP
4149ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid)
4150{
4151 StructuredData::ObjectSP object_sp;
4152
4153 if (m_gdb_comm.GetThreadExtendedInfoSupported())
4154 {
4155 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4156 SystemRuntime *runtime = GetSystemRuntime();
4157 if (runtime)
4158 {
4159 runtime->AddThreadExtendedInfoPacketHints (args_dict);
4160 }
4161 args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid);
4162
4163 StreamString packet;
4164 packet << "jThreadExtendedInfo:";
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004165 args_dict->Dump (packet, false);
Jason Molenda705b1802014-06-13 02:37:02 +00004166
4167 // FIXME the final character of a JSON dictionary, '}', is the escape
4168 // character in gdb-remote binary mode. lldb currently doesn't escape
4169 // these characters in its packet output -- so we add the quoted version
4170 // of the } character here manually in case we talk to a debugserver which
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004171 // un-escapes the characters at packet read time.
Jason Molenda705b1802014-06-13 02:37:02 +00004172 packet << (char) (0x7d ^ 0x20);
4173
4174 StringExtractorGDBRemote response;
Greg Clayton830c81d2016-04-01 00:41:29 +00004175 response.SetResponseValidatorToJSON();
Jason Molenda705b1802014-06-13 02:37:02 +00004176 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4177 {
4178 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4179 if (response_type == StringExtractorGDBRemote::eResponse)
4180 {
4181 if (!response.Empty())
4182 {
Jason Molenda20ee21b2015-07-10 23:15:22 +00004183 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4184 }
4185 }
4186 }
4187 }
4188 return object_sp;
4189}
4190
4191StructuredData::ObjectSP
4192ProcessGDBRemote::GetLoadedDynamicLibrariesInfos (lldb::addr_t image_list_address, lldb::addr_t image_count)
4193{
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004194
4195 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4196 args_dict->GetAsDictionary()->AddIntegerItem ("image_list_address", image_list_address);
4197 args_dict->GetAsDictionary()->AddIntegerItem ("image_count", image_count);
4198
4199 return GetLoadedDynamicLibrariesInfos_sender (args_dict);
4200}
4201
4202StructuredData::ObjectSP
4203ProcessGDBRemote::GetLoadedDynamicLibrariesInfos ()
4204{
4205 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4206
4207 args_dict->GetAsDictionary()->AddBooleanItem ("fetch_all_solibs", true);
4208
4209 return GetLoadedDynamicLibrariesInfos_sender (args_dict);
4210}
4211
4212StructuredData::ObjectSP
4213ProcessGDBRemote::GetLoadedDynamicLibrariesInfos (const std::vector<lldb::addr_t> &load_addresses)
4214{
4215 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4216 StructuredData::ArraySP addresses(new StructuredData::Array);
4217
4218 for (auto addr : load_addresses)
4219 {
4220 StructuredData::ObjectSP addr_sp (new StructuredData::Integer (addr));
4221 addresses->AddItem (addr_sp);
4222 }
4223
4224 args_dict->GetAsDictionary()->AddItem ("solib_addresses", addresses);
4225
4226 return GetLoadedDynamicLibrariesInfos_sender (args_dict);
4227}
4228
4229StructuredData::ObjectSP
4230ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender (StructuredData::ObjectSP args_dict)
4231{
Jason Molenda20ee21b2015-07-10 23:15:22 +00004232 StructuredData::ObjectSP object_sp;
4233
4234 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported())
4235 {
Jason Molenda1d3b3562015-11-05 23:54:29 +00004236 // Scope for the scoped timeout object
4237 GDBRemoteCommunication::ScopedTimeout timeout (m_gdb_comm, 10);
4238
Jason Molenda20ee21b2015-07-10 23:15:22 +00004239 StreamString packet;
4240 packet << "jGetLoadedDynamicLibrariesInfos:";
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004241 args_dict->Dump (packet, false);
Jason Molenda20ee21b2015-07-10 23:15:22 +00004242
4243 // FIXME the final character of a JSON dictionary, '}', is the escape
4244 // character in gdb-remote binary mode. lldb currently doesn't escape
4245 // these characters in its packet output -- so we add the quoted version
4246 // of the } character here manually in case we talk to a debugserver which
4247 // un-escapes the characters at packet read time.
4248 packet << (char) (0x7d ^ 0x20);
4249
4250 StringExtractorGDBRemote response;
Greg Clayton830c81d2016-04-01 00:41:29 +00004251 response.SetResponseValidatorToJSON();
Jason Molenda20ee21b2015-07-10 23:15:22 +00004252 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4253 {
4254 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4255 if (response_type == StringExtractorGDBRemote::eResponse)
4256 {
4257 if (!response.Empty())
4258 {
Jason Molenda705b1802014-06-13 02:37:02 +00004259 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4260 }
4261 }
4262 }
4263 }
4264 return object_sp;
4265}
4266
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004267
4268
4269
Jason Molenda37397352016-07-22 00:17:55 +00004270StructuredData::ObjectSP
4271ProcessGDBRemote::GetSharedCacheInfo ()
4272{
4273 StructuredData::ObjectSP object_sp;
4274 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4275
4276 if (m_gdb_comm.GetSharedCacheInfoSupported())
4277 {
4278 StreamString packet;
4279 packet << "jGetSharedCacheInfo:";
4280 args_dict->Dump (packet, false);
4281
4282 // FIXME the final character of a JSON dictionary, '}', is the escape
4283 // character in gdb-remote binary mode. lldb currently doesn't escape
4284 // these characters in its packet output -- so we add the quoted version
4285 // of the } character here manually in case we talk to a debugserver which
4286 // un-escapes the characters at packet read time.
4287 packet << (char) (0x7d ^ 0x20);
4288
4289 StringExtractorGDBRemote response;
4290 response.SetResponseValidatorToJSON();
4291 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4292 {
4293 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4294 if (response_type == StringExtractorGDBRemote::eResponse)
4295 {
4296 if (!response.Empty())
4297 {
4298 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4299 }
4300 }
4301 }
4302 }
4303 return object_sp;
4304}
4305
4306
Jason Molenda6076bf42014-05-06 04:34:52 +00004307// Establish the largest memory read/write payloads we should use.
4308// If the remote stub has a max packet size, stay under that size.
Ed Maste81b4c5f2016-01-04 01:43:47 +00004309//
4310// If the remote stub's max packet size is crazy large, use a
Jason Molenda6076bf42014-05-06 04:34:52 +00004311// reasonable largeish default.
4312//
4313// If the remote stub doesn't advertise a max packet size, use a
4314// conservative default.
4315
4316void
4317ProcessGDBRemote::GetMaxMemorySize()
4318{
4319 const uint64_t reasonable_largeish_default = 128 * 1024;
4320 const uint64_t conservative_default = 512;
4321
4322 if (m_max_memory_size == 0)
4323 {
4324 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4325 if (stub_max_size != UINT64_MAX && stub_max_size != 0)
4326 {
4327 // Save the stub's claimed maximum packet size
4328 m_remote_stub_max_memory_size = stub_max_size;
4329
4330 // Even if the stub says it can support ginormous packets,
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004331 // don't exceed our reasonable largeish default packet size.
Jason Molenda6076bf42014-05-06 04:34:52 +00004332 if (stub_max_size > reasonable_largeish_default)
4333 {
4334 stub_max_size = reasonable_largeish_default;
4335 }
4336
4337 m_max_memory_size = stub_max_size;
4338 }
4339 else
4340 {
4341 m_max_memory_size = conservative_default;
4342 }
4343 }
4344}
4345
4346void
4347ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max)
4348{
4349 if (user_specified_max != 0)
4350 {
4351 GetMaxMemorySize ();
4352
4353 if (m_remote_stub_max_memory_size != 0)
4354 {
4355 if (m_remote_stub_max_memory_size < user_specified_max)
4356 {
4357 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a packet size too big, go as big
4358 // as the remote stub says we can go.
4359 }
4360 else
4361 {
4362 m_max_memory_size = user_specified_max; // user's packet size is good
4363 }
4364 }
4365 else
4366 {
4367 m_max_memory_size = user_specified_max; // user's packet size is probably fine
4368 }
4369 }
4370}
4371
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004372bool
4373ProcessGDBRemote::GetModuleSpec(const FileSpec& module_file_spec,
4374 const ArchSpec& arch,
4375 ModuleSpec &module_spec)
4376{
4377 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PLATFORM);
4378
4379 if (!m_gdb_comm.GetModuleInfo (module_file_spec, arch, module_spec))
4380 {
4381 if (log)
4382 log->Printf ("ProcessGDBRemote::%s - failed to get module info for %s:%s",
4383 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4384 arch.GetTriple ().getTriple ().c_str ());
4385 return false;
4386 }
4387
4388 if (log)
4389 {
4390 StreamString stream;
4391 module_spec.Dump (stream);
4392 log->Printf ("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4393 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4394 arch.GetTriple ().getTriple ().c_str (), stream.GetString ().c_str ());
4395 }
4396
4397 return true;
4398}
4399
Jim Ingham13c30d22015-11-05 22:33:17 +00004400bool
4401ProcessGDBRemote::GetHostOSVersion(uint32_t &major,
4402 uint32_t &minor,
4403 uint32_t &update)
4404{
4405 if (m_gdb_comm.GetOSVersion(major, minor, update))
4406 return true;
4407 // We failed to get the host OS version, defer to the base
4408 // implementation to correctly invalidate the arguments.
4409 return Process::GetHostOSVersion(major, minor, update);
4410}
4411
Colin Rileyc3c95b22015-04-16 15:51:33 +00004412namespace {
4413
4414typedef std::vector<std::string> stringVec;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004415
4416typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004417struct RegisterSetInfo
4418{
4419 ConstString name;
4420};
Colin Rileyc3c95b22015-04-16 15:51:33 +00004421
Greg Claytond04f0ed2015-05-26 18:00:51 +00004422typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004423
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004424struct GdbServerTargetInfo
4425{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004426 std::string arch;
4427 std::string osabi;
4428 stringVec includes;
4429 RegisterSetMap reg_set_map;
4430 XMLNode feature_node;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004431};
Ed Maste81b4c5f2016-01-04 01:43:47 +00004432
Colin Rileyc3c95b22015-04-16 15:51:33 +00004433bool
Francis Ricci55954ae2016-04-25 21:03:55 +00004434ParseRegisters (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 +00004435{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004436 if (!feature_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004437 return false;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004438
Jason Molenda63bd0db2015-09-15 23:20:34 +00004439 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 +00004440 std::string gdb_group;
4441 std::string gdb_type;
4442 ConstString reg_name;
4443 ConstString alt_name;
4444 ConstString set_name;
4445 std::vector<uint32_t> value_regs;
4446 std::vector<uint32_t> invalidate_regs;
4447 bool encoding_set = false;
4448 bool format_set = false;
4449 RegisterInfo reg_info = { NULL, // Name
4450 NULL, // Alt name
4451 0, // byte size
4452 reg_offset, // offset
4453 eEncodingUint, // encoding
Jason Molendabf67a302015-09-01 05:17:01 +00004454 eFormatHex, // format
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004455 {
Jason Molendabf67a302015-09-01 05:17:01 +00004456 LLDB_INVALID_REGNUM, // eh_frame reg num
Greg Claytond04f0ed2015-05-26 18:00:51 +00004457 LLDB_INVALID_REGNUM, // DWARF reg num
4458 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda63bd0db2015-09-15 23:20:34 +00004459 cur_reg_num, // process plugin reg num
4460 cur_reg_num // native register number
Greg Claytond04f0ed2015-05-26 18:00:51 +00004461 },
4462 NULL,
4463 NULL
4464 };
Ed Maste81b4c5f2016-01-04 01:43:47 +00004465
Jason Molenda63bd0db2015-09-15 23:20:34 +00004466 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](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004467 if (name == "name")
4468 {
4469 reg_name.SetString(value);
4470 }
4471 else if (name == "bitsize")
4472 {
4473 reg_info.byte_size = StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
4474 }
4475 else if (name == "type")
4476 {
4477 gdb_type = value.str();
4478 }
4479 else if (name == "group")
4480 {
4481 gdb_group = value.str();
4482 }
4483 else if (name == "regnum")
4484 {
4485 const uint32_t regnum = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4486 if (regnum != LLDB_INVALID_REGNUM)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004487 {
Jason Molenda63bd0db2015-09-15 23:20:34 +00004488 reg_info.kinds[eRegisterKindProcessPlugin] = regnum;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004489 }
4490 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004491 else if (name == "offset")
4492 {
4493 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4494 }
4495 else if (name == "altname")
4496 {
4497 alt_name.SetString(value);
4498 }
4499 else if (name == "encoding")
4500 {
4501 encoding_set = true;
4502 reg_info.encoding = Args::StringToEncoding (value.data(), eEncodingUint);
4503 }
4504 else if (name == "format")
4505 {
4506 format_set = true;
4507 Format format = eFormatInvalid;
4508 if (Args::StringToFormat (value.data(), format, NULL).Success())
4509 reg_info.format = format;
4510 else if (value == "vector-sint8")
4511 reg_info.format = eFormatVectorOfSInt8;
4512 else if (value == "vector-uint8")
4513 reg_info.format = eFormatVectorOfUInt8;
4514 else if (value == "vector-sint16")
4515 reg_info.format = eFormatVectorOfSInt16;
4516 else if (value == "vector-uint16")
4517 reg_info.format = eFormatVectorOfUInt16;
4518 else if (value == "vector-sint32")
4519 reg_info.format = eFormatVectorOfSInt32;
4520 else if (value == "vector-uint32")
4521 reg_info.format = eFormatVectorOfUInt32;
4522 else if (value == "vector-float32")
4523 reg_info.format = eFormatVectorOfFloat32;
4524 else if (value == "vector-uint128")
4525 reg_info.format = eFormatVectorOfUInt128;
4526 }
4527 else if (name == "group_id")
4528 {
4529 const uint32_t set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4530 RegisterSetMap::const_iterator pos = target_info.reg_set_map.find(set_id);
4531 if (pos != target_info.reg_set_map.end())
4532 set_name = pos->second.name;
4533 }
Jason Molendaa18f7072015-08-15 01:21:01 +00004534 else if (name == "gcc_regnum" || name == "ehframe_regnum")
Greg Claytond04f0ed2015-05-26 18:00:51 +00004535 {
Jason Molendaa18f7072015-08-15 01:21:01 +00004536 reg_info.kinds[eRegisterKindEHFrame] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004537 }
4538 else if (name == "dwarf_regnum")
4539 {
4540 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4541 }
4542 else if (name == "generic")
4543 {
4544 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister(value.data());
4545 }
4546 else if (name == "value_regnums")
4547 {
4548 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
4549 }
4550 else if (name == "invalidate_regnums")
4551 {
4552 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
4553 }
4554 else
4555 {
4556 printf("unhandled attribute %s = %s\n", name.data(), value.data());
4557 }
4558 return true; // Keep iterating through all attributes
4559 });
Ed Maste81b4c5f2016-01-04 01:43:47 +00004560
Greg Claytond04f0ed2015-05-26 18:00:51 +00004561 if (!gdb_type.empty() && !(encoding_set || format_set))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004562 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004563 if (gdb_type.find("int") == 0)
4564 {
4565 reg_info.format = eFormatHex;
4566 reg_info.encoding = eEncodingUint;
4567 }
4568 else if (gdb_type == "data_ptr" || gdb_type == "code_ptr")
4569 {
4570 reg_info.format = eFormatAddressInfo;
4571 reg_info.encoding = eEncodingUint;
4572 }
4573 else if (gdb_type == "i387_ext" || gdb_type == "float")
4574 {
4575 reg_info.format = eFormatFloat;
4576 reg_info.encoding = eEncodingIEEE754;
4577 }
Colin Rileyc3c95b22015-04-16 15:51:33 +00004578 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004579
Greg Claytond04f0ed2015-05-26 18:00:51 +00004580 // Only update the register set name if we didn't get a "reg_set" attribute.
4581 // "set_name" will be empty if we didn't have a "reg_set" attribute.
4582 if (!set_name && !gdb_group.empty())
4583 set_name.SetCString(gdb_group.c_str());
Ed Maste81b4c5f2016-01-04 01:43:47 +00004584
Greg Claytond04f0ed2015-05-26 18:00:51 +00004585 reg_info.byte_offset = reg_offset;
4586 assert (reg_info.byte_size != 0);
4587 reg_offset += reg_info.byte_size;
4588 if (!value_regs.empty())
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004589 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004590 value_regs.push_back(LLDB_INVALID_REGNUM);
4591 reg_info.value_regs = value_regs.data();
Colin Rileyc3c95b22015-04-16 15:51:33 +00004592 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004593 if (!invalidate_regs.empty())
4594 {
4595 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
4596 reg_info.invalidate_regs = invalidate_regs.data();
4597 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004598
Jason Molenda63bd0db2015-09-15 23:20:34 +00004599 ++cur_reg_num;
Jason Molenda21586c82015-09-09 03:36:24 +00004600 AugmentRegisterInfoViaABI (reg_info, reg_name, abi_sp);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004601 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
Ed Maste81b4c5f2016-01-04 01:43:47 +00004602
Greg Claytond04f0ed2015-05-26 18:00:51 +00004603 return true; // Keep iterating through all "reg" elements
4604 });
Colin Rileyc3c95b22015-04-16 15:51:33 +00004605 return true;
4606}
Ed Maste81b4c5f2016-01-04 01:43:47 +00004607
Eugene Zelenko0722f082015-10-24 01:28:05 +00004608} // namespace {}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004609
Colin Rileyc3c95b22015-04-16 15:51:33 +00004610
4611// query the target of gdb-remote for extended target information
4612// return: 'true' on success
4613// 'false' on failure
4614bool
Jim Ingham7b71c0b2016-02-18 23:58:45 +00004615ProcessGDBRemote::GetGDBServerRegisterInfo (ArchSpec &arch_to_use)
Colin Rileyc3c95b22015-04-16 15:51:33 +00004616{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004617 // Make sure LLDB has an XML parser it can use first
4618 if (!XMLDocument::XMLEnabled())
4619 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004620
4621 // redirect libxml2's error handler since the default prints to stdout
Colin Rileyc3c95b22015-04-16 15:51:33 +00004622
4623 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004624
4625 // check that we have extended feature read support
4626 if ( !comm.GetQXferFeaturesReadSupported( ) )
4627 return false;
4628
4629 // request the target xml file
4630 std::string raw;
4631 lldb_private::Error lldberr;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004632 if (!comm.ReadExtFeature(ConstString("features"),
4633 ConstString("target.xml"),
4634 raw,
4635 lldberr))
4636 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00004637 return false;
4638 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004639
Colin Rileyc3c95b22015-04-16 15:51:33 +00004640
Greg Claytond04f0ed2015-05-26 18:00:51 +00004641 XMLDocument xml_document;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004642
Greg Claytond04f0ed2015-05-26 18:00:51 +00004643 if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml"))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004644 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004645 GdbServerTargetInfo target_info;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004646
Greg Claytond04f0ed2015-05-26 18:00:51 +00004647 XMLNode target_node = xml_document.GetRootElement("target");
4648 if (target_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004649 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004650 XMLNode feature_node;
4651 target_node.ForEachChildElement([&target_info, this, &feature_node](const XMLNode &node) -> bool
4652 {
4653 llvm::StringRef name = node.GetName();
4654 if (name == "architecture")
4655 {
4656 node.GetElementText(target_info.arch);
4657 }
4658 else if (name == "osabi")
4659 {
4660 node.GetElementText(target_info.osabi);
4661 }
Ewan Crawford682e8422015-06-26 09:38:27 +00004662 else if (name == "xi:include" || name == "include")
Greg Claytond04f0ed2015-05-26 18:00:51 +00004663 {
4664 llvm::StringRef href = node.GetAttributeValue("href");
4665 if (!href.empty())
4666 target_info.includes.push_back(href.str());
4667 }
4668 else if (name == "feature")
4669 {
4670 feature_node = node;
4671 }
4672 else if (name == "groups")
4673 {
4674 node.ForEachChildElementWithName("group", [&target_info](const XMLNode &node) -> bool {
4675 uint32_t set_id = UINT32_MAX;
4676 RegisterSetInfo set_info;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004677
Greg Claytond04f0ed2015-05-26 18:00:51 +00004678 node.ForEachAttribute([&set_id, &set_info](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
4679 if (name == "id")
4680 set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4681 if (name == "name")
4682 set_info.name = ConstString(value);
4683 return true; // Keep iterating through all attributes
4684 });
Ed Maste81b4c5f2016-01-04 01:43:47 +00004685
Greg Claytond04f0ed2015-05-26 18:00:51 +00004686 if (set_id != UINT32_MAX)
4687 target_info.reg_set_map[set_id] = set_info;
4688 return true; // Keep iterating through all "group" elements
4689 });
4690 }
4691 return true; // Keep iterating through all children of the target_node
4692 });
Ed Maste81b4c5f2016-01-04 01:43:47 +00004693
Francis Ricci55954ae2016-04-25 21:03:55 +00004694 // Initialize these outside of ParseRegisters, since they should not be reset inside each include feature
4695 uint32_t cur_reg_num = 0;
4696 uint32_t reg_offset = 0;
4697
Jim Ingham7b71c0b2016-02-18 23:58:45 +00004698 // Don't use Process::GetABI, this code gets called from DidAttach, and in that context we haven't
4699 // set the Target's architecture yet, so the ABI is also potentially incorrect.
4700 ABISP abi_to_use_sp = ABI::FindPlugin(arch_to_use);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004701 if (feature_node)
4702 {
Francis Ricci55954ae2016-04-25 21:03:55 +00004703 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 +00004704 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004705
Greg Claytond04f0ed2015-05-26 18:00:51 +00004706 for (const auto &include : target_info.includes)
4707 {
4708 // request register file
4709 std::string xml_data;
4710 if (!comm.ReadExtFeature(ConstString("features"),
4711 ConstString(include),
4712 xml_data,
4713 lldberr))
4714 continue;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004715
Greg Claytond04f0ed2015-05-26 18:00:51 +00004716 XMLDocument include_xml_document;
4717 include_xml_document.ParseMemory(xml_data.data(), xml_data.size(), include.c_str());
4718 XMLNode include_feature_node = include_xml_document.GetRootElement("feature");
4719 if (include_feature_node)
4720 {
Francis Ricci55954ae2016-04-25 21:03:55 +00004721 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 +00004722 }
4723 }
Jim Ingham7b71c0b2016-02-18 23:58:45 +00004724 this->m_register_info.Finalize(arch_to_use);
Colin Rileyc3c95b22015-04-16 15:51:33 +00004725 }
4726 }
4727
Greg Claytond04f0ed2015-05-26 18:00:51 +00004728 return m_register_info.GetNumRegisters() > 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004729}
4730
Aidan Doddsc0c83852015-05-08 09:36:31 +00004731Error
Stephane Sezer87b0fe02016-01-12 19:02:41 +00004732ProcessGDBRemote::GetLoadedModuleList (LoadedModuleInfoList & list)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004733{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004734 // Make sure LLDB has an XML parser it can use first
4735 if (!XMLDocument::XMLEnabled())
4736 return Error (0, ErrorType::eErrorTypeGeneric);
4737
Aidan Doddsc0c83852015-05-08 09:36:31 +00004738 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS);
4739 if (log)
4740 log->Printf ("ProcessGDBRemote::%s", __FUNCTION__);
4741
Aidan Doddsc0c83852015-05-08 09:36:31 +00004742 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004743
4744 // check that we have extended feature read support
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004745 if (comm.GetQXferLibrariesSVR4ReadSupported ()) {
4746 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004747
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004748 // request the loaded library list
4749 std::string raw;
4750 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004751
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004752 if (!comm.ReadExtFeature (ConstString ("libraries-svr4"), ConstString (""), raw, lldberr))
4753 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004754
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004755 // parse the xml file in memory
4756 if (log)
4757 log->Printf ("parsing: %s", raw.c_str());
4758 XMLDocument doc;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004759
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004760 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4761 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004762
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004763 XMLNode root_element = doc.GetRootElement("library-list-svr4");
4764 if (!root_element)
4765 return Error();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004766
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004767 // main link map structure
4768 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4769 if (!main_lm.empty())
4770 {
4771 list.m_link_map = StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
4772 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004773
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004774 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
Aidan Doddsc0c83852015-05-08 09:36:31 +00004775
Stephane Sezer87b0fe02016-01-12 19:02:41 +00004776 LoadedModuleInfoList::LoadedModuleInfo module;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004777
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004778 library.ForEachAttribute([log, &module](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
Ed Maste81b4c5f2016-01-04 01:43:47 +00004779
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004780 if (name == "name")
4781 module.set_name (value.str());
4782 else if (name == "lm")
4783 {
4784 // the address of the link_map struct.
4785 module.set_link_map(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4786 }
4787 else if (name == "l_addr")
4788 {
4789 // the displacement as read from the field 'l_addr' of the link_map struct.
4790 module.set_base(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
Stephane Sezerc6845a02015-08-20 22:07:48 +00004791 // base address is always a displacement, not an absolute value.
4792 module.set_base_is_offset(true);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004793 }
4794 else if (name == "l_ld")
4795 {
4796 // the memory address of the libraries PT_DYAMIC section.
4797 module.set_dynamic(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4798 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004799
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004800 return true; // Keep iterating over all properties of "library"
4801 });
4802
4803 if (log)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004804 {
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004805 std::string name;
4806 lldb::addr_t lm=0, base=0, ld=0;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004807 bool base_is_offset;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004808
4809 module.get_name (name);
4810 module.get_link_map (lm);
4811 module.get_base (base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004812 module.get_base_is_offset (base_is_offset);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004813 module.get_dynamic (ld);
4814
Stephane Sezerc6845a02015-08-20 22:07:48 +00004815 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 +00004816 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004817
4818 list.add (module);
4819 return true; // Keep iterating over all "library" elements in the root node
Greg Claytond04f0ed2015-05-26 18:00:51 +00004820 });
Aidan Doddsc0c83852015-05-08 09:36:31 +00004821
4822 if (log)
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004823 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4824 } else if (comm.GetQXferLibrariesReadSupported ()) {
4825 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004826
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004827 // request the loaded library list
4828 std::string raw;
4829 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004830
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004831 if (!comm.ReadExtFeature (ConstString ("libraries"), ConstString (""), raw, lldberr))
4832 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004833
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004834 if (log)
4835 log->Printf ("parsing: %s", raw.c_str());
4836 XMLDocument doc;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004837
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004838 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4839 return Error (0, ErrorType::eErrorTypeGeneric);
4840
4841 XMLNode root_element = doc.GetRootElement("library-list");
4842 if (!root_element)
4843 return Error();
4844
4845 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
Stephane Sezer87b0fe02016-01-12 19:02:41 +00004846 LoadedModuleInfoList::LoadedModuleInfo module;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004847
4848 llvm::StringRef name = library.GetAttributeValue("name");
4849 module.set_name(name.str());
4850
4851 // The base address of a given library will be the address of its
4852 // first section. Most remotes send only one section for Windows
4853 // targets for example.
4854 const XMLNode &section = library.FindFirstChildElementWithName("section");
4855 llvm::StringRef address = section.GetAttributeValue("address");
4856 module.set_base(StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0));
Stephane Sezerc6845a02015-08-20 22:07:48 +00004857 // These addresses are absolute values.
4858 module.set_base_is_offset(false);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004859
4860 if (log)
4861 {
4862 std::string name;
4863 lldb::addr_t base = 0;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004864 bool base_is_offset;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004865 module.get_name (name);
4866 module.get_base (base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004867 module.get_base_is_offset (base_is_offset);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004868
Stephane Sezerc6845a02015-08-20 22:07:48 +00004869 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 +00004870 }
4871
4872 list.add (module);
4873 return true; // Keep iterating over all "library" elements in the root node
4874 });
4875
4876 if (log)
4877 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4878 } else {
4879 return Error (0, ErrorType::eErrorTypeGeneric);
4880 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004881
4882 return Error();
4883}
4884
Aidan Doddsc0c83852015-05-08 09:36:31 +00004885lldb::ModuleSP
Stephane Sezer3553c0e2016-04-05 17:25:32 +00004886ProcessGDBRemote::LoadModuleAtAddress (const FileSpec &file, lldb::addr_t link_map,
4887 lldb::addr_t base_addr, bool value_is_offset)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004888{
Stephane Sezer3553c0e2016-04-05 17:25:32 +00004889 DynamicLoader *loader = GetDynamicLoader();
4890 if (!loader)
4891 return nullptr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004892
Stephane Sezer3553c0e2016-04-05 17:25:32 +00004893 return loader->LoadModuleAtAddress(file, link_map, base_addr, value_is_offset);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004894}
4895
4896size_t
Stephane Sezer87b0fe02016-01-12 19:02:41 +00004897ProcessGDBRemote::LoadModules (LoadedModuleInfoList &module_list)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004898{
4899 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4900
4901 // request a list of loaded libraries from GDBServer
Aidan Doddsc0c83852015-05-08 09:36:31 +00004902 if (GetLoadedModuleList (module_list).Fail())
4903 return 0;
4904
4905 // get a list of all the modules
4906 ModuleList new_modules;
4907
Stephane Sezer87b0fe02016-01-12 19:02:41 +00004908 for (LoadedModuleInfoList::LoadedModuleInfo & modInfo : module_list.m_list)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004909 {
4910 std::string mod_name;
4911 lldb::addr_t mod_base;
Stephane Sezer3553c0e2016-04-05 17:25:32 +00004912 lldb::addr_t link_map;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004913 bool mod_base_is_offset;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004914
4915 bool valid = true;
4916 valid &= modInfo.get_name (mod_name);
4917 valid &= modInfo.get_base (mod_base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004918 valid &= modInfo.get_base_is_offset (mod_base_is_offset);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004919 if (!valid)
4920 continue;
4921
Stephane Sezer3553c0e2016-04-05 17:25:32 +00004922 if (!modInfo.get_link_map (link_map))
4923 link_map = LLDB_INVALID_ADDRESS;
4924
Francis Riccia0300612016-04-27 17:10:15 +00004925 FileSpec file (mod_name.c_str(), true);
Stephane Sezer3553c0e2016-04-05 17:25:32 +00004926 lldb::ModuleSP module_sp = LoadModuleAtAddress (file, link_map, mod_base,
4927 mod_base_is_offset);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004928
4929 if (module_sp.get())
4930 new_modules.Append (module_sp);
4931 }
4932
4933 if (new_modules.GetSize() > 0)
4934 {
Francis Riccibe8cab72016-04-25 21:02:24 +00004935 ModuleList removed_modules;
Zachary Turner7529df92015-09-01 20:02:29 +00004936 Target &target = GetTarget();
Francis Riccibe8cab72016-04-25 21:02:24 +00004937 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4938
4939 for (size_t i = 0; i < loaded_modules.GetSize(); ++i)
4940 {
4941 const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i);
4942
4943 bool found = false;
4944 for (size_t j = 0; j < new_modules.GetSize(); ++j)
4945 {
4946 if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get())
4947 found = true;
4948 }
4949
Francis Ricci80dbd152016-06-06 15:00:50 +00004950 // The main executable will never be included in libraries-svr4, don't remove it
4951 if (!found && loaded_module.get() != target.GetExecutableModulePointer())
Francis Riccibe8cab72016-04-25 21:02:24 +00004952 {
Francis Ricci80dbd152016-06-06 15:00:50 +00004953 removed_modules.Append (loaded_module);
Francis Riccibe8cab72016-04-25 21:02:24 +00004954 }
4955 }
4956
4957 loaded_modules.Remove (removed_modules);
4958 m_process->GetTarget().ModulesDidUnload (removed_modules, false);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004959
4960 new_modules.ForEach ([&target](const lldb::ModuleSP module_sp) -> bool
4961 {
4962 lldb_private::ObjectFile * obj = module_sp->GetObjectFile ();
4963 if (!obj)
4964 return true;
4965
4966 if (obj->GetType () != ObjectFile::Type::eTypeExecutable)
4967 return true;
4968
4969 lldb::ModuleSP module_copy_sp = module_sp;
4970 target.SetExecutableModule (module_copy_sp, false);
4971 return false;
4972 });
4973
Aidan Doddsc0c83852015-05-08 09:36:31 +00004974 loaded_modules.AppendIfNeeded (new_modules);
4975 m_process->GetTarget().ModulesDidLoad (new_modules);
4976 }
4977
4978 return new_modules.GetSize();
Stephane Sezer87b0fe02016-01-12 19:02:41 +00004979}
4980
4981size_t
4982ProcessGDBRemote::LoadModules ()
4983{
4984 LoadedModuleInfoList module_list;
4985 return LoadModules (module_list);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004986}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004987
Tamas Berghammer783bfc82015-06-18 20:43:56 +00004988Error
4989ProcessGDBRemote::GetFileLoadAddress(const FileSpec& file, bool& is_loaded, lldb::addr_t& load_addr)
4990{
4991 is_loaded = false;
4992 load_addr = LLDB_INVALID_ADDRESS;
4993
4994 std::string file_path = file.GetPath(false);
4995 if (file_path.empty ())
4996 return Error("Empty file name specified");
4997
4998 StreamString packet;
4999 packet.PutCString("qFileLoadAddress:");
5000 packet.PutCStringAsRawHex8(file_path.c_str());
5001
5002 StringExtractorGDBRemote response;
5003 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString().c_str(), response, false) != GDBRemoteCommunication::PacketResult::Success)
5004 return Error("Sending qFileLoadAddress packet failed");
5005
5006 if (response.IsErrorResponse())
5007 {
5008 if (response.GetError() == 1)
5009 {
5010 // The file is not loaded into the inferior
5011 is_loaded = false;
5012 load_addr = LLDB_INVALID_ADDRESS;
5013 return Error();
5014 }
5015
5016 return Error("Fetching file load address from remote server returned an error");
5017 }
5018
5019 if (response.IsNormalResponse())
5020 {
5021 is_loaded = true;
5022 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
5023 return Error();
5024 }
5025
5026 return Error("Unknown error happened during sending the load address packet");
5027}
5028
Eugene Zelenko0722f082015-10-24 01:28:05 +00005029
Greg Clayton0b90be12015-06-23 21:27:50 +00005030void
5031ProcessGDBRemote::ModulesDidLoad (ModuleList &module_list)
5032{
5033 // We must call the lldb_private::Process::ModulesDidLoad () first before we do anything
5034 Process::ModulesDidLoad (module_list);
5035
5036 // After loading shared libraries, we can ask our remote GDB server if
5037 // it needs any symbols.
5038 m_gdb_comm.ServeSymbolLookups(this);
5039}
5040
Eugene Zelenko0722f082015-10-24 01:28:05 +00005041
Greg Claytone034a042015-05-21 20:52:06 +00005042class CommandObjectProcessGDBRemoteSpeedTest: public CommandObjectParsed
5043{
5044public:
5045 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter) :
5046 CommandObjectParsed (interpreter,
5047 "process plugin packet speed-test",
5048 "Tests packet speeds of various sizes to determine the performance characteristics of the GDB remote connection. ",
5049 NULL),
5050 m_option_group (interpreter),
5051 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),
5052 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),
5053 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),
5054 m_json (LLDB_OPT_SET_1, false, "json", 'j', "Print the output as JSON data for easy parsing.", false, true)
5055 {
5056 m_option_group.Append (&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5057 m_option_group.Append (&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5058 m_option_group.Append (&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5059 m_option_group.Append (&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5060 m_option_group.Finalize();
5061 }
5062
Eugene Zelenko0722f082015-10-24 01:28:05 +00005063 ~CommandObjectProcessGDBRemoteSpeedTest ()
5064 {
5065 }
5066
Greg Claytone034a042015-05-21 20:52:06 +00005067
5068 Options *
5069 GetOptions () override
5070 {
5071 return &m_option_group;
5072 }
5073
5074 bool
5075 DoExecute (Args& command, CommandReturnObject &result) override
5076 {
5077 const size_t argc = command.GetArgumentCount();
5078 if (argc == 0)
5079 {
5080 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5081 if (process)
5082 {
5083 StreamSP output_stream_sp (m_interpreter.GetDebugger().GetAsyncOutputStream());
5084 result.SetImmediateOutputStream (output_stream_sp);
5085
5086 const uint32_t num_packets = (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
5087 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
5088 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
5089 const bool json = m_json.GetOptionValue().GetCurrentValue();
5090 if (output_stream_sp)
5091 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, *output_stream_sp);
5092 else
5093 {
5094 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, result.GetOutputStream());
5095 }
5096 result.SetStatus (eReturnStatusSuccessFinishResult);
5097 return true;
5098 }
5099 }
5100 else
5101 {
5102 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
5103 }
5104 result.SetStatus (eReturnStatusFailed);
5105 return false;
5106 }
5107protected:
5108 OptionGroupOptions m_option_group;
5109 OptionGroupUInt64 m_num_packets;
5110 OptionGroupUInt64 m_max_send;
5111 OptionGroupUInt64 m_max_recv;
5112 OptionGroupBoolean m_json;
Eugene Zelenko0722f082015-10-24 01:28:05 +00005113
Greg Claytone034a042015-05-21 20:52:06 +00005114};
5115
Greg Clayton02686b82012-10-15 22:42:16 +00005116class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00005117{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005118private:
Ed Maste81b4c5f2016-01-04 01:43:47 +00005119
Greg Clayton998255b2012-10-13 02:07:45 +00005120public:
Greg Clayton02686b82012-10-15 22:42:16 +00005121 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00005122 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00005123 "process plugin packet history",
5124 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00005125 NULL)
5126 {
5127 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005128
Eugene Zelenko0722f082015-10-24 01:28:05 +00005129 ~CommandObjectProcessGDBRemotePacketHistory ()
5130 {
5131 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005132
Greg Clayton998255b2012-10-13 02:07:45 +00005133 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005134 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton998255b2012-10-13 02:07:45 +00005135 {
Greg Clayton02686b82012-10-15 22:42:16 +00005136 const size_t argc = command.GetArgumentCount();
5137 if (argc == 0)
5138 {
5139 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5140 if (process)
5141 {
5142 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
5143 result.SetStatus (eReturnStatusSuccessFinishResult);
5144 return true;
5145 }
5146 }
5147 else
5148 {
5149 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
5150 }
5151 result.SetStatus (eReturnStatusFailed);
5152 return false;
5153 }
5154};
5155
Jason Molenda6076bf42014-05-06 04:34:52 +00005156class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed
5157{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005158private:
Ed Maste81b4c5f2016-01-04 01:43:47 +00005159
Jason Molenda6076bf42014-05-06 04:34:52 +00005160public:
5161 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) :
5162 CommandObjectParsed (interpreter,
5163 "process plugin packet xfer-size",
5164 "Maximum size that lldb will try to read/write one one chunk.",
5165 NULL)
5166 {
5167 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005168
Eugene Zelenko0722f082015-10-24 01:28:05 +00005169 ~CommandObjectProcessGDBRemotePacketXferSize ()
5170 {
5171 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005172
Jason Molenda6076bf42014-05-06 04:34:52 +00005173 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005174 DoExecute (Args& command, CommandReturnObject &result) override
Jason Molenda6076bf42014-05-06 04:34:52 +00005175 {
5176 const size_t argc = command.GetArgumentCount();
5177 if (argc == 0)
5178 {
5179 result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str());
5180 result.SetStatus (eReturnStatusFailed);
5181 return false;
5182 }
5183
5184 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5185 if (process)
5186 {
5187 const char *packet_size = command.GetArgumentAtIndex(0);
5188 errno = 0;
5189 uint64_t user_specified_max = strtoul (packet_size, NULL, 10);
5190 if (errno == 0 && user_specified_max != 0)
5191 {
5192 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max);
5193 result.SetStatus (eReturnStatusSuccessFinishResult);
5194 return true;
5195 }
5196 }
5197 result.SetStatus (eReturnStatusFailed);
5198 return false;
5199 }
5200};
5201
Eugene Zelenko0722f082015-10-24 01:28:05 +00005202
Greg Clayton02686b82012-10-15 22:42:16 +00005203class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
5204{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005205private:
Ed Maste81b4c5f2016-01-04 01:43:47 +00005206
Greg Clayton02686b82012-10-15 22:42:16 +00005207public:
5208 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
5209 CommandObjectParsed (interpreter,
5210 "process plugin packet send",
5211 "Send a custom packet through the GDB remote protocol and print the answer. "
5212 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
5213 NULL)
5214 {
5215 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005216
Eugene Zelenko0722f082015-10-24 01:28:05 +00005217 ~CommandObjectProcessGDBRemotePacketSend ()
5218 {
5219 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005220
Greg Clayton02686b82012-10-15 22:42:16 +00005221 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005222 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton02686b82012-10-15 22:42:16 +00005223 {
5224 const size_t argc = command.GetArgumentCount();
5225 if (argc == 0)
5226 {
5227 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
5228 result.SetStatus (eReturnStatusFailed);
5229 return false;
5230 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005231
Greg Clayton02686b82012-10-15 22:42:16 +00005232 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5233 if (process)
5234 {
Han Ming Ong84145852012-11-26 20:42:03 +00005235 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00005236 {
Han Ming Ong84145852012-11-26 20:42:03 +00005237 const char *packet_cstr = command.GetArgumentAtIndex(0);
5238 bool send_async = true;
5239 StringExtractorGDBRemote response;
5240 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
5241 result.SetStatus (eReturnStatusSuccessFinishResult);
5242 Stream &output_strm = result.GetOutputStream();
5243 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00005244 std::string &response_str = response.GetStringRef();
Ed Maste81b4c5f2016-01-04 01:43:47 +00005245
Han Ming Ong399289e2013-06-21 19:56:59 +00005246 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00005247 {
Pavel Labath4cb69922016-07-29 15:41:52 +00005248 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00005249 }
5250
Han Ming Ong84145852012-11-26 20:42:03 +00005251 if (response_str.empty())
5252 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
5253 else
5254 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00005255 }
Greg Clayton02686b82012-10-15 22:42:16 +00005256 }
Greg Clayton998255b2012-10-13 02:07:45 +00005257 return true;
5258 }
5259};
5260
Greg Claytonba4a0a52013-02-01 23:03:47 +00005261class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
5262{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005263private:
Ed Maste81b4c5f2016-01-04 01:43:47 +00005264
Greg Claytonba4a0a52013-02-01 23:03:47 +00005265public:
5266 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
5267 CommandObjectRaw (interpreter,
5268 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00005269 "Send a qRcmd packet through the GDB remote protocol and print the response."
5270 "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 +00005271 NULL)
5272 {
5273 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005274
Eugene Zelenko0722f082015-10-24 01:28:05 +00005275 ~CommandObjectProcessGDBRemotePacketMonitor ()
5276 {
5277 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005278
Greg Claytonba4a0a52013-02-01 23:03:47 +00005279 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005280 DoExecute (const char *command, CommandReturnObject &result) override
Greg Claytonba4a0a52013-02-01 23:03:47 +00005281 {
5282 if (command == NULL || command[0] == '\0')
5283 {
5284 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
5285 result.SetStatus (eReturnStatusFailed);
5286 return false;
5287 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005288
Greg Claytonba4a0a52013-02-01 23:03:47 +00005289 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5290 if (process)
5291 {
5292 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00005293 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00005294 packet.PutBytesAsRawHex8(command, strlen(command));
5295 const char *packet_cstr = packet.GetString().c_str();
Ed Maste81b4c5f2016-01-04 01:43:47 +00005296
Greg Claytonba4a0a52013-02-01 23:03:47 +00005297 bool send_async = true;
5298 StringExtractorGDBRemote response;
5299 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
5300 result.SetStatus (eReturnStatusSuccessFinishResult);
5301 Stream &output_strm = result.GetOutputStream();
5302 output_strm.Printf (" packet: %s\n", packet_cstr);
5303 const std::string &response_str = response.GetStringRef();
Ed Maste81b4c5f2016-01-04 01:43:47 +00005304
Greg Claytonba4a0a52013-02-01 23:03:47 +00005305 if (response_str.empty())
5306 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
5307 else
5308 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
5309 }
5310 return true;
5311 }
5312};
5313
Greg Clayton02686b82012-10-15 22:42:16 +00005314class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
5315{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005316private:
Ed Maste81b4c5f2016-01-04 01:43:47 +00005317
Greg Clayton02686b82012-10-15 22:42:16 +00005318public:
5319 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
5320 CommandObjectMultiword (interpreter,
5321 "process plugin packet",
5322 "Commands that deal with GDB remote packets.",
5323 NULL)
5324 {
5325 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
5326 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00005327 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Jason Molenda6076bf42014-05-06 04:34:52 +00005328 LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter)));
Greg Claytone034a042015-05-21 20:52:06 +00005329 LoadSubCommand ("speed-test", CommandObjectSP (new CommandObjectProcessGDBRemoteSpeedTest (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00005330 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005331
Eugene Zelenko0722f082015-10-24 01:28:05 +00005332 ~CommandObjectProcessGDBRemotePacket ()
5333 {
Ed Maste81b4c5f2016-01-04 01:43:47 +00005334 }
Greg Clayton02686b82012-10-15 22:42:16 +00005335};
Greg Clayton998255b2012-10-13 02:07:45 +00005336
5337class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
5338{
5339public:
Kate Stone7428a182016-07-14 22:03:10 +00005340 CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter)
5341 : CommandObjectMultiword(interpreter, "process plugin", "Commands for operating on a ProcessGDBRemote process.",
5342 "process plugin <subcommand> [<subcommand-options>]")
Greg Clayton998255b2012-10-13 02:07:45 +00005343 {
5344 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
5345 }
5346
Eugene Zelenko0722f082015-10-24 01:28:05 +00005347 ~CommandObjectMultiwordProcessGDBRemote ()
5348 {
5349 }
Greg Clayton998255b2012-10-13 02:07:45 +00005350};
5351
Greg Clayton998255b2012-10-13 02:07:45 +00005352CommandObject *
5353ProcessGDBRemote::GetPluginCommandObject()
5354{
5355 if (!m_command_sp)
5356 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
5357 return m_command_sp.get();
5358}