blob: eb82dc1eba38a9244a53a0dc3f443cdc5c6c297c [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
Greg Claytonc6c420f2016-08-12 16:46:18 +000019#include <sys/socket.h>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include <sys/stat.h>
Greg Clayton2a48f522011-05-14 01:50:35 +000021#include <sys/types.h>
Stephen Wilsondc916862011-03-30 00:12:40 +000022#include <time.h>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000023
24// C++ Includes
25#include <algorithm>
26#include <map>
Benjamin Kramer3f69fa62015-04-03 10:55:00 +000027#include <mutex>
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000028#include <sstream>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000029
Johnny Chen01a67862011-10-14 00:42:25 +000030#include "lldb/Breakpoint/Watchpoint.h"
Jim Ingham40af72e2010-06-15 19:49:27 +000031#include "lldb/Interpreter/Args.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000032#include "lldb/Core/ArchSpec.h"
33#include "lldb/Core/Debugger.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000034#include "lldb/Host/ConnectionFileDescriptor.h"
Greg Clayton53239f02011-02-08 05:05:52 +000035#include "lldb/Host/FileSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000036#include "lldb/Core/Module.h"
Greg Clayton1f746072012-08-29 21:13:06 +000037#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000038#include "lldb/Core/PluginManager.h"
39#include "lldb/Core/State.h"
Greg Claytond451c1a2012-04-13 21:24:18 +000040#include "lldb/Core/StreamFile.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000041#include "lldb/Core/StreamString.h"
42#include "lldb/Core/Timer.h"
Greg Clayton70b57652011-05-15 01:25:55 +000043#include "lldb/Core/Value.h"
Greg Claytond04f0ed2015-05-26 18:00:51 +000044#include "lldb/DataFormatters/FormatManager.h"
Zachary Turner4eff2d32015-10-14 21:37:36 +000045#include "lldb/Host/FileSystem.h"
Zachary Turner39de3112014-09-09 20:54:56 +000046#include "lldb/Host/HostThread.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000047#include "lldb/Host/StringConvert.h"
Jason Molendad1fae142012-09-29 08:03:33 +000048#include "lldb/Host/Symbols.h"
Zachary Turner39de3112014-09-09 20:54:56 +000049#include "lldb/Host/ThreadLauncher.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000050#include "lldb/Host/TimeValue.h"
Greg Claytond04f0ed2015-05-26 18:00:51 +000051#include "lldb/Host/XML.h"
Greg Clayton02686b82012-10-15 22:42:16 +000052#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton1d19a2f2012-10-19 22:22:57 +000053#include "lldb/Interpreter/CommandObject.h"
54#include "lldb/Interpreter/CommandObjectMultiword.h"
Greg Clayton02686b82012-10-15 22:42:16 +000055#include "lldb/Interpreter/CommandReturnObject.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000056#include "lldb/Interpreter/OptionValueProperties.h"
Greg Claytone034a042015-05-21 20:52:06 +000057#include "lldb/Interpreter/Options.h"
58#include "lldb/Interpreter/OptionGroupBoolean.h"
59#include "lldb/Interpreter/OptionGroupUInt64.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000060#include "lldb/Interpreter/Property.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000061#include "lldb/Symbol/ObjectFile.h"
Jason Molenda21586c82015-09-09 03:36:24 +000062#include "lldb/Target/ABI.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000063#include "lldb/Target/DynamicLoader.h"
64#include "lldb/Target/Target.h"
65#include "lldb/Target/TargetList.h"
Greg Clayton2a48f522011-05-14 01:50:35 +000066#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molenda705b1802014-06-13 02:37:02 +000067#include "lldb/Target/SystemRuntime.h"
Greg Claytonc6c420f2016-08-12 16:46:18 +000068#include "lldb/Utility/CleanUp.h"
Jason Molendaa34a0c62010-06-09 21:28:42 +000069#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000070
Eugene Zelenko0722f082015-10-24 01:28:05 +000071// Project includes
Chris Lattner30fdc8d2010-06-08 16:52:24 +000072#include "lldb/Host/Host.h"
Chaoren Lin98d0a4b2015-07-14 01:09:28 +000073#include "Plugins/Process/Utility/GDBRemoteSignals.h"
Peter Collingbourne99f9aa02011-06-03 20:40:38 +000074#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Jason Molendac42d2432012-07-25 03:40:06 +000075#include "Plugins/Process/Utility/StopInfoMachException.h"
Jim Ingham43c555d2012-07-04 00:35:43 +000076#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
Greg Claytonc982c762010-07-09 20:39:50 +000077#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000078#include "GDBRemoteRegisterContext.h"
79#include "ProcessGDBRemote.h"
80#include "ProcessGDBRemoteLog.h"
81#include "ThreadGDBRemote.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000082
Tamas Berghammerdb264a62015-03-31 09:52:22 +000083#define DEBUGSERVER_BASENAME "debugserver"
84using namespace lldb;
85using namespace lldb_private;
86using namespace lldb_private::process_gdb_remote;
Jason Molenda5e8534e2012-10-03 01:29:34 +000087
Greg Claytonc1422c12012-04-09 22:46:21 +000088namespace lldb
89{
90 // Provide a function that can easily dump the packet history if we know a
91 // ProcessGDBRemote * value (which we can get from logs or from debugging).
92 // We need the function in the lldb namespace so it makes it into the final
93 // executable since the LLDB shared library only exports stuff in the lldb
94 // namespace. This allows you to attach with a debugger and call this
95 // function and get the packet history dumped to a file.
96 void
97 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
98 {
Tamas Berghammerdb264a62015-03-31 09:52:22 +000099 StreamFile strm;
100 Error error (strm.GetFile().Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate));
Greg Claytond451c1a2012-04-13 21:24:18 +0000101 if (error.Success())
102 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
Greg Claytonc1422c12012-04-09 22:46:21 +0000103 }
Eugene Zelenko0722f082015-10-24 01:28:05 +0000104}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000105
Greg Clayton7f982402013-07-15 22:54:20 +0000106namespace {
Steve Pucci5ec012d2014-01-16 22:18:14 +0000107
Greg Clayton7f982402013-07-15 22:54:20 +0000108 static PropertyDefinition
109 g_properties[] =
110 {
111 { "packet-timeout" , OptionValue::eTypeUInt64 , true , 1, NULL, NULL, "Specify the default packet timeout in seconds." },
Greg Claytonef8180a2013-10-15 00:14:28 +0000112 { "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 +0000113 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
114 };
Ed Maste81b4c5f2016-01-04 01:43:47 +0000115
Greg Clayton7f982402013-07-15 22:54:20 +0000116 enum
117 {
Greg Claytonef8180a2013-10-15 00:14:28 +0000118 ePropertyPacketTimeout,
119 ePropertyTargetDefinitionFile
Greg Clayton7f982402013-07-15 22:54:20 +0000120 };
Ed Maste81b4c5f2016-01-04 01:43:47 +0000121
Greg Clayton7f982402013-07-15 22:54:20 +0000122 class PluginProperties : public Properties
123 {
124 public:
Ed Maste81b4c5f2016-01-04 01:43:47 +0000125
Greg Clayton7f982402013-07-15 22:54:20 +0000126 static ConstString
127 GetSettingName ()
128 {
129 return ProcessGDBRemote::GetPluginNameStatic();
130 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000131
Greg Clayton7f982402013-07-15 22:54:20 +0000132 PluginProperties() :
133 Properties ()
134 {
135 m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
136 m_collection_sp->Initialize(g_properties);
137 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000138
Eugene Zelenko0722f082015-10-24 01:28:05 +0000139 virtual
140 ~PluginProperties()
141 {
142 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000143
Greg Clayton7f982402013-07-15 22:54:20 +0000144 uint64_t
145 GetPacketTimeout()
146 {
147 const uint32_t idx = ePropertyPacketTimeout;
148 return m_collection_sp->GetPropertyAtIndexAsUInt64(NULL, idx, g_properties[idx].default_uint_value);
149 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000150
151 bool
152 SetPacketTimeout(uint64_t timeout)
153 {
154 const uint32_t idx = ePropertyPacketTimeout;
155 return m_collection_sp->SetPropertyAtIndexAsUInt64(NULL, idx, timeout);
156 }
157
Greg Claytonef8180a2013-10-15 00:14:28 +0000158 FileSpec
159 GetTargetDefinitionFile () const
160 {
161 const uint32_t idx = ePropertyTargetDefinitionFile;
162 return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
163 }
Greg Clayton7f982402013-07-15 22:54:20 +0000164 };
Ed Maste81b4c5f2016-01-04 01:43:47 +0000165
Greg Clayton7f982402013-07-15 22:54:20 +0000166 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
Ed Maste81b4c5f2016-01-04 01:43:47 +0000167
Greg Clayton7f982402013-07-15 22:54:20 +0000168 static const ProcessKDPPropertiesSP &
169 GetGlobalPluginProperties()
170 {
171 static ProcessKDPPropertiesSP g_settings_sp;
172 if (!g_settings_sp)
173 g_settings_sp.reset (new PluginProperties ());
174 return g_settings_sp;
175 }
Ed Maste81b4c5f2016-01-04 01:43:47 +0000176
Eugene Zelenko0722f082015-10-24 01:28:05 +0000177} // anonymous namespace end
Greg Clayton7f982402013-07-15 22:54:20 +0000178
Greg Claytonfda4fab2014-01-10 22:24:11 +0000179// TODO Randomly assigning a port is unsafe. We should get an unused
180// ephemeral port from the kernel and make sure we reserve it before passing
181// it to debugserver.
182
183#if defined (__APPLE__)
184#define LOW_PORT (IPPORT_RESERVED)
185#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
186#else
187#define LOW_PORT (1024u)
188#define HIGH_PORT (49151u)
189#endif
190
Todd Fiala013434e2014-07-09 01:29:05 +0000191#if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000192static bool rand_initialized = false;
193
Greg Claytonfda4fab2014-01-10 22:24:11 +0000194static inline uint16_t
195get_random_port ()
196{
197 if (!rand_initialized)
198 {
199 time_t seed = time(NULL);
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000200
Greg Claytonfda4fab2014-01-10 22:24:11 +0000201 rand_initialized = true;
202 srand(seed);
203 }
204 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
205}
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000206#endif
Greg Claytonfda4fab2014-01-10 22:24:11 +0000207
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000208ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000209ProcessGDBRemote::GetPluginNameStatic()
210{
Greg Clayton57abc5d2013-05-10 21:47:16 +0000211 static ConstString g_name("gdb-remote");
212 return g_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000213}
214
215const char *
216ProcessGDBRemote::GetPluginDescriptionStatic()
217{
218 return "GDB Remote protocol based debugging plug-in.";
219}
220
221void
222ProcessGDBRemote::Terminate()
223{
224 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
225}
226
Eugene Zelenko0722f082015-10-24 01:28:05 +0000227
Greg Claytonc3776bf2012-02-09 06:16:32 +0000228lldb::ProcessSP
Jim Ingham583bbb12016-03-07 21:50:25 +0000229ProcessGDBRemote::CreateInstance (lldb::TargetSP target_sp, ListenerSP listener_sp, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000230{
Greg Claytonc3776bf2012-02-09 06:16:32 +0000231 lldb::ProcessSP process_sp;
232 if (crash_file_path == NULL)
Jim Ingham583bbb12016-03-07 21:50:25 +0000233 process_sp.reset (new ProcessGDBRemote (target_sp, listener_sp));
Greg Claytonc3776bf2012-02-09 06:16:32 +0000234 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000235}
236
237bool
Zachary Turner7529df92015-09-01 20:02:29 +0000238ProcessGDBRemote::CanDebug (lldb::TargetSP target_sp, bool plugin_specified_by_name)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000239{
Greg Clayton596ed242011-10-21 21:41:45 +0000240 if (plugin_specified_by_name)
241 return true;
242
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000243 // For now we are just making sure the file exists for a given module
Zachary Turner7529df92015-09-01 20:02:29 +0000244 Module *exe_module = target_sp->GetExecutableModulePointer();
Greg Claytonaa149cb2011-08-11 02:48:45 +0000245 if (exe_module)
Greg Claytonc3776bf2012-02-09 06:16:32 +0000246 {
247 ObjectFile *exe_objfile = exe_module->GetObjectFile();
248 // We can't debug core files...
249 switch (exe_objfile->GetType())
250 {
251 case ObjectFile::eTypeInvalid:
252 case ObjectFile::eTypeCoreFile:
253 case ObjectFile::eTypeDebugInfo:
254 case ObjectFile::eTypeObjectFile:
255 case ObjectFile::eTypeSharedLibrary:
256 case ObjectFile::eTypeStubLibrary:
Greg Clayton23f8c952014-03-24 23:10:19 +0000257 case ObjectFile::eTypeJIT:
Greg Claytonc3776bf2012-02-09 06:16:32 +0000258 return false;
259 case ObjectFile::eTypeExecutable:
260 case ObjectFile::eTypeDynamicLinker:
261 case ObjectFile::eTypeUnknown:
262 break;
263 }
Greg Claytonaa149cb2011-08-11 02:48:45 +0000264 return exe_module->GetFileSpec().Exists();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000265 }
Jim Ingham5aee1622010-08-09 23:31:02 +0000266 // However, if there is no executable module, we return true since we might be preparing to attach.
267 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000268}
269
Eugene Zelenko0722f082015-10-24 01:28:05 +0000270//----------------------------------------------------------------------
271// ProcessGDBRemote constructor
272//----------------------------------------------------------------------
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000273ProcessGDBRemote::ProcessGDBRemote(lldb::TargetSP target_sp, ListenerSP listener_sp)
274 : Process(target_sp, listener_sp),
275 m_flags(0),
276 m_gdb_comm(),
277 m_debugserver_pid(LLDB_INVALID_PROCESS_ID),
278 m_last_stop_packet_mutex(),
279 m_register_info(),
280 m_async_broadcaster(NULL, "lldb.process.gdb-remote.async-broadcaster"),
281 m_async_listener_sp(Listener::MakeListener("lldb.process.gdb-remote.async-listener")),
282 m_async_thread_state_mutex(),
283 m_thread_ids(),
284 m_thread_pcs(),
285 m_jstopinfo_sp(),
286 m_jthreadsinfo_sp(),
287 m_continue_c_tids(),
288 m_continue_C_tids(),
289 m_continue_s_tids(),
290 m_continue_S_tids(),
291 m_max_memory_size(0),
292 m_remote_stub_max_memory_size(0),
293 m_addr_to_mmap_size(),
294 m_thread_create_bp_sp(),
295 m_waiting_for_attach(false),
296 m_destroy_tried_resuming(false),
297 m_command_sp(),
298 m_breakpoint_pc_offset(0),
299 m_initial_tid(LLDB_INVALID_THREAD_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000300{
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000301 m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
302 m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue, "async thread continue");
303 m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Pavel Labath50556852015-09-03 09:36:22 +0000304
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000305 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_ASYNC));
Pavel Labath50556852015-09-03 09:36:22 +0000306
307 const uint32_t async_event_mask = eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
308
Jim Ingham583bbb12016-03-07 21:50:25 +0000309 if (m_async_listener_sp->StartListeningForEvents(&m_async_broadcaster, async_event_mask) != async_event_mask)
Pavel Labath50556852015-09-03 09:36:22 +0000310 {
311 if (log)
312 log->Printf("ProcessGDBRemote::%s failed to listen for m_async_broadcaster events", __FUNCTION__);
313 }
314
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000315 const uint32_t gdb_event_mask =
316 Communication::eBroadcastBitReadThreadDidExit | GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify;
Jim Ingham583bbb12016-03-07 21:50:25 +0000317 if (m_async_listener_sp->StartListeningForEvents(&m_gdb_comm, gdb_event_mask) != gdb_event_mask)
Pavel Labath50556852015-09-03 09:36:22 +0000318 {
319 if (log)
320 log->Printf("ProcessGDBRemote::%s failed to listen for m_gdb_comm events", __FUNCTION__);
321 }
322
Greg Clayton7f982402013-07-15 22:54:20 +0000323 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
324 if (timeout_seconds > 0)
325 m_gdb_comm.SetPacketTimeout(timeout_seconds);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000326}
327
Eugene Zelenko0722f082015-10-24 01:28:05 +0000328//----------------------------------------------------------------------
329// Destructor
330//----------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000331ProcessGDBRemote::~ProcessGDBRemote()
332{
333 // m_mach_process.UnregisterNotificationCallbacks (this);
334 Clear();
Greg Clayton1ed54f52011-10-01 00:45:15 +0000335 // We need to call finalize on the process before destroying ourselves
336 // to make sure all of the broadcaster cleanup goes as planned. If we
337 // destruct this class, then Process::~Process() might have problems
338 // trying to fully destroy the broadcaster.
339 Finalize();
Ed Maste81b4c5f2016-01-04 01:43:47 +0000340
Jim Ingham455fa5c2012-11-01 01:15:33 +0000341 // The general Finalize is going to try to destroy the process and that SHOULD
342 // shut down the async thread. However, if we don't kill it it will get stranded and
343 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
344 StopAsyncThread();
345 KillDebugserverProcess();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000346}
347
348//----------------------------------------------------------------------
349// PluginInterface
350//----------------------------------------------------------------------
Greg Clayton57abc5d2013-05-10 21:47:16 +0000351ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000352ProcessGDBRemote::GetPluginName()
353{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000354 return GetPluginNameStatic();
355}
356
357uint32_t
358ProcessGDBRemote::GetPluginVersion()
359{
360 return 1;
361}
362
Greg Claytonef8180a2013-10-15 00:14:28 +0000363bool
364ProcessGDBRemote::ParsePythonTargetDefinition(const FileSpec &target_definition_fspec)
365{
366 ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
367 Error error;
Zachary Turner0641ca12015-03-17 20:04:04 +0000368 StructuredData::ObjectSP module_object_sp(interpreter->LoadPluginModule(target_definition_fspec, error));
Greg Claytonef8180a2013-10-15 00:14:28 +0000369 if (module_object_sp)
370 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000371 StructuredData::DictionarySP target_definition_sp(
372 interpreter->GetDynamicSettings(module_object_sp, &GetTarget(), "gdb-server-target-definition", error));
Greg Claytonef8180a2013-10-15 00:14:28 +0000373
Zachary Turner0641ca12015-03-17 20:04:04 +0000374 if (target_definition_sp)
Greg Claytonef8180a2013-10-15 00:14:28 +0000375 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000376 StructuredData::ObjectSP target_object(target_definition_sp->GetValueForKey("host-info"));
377 if (target_object)
Greg Clayton312bcbe2013-10-17 01:10:23 +0000378 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000379 if (auto host_info_dict = target_object->GetAsDictionary())
Greg Clayton312bcbe2013-10-17 01:10:23 +0000380 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000381 StructuredData::ObjectSP triple_value = host_info_dict->GetValueForKey("triple");
382 if (auto triple_string_value = triple_value->GetAsString())
383 {
384 std::string triple_string = triple_string_value->GetValue();
385 ArchSpec host_arch(triple_string.c_str());
386 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture()))
387 {
388 GetTarget().SetArchitecture(host_arch);
389 }
390 }
Greg Clayton312bcbe2013-10-17 01:10:23 +0000391 }
Greg Clayton312bcbe2013-10-17 01:10:23 +0000392 }
Zachary Turner0641ca12015-03-17 20:04:04 +0000393 m_breakpoint_pc_offset = 0;
394 StructuredData::ObjectSP breakpoint_pc_offset_value = target_definition_sp->GetValueForKey("breakpoint-pc-offset");
395 if (breakpoint_pc_offset_value)
396 {
397 if (auto breakpoint_pc_int_value = breakpoint_pc_offset_value->GetAsInteger())
398 m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
399 }
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000400
Greg Claytond04f0ed2015-05-26 18:00:51 +0000401 if (m_register_info.SetRegisterInfo(*target_definition_sp, GetTarget().GetArchitecture()) > 0)
Greg Claytonef8180a2013-10-15 00:14:28 +0000402 {
403 return true;
404 }
405 }
406 }
407 return false;
408}
409
Jason Molenda21586c82015-09-09 03:36:24 +0000410// If the remote stub didn't give us eh_frame or DWARF register numbers for a register,
411// see if the ABI can provide them.
412// DWARF and eh_frame register numbers are defined as a part of the ABI.
413static void
414AugmentRegisterInfoViaABI (RegisterInfo &reg_info, ConstString reg_name, ABISP abi_sp)
415{
416 if (reg_info.kinds[eRegisterKindEHFrame] == LLDB_INVALID_REGNUM
417 || reg_info.kinds[eRegisterKindDWARF] == LLDB_INVALID_REGNUM)
418 {
419 if (abi_sp)
420 {
421 RegisterInfo abi_reg_info;
422 if (abi_sp->GetRegisterInfoByName (reg_name, abi_reg_info))
423 {
Greg Claytonb1583dc2015-12-04 18:37:48 +0000424 if (reg_info.kinds[eRegisterKindEHFrame] == LLDB_INVALID_REGNUM &&
425 abi_reg_info.kinds[eRegisterKindEHFrame] != LLDB_INVALID_REGNUM)
Jason Molenda21586c82015-09-09 03:36:24 +0000426 {
427 reg_info.kinds[eRegisterKindEHFrame] = abi_reg_info.kinds[eRegisterKindEHFrame];
428 }
Greg Claytonb1583dc2015-12-04 18:37:48 +0000429 if (reg_info.kinds[eRegisterKindDWARF] == LLDB_INVALID_REGNUM &&
430 abi_reg_info.kinds[eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
Jason Molenda21586c82015-09-09 03:36:24 +0000431 {
432 reg_info.kinds[eRegisterKindDWARF] = abi_reg_info.kinds[eRegisterKindDWARF];
433 }
Greg Claytonb1583dc2015-12-04 18:37:48 +0000434 if (reg_info.kinds[eRegisterKindGeneric] == LLDB_INVALID_REGNUM &&
435 abi_reg_info.kinds[eRegisterKindGeneric] != LLDB_INVALID_REGNUM)
436 {
437 reg_info.kinds[eRegisterKindGeneric] = abi_reg_info.kinds[eRegisterKindGeneric];
438 }
Jason Molenda21586c82015-09-09 03:36:24 +0000439 }
440 }
441 }
442}
443
Greg Claytond04f0ed2015-05-26 18:00:51 +0000444static size_t
445SplitCommaSeparatedRegisterNumberString(const llvm::StringRef &comma_separated_regiter_numbers, std::vector<uint32_t> &regnums, int base)
446{
447 regnums.clear();
448 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
449 value_pair.second = comma_separated_regiter_numbers;
450 do
451 {
452 value_pair = value_pair.second.split(',');
453 if (!value_pair.first.empty())
454 {
455 uint32_t reg = StringConvert::ToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, base);
456 if (reg != LLDB_INVALID_REGNUM)
457 regnums.push_back (reg);
458 }
459 } while (!value_pair.second.empty());
460 return regnums.size();
461}
462
Eugene Zelenko0722f082015-10-24 01:28:05 +0000463
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000464void
Greg Clayton513c26c2011-01-29 07:10:55 +0000465ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000466{
Greg Clayton513c26c2011-01-29 07:10:55 +0000467 if (!force && m_register_info.GetNumRegisters() > 0)
468 return;
469
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000470 m_register_info.Clear();
Greg Claytond04f0ed2015-05-26 18:00:51 +0000471
472 // Check if qHostInfo specified a specific packet timeout for this connection.
473 // If so then lets update our setting so the user knows what the timeout is
474 // and can see it.
475 const uint32_t host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
476 if (host_packet_timeout)
477 {
478 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout);
479 }
480
Ed Maste81b4c5f2016-01-04 01:43:47 +0000481 // Register info search order:
Ewan Crawford0c996a92015-06-30 13:08:44 +0000482 // 1 - Use the target definition python file if one is specified.
483 // 2 - If the target definition doesn't have any of the info from the target.xml (registers) then proceed to read the target.xml.
484 // 3 - Fall back on the qRegisterInfo packets.
485
486 FileSpec target_definition_fspec = GetGlobalPluginProperties()->GetTargetDefinitionFile ();
Jason Molenda91e468c2015-08-20 04:29:46 +0000487 if (!target_definition_fspec.Exists())
488 {
489 // If the filename doesn't exist, it may be a ~ not having been expanded - try to resolve it.
490 target_definition_fspec.ResolvePath();
491 }
Ewan Crawford0c996a92015-06-30 13:08:44 +0000492 if (target_definition_fspec)
493 {
494 // See if we can get register definitions from a python file
495 if (ParsePythonTargetDefinition (target_definition_fspec))
Jason Molenda5543abb2015-08-20 03:05:09 +0000496 {
Ewan Crawford0c996a92015-06-30 13:08:44 +0000497 return;
Jason Molenda5543abb2015-08-20 03:05:09 +0000498 }
499 else
500 {
501 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
502 stream_sp->Printf ("ERROR: target description file %s failed to parse.\n", target_definition_fspec.GetPath().c_str());
503 }
Ewan Crawford0c996a92015-06-30 13:08:44 +0000504 }
505
Jim Ingham7b71c0b2016-02-18 23:58:45 +0000506 const ArchSpec &target_arch = GetTarget().GetArchitecture();
507 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
508 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
509
510 // Use the process' architecture instead of the host arch, if available
511 ArchSpec arch_to_use;
512 if (remote_process_arch.IsValid ())
513 arch_to_use = remote_process_arch;
514 else
515 arch_to_use = remote_host_arch;
516
517 if (!arch_to_use.IsValid())
518 arch_to_use = target_arch;
519
520 if (GetGDBServerRegisterInfo (arch_to_use))
Greg Claytond04f0ed2015-05-26 18:00:51 +0000521 return;
Ed Maste81b4c5f2016-01-04 01:43:47 +0000522
Greg Claytond04f0ed2015-05-26 18:00:51 +0000523 char packet[128];
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000524 uint32_t reg_offset = 0;
525 uint32_t reg_num = 0;
Greg Clayton23f59502012-07-17 03:23:13 +0000526 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Ed Maste81b4c5f2016-01-04 01:43:47 +0000527 response_type == StringExtractorGDBRemote::eResponse;
Greg Clayton576d8832011-03-22 04:00:09 +0000528 ++reg_num)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000529 {
Greg Clayton513c26c2011-01-29 07:10:55 +0000530 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
Andy Gibbsa297a972013-06-19 19:04:53 +0000531 assert (packet_len < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000532 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000533 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000534 {
Greg Clayton576d8832011-03-22 04:00:09 +0000535 response_type = response.GetResponseType();
536 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000537 {
538 std::string name;
539 std::string value;
540 ConstString reg_name;
541 ConstString alt_name;
542 ConstString set_name;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000543 std::vector<uint32_t> value_regs;
544 std::vector<uint32_t> invalidate_regs;
Nitesh Jain52b6cc52016-08-01 13:45:51 +0000545 std::vector<uint8_t> dwarf_opcode_bytes;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000546 RegisterInfo reg_info = { NULL, // Name
547 NULL, // Alt name
548 0, // byte size
549 reg_offset, // offset
550 eEncodingUint, // encoding
Jason Molendabf67a302015-09-01 05:17:01 +0000551 eFormatHex, // format
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000552 {
Jason Molendabf67a302015-09-01 05:17:01 +0000553 LLDB_INVALID_REGNUM, // eh_frame reg num
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000554 LLDB_INVALID_REGNUM, // DWARF reg num
555 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda63bd0db2015-09-15 23:20:34 +0000556 reg_num, // process plugin reg num
Jason Molendafbcb7f22010-09-10 07:49:16 +0000557 reg_num // native register number
Greg Clayton435d85a2012-02-29 19:27:27 +0000558 },
559 NULL,
Nitesh Jain52b6cc52016-08-01 13:45:51 +0000560 NULL,
561 NULL, // Dwarf expression opcode bytes pointer
562 0 // Dwarf expression opcode bytes length
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000563 };
564
565 while (response.GetNameColonValue(name, value))
566 {
567 if (name.compare("name") == 0)
568 {
569 reg_name.SetCString(value.c_str());
570 }
571 else if (name.compare("alt-name") == 0)
572 {
573 alt_name.SetCString(value.c_str());
574 }
575 else if (name.compare("bitsize") == 0)
576 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000577 reg_info.byte_size = StringConvert::ToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000578 }
579 else if (name.compare("offset") == 0)
580 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000581 uint32_t offset = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda743e86a2010-06-11 23:44:18 +0000582 if (reg_offset != offset)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000583 {
584 reg_offset = offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000585 }
586 }
587 else if (name.compare("encoding") == 0)
588 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000589 const Encoding encoding = Args::StringToEncoding (value.c_str());
590 if (encoding != eEncodingInvalid)
591 reg_info.encoding = encoding;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000592 }
593 else if (name.compare("format") == 0)
594 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000595 Format format = eFormatInvalid;
596 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
597 reg_info.format = format;
598 else if (value.compare("binary") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000599 reg_info.format = eFormatBinary;
600 else if (value.compare("decimal") == 0)
601 reg_info.format = eFormatDecimal;
602 else if (value.compare("hex") == 0)
603 reg_info.format = eFormatHex;
604 else if (value.compare("float") == 0)
605 reg_info.format = eFormatFloat;
606 else if (value.compare("vector-sint8") == 0)
607 reg_info.format = eFormatVectorOfSInt8;
608 else if (value.compare("vector-uint8") == 0)
609 reg_info.format = eFormatVectorOfUInt8;
610 else if (value.compare("vector-sint16") == 0)
611 reg_info.format = eFormatVectorOfSInt16;
612 else if (value.compare("vector-uint16") == 0)
613 reg_info.format = eFormatVectorOfUInt16;
614 else if (value.compare("vector-sint32") == 0)
615 reg_info.format = eFormatVectorOfSInt32;
616 else if (value.compare("vector-uint32") == 0)
617 reg_info.format = eFormatVectorOfUInt32;
618 else if (value.compare("vector-float32") == 0)
619 reg_info.format = eFormatVectorOfFloat32;
620 else if (value.compare("vector-uint128") == 0)
621 reg_info.format = eFormatVectorOfUInt128;
622 }
623 else if (name.compare("set") == 0)
624 {
625 set_name.SetCString(value.c_str());
626 }
Jason Molendaa18f7072015-08-15 01:21:01 +0000627 else if (name.compare("gcc") == 0 || name.compare("ehframe") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000628 {
Jason Molendaa18f7072015-08-15 01:21:01 +0000629 reg_info.kinds[eRegisterKindEHFrame] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000630 }
631 else if (name.compare("dwarf") == 0)
632 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000633 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000634 }
635 else if (name.compare("generic") == 0)
636 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000637 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000638 }
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000639 else if (name.compare("container-regs") == 0)
640 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000641 SplitCommaSeparatedRegisterNumberString(value, value_regs, 16);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000642 }
643 else if (name.compare("invalidate-regs") == 0)
644 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000645 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 16);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000646 }
Nitesh Jain52b6cc52016-08-01 13:45:51 +0000647 else if (name.compare("dynamic_size_dwarf_expr_bytes") == 0)
648 {
649 size_t dwarf_opcode_len = value.length () / 2;
650 assert (dwarf_opcode_len > 0);
651
652 dwarf_opcode_bytes.resize (dwarf_opcode_len);
653 StringExtractor opcode_extractor;
654 reg_info.dynamic_size_dwarf_len = dwarf_opcode_len;
655
656 // Swap "value" over into "opcode_extractor"
657 opcode_extractor.GetStringRef ().swap (value);
658 uint32_t ret_val = opcode_extractor.GetHexBytesAvail (dwarf_opcode_bytes.data (),
659 dwarf_opcode_len);
660 assert (dwarf_opcode_len == ret_val);
661
662 reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data ();
663 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000664 }
665
Jason Molenda743e86a2010-06-11 23:44:18 +0000666 reg_info.byte_offset = reg_offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000667 assert (reg_info.byte_size != 0);
668 reg_offset += reg_info.byte_size;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000669 if (!value_regs.empty())
670 {
671 value_regs.push_back(LLDB_INVALID_REGNUM);
672 reg_info.value_regs = value_regs.data();
673 }
674 if (!invalidate_regs.empty())
675 {
676 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
677 reg_info.invalidate_regs = invalidate_regs.data();
678 }
679
Jim Ingham7b71c0b2016-02-18 23:58:45 +0000680 // We have to make a temporary ABI here, and not use the GetABI because this code
681 // gets called in DidAttach, when the target architecture (and consequently the ABI we'll get from
682 // the process) may be wrong.
683 ABISP abi_to_use = ABI::FindPlugin(arch_to_use);
684
685 AugmentRegisterInfoViaABI (reg_info, reg_name, abi_to_use);
Jason Molenda21586c82015-09-09 03:36:24 +0000686
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000687 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
688 }
Todd Fiala1a634402014-01-08 07:52:40 +0000689 else
690 {
691 break; // ensure exit before reg_num is incremented
692 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000693 }
694 else
695 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000696 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000697 }
698 }
699
Greg Claytond04f0ed2015-05-26 18:00:51 +0000700 if (m_register_info.GetNumRegisters() > 0)
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000701 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000702 m_register_info.Finalize(GetTarget().GetArchitecture());
703 return;
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000704 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000705
Johnny Chen2fa9de12012-05-14 18:44:23 +0000706 // We didn't get anything if the accumulated reg_num is zero. See if we are
707 // debugging ARM and fill with a hard coded register set until we can get an
708 // updated debugserver down on the devices.
709 // On the other hand, if the accumulated reg_num is positive, see if we can
710 // add composite registers to the existing primordial ones.
Greg Claytond04f0ed2015-05-26 18:00:51 +0000711 bool from_scratch = (m_register_info.GetNumRegisters() == 0);
Johnny Chen2fa9de12012-05-14 18:44:23 +0000712
Johnny Chen2fa9de12012-05-14 18:44:23 +0000713 if (!target_arch.IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000714 {
Jim Ingham7b71c0b2016-02-18 23:58:45 +0000715 if (arch_to_use.IsValid()
716 && (arch_to_use.GetMachine() == llvm::Triple::arm || arch_to_use.GetMachine() == llvm::Triple::thumb)
717 && arch_to_use.GetTriple().getVendor() == llvm::Triple::Apple)
Johnny Chen2fa9de12012-05-14 18:44:23 +0000718 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000719 }
Jason Molenda6d9fe8c2015-08-21 00:13:37 +0000720 else if (target_arch.GetMachine() == llvm::Triple::arm
721 || target_arch.GetMachine() == llvm::Triple::thumb)
Johnny Chen2fa9de12012-05-14 18:44:23 +0000722 {
723 m_register_info.HardcodeARMRegisters(from_scratch);
724 }
725
726 // At this point, we can finalize our register info.
Greg Claytond04f0ed2015-05-26 18:00:51 +0000727 m_register_info.Finalize (GetTarget().GetArchitecture());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000728}
729
730Error
731ProcessGDBRemote::WillLaunch (Module* module)
732{
733 return WillLaunchOrAttach ();
734}
735
736Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000737ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000738{
739 return WillLaunchOrAttach ();
740}
741
742Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000743ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000744{
745 return WillLaunchOrAttach ();
746}
747
748Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000749ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +0000750{
Todd Fialaaf245d12014-06-30 21:05:18 +0000751 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Claytonb766a732011-02-04 01:58:07 +0000752 Error error (WillLaunchOrAttach ());
Ed Maste81b4c5f2016-01-04 01:43:47 +0000753
Greg Claytonb766a732011-02-04 01:58:07 +0000754 if (error.Fail())
755 return error;
756
Greg Clayton2289fa42011-04-30 01:09:13 +0000757 error = ConnectToDebugserver (remote_url);
Greg Claytonb766a732011-02-04 01:58:07 +0000758
759 if (error.Fail())
760 return error;
761 StartAsyncThread ();
762
Greg Claytonc574ede2011-03-10 02:26:48 +0000763 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonb766a732011-02-04 01:58:07 +0000764 if (pid == LLDB_INVALID_PROCESS_ID)
765 {
766 // We don't have a valid process ID, so note that we are connected
Ed Maste81b4c5f2016-01-04 01:43:47 +0000767 // and could now request to launch or attach, or get remote process
Greg Claytonb766a732011-02-04 01:58:07 +0000768 // listings...
769 SetPrivateState (eStateConnected);
770 }
771 else
772 {
773 // We have a valid process
774 SetID (pid);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000775 GetThreadList();
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000776 StringExtractorGDBRemote response;
777 if (m_gdb_comm.GetStopReply(response))
Greg Claytonb766a732011-02-04 01:58:07 +0000778 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000779 SetLastStopPacket(response);
Ewan Crawford78baa192015-05-13 09:18:18 +0000780
781 // '?' Packets must be handled differently in non-stop mode
782 if (GetTarget().GetNonStopModeEnabled())
783 HandleStopReplySequence();
784
Zachary Turner7529df92015-09-01 20:02:29 +0000785 Target &target = GetTarget();
Ed Maste81b4c5f2016-01-04 01:43:47 +0000786 if (!target.GetArchitecture().IsValid())
Jason Molendac62bd7b2013-12-21 05:20:36 +0000787 {
788 if (m_gdb_comm.GetProcessArchitecture().IsValid())
789 {
Zachary Turner7529df92015-09-01 20:02:29 +0000790 target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
Jason Molendac62bd7b2013-12-21 05:20:36 +0000791 }
792 else
793 {
Zachary Turner7529df92015-09-01 20:02:29 +0000794 target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molendac62bd7b2013-12-21 05:20:36 +0000795 }
Carlo Kok74389122013-10-14 07:09:13 +0000796 }
797
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000798 const StateType state = SetThreadStopInfo (response);
Greg Clayton2e309072015-07-17 23:42:28 +0000799 if (state != eStateInvalid)
Greg Claytonb766a732011-02-04 01:58:07 +0000800 {
801 SetPrivateState (state);
802 }
803 else
Daniel Malead01b2952012-11-29 21:49:15 +0000804 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 +0000805 }
806 else
Daniel Malead01b2952012-11-29 21:49:15 +0000807 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 +0000808 }
Jason Molenda16d127c2012-05-03 22:37:30 +0000809
Todd Fialaaf245d12014-06-30 21:05:18 +0000810 if (log)
811 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");
812
813
814 if (error.Success()
Jason Molenda16d127c2012-05-03 22:37:30 +0000815 && !GetTarget().GetArchitecture().IsValid()
816 && m_gdb_comm.GetHostArchitecture().IsValid())
817 {
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000818 // Prefer the *process'* architecture over that of the *host*, if available.
819 if (m_gdb_comm.GetProcessArchitecture().IsValid())
820 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
821 else
822 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molenda16d127c2012-05-03 22:37:30 +0000823 }
824
Todd Fialaaf245d12014-06-30 21:05:18 +0000825 if (log)
826 log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": normalized target architecture triple: %s", __FUNCTION__, GetID (), GetTarget ().GetArchitecture ().GetTriple ().getTriple ().c_str ());
827
Chaoren Lin98d0a4b2015-07-14 01:09:28 +0000828 if (error.Success())
Jaydeep Patil6fc590d2015-07-30 05:06:51 +0000829 {
830 PlatformSP platform_sp = GetTarget().GetPlatform();
831 if (platform_sp && platform_sp->IsConnected())
832 SetUnixSignals(platform_sp->GetUnixSignals());
833 else
834 SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
835 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000836
Greg Claytonb766a732011-02-04 01:58:07 +0000837 return error;
838}
839
840Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000841ProcessGDBRemote::WillLaunchOrAttach ()
842{
843 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000844 m_stdio_communication.Clear ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000845 return error;
846}
847
848//----------------------------------------------------------------------
849// Process Control
850//----------------------------------------------------------------------
851Error
Jean-Daniel Dupas7782de92013-12-09 22:52:50 +0000852ProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000853{
Todd Fiala75f47c32014-10-11 21:42:09 +0000854 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton4957bf62010-09-30 21:49:03 +0000855 Error error;
Greg Clayton982c9762011-11-03 21:22:33 +0000856
Todd Fiala75f47c32014-10-11 21:42:09 +0000857 if (log)
858 log->Printf ("ProcessGDBRemote::%s() entered", __FUNCTION__);
859
Greg Clayton982c9762011-11-03 21:22:33 +0000860 uint32_t launch_flags = launch_info.GetFlags().Get();
Chaoren Lind3173f32015-05-29 19:52:29 +0000861 FileSpec stdin_file_spec{};
862 FileSpec stdout_file_spec{};
863 FileSpec stderr_file_spec{};
864 FileSpec working_dir = launch_info.GetWorkingDirectory();
Greg Clayton982c9762011-11-03 21:22:33 +0000865
Zachary Turner696b5282014-08-14 16:01:25 +0000866 const FileAction *file_action;
Greg Clayton982c9762011-11-03 21:22:33 +0000867 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
868 if (file_action)
869 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000870 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000871 stdin_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000872 }
873 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
874 if (file_action)
875 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000876 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000877 stdout_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000878 }
879 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
880 if (file_action)
881 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000882 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000883 stderr_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000884 }
885
Todd Fiala75f47c32014-10-11 21:42:09 +0000886 if (log)
887 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000888 if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
Vince Harron4a8abd32015-02-13 19:15:24 +0000889 log->Printf ("ProcessGDBRemote::%s provided with STDIO paths via launch_info: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000890 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000891 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
892 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
893 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Todd Fiala75f47c32014-10-11 21:42:09 +0000894 else
895 log->Printf ("ProcessGDBRemote::%s no STDIO paths given via launch_info", __FUNCTION__);
896 }
897
Vince Harrondf3f00f2015-02-10 21:09:04 +0000898 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Chaoren Lind3173f32015-05-29 19:52:29 +0000899 if (stdin_file_spec || disable_stdio)
Vince Harrondf3f00f2015-02-10 21:09:04 +0000900 {
901 // the inferior will be reading stdin from the specified file
902 // or stdio is completely disabled
903 m_stdin_forward = false;
904 }
905 else
906 {
907 m_stdin_forward = true;
908 }
909
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000910 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
911 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
912 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000913
Greg Clayton982c9762011-11-03 21:22:33 +0000914 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000915 if (object_file)
916 {
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +0000917 error = EstablishConnectionIfNeeded (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000918 if (error.Success())
919 {
920 lldb_utility::PseudoTerminal pty;
921 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000922
Zachary Turner7529df92015-09-01 20:02:29 +0000923 PlatformSP platform_sp (GetTarget().GetPlatform());
Vince Harrondf3f00f2015-02-10 21:09:04 +0000924 if (disable_stdio)
Greg Clayton71337622011-02-24 22:24:29 +0000925 {
Vince Harrondf3f00f2015-02-10 21:09:04 +0000926 // set to /dev/null unless redirected to a file above
Chaoren Lind3173f32015-05-29 19:52:29 +0000927 if (!stdin_file_spec)
Zachary Turner4eff2d32015-10-14 21:37:36 +0000928 stdin_file_spec.SetFile(FileSystem::DEV_NULL, false);
Chaoren Lind3173f32015-05-29 19:52:29 +0000929 if (!stdout_file_spec)
Zachary Turner4eff2d32015-10-14 21:37:36 +0000930 stdout_file_spec.SetFile(FileSystem::DEV_NULL, false);
Chaoren Lind3173f32015-05-29 19:52:29 +0000931 if (!stderr_file_spec)
Zachary Turner4eff2d32015-10-14 21:37:36 +0000932 stderr_file_spec.SetFile(FileSystem::DEV_NULL, false);
Vince Harrondf3f00f2015-02-10 21:09:04 +0000933 }
934 else if (platform_sp && platform_sp->IsHost())
935 {
936 // If the debugserver is local and we aren't disabling STDIO, lets use
937 // a pseudo terminal to instead of relying on the 'O' packets for stdio
938 // since 'O' packets can really slow down debugging if the inferior
939 // does a lot of output.
Chaoren Lind3173f32015-05-29 19:52:29 +0000940 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
941 pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000942 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000943 FileSpec slave_name{pty.GetSlaveName(NULL, 0), false};
944
945 if (!stdin_file_spec)
946 stdin_file_spec = slave_name;
947
948 if (!stdout_file_spec)
949 stdout_file_spec = slave_name;
950
951 if (!stderr_file_spec)
952 stderr_file_spec = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000953 }
Todd Fiala75f47c32014-10-11 21:42:09 +0000954 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +0000955 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 +0000956 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000957 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
958 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
959 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Greg Clayton71337622011-02-24 22:24:29 +0000960 }
961
Todd Fiala75f47c32014-10-11 21:42:09 +0000962 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +0000963 log->Printf ("ProcessGDBRemote::%s final STDIO paths after all adjustments: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000964 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000965 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
966 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
967 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Todd Fiala75f47c32014-10-11 21:42:09 +0000968
Chaoren Lind3173f32015-05-29 19:52:29 +0000969 if (stdin_file_spec)
970 m_gdb_comm.SetSTDIN(stdin_file_spec);
971 if (stdout_file_spec)
972 m_gdb_comm.SetSTDOUT(stdout_file_spec);
973 if (stderr_file_spec)
974 m_gdb_comm.SetSTDERR(stderr_file_spec);
Greg Clayton71337622011-02-24 22:24:29 +0000975
976 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
Jim Ingham106d0282014-06-25 02:32:56 +0000977 m_gdb_comm.SetDetachOnError (launch_flags & eLaunchFlagDetachOnError);
Greg Clayton71337622011-02-24 22:24:29 +0000978
Zachary Turner7529df92015-09-01 20:02:29 +0000979 m_gdb_comm.SendLaunchArchPacket (GetTarget().GetArchitecture().GetArchitectureName());
Ed Maste81b4c5f2016-01-04 01:43:47 +0000980
Jason Molendaa3329782014-03-29 18:54:20 +0000981 const char * launch_event_data = launch_info.GetLaunchEventData();
982 if (launch_event_data != NULL && *launch_event_data != '\0')
983 m_gdb_comm.SendLaunchEventDataPacket (launch_event_data);
Ed Maste81b4c5f2016-01-04 01:43:47 +0000984
Chaoren Lind3173f32015-05-29 19:52:29 +0000985 if (working_dir)
Greg Clayton71337622011-02-24 22:24:29 +0000986 {
987 m_gdb_comm.SetWorkingDir (working_dir);
988 }
989
990 // Send the environment and the program + arguments after we connect
Greg Clayton982c9762011-11-03 21:22:33 +0000991 const Args &environment = launch_info.GetEnvironmentEntries();
992 if (environment.GetArgumentCount())
Greg Clayton71337622011-02-24 22:24:29 +0000993 {
Greg Clayton982c9762011-11-03 21:22:33 +0000994 size_t num_environment_entries = environment.GetArgumentCount();
995 for (size_t i=0; i<num_environment_entries; ++i)
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000996 {
Greg Clayton982c9762011-11-03 21:22:33 +0000997 const char *env_entry = environment.GetArgumentAtIndex(i);
998 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Clayton71337622011-02-24 22:24:29 +0000999 break;
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001000 }
Greg Clayton71337622011-02-24 22:24:29 +00001001 }
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001002
Greg Clayton71337622011-02-24 22:24:29 +00001003 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001004 // Scope for the scoped timeout object
1005 GDBRemoteCommunication::ScopedTimeout timeout (m_gdb_comm, 10);
1006
1007 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
1008 if (arg_packet_err == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001009 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001010 std::string error_str;
1011 if (m_gdb_comm.GetLaunchSuccess (error_str))
1012 {
1013 SetID (m_gdb_comm.GetCurrentProcessID ());
1014 }
1015 else
1016 {
1017 error.SetErrorString (error_str.c_str());
1018 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001019 }
1020 else
1021 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001022 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001023 }
Greg Clayton71337622011-02-24 22:24:29 +00001024 }
Tamas Berghammer912800c2015-02-24 10:23:39 +00001025
Greg Clayton71337622011-02-24 22:24:29 +00001026 if (GetID() == LLDB_INVALID_PROCESS_ID)
1027 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001028 if (log)
1029 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton71337622011-02-24 22:24:29 +00001030 KillDebugserverProcess ();
1031 return error;
1032 }
1033
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001034 StringExtractorGDBRemote response;
1035 if (m_gdb_comm.GetStopReply(response))
Greg Clayton71337622011-02-24 22:24:29 +00001036 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001037 SetLastStopPacket(response);
Ewan Crawford78baa192015-05-13 09:18:18 +00001038 // '?' Packets must be handled differently in non-stop mode
1039 if (GetTarget().GetNonStopModeEnabled())
1040 HandleStopReplySequence();
1041
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001042 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
1043
1044 if (process_arch.IsValid())
Jason Molendac62bd7b2013-12-21 05:20:36 +00001045 {
Zachary Turner7529df92015-09-01 20:02:29 +00001046 GetTarget().MergeArchitecture(process_arch);
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001047 }
1048 else
1049 {
1050 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
1051 if (host_arch.IsValid())
Zachary Turner7529df92015-09-01 20:02:29 +00001052 GetTarget().MergeArchitecture(host_arch);
Carlo Kok74389122013-10-14 07:09:13 +00001053 }
1054
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001055 SetPrivateState (SetThreadStopInfo (response));
Ed Maste81b4c5f2016-01-04 01:43:47 +00001056
Greg Clayton71337622011-02-24 22:24:29 +00001057 if (!disable_stdio)
1058 {
1059 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Claytonee95ed52011-11-17 22:14:31 +00001060 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Clayton71337622011-02-24 22:24:29 +00001061 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001062 }
1063 }
Greg Claytonc235ac72011-08-09 05:20:29 +00001064 else
1065 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001066 if (log)
1067 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytonc235ac72011-08-09 05:20:29 +00001068 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001069 }
1070 else
1071 {
1072 // Set our user ID to an invalid process ID.
1073 SetID(LLDB_INVALID_PROCESS_ID);
Ed Maste81b4c5f2016-01-04 01:43:47 +00001074 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
1075 exe_module->GetFileSpec().GetFilename().AsCString(),
Greg Clayton982c9762011-11-03 21:22:33 +00001076 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001077 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001078 return error;
Eugene Zelenko0722f082015-10-24 01:28:05 +00001079
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001080}
1081
Eugene Zelenko0722f082015-10-24 01:28:05 +00001082
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001083Error
Greg Claytonb766a732011-02-04 01:58:07 +00001084ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001085{
1086 Error error;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001087 // Only connect if we have a valid connect URL
Vince Harron1b5a74e2015-01-21 22:42:49 +00001088 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Ed Maste81b4c5f2016-01-04 01:43:47 +00001089
Greg Clayton00fe87b2013-12-05 22:58:22 +00001090 if (connect_url && connect_url[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001091 {
Vince Harron1b5a74e2015-01-21 22:42:49 +00001092 if (log)
1093 log->Printf("ProcessGDBRemote::%s Connecting to %s", __FUNCTION__, connect_url);
Greg Clayton00fe87b2013-12-05 22:58:22 +00001094 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
1095 if (conn_ap.get())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001096 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001097 const uint32_t max_retry_count = 50;
1098 uint32_t retry_count = 0;
1099 while (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001100 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001101 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
1102 {
1103 m_gdb_comm.SetConnection (conn_ap.release());
1104 break;
1105 }
1106 else if (error.WasInterrupted())
1107 {
1108 // If we were interrupted, don't keep retrying.
1109 break;
1110 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001111
Greg Clayton00fe87b2013-12-05 22:58:22 +00001112 retry_count++;
Ed Maste81b4c5f2016-01-04 01:43:47 +00001113
Greg Clayton00fe87b2013-12-05 22:58:22 +00001114 if (retry_count >= max_retry_count)
1115 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001116
Greg Clayton00fe87b2013-12-05 22:58:22 +00001117 usleep (100000);
1118 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001119 }
1120 }
1121
1122 if (!m_gdb_comm.IsConnected())
1123 {
1124 if (error.Success())
1125 error.SetErrorString("not connected to remote gdb server");
1126 return error;
1127 }
1128
Eugene Zelenko0722f082015-10-24 01:28:05 +00001129
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001130 // Start the communications read thread so all incoming data can be
1131 // parsed into packets and queued as they arrive.
1132 if (GetTarget().GetNonStopModeEnabled())
1133 m_gdb_comm.StartReadThread();
1134
Greg Clayton32e0a752011-03-30 18:16:51 +00001135 // We always seem to be able to open a connection to a local port
1136 // so we need to make sure we can then send data to it. If we can't
1137 // then we aren't actually connected to anything, so try and do the
Ed Maste81b4c5f2016-01-04 01:43:47 +00001138 // handshake with the remote GDB server and make sure that goes
Greg Clayton32e0a752011-03-30 18:16:51 +00001139 // alright.
Greg Claytonfb909312013-11-23 01:58:15 +00001140 if (!m_gdb_comm.HandshakeWithServer (&error))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001141 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001142 m_gdb_comm.Disconnect();
1143 if (error.Success())
1144 error.SetErrorString("not connected to remote gdb server");
1145 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001146 }
Ewan Crawford78baa192015-05-13 09:18:18 +00001147
1148 // Send $QNonStop:1 packet on startup if required
1149 if (GetTarget().GetNonStopModeEnabled())
Ewan Crawfordaa7eda72015-06-24 15:14:26 +00001150 GetTarget().SetNonStopModeEnabled (m_gdb_comm.SetNonStopMode(true));
Ewan Crawford78baa192015-05-13 09:18:18 +00001151
Greg Claytonb30c50c2015-05-29 00:01:55 +00001152 m_gdb_comm.GetEchoSupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001153 m_gdb_comm.GetThreadSuffixSupported ();
Greg Clayton44633992012-04-10 03:22:03 +00001154 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001155 m_gdb_comm.GetHostInfo ();
1156 m_gdb_comm.GetVContSupported ('c');
Jim Inghamcd16df92012-07-20 21:37:13 +00001157 m_gdb_comm.GetVAttachOrWaitSupported();
Ewan Crawford78baa192015-05-13 09:18:18 +00001158
1159 // Ask the remote server for the default thread id
1160 if (GetTarget().GetNonStopModeEnabled())
1161 m_gdb_comm.GetDefaultThreadId(m_initial_tid);
1162
1163
Jim Ingham03afad82012-07-02 05:40:07 +00001164 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1165 for (size_t idx = 0; idx < num_cmds; idx++)
1166 {
1167 StringExtractorGDBRemote response;
Jim Ingham03afad82012-07-02 05:40:07 +00001168 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1169 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001170 return error;
1171}
1172
1173void
Jim Inghambb006ce2014-08-02 00:33:35 +00001174ProcessGDBRemote::DidLaunchOrAttach (ArchSpec& process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001175{
Greg Clayton5160ce52013-03-27 23:08:40 +00001176 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001177 if (log)
1178 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton93d3c8332011-02-16 04:46:07 +00001179 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001180 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001181 BuildDynamicRegisterInfo (false);
Greg Clayton3af9ea52010-11-18 05:57:03 +00001182
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001183 // See if the GDB server supports the qHostInfo information
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001184
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001185
1186 // See if the GDB server supports the qProcessInfo packet, if so
1187 // prefer that over the Host information as it will be more specific
1188 // to our process.
1189
Todd Fiala75f47c32014-10-11 21:42:09 +00001190 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1191 if (remote_process_arch.IsValid())
1192 {
1193 process_arch = remote_process_arch;
1194 if (log)
1195 log->Printf ("ProcessGDBRemote::%s gdb-remote had process architecture, using %s %s",
1196 __FUNCTION__,
1197 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1198 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1199 }
Jim Inghambb006ce2014-08-02 00:33:35 +00001200 else
Todd Fiala75f47c32014-10-11 21:42:09 +00001201 {
Jim Inghambb006ce2014-08-02 00:33:35 +00001202 process_arch = m_gdb_comm.GetHostArchitecture();
Todd Fiala75f47c32014-10-11 21:42:09 +00001203 if (log)
1204 log->Printf ("ProcessGDBRemote::%s gdb-remote did not have process architecture, using gdb-remote host architecture %s %s",
1205 __FUNCTION__,
1206 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1207 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1208 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001209
Jim Inghambb006ce2014-08-02 00:33:35 +00001210 if (process_arch.IsValid())
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001211 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001212 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Greg Claytond314e812011-03-23 00:09:55 +00001213 if (target_arch.IsValid())
1214 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001215 if (log)
1216 log->Printf ("ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1217 __FUNCTION__,
1218 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1219 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
1220
1221 // If the remote host is ARM and we have apple as the vendor, then
Greg Claytond314e812011-03-23 00:09:55 +00001222 // ARM executables and shared libraries can have mixed ARM architectures.
1223 // You can have an armv6 executable, and if the host is armv7, then the
1224 // system will load the best possible architecture for all shared libraries
1225 // it has, so we really need to take the remote host architecture as our
1226 // defacto architecture in this case.
1227
Jason Molenda6d9fe8c2015-08-21 00:13:37 +00001228 if ((process_arch.GetMachine() == llvm::Triple::arm || process_arch.GetMachine() == llvm::Triple::thumb)
1229 && process_arch.GetTriple().getVendor() == llvm::Triple::Apple)
Greg Claytond314e812011-03-23 00:09:55 +00001230 {
Jason Molenda921c01b2014-08-03 21:42:52 +00001231 GetTarget().SetArchitecture (process_arch);
Todd Fiala75f47c32014-10-11 21:42:09 +00001232 if (log)
1233 log->Printf ("ProcessGDBRemote::%s remote process is ARM/Apple, setting target arch to %s %s",
1234 __FUNCTION__,
1235 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1236 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001237 }
1238 else
1239 {
1240 // Fill in what is missing in the triple
Jim Inghambb006ce2014-08-02 00:33:35 +00001241 const llvm::Triple &remote_triple = process_arch.GetTriple();
Tamas Berghammere724af12015-03-13 10:32:37 +00001242 llvm::Triple new_target_triple = target_arch.GetTriple();
1243 if (new_target_triple.getVendorName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001244 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001245 new_target_triple.setVendor (remote_triple.getVendor());
Greg Claytond314e812011-03-23 00:09:55 +00001246
Tamas Berghammere724af12015-03-13 10:32:37 +00001247 if (new_target_triple.getOSName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001248 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001249 new_target_triple.setOS (remote_triple.getOS());
Greg Claytond314e812011-03-23 00:09:55 +00001250
Tamas Berghammere724af12015-03-13 10:32:37 +00001251 if (new_target_triple.getEnvironmentName().size() == 0)
1252 new_target_triple.setEnvironment (remote_triple.getEnvironment());
Greg Clayton70b57652011-05-15 01:25:55 +00001253 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001254
Tamas Berghammere724af12015-03-13 10:32:37 +00001255 ArchSpec new_target_arch = target_arch;
1256 new_target_arch.SetTriple(new_target_triple);
1257 GetTarget().SetArchitecture(new_target_arch);
1258 }
Greg Claytond314e812011-03-23 00:09:55 +00001259 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001260
1261 if (log)
1262 log->Printf ("ProcessGDBRemote::%s final target arch after adjustments for remote architecture: %s %s",
1263 __FUNCTION__,
1264 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1265 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001266 }
1267 else
1268 {
1269 // The target doesn't have a valid architecture yet, set it from
1270 // the architecture we got from the remote GDB server
Jason Molenda921c01b2014-08-03 21:42:52 +00001271 GetTarget().SetArchitecture (process_arch);
Greg Claytond314e812011-03-23 00:09:55 +00001272 }
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001273 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001274 }
1275}
1276
1277void
1278ProcessGDBRemote::DidLaunch ()
1279{
Jim Inghambb006ce2014-08-02 00:33:35 +00001280 ArchSpec process_arch;
1281 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001282}
1283
1284Error
Han Ming Ong84647042012-02-25 01:07:38 +00001285ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1286{
Todd Fiala75f47c32014-10-11 21:42:09 +00001287 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001288 Error error;
Todd Fiala75f47c32014-10-11 21:42:09 +00001289
1290 if (log)
1291 log->Printf ("ProcessGDBRemote::%s()", __FUNCTION__);
1292
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001293 // Clear out and clean up from any current state
1294 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001295 if (attach_pid != LLDB_INVALID_PROCESS_ID)
1296 {
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00001297 error = EstablishConnectionIfNeeded (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001298 if (error.Success())
1299 {
Jim Ingham106d0282014-06-25 02:32:56 +00001300 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
Todd Fiala75f47c32014-10-11 21:42:09 +00001301
Greg Clayton71337622011-02-24 22:24:29 +00001302 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001303 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Ed Maste81b4c5f2016-01-04 01:43:47 +00001304 SetID (attach_pid);
Greg Clayton71337622011-02-24 22:24:29 +00001305 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001306 }
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00001307 else
1308 SetExitStatus (-1, error.AsCString());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001309 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001310
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001311 return error;
1312}
1313
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001314Error
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001315ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001316{
1317 Error error;
1318 // Clear out and clean up from any current state
1319 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001320
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001321 if (process_name && process_name[0])
1322 {
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00001323 error = EstablishConnectionIfNeeded (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001324 if (error.Success())
1325 {
1326 StreamString packet;
Ed Maste81b4c5f2016-01-04 01:43:47 +00001327
Jim Ingham106d0282014-06-25 02:32:56 +00001328 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
Ed Maste81b4c5f2016-01-04 01:43:47 +00001329
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001330 if (attach_info.GetWaitForLaunch())
Jim Inghamcd16df92012-07-20 21:37:13 +00001331 {
1332 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1333 {
1334 packet.PutCString ("vAttachWait");
1335 }
1336 else
1337 {
1338 if (attach_info.GetIgnoreExisting())
1339 packet.PutCString("vAttachWait");
1340 else
1341 packet.PutCString ("vAttachOrWait");
1342 }
1343 }
Greg Clayton71337622011-02-24 22:24:29 +00001344 else
1345 packet.PutCString("vAttachName");
1346 packet.PutChar(';');
Bruce Mitchener9ccb9702015-11-07 04:40:13 +00001347 packet.PutBytesAsRawHex8(process_name, strlen(process_name), endian::InlHostByteOrder(), endian::InlHostByteOrder());
Ed Maste81b4c5f2016-01-04 01:43:47 +00001348
Greg Clayton71337622011-02-24 22:24:29 +00001349 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1350
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001351 }
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00001352 else
1353 SetExitStatus (-1, error.AsCString());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001354 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001355 return error;
1356}
1357
Greg Clayton5df78fa2015-05-23 03:54:53 +00001358void
1359ProcessGDBRemote::DidExit ()
Greg Claytonfbb76342013-11-20 21:07:01 +00001360{
Greg Clayton5df78fa2015-05-23 03:54:53 +00001361 // When we exit, disconnect from the GDB server communications
Greg Claytonfbb76342013-11-20 21:07:01 +00001362 m_gdb_comm.Disconnect();
Greg Claytonfbb76342013-11-20 21:07:01 +00001363}
1364
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001365void
Jim Inghambb006ce2014-08-02 00:33:35 +00001366ProcessGDBRemote::DidAttach (ArchSpec &process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001367{
Jim Inghambb006ce2014-08-02 00:33:35 +00001368 // If you can figure out what the architecture is, fill it in here.
1369 process_arch.Clear();
1370 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001371}
1372
Eugene Zelenko0722f082015-10-24 01:28:05 +00001373
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001374Error
1375ProcessGDBRemote::WillResume ()
1376{
Greg Clayton71fc2a32011-02-12 06:28:37 +00001377 m_continue_c_tids.clear();
1378 m_continue_C_tids.clear();
1379 m_continue_s_tids.clear();
1380 m_continue_S_tids.clear();
Greg Clayton2e309072015-07-17 23:42:28 +00001381 m_jstopinfo_sp.reset();
1382 m_jthreadsinfo_sp.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001383 return Error();
1384}
1385
1386Error
1387ProcessGDBRemote::DoResume ()
1388{
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001389 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001390 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001391 if (log)
1392 log->Printf ("ProcessGDBRemote::Resume()");
Ed Maste81b4c5f2016-01-04 01:43:47 +00001393
Jim Ingham583bbb12016-03-07 21:50:25 +00001394 ListenerSP listener_sp (Listener::MakeListener("gdb-remote.resume-packet-sent"));
1395 if (listener_sp->StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
Greg Claytone5219662010-12-03 06:02:24 +00001396 {
Jim Ingham583bbb12016-03-07 21:50:25 +00001397 listener_sp->StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
Ed Maste81b4c5f2016-01-04 01:43:47 +00001398
Greg Claytond1d06e42013-04-20 00:27:58 +00001399 const size_t num_threads = GetThreadList().GetSize();
1400
Greg Clayton71fc2a32011-02-12 06:28:37 +00001401 StreamString continue_packet;
1402 bool continue_packet_error = false;
1403 if (m_gdb_comm.HasAnyVContSupport ())
1404 {
Ewan Crawford78baa192015-05-13 09:18:18 +00001405 if (!GetTarget().GetNonStopModeEnabled() &&
1406 (m_continue_c_tids.size() == num_threads ||
Greg Claytone98008c2014-02-13 23:34:38 +00001407 (m_continue_c_tids.empty() &&
1408 m_continue_C_tids.empty() &&
1409 m_continue_s_tids.empty() &&
Ewan Crawford78baa192015-05-13 09:18:18 +00001410 m_continue_S_tids.empty())))
Greg Clayton71fc2a32011-02-12 06:28:37 +00001411 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001412 // All threads are continuing, just send a "c" packet
1413 continue_packet.PutCString ("c");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001414 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001415 else
1416 {
1417 continue_packet.PutCString ("vCont");
Ed Maste81b4c5f2016-01-04 01:43:47 +00001418
Greg Claytond1d06e42013-04-20 00:27:58 +00001419 if (!m_continue_c_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001420 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001421 if (m_gdb_comm.GetVContSupported ('c'))
1422 {
1423 for (tid_collection::const_iterator t_pos = m_continue_c_tids.begin(), t_end = m_continue_c_tids.end(); t_pos != t_end; ++t_pos)
1424 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1425 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001426 else
Greg Claytond1d06e42013-04-20 00:27:58 +00001427 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001428 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001429
Greg Claytond1d06e42013-04-20 00:27:58 +00001430 if (!continue_packet_error && !m_continue_C_tids.empty())
1431 {
1432 if (m_gdb_comm.GetVContSupported ('C'))
1433 {
1434 for (tid_sig_collection::const_iterator s_pos = m_continue_C_tids.begin(), s_end = m_continue_C_tids.end(); s_pos != s_end; ++s_pos)
1435 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1436 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001437 else
Greg Claytond1d06e42013-04-20 00:27:58 +00001438 continue_packet_error = true;
1439 }
Greg Claytone5219662010-12-03 06:02:24 +00001440
Greg Claytond1d06e42013-04-20 00:27:58 +00001441 if (!continue_packet_error && !m_continue_s_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001442 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001443 if (m_gdb_comm.GetVContSupported ('s'))
1444 {
1445 for (tid_collection::const_iterator t_pos = m_continue_s_tids.begin(), t_end = m_continue_s_tids.end(); t_pos != t_end; ++t_pos)
1446 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1447 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001448 else
Greg Claytond1d06e42013-04-20 00:27:58 +00001449 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001450 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001451
Greg Claytond1d06e42013-04-20 00:27:58 +00001452 if (!continue_packet_error && !m_continue_S_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001453 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001454 if (m_gdb_comm.GetVContSupported ('S'))
1455 {
1456 for (tid_sig_collection::const_iterator s_pos = m_continue_S_tids.begin(), s_end = m_continue_S_tids.end(); s_pos != s_end; ++s_pos)
1457 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1458 }
1459 else
1460 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001461 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001462
Greg Claytond1d06e42013-04-20 00:27:58 +00001463 if (continue_packet_error)
1464 continue_packet.GetString().clear();
Greg Clayton71fc2a32011-02-12 06:28:37 +00001465 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001466 }
1467 else
1468 continue_packet_error = true;
Ed Maste81b4c5f2016-01-04 01:43:47 +00001469
Greg Clayton71fc2a32011-02-12 06:28:37 +00001470 if (continue_packet_error)
1471 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001472 // Either no vCont support, or we tried to use part of the vCont
1473 // packet that wasn't supported by the remote GDB server.
1474 // We need to try and make a simple packet that can do our continue
Greg Clayton71fc2a32011-02-12 06:28:37 +00001475 const size_t num_continue_c_tids = m_continue_c_tids.size();
1476 const size_t num_continue_C_tids = m_continue_C_tids.size();
1477 const size_t num_continue_s_tids = m_continue_s_tids.size();
1478 const size_t num_continue_S_tids = m_continue_S_tids.size();
1479 if (num_continue_c_tids > 0)
1480 {
1481 if (num_continue_c_tids == num_threads)
1482 {
1483 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001484 m_gdb_comm.SetCurrentThreadForRun (-1);
Ed Maste81b4c5f2016-01-04 01:43:47 +00001485 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001486 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001487 }
1488 else if (num_continue_c_tids == 1 &&
Ed Maste81b4c5f2016-01-04 01:43:47 +00001489 num_continue_C_tids == 0 &&
1490 num_continue_s_tids == 0 &&
Greg Clayton71fc2a32011-02-12 06:28:37 +00001491 num_continue_S_tids == 0 )
1492 {
1493 // Only one thread is continuing
Greg Clayton8b82f082011-04-12 05:54:46 +00001494 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Ed Maste81b4c5f2016-01-04 01:43:47 +00001495 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001496 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001497 }
1498 }
1499
Greg Clayton0c74e782011-06-24 03:21:43 +00001500 if (continue_packet_error && num_continue_C_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001501 {
Ed Maste81b4c5f2016-01-04 01:43:47 +00001502 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1503 num_continue_C_tids > 0 &&
1504 num_continue_s_tids == 0 &&
Greg Clayton0c74e782011-06-24 03:21:43 +00001505 num_continue_S_tids == 0 )
Greg Clayton71fc2a32011-02-12 06:28:37 +00001506 {
1507 const int continue_signo = m_continue_C_tids.front().second;
Greg Clayton0c74e782011-06-24 03:21:43 +00001508 // Only one thread is continuing
Greg Clayton71fc2a32011-02-12 06:28:37 +00001509 if (num_continue_C_tids > 1)
1510 {
Ed Maste81b4c5f2016-01-04 01:43:47 +00001511 // More that one thread with a signal, yet we don't have
Greg Clayton0c74e782011-06-24 03:21:43 +00001512 // vCont support and we are being asked to resume each
1513 // thread with a signal, we need to make sure they are
1514 // all the same signal, or we can't issue the continue
1515 // accurately with the current support...
1516 if (num_continue_C_tids > 1)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001517 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001518 continue_packet_error = false;
1519 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1520 {
1521 if (m_continue_C_tids[i].second != continue_signo)
1522 continue_packet_error = true;
1523 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001524 }
Greg Clayton0c74e782011-06-24 03:21:43 +00001525 if (!continue_packet_error)
1526 m_gdb_comm.SetCurrentThreadForRun (-1);
1527 }
1528 else
1529 {
1530 // Set the continue thread ID
1531 continue_packet_error = false;
1532 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001533 }
1534 if (!continue_packet_error)
1535 {
1536 // Add threads continuing with the same signo...
Greg Clayton71fc2a32011-02-12 06:28:37 +00001537 continue_packet.Printf("C%2.2x", continue_signo);
1538 }
1539 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001540 }
1541
Greg Clayton0c74e782011-06-24 03:21:43 +00001542 if (continue_packet_error && num_continue_s_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001543 {
1544 if (num_continue_s_tids == num_threads)
1545 {
1546 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001547 m_gdb_comm.SetCurrentThreadForRun (-1);
Ewan Crawford76df2882015-06-23 12:32:06 +00001548
1549 // If in Non-Stop-Mode use vCont when stepping
1550 if (GetTarget().GetNonStopModeEnabled())
1551 {
1552 if (m_gdb_comm.GetVContSupported('s'))
1553 continue_packet.PutCString("vCont;s");
1554 else
1555 continue_packet.PutChar('s');
1556 }
1557 else
1558 continue_packet.PutChar('s');
1559
Greg Clayton0c74e782011-06-24 03:21:43 +00001560 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001561 }
1562 else if (num_continue_c_tids == 0 &&
Ed Maste81b4c5f2016-01-04 01:43:47 +00001563 num_continue_C_tids == 0 &&
1564 num_continue_s_tids == 1 &&
Greg Clayton71fc2a32011-02-12 06:28:37 +00001565 num_continue_S_tids == 0 )
1566 {
1567 // Only one thread is stepping
Greg Clayton8b82f082011-04-12 05:54:46 +00001568 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Ed Maste81b4c5f2016-01-04 01:43:47 +00001569 continue_packet.PutChar ('s');
Greg Clayton0c74e782011-06-24 03:21:43 +00001570 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001571 }
1572 }
1573
1574 if (!continue_packet_error && num_continue_S_tids > 0)
1575 {
1576 if (num_continue_S_tids == num_threads)
1577 {
1578 const int step_signo = m_continue_S_tids.front().second;
1579 // Are all threads trying to step with the same signal?
Greg Clayton0c74e782011-06-24 03:21:43 +00001580 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001581 if (num_continue_S_tids > 1)
1582 {
1583 for (size_t i=1; i<num_threads; ++i)
1584 {
1585 if (m_continue_S_tids[i].second != step_signo)
1586 continue_packet_error = true;
1587 }
1588 }
1589 if (!continue_packet_error)
1590 {
1591 // Add threads stepping with the same signo...
Greg Clayton8b82f082011-04-12 05:54:46 +00001592 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001593 continue_packet.Printf("S%2.2x", step_signo);
1594 }
1595 }
1596 else if (num_continue_c_tids == 0 &&
Ed Maste81b4c5f2016-01-04 01:43:47 +00001597 num_continue_C_tids == 0 &&
1598 num_continue_s_tids == 0 &&
Greg Clayton71fc2a32011-02-12 06:28:37 +00001599 num_continue_S_tids == 1 )
1600 {
1601 // Only one thread is stepping with signal
Greg Clayton8b82f082011-04-12 05:54:46 +00001602 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001603 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Clayton0c74e782011-06-24 03:21:43 +00001604 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001605 }
1606 }
1607 }
1608
1609 if (continue_packet_error)
1610 {
1611 error.SetErrorString ("can't make continue packet for this resume");
1612 }
1613 else
1614 {
1615 EventSP event_sp;
Zachary Turneracee96a2014-09-23 18:32:09 +00001616 if (!m_async_thread.IsJoinable())
Jim Inghamb1e2e842012-04-12 18:49:31 +00001617 {
1618 error.SetErrorString ("Trying to resume but the async thread is dead.");
1619 if (log)
1620 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1621 return error;
1622 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001623
Greg Clayton71fc2a32011-02-12 06:28:37 +00001624 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1625
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00001626 if (listener_sp->WaitForEvent(std::chrono::seconds(5), event_sp) == false)
Jim Inghamb1e2e842012-04-12 18:49:31 +00001627 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001628 error.SetErrorString("Resume timed out.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00001629 if (log)
1630 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1631 }
1632 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1633 {
1634 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1635 if (log)
1636 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1637 return error;
1638 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001639 }
Greg Claytone5219662010-12-03 06:02:24 +00001640 }
1641
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001642 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001643}
1644
Greg Clayton9e920902012-04-10 02:25:43 +00001645void
Ewan Crawford78baa192015-05-13 09:18:18 +00001646ProcessGDBRemote::HandleStopReplySequence ()
1647{
1648 while(true)
1649 {
1650 // Send vStopped
1651 StringExtractorGDBRemote response;
1652 m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false);
1653
1654 // OK represents end of signal list
1655 if (response.IsOKResponse())
1656 break;
1657
1658 // If not OK or a normal packet we have a problem
1659 if (!response.IsNormalResponse())
1660 break;
1661
1662 SetLastStopPacket(response);
1663 }
1664}
1665
1666void
Greg Clayton9e920902012-04-10 02:25:43 +00001667ProcessGDBRemote::ClearThreadIDList ()
1668{
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00001669 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001670 m_thread_ids.clear();
Jason Molenda545304d2015-12-18 00:45:35 +00001671 m_thread_pcs.clear();
Greg Clayton9e920902012-04-10 02:25:43 +00001672}
1673
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001674size_t
1675ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue (std::string &value)
1676{
1677 m_thread_ids.clear();
Jason Molenda545304d2015-12-18 00:45:35 +00001678 m_thread_pcs.clear();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001679 size_t comma_pos;
1680 lldb::tid_t tid;
1681 while ((comma_pos = value.find(',')) != std::string::npos)
1682 {
1683 value[comma_pos] = '\0';
1684 // thread in big endian hex
1685 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1686 if (tid != LLDB_INVALID_THREAD_ID)
1687 m_thread_ids.push_back (tid);
1688 value.erase(0, comma_pos + 1);
1689 }
1690 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1691 if (tid != LLDB_INVALID_THREAD_ID)
1692 m_thread_ids.push_back (tid);
1693 return m_thread_ids.size();
1694}
1695
Jason Molenda545304d2015-12-18 00:45:35 +00001696size_t
1697ProcessGDBRemote::UpdateThreadPCsFromStopReplyThreadsValue (std::string &value)
1698{
1699 m_thread_pcs.clear();
1700 size_t comma_pos;
1701 lldb::addr_t pc;
1702 while ((comma_pos = value.find(',')) != std::string::npos)
1703 {
1704 value[comma_pos] = '\0';
1705 pc = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
1706 if (pc != LLDB_INVALID_ADDRESS)
1707 m_thread_pcs.push_back (pc);
1708 value.erase(0, comma_pos + 1);
1709 }
1710 pc = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
1711 if (pc != LLDB_INVALID_THREAD_ID)
1712 m_thread_pcs.push_back (pc);
1713 return m_thread_pcs.size();
1714}
1715
Greg Clayton9e920902012-04-10 02:25:43 +00001716bool
1717ProcessGDBRemote::UpdateThreadIDList ()
1718{
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00001719 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001720
Greg Clayton2e309072015-07-17 23:42:28 +00001721 if (m_jthreadsinfo_sp)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001722 {
1723 // If we have the JSON threads info, we can get the thread list from that
Greg Clayton2e309072015-07-17 23:42:28 +00001724 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001725 if (thread_infos && thread_infos->GetSize() > 0)
1726 {
1727 m_thread_ids.clear();
Jason Molenda545304d2015-12-18 00:45:35 +00001728 m_thread_pcs.clear();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001729 thread_infos->ForEach([this](StructuredData::Object* object) -> bool {
1730 StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1731 if (thread_dict)
1732 {
1733 // Set the thread stop info from the JSON dictionary
1734 SetThreadStopInfo (thread_dict);
1735 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1736 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1737 m_thread_ids.push_back(tid);
1738 }
1739 return true; // Keep iterating through all thread_info objects
1740 });
1741 }
1742 if (!m_thread_ids.empty())
1743 return true;
1744 }
1745 else
1746 {
1747 // See if we can get the thread IDs from the current stop reply packets
1748 // that might contain a "threads" key/value pair
1749
1750 // Lock the thread stack while we access it
Greg Claytonfc1e77a982015-11-03 22:42:04 +00001751 //Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +00001752 std::unique_lock<std::recursive_mutex> stop_stack_lock(m_last_stop_packet_mutex, std::defer_lock);
1753 if (stop_stack_lock.try_lock())
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001754 {
Greg Claytonfc1e77a982015-11-03 22:42:04 +00001755 // Get the number of stop packets on the stack
1756 int nItems = m_stop_packet_stack.size();
1757 // Iterate over them
1758 for (int i = 0; i < nItems; i++)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001759 {
Greg Claytonfc1e77a982015-11-03 22:42:04 +00001760 // Get the thread stop info
1761 StringExtractorGDBRemote &stop_info = m_stop_packet_stack[i];
1762 const std::string &stop_info_str = stop_info.GetStringRef();
Jason Molenda545304d2015-12-18 00:45:35 +00001763
1764 m_thread_pcs.clear();
1765 const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:");
1766 if (thread_pcs_pos != std::string::npos)
1767 {
1768 const size_t start = thread_pcs_pos + strlen(";thread-pcs:");
1769 const size_t end = stop_info_str.find(';', start);
1770 if (end != std::string::npos)
1771 {
1772 std::string value = stop_info_str.substr(start, end - start);
1773 UpdateThreadPCsFromStopReplyThreadsValue(value);
1774 }
1775 }
1776
Greg Claytonfc1e77a982015-11-03 22:42:04 +00001777 const size_t threads_pos = stop_info_str.find(";threads:");
1778 if (threads_pos != std::string::npos)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001779 {
Greg Claytonfc1e77a982015-11-03 22:42:04 +00001780 const size_t start = threads_pos + strlen(";threads:");
1781 const size_t end = stop_info_str.find(';', start);
1782 if (end != std::string::npos)
1783 {
1784 std::string value = stop_info_str.substr(start, end - start);
1785 if (UpdateThreadIDsFromStopReplyThreadsValue(value))
1786 return true;
1787 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001788 }
1789 }
1790 }
1791 }
1792
Greg Clayton9e920902012-04-10 02:25:43 +00001793 bool sequence_mutex_unavailable = false;
1794 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1795 if (sequence_mutex_unavailable)
1796 {
Greg Clayton9e920902012-04-10 02:25:43 +00001797 return false; // We just didn't get the list
1798 }
1799 return true;
1800}
1801
Greg Clayton9fc13552012-04-10 00:18:59 +00001802bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001803ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001804{
1805 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +00001806 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Clayton73b472d2010-10-27 03:32:59 +00001807 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +00001808 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Ed Maste81b4c5f2016-01-04 01:43:47 +00001809
Greg Clayton9e920902012-04-10 02:25:43 +00001810 size_t num_thread_ids = m_thread_ids.size();
1811 // The "m_thread_ids" thread ID list should always be updated after each stop
1812 // reply packet, but in case it isn't, update it here.
1813 if (num_thread_ids == 0)
1814 {
1815 if (!UpdateThreadIDList ())
1816 return false;
1817 num_thread_ids = m_thread_ids.size();
1818 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001819
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001820 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001821 if (num_thread_ids > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001822 {
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001823 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001824 {
Greg Clayton9e920902012-04-10 02:25:43 +00001825 tid_t tid = m_thread_ids[i];
Greg Clayton160c9d82013-05-01 21:54:04 +00001826 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001827 if (!thread_sp)
Jim Inghamdee1bc92013-06-22 00:27:45 +00001828 {
Jim Ingham4f465cf2012-10-10 18:32:14 +00001829 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001830 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1831 log->Printf(
1832 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001833 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001834 thread_sp->GetID());
1835 }
1836 else
1837 {
1838 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1839 log->Printf(
1840 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001841 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001842 thread_sp->GetID());
1843 }
Jason Molenda545304d2015-12-18 00:45:35 +00001844 // The m_thread_pcs vector has pc values in big-endian order, not target-endian, unlike most
Ed Maste81b4c5f2016-01-04 01:43:47 +00001845 // of the register read/write packets in gdb-remote protocol.
Jason Molenda545304d2015-12-18 00:45:35 +00001846 // Early in the process startup, we may not yet have set the process ByteOrder so we ignore these;
1847 // they are a performance improvement over fetching thread register values individually, the
1848 // method we will fall back to if needed.
1849 if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() && GetByteOrder() != eByteOrderInvalid)
1850 {
1851 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1852 RegisterContextSP reg_ctx_sp (thread_sp->GetRegisterContext());
1853 if (reg_ctx_sp)
1854 {
Ed Maste81b4c5f2016-01-04 01:43:47 +00001855 uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber
Jason Molenda545304d2015-12-18 00:45:35 +00001856 (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1857 if (pc_regnum != LLDB_INVALID_REGNUM)
1858 {
1859 gdb_thread->PrivateSetRegisterValue (pc_regnum, m_thread_pcs[i]);
1860 }
1861 }
1862 }
Greg Clayton88f86b62016-06-10 23:23:34 +00001863 new_thread_list.AddThreadSortedByIndexID (thread_sp);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001864 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001865 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001866
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001867 // Whatever that is left in old_thread_list_copy are not
1868 // present in new_thread_list. Remove non-existent threads from internal id table.
1869 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1870 for (size_t i=0; i<old_num_thread_ids; i++)
1871 {
1872 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1873 if (old_thread_sp)
1874 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001875 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001876 m_thread_id_to_index_id_map.erase(old_thread_id);
1877 }
1878 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00001879
Greg Clayton9fc13552012-04-10 00:18:59 +00001880 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001881}
1882
Eugene Zelenko0722f082015-10-24 01:28:05 +00001883
Greg Clayton358cf1e2015-06-25 21:46:34 +00001884bool
Greg Clayton2e309072015-07-17 23:42:28 +00001885ProcessGDBRemote::GetThreadStopInfoFromJSON (ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001886{
1887 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet
Greg Clayton2e309072015-07-17 23:42:28 +00001888 if (thread_infos_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001889 {
Greg Clayton2e309072015-07-17 23:42:28 +00001890 StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
Greg Clayton358cf1e2015-06-25 21:46:34 +00001891 if (thread_infos)
1892 {
1893 lldb::tid_t tid;
1894 const size_t n = thread_infos->GetSize();
1895 for (size_t i=0; i<n; ++i)
1896 {
1897 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1898 if (thread_dict)
1899 {
1900 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid, LLDB_INVALID_THREAD_ID))
1901 {
1902 if (tid == thread->GetID())
Greg Clayton2e309072015-07-17 23:42:28 +00001903 return (bool)SetThreadStopInfo(thread_dict);
Greg Clayton358cf1e2015-06-25 21:46:34 +00001904 }
1905 }
1906 }
1907 }
1908 }
Greg Clayton2e309072015-07-17 23:42:28 +00001909 return false;
1910}
1911
1912bool
1913ProcessGDBRemote::CalculateThreadStopInfo (ThreadGDBRemote *thread)
1914{
1915 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet
1916 if (GetThreadStopInfoFromJSON (thread, m_jthreadsinfo_sp))
1917 return true;
1918
1919 // See if we got thread stop info for any threads valid stop info reasons threads
1920 // via the "jstopinfo" packet stop reply packet key/value pair?
1921 if (m_jstopinfo_sp)
1922 {
1923 // If we have "jstopinfo" then we have stop descriptions for all threads
1924 // that have stop reasons, and if there is no entry for a thread, then
1925 // it has no stop reason.
1926 thread->GetRegisterContext()->InvalidateIfNeeded(true);
1927 if (!GetThreadStopInfoFromJSON (thread, m_jstopinfo_sp))
1928 {
1929 thread->SetStopInfo (StopInfoSP());
1930 }
1931 return true;
1932 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00001933
1934 // Fall back to using the qThreadStopInfo packet
1935 StringExtractorGDBRemote stop_packet;
1936 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1937 return SetThreadStopInfo (stop_packet) == eStateStopped;
1938 return false;
1939}
1940
Eugene Zelenko0722f082015-10-24 01:28:05 +00001941
Greg Clayton358cf1e2015-06-25 21:46:34 +00001942ThreadSP
1943ProcessGDBRemote::SetThreadStopInfo (lldb::tid_t tid,
1944 ExpeditedRegisterMap &expedited_register_map,
1945 uint8_t signo,
1946 const std::string &thread_name,
1947 const std::string &reason,
1948 const std::string &description,
1949 uint32_t exc_type,
1950 const std::vector<addr_t> &exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001951 addr_t thread_dispatch_qaddr,
1952 bool queue_vars_valid, // Set to true if queue_name, queue_kind and queue_serial are valid
Jason Molenda77f89352016-01-12 07:09:16 +00001953 LazyBool associated_with_dispatch_queue,
1954 addr_t dispatch_queue_t,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001955 std::string &queue_name,
1956 QueueKind queue_kind,
1957 uint64_t queue_serial)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001958{
1959 ThreadSP thread_sp;
1960 if (tid != LLDB_INVALID_THREAD_ID)
1961 {
1962 // Scope for "locker" below
1963 {
1964 // m_thread_list_real does have its own mutex, but we need to
1965 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1966 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00001967 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
Greg Clayton358cf1e2015-06-25 21:46:34 +00001968 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1969
1970 if (!thread_sp)
1971 {
1972 // Create the thread if we need to
1973 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1974 m_thread_list_real.AddThread(thread_sp);
1975 }
1976 }
1977
1978 if (thread_sp)
1979 {
1980 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1981 gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001982
Greg Clayton358cf1e2015-06-25 21:46:34 +00001983 for (const auto &pair : expedited_register_map)
1984 {
1985 StringExtractor reg_value_extractor;
1986 reg_value_extractor.GetStringRef() = pair.second;
1987 gdb_thread->PrivateSetRegisterValue (pair.first, reg_value_extractor);
1988 }
1989
Greg Clayton358cf1e2015-06-25 21:46:34 +00001990 thread_sp->SetName (thread_name.empty() ? NULL : thread_name.c_str());
1991
1992 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001993 // Check if the GDB server was able to provide the queue name, kind and serial number
1994 if (queue_vars_valid)
Jason Molenda77f89352016-01-12 07:09:16 +00001995 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 +00001996 else
1997 gdb_thread->ClearQueueInfo();
1998
Jason Molenda77f89352016-01-12 07:09:16 +00001999 gdb_thread->SetAssociatedWithLibdispatchQueue (associated_with_dispatch_queue);
2000
2001 if (dispatch_queue_t != LLDB_INVALID_ADDRESS)
2002 gdb_thread->SetQueueLibdispatchQueueAddress (dispatch_queue_t);
2003
Greg Clayton2e309072015-07-17 23:42:28 +00002004 // Make sure we update our thread stop reason just once
2005 if (!thread_sp->StopInfoIsUpToDate())
Greg Clayton358cf1e2015-06-25 21:46:34 +00002006 {
Greg Clayton2e309072015-07-17 23:42:28 +00002007 thread_sp->SetStopInfo (StopInfoSP());
Ryan Brown65d4d5c2015-09-16 21:20:44 +00002008 // If there's a memory thread backed by this thread, we need to use it to calcualte StopInfo.
2009 ThreadSP memory_thread_sp = m_thread_list.FindThreadByProtocolID(thread_sp->GetProtocolID());
2010 if (memory_thread_sp)
2011 thread_sp = memory_thread_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002012
Greg Clayton2e309072015-07-17 23:42:28 +00002013 if (exc_type != 0)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002014 {
Greg Clayton2e309072015-07-17 23:42:28 +00002015 const size_t exc_data_size = exc_data.size();
2016
2017 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
2018 exc_type,
2019 exc_data_size,
2020 exc_data_size >= 1 ? exc_data[0] : 0,
2021 exc_data_size >= 2 ? exc_data[1] : 0,
2022 exc_data_size >= 3 ? exc_data[2] : 0));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002023 }
Greg Clayton2e309072015-07-17 23:42:28 +00002024 else
Greg Clayton358cf1e2015-06-25 21:46:34 +00002025 {
Greg Clayton2e309072015-07-17 23:42:28 +00002026 bool handled = false;
2027 bool did_exec = false;
2028 if (!reason.empty())
Greg Clayton358cf1e2015-06-25 21:46:34 +00002029 {
Greg Clayton2e309072015-07-17 23:42:28 +00002030 if (reason.compare("trace") == 0)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002031 {
Pavel Labathef409122016-04-07 08:16:10 +00002032 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
2033 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2034
2035 // If the current pc is a breakpoint site then the StopInfo should be set to Breakpoint
2036 // Otherwise, it will be set to Trace.
2037 if (bp_site_sp && bp_site_sp->ValidForThisThread(thread_sp.get()))
2038 {
2039 thread_sp->SetStopInfo(
2040 StopInfo::CreateStopReasonWithBreakpointSiteID(*thread_sp, bp_site_sp->GetID()));
2041 }
2042 else
2043 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Greg Clayton2e309072015-07-17 23:42:28 +00002044 handled = true;
2045 }
2046 else if (reason.compare("breakpoint") == 0)
2047 {
Pavel Labathef409122016-04-07 08:16:10 +00002048 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
2049 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2050 if (bp_site_sp)
2051 {
2052 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2053 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2054 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2055 handled = true;
2056 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2057 {
2058 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2059 }
2060 else
2061 {
2062 StopInfoSP invalid_stop_info_sp;
2063 thread_sp->SetStopInfo (invalid_stop_info_sp);
2064 }
2065 }
Greg Clayton2e309072015-07-17 23:42:28 +00002066 }
2067 else if (reason.compare("trap") == 0)
2068 {
2069 // Let the trap just use the standard signal stop reason below...
2070 }
2071 else if (reason.compare("watchpoint") == 0)
2072 {
2073 StringExtractor desc_extractor(description.c_str());
2074 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
2075 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
Jaydeep Patil83143502015-08-13 03:44:09 +00002076 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
Greg Clayton2e309072015-07-17 23:42:28 +00002077 watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
2078 if (wp_addr != LLDB_INVALID_ADDRESS)
2079 {
Mohit K. Bhakkad6846bc82015-12-02 17:45:02 +00002080 WatchpointSP wp_sp;
2081 ArchSpec::Core core = GetTarget().GetArchitecture().GetCore();
Omair Javaid43507f52016-06-16 16:41:22 +00002082 if ((core >= ArchSpec::kCore_mips_first && core <= ArchSpec::kCore_mips_last) ||
Omair Javaidc6dc90e2016-06-27 11:18:23 +00002083 (core >= ArchSpec::eCore_arm_generic && core <= ArchSpec::eCore_arm_aarch64))
Mohit K. Bhakkad6846bc82015-12-02 17:45:02 +00002084 wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_hit_addr);
2085 if (!wp_sp)
2086 wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
Greg Clayton2e309072015-07-17 23:42:28 +00002087 if (wp_sp)
2088 {
2089 wp_sp->SetHardwareIndex(wp_index);
2090 watch_id = wp_sp->GetID();
2091 }
2092 }
2093 if (watch_id == LLDB_INVALID_WATCH_ID)
2094 {
2095 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_WATCHPOINTS));
2096 if (log) log->Printf ("failed to find watchpoint");
2097 }
Jaydeep Patil83143502015-08-13 03:44:09 +00002098 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id, wp_hit_addr));
Greg Clayton2e309072015-07-17 23:42:28 +00002099 handled = true;
2100 }
2101 else if (reason.compare("exception") == 0)
2102 {
2103 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
2104 handled = true;
2105 }
2106 else if (reason.compare("exec") == 0)
2107 {
2108 did_exec = true;
2109 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
2110 handled = true;
2111 }
2112 }
Pavel Labath3ce324a2016-04-06 09:10:29 +00002113 else if (!signo)
2114 {
Pavel Labathef409122016-04-07 08:16:10 +00002115 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
2116 lldb::BreakpointSiteSP bp_site_sp =
2117 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2118
Pavel Labath3ce324a2016-04-06 09:10:29 +00002119 // If the current pc is a breakpoint site then the StopInfo should be set to Breakpoint
2120 // even though the remote stub did not set it as such. This can happen when
2121 // the thread is involuntarily interrupted (e.g. due to stops on other
2122 // threads) just as it is about to execute the breakpoint instruction.
Pavel Labathef409122016-04-07 08:16:10 +00002123 if (bp_site_sp && bp_site_sp->ValidForThisThread(thread_sp.get()))
2124 {
2125 thread_sp->SetStopInfo(
2126 StopInfo::CreateStopReasonWithBreakpointSiteID(*thread_sp, bp_site_sp->GetID()));
Pavel Labath3ce324a2016-04-06 09:10:29 +00002127 handled = true;
Pavel Labathef409122016-04-07 08:16:10 +00002128 }
Pavel Labath3ce324a2016-04-06 09:10:29 +00002129 }
Greg Clayton2e309072015-07-17 23:42:28 +00002130
2131 if (!handled && signo && did_exec == false)
2132 {
2133 if (signo == SIGTRAP)
2134 {
2135 // Currently we are going to assume SIGTRAP means we are either
2136 // hitting a breakpoint or hardware single stepping.
2137 handled = true;
2138 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
2139 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2140
2141 if (bp_site_sp)
2142 {
2143 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2144 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2145 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2146 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2147 {
2148 if(m_breakpoint_pc_offset != 0)
2149 thread_sp->GetRegisterContext()->SetPC(pc);
2150 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2151 }
2152 else
2153 {
2154 StopInfoSP invalid_stop_info_sp;
2155 thread_sp->SetStopInfo (invalid_stop_info_sp);
2156 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002157 }
2158 else
2159 {
Greg Clayton2e309072015-07-17 23:42:28 +00002160 // If we were stepping then assume the stop was the result of the trace. If we were
2161 // not stepping then report the SIGTRAP.
2162 // FIXME: We are still missing the case where we single step over a trap instruction.
2163 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
2164 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
2165 else
2166 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo, description.c_str()));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002167 }
2168 }
Greg Clayton2e309072015-07-17 23:42:28 +00002169 if (!handled)
2170 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo, description.c_str()));
2171 }
2172
2173 if (!description.empty())
2174 {
2175 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
2176 if (stop_info_sp)
2177 {
2178 const char *stop_info_desc = stop_info_sp->GetDescription();
2179 if (!stop_info_desc || !stop_info_desc[0])
2180 stop_info_sp->SetDescription (description.c_str());
2181 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002182 else
2183 {
Greg Clayton2e309072015-07-17 23:42:28 +00002184 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002185 }
2186 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002187 }
2188 }
2189 }
2190 }
2191 return thread_sp;
2192}
2193
Greg Clayton2e309072015-07-17 23:42:28 +00002194lldb::ThreadSP
Greg Clayton358cf1e2015-06-25 21:46:34 +00002195ProcessGDBRemote::SetThreadStopInfo (StructuredData::Dictionary *thread_dict)
2196{
2197 static ConstString g_key_tid("tid");
2198 static ConstString g_key_name("name");
2199 static ConstString g_key_reason("reason");
2200 static ConstString g_key_metype("metype");
2201 static ConstString g_key_medata("medata");
2202 static ConstString g_key_qaddr("qaddr");
Jason Molenda77f89352016-01-12 07:09:16 +00002203 static ConstString g_key_dispatch_queue_t("dispatch_queue_t");
2204 static ConstString g_key_associated_with_dispatch_queue("associated_with_dispatch_queue");
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002205 static ConstString g_key_queue_name("qname");
2206 static ConstString g_key_queue_kind("qkind");
Jason Molenda26d84e82016-01-08 00:20:48 +00002207 static ConstString g_key_queue_serial_number("qserialnum");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002208 static ConstString g_key_registers("registers");
2209 static ConstString g_key_memory("memory");
2210 static ConstString g_key_address("address");
2211 static ConstString g_key_bytes("bytes");
2212 static ConstString g_key_description("description");
Pavel Labath4a4bb122015-07-16 14:14:35 +00002213 static ConstString g_key_signal("signal");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002214
2215 // Stop with signal and thread info
2216 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2217 uint8_t signo = 0;
2218 std::string value;
2219 std::string thread_name;
2220 std::string reason;
2221 std::string description;
2222 uint32_t exc_type = 0;
2223 std::vector<addr_t> exc_data;
2224 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2225 ExpeditedRegisterMap expedited_register_map;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002226 bool queue_vars_valid = false;
Jason Molenda77f89352016-01-12 07:09:16 +00002227 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2228 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002229 std::string queue_name;
2230 QueueKind queue_kind = eQueueKindUnknown;
Jason Molenda26d84e82016-01-08 00:20:48 +00002231 uint64_t queue_serial_number = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002232 // Iterate through all of the thread dictionary key/value pairs from the structured data dictionary
2233
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002234 thread_dict->ForEach([this,
2235 &tid,
2236 &expedited_register_map,
2237 &thread_name,
2238 &signo,
2239 &reason,
2240 &description,
2241 &exc_type,
2242 &exc_data,
2243 &thread_dispatch_qaddr,
2244 &queue_vars_valid,
Jason Molenda77f89352016-01-12 07:09:16 +00002245 &associated_with_dispatch_queue,
2246 &dispatch_queue_t,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002247 &queue_name,
2248 &queue_kind,
Jason Molenda26d84e82016-01-08 00:20:48 +00002249 &queue_serial_number]
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002250 (ConstString key, StructuredData::Object* object) -> bool
Greg Clayton358cf1e2015-06-25 21:46:34 +00002251 {
2252 if (key == g_key_tid)
2253 {
2254 // thread in big endian hex
2255 tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
2256 }
2257 else if (key == g_key_metype)
2258 {
2259 // exception type in big endian hex
2260 exc_type = object->GetIntegerValue(0);
2261 }
2262 else if (key == g_key_medata)
2263 {
2264 // exception data in big endian hex
2265 StructuredData::Array *array = object->GetAsArray();
2266 if (array)
2267 {
2268 array->ForEach([&exc_data](StructuredData::Object* object) -> bool {
2269 exc_data.push_back(object->GetIntegerValue());
2270 return true; // Keep iterating through all array items
2271 });
2272 }
2273 }
2274 else if (key == g_key_name)
2275 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002276 thread_name = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002277 }
2278 else if (key == g_key_qaddr)
2279 {
2280 thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
2281 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002282 else if (key == g_key_queue_name)
2283 {
2284 queue_vars_valid = true;
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002285 queue_name = object->GetStringValue();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002286 }
2287 else if (key == g_key_queue_kind)
2288 {
2289 std::string queue_kind_str = object->GetStringValue();
2290 if (queue_kind_str == "serial")
2291 {
2292 queue_vars_valid = true;
2293 queue_kind = eQueueKindSerial;
2294 }
2295 else if (queue_kind_str == "concurrent")
2296 {
2297 queue_vars_valid = true;
2298 queue_kind = eQueueKindConcurrent;
2299 }
2300 }
Jason Molenda26d84e82016-01-08 00:20:48 +00002301 else if (key == g_key_queue_serial_number)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002302 {
Jason Molenda26d84e82016-01-08 00:20:48 +00002303 queue_serial_number = object->GetIntegerValue(0);
2304 if (queue_serial_number != 0)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002305 queue_vars_valid = true;
2306 }
Jason Molenda77f89352016-01-12 07:09:16 +00002307 else if (key == g_key_dispatch_queue_t)
2308 {
2309 dispatch_queue_t = object->GetIntegerValue(0);
2310 if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS)
2311 queue_vars_valid = true;
2312 }
2313 else if (key == g_key_associated_with_dispatch_queue)
2314 {
2315 queue_vars_valid = true;
2316 bool associated = object->GetBooleanValue ();
2317 if (associated)
2318 associated_with_dispatch_queue = eLazyBoolYes;
2319 else
2320 associated_with_dispatch_queue = eLazyBoolNo;
2321 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002322 else if (key == g_key_reason)
2323 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002324 reason = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002325 }
2326 else if (key == g_key_description)
2327 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002328 description = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002329 }
2330 else if (key == g_key_registers)
2331 {
2332 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2333
2334 if (registers_dict)
2335 {
2336 registers_dict->ForEach([&expedited_register_map](ConstString key, StructuredData::Object* object) -> bool {
2337 const uint32_t reg = StringConvert::ToUInt32 (key.GetCString(), UINT32_MAX, 10);
2338 if (reg != UINT32_MAX)
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002339 expedited_register_map[reg] = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002340 return true; // Keep iterating through all array items
2341 });
2342 }
2343 }
2344 else if (key == g_key_memory)
2345 {
2346 StructuredData::Array *array = object->GetAsArray();
2347 if (array)
2348 {
2349 array->ForEach([this](StructuredData::Object* object) -> bool {
2350 StructuredData::Dictionary *mem_cache_dict = object->GetAsDictionary();
2351 if (mem_cache_dict)
2352 {
2353 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2354 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>("address", mem_cache_addr))
2355 {
2356 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
2357 {
2358 StringExtractor bytes;
2359 if (mem_cache_dict->GetValueForKeyAsString("bytes", bytes.GetStringRef()))
2360 {
2361 bytes.SetFilePos(0);
2362
2363 const size_t byte_size = bytes.GetStringRef().size()/2;
2364 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2365 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2366 if (bytes_copied == byte_size)
2367 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2368 }
2369 }
2370 }
2371 }
2372 return true; // Keep iterating through all array items
2373 });
2374 }
Eugene Zelenko0722f082015-10-24 01:28:05 +00002375
Greg Clayton358cf1e2015-06-25 21:46:34 +00002376 }
Pavel Labath4a4bb122015-07-16 14:14:35 +00002377 else if (key == g_key_signal)
2378 signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002379 return true; // Keep iterating through all dictionary key/value pairs
2380 });
2381
Greg Clayton2e309072015-07-17 23:42:28 +00002382 return SetThreadStopInfo (tid,
2383 expedited_register_map,
2384 signo,
2385 thread_name,
2386 reason,
2387 description,
2388 exc_type,
2389 exc_data,
2390 thread_dispatch_qaddr,
2391 queue_vars_valid,
Jason Molenda77f89352016-01-12 07:09:16 +00002392 associated_with_dispatch_queue,
2393 dispatch_queue_t,
Greg Clayton2e309072015-07-17 23:42:28 +00002394 queue_name,
2395 queue_kind,
Jason Molenda26d84e82016-01-08 00:20:48 +00002396 queue_serial_number);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002397}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002398
2399StateType
2400ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
2401{
Greg Claytondd0e5a52011-06-02 22:22:38 +00002402 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002403 const char stop_type = stop_packet.GetChar();
2404 switch (stop_type)
2405 {
2406 case 'T':
2407 case 'S':
2408 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00002409 // This is a bit of a hack, but is is required. If we did exec, we
2410 // need to clear our thread lists and also know to rebuild our dynamic
2411 // register info before we lookup and threads and populate the expedited
2412 // register values so we need to know this right away so we can cleanup
2413 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00002414 const uint32_t stop_id = GetStopID();
2415 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00002416 {
2417 // Our first stop, make sure we have a process ID, and also make
2418 // sure we know about our registers
2419 if (GetID() == LLDB_INVALID_PROCESS_ID)
2420 {
Greg Claytonc574ede2011-03-10 02:26:48 +00002421 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00002422 if (pid != LLDB_INVALID_PROCESS_ID)
2423 SetID (pid);
2424 }
2425 BuildDynamicRegisterInfo (true);
2426 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002427 // Stop with signal and thread info
Greg Clayton358cf1e2015-06-25 21:46:34 +00002428 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002429 const uint8_t signo = stop_packet.GetHexU8();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002430 std::string key;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002431 std::string value;
2432 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00002433 std::string reason;
2434 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002435 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00002436 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002437 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton0b90be12015-06-23 21:27:50 +00002438 bool queue_vars_valid = false; // says if locals below that start with "queue_" are valid
Jason Molenda77f89352016-01-12 07:09:16 +00002439 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2440 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
Greg Clayton0b90be12015-06-23 21:27:50 +00002441 std::string queue_name;
2442 QueueKind queue_kind = eQueueKindUnknown;
Jason Molenda26d84e82016-01-08 00:20:48 +00002443 uint64_t queue_serial_number = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002444 ExpeditedRegisterMap expedited_register_map;
2445 while (stop_packet.GetNameColonValue(key, value))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002446 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002447 if (key.compare("metype") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002448 {
2449 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002450 exc_type = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002451 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002452 else if (key.compare("medata") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002453 {
2454 // exception data in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002455 exc_data.push_back(StringConvert::ToUInt64 (value.c_str(), 0, 16));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002456 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002457 else if (key.compare("thread") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002458 {
2459 // thread in big endian hex
Greg Clayton358cf1e2015-06-25 21:46:34 +00002460 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002461 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002462 else if (key.compare("threads") == 0)
Greg Clayton9e920902012-04-10 02:25:43 +00002463 {
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00002464 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
2465
Greg Clayton9e920902012-04-10 02:25:43 +00002466 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00002467 // A comma separated list of all threads in the current
2468 // process that includes the thread for this stop reply
2469 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00002470 size_t comma_pos;
2471 lldb::tid_t tid;
2472 while ((comma_pos = value.find(',')) != std::string::npos)
2473 {
2474 value[comma_pos] = '\0';
2475 // thread in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002476 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00002477 if (tid != LLDB_INVALID_THREAD_ID)
2478 m_thread_ids.push_back (tid);
2479 value.erase(0, comma_pos + 1);
Greg Clayton9e920902012-04-10 02:25:43 +00002480 }
Vince Harron5275aaa2015-01-15 20:08:35 +00002481 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00002482 if (tid != LLDB_INVALID_THREAD_ID)
2483 m_thread_ids.push_back (tid);
2484 }
Jason Molenda545304d2015-12-18 00:45:35 +00002485 else if (key.compare("thread-pcs") == 0)
2486 {
2487 m_thread_pcs.clear();
2488 // A comma separated list of all threads in the current
2489 // process that includes the thread for this stop reply
2490 // packet
2491 size_t comma_pos;
2492 lldb::addr_t pc;
2493 while ((comma_pos = value.find(',')) != std::string::npos)
2494 {
2495 value[comma_pos] = '\0';
2496 // thread in big endian hex
2497 pc = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
2498 if (pc != LLDB_INVALID_ADDRESS)
2499 m_thread_pcs.push_back (pc);
2500 value.erase(0, comma_pos + 1);
2501 }
2502 pc = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
2503 if (pc != LLDB_INVALID_ADDRESS)
2504 m_thread_pcs.push_back (pc);
2505 }
Greg Clayton2e309072015-07-17 23:42:28 +00002506 else if (key.compare("jstopinfo") == 0)
Greg Claytona5801ad2015-07-15 22:59:03 +00002507 {
2508 StringExtractor json_extractor;
2509 // Swap "value" over into "name_extractor"
2510 json_extractor.GetStringRef().swap(value);
2511 // Now convert the HEX bytes into a string value
2512 json_extractor.GetHexByteString (value);
2513
2514 // This JSON contains thread IDs and thread stop info for all threads.
2515 // It doesn't contain expedited registers, memory or queue info.
Greg Clayton2e309072015-07-17 23:42:28 +00002516 m_jstopinfo_sp = StructuredData::ParseJSON (value);
Greg Claytona5801ad2015-07-15 22:59:03 +00002517 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002518 else if (key.compare("hexname") == 0)
Greg Claytonde9d0492011-01-08 03:17:57 +00002519 {
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 thread_name.swap (value);
2526 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002527 else if (key.compare("name") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002528 {
2529 thread_name.swap (value);
2530 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002531 else if (key.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002532 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002533 thread_dispatch_qaddr = StringConvert::ToUInt64 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002534 }
Jason Molenda77f89352016-01-12 07:09:16 +00002535 else if (key.compare("dispatch_queue_t") == 0)
2536 {
2537 queue_vars_valid = true;
2538 dispatch_queue_t = StringConvert::ToUInt64 (value.c_str(), 0, 16);
2539 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002540 else if (key.compare("qname") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002541 {
2542 queue_vars_valid = true;
2543 StringExtractor name_extractor;
2544 // Swap "value" over into "name_extractor"
2545 name_extractor.GetStringRef().swap(value);
2546 // Now convert the HEX bytes into a string value
2547 name_extractor.GetHexByteString (value);
2548 queue_name.swap (value);
2549 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002550 else if (key.compare("qkind") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002551 {
Greg Clayton0b90be12015-06-23 21:27:50 +00002552 if (value == "serial")
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002553 {
2554 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002555 queue_kind = eQueueKindSerial;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002556 }
Greg Clayton0b90be12015-06-23 21:27:50 +00002557 else if (value == "concurrent")
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002558 {
2559 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002560 queue_kind = eQueueKindConcurrent;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002561 }
Greg Clayton0b90be12015-06-23 21:27:50 +00002562 }
Jason Molenda26d84e82016-01-08 00:20:48 +00002563 else if (key.compare("qserialnum") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002564 {
Jason Molenda26d84e82016-01-08 00:20:48 +00002565 queue_serial_number = StringConvert::ToUInt64 (value.c_str(), 0, 0);
2566 if (queue_serial_number != 0)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002567 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002568 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002569 else if (key.compare("reason") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002570 {
2571 reason.swap(value);
2572 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002573 else if (key.compare("description") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002574 {
2575 StringExtractor desc_extractor;
2576 // Swap "value" over into "name_extractor"
2577 desc_extractor.GetStringRef().swap(value);
2578 // Now convert the HEX bytes into a string value
Chaoren Lin28e57422015-02-03 01:51:25 +00002579 desc_extractor.GetHexByteString (value);
2580 description.swap(value);
Greg Claytona658fd22011-06-04 01:26:29 +00002581 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002582 else if (key.compare("memory") == 0)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002583 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002584 // Expedited memory. GDB servers can choose to send back expedited memory
2585 // that can populate the L1 memory cache in the process so that things like
2586 // the frame pointer backchain can be expedited. This will help stack
2587 // backtracing be more efficient by not having to send as many memory read
2588 // requests down the remote GDB server.
Chaoren Lin7a306082015-06-23 03:17:01 +00002589
Greg Clayton358cf1e2015-06-25 21:46:34 +00002590 // Key/value pair format: memory:<addr>=<bytes>;
2591 // <addr> is a number whose base will be interpreted by the prefix:
2592 // "0x[0-9a-fA-F]+" for hex
2593 // "0[0-7]+" for octal
2594 // "[1-9]+" for decimal
2595 // <bytes> is native endian ASCII hex bytes just like the register values
2596 llvm::StringRef value_ref(value);
2597 std::pair<llvm::StringRef, llvm::StringRef> pair;
2598 pair = value_ref.split('=');
2599 if (!pair.first.empty() && !pair.second.empty())
2600 {
2601 std::string addr_str(pair.first.str());
2602 const lldb::addr_t mem_cache_addr = StringConvert::ToUInt64(addr_str.c_str(), LLDB_INVALID_ADDRESS, 0);
2603 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002604 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002605 StringExtractor bytes;
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002606 bytes.GetStringRef() = pair.second.str();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002607 const size_t byte_size = bytes.GetStringRef().size()/2;
2608 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2609 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2610 if (bytes_copied == byte_size)
2611 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
Greg Clayton3e06bd92011-01-09 21:07:35 +00002612 }
2613 }
2614 }
Jaydeep Patil725666c2015-08-13 03:46:01 +00002615 else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 || key.compare("awatch") == 0)
2616 {
2617 // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2618 lldb::addr_t wp_addr = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
2619 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2620 uint32_t wp_index = LLDB_INVALID_INDEX32;
2621
2622 if (wp_sp)
2623 wp_index = wp_sp->GetHardwareIndex();
2624
2625 reason = "watchpoint";
2626 StreamString ostr;
2627 ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
2628 description = ostr.GetString().c_str();
2629 }
Stephane Sezer2618e912015-08-21 16:51:56 +00002630 else if (key.compare("library") == 0)
2631 {
2632 LoadModules();
2633 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002634 else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1]))
2635 {
2636 uint32_t reg = StringConvert::ToUInt32 (key.c_str(), UINT32_MAX, 16);
2637 if (reg != UINT32_MAX)
2638 expedited_register_map[reg] = std::move(value);
2639 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002640 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002641
Bhushan D. Attarde1e271df2015-07-24 04:06:20 +00002642 if (tid == LLDB_INVALID_THREAD_ID)
2643 {
Ed Maste81b4c5f2016-01-04 01:43:47 +00002644 // 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 +00002645 // thread information. So update the thread list and choose the first one.
2646 UpdateThreadIDList ();
Ed Maste81b4c5f2016-01-04 01:43:47 +00002647
Bhushan D. Attarde1e271df2015-07-24 04:06:20 +00002648 if (!m_thread_ids.empty ())
2649 {
2650 tid = m_thread_ids.front ();
2651 }
2652 }
2653
Greg Clayton358cf1e2015-06-25 21:46:34 +00002654 ThreadSP thread_sp = SetThreadStopInfo (tid,
2655 expedited_register_map,
2656 signo,
2657 thread_name,
2658 reason,
2659 description,
2660 exc_type,
2661 exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002662 thread_dispatch_qaddr,
2663 queue_vars_valid,
Jason Molenda77f89352016-01-12 07:09:16 +00002664 associated_with_dispatch_queue,
2665 dispatch_queue_t,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002666 queue_name,
2667 queue_kind,
Jason Molenda26d84e82016-01-08 00:20:48 +00002668 queue_serial_number);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002669
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002670 return eStateStopped;
2671 }
2672 break;
2673
2674 case 'W':
Todd Fialaff6131a2014-05-19 04:57:23 +00002675 case 'X':
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002676 // process exited
2677 return eStateExited;
2678
2679 default:
2680 break;
2681 }
2682 return eStateInvalid;
2683}
2684
2685void
2686ProcessGDBRemote::RefreshStateAfterStop ()
2687{
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00002688 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
2689
Greg Clayton9e920902012-04-10 02:25:43 +00002690 m_thread_ids.clear();
Jason Molenda545304d2015-12-18 00:45:35 +00002691 m_thread_pcs.clear();
Greg Clayton9e920902012-04-10 02:25:43 +00002692 // Set the thread stop info. It might have a "threads" key whose value is
2693 // a list of all thread IDs in the current process, so m_thread_ids might
2694 // get set.
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002695
2696 // Scope for the lock
2697 {
2698 // Lock the thread stack while we access it
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +00002699 std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002700 // Get the number of stop packets on the stack
2701 int nItems = m_stop_packet_stack.size();
2702 // Iterate over them
2703 for (int i = 0; i < nItems; i++)
2704 {
2705 // Get the thread stop info
2706 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2707 // Process thread stop info
2708 SetThreadStopInfo(stop_info);
2709 }
2710 // Clear the thread stop stack
2711 m_stop_packet_stack.clear();
2712 }
2713
Greg Clayton9e920902012-04-10 02:25:43 +00002714 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2715 if (m_thread_ids.empty())
2716 {
2717 // No, we need to fetch the thread list manually
2718 UpdateThreadIDList();
2719 }
2720
Ewan Crawford78baa192015-05-13 09:18:18 +00002721 // If we have queried for a default thread id
2722 if (m_initial_tid != LLDB_INVALID_THREAD_ID)
2723 {
2724 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2725 m_initial_tid = LLDB_INVALID_THREAD_ID;
2726 }
2727
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002728 // Let all threads recover from stopping and do any clean up based
2729 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002730 m_thread_list_real.RefreshStateAfterStop();
Ed Maste81b4c5f2016-01-04 01:43:47 +00002731
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002732}
2733
2734Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002735ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002736{
2737 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002738
Greg Clayton513c26c2011-01-29 07:10:55 +00002739 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002740 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002741 // We are being asked to halt during an attach. We need to just close
2742 // our file handle and debugserver will go away, and we can be done...
2743 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00002744 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002745 else
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00002746 caused_stop = m_gdb_comm.Interrupt();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002747 return error;
2748}
2749
2750Error
Jim Inghamacff8952013-05-02 00:27:30 +00002751ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002752{
2753 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002754 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00002755 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00002756 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
Ed Maste81b4c5f2016-01-04 01:43:47 +00002757
Jim Inghamacff8952013-05-02 00:27:30 +00002758 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002759 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002760 {
Jim Inghamacff8952013-05-02 00:27:30 +00002761 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002762 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
2763 else
Jim Inghamacff8952013-05-02 00:27:30 +00002764 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00002765 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00002766
Jim Inghamacff8952013-05-02 00:27:30 +00002767 if (!error.Success())
2768 return error;
2769
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002770 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00002771 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002772
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002773 SetPrivateState (eStateDetached);
2774 ResumePrivateStateThread();
2775
2776 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00002777 return error;
2778}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002779
Eugene Zelenko0722f082015-10-24 01:28:05 +00002780
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002781Error
2782ProcessGDBRemote::DoDestroy ()
2783{
2784 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002785 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002786 if (log)
2787 log->Printf ("ProcessGDBRemote::DoDestroy()");
2788
Jim Ingham43c555d2012-07-04 00:35:43 +00002789 // There is a bug in older iOS debugservers where they don't shut down the process
2790 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
2791 // this can cause problems with restarting. So we check to see if any of our threads are stopped
2792 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
2793 // destroy it again.
2794 //
2795 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
2796 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
2797 // the debugservers with this bug are equal. There really should be a better way to test this!
2798 //
2799 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
2800 // get called here to destroy again and we're still at a breakpoint or exception, then we should
2801 // just do the straight-forward kill.
2802 //
2803 // And of course, if we weren't able to stop the process by the time we get here, it isn't
2804 // necessary (or helpful) to do any of this.
2805
2806 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
2807 {
2808 PlatformSP platform_sp = GetTarget().GetPlatform();
Ed Maste81b4c5f2016-01-04 01:43:47 +00002809
Jim Ingham43c555d2012-07-04 00:35:43 +00002810 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2811 if (platform_sp
2812 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00002813 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00002814 {
2815 if (m_destroy_tried_resuming)
2816 {
2817 if (log)
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002818 log->PutCString ("ProcessGDBRemote::DoDestroy() - Tried resuming to destroy once already, not doing it again.");
Jim Ingham43c555d2012-07-04 00:35:43 +00002819 }
2820 else
Ed Maste81b4c5f2016-01-04 01:43:47 +00002821 {
Jim Ingham43c555d2012-07-04 00:35:43 +00002822 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
2823 // but we really need it to happen here and it doesn't matter if we do it twice.
2824 m_thread_list.DiscardThreadPlans();
2825 DisableAllBreakpointSites();
Ed Maste81b4c5f2016-01-04 01:43:47 +00002826
Jim Ingham43c555d2012-07-04 00:35:43 +00002827 bool stop_looks_like_crash = false;
2828 ThreadList &threads = GetThreadList();
Ed Maste81b4c5f2016-01-04 01:43:47 +00002829
Jim Ingham43c555d2012-07-04 00:35:43 +00002830 {
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00002831 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
Ed Maste81b4c5f2016-01-04 01:43:47 +00002832
Jim Ingham43c555d2012-07-04 00:35:43 +00002833 size_t num_threads = threads.GetSize();
2834 for (size_t i = 0; i < num_threads; i++)
2835 {
2836 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002837 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002838 StopReason reason = eStopReasonInvalid;
2839 if (stop_info_sp)
2840 reason = stop_info_sp->GetStopReason();
2841 if (reason == eStopReasonBreakpoint
2842 || reason == eStopReasonException)
2843 {
2844 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002845 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
2846 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00002847 stop_info_sp->GetDescription());
2848 stop_looks_like_crash = true;
2849 break;
2850 }
2851 }
2852 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00002853
Jim Ingham43c555d2012-07-04 00:35:43 +00002854 if (stop_looks_like_crash)
2855 {
2856 if (log)
2857 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
2858 m_destroy_tried_resuming = true;
Ed Maste81b4c5f2016-01-04 01:43:47 +00002859
2860 // 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 +00002861 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
2862 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
2863 // have to run the risk of letting those threads proceed a bit.
Ed Maste81b4c5f2016-01-04 01:43:47 +00002864
Jim Ingham43c555d2012-07-04 00:35:43 +00002865 {
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00002866 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
Ed Maste81b4c5f2016-01-04 01:43:47 +00002867
Jim Ingham43c555d2012-07-04 00:35:43 +00002868 size_t num_threads = threads.GetSize();
2869 for (size_t i = 0; i < num_threads; i++)
2870 {
2871 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002872 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002873 StopReason reason = eStopReasonInvalid;
2874 if (stop_info_sp)
2875 reason = stop_info_sp->GetStopReason();
2876 if (reason != eStopReasonBreakpoint
2877 && reason != eStopReasonException)
2878 {
2879 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002880 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
2881 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00002882 thread_sp->SetResumeState(eStateSuspended);
2883 }
2884 }
2885 }
2886 Resume ();
Jason Molendaede31932015-04-17 05:01:58 +00002887 return Destroy(false);
Jim Ingham43c555d2012-07-04 00:35:43 +00002888 }
2889 }
2890 }
2891 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00002892
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002893 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00002894 int exit_status = SIGABRT;
2895 std::string exit_string;
2896
Greg Clayton6ed95942011-01-22 07:12:45 +00002897 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002898 {
Jim Inghamaab78372011-10-28 01:11:35 +00002899 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00002900 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002901 StringExtractorGDBRemote response;
2902 bool send_async = true;
Tamas Berghammer912800c2015-02-24 10:23:39 +00002903 GDBRemoteCommunication::ScopedTimeout (m_gdb_comm, 3);
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002904
Greg Clayton3dedae12013-12-06 21:45:27 +00002905 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton513c26c2011-01-29 07:10:55 +00002906 {
2907 char packet_cmd = response.GetChar(0);
2908
2909 if (packet_cmd == 'W' || packet_cmd == 'X')
2910 {
Jim Inghameac0aa42014-02-21 22:36:11 +00002911#if defined(__APPLE__)
Jason Molenda17b45392016-06-23 04:24:16 +00002912 // 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 +00002913 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill
Jason Molenda17b45392016-06-23 04:24:16 +00002914 // 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 +00002915 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap
2916 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of
2917 // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2918 // Anyway, so call waitpid here to finally reap it.
2919 PlatformSP platform_sp(GetTarget().GetPlatform());
2920 if (platform_sp && platform_sp->IsHost())
2921 {
2922 int status;
2923 ::pid_t reap_pid;
2924 reap_pid = waitpid (GetID(), &status, WNOHANG);
2925 if (log)
2926 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2927 }
2928#endif
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002929 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002930 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00002931 exit_status = response.GetHexU8();
2932 }
2933 else
2934 {
2935 if (log)
2936 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2937 exit_string.assign("got unexpected response to k packet: ");
2938 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00002939 }
2940 }
2941 else
2942 {
Jim Inghambabfc382012-06-06 00:32:39 +00002943 if (log)
2944 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2945 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00002946 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002947 }
Jim Inghambabfc382012-06-06 00:32:39 +00002948 else
2949 {
2950 if (log)
Ed Masteb3a53332014-03-17 17:05:22 +00002951 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching");
Jim Inghamcfc09352012-07-27 23:57:19 +00002952 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00002953 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002954 }
Jim Inghambabfc382012-06-06 00:32:39 +00002955 else
2956 {
2957 // If we missed setting the exit status on the way out, do it here.
2958 // NB set exit status can be called multiple times, the first one sets the status.
2959 exit_string.assign("destroying when not connected to debugserver");
2960 }
2961
2962 SetExitStatus(exit_status, exit_string.c_str());
2963
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002964 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002965 KillDebugserverProcess ();
2966 return error;
2967}
2968
Greg Clayton8cda7f02013-05-21 21:55:59 +00002969void
2970ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2971{
Greg Clayton8cda7f02013-05-21 21:55:59 +00002972 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2973 if (did_exec)
2974 {
2975 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2976 if (log)
2977 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2978
2979 m_thread_list_real.Clear();
2980 m_thread_list.Clear();
2981 BuildDynamicRegisterInfo (true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002982 m_gdb_comm.ResetDiscoverableSettings (did_exec);
Greg Clayton8cda7f02013-05-21 21:55:59 +00002983 }
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002984
2985 // Scope the lock
2986 {
2987 // Lock the thread stack while we access it
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +00002988 std::lock_guard<std::recursive_mutex> guard(m_last_stop_packet_mutex);
Greg Clayton2e309072015-07-17 23:42:28 +00002989
2990 // We are are not using non-stop mode, there can only be one last stop
2991 // reply packet, so clear the list.
2992 if (GetTarget().GetNonStopModeEnabled() == false)
2993 m_stop_packet_stack.clear();
2994
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002995 // Add this stop packet to the stop packet stack
2996 // This stack will get popped and examined when we switch to the
2997 // Stopped state
2998 m_stop_packet_stack.push_back(response);
2999 }
Greg Clayton8cda7f02013-05-21 21:55:59 +00003000}
3001
Chaoren Linc963a222015-09-01 16:58:45 +00003002void
3003ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp)
3004{
3005 Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
3006}
3007
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003008//------------------------------------------------------------------
3009// Process Queries
3010//------------------------------------------------------------------
3011
3012bool
3013ProcessGDBRemote::IsAlive ()
3014{
Jason Molenda1d3b3562015-11-05 23:54:29 +00003015 return m_gdb_comm.IsConnected() && Process::IsAlive();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003016}
3017
3018addr_t
3019ProcessGDBRemote::GetImageInfoAddress()
3020{
Aidan Doddsc0c83852015-05-08 09:36:31 +00003021 // request the link map address via the $qShlibInfoAddr packet
3022 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
3023
3024 // the loaded module list can also provides a link map address
3025 if (addr == LLDB_INVALID_ADDRESS)
3026 {
Stephane Sezer87b0fe02016-01-12 19:02:41 +00003027 LoadedModuleInfoList list;
Aidan Doddsc0c83852015-05-08 09:36:31 +00003028 if (GetLoadedModuleList (list).Success())
3029 addr = list.m_link_map;
3030 }
3031
3032 return addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003033}
3034
Greg Clayton2e309072015-07-17 23:42:28 +00003035void
3036ProcessGDBRemote::WillPublicStop ()
3037{
3038 // See if the GDB remote client supports the JSON threads info.
3039 // If so, we gather stop info for all threads, expedited registers,
3040 // expedited memory, runtime queue information (iOS and MacOSX only),
3041 // and more. Expediting memory will help stack backtracing be much
3042 // faster. Expediting registers will make sure we don't have to read
3043 // the thread registers for GPRs.
3044 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
3045
3046 if (m_jthreadsinfo_sp)
3047 {
3048 // Now set the stop info for each thread and also expedite any registers
3049 // and memory that was in the jThreadsInfo response.
3050 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
3051 if (thread_infos)
3052 {
3053 const size_t n = thread_infos->GetSize();
3054 for (size_t i=0; i<n; ++i)
3055 {
3056 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
3057 if (thread_dict)
3058 SetThreadStopInfo(thread_dict);
3059 }
3060 }
3061 }
3062}
3063
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003064//------------------------------------------------------------------
3065// Process Memory
3066//------------------------------------------------------------------
3067size_t
3068ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
3069{
Jason Molenda6076bf42014-05-06 04:34:52 +00003070 GetMaxMemorySize ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003071 if (size > m_max_memory_size)
3072 {
3073 // Keep memory read sizes down to a sane limit. This function will be
Ed Maste81b4c5f2016-01-04 01:43:47 +00003074 // called multiple times in order to complete the task by
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003075 // lldb_private::Process so it is ok to do this.
3076 size = m_max_memory_size;
3077 }
3078
3079 char packet[64];
Jason Molenda6076bf42014-05-06 04:34:52 +00003080 int packet_len;
3081 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
Pavel Labath3bf11252015-10-14 12:59:37 +00003082 packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64,
3083 binary_memory_read ? 'x' : 'm', (uint64_t)addr, (uint64_t)size);
Andy Gibbsa297a972013-06-19 19:04:53 +00003084 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003085 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003086 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003087 {
Greg Clayton576d8832011-03-22 04:00:09 +00003088 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003089 {
3090 error.Clear();
Jason Molenda6076bf42014-05-06 04:34:52 +00003091 if (binary_memory_read)
3092 {
3093 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any
3094 // 0x7d character escaping that was present in the packet
3095
3096 size_t data_received_size = response.GetBytesLeft();
3097 if (data_received_size > size)
3098 {
3099 // Don't write past the end of BUF if the remote debug server gave us too
3100 // much data for some reason.
3101 data_received_size = size;
3102 }
3103 memcpy (buf, response.GetStringRef().data(), data_received_size);
3104 return data_received_size;
3105 }
3106 else
3107 {
3108 return response.GetHexBytes(buf, size, '\xdd');
3109 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003110 }
Greg Clayton576d8832011-03-22 04:00:09 +00003111 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00003112 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00003113 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00003114 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003115 else
Greg Clayton9944cd72012-09-19 01:46:31 +00003116 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003117 }
3118 else
3119 {
Jim Ingham35579dd2013-06-03 19:34:01 +00003120 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003121 }
3122 return 0;
3123}
3124
3125size_t
3126ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
3127{
Jason Molenda6076bf42014-05-06 04:34:52 +00003128 GetMaxMemorySize ();
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00003129 if (size > m_max_memory_size)
3130 {
3131 // Keep memory read sizes down to a sane limit. This function will be
Ed Maste81b4c5f2016-01-04 01:43:47 +00003132 // called multiple times in order to complete the task by
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00003133 // lldb_private::Process so it is ok to do this.
3134 size = m_max_memory_size;
3135 }
3136
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003137 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00003138 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Bruce Mitchener9ccb9702015-11-07 04:40:13 +00003139 packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(), endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003140 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003141 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003142 {
Greg Clayton576d8832011-03-22 04:00:09 +00003143 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003144 {
3145 error.Clear();
3146 return size;
3147 }
Greg Clayton576d8832011-03-22 04:00:09 +00003148 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00003149 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00003150 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00003151 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003152 else
Greg Clayton9944cd72012-09-19 01:46:31 +00003153 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 +00003154 }
3155 else
3156 {
Jim Ingham35579dd2013-06-03 19:34:01 +00003157 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003158 }
3159 return 0;
3160}
3161
3162lldb::addr_t
3163ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
3164{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003165 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_EXPRESSIONS));
Greg Clayton2a48f522011-05-14 01:50:35 +00003166 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
Ed Maste81b4c5f2016-01-04 01:43:47 +00003167
Greg Claytoncec91ef2016-02-26 01:20:20 +00003168 if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo)
Greg Clayton2a48f522011-05-14 01:50:35 +00003169 {
Greg Claytoncec91ef2016-02-26 01:20:20 +00003170 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
3171 if (allocated_addr != LLDB_INVALID_ADDRESS || m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes)
3172 return allocated_addr;
3173 }
Greg Clayton2a48f522011-05-14 01:50:35 +00003174
Greg Claytoncec91ef2016-02-26 01:20:20 +00003175 if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo)
3176 {
3177 // Call mmap() to create memory in the inferior..
3178 unsigned prot = 0;
3179 if (permissions & lldb::ePermissionsReadable)
3180 prot |= eMmapProtRead;
3181 if (permissions & lldb::ePermissionsWritable)
3182 prot |= eMmapProtWrite;
3183 if (permissions & lldb::ePermissionsExecutable)
3184 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00003185
Greg Claytoncec91ef2016-02-26 01:20:20 +00003186 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
3187 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
3188 m_addr_to_mmap_size[allocated_addr] = size;
3189 else
3190 {
3191 allocated_addr = LLDB_INVALID_ADDRESS;
3192 if (log)
3193 log->Printf ("ProcessGDBRemote::%s no direct stub support for memory allocation, and InferiorCallMmap also failed - is stub missing register context save/restore capability?", __FUNCTION__);
3194 }
Greg Clayton2a48f522011-05-14 01:50:35 +00003195 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00003196
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003197 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00003198 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003199 else
3200 error.Clear();
3201 return allocated_addr;
3202}
3203
3204Error
Ed Maste81b4c5f2016-01-04 01:43:47 +00003205ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
Greg Clayton46fb5582011-11-18 07:03:08 +00003206 MemoryRegionInfo &region_info)
3207{
Ed Maste81b4c5f2016-01-04 01:43:47 +00003208
Greg Clayton46fb5582011-11-18 07:03:08 +00003209 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
3210 return error;
3211}
3212
3213Error
Johnny Chen64637202012-05-23 21:09:52 +00003214ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
3215{
Ed Maste81b4c5f2016-01-04 01:43:47 +00003216
Johnny Chen64637202012-05-23 21:09:52 +00003217 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
3218 return error;
3219}
3220
3221Error
Enrico Granataf04a2192012-07-13 23:18:48 +00003222ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
3223{
Jaydeep Patil725666c2015-08-13 03:46:01 +00003224 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after, GetTarget().GetArchitecture()));
Enrico Granataf04a2192012-07-13 23:18:48 +00003225 return error;
3226}
3227
3228Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003229ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
3230{
Ed Maste81b4c5f2016-01-04 01:43:47 +00003231 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00003232 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
3233
3234 switch (supported)
3235 {
3236 case eLazyBoolCalculate:
Ed Maste81b4c5f2016-01-04 01:43:47 +00003237 // We should never be deallocating memory without allocating memory
Greg Clayton70b57652011-05-15 01:25:55 +00003238 // first so we should never get eLazyBoolCalculate
3239 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
3240 break;
3241
3242 case eLazyBoolYes:
3243 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00003244 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003245 break;
Ed Maste81b4c5f2016-01-04 01:43:47 +00003246
Greg Clayton70b57652011-05-15 01:25:55 +00003247 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003248 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00003249 {
3250 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003251 if (pos != m_addr_to_mmap_size.end() &&
3252 InferiorCallMunmap(this, addr, pos->second))
3253 m_addr_to_mmap_size.erase (pos);
3254 else
Daniel Malead01b2952012-11-29 21:49:15 +00003255 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003256 }
3257 break;
3258 }
3259
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003260 return error;
3261}
3262
Eugene Zelenko0722f082015-10-24 01:28:05 +00003263
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003264//------------------------------------------------------------------
3265// Process STDIO
3266//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003267size_t
3268ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
3269{
3270 if (m_stdio_communication.IsConnected())
3271 {
3272 ConnectionStatus status;
3273 m_stdio_communication.Write(src, src_len, status, NULL);
3274 }
Vince Harrondf3f00f2015-02-10 21:09:04 +00003275 else if (m_stdin_forward)
Vince Harrone0be4252015-02-06 18:32:57 +00003276 {
3277 m_gdb_comm.SendStdinNotification(src, src_len);
3278 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003279 return 0;
3280}
3281
3282Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003283ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003284{
3285 Error error;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003286 assert(bp_site != NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003287
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003288 // Get logging info
3289 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003290 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003291
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003292 // Get the breakpoint address
3293 const addr_t addr = bp_site->GetLoadAddress();
3294
3295 // Log that a breakpoint was requested
3296 if (log)
3297 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
3298
3299 // Breakpoint already exists and is enabled
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003300 if (bp_site->IsEnabled())
3301 {
3302 if (log)
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003303 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 +00003304 return error;
3305 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003306
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003307 // Get the software breakpoint trap opcode size
3308 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3309
3310 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
3311 // is supported by the remote stub. These are set to true by default, and later set to false
3312 // only after we receive an unimplemented response when sending a breakpoint packet. This means
3313 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
3314 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
3315 // indicates if the user specifically asked for hardware breakpoints. If true then we will
3316 // skip over software breakpoints.
3317 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
3318 {
3319 // Try to send off a software breakpoint packet ($Z0)
Jim Ingham906d91e2016-05-19 02:13:44 +00003320 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size);
3321 if (error_no == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003322 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003323 // The breakpoint was placed successfully
3324 bp_site->SetEnabled(true);
3325 bp_site->SetType(BreakpointSite::eExternal);
Greg Claytoneb023e72013-10-11 19:48:25 +00003326 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003327 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003328
3329 // SendGDBStoppointTypePacket() will return an error if it was unable to set this
3330 // breakpoint. We need to differentiate between a error specific to placing this breakpoint
3331 // or if we have learned that this breakpoint type is unsupported. To do this, we
3332 // must test the support boolean for this breakpoint type to see if it now indicates that
3333 // this breakpoint type is unsupported. If they are still supported then we should return
3334 // with the error code. If they are now unsupported, then we would like to fall through
3335 // and try another form of breakpoint.
3336 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
Jim Ingham906d91e2016-05-19 02:13:44 +00003337 {
3338 if (error_no != UINT8_MAX)
3339 error.SetErrorStringWithFormat("error: %d sending the breakpoint request", errno);
3340 else
3341 error.SetErrorString("error sending the breakpoint request");
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003342 return error;
Jim Ingham906d91e2016-05-19 02:13:44 +00003343 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003344
3345 // We reach here when software breakpoints have been found to be unsupported. For future
3346 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
3347 // known not to be supported.
3348 if (log)
3349 log->Printf("Software breakpoints are unsupported");
3350
3351 // So we will fall through and try a hardware breakpoint
3352 }
3353
3354 // The process of setting a hardware breakpoint is much the same as above. We check the
3355 // supported boolean for this breakpoint type, and if it is thought to be supported then we
3356 // will try to set this breakpoint with a hardware breakpoint.
3357 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3358 {
3359 // Try to send off a hardware breakpoint packet ($Z1)
Jim Ingham906d91e2016-05-19 02:13:44 +00003360 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size);
3361 if (error_no == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003362 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003363 // The breakpoint was placed successfully
3364 bp_site->SetEnabled(true);
3365 bp_site->SetType(BreakpointSite::eHardware);
3366 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003367 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003368
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003369 // Check if the error was something other then an unsupported breakpoint type
3370 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3371 {
3372 // Unable to set this hardware breakpoint
Jim Ingham906d91e2016-05-19 02:13:44 +00003373 if (error_no != UINT8_MAX)
3374 error.SetErrorStringWithFormat("error: %d sending the hardware breakpoint request "
3375 "(hardware breakpoint resources might be exhausted or unavailable)",
3376 error_no);
3377 else
3378 error.SetErrorString("error sending the hardware breakpoint request (hardware breakpoint resources "
3379 "might be exhausted or unavailable)");
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003380 return error;
3381 }
3382
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003383 // We will reach here when the stub gives an unsupported response to a hardware breakpoint
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003384 if (log)
3385 log->Printf("Hardware breakpoints are unsupported");
3386
3387 // Finally we will falling through to a #trap style breakpoint
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003388 }
3389
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003390 // Don't fall through when hardware breakpoints were specifically requested
3391 if (bp_site->HardwareRequired())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003392 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003393 error.SetErrorString("hardware breakpoints are not supported");
3394 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003395 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003396
3397 // As a last resort we want to place a manual breakpoint. An instruction
3398 // is placed into the process memory using memory write packets.
3399 return EnableSoftwareBreakpoint(bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003400}
3401
3402Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003403ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003404{
3405 Error error;
3406 assert (bp_site != NULL);
3407 addr_t addr = bp_site->GetLoadAddress();
3408 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00003409 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003410 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003411 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003412
3413 if (bp_site->IsEnabled())
3414 {
3415 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
3416
Greg Clayton8b82f082011-04-12 05:54:46 +00003417 BreakpointSite::Type bp_type = bp_site->GetType();
3418 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003419 {
Greg Clayton8b82f082011-04-12 05:54:46 +00003420 case BreakpointSite::eSoftware:
3421 error = DisableSoftwareBreakpoint (bp_site);
3422 break;
3423
3424 case BreakpointSite::eHardware:
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003425 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003426 error.SetErrorToGenericError();
3427 break;
3428
3429 case BreakpointSite::eExternal:
Jim Inghama04ef752014-03-07 11:18:02 +00003430 {
3431 GDBStoppointType stoppoint_type;
3432 if (bp_site->IsHardware())
3433 stoppoint_type = eBreakpointHardware;
3434 else
3435 stoppoint_type = eBreakpointSoftware;
Ed Maste81b4c5f2016-01-04 01:43:47 +00003436
Jim Inghama04ef752014-03-07 11:18:02 +00003437 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003438 error.SetErrorToGenericError();
Jim Inghama04ef752014-03-07 11:18:02 +00003439 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003440 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003441 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003442 if (error.Success())
3443 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003444 }
3445 else
3446 {
3447 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003448 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 +00003449 return error;
3450 }
3451
3452 if (error.Success())
3453 error.SetErrorToGenericError();
3454 return error;
3455}
3456
Johnny Chen11309a32011-09-06 22:38:36 +00003457// Pre-requisite: wp != NULL.
3458static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00003459GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00003460{
3461 assert(wp);
3462 bool watch_read = wp->WatchpointRead();
3463 bool watch_write = wp->WatchpointWrite();
3464
3465 // watch_read and watch_write cannot both be false.
3466 assert(watch_read || watch_write);
3467 if (watch_read && watch_write)
3468 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00003469 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00003470 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00003471 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00003472 return eWatchpointWrite;
3473}
3474
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003475Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003476ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003477{
3478 Error error;
3479 if (wp)
3480 {
3481 user_id_t watchID = wp->GetID();
3482 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00003483 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003484 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003485 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003486 if (wp->IsEnabled())
3487 {
3488 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003489 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 +00003490 return error;
3491 }
Johnny Chen11309a32011-09-06 22:38:36 +00003492
3493 GDBStoppointType type = GetGDBStoppointType(wp);
3494 // Pass down an appropriate z/Z packet...
3495 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003496 {
Johnny Chen11309a32011-09-06 22:38:36 +00003497 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
3498 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003499 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003500 return error;
3501 }
3502 else
3503 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003504 }
Johnny Chen11309a32011-09-06 22:38:36 +00003505 else
3506 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003507 }
3508 else
3509 {
Johnny Chen01a67862011-10-14 00:42:25 +00003510 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003511 }
3512 if (error.Success())
3513 error.SetErrorToGenericError();
3514 return error;
3515}
3516
3517Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003518ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003519{
3520 Error error;
3521 if (wp)
3522 {
3523 user_id_t watchID = wp->GetID();
3524
Greg Clayton5160ce52013-03-27 23:08:40 +00003525 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003526
3527 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00003528
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003529 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003530 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003531
Johnny Chen11309a32011-09-06 22:38:36 +00003532 if (!wp->IsEnabled())
3533 {
3534 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003535 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 +00003536 // See also 'class WatchpointSentry' within StopInfo.cpp.
3537 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
3538 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00003539 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003540 return error;
3541 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00003542
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003543 if (wp->IsHardware())
3544 {
Johnny Chen11309a32011-09-06 22:38:36 +00003545 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003546 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00003547 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
3548 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003549 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003550 return error;
3551 }
3552 else
Ed Maste81b4c5f2016-01-04 01:43:47 +00003553 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003554 }
3555 // TODO: clear software watchpoints if we implement them
3556 }
3557 else
3558 {
Johnny Chen01a67862011-10-14 00:42:25 +00003559 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003560 }
3561 if (error.Success())
3562 error.SetErrorToGenericError();
3563 return error;
3564}
3565
3566void
3567ProcessGDBRemote::Clear()
3568{
3569 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00003570 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003571 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003572}
3573
3574Error
3575ProcessGDBRemote::DoSignal (int signo)
3576{
3577 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00003578 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003579 if (log)
3580 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
3581
3582 if (!m_gdb_comm.SendAsyncSignal (signo))
3583 error.SetErrorStringWithFormat("failed to send signal %i", signo);
3584 return error;
3585}
3586
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003587Error
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00003588ProcessGDBRemote::EstablishConnectionIfNeeded (const ProcessInfo &process_info)
3589{
3590 // Make sure we aren't already connected?
3591 if (m_gdb_comm.IsConnected())
3592 return Error();
3593
3594 PlatformSP platform_sp (GetTarget ().GetPlatform ());
3595 if (platform_sp && !platform_sp->IsHost ())
3596 return Error("Lost debug server connection");
3597
3598 auto error = LaunchAndConnectToDebugserver (process_info);
3599 if (error.Fail())
3600 {
3601 const char *error_string = error.AsCString();
3602 if (error_string == nullptr)
3603 error_string = "unable to launch " DEBUGSERVER_BASENAME;
3604 }
3605 return error;
3606}
Greg Claytonc6c420f2016-08-12 16:46:18 +00003607#if defined (__APPLE__)
3608#define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1
3609#endif
3610
3611#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3612static bool SetCloexecFlag(int fd)
3613{
3614#if defined(FD_CLOEXEC)
3615 int flags = ::fcntl(fd, F_GETFD);
3616 if (flags == -1)
3617 return false;
3618 return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0);
3619#else
3620 return false;
3621#endif
3622}
3623#endif
Oleksiy Vyalovafd6ce42015-11-23 19:32:24 +00003624
3625Error
Greg Clayton91a9b2472013-12-04 19:19:12 +00003626ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003627{
Pavel Labath998bdc52016-05-11 16:59:04 +00003628 using namespace std::placeholders; // For _1, _2, etc.
3629
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003630 Error error;
3631 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
3632 {
3633 // If we locate debugserver, keep that located version around
3634 static FileSpec g_debugserver_file_spec;
3635
Han Ming Ong84647042012-02-25 01:07:38 +00003636 ProcessLaunchInfo debugserver_launch_info;
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00003637 // Make debugserver run in its own session so signals generated by
3638 // special terminal key sequences (^C) don't affect debugserver.
3639 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3640
Pavel Labath194357c2016-05-12 11:10:01 +00003641 const std::weak_ptr<ProcessGDBRemote> this_wp = std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
3642 debugserver_launch_info.SetMonitorProcessCallback(std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3, _4),
Pavel Labath998bdc52016-05-11 16:59:04 +00003643 false);
Greg Clayton91a9b2472013-12-04 19:19:12 +00003644 debugserver_launch_info.SetUserID(process_info.GetUserID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003645
Greg Claytonfda4fab2014-01-10 22:24:11 +00003646
Greg Claytonc6c420f2016-08-12 16:46:18 +00003647 int communication_fd = -1;
3648#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3649 // Auto close the sockets we might open up unless everything goes OK. This
3650 // helps us not leak file descriptors when things go wrong.
3651 lldb_utility::CleanUp <int, int> our_socket(-1, -1, close);
3652 lldb_utility::CleanUp <int, int> gdb_socket(-1, -1, close);
3653
3654 // Use a socketpair on Apple for now until other platforms can verify it
3655 // works and is fast enough
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003656 {
Greg Claytonc6c420f2016-08-12 16:46:18 +00003657 int sockets[2]; /* the pair of socket descriptors */
3658 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1)
3659 {
3660 error.SetErrorToErrno();
3661 return error;
3662 }
3663
3664 our_socket.set(sockets[0]);
3665 gdb_socket.set(sockets[1]);
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003666 }
3667
Greg Claytonc6c420f2016-08-12 16:46:18 +00003668 // Don't let any child processes inherit our communication socket
3669 SetCloexecFlag(our_socket.get());
3670 communication_fd = gdb_socket.get();
3671#endif
3672
3673 error = m_gdb_comm.StartDebugserverProcess(nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info, nullptr, nullptr, communication_fd);
Greg Clayton91a9b2472013-12-04 19:19:12 +00003674
3675 if (error.Success ())
3676 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003677 else
Greg Clayton91a9b2472013-12-04 19:19:12 +00003678 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003679
3680 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytonc6c420f2016-08-12 16:46:18 +00003681 {
3682#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3683 // Our process spawned correctly, we can now set our connection to use our
3684 // end of the socket pair
3685 m_gdb_comm.SetConnection(new ConnectionFileDescriptor(our_socket.release(), true));
3686#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003687 StartAsyncThread ();
Greg Claytonc6c420f2016-08-12 16:46:18 +00003688 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00003689
Greg Clayton91a9b2472013-12-04 19:19:12 +00003690 if (error.Fail())
3691 {
3692 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
3693
3694 if (log)
3695 log->Printf("failed to start debugserver process: %s", error.AsCString());
3696 return error;
3697 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00003698
Greg Clayton00fe87b2013-12-05 22:58:22 +00003699 if (m_gdb_comm.IsConnected())
3700 {
3701 // Finish the connection process by doing the handshake without connecting (send NULL URL)
Greg Claytonc6c420f2016-08-12 16:46:18 +00003702 ConnectToDebugserver(NULL);
Greg Clayton00fe87b2013-12-05 22:58:22 +00003703 }
3704 else
3705 {
Greg Claytonc6c420f2016-08-12 16:46:18 +00003706 error.SetErrorString("connection failed");
Greg Clayton00fe87b2013-12-05 22:58:22 +00003707 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00003708
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003709 }
3710 return error;
3711}
3712
3713bool
Pavel Labath194357c2016-05-12 11:10:01 +00003714ProcessGDBRemote::MonitorDebugserverProcess(std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid,
Pavel Labath998bdc52016-05-11 16:59:04 +00003715 bool exited, // True if the process did exit
3716 int signo, // Zero for no signal
3717 int exit_status // Exit value of process if signal is zero
3718 )
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003719{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003720 // "debugserver_pid" argument passed in is the process ID for
3721 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00003722 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Pavel Labath194357c2016-05-12 11:10:01 +00003723 const bool handled = true;
Greg Claytone4e45922011-11-16 05:37:56 +00003724
Greg Clayton6779606a2011-01-22 23:43:18 +00003725 if (log)
Pavel Labath194357c2016-05-12 11:10:01 +00003726 log->Printf("ProcessGDBRemote::%s(process_wp, pid=%" PRIu64 ", signo=%i (0x%x), exit_status=%i)", __FUNCTION__,
3727 debugserver_pid, signo, signo, exit_status);
Greg Clayton6779606a2011-01-22 23:43:18 +00003728
Pavel Labath194357c2016-05-12 11:10:01 +00003729 std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
3730 if (log)
Saleem Abdulrasoolabdfc212016-05-15 18:18:13 +00003731 log->Printf("ProcessGDBRemote::%s(process = %p)", __FUNCTION__, static_cast<void *>(process_sp.get()));
Pavel Labath194357c2016-05-12 11:10:01 +00003732 if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
3733 return handled;
3734
3735 // Sleep for a half a second to make sure our inferior process has
3736 // time to set its exit status before we set it incorrectly when
3737 // both the debugserver and the inferior process shut down.
3738 usleep(500000);
3739 // If our process hasn't yet exited, debugserver might have died.
3740 // If the process did exit, then we are reaping it.
3741 const StateType state = process_sp->GetState();
3742
3743 if (state != eStateInvalid && state != eStateUnloaded && state != eStateExited && state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003744 {
Pavel Labath194357c2016-05-12 11:10:01 +00003745 char error_str[1024];
3746 if (signo)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003747 {
Pavel Labath194357c2016-05-12 11:10:01 +00003748 const char *signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
3749 if (signal_cstr)
3750 ::snprintf(error_str, sizeof(error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3751 else
3752 ::snprintf(error_str, sizeof(error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003753 }
Pavel Labath194357c2016-05-12 11:10:01 +00003754 else
3755 {
3756 ::snprintf(error_str, sizeof(error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x",
3757 exit_status);
3758 }
3759
3760 process_sp->SetExitStatus(-1, error_str);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003761 }
Pavel Labath194357c2016-05-12 11:10:01 +00003762 // Debugserver has exited we need to let our ProcessGDBRemote
3763 // know that it no longer has a debugserver instance
3764 process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3765 return handled;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003766}
3767
3768void
3769ProcessGDBRemote::KillDebugserverProcess ()
3770{
Greg Claytonfbb76342013-11-20 21:07:01 +00003771 m_gdb_comm.Disconnect();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003772 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3773 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003774 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003775 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3776 }
3777}
3778
3779void
3780ProcessGDBRemote::Initialize()
3781{
Davide Italianoc8d69822015-04-03 04:24:32 +00003782 static std::once_flag g_once_flag;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003783
Davide Italianoc8d69822015-04-03 04:24:32 +00003784 std::call_once(g_once_flag, []()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003785 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003786 PluginManager::RegisterPlugin (GetPluginNameStatic(),
3787 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00003788 CreateInstance,
3789 DebuggerInitialize);
Davide Italianoc8d69822015-04-03 04:24:32 +00003790 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003791}
3792
Greg Clayton7f982402013-07-15 22:54:20 +00003793void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003794ProcessGDBRemote::DebuggerInitialize (Debugger &debugger)
Greg Clayton7f982402013-07-15 22:54:20 +00003795{
3796 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
3797 {
3798 const bool is_global_setting = true;
3799 PluginManager::CreateSettingForProcessPlugin (debugger,
3800 GetGlobalPluginProperties()->GetValueProperties(),
3801 ConstString ("Properties for the gdb-remote process plug-in."),
3802 is_global_setting);
3803 }
3804}
3805
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003806bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003807ProcessGDBRemote::StartAsyncThread ()
3808{
Greg Clayton5160ce52013-03-27 23:08:40 +00003809 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003810
3811 if (log)
3812 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Ed Maste81b4c5f2016-01-04 01:43:47 +00003813
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +00003814 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003815 if (!m_async_thread.IsJoinable())
Jim Ingham455fa5c2012-11-01 01:15:33 +00003816 {
3817 // Create a thread that watches our internal state and controls which
3818 // events make it to clients (into the DCProcess event queue).
Zachary Turner39de3112014-09-09 20:54:56 +00003819
3820 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003821 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003822 else if (log)
3823 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was already running.", __FUNCTION__);
Zachary Turner39de3112014-09-09 20:54:56 +00003824
Zachary Turneracee96a2014-09-23 18:32:09 +00003825 return m_async_thread.IsJoinable();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003826}
3827
3828void
3829ProcessGDBRemote::StopAsyncThread ()
3830{
Greg Clayton5160ce52013-03-27 23:08:40 +00003831 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003832
3833 if (log)
3834 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
3835
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +00003836 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003837 if (m_async_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003838 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00003839 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
Ed Maste81b4c5f2016-01-04 01:43:47 +00003840
Jim Ingham455fa5c2012-11-01 01:15:33 +00003841 // This will shut down the async thread.
3842 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3843
3844 // Stop the stdio thread
Zachary Turner39de3112014-09-09 20:54:56 +00003845 m_async_thread.Join(nullptr);
Pavel Labatha55a9532015-03-11 09:53:42 +00003846 m_async_thread.Reset();
Jim Ingham455fa5c2012-11-01 01:15:33 +00003847 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003848 else if (log)
3849 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003850}
3851
Ewan Crawford76df2882015-06-23 12:32:06 +00003852bool
3853ProcessGDBRemote::HandleNotifyPacket (StringExtractorGDBRemote &packet)
3854{
3855 // get the packet at a string
3856 const std::string &pkt = packet.GetStringRef();
3857 // skip %stop:
3858 StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
3859
3860 // pass as a thread stop info packet
3861 SetLastStopPacket(stop_info);
3862
3863 // check for more stop reasons
3864 HandleStopReplySequence();
3865
3866 // if the process is stopped then we need to fake a resume
3867 // so that we can stop properly with the new break. This
3868 // is possible due to SetPrivateState() broadcasting the
3869 // state change as a side effect.
3870 if (GetPrivateState() == lldb::StateType::eStateStopped)
3871 {
3872 SetPrivateState(lldb::StateType::eStateRunning);
3873 }
3874
3875 // since we have some stopped packets we can halt the process
3876 SetPrivateState(lldb::StateType::eStateStopped);
3877
3878 return true;
3879}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003880
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003881thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003882ProcessGDBRemote::AsyncThread (void *arg)
3883{
3884 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
3885
Greg Clayton5160ce52013-03-27 23:08:40 +00003886 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003887 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003888 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003889
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003890 EventSP event_sp;
Pavel Labath50556852015-09-03 09:36:22 +00003891 bool done = false;
3892 while (!done)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003893 {
Pavel Labath50556852015-09-03 09:36:22 +00003894 if (log)
3895 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003896 if (process->m_async_listener_sp->WaitForEvent(std::chrono::microseconds(0), event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003897 {
Pavel Labath50556852015-09-03 09:36:22 +00003898 const uint32_t event_type = event_sp->GetType();
3899 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003900 {
3901 if (log)
Pavel Labath50556852015-09-03 09:36:22 +00003902 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
3903
3904 switch (event_type)
3905 {
3906 case eBroadcastBitAsyncContinue:
3907 {
3908 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
3909
3910 if (continue_packet)
3911 {
3912 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
3913 const size_t continue_cstr_len = continue_packet->GetByteSize ();
3914 if (log)
3915 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
3916
3917 if (::strstr (continue_cstr, "vAttach") == NULL)
3918 process->SetPrivateState(eStateRunning);
3919 StringExtractorGDBRemote response;
3920
3921 // If in Non-Stop-Mode
3922 if (process->GetTarget().GetNonStopModeEnabled())
3923 {
3924 // send the vCont packet
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00003925 if (!process->GetGDBRemote().SendvContPacket(
3926 llvm::StringRef(continue_cstr, continue_cstr_len), response))
Pavel Labath50556852015-09-03 09:36:22 +00003927 {
3928 // Something went wrong
3929 done = true;
3930 break;
3931 }
3932 }
3933 // If in All-Stop-Mode
3934 else
3935 {
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00003936 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse(
3937 *process, *process->GetUnixSignals(),
3938 llvm::StringRef(continue_cstr, continue_cstr_len), response);
Pavel Labath50556852015-09-03 09:36:22 +00003939
3940 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
3941 // The thread ID list might be contained within the "response", or the stop reply packet that
3942 // caused the stop. So clear it now before we give the stop reply packet to the process
3943 // using the process->SetLastStopPacket()...
3944 process->ClearThreadIDList ();
3945
3946 switch (stop_state)
3947 {
3948 case eStateStopped:
3949 case eStateCrashed:
3950 case eStateSuspended:
3951 process->SetLastStopPacket (response);
3952 process->SetPrivateState (stop_state);
3953 break;
3954
3955 case eStateExited:
3956 {
3957 process->SetLastStopPacket (response);
3958 process->ClearThreadIDList();
3959 response.SetFilePos(1);
Ed Maste81b4c5f2016-01-04 01:43:47 +00003960
Pavel Labath50556852015-09-03 09:36:22 +00003961 int exit_status = response.GetHexU8();
3962 const char *desc_cstr = NULL;
3963 StringExtractor extractor;
3964 std::string desc_string;
3965 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';')
3966 {
3967 std::string desc_token;
3968 while (response.GetNameColonValue (desc_token, desc_string))
3969 {
3970 if (desc_token == "description")
3971 {
3972 extractor.GetStringRef().swap(desc_string);
3973 extractor.SetFilePos(0);
3974 extractor.GetHexByteString (desc_string);
3975 desc_cstr = desc_string.c_str();
3976 }
3977 }
3978 }
3979 process->SetExitStatus(exit_status, desc_cstr);
3980 done = true;
3981 break;
3982 }
3983 case eStateInvalid:
3984 {
3985 // Check to see if we were trying to attach and if we got back
3986 // the "E87" error code from debugserver -- this indicates that
3987 // the process is not debuggable. Return a slightly more helpful
3988 // error message about why the attach failed.
3989 if (::strstr (continue_cstr, "vAttach") != NULL
3990 && response.GetError() == 0x87)
3991 {
3992 process->SetExitStatus(-1, "cannot attach to process due to System Integrity Protection");
3993 }
3994 // E01 code from vAttach means that the attach failed
3995 if (::strstr (continue_cstr, "vAttach") != NULL
3996 && response.GetError() == 0x1)
3997 {
3998 process->SetExitStatus(-1, "unable to attach");
3999 }
4000 else
4001 {
4002 process->SetExitStatus(-1, "lost connection");
4003 }
4004 break;
4005 }
4006
4007 default:
4008 process->SetPrivateState (stop_state);
4009 break;
4010 } // switch(stop_state)
4011 } // else // if in All-stop-mode
4012 } // if (continue_packet)
4013 } // case eBroadcastBitAysncContinue
4014 break;
4015
4016 case eBroadcastBitAsyncThreadShouldExit:
4017 if (log)
4018 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
4019 done = true;
4020 break;
4021
4022 default:
4023 if (log)
4024 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
4025 done = true;
4026 break;
4027 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004028 }
Pavel Labath50556852015-09-03 09:36:22 +00004029 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
4030 {
4031 switch (event_type)
4032 {
4033 case Communication::eBroadcastBitReadThreadDidExit:
4034 process->SetExitStatus (-1, "lost connection");
4035 done = true;
4036 break;
4037
4038 case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify:
4039 {
4040 lldb_private::Event *event = event_sp.get();
4041 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event);
4042 StringExtractorGDBRemote notify((const char*)continue_packet->GetBytes());
4043 // Hand this over to the process to handle
4044 process->HandleNotifyPacket(notify);
4045 break;
4046 }
4047
4048 default:
4049 if (log)
4050 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
4051 done = true;
4052 break;
4053 }
4054 }
4055 }
4056 else
4057 {
4058 if (log)
4059 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
4060 done = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004061 }
4062 }
4063
4064 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004065 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004066
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004067 return NULL;
4068}
4069
Greg Claytone996fd32011-03-08 22:40:15 +00004070//uint32_t
4071//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4072//{
4073// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
4074// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
4075// if (m_local_debugserver)
4076// {
4077// return Host::ListProcessesMatchingName (name, matches, pids);
4078// }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004079// else
Greg Claytone996fd32011-03-08 22:40:15 +00004080// {
4081// // FIXME: Implement talking to the remote debugserver.
4082// return 0;
4083// }
4084//
4085//}
4086//
Jim Ingham1c823b42011-01-22 01:33:44 +00004087bool
4088ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004089 StoppointCallbackContext *context,
Jim Ingham1c823b42011-01-22 01:33:44 +00004090 lldb::user_id_t break_id,
4091 lldb::user_id_t break_loc_id)
4092{
Ed Maste81b4c5f2016-01-04 01:43:47 +00004093 // 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 +00004094 // run so I can stop it if that's what I want to do.
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004095 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00004096 if (log)
4097 log->Printf("Hit New Thread Notification breakpoint.");
4098 return false;
4099}
4100
Eugene Zelenko0722f082015-10-24 01:28:05 +00004101
Jim Ingham1c823b42011-01-22 01:33:44 +00004102bool
4103ProcessGDBRemote::StartNoticingNewThreads()
4104{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004105 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00004106 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00004107 {
Greg Clayton4116e932012-05-15 02:33:01 +00004108 if (log && log->GetVerbose())
4109 log->Printf("Enabled noticing new thread breakpoint.");
4110 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00004111 }
Greg Clayton4116e932012-05-15 02:33:01 +00004112 else
Jim Ingham1c823b42011-01-22 01:33:44 +00004113 {
Zachary Turner7529df92015-09-01 20:02:29 +00004114 PlatformSP platform_sp (GetTarget().GetPlatform());
Greg Clayton4116e932012-05-15 02:33:01 +00004115 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00004116 {
Zachary Turner7529df92015-09-01 20:02:29 +00004117 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(GetTarget());
Greg Clayton4116e932012-05-15 02:33:01 +00004118 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00004119 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00004120 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00004121 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
4122 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00004123 }
4124 else
4125 {
4126 if (log)
4127 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00004128 }
4129 }
4130 }
Greg Clayton4116e932012-05-15 02:33:01 +00004131 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00004132}
4133
4134bool
4135ProcessGDBRemote::StopNoticingNewThreads()
Ed Maste81b4c5f2016-01-04 01:43:47 +00004136{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004137 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00004138 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00004139 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00004140
4141 if (m_thread_create_bp_sp)
4142 m_thread_create_bp_sp->SetEnabled(false);
4143
Jim Ingham1c823b42011-01-22 01:33:44 +00004144 return true;
4145}
Ed Maste81b4c5f2016-01-04 01:43:47 +00004146
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004147DynamicLoader *
Jason Molenda5e8534e2012-10-03 01:29:34 +00004148ProcessGDBRemote::GetDynamicLoader ()
4149{
4150 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00004151 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00004152 return m_dyld_ap.get();
4153}
Jim Ingham1c823b42011-01-22 01:33:44 +00004154
Jason Molendaa3329782014-03-29 18:54:20 +00004155Error
4156ProcessGDBRemote::SendEventData(const char *data)
4157{
4158 int return_value;
4159 bool was_supported;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004160
Jason Molendaa3329782014-03-29 18:54:20 +00004161 Error error;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004162
Jason Molendaa3329782014-03-29 18:54:20 +00004163 return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported);
4164 if (return_value != 0)
4165 {
4166 if (!was_supported)
4167 error.SetErrorString("Sending events is not supported for this process.");
4168 else
4169 error.SetErrorStringWithFormat("Error sending event data: %d.", return_value);
4170 }
4171 return error;
4172}
4173
Steve Pucci03904ac2014-03-04 23:18:46 +00004174const DataBufferSP
4175ProcessGDBRemote::GetAuxvData()
4176{
4177 DataBufferSP buf;
4178 if (m_gdb_comm.GetQXferAuxvReadSupported())
4179 {
4180 std::string response_string;
4181 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success)
4182 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length()));
4183 }
4184 return buf;
4185}
4186
Jason Molenda705b1802014-06-13 02:37:02 +00004187StructuredData::ObjectSP
4188ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid)
4189{
4190 StructuredData::ObjectSP object_sp;
4191
4192 if (m_gdb_comm.GetThreadExtendedInfoSupported())
4193 {
4194 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4195 SystemRuntime *runtime = GetSystemRuntime();
4196 if (runtime)
4197 {
4198 runtime->AddThreadExtendedInfoPacketHints (args_dict);
4199 }
4200 args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid);
4201
4202 StreamString packet;
4203 packet << "jThreadExtendedInfo:";
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004204 args_dict->Dump (packet, false);
Jason Molenda705b1802014-06-13 02:37:02 +00004205
4206 // FIXME the final character of a JSON dictionary, '}', is the escape
4207 // character in gdb-remote binary mode. lldb currently doesn't escape
4208 // these characters in its packet output -- so we add the quoted version
4209 // of the } character here manually in case we talk to a debugserver which
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004210 // un-escapes the characters at packet read time.
Jason Molenda705b1802014-06-13 02:37:02 +00004211 packet << (char) (0x7d ^ 0x20);
4212
4213 StringExtractorGDBRemote response;
Greg Clayton830c81d2016-04-01 00:41:29 +00004214 response.SetResponseValidatorToJSON();
Jason Molenda705b1802014-06-13 02:37:02 +00004215 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4216 {
4217 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4218 if (response_type == StringExtractorGDBRemote::eResponse)
4219 {
4220 if (!response.Empty())
4221 {
Jason Molenda20ee21b2015-07-10 23:15:22 +00004222 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4223 }
4224 }
4225 }
4226 }
4227 return object_sp;
4228}
4229
4230StructuredData::ObjectSP
4231ProcessGDBRemote::GetLoadedDynamicLibrariesInfos (lldb::addr_t image_list_address, lldb::addr_t image_count)
4232{
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004233
4234 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4235 args_dict->GetAsDictionary()->AddIntegerItem ("image_list_address", image_list_address);
4236 args_dict->GetAsDictionary()->AddIntegerItem ("image_count", image_count);
4237
4238 return GetLoadedDynamicLibrariesInfos_sender (args_dict);
4239}
4240
4241StructuredData::ObjectSP
4242ProcessGDBRemote::GetLoadedDynamicLibrariesInfos ()
4243{
4244 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4245
4246 args_dict->GetAsDictionary()->AddBooleanItem ("fetch_all_solibs", true);
4247
4248 return GetLoadedDynamicLibrariesInfos_sender (args_dict);
4249}
4250
4251StructuredData::ObjectSP
4252ProcessGDBRemote::GetLoadedDynamicLibrariesInfos (const std::vector<lldb::addr_t> &load_addresses)
4253{
4254 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4255 StructuredData::ArraySP addresses(new StructuredData::Array);
4256
4257 for (auto addr : load_addresses)
4258 {
4259 StructuredData::ObjectSP addr_sp (new StructuredData::Integer (addr));
4260 addresses->AddItem (addr_sp);
4261 }
4262
4263 args_dict->GetAsDictionary()->AddItem ("solib_addresses", addresses);
4264
4265 return GetLoadedDynamicLibrariesInfos_sender (args_dict);
4266}
4267
4268StructuredData::ObjectSP
4269ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender (StructuredData::ObjectSP args_dict)
4270{
Jason Molenda20ee21b2015-07-10 23:15:22 +00004271 StructuredData::ObjectSP object_sp;
4272
4273 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported())
4274 {
Jason Molenda1d3b3562015-11-05 23:54:29 +00004275 // Scope for the scoped timeout object
4276 GDBRemoteCommunication::ScopedTimeout timeout (m_gdb_comm, 10);
4277
Jason Molenda20ee21b2015-07-10 23:15:22 +00004278 StreamString packet;
4279 packet << "jGetLoadedDynamicLibrariesInfos:";
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004280 args_dict->Dump (packet, false);
Jason Molenda20ee21b2015-07-10 23:15:22 +00004281
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;
Greg Clayton830c81d2016-04-01 00:41:29 +00004290 response.SetResponseValidatorToJSON();
Jason Molenda20ee21b2015-07-10 23:15:22 +00004291 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 {
Jason Molenda705b1802014-06-13 02:37:02 +00004298 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4299 }
4300 }
4301 }
4302 }
4303 return object_sp;
4304}
4305
Jason Molenda9ab5dc22016-07-21 08:30:55 +00004306
4307
4308
Jason Molenda37397352016-07-22 00:17:55 +00004309StructuredData::ObjectSP
4310ProcessGDBRemote::GetSharedCacheInfo ()
4311{
4312 StructuredData::ObjectSP object_sp;
4313 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4314
4315 if (m_gdb_comm.GetSharedCacheInfoSupported())
4316 {
4317 StreamString packet;
4318 packet << "jGetSharedCacheInfo:";
4319 args_dict->Dump (packet, false);
4320
4321 // FIXME the final character of a JSON dictionary, '}', is the escape
4322 // character in gdb-remote binary mode. lldb currently doesn't escape
4323 // these characters in its packet output -- so we add the quoted version
4324 // of the } character here manually in case we talk to a debugserver which
4325 // un-escapes the characters at packet read time.
4326 packet << (char) (0x7d ^ 0x20);
4327
4328 StringExtractorGDBRemote response;
4329 response.SetResponseValidatorToJSON();
4330 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4331 {
4332 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4333 if (response_type == StringExtractorGDBRemote::eResponse)
4334 {
4335 if (!response.Empty())
4336 {
4337 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4338 }
4339 }
4340 }
4341 }
4342 return object_sp;
4343}
4344
4345
Jason Molenda6076bf42014-05-06 04:34:52 +00004346// Establish the largest memory read/write payloads we should use.
4347// If the remote stub has a max packet size, stay under that size.
Ed Maste81b4c5f2016-01-04 01:43:47 +00004348//
4349// If the remote stub's max packet size is crazy large, use a
Jason Molenda6076bf42014-05-06 04:34:52 +00004350// reasonable largeish default.
4351//
4352// If the remote stub doesn't advertise a max packet size, use a
4353// conservative default.
4354
4355void
4356ProcessGDBRemote::GetMaxMemorySize()
4357{
4358 const uint64_t reasonable_largeish_default = 128 * 1024;
4359 const uint64_t conservative_default = 512;
4360
4361 if (m_max_memory_size == 0)
4362 {
4363 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4364 if (stub_max_size != UINT64_MAX && stub_max_size != 0)
4365 {
4366 // Save the stub's claimed maximum packet size
4367 m_remote_stub_max_memory_size = stub_max_size;
4368
4369 // Even if the stub says it can support ginormous packets,
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004370 // don't exceed our reasonable largeish default packet size.
Jason Molenda6076bf42014-05-06 04:34:52 +00004371 if (stub_max_size > reasonable_largeish_default)
4372 {
4373 stub_max_size = reasonable_largeish_default;
4374 }
4375
4376 m_max_memory_size = stub_max_size;
4377 }
4378 else
4379 {
4380 m_max_memory_size = conservative_default;
4381 }
4382 }
4383}
4384
4385void
4386ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max)
4387{
4388 if (user_specified_max != 0)
4389 {
4390 GetMaxMemorySize ();
4391
4392 if (m_remote_stub_max_memory_size != 0)
4393 {
4394 if (m_remote_stub_max_memory_size < user_specified_max)
4395 {
4396 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a packet size too big, go as big
4397 // as the remote stub says we can go.
4398 }
4399 else
4400 {
4401 m_max_memory_size = user_specified_max; // user's packet size is good
4402 }
4403 }
4404 else
4405 {
4406 m_max_memory_size = user_specified_max; // user's packet size is probably fine
4407 }
4408 }
4409}
4410
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004411bool
4412ProcessGDBRemote::GetModuleSpec(const FileSpec& module_file_spec,
4413 const ArchSpec& arch,
4414 ModuleSpec &module_spec)
4415{
4416 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PLATFORM);
4417
4418 if (!m_gdb_comm.GetModuleInfo (module_file_spec, arch, module_spec))
4419 {
4420 if (log)
4421 log->Printf ("ProcessGDBRemote::%s - failed to get module info for %s:%s",
4422 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4423 arch.GetTriple ().getTriple ().c_str ());
4424 return false;
4425 }
4426
4427 if (log)
4428 {
4429 StreamString stream;
4430 module_spec.Dump (stream);
4431 log->Printf ("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4432 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4433 arch.GetTriple ().getTriple ().c_str (), stream.GetString ().c_str ());
4434 }
4435
4436 return true;
4437}
4438
Jim Ingham13c30d22015-11-05 22:33:17 +00004439bool
4440ProcessGDBRemote::GetHostOSVersion(uint32_t &major,
4441 uint32_t &minor,
4442 uint32_t &update)
4443{
4444 if (m_gdb_comm.GetOSVersion(major, minor, update))
4445 return true;
4446 // We failed to get the host OS version, defer to the base
4447 // implementation to correctly invalidate the arguments.
4448 return Process::GetHostOSVersion(major, minor, update);
4449}
4450
Colin Rileyc3c95b22015-04-16 15:51:33 +00004451namespace {
4452
4453typedef std::vector<std::string> stringVec;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004454
4455typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004456struct RegisterSetInfo
4457{
4458 ConstString name;
4459};
Colin Rileyc3c95b22015-04-16 15:51:33 +00004460
Greg Claytond04f0ed2015-05-26 18:00:51 +00004461typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004462
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004463struct GdbServerTargetInfo
4464{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004465 std::string arch;
4466 std::string osabi;
4467 stringVec includes;
4468 RegisterSetMap reg_set_map;
4469 XMLNode feature_node;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004470};
Ed Maste81b4c5f2016-01-04 01:43:47 +00004471
Colin Rileyc3c95b22015-04-16 15:51:33 +00004472bool
Francis Ricci55954ae2016-04-25 21:03:55 +00004473ParseRegisters (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 +00004474{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004475 if (!feature_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004476 return false;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004477
Jason Molenda63bd0db2015-09-15 23:20:34 +00004478 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 +00004479 std::string gdb_group;
4480 std::string gdb_type;
4481 ConstString reg_name;
4482 ConstString alt_name;
4483 ConstString set_name;
4484 std::vector<uint32_t> value_regs;
4485 std::vector<uint32_t> invalidate_regs;
Nitesh Jain52b6cc52016-08-01 13:45:51 +00004486 std::vector<uint8_t> dwarf_opcode_bytes;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004487 bool encoding_set = false;
4488 bool format_set = false;
4489 RegisterInfo reg_info = { NULL, // Name
4490 NULL, // Alt name
4491 0, // byte size
4492 reg_offset, // offset
4493 eEncodingUint, // encoding
Jason Molendabf67a302015-09-01 05:17:01 +00004494 eFormatHex, // format
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004495 {
Jason Molendabf67a302015-09-01 05:17:01 +00004496 LLDB_INVALID_REGNUM, // eh_frame reg num
Greg Claytond04f0ed2015-05-26 18:00:51 +00004497 LLDB_INVALID_REGNUM, // DWARF reg num
4498 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda63bd0db2015-09-15 23:20:34 +00004499 cur_reg_num, // process plugin reg num
4500 cur_reg_num // native register number
Greg Claytond04f0ed2015-05-26 18:00:51 +00004501 },
4502 NULL,
Nitesh Jain52b6cc52016-08-01 13:45:51 +00004503 NULL,
4504 NULL, // Dwarf Expression opcode bytes pointer
4505 0 // Dwarf Expression opcode bytes length
Greg Claytond04f0ed2015-05-26 18:00:51 +00004506 };
Ed Maste81b4c5f2016-01-04 01:43:47 +00004507
Nitesh Jain52b6cc52016-08-01 13:45:51 +00004508 reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type, &reg_name, &alt_name, &set_name, &value_regs, &invalidate_regs, &encoding_set, &format_set, &reg_info, &cur_reg_num, &reg_offset, &dwarf_opcode_bytes](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004509 if (name == "name")
4510 {
4511 reg_name.SetString(value);
4512 }
4513 else if (name == "bitsize")
4514 {
4515 reg_info.byte_size = StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
4516 }
4517 else if (name == "type")
4518 {
4519 gdb_type = value.str();
4520 }
4521 else if (name == "group")
4522 {
4523 gdb_group = value.str();
4524 }
4525 else if (name == "regnum")
4526 {
4527 const uint32_t regnum = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4528 if (regnum != LLDB_INVALID_REGNUM)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004529 {
Jason Molenda63bd0db2015-09-15 23:20:34 +00004530 reg_info.kinds[eRegisterKindProcessPlugin] = regnum;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004531 }
4532 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004533 else if (name == "offset")
4534 {
4535 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4536 }
4537 else if (name == "altname")
4538 {
4539 alt_name.SetString(value);
4540 }
4541 else if (name == "encoding")
4542 {
4543 encoding_set = true;
4544 reg_info.encoding = Args::StringToEncoding (value.data(), eEncodingUint);
4545 }
4546 else if (name == "format")
4547 {
4548 format_set = true;
4549 Format format = eFormatInvalid;
4550 if (Args::StringToFormat (value.data(), format, NULL).Success())
4551 reg_info.format = format;
4552 else if (value == "vector-sint8")
4553 reg_info.format = eFormatVectorOfSInt8;
4554 else if (value == "vector-uint8")
4555 reg_info.format = eFormatVectorOfUInt8;
4556 else if (value == "vector-sint16")
4557 reg_info.format = eFormatVectorOfSInt16;
4558 else if (value == "vector-uint16")
4559 reg_info.format = eFormatVectorOfUInt16;
4560 else if (value == "vector-sint32")
4561 reg_info.format = eFormatVectorOfSInt32;
4562 else if (value == "vector-uint32")
4563 reg_info.format = eFormatVectorOfUInt32;
4564 else if (value == "vector-float32")
4565 reg_info.format = eFormatVectorOfFloat32;
4566 else if (value == "vector-uint128")
4567 reg_info.format = eFormatVectorOfUInt128;
4568 }
4569 else if (name == "group_id")
4570 {
4571 const uint32_t set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4572 RegisterSetMap::const_iterator pos = target_info.reg_set_map.find(set_id);
4573 if (pos != target_info.reg_set_map.end())
4574 set_name = pos->second.name;
4575 }
Jason Molendaa18f7072015-08-15 01:21:01 +00004576 else if (name == "gcc_regnum" || name == "ehframe_regnum")
Greg Claytond04f0ed2015-05-26 18:00:51 +00004577 {
Jason Molendaa18f7072015-08-15 01:21:01 +00004578 reg_info.kinds[eRegisterKindEHFrame] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004579 }
4580 else if (name == "dwarf_regnum")
4581 {
4582 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4583 }
4584 else if (name == "generic")
4585 {
4586 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister(value.data());
4587 }
4588 else if (name == "value_regnums")
4589 {
4590 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
4591 }
4592 else if (name == "invalidate_regnums")
4593 {
4594 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
4595 }
Nitesh Jain52b6cc52016-08-01 13:45:51 +00004596 else if (name == "dynamic_size_dwarf_expr_bytes")
4597 {
4598 StringExtractor opcode_extractor;
4599 std::string opcode_string = value.str ();
4600 size_t dwarf_opcode_len = opcode_string.length () / 2;
4601 assert (dwarf_opcode_len > 0);
4602
4603 dwarf_opcode_bytes.resize (dwarf_opcode_len);
4604 reg_info.dynamic_size_dwarf_len = dwarf_opcode_len;
4605 opcode_extractor.GetStringRef ().swap (opcode_string);
4606 uint32_t ret_val = opcode_extractor.GetHexBytesAvail (dwarf_opcode_bytes.data (),
4607 dwarf_opcode_len);
4608 assert (dwarf_opcode_len == ret_val);
4609
4610 reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data ();
4611 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004612 else
4613 {
4614 printf("unhandled attribute %s = %s\n", name.data(), value.data());
4615 }
4616 return true; // Keep iterating through all attributes
4617 });
Ed Maste81b4c5f2016-01-04 01:43:47 +00004618
Greg Claytond04f0ed2015-05-26 18:00:51 +00004619 if (!gdb_type.empty() && !(encoding_set || format_set))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004620 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004621 if (gdb_type.find("int") == 0)
4622 {
4623 reg_info.format = eFormatHex;
4624 reg_info.encoding = eEncodingUint;
4625 }
4626 else if (gdb_type == "data_ptr" || gdb_type == "code_ptr")
4627 {
4628 reg_info.format = eFormatAddressInfo;
4629 reg_info.encoding = eEncodingUint;
4630 }
4631 else if (gdb_type == "i387_ext" || gdb_type == "float")
4632 {
4633 reg_info.format = eFormatFloat;
4634 reg_info.encoding = eEncodingIEEE754;
4635 }
Colin Rileyc3c95b22015-04-16 15:51:33 +00004636 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004637
Greg Claytond04f0ed2015-05-26 18:00:51 +00004638 // Only update the register set name if we didn't get a "reg_set" attribute.
4639 // "set_name" will be empty if we didn't have a "reg_set" attribute.
4640 if (!set_name && !gdb_group.empty())
4641 set_name.SetCString(gdb_group.c_str());
Ed Maste81b4c5f2016-01-04 01:43:47 +00004642
Greg Claytond04f0ed2015-05-26 18:00:51 +00004643 reg_info.byte_offset = reg_offset;
4644 assert (reg_info.byte_size != 0);
4645 reg_offset += reg_info.byte_size;
4646 if (!value_regs.empty())
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004647 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004648 value_regs.push_back(LLDB_INVALID_REGNUM);
4649 reg_info.value_regs = value_regs.data();
Colin Rileyc3c95b22015-04-16 15:51:33 +00004650 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004651 if (!invalidate_regs.empty())
4652 {
4653 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
4654 reg_info.invalidate_regs = invalidate_regs.data();
4655 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004656
Jason Molenda63bd0db2015-09-15 23:20:34 +00004657 ++cur_reg_num;
Jason Molenda21586c82015-09-09 03:36:24 +00004658 AugmentRegisterInfoViaABI (reg_info, reg_name, abi_sp);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004659 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
Ed Maste81b4c5f2016-01-04 01:43:47 +00004660
Greg Claytond04f0ed2015-05-26 18:00:51 +00004661 return true; // Keep iterating through all "reg" elements
4662 });
Colin Rileyc3c95b22015-04-16 15:51:33 +00004663 return true;
4664}
Ed Maste81b4c5f2016-01-04 01:43:47 +00004665
Eugene Zelenko0722f082015-10-24 01:28:05 +00004666} // namespace {}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004667
Colin Rileyc3c95b22015-04-16 15:51:33 +00004668
4669// query the target of gdb-remote for extended target information
4670// return: 'true' on success
4671// 'false' on failure
4672bool
Jim Ingham7b71c0b2016-02-18 23:58:45 +00004673ProcessGDBRemote::GetGDBServerRegisterInfo (ArchSpec &arch_to_use)
Colin Rileyc3c95b22015-04-16 15:51:33 +00004674{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004675 // Make sure LLDB has an XML parser it can use first
4676 if (!XMLDocument::XMLEnabled())
4677 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004678
4679 // redirect libxml2's error handler since the default prints to stdout
Colin Rileyc3c95b22015-04-16 15:51:33 +00004680
4681 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004682
4683 // check that we have extended feature read support
4684 if ( !comm.GetQXferFeaturesReadSupported( ) )
4685 return false;
4686
4687 // request the target xml file
4688 std::string raw;
4689 lldb_private::Error lldberr;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004690 if (!comm.ReadExtFeature(ConstString("features"),
4691 ConstString("target.xml"),
4692 raw,
4693 lldberr))
4694 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00004695 return false;
4696 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004697
Colin Rileyc3c95b22015-04-16 15:51:33 +00004698
Greg Claytond04f0ed2015-05-26 18:00:51 +00004699 XMLDocument xml_document;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004700
Greg Claytond04f0ed2015-05-26 18:00:51 +00004701 if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml"))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004702 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004703 GdbServerTargetInfo target_info;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004704
Greg Claytond04f0ed2015-05-26 18:00:51 +00004705 XMLNode target_node = xml_document.GetRootElement("target");
4706 if (target_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004707 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004708 XMLNode feature_node;
4709 target_node.ForEachChildElement([&target_info, this, &feature_node](const XMLNode &node) -> bool
4710 {
4711 llvm::StringRef name = node.GetName();
4712 if (name == "architecture")
4713 {
4714 node.GetElementText(target_info.arch);
4715 }
4716 else if (name == "osabi")
4717 {
4718 node.GetElementText(target_info.osabi);
4719 }
Ewan Crawford682e8422015-06-26 09:38:27 +00004720 else if (name == "xi:include" || name == "include")
Greg Claytond04f0ed2015-05-26 18:00:51 +00004721 {
4722 llvm::StringRef href = node.GetAttributeValue("href");
4723 if (!href.empty())
4724 target_info.includes.push_back(href.str());
4725 }
4726 else if (name == "feature")
4727 {
4728 feature_node = node;
4729 }
4730 else if (name == "groups")
4731 {
4732 node.ForEachChildElementWithName("group", [&target_info](const XMLNode &node) -> bool {
4733 uint32_t set_id = UINT32_MAX;
4734 RegisterSetInfo set_info;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004735
Greg Claytond04f0ed2015-05-26 18:00:51 +00004736 node.ForEachAttribute([&set_id, &set_info](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
4737 if (name == "id")
4738 set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4739 if (name == "name")
4740 set_info.name = ConstString(value);
4741 return true; // Keep iterating through all attributes
4742 });
Ed Maste81b4c5f2016-01-04 01:43:47 +00004743
Greg Claytond04f0ed2015-05-26 18:00:51 +00004744 if (set_id != UINT32_MAX)
4745 target_info.reg_set_map[set_id] = set_info;
4746 return true; // Keep iterating through all "group" elements
4747 });
4748 }
4749 return true; // Keep iterating through all children of the target_node
4750 });
Ed Maste81b4c5f2016-01-04 01:43:47 +00004751
Francis Ricci55954ae2016-04-25 21:03:55 +00004752 // Initialize these outside of ParseRegisters, since they should not be reset inside each include feature
4753 uint32_t cur_reg_num = 0;
4754 uint32_t reg_offset = 0;
4755
Jim Ingham7b71c0b2016-02-18 23:58:45 +00004756 // Don't use Process::GetABI, this code gets called from DidAttach, and in that context we haven't
4757 // set the Target's architecture yet, so the ABI is also potentially incorrect.
4758 ABISP abi_to_use_sp = ABI::FindPlugin(arch_to_use);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004759 if (feature_node)
4760 {
Francis Ricci55954ae2016-04-25 21:03:55 +00004761 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 +00004762 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004763
Greg Claytond04f0ed2015-05-26 18:00:51 +00004764 for (const auto &include : target_info.includes)
4765 {
4766 // request register file
4767 std::string xml_data;
4768 if (!comm.ReadExtFeature(ConstString("features"),
4769 ConstString(include),
4770 xml_data,
4771 lldberr))
4772 continue;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004773
Greg Claytond04f0ed2015-05-26 18:00:51 +00004774 XMLDocument include_xml_document;
4775 include_xml_document.ParseMemory(xml_data.data(), xml_data.size(), include.c_str());
4776 XMLNode include_feature_node = include_xml_document.GetRootElement("feature");
4777 if (include_feature_node)
4778 {
Francis Ricci55954ae2016-04-25 21:03:55 +00004779 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 +00004780 }
4781 }
Jim Ingham7b71c0b2016-02-18 23:58:45 +00004782 this->m_register_info.Finalize(arch_to_use);
Colin Rileyc3c95b22015-04-16 15:51:33 +00004783 }
4784 }
4785
Greg Claytond04f0ed2015-05-26 18:00:51 +00004786 return m_register_info.GetNumRegisters() > 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004787}
4788
Aidan Doddsc0c83852015-05-08 09:36:31 +00004789Error
Stephane Sezer87b0fe02016-01-12 19:02:41 +00004790ProcessGDBRemote::GetLoadedModuleList (LoadedModuleInfoList & list)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004791{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004792 // Make sure LLDB has an XML parser it can use first
4793 if (!XMLDocument::XMLEnabled())
4794 return Error (0, ErrorType::eErrorTypeGeneric);
4795
Aidan Doddsc0c83852015-05-08 09:36:31 +00004796 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS);
4797 if (log)
4798 log->Printf ("ProcessGDBRemote::%s", __FUNCTION__);
4799
Aidan Doddsc0c83852015-05-08 09:36:31 +00004800 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004801
4802 // check that we have extended feature read support
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004803 if (comm.GetQXferLibrariesSVR4ReadSupported ()) {
4804 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004805
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004806 // request the loaded library list
4807 std::string raw;
4808 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004809
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004810 if (!comm.ReadExtFeature (ConstString ("libraries-svr4"), ConstString (""), raw, lldberr))
4811 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004812
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004813 // parse the xml file in memory
4814 if (log)
4815 log->Printf ("parsing: %s", raw.c_str());
4816 XMLDocument doc;
Ed Maste81b4c5f2016-01-04 01:43:47 +00004817
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004818 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4819 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004820
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004821 XMLNode root_element = doc.GetRootElement("library-list-svr4");
4822 if (!root_element)
4823 return Error();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004824
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004825 // main link map structure
4826 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4827 if (!main_lm.empty())
4828 {
4829 list.m_link_map = StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
4830 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004831
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004832 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
Aidan Doddsc0c83852015-05-08 09:36:31 +00004833
Stephane Sezer87b0fe02016-01-12 19:02:41 +00004834 LoadedModuleInfoList::LoadedModuleInfo module;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004835
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004836 library.ForEachAttribute([log, &module](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
Ed Maste81b4c5f2016-01-04 01:43:47 +00004837
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004838 if (name == "name")
4839 module.set_name (value.str());
4840 else if (name == "lm")
4841 {
4842 // the address of the link_map struct.
4843 module.set_link_map(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4844 }
4845 else if (name == "l_addr")
4846 {
4847 // the displacement as read from the field 'l_addr' of the link_map struct.
4848 module.set_base(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
Stephane Sezerc6845a02015-08-20 22:07:48 +00004849 // base address is always a displacement, not an absolute value.
4850 module.set_base_is_offset(true);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004851 }
4852 else if (name == "l_ld")
4853 {
4854 // the memory address of the libraries PT_DYAMIC section.
4855 module.set_dynamic(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4856 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00004857
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004858 return true; // Keep iterating over all properties of "library"
4859 });
4860
4861 if (log)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004862 {
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004863 std::string name;
4864 lldb::addr_t lm=0, base=0, ld=0;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004865 bool base_is_offset;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004866
4867 module.get_name (name);
4868 module.get_link_map (lm);
4869 module.get_base (base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004870 module.get_base_is_offset (base_is_offset);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004871 module.get_dynamic (ld);
4872
Stephane Sezerc6845a02015-08-20 22:07:48 +00004873 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 +00004874 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004875
4876 list.add (module);
4877 return true; // Keep iterating over all "library" elements in the root node
Greg Claytond04f0ed2015-05-26 18:00:51 +00004878 });
Aidan Doddsc0c83852015-05-08 09:36:31 +00004879
4880 if (log)
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004881 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4882 } else if (comm.GetQXferLibrariesReadSupported ()) {
4883 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004884
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004885 // request the loaded library list
4886 std::string raw;
4887 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004888
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004889 if (!comm.ReadExtFeature (ConstString ("libraries"), ConstString (""), raw, lldberr))
4890 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004891
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004892 if (log)
4893 log->Printf ("parsing: %s", raw.c_str());
4894 XMLDocument doc;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004895
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004896 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4897 return Error (0, ErrorType::eErrorTypeGeneric);
4898
4899 XMLNode root_element = doc.GetRootElement("library-list");
4900 if (!root_element)
4901 return Error();
4902
4903 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
Stephane Sezer87b0fe02016-01-12 19:02:41 +00004904 LoadedModuleInfoList::LoadedModuleInfo module;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004905
4906 llvm::StringRef name = library.GetAttributeValue("name");
4907 module.set_name(name.str());
4908
4909 // The base address of a given library will be the address of its
4910 // first section. Most remotes send only one section for Windows
4911 // targets for example.
4912 const XMLNode &section = library.FindFirstChildElementWithName("section");
4913 llvm::StringRef address = section.GetAttributeValue("address");
4914 module.set_base(StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0));
Stephane Sezerc6845a02015-08-20 22:07:48 +00004915 // These addresses are absolute values.
4916 module.set_base_is_offset(false);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004917
4918 if (log)
4919 {
4920 std::string name;
4921 lldb::addr_t base = 0;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004922 bool base_is_offset;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004923 module.get_name (name);
4924 module.get_base (base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004925 module.get_base_is_offset (base_is_offset);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004926
Stephane Sezerc6845a02015-08-20 22:07:48 +00004927 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 +00004928 }
4929
4930 list.add (module);
4931 return true; // Keep iterating over all "library" elements in the root node
4932 });
4933
4934 if (log)
4935 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4936 } else {
4937 return Error (0, ErrorType::eErrorTypeGeneric);
4938 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004939
4940 return Error();
4941}
4942
Aidan Doddsc0c83852015-05-08 09:36:31 +00004943lldb::ModuleSP
Stephane Sezer3553c0e2016-04-05 17:25:32 +00004944ProcessGDBRemote::LoadModuleAtAddress (const FileSpec &file, lldb::addr_t link_map,
4945 lldb::addr_t base_addr, bool value_is_offset)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004946{
Stephane Sezer3553c0e2016-04-05 17:25:32 +00004947 DynamicLoader *loader = GetDynamicLoader();
4948 if (!loader)
4949 return nullptr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004950
Stephane Sezer3553c0e2016-04-05 17:25:32 +00004951 return loader->LoadModuleAtAddress(file, link_map, base_addr, value_is_offset);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004952}
4953
4954size_t
Stephane Sezer87b0fe02016-01-12 19:02:41 +00004955ProcessGDBRemote::LoadModules (LoadedModuleInfoList &module_list)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004956{
4957 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4958
4959 // request a list of loaded libraries from GDBServer
Aidan Doddsc0c83852015-05-08 09:36:31 +00004960 if (GetLoadedModuleList (module_list).Fail())
4961 return 0;
4962
4963 // get a list of all the modules
4964 ModuleList new_modules;
4965
Stephane Sezer87b0fe02016-01-12 19:02:41 +00004966 for (LoadedModuleInfoList::LoadedModuleInfo & modInfo : module_list.m_list)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004967 {
4968 std::string mod_name;
4969 lldb::addr_t mod_base;
Stephane Sezer3553c0e2016-04-05 17:25:32 +00004970 lldb::addr_t link_map;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004971 bool mod_base_is_offset;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004972
4973 bool valid = true;
4974 valid &= modInfo.get_name (mod_name);
4975 valid &= modInfo.get_base (mod_base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004976 valid &= modInfo.get_base_is_offset (mod_base_is_offset);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004977 if (!valid)
4978 continue;
4979
Stephane Sezer3553c0e2016-04-05 17:25:32 +00004980 if (!modInfo.get_link_map (link_map))
4981 link_map = LLDB_INVALID_ADDRESS;
4982
Francis Riccia0300612016-04-27 17:10:15 +00004983 FileSpec file (mod_name.c_str(), true);
Stephane Sezer3553c0e2016-04-05 17:25:32 +00004984 lldb::ModuleSP module_sp = LoadModuleAtAddress (file, link_map, mod_base,
4985 mod_base_is_offset);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004986
4987 if (module_sp.get())
4988 new_modules.Append (module_sp);
4989 }
4990
4991 if (new_modules.GetSize() > 0)
4992 {
Francis Riccibe8cab72016-04-25 21:02:24 +00004993 ModuleList removed_modules;
Zachary Turner7529df92015-09-01 20:02:29 +00004994 Target &target = GetTarget();
Francis Riccibe8cab72016-04-25 21:02:24 +00004995 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4996
4997 for (size_t i = 0; i < loaded_modules.GetSize(); ++i)
4998 {
4999 const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i);
5000
5001 bool found = false;
5002 for (size_t j = 0; j < new_modules.GetSize(); ++j)
5003 {
5004 if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get())
5005 found = true;
5006 }
5007
Francis Ricci80dbd152016-06-06 15:00:50 +00005008 // The main executable will never be included in libraries-svr4, don't remove it
5009 if (!found && loaded_module.get() != target.GetExecutableModulePointer())
Francis Riccibe8cab72016-04-25 21:02:24 +00005010 {
Francis Ricci80dbd152016-06-06 15:00:50 +00005011 removed_modules.Append (loaded_module);
Francis Riccibe8cab72016-04-25 21:02:24 +00005012 }
5013 }
5014
5015 loaded_modules.Remove (removed_modules);
5016 m_process->GetTarget().ModulesDidUnload (removed_modules, false);
Aidan Doddsc0c83852015-05-08 09:36:31 +00005017
5018 new_modules.ForEach ([&target](const lldb::ModuleSP module_sp) -> bool
5019 {
5020 lldb_private::ObjectFile * obj = module_sp->GetObjectFile ();
5021 if (!obj)
5022 return true;
5023
5024 if (obj->GetType () != ObjectFile::Type::eTypeExecutable)
5025 return true;
5026
5027 lldb::ModuleSP module_copy_sp = module_sp;
5028 target.SetExecutableModule (module_copy_sp, false);
5029 return false;
5030 });
5031
Aidan Doddsc0c83852015-05-08 09:36:31 +00005032 loaded_modules.AppendIfNeeded (new_modules);
5033 m_process->GetTarget().ModulesDidLoad (new_modules);
5034 }
5035
5036 return new_modules.GetSize();
Stephane Sezer87b0fe02016-01-12 19:02:41 +00005037}
5038
5039size_t
5040ProcessGDBRemote::LoadModules ()
5041{
5042 LoadedModuleInfoList module_list;
5043 return LoadModules (module_list);
Aidan Doddsc0c83852015-05-08 09:36:31 +00005044}
Colin Rileyc3c95b22015-04-16 15:51:33 +00005045
Tamas Berghammer783bfc82015-06-18 20:43:56 +00005046Error
5047ProcessGDBRemote::GetFileLoadAddress(const FileSpec& file, bool& is_loaded, lldb::addr_t& load_addr)
5048{
5049 is_loaded = false;
5050 load_addr = LLDB_INVALID_ADDRESS;
5051
5052 std::string file_path = file.GetPath(false);
5053 if (file_path.empty ())
5054 return Error("Empty file name specified");
5055
5056 StreamString packet;
5057 packet.PutCString("qFileLoadAddress:");
5058 packet.PutCStringAsRawHex8(file_path.c_str());
5059
5060 StringExtractorGDBRemote response;
5061 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString().c_str(), response, false) != GDBRemoteCommunication::PacketResult::Success)
5062 return Error("Sending qFileLoadAddress packet failed");
5063
5064 if (response.IsErrorResponse())
5065 {
5066 if (response.GetError() == 1)
5067 {
5068 // The file is not loaded into the inferior
5069 is_loaded = false;
5070 load_addr = LLDB_INVALID_ADDRESS;
5071 return Error();
5072 }
5073
5074 return Error("Fetching file load address from remote server returned an error");
5075 }
5076
5077 if (response.IsNormalResponse())
5078 {
5079 is_loaded = true;
5080 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
5081 return Error();
5082 }
5083
5084 return Error("Unknown error happened during sending the load address packet");
5085}
5086
Eugene Zelenko0722f082015-10-24 01:28:05 +00005087
Greg Clayton0b90be12015-06-23 21:27:50 +00005088void
5089ProcessGDBRemote::ModulesDidLoad (ModuleList &module_list)
5090{
5091 // We must call the lldb_private::Process::ModulesDidLoad () first before we do anything
5092 Process::ModulesDidLoad (module_list);
5093
5094 // After loading shared libraries, we can ask our remote GDB server if
5095 // it needs any symbols.
5096 m_gdb_comm.ServeSymbolLookups(this);
5097}
5098
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005099void
5100ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out)
5101{
5102 AppendSTDOUT(out.data(), out.size());
5103}
5104
5105static const char *end_delimiter = "--end--;";
5106static const int end_delimiter_len = 8;
5107
5108void
5109ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data)
5110{
5111 std::string input = data.str(); // '1' to move beyond 'A'
5112 if (m_partial_profile_data.length() > 0)
5113 {
5114 m_partial_profile_data.append(input);
5115 input = m_partial_profile_data;
5116 m_partial_profile_data.clear();
5117 }
5118
5119 size_t found, pos = 0, len = input.length();
5120 while ((found = input.find(end_delimiter, pos)) != std::string::npos)
5121 {
5122 StringExtractorGDBRemote profileDataExtractor(input.substr(pos, found).c_str());
5123 std::string profile_data = HarmonizeThreadIdsForProfileData(profileDataExtractor);
5124 BroadcastAsyncProfileData(profile_data);
5125
5126 pos = found + end_delimiter_len;
5127 }
5128
5129 if (pos < len)
5130 {
5131 // Last incomplete chunk.
5132 m_partial_profile_data = input.substr(pos);
5133 }
5134}
5135
5136std::string
5137ProcessGDBRemote::HarmonizeThreadIdsForProfileData(StringExtractorGDBRemote &profileDataExtractor)
5138{
5139 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
5140 std::stringstream final_output;
5141 std::string name, value;
5142
5143 // Going to assuming thread_used_usec comes first, else bail out.
5144 while (profileDataExtractor.GetNameColonValue(name, value))
5145 {
5146 if (name.compare("thread_used_id") == 0)
5147 {
5148 StringExtractor threadIDHexExtractor(value.c_str());
5149 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
5150
5151 bool has_used_usec = false;
5152 uint32_t curr_used_usec = 0;
5153 std::string usec_name, usec_value;
5154 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
5155 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value))
5156 {
5157 if (usec_name.compare("thread_used_usec") == 0)
5158 {
5159 has_used_usec = true;
5160 curr_used_usec = strtoull(usec_value.c_str(), NULL, 0);
5161 }
5162 else
5163 {
5164 // We didn't find what we want, it is probably
5165 // an older version. Bail out.
5166 profileDataExtractor.SetFilePos(input_file_pos);
5167 }
5168 }
5169
5170 if (has_used_usec)
5171 {
5172 uint32_t prev_used_usec = 0;
5173 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_used_usec_map.find(thread_id);
5174 if (iterator != m_thread_id_to_used_usec_map.end())
5175 {
5176 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
5177 }
5178
5179 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
5180 // A good first time record is one that runs for at least 0.25 sec
5181 bool good_first_time = (prev_used_usec == 0) && (real_used_usec > 250000);
5182 bool good_subsequent_time =
5183 (prev_used_usec > 0) && ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id)));
5184
5185 if (good_first_time || good_subsequent_time)
5186 {
5187 // We try to avoid doing too many index id reservation,
5188 // resulting in fast increase of index ids.
5189
5190 final_output << name << ":";
5191 int32_t index_id = AssignIndexIDToThread(thread_id);
5192 final_output << index_id << ";";
5193
5194 final_output << usec_name << ":" << usec_value << ";";
5195 }
5196 else
5197 {
5198 // Skip past 'thread_used_name'.
5199 std::string local_name, local_value;
5200 profileDataExtractor.GetNameColonValue(local_name, local_value);
5201 }
5202
5203 // Store current time as previous time so that they can be compared later.
5204 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
5205 }
5206 else
5207 {
5208 // Bail out and use old string.
5209 final_output << name << ":" << value << ";";
5210 }
5211 }
5212 else
5213 {
5214 final_output << name << ":" << value << ";";
5215 }
5216 }
5217 final_output << end_delimiter;
5218 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
5219
5220 return final_output.str();
5221}
5222
5223void
5224ProcessGDBRemote::HandleStopReply()
5225{
5226 if (GetStopID() != 0)
5227 return;
5228
5229 if (GetID() == LLDB_INVALID_PROCESS_ID)
5230 {
5231 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
5232 if (pid != LLDB_INVALID_PROCESS_ID)
5233 SetID(pid);
5234 }
5235 BuildDynamicRegisterInfo(true);
5236}
Eugene Zelenko0722f082015-10-24 01:28:05 +00005237
Greg Claytone034a042015-05-21 20:52:06 +00005238class CommandObjectProcessGDBRemoteSpeedTest: public CommandObjectParsed
5239{
5240public:
5241 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter) :
5242 CommandObjectParsed (interpreter,
5243 "process plugin packet speed-test",
5244 "Tests packet speeds of various sizes to determine the performance characteristics of the GDB remote connection. ",
5245 NULL),
Todd Fialae1cfbc72016-08-11 23:51:28 +00005246 m_option_group (),
Greg Claytone034a042015-05-21 20:52:06 +00005247 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),
5248 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),
5249 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),
5250 m_json (LLDB_OPT_SET_1, false, "json", 'j', "Print the output as JSON data for easy parsing.", false, true)
5251 {
5252 m_option_group.Append (&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5253 m_option_group.Append (&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5254 m_option_group.Append (&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5255 m_option_group.Append (&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
5256 m_option_group.Finalize();
5257 }
5258
Eugene Zelenko0722f082015-10-24 01:28:05 +00005259 ~CommandObjectProcessGDBRemoteSpeedTest ()
5260 {
5261 }
5262
Greg Claytone034a042015-05-21 20:52:06 +00005263
5264 Options *
5265 GetOptions () override
5266 {
5267 return &m_option_group;
5268 }
5269
5270 bool
5271 DoExecute (Args& command, CommandReturnObject &result) override
5272 {
5273 const size_t argc = command.GetArgumentCount();
5274 if (argc == 0)
5275 {
5276 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5277 if (process)
5278 {
5279 StreamSP output_stream_sp (m_interpreter.GetDebugger().GetAsyncOutputStream());
5280 result.SetImmediateOutputStream (output_stream_sp);
5281
5282 const uint32_t num_packets = (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
5283 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
5284 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
5285 const bool json = m_json.GetOptionValue().GetCurrentValue();
5286 if (output_stream_sp)
5287 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, *output_stream_sp);
5288 else
5289 {
5290 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, result.GetOutputStream());
5291 }
5292 result.SetStatus (eReturnStatusSuccessFinishResult);
5293 return true;
5294 }
5295 }
5296 else
5297 {
5298 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
5299 }
5300 result.SetStatus (eReturnStatusFailed);
5301 return false;
5302 }
5303protected:
5304 OptionGroupOptions m_option_group;
5305 OptionGroupUInt64 m_num_packets;
5306 OptionGroupUInt64 m_max_send;
5307 OptionGroupUInt64 m_max_recv;
5308 OptionGroupBoolean m_json;
Eugene Zelenko0722f082015-10-24 01:28:05 +00005309
Greg Claytone034a042015-05-21 20:52:06 +00005310};
5311
Greg Clayton02686b82012-10-15 22:42:16 +00005312class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00005313{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005314private:
Ed Maste81b4c5f2016-01-04 01:43:47 +00005315
Greg Clayton998255b2012-10-13 02:07:45 +00005316public:
Greg Clayton02686b82012-10-15 22:42:16 +00005317 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00005318 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00005319 "process plugin packet history",
5320 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00005321 NULL)
5322 {
5323 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005324
Eugene Zelenko0722f082015-10-24 01:28:05 +00005325 ~CommandObjectProcessGDBRemotePacketHistory ()
5326 {
5327 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005328
Greg Clayton998255b2012-10-13 02:07:45 +00005329 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005330 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton998255b2012-10-13 02:07:45 +00005331 {
Greg Clayton02686b82012-10-15 22:42:16 +00005332 const size_t argc = command.GetArgumentCount();
5333 if (argc == 0)
5334 {
5335 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5336 if (process)
5337 {
5338 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
5339 result.SetStatus (eReturnStatusSuccessFinishResult);
5340 return true;
5341 }
5342 }
5343 else
5344 {
5345 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
5346 }
5347 result.SetStatus (eReturnStatusFailed);
5348 return false;
5349 }
5350};
5351
Jason Molenda6076bf42014-05-06 04:34:52 +00005352class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed
5353{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005354private:
Ed Maste81b4c5f2016-01-04 01:43:47 +00005355
Jason Molenda6076bf42014-05-06 04:34:52 +00005356public:
5357 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) :
5358 CommandObjectParsed (interpreter,
5359 "process plugin packet xfer-size",
5360 "Maximum size that lldb will try to read/write one one chunk.",
5361 NULL)
5362 {
5363 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005364
Eugene Zelenko0722f082015-10-24 01:28:05 +00005365 ~CommandObjectProcessGDBRemotePacketXferSize ()
5366 {
5367 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005368
Jason Molenda6076bf42014-05-06 04:34:52 +00005369 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005370 DoExecute (Args& command, CommandReturnObject &result) override
Jason Molenda6076bf42014-05-06 04:34:52 +00005371 {
5372 const size_t argc = command.GetArgumentCount();
5373 if (argc == 0)
5374 {
5375 result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str());
5376 result.SetStatus (eReturnStatusFailed);
5377 return false;
5378 }
5379
5380 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5381 if (process)
5382 {
5383 const char *packet_size = command.GetArgumentAtIndex(0);
5384 errno = 0;
5385 uint64_t user_specified_max = strtoul (packet_size, NULL, 10);
5386 if (errno == 0 && user_specified_max != 0)
5387 {
5388 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max);
5389 result.SetStatus (eReturnStatusSuccessFinishResult);
5390 return true;
5391 }
5392 }
5393 result.SetStatus (eReturnStatusFailed);
5394 return false;
5395 }
5396};
5397
Eugene Zelenko0722f082015-10-24 01:28:05 +00005398
Greg Clayton02686b82012-10-15 22:42:16 +00005399class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
5400{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005401private:
Ed Maste81b4c5f2016-01-04 01:43:47 +00005402
Greg Clayton02686b82012-10-15 22:42:16 +00005403public:
5404 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
5405 CommandObjectParsed (interpreter,
5406 "process plugin packet send",
5407 "Send a custom packet through the GDB remote protocol and print the answer. "
5408 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
5409 NULL)
5410 {
5411 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005412
Eugene Zelenko0722f082015-10-24 01:28:05 +00005413 ~CommandObjectProcessGDBRemotePacketSend ()
5414 {
5415 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005416
Greg Clayton02686b82012-10-15 22:42:16 +00005417 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005418 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton02686b82012-10-15 22:42:16 +00005419 {
5420 const size_t argc = command.GetArgumentCount();
5421 if (argc == 0)
5422 {
5423 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
5424 result.SetStatus (eReturnStatusFailed);
5425 return false;
5426 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005427
Greg Clayton02686b82012-10-15 22:42:16 +00005428 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5429 if (process)
5430 {
Han Ming Ong84145852012-11-26 20:42:03 +00005431 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00005432 {
Han Ming Ong84145852012-11-26 20:42:03 +00005433 const char *packet_cstr = command.GetArgumentAtIndex(0);
5434 bool send_async = true;
5435 StringExtractorGDBRemote response;
5436 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
5437 result.SetStatus (eReturnStatusSuccessFinishResult);
5438 Stream &output_strm = result.GetOutputStream();
5439 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00005440 std::string &response_str = response.GetStringRef();
Ed Maste81b4c5f2016-01-04 01:43:47 +00005441
Han Ming Ong399289e2013-06-21 19:56:59 +00005442 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00005443 {
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00005444 response_str = process->HarmonizeThreadIdsForProfileData(response);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00005445 }
5446
Han Ming Ong84145852012-11-26 20:42:03 +00005447 if (response_str.empty())
5448 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
5449 else
5450 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00005451 }
Greg Clayton02686b82012-10-15 22:42:16 +00005452 }
Greg Clayton998255b2012-10-13 02:07:45 +00005453 return true;
5454 }
5455};
5456
Greg Claytonba4a0a52013-02-01 23:03:47 +00005457class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
5458{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005459private:
Ed Maste81b4c5f2016-01-04 01:43:47 +00005460
Greg Claytonba4a0a52013-02-01 23:03:47 +00005461public:
5462 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
5463 CommandObjectRaw (interpreter,
5464 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00005465 "Send a qRcmd packet through the GDB remote protocol and print the response."
5466 "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 +00005467 NULL)
5468 {
5469 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005470
Eugene Zelenko0722f082015-10-24 01:28:05 +00005471 ~CommandObjectProcessGDBRemotePacketMonitor ()
5472 {
5473 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005474
Greg Claytonba4a0a52013-02-01 23:03:47 +00005475 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005476 DoExecute (const char *command, CommandReturnObject &result) override
Greg Claytonba4a0a52013-02-01 23:03:47 +00005477 {
5478 if (command == NULL || command[0] == '\0')
5479 {
5480 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
5481 result.SetStatus (eReturnStatusFailed);
5482 return false;
5483 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005484
Greg Claytonba4a0a52013-02-01 23:03:47 +00005485 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5486 if (process)
5487 {
5488 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00005489 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00005490 packet.PutBytesAsRawHex8(command, strlen(command));
5491 const char *packet_cstr = packet.GetString().c_str();
Ed Maste81b4c5f2016-01-04 01:43:47 +00005492
Greg Claytonba4a0a52013-02-01 23:03:47 +00005493 bool send_async = true;
5494 StringExtractorGDBRemote response;
5495 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
5496 result.SetStatus (eReturnStatusSuccessFinishResult);
5497 Stream &output_strm = result.GetOutputStream();
5498 output_strm.Printf (" packet: %s\n", packet_cstr);
5499 const std::string &response_str = response.GetStringRef();
Ed Maste81b4c5f2016-01-04 01:43:47 +00005500
Greg Claytonba4a0a52013-02-01 23:03:47 +00005501 if (response_str.empty())
5502 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
5503 else
5504 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
5505 }
5506 return true;
5507 }
5508};
5509
Greg Clayton02686b82012-10-15 22:42:16 +00005510class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
5511{
Eugene Zelenko0722f082015-10-24 01:28:05 +00005512private:
Ed Maste81b4c5f2016-01-04 01:43:47 +00005513
Greg Clayton02686b82012-10-15 22:42:16 +00005514public:
5515 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
5516 CommandObjectMultiword (interpreter,
5517 "process plugin packet",
5518 "Commands that deal with GDB remote packets.",
5519 NULL)
5520 {
5521 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
5522 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00005523 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Jason Molenda6076bf42014-05-06 04:34:52 +00005524 LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter)));
Greg Claytone034a042015-05-21 20:52:06 +00005525 LoadSubCommand ("speed-test", CommandObjectSP (new CommandObjectProcessGDBRemoteSpeedTest (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00005526 }
Ed Maste81b4c5f2016-01-04 01:43:47 +00005527
Eugene Zelenko0722f082015-10-24 01:28:05 +00005528 ~CommandObjectProcessGDBRemotePacket ()
5529 {
Ed Maste81b4c5f2016-01-04 01:43:47 +00005530 }
Greg Clayton02686b82012-10-15 22:42:16 +00005531};
Greg Clayton998255b2012-10-13 02:07:45 +00005532
5533class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
5534{
5535public:
Kate Stone7428a182016-07-14 22:03:10 +00005536 CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter)
5537 : CommandObjectMultiword(interpreter, "process plugin", "Commands for operating on a ProcessGDBRemote process.",
5538 "process plugin <subcommand> [<subcommand-options>]")
Greg Clayton998255b2012-10-13 02:07:45 +00005539 {
5540 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
5541 }
5542
Eugene Zelenko0722f082015-10-24 01:28:05 +00005543 ~CommandObjectMultiwordProcessGDBRemote ()
5544 {
5545 }
Greg Clayton998255b2012-10-13 02:07:45 +00005546};
5547
Greg Clayton998255b2012-10-13 02:07:45 +00005548CommandObject *
5549ProcessGDBRemote::GetPluginCommandObject()
5550{
5551 if (!m_command_sp)
5552 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
5553 return m_command_sp.get();
5554}