blob: 92027bb2a3b7cb07e887e0a567700d5d77d79ae8 [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
Virgile Bellob2f1fb22013-08-23 12:44:05 +000010#include "lldb/Host/Config.h"
Daniel Malea93a64302012-12-05 00:20:57 +000011
Chris Lattner30fdc8d2010-06-08 16:52:24 +000012// C Includes
13#include <errno.h>
Stephen Wilsona78867b2011-03-25 18:16:28 +000014#include <stdlib.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000015#ifndef LLDB_DISABLE_POSIX
Sean Callanan224f6f52012-07-19 18:07:36 +000016#include <netinet/in.h>
Greg Clayton2a48f522011-05-14 01:50:35 +000017#include <sys/mman.h> // for mmap
Virgile Bellob2f1fb22013-08-23 12:44:05 +000018#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000019#include <sys/stat.h>
Greg Clayton2a48f522011-05-14 01:50:35 +000020#include <sys/types.h>
Stephen Wilsondc916862011-03-30 00:12:40 +000021#include <time.h>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000022
23// C++ Includes
24#include <algorithm>
25#include <map>
Benjamin Kramer3f69fa62015-04-03 10:55:00 +000026#include <mutex>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000027
Johnny Chen01a67862011-10-14 00:42:25 +000028#include "lldb/Breakpoint/Watchpoint.h"
Jim Ingham40af72e2010-06-15 19:49:27 +000029#include "lldb/Interpreter/Args.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000030#include "lldb/Core/ArchSpec.h"
31#include "lldb/Core/Debugger.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000032#include "lldb/Host/ConnectionFileDescriptor.h"
Greg Clayton53239f02011-02-08 05:05:52 +000033#include "lldb/Host/FileSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000034#include "lldb/Core/Module.h"
Greg Clayton1f746072012-08-29 21:13:06 +000035#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000036#include "lldb/Core/PluginManager.h"
37#include "lldb/Core/State.h"
Greg Claytond451c1a2012-04-13 21:24:18 +000038#include "lldb/Core/StreamFile.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000039#include "lldb/Core/StreamString.h"
40#include "lldb/Core/Timer.h"
Greg Clayton70b57652011-05-15 01:25:55 +000041#include "lldb/Core/Value.h"
Greg Claytond04f0ed2015-05-26 18:00:51 +000042#include "lldb/DataFormatters/FormatManager.h"
Zachary Turner39de3112014-09-09 20:54:56 +000043#include "lldb/Host/HostThread.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000044#include "lldb/Host/StringConvert.h"
Jason Molendad1fae142012-09-29 08:03:33 +000045#include "lldb/Host/Symbols.h"
Zachary Turner39de3112014-09-09 20:54:56 +000046#include "lldb/Host/ThreadLauncher.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000047#include "lldb/Host/TimeValue.h"
Greg Claytond04f0ed2015-05-26 18:00:51 +000048#include "lldb/Host/XML.h"
Greg Clayton02686b82012-10-15 22:42:16 +000049#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton1d19a2f2012-10-19 22:22:57 +000050#include "lldb/Interpreter/CommandObject.h"
51#include "lldb/Interpreter/CommandObjectMultiword.h"
Greg Clayton02686b82012-10-15 22:42:16 +000052#include "lldb/Interpreter/CommandReturnObject.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000053#include "lldb/Interpreter/OptionValueProperties.h"
Greg Claytone034a042015-05-21 20:52:06 +000054#include "lldb/Interpreter/Options.h"
55#include "lldb/Interpreter/OptionGroupBoolean.h"
56#include "lldb/Interpreter/OptionGroupUInt64.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000057#include "lldb/Interpreter/Property.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000058#include "lldb/Symbol/ObjectFile.h"
59#include "lldb/Target/DynamicLoader.h"
60#include "lldb/Target/Target.h"
61#include "lldb/Target/TargetList.h"
Greg Clayton2a48f522011-05-14 01:50:35 +000062#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molenda705b1802014-06-13 02:37:02 +000063#include "lldb/Target/SystemRuntime.h"
Jason Molendaa34a0c62010-06-09 21:28:42 +000064#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000065
66// Project includes
67#include "lldb/Host/Host.h"
Chaoren Lin98d0a4b2015-07-14 01:09:28 +000068#include "Plugins/Process/Utility/GDBRemoteSignals.h"
Peter Collingbourne99f9aa02011-06-03 20:40:38 +000069#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Jason Molendac42d2432012-07-25 03:40:06 +000070#include "Plugins/Process/Utility/StopInfoMachException.h"
Jim Ingham43c555d2012-07-04 00:35:43 +000071#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
Greg Claytonc982c762010-07-09 20:39:50 +000072#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000073#include "GDBRemoteRegisterContext.h"
74#include "ProcessGDBRemote.h"
75#include "ProcessGDBRemoteLog.h"
76#include "ThreadGDBRemote.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000077
Tamas Berghammerdb264a62015-03-31 09:52:22 +000078#define DEBUGSERVER_BASENAME "debugserver"
79using namespace lldb;
80using namespace lldb_private;
81using namespace lldb_private::process_gdb_remote;
Jason Molenda5e8534e2012-10-03 01:29:34 +000082
Greg Claytonc1422c12012-04-09 22:46:21 +000083namespace lldb
84{
85 // Provide a function that can easily dump the packet history if we know a
86 // ProcessGDBRemote * value (which we can get from logs or from debugging).
87 // We need the function in the lldb namespace so it makes it into the final
88 // executable since the LLDB shared library only exports stuff in the lldb
89 // namespace. This allows you to attach with a debugger and call this
90 // function and get the packet history dumped to a file.
91 void
92 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
93 {
Tamas Berghammerdb264a62015-03-31 09:52:22 +000094 StreamFile strm;
95 Error error (strm.GetFile().Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate));
Greg Claytond451c1a2012-04-13 21:24:18 +000096 if (error.Success())
97 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
Greg Claytonc1422c12012-04-09 22:46:21 +000098 }
Filipe Cabecinhasc34f7762012-05-23 16:27:09 +000099}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000100
Greg Clayton7f982402013-07-15 22:54:20 +0000101namespace {
Steve Pucci5ec012d2014-01-16 22:18:14 +0000102
Greg Clayton7f982402013-07-15 22:54:20 +0000103 static PropertyDefinition
104 g_properties[] =
105 {
106 { "packet-timeout" , OptionValue::eTypeUInt64 , true , 1, NULL, NULL, "Specify the default packet timeout in seconds." },
Greg Claytonef8180a2013-10-15 00:14:28 +0000107 { "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 +0000108 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
109 };
110
111 enum
112 {
Greg Claytonef8180a2013-10-15 00:14:28 +0000113 ePropertyPacketTimeout,
114 ePropertyTargetDefinitionFile
Greg Clayton7f982402013-07-15 22:54:20 +0000115 };
116
117 class PluginProperties : public Properties
118 {
119 public:
120
121 static ConstString
122 GetSettingName ()
123 {
124 return ProcessGDBRemote::GetPluginNameStatic();
125 }
126
127 PluginProperties() :
128 Properties ()
129 {
130 m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
131 m_collection_sp->Initialize(g_properties);
132 }
133
134 virtual
135 ~PluginProperties()
136 {
137 }
138
139 uint64_t
140 GetPacketTimeout()
141 {
142 const uint32_t idx = ePropertyPacketTimeout;
143 return m_collection_sp->GetPropertyAtIndexAsUInt64(NULL, idx, g_properties[idx].default_uint_value);
144 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000145
146 bool
147 SetPacketTimeout(uint64_t timeout)
148 {
149 const uint32_t idx = ePropertyPacketTimeout;
150 return m_collection_sp->SetPropertyAtIndexAsUInt64(NULL, idx, timeout);
151 }
152
Greg Claytonef8180a2013-10-15 00:14:28 +0000153 FileSpec
154 GetTargetDefinitionFile () const
155 {
156 const uint32_t idx = ePropertyTargetDefinitionFile;
157 return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
158 }
Greg Clayton7f982402013-07-15 22:54:20 +0000159 };
160
161 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
162
163 static const ProcessKDPPropertiesSP &
164 GetGlobalPluginProperties()
165 {
166 static ProcessKDPPropertiesSP g_settings_sp;
167 if (!g_settings_sp)
168 g_settings_sp.reset (new PluginProperties ());
169 return g_settings_sp;
170 }
171
172} // anonymous namespace end
173
Aidan Doddsc0c83852015-05-08 09:36:31 +0000174class ProcessGDBRemote::GDBLoadedModuleInfoList
175{
176public:
177
178 class LoadedModuleInfo
179 {
180 public:
181
182 enum e_data_point
183 {
184 e_has_name = 0,
185 e_has_base ,
186 e_has_dynamic ,
187 e_has_link_map ,
188 e_num
189 };
190
191 LoadedModuleInfo ()
192 {
193 for (uint32_t i = 0; i < e_num; ++i)
194 m_has[i] = false;
Pavel Labathcb213b32015-07-22 08:12:01 +0000195 }
Aidan Doddsc0c83852015-05-08 09:36:31 +0000196
197 void set_name (const std::string & name)
198 {
199 m_name = name;
200 m_has[e_has_name] = true;
201 }
202 bool get_name (std::string & out) const
203 {
204 out = m_name;
205 return m_has[e_has_name];
206 }
207
208 void set_base (const lldb::addr_t base)
209 {
210 m_base = base;
211 m_has[e_has_base] = true;
212 }
213 bool get_base (lldb::addr_t & out) const
214 {
215 out = m_base;
216 return m_has[e_has_base];
217 }
218
Stephane Sezerc6845a02015-08-20 22:07:48 +0000219 void set_base_is_offset (bool is_offset)
220 {
221 m_base_is_offset = is_offset;
222 }
223 bool get_base_is_offset(bool & out) const
224 {
225 out = m_base_is_offset;
226 return m_has[e_has_base];
227 }
228
Aidan Doddsc0c83852015-05-08 09:36:31 +0000229 void set_link_map (const lldb::addr_t addr)
230 {
231 m_link_map = addr;
232 m_has[e_has_link_map] = true;
233 }
234 bool get_link_map (lldb::addr_t & out) const
235 {
236 out = m_link_map;
237 return m_has[e_has_link_map];
238 }
239
240 void set_dynamic (const lldb::addr_t addr)
241 {
242 m_dynamic = addr;
243 m_has[e_has_dynamic] = true;
244 }
245 bool get_dynamic (lldb::addr_t & out) const
246 {
247 out = m_dynamic;
248 return m_has[e_has_dynamic];
249 }
250
251 bool has_info (e_data_point datum)
252 {
253 assert (datum < e_num);
254 return m_has[datum];
255 }
256
257 protected:
258
259 bool m_has[e_num];
260 std::string m_name;
261 lldb::addr_t m_link_map;
262 lldb::addr_t m_base;
Stephane Sezerc6845a02015-08-20 22:07:48 +0000263 bool m_base_is_offset;
Aidan Doddsc0c83852015-05-08 09:36:31 +0000264 lldb::addr_t m_dynamic;
265 };
266
267 GDBLoadedModuleInfoList ()
268 : m_list ()
269 , m_link_map (LLDB_INVALID_ADDRESS)
270 {}
271
272 void add (const LoadedModuleInfo & mod)
273 {
274 m_list.push_back (mod);
275 }
276
277 void clear ()
278 {
279 m_list.clear ();
280 }
281
282 std::vector<LoadedModuleInfo> m_list;
283 lldb::addr_t m_link_map;
284};
285
Greg Claytonfda4fab2014-01-10 22:24:11 +0000286// TODO Randomly assigning a port is unsafe. We should get an unused
287// ephemeral port from the kernel and make sure we reserve it before passing
288// it to debugserver.
289
290#if defined (__APPLE__)
291#define LOW_PORT (IPPORT_RESERVED)
292#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
293#else
294#define LOW_PORT (1024u)
295#define HIGH_PORT (49151u)
296#endif
297
Todd Fiala013434e2014-07-09 01:29:05 +0000298#if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000299static bool rand_initialized = false;
300
Greg Claytonfda4fab2014-01-10 22:24:11 +0000301static inline uint16_t
302get_random_port ()
303{
304 if (!rand_initialized)
305 {
306 time_t seed = time(NULL);
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000307
Greg Claytonfda4fab2014-01-10 22:24:11 +0000308 rand_initialized = true;
309 srand(seed);
310 }
311 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
312}
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000313#endif
Greg Claytonfda4fab2014-01-10 22:24:11 +0000314
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000315ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000316ProcessGDBRemote::GetPluginNameStatic()
317{
Greg Clayton57abc5d2013-05-10 21:47:16 +0000318 static ConstString g_name("gdb-remote");
319 return g_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000320}
321
322const char *
323ProcessGDBRemote::GetPluginDescriptionStatic()
324{
325 return "GDB Remote protocol based debugging plug-in.";
326}
327
328void
329ProcessGDBRemote::Terminate()
330{
331 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
332}
333
334
Greg Claytonc3776bf2012-02-09 06:16:32 +0000335lldb::ProcessSP
336ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000337{
Greg Claytonc3776bf2012-02-09 06:16:32 +0000338 lldb::ProcessSP process_sp;
339 if (crash_file_path == NULL)
340 process_sp.reset (new ProcessGDBRemote (target, listener));
341 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000342}
343
344bool
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000345ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000346{
Greg Clayton596ed242011-10-21 21:41:45 +0000347 if (plugin_specified_by_name)
348 return true;
349
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000350 // For now we are just making sure the file exists for a given module
Greg Claytonaa149cb2011-08-11 02:48:45 +0000351 Module *exe_module = target.GetExecutableModulePointer();
352 if (exe_module)
Greg Claytonc3776bf2012-02-09 06:16:32 +0000353 {
354 ObjectFile *exe_objfile = exe_module->GetObjectFile();
355 // We can't debug core files...
356 switch (exe_objfile->GetType())
357 {
358 case ObjectFile::eTypeInvalid:
359 case ObjectFile::eTypeCoreFile:
360 case ObjectFile::eTypeDebugInfo:
361 case ObjectFile::eTypeObjectFile:
362 case ObjectFile::eTypeSharedLibrary:
363 case ObjectFile::eTypeStubLibrary:
Greg Clayton23f8c952014-03-24 23:10:19 +0000364 case ObjectFile::eTypeJIT:
Greg Claytonc3776bf2012-02-09 06:16:32 +0000365 return false;
366 case ObjectFile::eTypeExecutable:
367 case ObjectFile::eTypeDynamicLinker:
368 case ObjectFile::eTypeUnknown:
369 break;
370 }
Greg Claytonaa149cb2011-08-11 02:48:45 +0000371 return exe_module->GetFileSpec().Exists();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000372 }
Jim Ingham5aee1622010-08-09 23:31:02 +0000373 // However, if there is no executable module, we return true since we might be preparing to attach.
374 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000375}
376
377//----------------------------------------------------------------------
378// ProcessGDBRemote constructor
379//----------------------------------------------------------------------
380ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
381 Process (target, listener),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000382 m_flags (0),
Tamas Berghammere13c2732015-02-11 10:29:30 +0000383 m_gdb_comm (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000384 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Bhushan D. Attarde1e271df2015-07-24 04:06:20 +0000385 m_last_stop_packet_mutex (Mutex::eMutexTypeRecursive),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000386 m_register_info (),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000387 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
Jim Ingham455fa5c2012-11-01 01:15:33 +0000388 m_async_thread_state_mutex(Mutex::eMutexTypeRecursive),
Greg Clayton9e920902012-04-10 02:25:43 +0000389 m_thread_ids (),
Greg Clayton2e309072015-07-17 23:42:28 +0000390 m_jstopinfo_sp (),
391 m_jthreadsinfo_sp (),
Greg Clayton71fc2a32011-02-12 06:28:37 +0000392 m_continue_c_tids (),
393 m_continue_C_tids (),
394 m_continue_s_tids (),
395 m_continue_S_tids (),
Jason Molenda6076bf42014-05-06 04:34:52 +0000396 m_max_memory_size (0),
397 m_remote_stub_max_memory_size (0),
Greg Clayton4116e932012-05-15 02:33:01 +0000398 m_addr_to_mmap_size (),
399 m_thread_create_bp_sp (),
Jim Ingham43c555d2012-07-04 00:35:43 +0000400 m_waiting_for_attach (false),
Jason Molenda5e8534e2012-10-03 01:29:34 +0000401 m_destroy_tried_resuming (false),
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000402 m_command_sp (),
Ewan Crawford78baa192015-05-13 09:18:18 +0000403 m_breakpoint_pc_offset (0),
404 m_initial_tid (LLDB_INVALID_THREAD_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000405{
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000406 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
407 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Inghamb1e2e842012-04-12 18:49:31 +0000408 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Greg Clayton7f982402013-07-15 22:54:20 +0000409 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
410 if (timeout_seconds > 0)
411 m_gdb_comm.SetPacketTimeout(timeout_seconds);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000412}
413
414//----------------------------------------------------------------------
415// Destructor
416//----------------------------------------------------------------------
417ProcessGDBRemote::~ProcessGDBRemote()
418{
419 // m_mach_process.UnregisterNotificationCallbacks (this);
420 Clear();
Greg Clayton1ed54f52011-10-01 00:45:15 +0000421 // We need to call finalize on the process before destroying ourselves
422 // to make sure all of the broadcaster cleanup goes as planned. If we
423 // destruct this class, then Process::~Process() might have problems
424 // trying to fully destroy the broadcaster.
425 Finalize();
Jim Ingham455fa5c2012-11-01 01:15:33 +0000426
427 // The general Finalize is going to try to destroy the process and that SHOULD
428 // shut down the async thread. However, if we don't kill it it will get stranded and
429 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
430 StopAsyncThread();
431 KillDebugserverProcess();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000432}
433
434//----------------------------------------------------------------------
435// PluginInterface
436//----------------------------------------------------------------------
Greg Clayton57abc5d2013-05-10 21:47:16 +0000437ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000438ProcessGDBRemote::GetPluginName()
439{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000440 return GetPluginNameStatic();
441}
442
443uint32_t
444ProcessGDBRemote::GetPluginVersion()
445{
446 return 1;
447}
448
Greg Claytonef8180a2013-10-15 00:14:28 +0000449bool
450ProcessGDBRemote::ParsePythonTargetDefinition(const FileSpec &target_definition_fspec)
451{
452 ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
453 Error error;
Zachary Turner0641ca12015-03-17 20:04:04 +0000454 StructuredData::ObjectSP module_object_sp(interpreter->LoadPluginModule(target_definition_fspec, error));
Greg Claytonef8180a2013-10-15 00:14:28 +0000455 if (module_object_sp)
456 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000457 StructuredData::DictionarySP target_definition_sp(
458 interpreter->GetDynamicSettings(module_object_sp, &GetTarget(), "gdb-server-target-definition", error));
Greg Claytonef8180a2013-10-15 00:14:28 +0000459
Zachary Turner0641ca12015-03-17 20:04:04 +0000460 if (target_definition_sp)
Greg Claytonef8180a2013-10-15 00:14:28 +0000461 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000462 StructuredData::ObjectSP target_object(target_definition_sp->GetValueForKey("host-info"));
463 if (target_object)
Greg Clayton312bcbe2013-10-17 01:10:23 +0000464 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000465 if (auto host_info_dict = target_object->GetAsDictionary())
Greg Clayton312bcbe2013-10-17 01:10:23 +0000466 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000467 StructuredData::ObjectSP triple_value = host_info_dict->GetValueForKey("triple");
468 if (auto triple_string_value = triple_value->GetAsString())
469 {
470 std::string triple_string = triple_string_value->GetValue();
471 ArchSpec host_arch(triple_string.c_str());
472 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture()))
473 {
474 GetTarget().SetArchitecture(host_arch);
475 }
476 }
Greg Clayton312bcbe2013-10-17 01:10:23 +0000477 }
Greg Clayton312bcbe2013-10-17 01:10:23 +0000478 }
Zachary Turner0641ca12015-03-17 20:04:04 +0000479 m_breakpoint_pc_offset = 0;
480 StructuredData::ObjectSP breakpoint_pc_offset_value = target_definition_sp->GetValueForKey("breakpoint-pc-offset");
481 if (breakpoint_pc_offset_value)
482 {
483 if (auto breakpoint_pc_int_value = breakpoint_pc_offset_value->GetAsInteger())
484 m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
485 }
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000486
Greg Claytond04f0ed2015-05-26 18:00:51 +0000487 if (m_register_info.SetRegisterInfo(*target_definition_sp, GetTarget().GetArchitecture()) > 0)
Greg Claytonef8180a2013-10-15 00:14:28 +0000488 {
489 return true;
490 }
491 }
492 }
493 return false;
494}
495
Greg Claytond04f0ed2015-05-26 18:00:51 +0000496static size_t
497SplitCommaSeparatedRegisterNumberString(const llvm::StringRef &comma_separated_regiter_numbers, std::vector<uint32_t> &regnums, int base)
498{
499 regnums.clear();
500 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
501 value_pair.second = comma_separated_regiter_numbers;
502 do
503 {
504 value_pair = value_pair.second.split(',');
505 if (!value_pair.first.empty())
506 {
507 uint32_t reg = StringConvert::ToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, base);
508 if (reg != LLDB_INVALID_REGNUM)
509 regnums.push_back (reg);
510 }
511 } while (!value_pair.second.empty());
512 return regnums.size();
513}
514
Greg Claytonef8180a2013-10-15 00:14:28 +0000515
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000516void
Greg Clayton513c26c2011-01-29 07:10:55 +0000517ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000518{
Greg Clayton513c26c2011-01-29 07:10:55 +0000519 if (!force && m_register_info.GetNumRegisters() > 0)
520 return;
521
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000522 m_register_info.Clear();
Greg Claytond04f0ed2015-05-26 18:00:51 +0000523
524 // Check if qHostInfo specified a specific packet timeout for this connection.
525 // If so then lets update our setting so the user knows what the timeout is
526 // and can see it.
527 const uint32_t host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
528 if (host_packet_timeout)
529 {
530 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout);
531 }
532
Ewan Crawford0c996a92015-06-30 13:08:44 +0000533 // Register info search order:
534 // 1 - Use the target definition python file if one is specified.
535 // 2 - If the target definition doesn't have any of the info from the target.xml (registers) then proceed to read the target.xml.
536 // 3 - Fall back on the qRegisterInfo packets.
537
538 FileSpec target_definition_fspec = GetGlobalPluginProperties()->GetTargetDefinitionFile ();
Jason Molenda91e468c2015-08-20 04:29:46 +0000539 if (!target_definition_fspec.Exists())
540 {
541 // If the filename doesn't exist, it may be a ~ not having been expanded - try to resolve it.
542 target_definition_fspec.ResolvePath();
543 }
Ewan Crawford0c996a92015-06-30 13:08:44 +0000544 if (target_definition_fspec)
545 {
546 // See if we can get register definitions from a python file
547 if (ParsePythonTargetDefinition (target_definition_fspec))
Jason Molenda5543abb2015-08-20 03:05:09 +0000548 {
Ewan Crawford0c996a92015-06-30 13:08:44 +0000549 return;
Jason Molenda5543abb2015-08-20 03:05:09 +0000550 }
551 else
552 {
553 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
554 stream_sp->Printf ("ERROR: target description file %s failed to parse.\n", target_definition_fspec.GetPath().c_str());
555 }
Ewan Crawford0c996a92015-06-30 13:08:44 +0000556 }
557
Greg Claytond04f0ed2015-05-26 18:00:51 +0000558 if (GetGDBServerRegisterInfo ())
559 return;
560
561 char packet[128];
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000562 uint32_t reg_offset = 0;
563 uint32_t reg_num = 0;
Greg Clayton23f59502012-07-17 03:23:13 +0000564 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Greg Clayton576d8832011-03-22 04:00:09 +0000565 response_type == StringExtractorGDBRemote::eResponse;
566 ++reg_num)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000567 {
Greg Clayton513c26c2011-01-29 07:10:55 +0000568 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
Andy Gibbsa297a972013-06-19 19:04:53 +0000569 assert (packet_len < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000570 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000571 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000572 {
Greg Clayton576d8832011-03-22 04:00:09 +0000573 response_type = response.GetResponseType();
574 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000575 {
576 std::string name;
577 std::string value;
578 ConstString reg_name;
579 ConstString alt_name;
580 ConstString set_name;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000581 std::vector<uint32_t> value_regs;
582 std::vector<uint32_t> invalidate_regs;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000583 RegisterInfo reg_info = { NULL, // Name
584 NULL, // Alt name
585 0, // byte size
586 reg_offset, // offset
587 eEncodingUint, // encoding
588 eFormatHex, // formate
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000589 {
590 LLDB_INVALID_REGNUM, // GCC reg num
591 LLDB_INVALID_REGNUM, // DWARF reg num
592 LLDB_INVALID_REGNUM, // generic reg num
Jason Molendafbcb7f22010-09-10 07:49:16 +0000593 reg_num, // GDB reg num
594 reg_num // native register number
Greg Clayton435d85a2012-02-29 19:27:27 +0000595 },
596 NULL,
597 NULL
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000598 };
599
600 while (response.GetNameColonValue(name, value))
601 {
602 if (name.compare("name") == 0)
603 {
604 reg_name.SetCString(value.c_str());
605 }
606 else if (name.compare("alt-name") == 0)
607 {
608 alt_name.SetCString(value.c_str());
609 }
610 else if (name.compare("bitsize") == 0)
611 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000612 reg_info.byte_size = StringConvert::ToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000613 }
614 else if (name.compare("offset") == 0)
615 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000616 uint32_t offset = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda743e86a2010-06-11 23:44:18 +0000617 if (reg_offset != offset)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000618 {
619 reg_offset = offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000620 }
621 }
622 else if (name.compare("encoding") == 0)
623 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000624 const Encoding encoding = Args::StringToEncoding (value.c_str());
625 if (encoding != eEncodingInvalid)
626 reg_info.encoding = encoding;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000627 }
628 else if (name.compare("format") == 0)
629 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000630 Format format = eFormatInvalid;
631 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
632 reg_info.format = format;
633 else if (value.compare("binary") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000634 reg_info.format = eFormatBinary;
635 else if (value.compare("decimal") == 0)
636 reg_info.format = eFormatDecimal;
637 else if (value.compare("hex") == 0)
638 reg_info.format = eFormatHex;
639 else if (value.compare("float") == 0)
640 reg_info.format = eFormatFloat;
641 else if (value.compare("vector-sint8") == 0)
642 reg_info.format = eFormatVectorOfSInt8;
643 else if (value.compare("vector-uint8") == 0)
644 reg_info.format = eFormatVectorOfUInt8;
645 else if (value.compare("vector-sint16") == 0)
646 reg_info.format = eFormatVectorOfSInt16;
647 else if (value.compare("vector-uint16") == 0)
648 reg_info.format = eFormatVectorOfUInt16;
649 else if (value.compare("vector-sint32") == 0)
650 reg_info.format = eFormatVectorOfSInt32;
651 else if (value.compare("vector-uint32") == 0)
652 reg_info.format = eFormatVectorOfUInt32;
653 else if (value.compare("vector-float32") == 0)
654 reg_info.format = eFormatVectorOfFloat32;
655 else if (value.compare("vector-uint128") == 0)
656 reg_info.format = eFormatVectorOfUInt128;
657 }
658 else if (name.compare("set") == 0)
659 {
660 set_name.SetCString(value.c_str());
661 }
Jason Molendaa18f7072015-08-15 01:21:01 +0000662 else if (name.compare("gcc") == 0 || name.compare("ehframe") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000663 {
Jason Molendaa18f7072015-08-15 01:21:01 +0000664 reg_info.kinds[eRegisterKindEHFrame] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000665 }
666 else if (name.compare("dwarf") == 0)
667 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000668 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000669 }
670 else if (name.compare("generic") == 0)
671 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000672 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000673 }
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000674 else if (name.compare("container-regs") == 0)
675 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000676 SplitCommaSeparatedRegisterNumberString(value, value_regs, 16);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000677 }
678 else if (name.compare("invalidate-regs") == 0)
679 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000680 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 16);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000681 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000682 }
683
Jason Molenda743e86a2010-06-11 23:44:18 +0000684 reg_info.byte_offset = reg_offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000685 assert (reg_info.byte_size != 0);
686 reg_offset += reg_info.byte_size;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000687 if (!value_regs.empty())
688 {
689 value_regs.push_back(LLDB_INVALID_REGNUM);
690 reg_info.value_regs = value_regs.data();
691 }
692 if (!invalidate_regs.empty())
693 {
694 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
695 reg_info.invalidate_regs = invalidate_regs.data();
696 }
697
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000698 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
699 }
Todd Fiala1a634402014-01-08 07:52:40 +0000700 else
701 {
702 break; // ensure exit before reg_num is incremented
703 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000704 }
705 else
706 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000707 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000708 }
709 }
710
Greg Claytond04f0ed2015-05-26 18:00:51 +0000711 if (m_register_info.GetNumRegisters() > 0)
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000712 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000713 m_register_info.Finalize(GetTarget().GetArchitecture());
714 return;
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000715 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000716
Johnny Chen2fa9de12012-05-14 18:44:23 +0000717 // We didn't get anything if the accumulated reg_num is zero. See if we are
718 // debugging ARM and fill with a hard coded register set until we can get an
719 // updated debugserver down on the devices.
720 // On the other hand, if the accumulated reg_num is positive, see if we can
721 // add composite registers to the existing primordial ones.
Greg Claytond04f0ed2015-05-26 18:00:51 +0000722 bool from_scratch = (m_register_info.GetNumRegisters() == 0);
Johnny Chen2fa9de12012-05-14 18:44:23 +0000723
724 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000725 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
726 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
727
728 // Use the process' architecture instead of the host arch, if available
729 ArchSpec remote_arch;
730 if (remote_process_arch.IsValid ())
731 remote_arch = remote_process_arch;
732 else
733 remote_arch = remote_host_arch;
734
Johnny Chen2fa9de12012-05-14 18:44:23 +0000735 if (!target_arch.IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000736 {
Johnny Chen2fa9de12012-05-14 18:44:23 +0000737 if (remote_arch.IsValid()
738 && remote_arch.GetMachine() == llvm::Triple::arm
739 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
740 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000741 }
Johnny Chen2fa9de12012-05-14 18:44:23 +0000742 else if (target_arch.GetMachine() == llvm::Triple::arm)
743 {
744 m_register_info.HardcodeARMRegisters(from_scratch);
745 }
746
747 // At this point, we can finalize our register info.
Greg Claytond04f0ed2015-05-26 18:00:51 +0000748 m_register_info.Finalize (GetTarget().GetArchitecture());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000749}
750
751Error
752ProcessGDBRemote::WillLaunch (Module* module)
753{
754 return WillLaunchOrAttach ();
755}
756
757Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000758ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000759{
760 return WillLaunchOrAttach ();
761}
762
763Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000764ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000765{
766 return WillLaunchOrAttach ();
767}
768
769Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000770ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +0000771{
Todd Fialaaf245d12014-06-30 21:05:18 +0000772 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Claytonb766a732011-02-04 01:58:07 +0000773 Error error (WillLaunchOrAttach ());
774
775 if (error.Fail())
776 return error;
777
Greg Clayton2289fa42011-04-30 01:09:13 +0000778 error = ConnectToDebugserver (remote_url);
Greg Claytonb766a732011-02-04 01:58:07 +0000779
780 if (error.Fail())
781 return error;
782 StartAsyncThread ();
783
Greg Claytonc574ede2011-03-10 02:26:48 +0000784 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonb766a732011-02-04 01:58:07 +0000785 if (pid == LLDB_INVALID_PROCESS_ID)
786 {
787 // We don't have a valid process ID, so note that we are connected
788 // and could now request to launch or attach, or get remote process
789 // listings...
790 SetPrivateState (eStateConnected);
791 }
792 else
793 {
794 // We have a valid process
795 SetID (pid);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000796 GetThreadList();
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000797 StringExtractorGDBRemote response;
798 if (m_gdb_comm.GetStopReply(response))
Greg Claytonb766a732011-02-04 01:58:07 +0000799 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000800 SetLastStopPacket(response);
Ewan Crawford78baa192015-05-13 09:18:18 +0000801
802 // '?' Packets must be handled differently in non-stop mode
803 if (GetTarget().GetNonStopModeEnabled())
804 HandleStopReplySequence();
805
Jason Molendac62bd7b2013-12-21 05:20:36 +0000806 if (!m_target.GetArchitecture().IsValid())
807 {
808 if (m_gdb_comm.GetProcessArchitecture().IsValid())
809 {
810 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
811 }
812 else
813 {
814 m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
815 }
Carlo Kok74389122013-10-14 07:09:13 +0000816 }
817
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000818 const StateType state = SetThreadStopInfo (response);
Greg Clayton2e309072015-07-17 23:42:28 +0000819 if (state != eStateInvalid)
Greg Claytonb766a732011-02-04 01:58:07 +0000820 {
821 SetPrivateState (state);
822 }
823 else
Daniel Malead01b2952012-11-29 21:49:15 +0000824 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 +0000825 }
826 else
Daniel Malead01b2952012-11-29 21:49:15 +0000827 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 +0000828 }
Jason Molenda16d127c2012-05-03 22:37:30 +0000829
Todd Fialaaf245d12014-06-30 21:05:18 +0000830 if (log)
831 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");
832
833
834 if (error.Success()
Jason Molenda16d127c2012-05-03 22:37:30 +0000835 && !GetTarget().GetArchitecture().IsValid()
836 && m_gdb_comm.GetHostArchitecture().IsValid())
837 {
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000838 // Prefer the *process'* architecture over that of the *host*, if available.
839 if (m_gdb_comm.GetProcessArchitecture().IsValid())
840 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
841 else
842 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molenda16d127c2012-05-03 22:37:30 +0000843 }
844
Todd Fialaaf245d12014-06-30 21:05:18 +0000845 if (log)
846 log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": normalized target architecture triple: %s", __FUNCTION__, GetID (), GetTarget ().GetArchitecture ().GetTriple ().getTriple ().c_str ());
847
Chaoren Lin98d0a4b2015-07-14 01:09:28 +0000848 if (error.Success())
Jaydeep Patil6fc590d2015-07-30 05:06:51 +0000849 {
850 PlatformSP platform_sp = GetTarget().GetPlatform();
851 if (platform_sp && platform_sp->IsConnected())
852 SetUnixSignals(platform_sp->GetUnixSignals());
853 else
854 SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
855 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000856
Greg Claytonb766a732011-02-04 01:58:07 +0000857 return error;
858}
859
860Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000861ProcessGDBRemote::WillLaunchOrAttach ()
862{
863 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000864 m_stdio_communication.Clear ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000865 return error;
866}
867
868//----------------------------------------------------------------------
869// Process Control
870//----------------------------------------------------------------------
871Error
Jean-Daniel Dupas7782de92013-12-09 22:52:50 +0000872ProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000873{
Todd Fiala75f47c32014-10-11 21:42:09 +0000874 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton4957bf62010-09-30 21:49:03 +0000875 Error error;
Greg Clayton982c9762011-11-03 21:22:33 +0000876
Todd Fiala75f47c32014-10-11 21:42:09 +0000877 if (log)
878 log->Printf ("ProcessGDBRemote::%s() entered", __FUNCTION__);
879
Greg Clayton982c9762011-11-03 21:22:33 +0000880 uint32_t launch_flags = launch_info.GetFlags().Get();
Chaoren Lind3173f32015-05-29 19:52:29 +0000881 FileSpec stdin_file_spec{};
882 FileSpec stdout_file_spec{};
883 FileSpec stderr_file_spec{};
884 FileSpec working_dir = launch_info.GetWorkingDirectory();
Greg Clayton982c9762011-11-03 21:22:33 +0000885
Zachary Turner696b5282014-08-14 16:01:25 +0000886 const FileAction *file_action;
Greg Clayton982c9762011-11-03 21:22:33 +0000887 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
888 if (file_action)
889 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000890 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000891 stdin_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000892 }
893 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
894 if (file_action)
895 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000896 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000897 stdout_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000898 }
899 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
900 if (file_action)
901 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000902 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000903 stderr_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000904 }
905
Todd Fiala75f47c32014-10-11 21:42:09 +0000906 if (log)
907 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000908 if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
Vince Harron4a8abd32015-02-13 19:15:24 +0000909 log->Printf ("ProcessGDBRemote::%s provided with STDIO paths via launch_info: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000910 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000911 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
912 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
913 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Todd Fiala75f47c32014-10-11 21:42:09 +0000914 else
915 log->Printf ("ProcessGDBRemote::%s no STDIO paths given via launch_info", __FUNCTION__);
916 }
917
Vince Harrondf3f00f2015-02-10 21:09:04 +0000918 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Chaoren Lind3173f32015-05-29 19:52:29 +0000919 if (stdin_file_spec || disable_stdio)
Vince Harrondf3f00f2015-02-10 21:09:04 +0000920 {
921 // the inferior will be reading stdin from the specified file
922 // or stdio is completely disabled
923 m_stdin_forward = false;
924 }
925 else
926 {
927 m_stdin_forward = true;
928 }
929
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000930 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
931 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
932 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000933
Greg Clayton982c9762011-11-03 21:22:33 +0000934 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000935 if (object_file)
936 {
Greg Clayton71337622011-02-24 22:24:29 +0000937 // Make sure we aren't already connected?
938 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000939 {
Greg Clayton91a9b2472013-12-04 19:19:12 +0000940 error = LaunchAndConnectToDebugserver (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000941 }
942
943 if (error.Success())
944 {
945 lldb_utility::PseudoTerminal pty;
946 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000947
Greg Claytonf58c2692011-06-24 22:32:10 +0000948 PlatformSP platform_sp (m_target.GetPlatform());
Vince Harrondf3f00f2015-02-10 21:09:04 +0000949 if (disable_stdio)
Greg Clayton71337622011-02-24 22:24:29 +0000950 {
Vince Harrondf3f00f2015-02-10 21:09:04 +0000951 // set to /dev/null unless redirected to a file above
Chaoren Lind3173f32015-05-29 19:52:29 +0000952 if (!stdin_file_spec)
953 stdin_file_spec.SetFile("/dev/null", false);
954 if (!stdout_file_spec)
955 stdout_file_spec.SetFile("/dev/null", false);
956 if (!stderr_file_spec)
957 stderr_file_spec.SetFile("/dev/null", false);
Vince Harrondf3f00f2015-02-10 21:09:04 +0000958 }
959 else if (platform_sp && platform_sp->IsHost())
960 {
961 // If the debugserver is local and we aren't disabling STDIO, lets use
962 // a pseudo terminal to instead of relying on the 'O' packets for stdio
963 // since 'O' packets can really slow down debugging if the inferior
964 // does a lot of output.
Chaoren Lind3173f32015-05-29 19:52:29 +0000965 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
966 pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000967 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000968 FileSpec slave_name{pty.GetSlaveName(NULL, 0), false};
969
970 if (!stdin_file_spec)
971 stdin_file_spec = slave_name;
972
973 if (!stdout_file_spec)
974 stdout_file_spec = slave_name;
975
976 if (!stderr_file_spec)
977 stderr_file_spec = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000978 }
Todd Fiala75f47c32014-10-11 21:42:09 +0000979 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +0000980 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 +0000981 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000982 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
983 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
984 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Greg Clayton71337622011-02-24 22:24:29 +0000985 }
986
Todd Fiala75f47c32014-10-11 21:42:09 +0000987 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +0000988 log->Printf ("ProcessGDBRemote::%s final STDIO paths after all adjustments: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000989 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000990 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
991 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
992 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Todd Fiala75f47c32014-10-11 21:42:09 +0000993
Chaoren Lind3173f32015-05-29 19:52:29 +0000994 if (stdin_file_spec)
995 m_gdb_comm.SetSTDIN(stdin_file_spec);
996 if (stdout_file_spec)
997 m_gdb_comm.SetSTDOUT(stdout_file_spec);
998 if (stderr_file_spec)
999 m_gdb_comm.SetSTDERR(stderr_file_spec);
Greg Clayton71337622011-02-24 22:24:29 +00001000
1001 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
Jim Ingham106d0282014-06-25 02:32:56 +00001002 m_gdb_comm.SetDetachOnError (launch_flags & eLaunchFlagDetachOnError);
Greg Clayton71337622011-02-24 22:24:29 +00001003
Greg Claytonc4103b32011-05-08 04:53:50 +00001004 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Clayton71337622011-02-24 22:24:29 +00001005
Jason Molendaa3329782014-03-29 18:54:20 +00001006 const char * launch_event_data = launch_info.GetLaunchEventData();
1007 if (launch_event_data != NULL && *launch_event_data != '\0')
1008 m_gdb_comm.SendLaunchEventDataPacket (launch_event_data);
1009
Chaoren Lind3173f32015-05-29 19:52:29 +00001010 if (working_dir)
Greg Clayton71337622011-02-24 22:24:29 +00001011 {
1012 m_gdb_comm.SetWorkingDir (working_dir);
1013 }
1014
1015 // Send the environment and the program + arguments after we connect
Greg Clayton982c9762011-11-03 21:22:33 +00001016 const Args &environment = launch_info.GetEnvironmentEntries();
1017 if (environment.GetArgumentCount())
Greg Clayton71337622011-02-24 22:24:29 +00001018 {
Greg Clayton982c9762011-11-03 21:22:33 +00001019 size_t num_environment_entries = environment.GetArgumentCount();
1020 for (size_t i=0; i<num_environment_entries; ++i)
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001021 {
Greg Clayton982c9762011-11-03 21:22:33 +00001022 const char *env_entry = environment.GetArgumentAtIndex(i);
1023 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Clayton71337622011-02-24 22:24:29 +00001024 break;
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001025 }
Greg Clayton71337622011-02-24 22:24:29 +00001026 }
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001027
Greg Clayton71337622011-02-24 22:24:29 +00001028 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001029 // Scope for the scoped timeout object
1030 GDBRemoteCommunication::ScopedTimeout timeout (m_gdb_comm, 10);
1031
1032 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
1033 if (arg_packet_err == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001034 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001035 std::string error_str;
1036 if (m_gdb_comm.GetLaunchSuccess (error_str))
1037 {
1038 SetID (m_gdb_comm.GetCurrentProcessID ());
1039 }
1040 else
1041 {
1042 error.SetErrorString (error_str.c_str());
1043 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001044 }
1045 else
1046 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001047 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001048 }
Greg Clayton71337622011-02-24 22:24:29 +00001049 }
Tamas Berghammer912800c2015-02-24 10:23:39 +00001050
Greg Clayton71337622011-02-24 22:24:29 +00001051 if (GetID() == LLDB_INVALID_PROCESS_ID)
1052 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001053 if (log)
1054 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton71337622011-02-24 22:24:29 +00001055 KillDebugserverProcess ();
1056 return error;
1057 }
1058
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001059 StringExtractorGDBRemote response;
1060 if (m_gdb_comm.GetStopReply(response))
Greg Clayton71337622011-02-24 22:24:29 +00001061 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001062 SetLastStopPacket(response);
Ewan Crawford78baa192015-05-13 09:18:18 +00001063 // '?' Packets must be handled differently in non-stop mode
1064 if (GetTarget().GetNonStopModeEnabled())
1065 HandleStopReplySequence();
1066
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001067 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
1068
1069 if (process_arch.IsValid())
Jason Molendac62bd7b2013-12-21 05:20:36 +00001070 {
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001071 m_target.MergeArchitecture(process_arch);
1072 }
1073 else
1074 {
1075 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
1076 if (host_arch.IsValid())
1077 m_target.MergeArchitecture(host_arch);
Carlo Kok74389122013-10-14 07:09:13 +00001078 }
1079
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001080 SetPrivateState (SetThreadStopInfo (response));
Greg Clayton71337622011-02-24 22:24:29 +00001081
1082 if (!disable_stdio)
1083 {
1084 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Claytonee95ed52011-11-17 22:14:31 +00001085 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Clayton71337622011-02-24 22:24:29 +00001086 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001087 }
1088 }
Greg Claytonc235ac72011-08-09 05:20:29 +00001089 else
1090 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001091 if (log)
1092 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytonc235ac72011-08-09 05:20:29 +00001093 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001094 }
1095 else
1096 {
1097 // Set our user ID to an invalid process ID.
1098 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton982c9762011-11-03 21:22:33 +00001099 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
1100 exe_module->GetFileSpec().GetFilename().AsCString(),
1101 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001102 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001103 return error;
Greg Clayton4957bf62010-09-30 21:49:03 +00001104
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001105}
1106
1107
1108Error
Greg Claytonb766a732011-02-04 01:58:07 +00001109ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001110{
1111 Error error;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001112 // Only connect if we have a valid connect URL
Vince Harron1b5a74e2015-01-21 22:42:49 +00001113 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton00fe87b2013-12-05 22:58:22 +00001114
1115 if (connect_url && connect_url[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001116 {
Vince Harron1b5a74e2015-01-21 22:42:49 +00001117 if (log)
1118 log->Printf("ProcessGDBRemote::%s Connecting to %s", __FUNCTION__, connect_url);
Greg Clayton00fe87b2013-12-05 22:58:22 +00001119 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
1120 if (conn_ap.get())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001121 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001122 const uint32_t max_retry_count = 50;
1123 uint32_t retry_count = 0;
1124 while (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001125 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001126 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
1127 {
1128 m_gdb_comm.SetConnection (conn_ap.release());
1129 break;
1130 }
1131 else if (error.WasInterrupted())
1132 {
1133 // If we were interrupted, don't keep retrying.
1134 break;
1135 }
1136
1137 retry_count++;
1138
1139 if (retry_count >= max_retry_count)
1140 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001141
Greg Clayton00fe87b2013-12-05 22:58:22 +00001142 usleep (100000);
1143 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001144 }
1145 }
1146
1147 if (!m_gdb_comm.IsConnected())
1148 {
1149 if (error.Success())
1150 error.SetErrorString("not connected to remote gdb server");
1151 return error;
1152 }
1153
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001154
1155 // Start the communications read thread so all incoming data can be
1156 // parsed into packets and queued as they arrive.
1157 if (GetTarget().GetNonStopModeEnabled())
1158 m_gdb_comm.StartReadThread();
1159
Greg Clayton32e0a752011-03-30 18:16:51 +00001160 // We always seem to be able to open a connection to a local port
1161 // so we need to make sure we can then send data to it. If we can't
1162 // then we aren't actually connected to anything, so try and do the
1163 // handshake with the remote GDB server and make sure that goes
1164 // alright.
Greg Claytonfb909312013-11-23 01:58:15 +00001165 if (!m_gdb_comm.HandshakeWithServer (&error))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001166 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001167 m_gdb_comm.Disconnect();
1168 if (error.Success())
1169 error.SetErrorString("not connected to remote gdb server");
1170 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001171 }
Ewan Crawford78baa192015-05-13 09:18:18 +00001172
1173 // Send $QNonStop:1 packet on startup if required
1174 if (GetTarget().GetNonStopModeEnabled())
Ewan Crawfordaa7eda72015-06-24 15:14:26 +00001175 GetTarget().SetNonStopModeEnabled (m_gdb_comm.SetNonStopMode(true));
Ewan Crawford78baa192015-05-13 09:18:18 +00001176
Greg Claytonb30c50c2015-05-29 00:01:55 +00001177 m_gdb_comm.GetEchoSupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001178 m_gdb_comm.GetThreadSuffixSupported ();
Greg Clayton44633992012-04-10 03:22:03 +00001179 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001180 m_gdb_comm.GetHostInfo ();
1181 m_gdb_comm.GetVContSupported ('c');
Jim Inghamcd16df92012-07-20 21:37:13 +00001182 m_gdb_comm.GetVAttachOrWaitSupported();
Ewan Crawford78baa192015-05-13 09:18:18 +00001183
1184 // Ask the remote server for the default thread id
1185 if (GetTarget().GetNonStopModeEnabled())
1186 m_gdb_comm.GetDefaultThreadId(m_initial_tid);
1187
1188
Jim Ingham03afad82012-07-02 05:40:07 +00001189 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1190 for (size_t idx = 0; idx < num_cmds; idx++)
1191 {
1192 StringExtractorGDBRemote response;
Jim Ingham03afad82012-07-02 05:40:07 +00001193 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1194 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001195 return error;
1196}
1197
1198void
Jim Inghambb006ce2014-08-02 00:33:35 +00001199ProcessGDBRemote::DidLaunchOrAttach (ArchSpec& process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001200{
Greg Clayton5160ce52013-03-27 23:08:40 +00001201 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001202 if (log)
1203 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton93d3c8332011-02-16 04:46:07 +00001204 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001205 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001206 BuildDynamicRegisterInfo (false);
Greg Clayton3af9ea52010-11-18 05:57:03 +00001207
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001208 // See if the GDB server supports the qHostInfo information
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001209
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001210
1211 // See if the GDB server supports the qProcessInfo packet, if so
1212 // prefer that over the Host information as it will be more specific
1213 // to our process.
1214
Todd Fiala75f47c32014-10-11 21:42:09 +00001215 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1216 if (remote_process_arch.IsValid())
1217 {
1218 process_arch = remote_process_arch;
1219 if (log)
1220 log->Printf ("ProcessGDBRemote::%s gdb-remote had process architecture, using %s %s",
1221 __FUNCTION__,
1222 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1223 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1224 }
Jim Inghambb006ce2014-08-02 00:33:35 +00001225 else
Todd Fiala75f47c32014-10-11 21:42:09 +00001226 {
Jim Inghambb006ce2014-08-02 00:33:35 +00001227 process_arch = m_gdb_comm.GetHostArchitecture();
Todd Fiala75f47c32014-10-11 21:42:09 +00001228 if (log)
1229 log->Printf ("ProcessGDBRemote::%s gdb-remote did not have process architecture, using gdb-remote host architecture %s %s",
1230 __FUNCTION__,
1231 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1232 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1233 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001234
Jim Inghambb006ce2014-08-02 00:33:35 +00001235 if (process_arch.IsValid())
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001236 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001237 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Greg Claytond314e812011-03-23 00:09:55 +00001238 if (target_arch.IsValid())
1239 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001240 if (log)
1241 log->Printf ("ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1242 __FUNCTION__,
1243 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1244 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
1245
1246 // If the remote host is ARM and we have apple as the vendor, then
Greg Claytond314e812011-03-23 00:09:55 +00001247 // ARM executables and shared libraries can have mixed ARM architectures.
1248 // You can have an armv6 executable, and if the host is armv7, then the
1249 // system will load the best possible architecture for all shared libraries
1250 // it has, so we really need to take the remote host architecture as our
1251 // defacto architecture in this case.
1252
Jim Inghambb006ce2014-08-02 00:33:35 +00001253 if (process_arch.GetMachine() == llvm::Triple::arm &&
1254 process_arch.GetTriple().getVendor() == llvm::Triple::Apple)
Greg Claytond314e812011-03-23 00:09:55 +00001255 {
Jason Molenda921c01b2014-08-03 21:42:52 +00001256 GetTarget().SetArchitecture (process_arch);
Todd Fiala75f47c32014-10-11 21:42:09 +00001257 if (log)
1258 log->Printf ("ProcessGDBRemote::%s remote process is ARM/Apple, setting target arch to %s %s",
1259 __FUNCTION__,
1260 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1261 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001262 }
1263 else
1264 {
1265 // Fill in what is missing in the triple
Jim Inghambb006ce2014-08-02 00:33:35 +00001266 const llvm::Triple &remote_triple = process_arch.GetTriple();
Tamas Berghammere724af12015-03-13 10:32:37 +00001267 llvm::Triple new_target_triple = target_arch.GetTriple();
1268 if (new_target_triple.getVendorName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001269 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001270 new_target_triple.setVendor (remote_triple.getVendor());
Greg Claytond314e812011-03-23 00:09:55 +00001271
Tamas Berghammere724af12015-03-13 10:32:37 +00001272 if (new_target_triple.getOSName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001273 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001274 new_target_triple.setOS (remote_triple.getOS());
Greg Claytond314e812011-03-23 00:09:55 +00001275
Tamas Berghammere724af12015-03-13 10:32:37 +00001276 if (new_target_triple.getEnvironmentName().size() == 0)
1277 new_target_triple.setEnvironment (remote_triple.getEnvironment());
Greg Clayton70b57652011-05-15 01:25:55 +00001278 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001279
Tamas Berghammere724af12015-03-13 10:32:37 +00001280 ArchSpec new_target_arch = target_arch;
1281 new_target_arch.SetTriple(new_target_triple);
1282 GetTarget().SetArchitecture(new_target_arch);
1283 }
Greg Claytond314e812011-03-23 00:09:55 +00001284 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001285
1286 if (log)
1287 log->Printf ("ProcessGDBRemote::%s final target arch after adjustments for remote architecture: %s %s",
1288 __FUNCTION__,
1289 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1290 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001291 }
1292 else
1293 {
1294 // The target doesn't have a valid architecture yet, set it from
1295 // the architecture we got from the remote GDB server
Jason Molenda921c01b2014-08-03 21:42:52 +00001296 GetTarget().SetArchitecture (process_arch);
Greg Claytond314e812011-03-23 00:09:55 +00001297 }
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001298 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001299 }
1300}
1301
1302void
1303ProcessGDBRemote::DidLaunch ()
1304{
Jim Inghambb006ce2014-08-02 00:33:35 +00001305 ArchSpec process_arch;
1306 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001307}
1308
1309Error
Han Ming Ong84647042012-02-25 01:07:38 +00001310ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1311{
Todd Fiala75f47c32014-10-11 21:42:09 +00001312 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001313 Error error;
Todd Fiala75f47c32014-10-11 21:42:09 +00001314
1315 if (log)
1316 log->Printf ("ProcessGDBRemote::%s()", __FUNCTION__);
1317
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001318 // Clear out and clean up from any current state
1319 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001320 if (attach_pid != LLDB_INVALID_PROCESS_ID)
1321 {
Greg Clayton71337622011-02-24 22:24:29 +00001322 // Make sure we aren't already connected?
1323 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001324 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001325 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001326
1327 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001328 {
Greg Clayton71337622011-02-24 22:24:29 +00001329 const char *error_string = error.AsCString();
1330 if (error_string == NULL)
1331 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1332
1333 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001334 }
Greg Clayton71337622011-02-24 22:24:29 +00001335 }
1336
1337 if (error.Success())
1338 {
Jim Ingham106d0282014-06-25 02:32:56 +00001339 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
Todd Fiala75f47c32014-10-11 21:42:09 +00001340
Greg Clayton71337622011-02-24 22:24:29 +00001341 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001342 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Greg Clayton3b608422011-11-19 02:11:30 +00001343 SetID (attach_pid);
Greg Clayton71337622011-02-24 22:24:29 +00001344 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001345 }
1346 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001347
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001348 return error;
1349}
1350
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001351Error
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001352ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001353{
1354 Error error;
1355 // Clear out and clean up from any current state
1356 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001357
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001358 if (process_name && process_name[0])
1359 {
Greg Clayton71337622011-02-24 22:24:29 +00001360 // Make sure we aren't already connected?
1361 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001362 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001363 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001364
Greg Clayton71337622011-02-24 22:24:29 +00001365 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001366 {
Greg Clayton71337622011-02-24 22:24:29 +00001367 const char *error_string = error.AsCString();
1368 if (error_string == NULL)
1369 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001370
Greg Clayton71337622011-02-24 22:24:29 +00001371 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001372 }
Greg Clayton71337622011-02-24 22:24:29 +00001373 }
1374
1375 if (error.Success())
1376 {
1377 StreamString packet;
1378
Jim Ingham106d0282014-06-25 02:32:56 +00001379 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1380
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001381 if (attach_info.GetWaitForLaunch())
Jim Inghamcd16df92012-07-20 21:37:13 +00001382 {
1383 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1384 {
1385 packet.PutCString ("vAttachWait");
1386 }
1387 else
1388 {
1389 if (attach_info.GetIgnoreExisting())
1390 packet.PutCString("vAttachWait");
1391 else
1392 packet.PutCString ("vAttachOrWait");
1393 }
1394 }
Greg Clayton71337622011-02-24 22:24:29 +00001395 else
1396 packet.PutCString("vAttachName");
1397 packet.PutChar(';');
1398 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1399
1400 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1401
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001402 }
1403 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001404 return error;
1405}
1406
Greg Clayton5df78fa2015-05-23 03:54:53 +00001407void
1408ProcessGDBRemote::DidExit ()
Greg Claytonfbb76342013-11-20 21:07:01 +00001409{
Greg Clayton5df78fa2015-05-23 03:54:53 +00001410 // When we exit, disconnect from the GDB server communications
Greg Claytonfbb76342013-11-20 21:07:01 +00001411 m_gdb_comm.Disconnect();
Greg Claytonfbb76342013-11-20 21:07:01 +00001412}
1413
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001414void
Jim Inghambb006ce2014-08-02 00:33:35 +00001415ProcessGDBRemote::DidAttach (ArchSpec &process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001416{
Jim Inghambb006ce2014-08-02 00:33:35 +00001417 // If you can figure out what the architecture is, fill it in here.
1418 process_arch.Clear();
1419 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001420}
1421
Greg Clayton90ba8112012-12-05 00:16:59 +00001422
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001423Error
1424ProcessGDBRemote::WillResume ()
1425{
Greg Clayton71fc2a32011-02-12 06:28:37 +00001426 m_continue_c_tids.clear();
1427 m_continue_C_tids.clear();
1428 m_continue_s_tids.clear();
1429 m_continue_S_tids.clear();
Greg Clayton2e309072015-07-17 23:42:28 +00001430 m_jstopinfo_sp.reset();
1431 m_jthreadsinfo_sp.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001432 return Error();
1433}
1434
1435Error
1436ProcessGDBRemote::DoResume ()
1437{
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001438 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001439 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001440 if (log)
1441 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytone5219662010-12-03 06:02:24 +00001442
1443 Listener listener ("gdb-remote.resume-packet-sent");
1444 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1445 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00001446 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1447
Greg Claytond1d06e42013-04-20 00:27:58 +00001448 const size_t num_threads = GetThreadList().GetSize();
1449
Greg Clayton71fc2a32011-02-12 06:28:37 +00001450 StreamString continue_packet;
1451 bool continue_packet_error = false;
1452 if (m_gdb_comm.HasAnyVContSupport ())
1453 {
Ewan Crawford78baa192015-05-13 09:18:18 +00001454 if (!GetTarget().GetNonStopModeEnabled() &&
1455 (m_continue_c_tids.size() == num_threads ||
Greg Claytone98008c2014-02-13 23:34:38 +00001456 (m_continue_c_tids.empty() &&
1457 m_continue_C_tids.empty() &&
1458 m_continue_s_tids.empty() &&
Ewan Crawford78baa192015-05-13 09:18:18 +00001459 m_continue_S_tids.empty())))
Greg Clayton71fc2a32011-02-12 06:28:37 +00001460 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001461 // All threads are continuing, just send a "c" packet
1462 continue_packet.PutCString ("c");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001463 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001464 else
1465 {
1466 continue_packet.PutCString ("vCont");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001467
Greg Claytond1d06e42013-04-20 00:27:58 +00001468 if (!m_continue_c_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001469 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001470 if (m_gdb_comm.GetVContSupported ('c'))
1471 {
1472 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)
1473 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1474 }
1475 else
1476 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001477 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001478
1479 if (!continue_packet_error && !m_continue_C_tids.empty())
1480 {
1481 if (m_gdb_comm.GetVContSupported ('C'))
1482 {
1483 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)
1484 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1485 }
1486 else
1487 continue_packet_error = true;
1488 }
Greg Claytone5219662010-12-03 06:02:24 +00001489
Greg Claytond1d06e42013-04-20 00:27:58 +00001490 if (!continue_packet_error && !m_continue_s_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001491 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001492 if (m_gdb_comm.GetVContSupported ('s'))
1493 {
1494 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)
1495 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1496 }
1497 else
1498 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001499 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001500
1501 if (!continue_packet_error && !m_continue_S_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001502 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001503 if (m_gdb_comm.GetVContSupported ('S'))
1504 {
1505 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)
1506 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1507 }
1508 else
1509 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001510 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001511
1512 if (continue_packet_error)
1513 continue_packet.GetString().clear();
Greg Clayton71fc2a32011-02-12 06:28:37 +00001514 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001515 }
1516 else
1517 continue_packet_error = true;
1518
1519 if (continue_packet_error)
1520 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001521 // Either no vCont support, or we tried to use part of the vCont
1522 // packet that wasn't supported by the remote GDB server.
1523 // We need to try and make a simple packet that can do our continue
Greg Clayton71fc2a32011-02-12 06:28:37 +00001524 const size_t num_continue_c_tids = m_continue_c_tids.size();
1525 const size_t num_continue_C_tids = m_continue_C_tids.size();
1526 const size_t num_continue_s_tids = m_continue_s_tids.size();
1527 const size_t num_continue_S_tids = m_continue_S_tids.size();
1528 if (num_continue_c_tids > 0)
1529 {
1530 if (num_continue_c_tids == num_threads)
1531 {
1532 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001533 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001534 continue_packet.PutChar ('c');
1535 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001536 }
1537 else if (num_continue_c_tids == 1 &&
1538 num_continue_C_tids == 0 &&
1539 num_continue_s_tids == 0 &&
1540 num_continue_S_tids == 0 )
1541 {
1542 // Only one thread is continuing
Greg Clayton8b82f082011-04-12 05:54:46 +00001543 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001544 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001545 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001546 }
1547 }
1548
Greg Clayton0c74e782011-06-24 03:21:43 +00001549 if (continue_packet_error && num_continue_C_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001550 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001551 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1552 num_continue_C_tids > 0 &&
1553 num_continue_s_tids == 0 &&
1554 num_continue_S_tids == 0 )
Greg Clayton71fc2a32011-02-12 06:28:37 +00001555 {
1556 const int continue_signo = m_continue_C_tids.front().second;
Greg Clayton0c74e782011-06-24 03:21:43 +00001557 // Only one thread is continuing
Greg Clayton71fc2a32011-02-12 06:28:37 +00001558 if (num_continue_C_tids > 1)
1559 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001560 // More that one thread with a signal, yet we don't have
1561 // vCont support and we are being asked to resume each
1562 // thread with a signal, we need to make sure they are
1563 // all the same signal, or we can't issue the continue
1564 // accurately with the current support...
1565 if (num_continue_C_tids > 1)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001566 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001567 continue_packet_error = false;
1568 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1569 {
1570 if (m_continue_C_tids[i].second != continue_signo)
1571 continue_packet_error = true;
1572 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001573 }
Greg Clayton0c74e782011-06-24 03:21:43 +00001574 if (!continue_packet_error)
1575 m_gdb_comm.SetCurrentThreadForRun (-1);
1576 }
1577 else
1578 {
1579 // Set the continue thread ID
1580 continue_packet_error = false;
1581 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001582 }
1583 if (!continue_packet_error)
1584 {
1585 // Add threads continuing with the same signo...
Greg Clayton71fc2a32011-02-12 06:28:37 +00001586 continue_packet.Printf("C%2.2x", continue_signo);
1587 }
1588 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001589 }
1590
Greg Clayton0c74e782011-06-24 03:21:43 +00001591 if (continue_packet_error && num_continue_s_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001592 {
1593 if (num_continue_s_tids == num_threads)
1594 {
1595 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001596 m_gdb_comm.SetCurrentThreadForRun (-1);
Ewan Crawford76df2882015-06-23 12:32:06 +00001597
1598 // If in Non-Stop-Mode use vCont when stepping
1599 if (GetTarget().GetNonStopModeEnabled())
1600 {
1601 if (m_gdb_comm.GetVContSupported('s'))
1602 continue_packet.PutCString("vCont;s");
1603 else
1604 continue_packet.PutChar('s');
1605 }
1606 else
1607 continue_packet.PutChar('s');
1608
Greg Clayton0c74e782011-06-24 03:21:43 +00001609 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001610 }
1611 else if (num_continue_c_tids == 0 &&
1612 num_continue_C_tids == 0 &&
1613 num_continue_s_tids == 1 &&
1614 num_continue_S_tids == 0 )
1615 {
1616 // Only one thread is stepping
Greg Clayton8b82f082011-04-12 05:54:46 +00001617 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001618 continue_packet.PutChar ('s');
Greg Clayton0c74e782011-06-24 03:21:43 +00001619 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001620 }
1621 }
1622
1623 if (!continue_packet_error && num_continue_S_tids > 0)
1624 {
1625 if (num_continue_S_tids == num_threads)
1626 {
1627 const int step_signo = m_continue_S_tids.front().second;
1628 // Are all threads trying to step with the same signal?
Greg Clayton0c74e782011-06-24 03:21:43 +00001629 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001630 if (num_continue_S_tids > 1)
1631 {
1632 for (size_t i=1; i<num_threads; ++i)
1633 {
1634 if (m_continue_S_tids[i].second != step_signo)
1635 continue_packet_error = true;
1636 }
1637 }
1638 if (!continue_packet_error)
1639 {
1640 // Add threads stepping with the same signo...
Greg Clayton8b82f082011-04-12 05:54:46 +00001641 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001642 continue_packet.Printf("S%2.2x", step_signo);
1643 }
1644 }
1645 else if (num_continue_c_tids == 0 &&
1646 num_continue_C_tids == 0 &&
1647 num_continue_s_tids == 0 &&
1648 num_continue_S_tids == 1 )
1649 {
1650 // Only one thread is stepping with signal
Greg Clayton8b82f082011-04-12 05:54:46 +00001651 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001652 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Clayton0c74e782011-06-24 03:21:43 +00001653 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001654 }
1655 }
1656 }
1657
1658 if (continue_packet_error)
1659 {
1660 error.SetErrorString ("can't make continue packet for this resume");
1661 }
1662 else
1663 {
1664 EventSP event_sp;
1665 TimeValue timeout;
1666 timeout = TimeValue::Now();
1667 timeout.OffsetWithSeconds (5);
Zachary Turneracee96a2014-09-23 18:32:09 +00001668 if (!m_async_thread.IsJoinable())
Jim Inghamb1e2e842012-04-12 18:49:31 +00001669 {
1670 error.SetErrorString ("Trying to resume but the async thread is dead.");
1671 if (log)
1672 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1673 return error;
1674 }
1675
Greg Clayton71fc2a32011-02-12 06:28:37 +00001676 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1677
1678 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Inghamb1e2e842012-04-12 18:49:31 +00001679 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001680 error.SetErrorString("Resume timed out.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00001681 if (log)
1682 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1683 }
1684 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1685 {
1686 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1687 if (log)
1688 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1689 return error;
1690 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001691 }
Greg Claytone5219662010-12-03 06:02:24 +00001692 }
1693
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001694 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001695}
1696
Greg Clayton9e920902012-04-10 02:25:43 +00001697void
Ewan Crawford78baa192015-05-13 09:18:18 +00001698ProcessGDBRemote::HandleStopReplySequence ()
1699{
1700 while(true)
1701 {
1702 // Send vStopped
1703 StringExtractorGDBRemote response;
1704 m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false);
1705
1706 // OK represents end of signal list
1707 if (response.IsOKResponse())
1708 break;
1709
1710 // If not OK or a normal packet we have a problem
1711 if (!response.IsNormalResponse())
1712 break;
1713
1714 SetLastStopPacket(response);
1715 }
1716}
1717
1718void
Greg Clayton9e920902012-04-10 02:25:43 +00001719ProcessGDBRemote::ClearThreadIDList ()
1720{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001721 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001722 m_thread_ids.clear();
1723}
1724
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001725size_t
1726ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue (std::string &value)
1727{
1728 m_thread_ids.clear();
1729 size_t comma_pos;
1730 lldb::tid_t tid;
1731 while ((comma_pos = value.find(',')) != std::string::npos)
1732 {
1733 value[comma_pos] = '\0';
1734 // thread in big endian hex
1735 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1736 if (tid != LLDB_INVALID_THREAD_ID)
1737 m_thread_ids.push_back (tid);
1738 value.erase(0, comma_pos + 1);
1739 }
1740 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1741 if (tid != LLDB_INVALID_THREAD_ID)
1742 m_thread_ids.push_back (tid);
1743 return m_thread_ids.size();
1744}
1745
Greg Clayton9e920902012-04-10 02:25:43 +00001746bool
1747ProcessGDBRemote::UpdateThreadIDList ()
1748{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001749 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001750
Greg Clayton2e309072015-07-17 23:42:28 +00001751 if (m_jthreadsinfo_sp)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001752 {
1753 // If we have the JSON threads info, we can get the thread list from that
Greg Clayton2e309072015-07-17 23:42:28 +00001754 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001755 if (thread_infos && thread_infos->GetSize() > 0)
1756 {
1757 m_thread_ids.clear();
1758 thread_infos->ForEach([this](StructuredData::Object* object) -> bool {
1759 StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1760 if (thread_dict)
1761 {
1762 // Set the thread stop info from the JSON dictionary
1763 SetThreadStopInfo (thread_dict);
1764 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1765 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1766 m_thread_ids.push_back(tid);
1767 }
1768 return true; // Keep iterating through all thread_info objects
1769 });
1770 }
1771 if (!m_thread_ids.empty())
1772 return true;
1773 }
1774 else
1775 {
1776 // See if we can get the thread IDs from the current stop reply packets
1777 // that might contain a "threads" key/value pair
1778
1779 // Lock the thread stack while we access it
1780 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
1781 // Get the number of stop packets on the stack
1782 int nItems = m_stop_packet_stack.size();
1783 // Iterate over them
1784 for (int i = 0; i < nItems; i++)
1785 {
1786 // Get the thread stop info
1787 StringExtractorGDBRemote &stop_info = m_stop_packet_stack[i];
1788 const std::string &stop_info_str = stop_info.GetStringRef();
1789 const size_t threads_pos = stop_info_str.find(";threads:");
1790 if (threads_pos != std::string::npos)
1791 {
1792 const size_t start = threads_pos + strlen(";threads:");
1793 const size_t end = stop_info_str.find(';', start);
1794 if (end != std::string::npos)
1795 {
1796 std::string value = stop_info_str.substr(start, end - start);
1797 if (UpdateThreadIDsFromStopReplyThreadsValue(value))
1798 return true;
1799 }
1800 }
1801 }
1802 }
1803
Greg Clayton9e920902012-04-10 02:25:43 +00001804 bool sequence_mutex_unavailable = false;
1805 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1806 if (sequence_mutex_unavailable)
1807 {
Greg Clayton9e920902012-04-10 02:25:43 +00001808 return false; // We just didn't get the list
1809 }
1810 return true;
1811}
1812
Greg Clayton9fc13552012-04-10 00:18:59 +00001813bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001814ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001815{
1816 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +00001817 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Clayton73b472d2010-10-27 03:32:59 +00001818 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +00001819 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton9e920902012-04-10 02:25:43 +00001820
1821 size_t num_thread_ids = m_thread_ids.size();
1822 // The "m_thread_ids" thread ID list should always be updated after each stop
1823 // reply packet, but in case it isn't, update it here.
1824 if (num_thread_ids == 0)
1825 {
1826 if (!UpdateThreadIDList ())
1827 return false;
1828 num_thread_ids = m_thread_ids.size();
1829 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001830
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001831 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001832 if (num_thread_ids > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001833 {
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001834 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001835 {
Greg Clayton9e920902012-04-10 02:25:43 +00001836 tid_t tid = m_thread_ids[i];
Greg Clayton160c9d82013-05-01 21:54:04 +00001837 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001838 if (!thread_sp)
Jim Inghamdee1bc92013-06-22 00:27:45 +00001839 {
Jim Ingham4f465cf2012-10-10 18:32:14 +00001840 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001841 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1842 log->Printf(
1843 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001844 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001845 thread_sp->GetID());
1846 }
1847 else
1848 {
1849 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1850 log->Printf(
1851 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001852 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001853 thread_sp->GetID());
1854 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001855 new_thread_list.AddThread(thread_sp);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001856 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001857 }
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001858
1859 // Whatever that is left in old_thread_list_copy are not
1860 // present in new_thread_list. Remove non-existent threads from internal id table.
1861 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1862 for (size_t i=0; i<old_num_thread_ids; i++)
1863 {
1864 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1865 if (old_thread_sp)
1866 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001867 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001868 m_thread_id_to_index_id_map.erase(old_thread_id);
1869 }
1870 }
1871
Greg Clayton9fc13552012-04-10 00:18:59 +00001872 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001873}
1874
Greg Clayton2e309072015-07-17 23:42:28 +00001875
Greg Clayton358cf1e2015-06-25 21:46:34 +00001876bool
Greg Clayton2e309072015-07-17 23:42:28 +00001877ProcessGDBRemote::GetThreadStopInfoFromJSON (ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001878{
1879 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet
Greg Clayton2e309072015-07-17 23:42:28 +00001880 if (thread_infos_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001881 {
Greg Clayton2e309072015-07-17 23:42:28 +00001882 StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
Greg Clayton358cf1e2015-06-25 21:46:34 +00001883 if (thread_infos)
1884 {
1885 lldb::tid_t tid;
1886 const size_t n = thread_infos->GetSize();
1887 for (size_t i=0; i<n; ++i)
1888 {
1889 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1890 if (thread_dict)
1891 {
1892 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid, LLDB_INVALID_THREAD_ID))
1893 {
1894 if (tid == thread->GetID())
Greg Clayton2e309072015-07-17 23:42:28 +00001895 return (bool)SetThreadStopInfo(thread_dict);
Greg Clayton358cf1e2015-06-25 21:46:34 +00001896 }
1897 }
1898 }
1899 }
1900 }
Greg Clayton2e309072015-07-17 23:42:28 +00001901 return false;
1902}
1903
1904bool
1905ProcessGDBRemote::CalculateThreadStopInfo (ThreadGDBRemote *thread)
1906{
1907 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet
1908 if (GetThreadStopInfoFromJSON (thread, m_jthreadsinfo_sp))
1909 return true;
1910
1911 // See if we got thread stop info for any threads valid stop info reasons threads
1912 // via the "jstopinfo" packet stop reply packet key/value pair?
1913 if (m_jstopinfo_sp)
1914 {
1915 // If we have "jstopinfo" then we have stop descriptions for all threads
1916 // that have stop reasons, and if there is no entry for a thread, then
1917 // it has no stop reason.
1918 thread->GetRegisterContext()->InvalidateIfNeeded(true);
1919 if (!GetThreadStopInfoFromJSON (thread, m_jstopinfo_sp))
1920 {
1921 thread->SetStopInfo (StopInfoSP());
1922 }
1923 return true;
1924 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00001925
1926 // Fall back to using the qThreadStopInfo packet
1927 StringExtractorGDBRemote stop_packet;
1928 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1929 return SetThreadStopInfo (stop_packet) == eStateStopped;
1930 return false;
1931}
1932
1933
1934ThreadSP
1935ProcessGDBRemote::SetThreadStopInfo (lldb::tid_t tid,
1936 ExpeditedRegisterMap &expedited_register_map,
1937 uint8_t signo,
1938 const std::string &thread_name,
1939 const std::string &reason,
1940 const std::string &description,
1941 uint32_t exc_type,
1942 const std::vector<addr_t> &exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001943 addr_t thread_dispatch_qaddr,
1944 bool queue_vars_valid, // Set to true if queue_name, queue_kind and queue_serial are valid
1945 std::string &queue_name,
1946 QueueKind queue_kind,
1947 uint64_t queue_serial)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001948{
1949 ThreadSP thread_sp;
1950 if (tid != LLDB_INVALID_THREAD_ID)
1951 {
1952 // Scope for "locker" below
1953 {
1954 // m_thread_list_real does have its own mutex, but we need to
1955 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1956 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1957 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1958 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1959
1960 if (!thread_sp)
1961 {
1962 // Create the thread if we need to
1963 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1964 m_thread_list_real.AddThread(thread_sp);
1965 }
1966 }
1967
1968 if (thread_sp)
1969 {
1970 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1971 gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001972
Greg Clayton358cf1e2015-06-25 21:46:34 +00001973 for (const auto &pair : expedited_register_map)
1974 {
1975 StringExtractor reg_value_extractor;
1976 reg_value_extractor.GetStringRef() = pair.second;
1977 gdb_thread->PrivateSetRegisterValue (pair.first, reg_value_extractor);
1978 }
1979
Greg Clayton358cf1e2015-06-25 21:46:34 +00001980 thread_sp->SetName (thread_name.empty() ? NULL : thread_name.c_str());
1981
1982 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001983 // Check if the GDB server was able to provide the queue name, kind and serial number
1984 if (queue_vars_valid)
1985 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind, queue_serial);
1986 else
1987 gdb_thread->ClearQueueInfo();
1988
Greg Clayton2e309072015-07-17 23:42:28 +00001989 // Make sure we update our thread stop reason just once
1990 if (!thread_sp->StopInfoIsUpToDate())
Greg Clayton358cf1e2015-06-25 21:46:34 +00001991 {
Greg Clayton2e309072015-07-17 23:42:28 +00001992 thread_sp->SetStopInfo (StopInfoSP());
Greg Clayton358cf1e2015-06-25 21:46:34 +00001993
Greg Clayton2e309072015-07-17 23:42:28 +00001994 if (exc_type != 0)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001995 {
Greg Clayton2e309072015-07-17 23:42:28 +00001996 const size_t exc_data_size = exc_data.size();
1997
1998 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1999 exc_type,
2000 exc_data_size,
2001 exc_data_size >= 1 ? exc_data[0] : 0,
2002 exc_data_size >= 2 ? exc_data[1] : 0,
2003 exc_data_size >= 3 ? exc_data[2] : 0));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002004 }
Greg Clayton2e309072015-07-17 23:42:28 +00002005 else
Greg Clayton358cf1e2015-06-25 21:46:34 +00002006 {
Greg Clayton2e309072015-07-17 23:42:28 +00002007 bool handled = false;
2008 bool did_exec = false;
2009 if (!reason.empty())
Greg Clayton358cf1e2015-06-25 21:46:34 +00002010 {
Greg Clayton2e309072015-07-17 23:42:28 +00002011 if (reason.compare("trace") == 0)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002012 {
Greg Clayton2e309072015-07-17 23:42:28 +00002013 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
2014 handled = true;
2015 }
2016 else if (reason.compare("breakpoint") == 0)
2017 {
2018 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
2019 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2020 if (bp_site_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002021 {
Greg Clayton2e309072015-07-17 23:42:28 +00002022 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2023 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2024 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2025 handled = true;
2026 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2027 {
2028 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2029 }
2030 else
2031 {
2032 StopInfoSP invalid_stop_info_sp;
2033 thread_sp->SetStopInfo (invalid_stop_info_sp);
2034 }
2035 }
2036 }
2037 else if (reason.compare("trap") == 0)
2038 {
2039 // Let the trap just use the standard signal stop reason below...
2040 }
2041 else if (reason.compare("watchpoint") == 0)
2042 {
2043 StringExtractor desc_extractor(description.c_str());
2044 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
2045 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
Jaydeep Patil83143502015-08-13 03:44:09 +00002046 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
Greg Clayton2e309072015-07-17 23:42:28 +00002047 watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
2048 if (wp_addr != LLDB_INVALID_ADDRESS)
2049 {
2050 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2051 if (wp_sp)
2052 {
2053 wp_sp->SetHardwareIndex(wp_index);
2054 watch_id = wp_sp->GetID();
2055 }
2056 }
2057 if (watch_id == LLDB_INVALID_WATCH_ID)
2058 {
2059 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_WATCHPOINTS));
2060 if (log) log->Printf ("failed to find watchpoint");
2061 }
Jaydeep Patil83143502015-08-13 03:44:09 +00002062 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id, wp_hit_addr));
Greg Clayton2e309072015-07-17 23:42:28 +00002063 handled = true;
2064 }
2065 else if (reason.compare("exception") == 0)
2066 {
2067 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
2068 handled = true;
2069 }
2070 else if (reason.compare("exec") == 0)
2071 {
2072 did_exec = true;
2073 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
2074 handled = true;
2075 }
2076 }
2077
2078 if (!handled && signo && did_exec == false)
2079 {
2080 if (signo == SIGTRAP)
2081 {
2082 // Currently we are going to assume SIGTRAP means we are either
2083 // hitting a breakpoint or hardware single stepping.
2084 handled = true;
2085 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
2086 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2087
2088 if (bp_site_sp)
2089 {
2090 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2091 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2092 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2093 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2094 {
2095 if(m_breakpoint_pc_offset != 0)
2096 thread_sp->GetRegisterContext()->SetPC(pc);
2097 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2098 }
2099 else
2100 {
2101 StopInfoSP invalid_stop_info_sp;
2102 thread_sp->SetStopInfo (invalid_stop_info_sp);
2103 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002104 }
2105 else
2106 {
Greg Clayton2e309072015-07-17 23:42:28 +00002107 // If we were stepping then assume the stop was the result of the trace. If we were
2108 // not stepping then report the SIGTRAP.
2109 // FIXME: We are still missing the case where we single step over a trap instruction.
2110 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
2111 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
2112 else
2113 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo, description.c_str()));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002114 }
2115 }
Greg Clayton2e309072015-07-17 23:42:28 +00002116 if (!handled)
2117 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo, description.c_str()));
2118 }
2119
2120 if (!description.empty())
2121 {
2122 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
2123 if (stop_info_sp)
2124 {
2125 const char *stop_info_desc = stop_info_sp->GetDescription();
2126 if (!stop_info_desc || !stop_info_desc[0])
2127 stop_info_sp->SetDescription (description.c_str());
2128 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002129 else
2130 {
Greg Clayton2e309072015-07-17 23:42:28 +00002131 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002132 }
2133 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002134 }
2135 }
2136 }
2137 }
2138 return thread_sp;
2139}
2140
Greg Clayton2e309072015-07-17 23:42:28 +00002141lldb::ThreadSP
Greg Clayton358cf1e2015-06-25 21:46:34 +00002142ProcessGDBRemote::SetThreadStopInfo (StructuredData::Dictionary *thread_dict)
2143{
2144 static ConstString g_key_tid("tid");
2145 static ConstString g_key_name("name");
2146 static ConstString g_key_reason("reason");
2147 static ConstString g_key_metype("metype");
2148 static ConstString g_key_medata("medata");
2149 static ConstString g_key_qaddr("qaddr");
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002150 static ConstString g_key_queue_name("qname");
2151 static ConstString g_key_queue_kind("qkind");
2152 static ConstString g_key_queue_serial("qserial");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002153 static ConstString g_key_registers("registers");
2154 static ConstString g_key_memory("memory");
2155 static ConstString g_key_address("address");
2156 static ConstString g_key_bytes("bytes");
2157 static ConstString g_key_description("description");
Pavel Labath4a4bb122015-07-16 14:14:35 +00002158 static ConstString g_key_signal("signal");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002159
2160 // Stop with signal and thread info
2161 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2162 uint8_t signo = 0;
2163 std::string value;
2164 std::string thread_name;
2165 std::string reason;
2166 std::string description;
2167 uint32_t exc_type = 0;
2168 std::vector<addr_t> exc_data;
2169 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2170 ExpeditedRegisterMap expedited_register_map;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002171 bool queue_vars_valid = false;
2172 std::string queue_name;
2173 QueueKind queue_kind = eQueueKindUnknown;
2174 uint64_t queue_serial = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002175 // Iterate through all of the thread dictionary key/value pairs from the structured data dictionary
2176
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002177 thread_dict->ForEach([this,
2178 &tid,
2179 &expedited_register_map,
2180 &thread_name,
2181 &signo,
2182 &reason,
2183 &description,
2184 &exc_type,
2185 &exc_data,
2186 &thread_dispatch_qaddr,
2187 &queue_vars_valid,
2188 &queue_name,
2189 &queue_kind,
2190 &queue_serial]
2191 (ConstString key, StructuredData::Object* object) -> bool
Greg Clayton358cf1e2015-06-25 21:46:34 +00002192 {
2193 if (key == g_key_tid)
2194 {
2195 // thread in big endian hex
2196 tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
2197 }
2198 else if (key == g_key_metype)
2199 {
2200 // exception type in big endian hex
2201 exc_type = object->GetIntegerValue(0);
2202 }
2203 else if (key == g_key_medata)
2204 {
2205 // exception data in big endian hex
2206 StructuredData::Array *array = object->GetAsArray();
2207 if (array)
2208 {
2209 array->ForEach([&exc_data](StructuredData::Object* object) -> bool {
2210 exc_data.push_back(object->GetIntegerValue());
2211 return true; // Keep iterating through all array items
2212 });
2213 }
2214 }
2215 else if (key == g_key_name)
2216 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002217 thread_name = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002218 }
2219 else if (key == g_key_qaddr)
2220 {
2221 thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
2222 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002223 else if (key == g_key_queue_name)
2224 {
2225 queue_vars_valid = true;
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002226 queue_name = object->GetStringValue();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002227 }
2228 else if (key == g_key_queue_kind)
2229 {
2230 std::string queue_kind_str = object->GetStringValue();
2231 if (queue_kind_str == "serial")
2232 {
2233 queue_vars_valid = true;
2234 queue_kind = eQueueKindSerial;
2235 }
2236 else if (queue_kind_str == "concurrent")
2237 {
2238 queue_vars_valid = true;
2239 queue_kind = eQueueKindConcurrent;
2240 }
2241 }
2242 else if (key == g_key_queue_serial)
2243 {
2244 queue_serial = object->GetIntegerValue(0);
2245 if (queue_serial != 0)
2246 queue_vars_valid = true;
2247 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002248 else if (key == g_key_reason)
2249 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002250 reason = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002251 }
2252 else if (key == g_key_description)
2253 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002254 description = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002255 }
2256 else if (key == g_key_registers)
2257 {
2258 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2259
2260 if (registers_dict)
2261 {
2262 registers_dict->ForEach([&expedited_register_map](ConstString key, StructuredData::Object* object) -> bool {
2263 const uint32_t reg = StringConvert::ToUInt32 (key.GetCString(), UINT32_MAX, 10);
2264 if (reg != UINT32_MAX)
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002265 expedited_register_map[reg] = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002266 return true; // Keep iterating through all array items
2267 });
2268 }
2269 }
2270 else if (key == g_key_memory)
2271 {
2272 StructuredData::Array *array = object->GetAsArray();
2273 if (array)
2274 {
2275 array->ForEach([this](StructuredData::Object* object) -> bool {
2276 StructuredData::Dictionary *mem_cache_dict = object->GetAsDictionary();
2277 if (mem_cache_dict)
2278 {
2279 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2280 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>("address", mem_cache_addr))
2281 {
2282 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
2283 {
2284 StringExtractor bytes;
2285 if (mem_cache_dict->GetValueForKeyAsString("bytes", bytes.GetStringRef()))
2286 {
2287 bytes.SetFilePos(0);
2288
2289 const size_t byte_size = bytes.GetStringRef().size()/2;
2290 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2291 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2292 if (bytes_copied == byte_size)
2293 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2294 }
2295 }
2296 }
2297 }
2298 return true; // Keep iterating through all array items
2299 });
2300 }
2301
2302 }
Pavel Labath4a4bb122015-07-16 14:14:35 +00002303 else if (key == g_key_signal)
2304 signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002305 return true; // Keep iterating through all dictionary key/value pairs
2306 });
2307
Greg Clayton2e309072015-07-17 23:42:28 +00002308 return SetThreadStopInfo (tid,
2309 expedited_register_map,
2310 signo,
2311 thread_name,
2312 reason,
2313 description,
2314 exc_type,
2315 exc_data,
2316 thread_dispatch_qaddr,
2317 queue_vars_valid,
2318 queue_name,
2319 queue_kind,
2320 queue_serial);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002321}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002322
2323StateType
2324ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
2325{
Greg Claytondd0e5a52011-06-02 22:22:38 +00002326 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002327 const char stop_type = stop_packet.GetChar();
2328 switch (stop_type)
2329 {
2330 case 'T':
2331 case 'S':
2332 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00002333 // This is a bit of a hack, but is is required. If we did exec, we
2334 // need to clear our thread lists and also know to rebuild our dynamic
2335 // register info before we lookup and threads and populate the expedited
2336 // register values so we need to know this right away so we can cleanup
2337 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00002338 const uint32_t stop_id = GetStopID();
2339 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00002340 {
2341 // Our first stop, make sure we have a process ID, and also make
2342 // sure we know about our registers
2343 if (GetID() == LLDB_INVALID_PROCESS_ID)
2344 {
Greg Claytonc574ede2011-03-10 02:26:48 +00002345 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00002346 if (pid != LLDB_INVALID_PROCESS_ID)
2347 SetID (pid);
2348 }
2349 BuildDynamicRegisterInfo (true);
2350 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002351 // Stop with signal and thread info
Greg Clayton358cf1e2015-06-25 21:46:34 +00002352 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002353 const uint8_t signo = stop_packet.GetHexU8();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002354 std::string key;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002355 std::string value;
2356 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00002357 std::string reason;
2358 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002359 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00002360 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002361 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton0b90be12015-06-23 21:27:50 +00002362 bool queue_vars_valid = false; // says if locals below that start with "queue_" are valid
2363 std::string queue_name;
2364 QueueKind queue_kind = eQueueKindUnknown;
2365 uint64_t queue_serial = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002366 ExpeditedRegisterMap expedited_register_map;
2367 while (stop_packet.GetNameColonValue(key, value))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002368 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002369 if (key.compare("metype") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002370 {
2371 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002372 exc_type = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002373 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002374 else if (key.compare("medata") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002375 {
2376 // exception data in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002377 exc_data.push_back(StringConvert::ToUInt64 (value.c_str(), 0, 16));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002378 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002379 else if (key.compare("thread") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002380 {
2381 // thread in big endian hex
Greg Clayton358cf1e2015-06-25 21:46:34 +00002382 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002383 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002384 else if (key.compare("threads") == 0)
Greg Clayton9e920902012-04-10 02:25:43 +00002385 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002386 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00002387 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00002388 // A comma separated list of all threads in the current
2389 // process that includes the thread for this stop reply
2390 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00002391 size_t comma_pos;
2392 lldb::tid_t tid;
2393 while ((comma_pos = value.find(',')) != std::string::npos)
2394 {
2395 value[comma_pos] = '\0';
2396 // thread in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002397 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00002398 if (tid != LLDB_INVALID_THREAD_ID)
2399 m_thread_ids.push_back (tid);
2400 value.erase(0, comma_pos + 1);
Greg Clayton9e920902012-04-10 02:25:43 +00002401 }
Vince Harron5275aaa2015-01-15 20:08:35 +00002402 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00002403 if (tid != LLDB_INVALID_THREAD_ID)
2404 m_thread_ids.push_back (tid);
2405 }
Greg Clayton2e309072015-07-17 23:42:28 +00002406 else if (key.compare("jstopinfo") == 0)
Greg Claytona5801ad2015-07-15 22:59:03 +00002407 {
2408 StringExtractor json_extractor;
2409 // Swap "value" over into "name_extractor"
2410 json_extractor.GetStringRef().swap(value);
2411 // Now convert the HEX bytes into a string value
2412 json_extractor.GetHexByteString (value);
2413
2414 // This JSON contains thread IDs and thread stop info for all threads.
2415 // It doesn't contain expedited registers, memory or queue info.
Greg Clayton2e309072015-07-17 23:42:28 +00002416 m_jstopinfo_sp = StructuredData::ParseJSON (value);
Greg Claytona5801ad2015-07-15 22:59:03 +00002417 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002418 else if (key.compare("hexname") == 0)
Greg Claytonde9d0492011-01-08 03:17:57 +00002419 {
2420 StringExtractor name_extractor;
2421 // Swap "value" over into "name_extractor"
2422 name_extractor.GetStringRef().swap(value);
2423 // Now convert the HEX bytes into a string value
2424 name_extractor.GetHexByteString (value);
2425 thread_name.swap (value);
2426 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002427 else if (key.compare("name") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002428 {
2429 thread_name.swap (value);
2430 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002431 else if (key.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002432 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002433 thread_dispatch_qaddr = StringConvert::ToUInt64 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002434 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002435 else if (key.compare("qname") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002436 {
2437 queue_vars_valid = true;
2438 StringExtractor name_extractor;
2439 // Swap "value" over into "name_extractor"
2440 name_extractor.GetStringRef().swap(value);
2441 // Now convert the HEX bytes into a string value
2442 name_extractor.GetHexByteString (value);
2443 queue_name.swap (value);
2444 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002445 else if (key.compare("qkind") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002446 {
Greg Clayton0b90be12015-06-23 21:27:50 +00002447 if (value == "serial")
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002448 {
2449 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002450 queue_kind = eQueueKindSerial;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002451 }
Greg Clayton0b90be12015-06-23 21:27:50 +00002452 else if (value == "concurrent")
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002453 {
2454 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002455 queue_kind = eQueueKindConcurrent;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002456 }
Greg Clayton0b90be12015-06-23 21:27:50 +00002457 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002458 else if (key.compare("qserial") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002459 {
Greg Clayton0b90be12015-06-23 21:27:50 +00002460 queue_serial = StringConvert::ToUInt64 (value.c_str(), 0, 0);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002461 if (queue_serial != 0)
2462 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002463 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002464 else if (key.compare("reason") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002465 {
2466 reason.swap(value);
2467 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002468 else if (key.compare("description") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002469 {
2470 StringExtractor desc_extractor;
2471 // Swap "value" over into "name_extractor"
2472 desc_extractor.GetStringRef().swap(value);
2473 // Now convert the HEX bytes into a string value
Chaoren Lin28e57422015-02-03 01:51:25 +00002474 desc_extractor.GetHexByteString (value);
2475 description.swap(value);
Greg Claytona658fd22011-06-04 01:26:29 +00002476 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002477 else if (key.compare("memory") == 0)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002478 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002479 // Expedited memory. GDB servers can choose to send back expedited memory
2480 // that can populate the L1 memory cache in the process so that things like
2481 // the frame pointer backchain can be expedited. This will help stack
2482 // backtracing be more efficient by not having to send as many memory read
2483 // requests down the remote GDB server.
Chaoren Lin7a306082015-06-23 03:17:01 +00002484
Greg Clayton358cf1e2015-06-25 21:46:34 +00002485 // Key/value pair format: memory:<addr>=<bytes>;
2486 // <addr> is a number whose base will be interpreted by the prefix:
2487 // "0x[0-9a-fA-F]+" for hex
2488 // "0[0-7]+" for octal
2489 // "[1-9]+" for decimal
2490 // <bytes> is native endian ASCII hex bytes just like the register values
2491 llvm::StringRef value_ref(value);
2492 std::pair<llvm::StringRef, llvm::StringRef> pair;
2493 pair = value_ref.split('=');
2494 if (!pair.first.empty() && !pair.second.empty())
2495 {
2496 std::string addr_str(pair.first.str());
2497 const lldb::addr_t mem_cache_addr = StringConvert::ToUInt64(addr_str.c_str(), LLDB_INVALID_ADDRESS, 0);
2498 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002499 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002500 StringExtractor bytes;
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002501 bytes.GetStringRef() = pair.second.str();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002502 const size_t byte_size = bytes.GetStringRef().size()/2;
2503 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2504 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2505 if (bytes_copied == byte_size)
2506 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
Greg Clayton3e06bd92011-01-09 21:07:35 +00002507 }
2508 }
2509 }
Jaydeep Patil725666c2015-08-13 03:46:01 +00002510 else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 || key.compare("awatch") == 0)
2511 {
2512 // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2513 lldb::addr_t wp_addr = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
2514 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2515 uint32_t wp_index = LLDB_INVALID_INDEX32;
2516
2517 if (wp_sp)
2518 wp_index = wp_sp->GetHardwareIndex();
2519
2520 reason = "watchpoint";
2521 StreamString ostr;
2522 ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
2523 description = ostr.GetString().c_str();
2524 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002525 else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1]))
2526 {
2527 uint32_t reg = StringConvert::ToUInt32 (key.c_str(), UINT32_MAX, 16);
2528 if (reg != UINT32_MAX)
2529 expedited_register_map[reg] = std::move(value);
2530 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002531 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002532
Bhushan D. Attarde1e271df2015-07-24 04:06:20 +00002533 if (tid == LLDB_INVALID_THREAD_ID)
2534 {
2535 // A thread id may be invalid if the response is old style 'S' packet which does not provide the
2536 // thread information. So update the thread list and choose the first one.
2537 UpdateThreadIDList ();
2538
2539 if (!m_thread_ids.empty ())
2540 {
2541 tid = m_thread_ids.front ();
2542 }
2543 }
2544
Greg Clayton358cf1e2015-06-25 21:46:34 +00002545 ThreadSP thread_sp = SetThreadStopInfo (tid,
2546 expedited_register_map,
2547 signo,
2548 thread_name,
2549 reason,
2550 description,
2551 exc_type,
2552 exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002553 thread_dispatch_qaddr,
2554 queue_vars_valid,
2555 queue_name,
2556 queue_kind,
2557 queue_serial);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002558
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002559 return eStateStopped;
2560 }
2561 break;
2562
2563 case 'W':
Todd Fialaff6131a2014-05-19 04:57:23 +00002564 case 'X':
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002565 // process exited
2566 return eStateExited;
2567
2568 default:
2569 break;
2570 }
2571 return eStateInvalid;
2572}
2573
2574void
2575ProcessGDBRemote::RefreshStateAfterStop ()
2576{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002577 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00002578 m_thread_ids.clear();
2579 // Set the thread stop info. It might have a "threads" key whose value is
2580 // a list of all thread IDs in the current process, so m_thread_ids might
2581 // get set.
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002582
2583 // Scope for the lock
2584 {
2585 // Lock the thread stack while we access it
2586 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
2587 // Get the number of stop packets on the stack
2588 int nItems = m_stop_packet_stack.size();
2589 // Iterate over them
2590 for (int i = 0; i < nItems; i++)
2591 {
2592 // Get the thread stop info
2593 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2594 // Process thread stop info
2595 SetThreadStopInfo(stop_info);
2596 }
2597 // Clear the thread stop stack
2598 m_stop_packet_stack.clear();
2599 }
2600
Greg Clayton9e920902012-04-10 02:25:43 +00002601 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2602 if (m_thread_ids.empty())
2603 {
2604 // No, we need to fetch the thread list manually
2605 UpdateThreadIDList();
2606 }
2607
Ewan Crawford78baa192015-05-13 09:18:18 +00002608 // If we have queried for a default thread id
2609 if (m_initial_tid != LLDB_INVALID_THREAD_ID)
2610 {
2611 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2612 m_initial_tid = LLDB_INVALID_THREAD_ID;
2613 }
2614
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002615 // Let all threads recover from stopping and do any clean up based
2616 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002617 m_thread_list_real.RefreshStateAfterStop();
Greg Clayton9e920902012-04-10 02:25:43 +00002618
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002619}
2620
2621Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002622ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002623{
2624 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002625
Greg Clayton6ed95942011-01-22 07:12:45 +00002626 bool timed_out = false;
2627 Mutex::Locker locker;
Greg Clayton513c26c2011-01-29 07:10:55 +00002628
2629 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002630 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002631 // We are being asked to halt during an attach. We need to just close
2632 // our file handle and debugserver will go away, and we can be done...
2633 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00002634 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002635 else
2636 {
Greg Clayton2687cd12012-03-29 01:55:41 +00002637 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton513c26c2011-01-29 07:10:55 +00002638 {
2639 if (timed_out)
2640 error.SetErrorString("timed out sending interrupt packet");
2641 else
2642 error.SetErrorString("unknown error sending interrupt packet");
2643 }
Greg Clayton2687cd12012-03-29 01:55:41 +00002644
2645 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton513c26c2011-01-29 07:10:55 +00002646 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002647 return error;
2648}
2649
2650Error
Jim Inghamacff8952013-05-02 00:27:30 +00002651ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002652{
2653 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002654 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00002655 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00002656 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2657
Jim Inghamacff8952013-05-02 00:27:30 +00002658 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002659 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002660 {
Jim Inghamacff8952013-05-02 00:27:30 +00002661 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002662 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
2663 else
Jim Inghamacff8952013-05-02 00:27:30 +00002664 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00002665 }
Jim Inghamacff8952013-05-02 00:27:30 +00002666
2667 if (!error.Success())
2668 return error;
2669
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002670 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00002671 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002672
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002673 SetPrivateState (eStateDetached);
2674 ResumePrivateStateThread();
2675
2676 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00002677 return error;
2678}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002679
Jim Ingham43c555d2012-07-04 00:35:43 +00002680
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002681Error
2682ProcessGDBRemote::DoDestroy ()
2683{
2684 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002685 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002686 if (log)
2687 log->Printf ("ProcessGDBRemote::DoDestroy()");
2688
Jim Ingham43c555d2012-07-04 00:35:43 +00002689 // There is a bug in older iOS debugservers where they don't shut down the process
2690 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
2691 // this can cause problems with restarting. So we check to see if any of our threads are stopped
2692 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
2693 // destroy it again.
2694 //
2695 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
2696 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
2697 // the debugservers with this bug are equal. There really should be a better way to test this!
2698 //
2699 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
2700 // get called here to destroy again and we're still at a breakpoint or exception, then we should
2701 // just do the straight-forward kill.
2702 //
2703 // And of course, if we weren't able to stop the process by the time we get here, it isn't
2704 // necessary (or helpful) to do any of this.
2705
2706 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
2707 {
2708 PlatformSP platform_sp = GetTarget().GetPlatform();
2709
2710 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2711 if (platform_sp
2712 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00002713 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00002714 {
2715 if (m_destroy_tried_resuming)
2716 {
2717 if (log)
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002718 log->PutCString ("ProcessGDBRemote::DoDestroy() - Tried resuming to destroy once already, not doing it again.");
Jim Ingham43c555d2012-07-04 00:35:43 +00002719 }
2720 else
2721 {
2722 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
2723 // but we really need it to happen here and it doesn't matter if we do it twice.
2724 m_thread_list.DiscardThreadPlans();
2725 DisableAllBreakpointSites();
2726
2727 bool stop_looks_like_crash = false;
2728 ThreadList &threads = GetThreadList();
2729
2730 {
Jim Ingham45350372012-09-11 00:08:52 +00002731 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002732
2733 size_t num_threads = threads.GetSize();
2734 for (size_t i = 0; i < num_threads; i++)
2735 {
2736 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002737 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002738 StopReason reason = eStopReasonInvalid;
2739 if (stop_info_sp)
2740 reason = stop_info_sp->GetStopReason();
2741 if (reason == eStopReasonBreakpoint
2742 || reason == eStopReasonException)
2743 {
2744 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002745 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
2746 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00002747 stop_info_sp->GetDescription());
2748 stop_looks_like_crash = true;
2749 break;
2750 }
2751 }
2752 }
2753
2754 if (stop_looks_like_crash)
2755 {
2756 if (log)
2757 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
2758 m_destroy_tried_resuming = true;
2759
2760 // If we are going to run again before killing, it would be good to suspend all the threads
2761 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
2762 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
2763 // have to run the risk of letting those threads proceed a bit.
2764
2765 {
Jim Ingham45350372012-09-11 00:08:52 +00002766 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002767
2768 size_t num_threads = threads.GetSize();
2769 for (size_t i = 0; i < num_threads; i++)
2770 {
2771 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002772 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002773 StopReason reason = eStopReasonInvalid;
2774 if (stop_info_sp)
2775 reason = stop_info_sp->GetStopReason();
2776 if (reason != eStopReasonBreakpoint
2777 && reason != eStopReasonException)
2778 {
2779 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002780 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
2781 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00002782 thread_sp->SetResumeState(eStateSuspended);
2783 }
2784 }
2785 }
2786 Resume ();
Jason Molendaede31932015-04-17 05:01:58 +00002787 return Destroy(false);
Jim Ingham43c555d2012-07-04 00:35:43 +00002788 }
2789 }
2790 }
2791 }
2792
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002793 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00002794 int exit_status = SIGABRT;
2795 std::string exit_string;
2796
Greg Clayton6ed95942011-01-22 07:12:45 +00002797 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002798 {
Jim Inghamaab78372011-10-28 01:11:35 +00002799 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00002800 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002801 StringExtractorGDBRemote response;
2802 bool send_async = true;
Tamas Berghammer912800c2015-02-24 10:23:39 +00002803 GDBRemoteCommunication::ScopedTimeout (m_gdb_comm, 3);
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002804
Greg Clayton3dedae12013-12-06 21:45:27 +00002805 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton513c26c2011-01-29 07:10:55 +00002806 {
2807 char packet_cmd = response.GetChar(0);
2808
2809 if (packet_cmd == 'W' || packet_cmd == 'X')
2810 {
Jim Inghameac0aa42014-02-21 22:36:11 +00002811#if defined(__APPLE__)
Jim Ingham9d67cc52014-02-21 22:35:29 +00002812 // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off
2813 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill
2814 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns
2815 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap
2816 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of
2817 // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2818 // Anyway, so call waitpid here to finally reap it.
2819 PlatformSP platform_sp(GetTarget().GetPlatform());
2820 if (platform_sp && platform_sp->IsHost())
2821 {
2822 int status;
2823 ::pid_t reap_pid;
2824 reap_pid = waitpid (GetID(), &status, WNOHANG);
2825 if (log)
2826 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2827 }
2828#endif
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002829 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002830 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00002831 exit_status = response.GetHexU8();
2832 }
2833 else
2834 {
2835 if (log)
2836 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2837 exit_string.assign("got unexpected response to k packet: ");
2838 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00002839 }
2840 }
2841 else
2842 {
Jim Inghambabfc382012-06-06 00:32:39 +00002843 if (log)
2844 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2845 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00002846 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002847 }
Jim Inghambabfc382012-06-06 00:32:39 +00002848 else
2849 {
2850 if (log)
Ed Masteb3a53332014-03-17 17:05:22 +00002851 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching");
Jim Inghamcfc09352012-07-27 23:57:19 +00002852 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00002853 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002854 }
Jim Inghambabfc382012-06-06 00:32:39 +00002855 else
2856 {
2857 // If we missed setting the exit status on the way out, do it here.
2858 // NB set exit status can be called multiple times, the first one sets the status.
2859 exit_string.assign("destroying when not connected to debugserver");
2860 }
2861
2862 SetExitStatus(exit_status, exit_string.c_str());
2863
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002864 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002865 KillDebugserverProcess ();
2866 return error;
2867}
2868
Greg Clayton8cda7f02013-05-21 21:55:59 +00002869void
2870ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2871{
Greg Clayton8cda7f02013-05-21 21:55:59 +00002872 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2873 if (did_exec)
2874 {
2875 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2876 if (log)
2877 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2878
2879 m_thread_list_real.Clear();
2880 m_thread_list.Clear();
2881 BuildDynamicRegisterInfo (true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002882 m_gdb_comm.ResetDiscoverableSettings (did_exec);
Greg Clayton8cda7f02013-05-21 21:55:59 +00002883 }
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002884
2885 // Scope the lock
2886 {
2887 // Lock the thread stack while we access it
2888 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
Greg Clayton2e309072015-07-17 23:42:28 +00002889
2890 // We are are not using non-stop mode, there can only be one last stop
2891 // reply packet, so clear the list.
2892 if (GetTarget().GetNonStopModeEnabled() == false)
2893 m_stop_packet_stack.clear();
2894
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002895 // Add this stop packet to the stop packet stack
2896 // This stack will get popped and examined when we switch to the
2897 // Stopped state
2898 m_stop_packet_stack.push_back(response);
2899 }
Greg Clayton8cda7f02013-05-21 21:55:59 +00002900}
2901
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002902//------------------------------------------------------------------
2903// Process Queries
2904//------------------------------------------------------------------
2905
2906bool
2907ProcessGDBRemote::IsAlive ()
2908{
Greg Clayton10177aa2010-12-08 05:08:21 +00002909 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002910}
2911
2912addr_t
2913ProcessGDBRemote::GetImageInfoAddress()
2914{
Aidan Doddsc0c83852015-05-08 09:36:31 +00002915 // request the link map address via the $qShlibInfoAddr packet
2916 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2917
2918 // the loaded module list can also provides a link map address
2919 if (addr == LLDB_INVALID_ADDRESS)
2920 {
2921 GDBLoadedModuleInfoList list;
2922 if (GetLoadedModuleList (list).Success())
2923 addr = list.m_link_map;
2924 }
2925
2926 return addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002927}
2928
Greg Clayton2e309072015-07-17 23:42:28 +00002929void
2930ProcessGDBRemote::WillPublicStop ()
2931{
2932 // See if the GDB remote client supports the JSON threads info.
2933 // If so, we gather stop info for all threads, expedited registers,
2934 // expedited memory, runtime queue information (iOS and MacOSX only),
2935 // and more. Expediting memory will help stack backtracing be much
2936 // faster. Expediting registers will make sure we don't have to read
2937 // the thread registers for GPRs.
2938 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
2939
2940 if (m_jthreadsinfo_sp)
2941 {
2942 // Now set the stop info for each thread and also expedite any registers
2943 // and memory that was in the jThreadsInfo response.
2944 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
2945 if (thread_infos)
2946 {
2947 const size_t n = thread_infos->GetSize();
2948 for (size_t i=0; i<n; ++i)
2949 {
2950 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
2951 if (thread_dict)
2952 SetThreadStopInfo(thread_dict);
2953 }
2954 }
2955 }
2956}
2957
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002958//------------------------------------------------------------------
2959// Process Memory
2960//------------------------------------------------------------------
2961size_t
2962ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2963{
Jason Molenda6076bf42014-05-06 04:34:52 +00002964 GetMaxMemorySize ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002965 if (size > m_max_memory_size)
2966 {
2967 // Keep memory read sizes down to a sane limit. This function will be
2968 // called multiple times in order to complete the task by
2969 // lldb_private::Process so it is ok to do this.
2970 size = m_max_memory_size;
2971 }
2972
2973 char packet[64];
Jason Molenda6076bf42014-05-06 04:34:52 +00002974 int packet_len;
2975 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2976 if (binary_memory_read)
2977 {
2978 packet_len = ::snprintf (packet, sizeof(packet), "x0x%" PRIx64 ",0x%" PRIx64, (uint64_t)addr, (uint64_t)size);
2979 }
2980 else
2981 {
2982 packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
2983 }
Andy Gibbsa297a972013-06-19 19:04:53 +00002984 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002985 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002986 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002987 {
Greg Clayton576d8832011-03-22 04:00:09 +00002988 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002989 {
2990 error.Clear();
Jason Molenda6076bf42014-05-06 04:34:52 +00002991 if (binary_memory_read)
2992 {
2993 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any
2994 // 0x7d character escaping that was present in the packet
2995
2996 size_t data_received_size = response.GetBytesLeft();
2997 if (data_received_size > size)
2998 {
2999 // Don't write past the end of BUF if the remote debug server gave us too
3000 // much data for some reason.
3001 data_received_size = size;
3002 }
3003 memcpy (buf, response.GetStringRef().data(), data_received_size);
3004 return data_received_size;
3005 }
3006 else
3007 {
3008 return response.GetHexBytes(buf, size, '\xdd');
3009 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003010 }
Greg Clayton576d8832011-03-22 04:00:09 +00003011 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00003012 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00003013 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00003014 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003015 else
Greg Clayton9944cd72012-09-19 01:46:31 +00003016 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003017 }
3018 else
3019 {
Jim Ingham35579dd2013-06-03 19:34:01 +00003020 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003021 }
3022 return 0;
3023}
3024
3025size_t
3026ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
3027{
Jason Molenda6076bf42014-05-06 04:34:52 +00003028 GetMaxMemorySize ();
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00003029 if (size > m_max_memory_size)
3030 {
3031 // Keep memory read sizes down to a sane limit. This function will be
3032 // called multiple times in order to complete the task by
3033 // lldb_private::Process so it is ok to do this.
3034 size = m_max_memory_size;
3035 }
3036
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003037 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00003038 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Clayton7fb56d02011-02-01 01:31:41 +00003039 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003040 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003041 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003042 {
Greg Clayton576d8832011-03-22 04:00:09 +00003043 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003044 {
3045 error.Clear();
3046 return size;
3047 }
Greg Clayton576d8832011-03-22 04:00:09 +00003048 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00003049 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00003050 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00003051 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003052 else
Greg Clayton9944cd72012-09-19 01:46:31 +00003053 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 +00003054 }
3055 else
3056 {
Jim Ingham35579dd2013-06-03 19:34:01 +00003057 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003058 }
3059 return 0;
3060}
3061
3062lldb::addr_t
3063ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
3064{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003065 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_EXPRESSIONS));
Greg Clayton2a48f522011-05-14 01:50:35 +00003066 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
3067
Greg Clayton70b57652011-05-15 01:25:55 +00003068 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton2a48f522011-05-14 01:50:35 +00003069 switch (supported)
3070 {
3071 case eLazyBoolCalculate:
3072 case eLazyBoolYes:
3073 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
3074 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
3075 return allocated_addr;
3076
3077 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003078 // Call mmap() to create memory in the inferior..
3079 unsigned prot = 0;
3080 if (permissions & lldb::ePermissionsReadable)
3081 prot |= eMmapProtRead;
3082 if (permissions & lldb::ePermissionsWritable)
3083 prot |= eMmapProtWrite;
3084 if (permissions & lldb::ePermissionsExecutable)
3085 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00003086
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003087 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
3088 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
3089 m_addr_to_mmap_size[allocated_addr] = size;
3090 else
Todd Fialaaf245d12014-06-30 21:05:18 +00003091 {
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003092 allocated_addr = LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00003093 if (log)
3094 log->Printf ("ProcessGDBRemote::%s no direct stub support for memory allocation, and InferiorCallMmap also failed - is stub missing register context save/restore capability?", __FUNCTION__);
3095 }
Greg Clayton2a48f522011-05-14 01:50:35 +00003096 break;
3097 }
3098
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003099 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00003100 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003101 else
3102 error.Clear();
3103 return allocated_addr;
3104}
3105
3106Error
Greg Clayton46fb5582011-11-18 07:03:08 +00003107ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
3108 MemoryRegionInfo &region_info)
3109{
3110
3111 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
3112 return error;
3113}
3114
3115Error
Johnny Chen64637202012-05-23 21:09:52 +00003116ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
3117{
3118
3119 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
3120 return error;
3121}
3122
3123Error
Enrico Granataf04a2192012-07-13 23:18:48 +00003124ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
3125{
Jaydeep Patil725666c2015-08-13 03:46:01 +00003126 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after, GetTarget().GetArchitecture()));
Enrico Granataf04a2192012-07-13 23:18:48 +00003127 return error;
3128}
3129
3130Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003131ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
3132{
3133 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00003134 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
3135
3136 switch (supported)
3137 {
3138 case eLazyBoolCalculate:
3139 // We should never be deallocating memory without allocating memory
3140 // first so we should never get eLazyBoolCalculate
3141 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
3142 break;
3143
3144 case eLazyBoolYes:
3145 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00003146 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003147 break;
3148
3149 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003150 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00003151 {
3152 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003153 if (pos != m_addr_to_mmap_size.end() &&
3154 InferiorCallMunmap(this, addr, pos->second))
3155 m_addr_to_mmap_size.erase (pos);
3156 else
Daniel Malead01b2952012-11-29 21:49:15 +00003157 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003158 }
3159 break;
3160 }
3161
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003162 return error;
3163}
3164
3165
3166//------------------------------------------------------------------
3167// Process STDIO
3168//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003169size_t
3170ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
3171{
3172 if (m_stdio_communication.IsConnected())
3173 {
3174 ConnectionStatus status;
3175 m_stdio_communication.Write(src, src_len, status, NULL);
3176 }
Vince Harrondf3f00f2015-02-10 21:09:04 +00003177 else if (m_stdin_forward)
Vince Harrone0be4252015-02-06 18:32:57 +00003178 {
3179 m_gdb_comm.SendStdinNotification(src, src_len);
3180 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003181 return 0;
3182}
3183
3184Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003185ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003186{
3187 Error error;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003188 assert(bp_site != NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003189
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003190 // Get logging info
3191 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003192 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003193
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003194 // Get the breakpoint address
3195 const addr_t addr = bp_site->GetLoadAddress();
3196
3197 // Log that a breakpoint was requested
3198 if (log)
3199 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
3200
3201 // Breakpoint already exists and is enabled
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003202 if (bp_site->IsEnabled())
3203 {
3204 if (log)
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003205 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 +00003206 return error;
3207 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003208
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003209 // Get the software breakpoint trap opcode size
3210 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3211
3212 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
3213 // is supported by the remote stub. These are set to true by default, and later set to false
3214 // only after we receive an unimplemented response when sending a breakpoint packet. This means
3215 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
3216 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
3217 // indicates if the user specifically asked for hardware breakpoints. If true then we will
3218 // skip over software breakpoints.
3219 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
3220 {
3221 // Try to send off a software breakpoint packet ($Z0)
3222 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003223 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003224 // The breakpoint was placed successfully
3225 bp_site->SetEnabled(true);
3226 bp_site->SetType(BreakpointSite::eExternal);
Greg Claytoneb023e72013-10-11 19:48:25 +00003227 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003228 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003229
3230 // SendGDBStoppointTypePacket() will return an error if it was unable to set this
3231 // breakpoint. We need to differentiate between a error specific to placing this breakpoint
3232 // or if we have learned that this breakpoint type is unsupported. To do this, we
3233 // must test the support boolean for this breakpoint type to see if it now indicates that
3234 // this breakpoint type is unsupported. If they are still supported then we should return
3235 // with the error code. If they are now unsupported, then we would like to fall through
3236 // and try another form of breakpoint.
3237 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
3238 return error;
3239
3240 // We reach here when software breakpoints have been found to be unsupported. For future
3241 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
3242 // known not to be supported.
3243 if (log)
3244 log->Printf("Software breakpoints are unsupported");
3245
3246 // So we will fall through and try a hardware breakpoint
3247 }
3248
3249 // The process of setting a hardware breakpoint is much the same as above. We check the
3250 // supported boolean for this breakpoint type, and if it is thought to be supported then we
3251 // will try to set this breakpoint with a hardware breakpoint.
3252 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3253 {
3254 // Try to send off a hardware breakpoint packet ($Z1)
3255 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003256 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003257 // The breakpoint was placed successfully
3258 bp_site->SetEnabled(true);
3259 bp_site->SetType(BreakpointSite::eHardware);
3260 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003261 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003262
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003263 // Check if the error was something other then an unsupported breakpoint type
3264 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3265 {
3266 // Unable to set this hardware breakpoint
3267 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
3268 return error;
3269 }
3270
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003271 // We will reach here when the stub gives an unsupported response to a hardware breakpoint
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003272 if (log)
3273 log->Printf("Hardware breakpoints are unsupported");
3274
3275 // Finally we will falling through to a #trap style breakpoint
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003276 }
3277
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003278 // Don't fall through when hardware breakpoints were specifically requested
3279 if (bp_site->HardwareRequired())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003280 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003281 error.SetErrorString("hardware breakpoints are not supported");
3282 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003283 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003284
3285 // As a last resort we want to place a manual breakpoint. An instruction
3286 // is placed into the process memory using memory write packets.
3287 return EnableSoftwareBreakpoint(bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003288}
3289
3290Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003291ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003292{
3293 Error error;
3294 assert (bp_site != NULL);
3295 addr_t addr = bp_site->GetLoadAddress();
3296 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00003297 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003298 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003299 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003300
3301 if (bp_site->IsEnabled())
3302 {
3303 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
3304
Greg Clayton8b82f082011-04-12 05:54:46 +00003305 BreakpointSite::Type bp_type = bp_site->GetType();
3306 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003307 {
Greg Clayton8b82f082011-04-12 05:54:46 +00003308 case BreakpointSite::eSoftware:
3309 error = DisableSoftwareBreakpoint (bp_site);
3310 break;
3311
3312 case BreakpointSite::eHardware:
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003313 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003314 error.SetErrorToGenericError();
3315 break;
3316
3317 case BreakpointSite::eExternal:
Jim Inghama04ef752014-03-07 11:18:02 +00003318 {
3319 GDBStoppointType stoppoint_type;
3320 if (bp_site->IsHardware())
3321 stoppoint_type = eBreakpointHardware;
3322 else
3323 stoppoint_type = eBreakpointSoftware;
3324
3325 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003326 error.SetErrorToGenericError();
Jim Inghama04ef752014-03-07 11:18:02 +00003327 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003328 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003329 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003330 if (error.Success())
3331 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003332 }
3333 else
3334 {
3335 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003336 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 +00003337 return error;
3338 }
3339
3340 if (error.Success())
3341 error.SetErrorToGenericError();
3342 return error;
3343}
3344
Johnny Chen11309a32011-09-06 22:38:36 +00003345// Pre-requisite: wp != NULL.
3346static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00003347GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00003348{
3349 assert(wp);
3350 bool watch_read = wp->WatchpointRead();
3351 bool watch_write = wp->WatchpointWrite();
3352
3353 // watch_read and watch_write cannot both be false.
3354 assert(watch_read || watch_write);
3355 if (watch_read && watch_write)
3356 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00003357 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00003358 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00003359 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00003360 return eWatchpointWrite;
3361}
3362
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003363Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003364ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003365{
3366 Error error;
3367 if (wp)
3368 {
3369 user_id_t watchID = wp->GetID();
3370 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00003371 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003372 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003373 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003374 if (wp->IsEnabled())
3375 {
3376 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003377 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 +00003378 return error;
3379 }
Johnny Chen11309a32011-09-06 22:38:36 +00003380
3381 GDBStoppointType type = GetGDBStoppointType(wp);
3382 // Pass down an appropriate z/Z packet...
3383 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003384 {
Johnny Chen11309a32011-09-06 22:38:36 +00003385 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
3386 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003387 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003388 return error;
3389 }
3390 else
3391 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003392 }
Johnny Chen11309a32011-09-06 22:38:36 +00003393 else
3394 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003395 }
3396 else
3397 {
Johnny Chen01a67862011-10-14 00:42:25 +00003398 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003399 }
3400 if (error.Success())
3401 error.SetErrorToGenericError();
3402 return error;
3403}
3404
3405Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003406ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003407{
3408 Error error;
3409 if (wp)
3410 {
3411 user_id_t watchID = wp->GetID();
3412
Greg Clayton5160ce52013-03-27 23:08:40 +00003413 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003414
3415 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00003416
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003417 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003418 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003419
Johnny Chen11309a32011-09-06 22:38:36 +00003420 if (!wp->IsEnabled())
3421 {
3422 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003423 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 +00003424 // See also 'class WatchpointSentry' within StopInfo.cpp.
3425 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
3426 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00003427 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003428 return error;
3429 }
3430
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003431 if (wp->IsHardware())
3432 {
Johnny Chen11309a32011-09-06 22:38:36 +00003433 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003434 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00003435 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
3436 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003437 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003438 return error;
3439 }
3440 else
3441 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003442 }
3443 // TODO: clear software watchpoints if we implement them
3444 }
3445 else
3446 {
Johnny Chen01a67862011-10-14 00:42:25 +00003447 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003448 }
3449 if (error.Success())
3450 error.SetErrorToGenericError();
3451 return error;
3452}
3453
3454void
3455ProcessGDBRemote::Clear()
3456{
3457 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00003458 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003459 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003460}
3461
3462Error
3463ProcessGDBRemote::DoSignal (int signo)
3464{
3465 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00003466 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003467 if (log)
3468 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
3469
3470 if (!m_gdb_comm.SendAsyncSignal (signo))
3471 error.SetErrorStringWithFormat("failed to send signal %i", signo);
3472 return error;
3473}
3474
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003475Error
Greg Clayton91a9b2472013-12-04 19:19:12 +00003476ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003477{
3478 Error error;
3479 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
3480 {
3481 // If we locate debugserver, keep that located version around
3482 static FileSpec g_debugserver_file_spec;
3483
Han Ming Ong84647042012-02-25 01:07:38 +00003484 ProcessLaunchInfo debugserver_launch_info;
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00003485 // Make debugserver run in its own session so signals generated by
3486 // special terminal key sequences (^C) don't affect debugserver.
3487 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3488
Greg Clayton91a9b2472013-12-04 19:19:12 +00003489 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
3490 debugserver_launch_info.SetUserID(process_info.GetUserID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003491
Todd Fiala013434e2014-07-09 01:29:05 +00003492#if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__) || defined (__aarch64__))
Greg Claytonfda4fab2014-01-10 22:24:11 +00003493 // On iOS, still do a local connection using a random port
Greg Clayton16810922014-02-27 19:38:18 +00003494 const char *hostname = "127.0.0.1";
Greg Claytonfda4fab2014-01-10 22:24:11 +00003495 uint16_t port = get_random_port ();
3496#else
3497 // Set hostname being NULL to do the reverse connect where debugserver
3498 // will bind to port zero and it will communicate back to us the port
3499 // that we will connect to
3500 const char *hostname = NULL;
3501 uint16_t port = 0;
3502#endif
3503
3504 error = m_gdb_comm.StartDebugserverProcess (hostname,
3505 port,
Greg Clayton00fe87b2013-12-05 22:58:22 +00003506 debugserver_launch_info,
3507 port);
Greg Clayton91a9b2472013-12-04 19:19:12 +00003508
3509 if (error.Success ())
3510 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003511 else
Greg Clayton91a9b2472013-12-04 19:19:12 +00003512 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003513
3514 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3515 StartAsyncThread ();
Greg Clayton91a9b2472013-12-04 19:19:12 +00003516
3517 if (error.Fail())
3518 {
3519 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
3520
3521 if (log)
3522 log->Printf("failed to start debugserver process: %s", error.AsCString());
3523 return error;
3524 }
3525
Greg Clayton00fe87b2013-12-05 22:58:22 +00003526 if (m_gdb_comm.IsConnected())
3527 {
3528 // Finish the connection process by doing the handshake without connecting (send NULL URL)
3529 ConnectToDebugserver (NULL);
3530 }
3531 else
3532 {
Greg Claytonfda4fab2014-01-10 22:24:11 +00003533 StreamString connect_url;
3534 connect_url.Printf("connect://%s:%u", hostname, port);
3535 error = ConnectToDebugserver (connect_url.GetString().c_str());
Greg Clayton00fe87b2013-12-05 22:58:22 +00003536 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00003537
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003538 }
3539 return error;
3540}
3541
3542bool
3543ProcessGDBRemote::MonitorDebugserverProcess
3544(
3545 void *callback_baton,
3546 lldb::pid_t debugserver_pid,
Greg Claytone4e45922011-11-16 05:37:56 +00003547 bool exited, // True if the process did exit
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003548 int signo, // Zero for no signal
3549 int exit_status // Exit value of process if signal is zero
3550)
3551{
Greg Claytone4e45922011-11-16 05:37:56 +00003552 // The baton is a "ProcessGDBRemote *". Now this class might be gone
3553 // and might not exist anymore, so we need to carefully try to get the
3554 // target for this process first since we have a race condition when
3555 // we are done running between getting the notice that the inferior
3556 // process has died and the debugserver that was debugging this process.
3557 // In our test suite, we are also continually running process after
3558 // process, so we must be very careful to make sure:
3559 // 1 - process object hasn't been deleted already
3560 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003561
3562 // "debugserver_pid" argument passed in is the process ID for
3563 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00003564 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003565
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003566 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton6779606a2011-01-22 23:43:18 +00003567
Greg Claytone4e45922011-11-16 05:37:56 +00003568 // Get a shared pointer to the target that has a matching process pointer.
3569 // This target could be gone, or the target could already have a new process
3570 // object inside of it
3571 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
3572
Greg Clayton6779606a2011-01-22 23:43:18 +00003573 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003574 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%" PRIu64 ", signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
Greg Clayton6779606a2011-01-22 23:43:18 +00003575
Greg Claytone4e45922011-11-16 05:37:56 +00003576 if (target_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003577 {
Greg Claytone4e45922011-11-16 05:37:56 +00003578 // We found a process in a target that matches, but another thread
3579 // might be in the process of launching a new process that will
3580 // soon replace it, so get a shared pointer to the process so we
3581 // can keep it alive.
3582 ProcessSP process_sp (target_sp->GetProcessSP());
3583 // Now we have a shared pointer to the process that can't go away on us
3584 // so we now make sure it was the same as the one passed in, and also make
3585 // sure that our previous "process *" didn't get deleted and have a new
3586 // "process *" created in its place with the same pointer. To verify this
3587 // we make sure the process has our debugserver process ID. If we pass all
3588 // of these tests, then we are sure that this process is the one we were
3589 // looking for.
3590 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003591 {
Greg Claytone4e45922011-11-16 05:37:56 +00003592 // Sleep for a half a second to make sure our inferior process has
3593 // time to set its exit status before we set it incorrectly when
3594 // both the debugserver and the inferior process shut down.
3595 usleep (500000);
3596 // If our process hasn't yet exited, debugserver might have died.
3597 // If the process did exit, the we are reaping it.
3598 const StateType state = process->GetState();
3599
3600 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
3601 state != eStateInvalid &&
3602 state != eStateUnloaded &&
3603 state != eStateExited &&
3604 state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003605 {
Greg Claytone4e45922011-11-16 05:37:56 +00003606 char error_str[1024];
3607 if (signo)
3608 {
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00003609 const char *signal_cstr = process->GetUnixSignals()->GetSignalAsCString(signo);
Greg Claytone4e45922011-11-16 05:37:56 +00003610 if (signal_cstr)
3611 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3612 else
3613 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
3614 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003615 else
Greg Claytone4e45922011-11-16 05:37:56 +00003616 {
3617 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
3618 }
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003619
Greg Claytone4e45922011-11-16 05:37:56 +00003620 process->SetExitStatus (-1, error_str);
3621 }
3622 // Debugserver has exited we need to let our ProcessGDBRemote
3623 // know that it no longer has a debugserver instance
3624 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003625 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003626 }
3627 return true;
3628}
3629
3630void
3631ProcessGDBRemote::KillDebugserverProcess ()
3632{
Greg Claytonfbb76342013-11-20 21:07:01 +00003633 m_gdb_comm.Disconnect();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003634 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3635 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003636 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003637 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3638 }
3639}
3640
3641void
3642ProcessGDBRemote::Initialize()
3643{
Davide Italianoc8d69822015-04-03 04:24:32 +00003644 static std::once_flag g_once_flag;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003645
Davide Italianoc8d69822015-04-03 04:24:32 +00003646 std::call_once(g_once_flag, []()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003647 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003648 PluginManager::RegisterPlugin (GetPluginNameStatic(),
3649 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00003650 CreateInstance,
3651 DebuggerInitialize);
Davide Italianoc8d69822015-04-03 04:24:32 +00003652 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003653}
3654
Greg Clayton7f982402013-07-15 22:54:20 +00003655void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003656ProcessGDBRemote::DebuggerInitialize (Debugger &debugger)
Greg Clayton7f982402013-07-15 22:54:20 +00003657{
3658 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
3659 {
3660 const bool is_global_setting = true;
3661 PluginManager::CreateSettingForProcessPlugin (debugger,
3662 GetGlobalPluginProperties()->GetValueProperties(),
3663 ConstString ("Properties for the gdb-remote process plug-in."),
3664 is_global_setting);
3665 }
3666}
3667
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003668bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003669ProcessGDBRemote::StartAsyncThread ()
3670{
Greg Clayton5160ce52013-03-27 23:08:40 +00003671 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003672
3673 if (log)
3674 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003675
3676 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003677 if (!m_async_thread.IsJoinable())
Jim Ingham455fa5c2012-11-01 01:15:33 +00003678 {
3679 // Create a thread that watches our internal state and controls which
3680 // events make it to clients (into the DCProcess event queue).
Zachary Turner39de3112014-09-09 20:54:56 +00003681
3682 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003683 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003684 else if (log)
3685 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was already running.", __FUNCTION__);
Zachary Turner39de3112014-09-09 20:54:56 +00003686
Zachary Turneracee96a2014-09-23 18:32:09 +00003687 return m_async_thread.IsJoinable();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003688}
3689
3690void
3691ProcessGDBRemote::StopAsyncThread ()
3692{
Greg Clayton5160ce52013-03-27 23:08:40 +00003693 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003694
3695 if (log)
3696 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
3697
Jim Ingham455fa5c2012-11-01 01:15:33 +00003698 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003699 if (m_async_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003700 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00003701 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
3702
3703 // This will shut down the async thread.
3704 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3705
3706 // Stop the stdio thread
Zachary Turner39de3112014-09-09 20:54:56 +00003707 m_async_thread.Join(nullptr);
Pavel Labatha55a9532015-03-11 09:53:42 +00003708 m_async_thread.Reset();
Jim Ingham455fa5c2012-11-01 01:15:33 +00003709 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003710 else if (log)
3711 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003712}
3713
Ewan Crawford76df2882015-06-23 12:32:06 +00003714bool
3715ProcessGDBRemote::HandleNotifyPacket (StringExtractorGDBRemote &packet)
3716{
3717 // get the packet at a string
3718 const std::string &pkt = packet.GetStringRef();
3719 // skip %stop:
3720 StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
3721
3722 // pass as a thread stop info packet
3723 SetLastStopPacket(stop_info);
3724
3725 // check for more stop reasons
3726 HandleStopReplySequence();
3727
3728 // if the process is stopped then we need to fake a resume
3729 // so that we can stop properly with the new break. This
3730 // is possible due to SetPrivateState() broadcasting the
3731 // state change as a side effect.
3732 if (GetPrivateState() == lldb::StateType::eStateStopped)
3733 {
3734 SetPrivateState(lldb::StateType::eStateRunning);
3735 }
3736
3737 // since we have some stopped packets we can halt the process
3738 SetPrivateState(lldb::StateType::eStateStopped);
3739
3740 return true;
3741}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003742
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003743thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003744ProcessGDBRemote::AsyncThread (void *arg)
3745{
3746 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
3747
Greg Clayton5160ce52013-03-27 23:08:40 +00003748 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003749 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003750 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003751
3752 Listener listener ("ProcessGDBRemote::AsyncThread");
3753 EventSP event_sp;
3754 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
3755 eBroadcastBitAsyncThreadShouldExit;
3756
3757 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
3758 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003759 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit |
3760 GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify);
3761
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003762 bool done = false;
3763 while (!done)
3764 {
3765 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003766 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003767 if (listener.WaitForEvent (NULL, event_sp))
3768 {
3769 const uint32_t event_type = event_sp->GetType();
Greg Clayton71337622011-02-24 22:24:29 +00003770 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003771 {
Greg Clayton71337622011-02-24 22:24:29 +00003772 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003773 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003774
Greg Clayton71337622011-02-24 22:24:29 +00003775 switch (event_type)
3776 {
3777 case eBroadcastBitAsyncContinue:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003778 {
Greg Clayton71337622011-02-24 22:24:29 +00003779 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003780
Greg Clayton71337622011-02-24 22:24:29 +00003781 if (continue_packet)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003782 {
Greg Clayton71337622011-02-24 22:24:29 +00003783 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
3784 const size_t continue_cstr_len = continue_packet->GetByteSize ();
3785 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003786 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003787
Greg Clayton71337622011-02-24 22:24:29 +00003788 if (::strstr (continue_cstr, "vAttach") == NULL)
3789 process->SetPrivateState(eStateRunning);
3790 StringExtractorGDBRemote response;
Ewan Crawford76df2882015-06-23 12:32:06 +00003791
3792 // If in Non-Stop-Mode
3793 if (process->GetTarget().GetNonStopModeEnabled())
Greg Clayton71337622011-02-24 22:24:29 +00003794 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003795 // send the vCont packet
3796 if (!process->GetGDBRemote().SendvContPacket(process, continue_cstr, continue_cstr_len, response))
Jason Molendaa3329782014-03-29 18:54:20 +00003797 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003798 // Something went wrong
3799 done = true;
3800 break;
3801 }
3802 }
3803 // If in All-Stop-Mode
3804 else
3805 {
3806 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
3807
3808 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
3809 // The thread ID list might be contained within the "response", or the stop reply packet that
3810 // caused the stop. So clear it now before we give the stop reply packet to the process
3811 // using the process->SetLastStopPacket()...
3812 process->ClearThreadIDList ();
3813
3814 switch (stop_state)
3815 {
3816 case eStateStopped:
3817 case eStateCrashed:
3818 case eStateSuspended:
3819 process->SetLastStopPacket (response);
3820 process->SetPrivateState (stop_state);
3821 break;
3822
3823 case eStateExited:
3824 {
3825 process->SetLastStopPacket (response);
3826 process->ClearThreadIDList();
3827 response.SetFilePos(1);
3828
3829 int exit_status = response.GetHexU8();
3830 const char *desc_cstr = NULL;
3831 StringExtractor extractor;
3832 std::string desc_string;
3833 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';')
Jason Molendaa3329782014-03-29 18:54:20 +00003834 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003835 std::string desc_token;
3836 while (response.GetNameColonValue (desc_token, desc_string))
Jason Molendaa3329782014-03-29 18:54:20 +00003837 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003838 if (desc_token == "description")
3839 {
3840 extractor.GetStringRef().swap(desc_string);
3841 extractor.SetFilePos(0);
3842 extractor.GetHexByteString (desc_string);
3843 desc_cstr = desc_string.c_str();
3844 }
Jason Molendaa3329782014-03-29 18:54:20 +00003845 }
3846 }
Ewan Crawford76df2882015-06-23 12:32:06 +00003847 process->SetExitStatus(exit_status, desc_cstr);
3848 done = true;
3849 break;
Jason Molendaa3329782014-03-29 18:54:20 +00003850 }
Ewan Crawford76df2882015-06-23 12:32:06 +00003851 case eStateInvalid:
Jason Molenda752e1e82015-07-29 01:42:16 +00003852 {
3853 // Check to see if we were trying to attach and if we got back
3854 // the "E87" error code from debugserver -- this indicates that
3855 // the process is not debuggable. Return a slightly more helpful
3856 // error message about why the attach failed.
3857 if (::strstr (continue_cstr, "vAttach") != NULL
3858 && response.GetError() == 0x87)
3859 {
3860 process->SetExitStatus(-1, "cannot attach to process due to System Integrity Protection");
3861 }
3862 // E01 code from vAttach means that the attach failed
3863 if (::strstr (continue_cstr, "vAttach") != NULL
3864 && response.GetError() == 0x1)
3865 {
3866 process->SetExitStatus(-1, "unable to attach");
3867 }
3868 else
3869 {
3870 process->SetExitStatus(-1, "lost connection");
3871 }
3872 break;
3873 }
Greg Clayton71337622011-02-24 22:24:29 +00003874
Ewan Crawford76df2882015-06-23 12:32:06 +00003875 default:
3876 process->SetPrivateState (stop_state);
3877 break;
3878 } // switch(stop_state)
3879 } // else // if in All-stop-mode
3880 } // if (continue_packet)
3881 } // case eBroadcastBitAysncContinue
Greg Clayton71337622011-02-24 22:24:29 +00003882 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003883
Greg Clayton71337622011-02-24 22:24:29 +00003884 case eBroadcastBitAsyncThreadShouldExit:
3885 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003886 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Clayton71337622011-02-24 22:24:29 +00003887 done = true;
3888 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003889
Greg Clayton71337622011-02-24 22:24:29 +00003890 default:
3891 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003892 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
Greg Clayton71337622011-02-24 22:24:29 +00003893 done = true;
3894 break;
3895 }
3896 }
3897 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
3898 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003899 switch (event_type)
Greg Clayton71337622011-02-24 22:24:29 +00003900 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003901 case Communication::eBroadcastBitReadThreadDidExit:
3902 process->SetExitStatus (-1, "lost connection");
3903 done = true;
3904 break;
3905
3906 case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify:
3907 {
3908 lldb_private::Event *event = event_sp.get();
3909 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event);
3910 StringExtractorGDBRemote notify((const char*)continue_packet->GetBytes());
3911 // Hand this over to the process to handle
3912 process->HandleNotifyPacket(notify);
3913 break;
3914 }
3915
3916 default:
3917 if (log)
3918 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
3919 done = true;
3920 break;
Greg Clayton71337622011-02-24 22:24:29 +00003921 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003922 }
3923 }
3924 else
3925 {
3926 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003927 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003928 done = true;
3929 }
3930 }
3931 }
3932
3933 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003934 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003935
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003936 return NULL;
3937}
3938
Greg Claytone996fd32011-03-08 22:40:15 +00003939//uint32_t
3940//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3941//{
3942// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
3943// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
3944// if (m_local_debugserver)
3945// {
3946// return Host::ListProcessesMatchingName (name, matches, pids);
3947// }
3948// else
3949// {
3950// // FIXME: Implement talking to the remote debugserver.
3951// return 0;
3952// }
3953//
3954//}
3955//
Jim Ingham1c823b42011-01-22 01:33:44 +00003956bool
3957ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003958 StoppointCallbackContext *context,
Jim Ingham1c823b42011-01-22 01:33:44 +00003959 lldb::user_id_t break_id,
3960 lldb::user_id_t break_loc_id)
3961{
3962 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3963 // run so I can stop it if that's what I want to do.
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003964 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00003965 if (log)
3966 log->Printf("Hit New Thread Notification breakpoint.");
3967 return false;
3968}
3969
3970
3971bool
3972ProcessGDBRemote::StartNoticingNewThreads()
3973{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003974 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00003975 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003976 {
Greg Clayton4116e932012-05-15 02:33:01 +00003977 if (log && log->GetVerbose())
3978 log->Printf("Enabled noticing new thread breakpoint.");
3979 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003980 }
Greg Clayton4116e932012-05-15 02:33:01 +00003981 else
Jim Ingham1c823b42011-01-22 01:33:44 +00003982 {
Greg Clayton4116e932012-05-15 02:33:01 +00003983 PlatformSP platform_sp (m_target.GetPlatform());
3984 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003985 {
Greg Clayton4116e932012-05-15 02:33:01 +00003986 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3987 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003988 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00003989 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00003990 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3991 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003992 }
3993 else
3994 {
3995 if (log)
3996 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00003997 }
3998 }
3999 }
Greg Clayton4116e932012-05-15 02:33:01 +00004000 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00004001}
4002
4003bool
4004ProcessGDBRemote::StopNoticingNewThreads()
4005{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004006 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00004007 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00004008 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00004009
4010 if (m_thread_create_bp_sp)
4011 m_thread_create_bp_sp->SetEnabled(false);
4012
Jim Ingham1c823b42011-01-22 01:33:44 +00004013 return true;
4014}
4015
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004016DynamicLoader *
Jason Molenda5e8534e2012-10-03 01:29:34 +00004017ProcessGDBRemote::GetDynamicLoader ()
4018{
4019 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00004020 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00004021 return m_dyld_ap.get();
4022}
Jim Ingham1c823b42011-01-22 01:33:44 +00004023
Jason Molendaa3329782014-03-29 18:54:20 +00004024Error
4025ProcessGDBRemote::SendEventData(const char *data)
4026{
4027 int return_value;
4028 bool was_supported;
4029
4030 Error error;
4031
4032 return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported);
4033 if (return_value != 0)
4034 {
4035 if (!was_supported)
4036 error.SetErrorString("Sending events is not supported for this process.");
4037 else
4038 error.SetErrorStringWithFormat("Error sending event data: %d.", return_value);
4039 }
4040 return error;
4041}
4042
Steve Pucci03904ac2014-03-04 23:18:46 +00004043const DataBufferSP
4044ProcessGDBRemote::GetAuxvData()
4045{
4046 DataBufferSP buf;
4047 if (m_gdb_comm.GetQXferAuxvReadSupported())
4048 {
4049 std::string response_string;
4050 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success)
4051 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length()));
4052 }
4053 return buf;
4054}
4055
Jason Molenda705b1802014-06-13 02:37:02 +00004056StructuredData::ObjectSP
4057ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid)
4058{
4059 StructuredData::ObjectSP object_sp;
4060
4061 if (m_gdb_comm.GetThreadExtendedInfoSupported())
4062 {
4063 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4064 SystemRuntime *runtime = GetSystemRuntime();
4065 if (runtime)
4066 {
4067 runtime->AddThreadExtendedInfoPacketHints (args_dict);
4068 }
4069 args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid);
4070
4071 StreamString packet;
4072 packet << "jThreadExtendedInfo:";
4073 args_dict->Dump (packet);
4074
4075 // FIXME the final character of a JSON dictionary, '}', is the escape
4076 // character in gdb-remote binary mode. lldb currently doesn't escape
4077 // these characters in its packet output -- so we add the quoted version
4078 // of the } character here manually in case we talk to a debugserver which
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004079 // un-escapes the characters at packet read time.
Jason Molenda705b1802014-06-13 02:37:02 +00004080 packet << (char) (0x7d ^ 0x20);
4081
4082 StringExtractorGDBRemote response;
4083 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4084 {
4085 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4086 if (response_type == StringExtractorGDBRemote::eResponse)
4087 {
4088 if (!response.Empty())
4089 {
Jason Molenda20ee21b2015-07-10 23:15:22 +00004090 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4091 }
4092 }
4093 }
4094 }
4095 return object_sp;
4096}
4097
4098StructuredData::ObjectSP
4099ProcessGDBRemote::GetLoadedDynamicLibrariesInfos (lldb::addr_t image_list_address, lldb::addr_t image_count)
4100{
4101 StructuredData::ObjectSP object_sp;
4102
4103 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported())
4104 {
4105 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4106 args_dict->GetAsDictionary()->AddIntegerItem ("image_list_address", image_list_address);
4107 args_dict->GetAsDictionary()->AddIntegerItem ("image_count", image_count);
4108
4109 StreamString packet;
4110 packet << "jGetLoadedDynamicLibrariesInfos:";
4111 args_dict->Dump (packet);
4112
4113 // FIXME the final character of a JSON dictionary, '}', is the escape
4114 // character in gdb-remote binary mode. lldb currently doesn't escape
4115 // these characters in its packet output -- so we add the quoted version
4116 // of the } character here manually in case we talk to a debugserver which
4117 // un-escapes the characters at packet read time.
4118 packet << (char) (0x7d ^ 0x20);
4119
4120 StringExtractorGDBRemote response;
4121 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4122 {
4123 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4124 if (response_type == StringExtractorGDBRemote::eResponse)
4125 {
4126 if (!response.Empty())
4127 {
Jason Molenda705b1802014-06-13 02:37:02 +00004128 // The packet has already had the 0x7d xor quoting stripped out at the
4129 // GDBRemoteCommunication packet receive level.
4130 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4131 }
4132 }
4133 }
4134 }
4135 return object_sp;
4136}
4137
Jason Molenda20ee21b2015-07-10 23:15:22 +00004138
Jason Molenda6076bf42014-05-06 04:34:52 +00004139// Establish the largest memory read/write payloads we should use.
4140// If the remote stub has a max packet size, stay under that size.
4141//
4142// If the remote stub's max packet size is crazy large, use a
4143// reasonable largeish default.
4144//
4145// If the remote stub doesn't advertise a max packet size, use a
4146// conservative default.
4147
4148void
4149ProcessGDBRemote::GetMaxMemorySize()
4150{
4151 const uint64_t reasonable_largeish_default = 128 * 1024;
4152 const uint64_t conservative_default = 512;
4153
4154 if (m_max_memory_size == 0)
4155 {
4156 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4157 if (stub_max_size != UINT64_MAX && stub_max_size != 0)
4158 {
4159 // Save the stub's claimed maximum packet size
4160 m_remote_stub_max_memory_size = stub_max_size;
4161
4162 // Even if the stub says it can support ginormous packets,
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004163 // don't exceed our reasonable largeish default packet size.
Jason Molenda6076bf42014-05-06 04:34:52 +00004164 if (stub_max_size > reasonable_largeish_default)
4165 {
4166 stub_max_size = reasonable_largeish_default;
4167 }
4168
4169 m_max_memory_size = stub_max_size;
4170 }
4171 else
4172 {
4173 m_max_memory_size = conservative_default;
4174 }
4175 }
4176}
4177
4178void
4179ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max)
4180{
4181 if (user_specified_max != 0)
4182 {
4183 GetMaxMemorySize ();
4184
4185 if (m_remote_stub_max_memory_size != 0)
4186 {
4187 if (m_remote_stub_max_memory_size < user_specified_max)
4188 {
4189 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a packet size too big, go as big
4190 // as the remote stub says we can go.
4191 }
4192 else
4193 {
4194 m_max_memory_size = user_specified_max; // user's packet size is good
4195 }
4196 }
4197 else
4198 {
4199 m_max_memory_size = user_specified_max; // user's packet size is probably fine
4200 }
4201 }
4202}
4203
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004204bool
4205ProcessGDBRemote::GetModuleSpec(const FileSpec& module_file_spec,
4206 const ArchSpec& arch,
4207 ModuleSpec &module_spec)
4208{
4209 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PLATFORM);
4210
4211 if (!m_gdb_comm.GetModuleInfo (module_file_spec, arch, module_spec))
4212 {
4213 if (log)
4214 log->Printf ("ProcessGDBRemote::%s - failed to get module info for %s:%s",
4215 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4216 arch.GetTriple ().getTriple ().c_str ());
4217 return false;
4218 }
4219
4220 if (log)
4221 {
4222 StreamString stream;
4223 module_spec.Dump (stream);
4224 log->Printf ("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4225 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4226 arch.GetTriple ().getTriple ().c_str (), stream.GetString ().c_str ());
4227 }
4228
4229 return true;
4230}
4231
Colin Rileyc3c95b22015-04-16 15:51:33 +00004232namespace {
4233
4234typedef std::vector<std::string> stringVec;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004235
4236typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004237struct RegisterSetInfo
4238{
4239 ConstString name;
4240};
Colin Rileyc3c95b22015-04-16 15:51:33 +00004241
Greg Claytond04f0ed2015-05-26 18:00:51 +00004242typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4243
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004244struct GdbServerTargetInfo
4245{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004246 std::string arch;
4247 std::string osabi;
4248 stringVec includes;
4249 RegisterSetMap reg_set_map;
4250 XMLNode feature_node;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004251};
Greg Claytond04f0ed2015-05-26 18:00:51 +00004252
Colin Rileyc3c95b22015-04-16 15:51:33 +00004253bool
Greg Claytond04f0ed2015-05-26 18:00:51 +00004254ParseRegisters (XMLNode feature_node, GdbServerTargetInfo &target_info, GDBRemoteDynamicRegisterInfo &dyn_reg_info)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004255{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004256 if (!feature_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004257 return false;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004258
4259 uint32_t prev_reg_num = 0;
4260 uint32_t reg_offset = 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004261
Greg Claytond04f0ed2015-05-26 18:00:51 +00004262 feature_node.ForEachChildElementWithName("reg", [&target_info, &dyn_reg_info, &prev_reg_num, &reg_offset](const XMLNode &reg_node) -> bool {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004263 std::string gdb_group;
4264 std::string gdb_type;
4265 ConstString reg_name;
4266 ConstString alt_name;
4267 ConstString set_name;
4268 std::vector<uint32_t> value_regs;
4269 std::vector<uint32_t> invalidate_regs;
4270 bool encoding_set = false;
4271 bool format_set = false;
4272 RegisterInfo reg_info = { NULL, // Name
4273 NULL, // Alt name
4274 0, // byte size
4275 reg_offset, // offset
4276 eEncodingUint, // encoding
4277 eFormatHex, // formate
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004278 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004279 LLDB_INVALID_REGNUM, // GCC reg num
4280 LLDB_INVALID_REGNUM, // DWARF reg num
4281 LLDB_INVALID_REGNUM, // generic reg num
4282 prev_reg_num, // GDB reg num
4283 prev_reg_num // native register number
4284 },
4285 NULL,
4286 NULL
4287 };
4288
Ewan Crawford682e8422015-06-26 09:38:27 +00004289 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, &prev_reg_num, &reg_offset](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004290 if (name == "name")
4291 {
4292 reg_name.SetString(value);
4293 }
4294 else if (name == "bitsize")
4295 {
4296 reg_info.byte_size = StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
4297 }
4298 else if (name == "type")
4299 {
4300 gdb_type = value.str();
4301 }
4302 else if (name == "group")
4303 {
4304 gdb_group = value.str();
4305 }
4306 else if (name == "regnum")
4307 {
4308 const uint32_t regnum = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4309 if (regnum != LLDB_INVALID_REGNUM)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004310 {
Jason Molendaa18f7072015-08-15 01:21:01 +00004311 reg_info.kinds[eRegisterKindStabs] = regnum;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004312 reg_info.kinds[eRegisterKindLLDB] = regnum;
4313 prev_reg_num = regnum;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004314 }
4315 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004316 else if (name == "offset")
4317 {
4318 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4319 }
4320 else if (name == "altname")
4321 {
4322 alt_name.SetString(value);
4323 }
4324 else if (name == "encoding")
4325 {
4326 encoding_set = true;
4327 reg_info.encoding = Args::StringToEncoding (value.data(), eEncodingUint);
4328 }
4329 else if (name == "format")
4330 {
4331 format_set = true;
4332 Format format = eFormatInvalid;
4333 if (Args::StringToFormat (value.data(), format, NULL).Success())
4334 reg_info.format = format;
4335 else if (value == "vector-sint8")
4336 reg_info.format = eFormatVectorOfSInt8;
4337 else if (value == "vector-uint8")
4338 reg_info.format = eFormatVectorOfUInt8;
4339 else if (value == "vector-sint16")
4340 reg_info.format = eFormatVectorOfSInt16;
4341 else if (value == "vector-uint16")
4342 reg_info.format = eFormatVectorOfUInt16;
4343 else if (value == "vector-sint32")
4344 reg_info.format = eFormatVectorOfSInt32;
4345 else if (value == "vector-uint32")
4346 reg_info.format = eFormatVectorOfUInt32;
4347 else if (value == "vector-float32")
4348 reg_info.format = eFormatVectorOfFloat32;
4349 else if (value == "vector-uint128")
4350 reg_info.format = eFormatVectorOfUInt128;
4351 }
4352 else if (name == "group_id")
4353 {
4354 const uint32_t set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4355 RegisterSetMap::const_iterator pos = target_info.reg_set_map.find(set_id);
4356 if (pos != target_info.reg_set_map.end())
4357 set_name = pos->second.name;
4358 }
Jason Molendaa18f7072015-08-15 01:21:01 +00004359 else if (name == "gcc_regnum" || name == "ehframe_regnum")
Greg Claytond04f0ed2015-05-26 18:00:51 +00004360 {
Jason Molendaa18f7072015-08-15 01:21:01 +00004361 reg_info.kinds[eRegisterKindEHFrame] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004362 }
4363 else if (name == "dwarf_regnum")
4364 {
4365 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4366 }
4367 else if (name == "generic")
4368 {
4369 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister(value.data());
4370 }
4371 else if (name == "value_regnums")
4372 {
4373 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
4374 }
4375 else if (name == "invalidate_regnums")
4376 {
4377 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
4378 }
4379 else
4380 {
4381 printf("unhandled attribute %s = %s\n", name.data(), value.data());
4382 }
4383 return true; // Keep iterating through all attributes
4384 });
4385
4386 if (!gdb_type.empty() && !(encoding_set || format_set))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004387 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004388 if (gdb_type.find("int") == 0)
4389 {
4390 reg_info.format = eFormatHex;
4391 reg_info.encoding = eEncodingUint;
4392 }
4393 else if (gdb_type == "data_ptr" || gdb_type == "code_ptr")
4394 {
4395 reg_info.format = eFormatAddressInfo;
4396 reg_info.encoding = eEncodingUint;
4397 }
4398 else if (gdb_type == "i387_ext" || gdb_type == "float")
4399 {
4400 reg_info.format = eFormatFloat;
4401 reg_info.encoding = eEncodingIEEE754;
4402 }
Colin Rileyc3c95b22015-04-16 15:51:33 +00004403 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004404
4405 // Only update the register set name if we didn't get a "reg_set" attribute.
4406 // "set_name" will be empty if we didn't have a "reg_set" attribute.
4407 if (!set_name && !gdb_group.empty())
4408 set_name.SetCString(gdb_group.c_str());
4409
4410 reg_info.byte_offset = reg_offset;
4411 assert (reg_info.byte_size != 0);
4412 reg_offset += reg_info.byte_size;
4413 if (!value_regs.empty())
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004414 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004415 value_regs.push_back(LLDB_INVALID_REGNUM);
4416 reg_info.value_regs = value_regs.data();
Colin Rileyc3c95b22015-04-16 15:51:33 +00004417 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004418 if (!invalidate_regs.empty())
4419 {
4420 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
4421 reg_info.invalidate_regs = invalidate_regs.data();
4422 }
4423
Ewan Crawford682e8422015-06-26 09:38:27 +00004424 ++prev_reg_num;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004425 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
4426
4427 return true; // Keep iterating through all "reg" elements
4428 });
Colin Rileyc3c95b22015-04-16 15:51:33 +00004429 return true;
4430}
Greg Claytond04f0ed2015-05-26 18:00:51 +00004431
Colin Rileyc3c95b22015-04-16 15:51:33 +00004432} // namespace {}
4433
Colin Rileyc3c95b22015-04-16 15:51:33 +00004434
4435// query the target of gdb-remote for extended target information
4436// return: 'true' on success
4437// 'false' on failure
4438bool
Aidan Doddsc0c83852015-05-08 09:36:31 +00004439ProcessGDBRemote::GetGDBServerRegisterInfo ()
Colin Rileyc3c95b22015-04-16 15:51:33 +00004440{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004441 // Make sure LLDB has an XML parser it can use first
4442 if (!XMLDocument::XMLEnabled())
4443 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004444
4445 // redirect libxml2's error handler since the default prints to stdout
Colin Rileyc3c95b22015-04-16 15:51:33 +00004446
4447 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004448
4449 // check that we have extended feature read support
4450 if ( !comm.GetQXferFeaturesReadSupported( ) )
4451 return false;
4452
4453 // request the target xml file
4454 std::string raw;
4455 lldb_private::Error lldberr;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004456 if (!comm.ReadExtFeature(ConstString("features"),
4457 ConstString("target.xml"),
4458 raw,
4459 lldberr))
4460 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00004461 return false;
4462 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004463
Colin Rileyc3c95b22015-04-16 15:51:33 +00004464
Greg Claytond04f0ed2015-05-26 18:00:51 +00004465 XMLDocument xml_document;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004466
Greg Claytond04f0ed2015-05-26 18:00:51 +00004467 if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml"))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004468 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004469 GdbServerTargetInfo target_info;
4470
4471 XMLNode target_node = xml_document.GetRootElement("target");
4472 if (target_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004473 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004474 XMLNode feature_node;
4475 target_node.ForEachChildElement([&target_info, this, &feature_node](const XMLNode &node) -> bool
4476 {
4477 llvm::StringRef name = node.GetName();
4478 if (name == "architecture")
4479 {
4480 node.GetElementText(target_info.arch);
4481 }
4482 else if (name == "osabi")
4483 {
4484 node.GetElementText(target_info.osabi);
4485 }
Ewan Crawford682e8422015-06-26 09:38:27 +00004486 else if (name == "xi:include" || name == "include")
Greg Claytond04f0ed2015-05-26 18:00:51 +00004487 {
4488 llvm::StringRef href = node.GetAttributeValue("href");
4489 if (!href.empty())
4490 target_info.includes.push_back(href.str());
4491 }
4492 else if (name == "feature")
4493 {
4494 feature_node = node;
4495 }
4496 else if (name == "groups")
4497 {
4498 node.ForEachChildElementWithName("group", [&target_info](const XMLNode &node) -> bool {
4499 uint32_t set_id = UINT32_MAX;
4500 RegisterSetInfo set_info;
4501
4502 node.ForEachAttribute([&set_id, &set_info](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
4503 if (name == "id")
4504 set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4505 if (name == "name")
4506 set_info.name = ConstString(value);
4507 return true; // Keep iterating through all attributes
4508 });
4509
4510 if (set_id != UINT32_MAX)
4511 target_info.reg_set_map[set_id] = set_info;
4512 return true; // Keep iterating through all "group" elements
4513 });
4514 }
4515 return true; // Keep iterating through all children of the target_node
4516 });
4517
4518 if (feature_node)
4519 {
4520 ParseRegisters(feature_node, target_info, this->m_register_info);
4521 }
4522
4523 for (const auto &include : target_info.includes)
4524 {
4525 // request register file
4526 std::string xml_data;
4527 if (!comm.ReadExtFeature(ConstString("features"),
4528 ConstString(include),
4529 xml_data,
4530 lldberr))
4531 continue;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004532
Greg Claytond04f0ed2015-05-26 18:00:51 +00004533 XMLDocument include_xml_document;
4534 include_xml_document.ParseMemory(xml_data.data(), xml_data.size(), include.c_str());
4535 XMLNode include_feature_node = include_xml_document.GetRootElement("feature");
4536 if (include_feature_node)
4537 {
4538 ParseRegisters(include_feature_node, target_info, this->m_register_info);
4539 }
4540 }
4541 this->m_register_info.Finalize(GetTarget().GetArchitecture());
Colin Rileyc3c95b22015-04-16 15:51:33 +00004542 }
4543 }
4544
Greg Claytond04f0ed2015-05-26 18:00:51 +00004545 return m_register_info.GetNumRegisters() > 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004546}
4547
Aidan Doddsc0c83852015-05-08 09:36:31 +00004548Error
4549ProcessGDBRemote::GetLoadedModuleList (GDBLoadedModuleInfoList & list)
4550{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004551 // Make sure LLDB has an XML parser it can use first
4552 if (!XMLDocument::XMLEnabled())
4553 return Error (0, ErrorType::eErrorTypeGeneric);
4554
Aidan Doddsc0c83852015-05-08 09:36:31 +00004555 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS);
4556 if (log)
4557 log->Printf ("ProcessGDBRemote::%s", __FUNCTION__);
4558
Aidan Doddsc0c83852015-05-08 09:36:31 +00004559 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004560
4561 // check that we have extended feature read support
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004562 if (comm.GetQXferLibrariesSVR4ReadSupported ()) {
4563 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004564
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004565 // request the loaded library list
4566 std::string raw;
4567 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004568
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004569 if (!comm.ReadExtFeature (ConstString ("libraries-svr4"), ConstString (""), raw, lldberr))
4570 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004571
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004572 // parse the xml file in memory
4573 if (log)
4574 log->Printf ("parsing: %s", raw.c_str());
4575 XMLDocument doc;
4576
4577 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4578 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004579
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004580 XMLNode root_element = doc.GetRootElement("library-list-svr4");
4581 if (!root_element)
4582 return Error();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004583
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004584 // main link map structure
4585 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4586 if (!main_lm.empty())
4587 {
4588 list.m_link_map = StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
4589 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004590
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004591 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
Aidan Doddsc0c83852015-05-08 09:36:31 +00004592
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004593 GDBLoadedModuleInfoList::LoadedModuleInfo module;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004594
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004595 library.ForEachAttribute([log, &module](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004596
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004597 if (name == "name")
4598 module.set_name (value.str());
4599 else if (name == "lm")
4600 {
4601 // the address of the link_map struct.
4602 module.set_link_map(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4603 }
4604 else if (name == "l_addr")
4605 {
4606 // the displacement as read from the field 'l_addr' of the link_map struct.
4607 module.set_base(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
Stephane Sezerc6845a02015-08-20 22:07:48 +00004608 // base address is always a displacement, not an absolute value.
4609 module.set_base_is_offset(true);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004610 }
4611 else if (name == "l_ld")
4612 {
4613 // the memory address of the libraries PT_DYAMIC section.
4614 module.set_dynamic(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4615 }
4616
4617 return true; // Keep iterating over all properties of "library"
4618 });
4619
4620 if (log)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004621 {
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004622 std::string name;
4623 lldb::addr_t lm=0, base=0, ld=0;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004624 bool base_is_offset;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004625
4626 module.get_name (name);
4627 module.get_link_map (lm);
4628 module.get_base (base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004629 module.get_base_is_offset (base_is_offset);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004630 module.get_dynamic (ld);
4631
Stephane Sezerc6845a02015-08-20 22:07:48 +00004632 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 +00004633 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004634
4635 list.add (module);
4636 return true; // Keep iterating over all "library" elements in the root node
Greg Claytond04f0ed2015-05-26 18:00:51 +00004637 });
Aidan Doddsc0c83852015-05-08 09:36:31 +00004638
4639 if (log)
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004640 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4641 } else if (comm.GetQXferLibrariesReadSupported ()) {
4642 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004643
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004644 // request the loaded library list
4645 std::string raw;
4646 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004647
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004648 if (!comm.ReadExtFeature (ConstString ("libraries"), ConstString (""), raw, lldberr))
4649 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004650
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004651 if (log)
4652 log->Printf ("parsing: %s", raw.c_str());
4653 XMLDocument doc;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004654
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004655 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4656 return Error (0, ErrorType::eErrorTypeGeneric);
4657
4658 XMLNode root_element = doc.GetRootElement("library-list");
4659 if (!root_element)
4660 return Error();
4661
4662 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
4663 GDBLoadedModuleInfoList::LoadedModuleInfo module;
4664
4665 llvm::StringRef name = library.GetAttributeValue("name");
4666 module.set_name(name.str());
4667
4668 // The base address of a given library will be the address of its
4669 // first section. Most remotes send only one section for Windows
4670 // targets for example.
4671 const XMLNode &section = library.FindFirstChildElementWithName("section");
4672 llvm::StringRef address = section.GetAttributeValue("address");
4673 module.set_base(StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0));
Stephane Sezerc6845a02015-08-20 22:07:48 +00004674 // These addresses are absolute values.
4675 module.set_base_is_offset(false);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004676
4677 if (log)
4678 {
4679 std::string name;
4680 lldb::addr_t base = 0;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004681 bool base_is_offset;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004682 module.get_name (name);
4683 module.get_base (base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004684 module.get_base_is_offset (base_is_offset);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004685
Stephane Sezerc6845a02015-08-20 22:07:48 +00004686 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 +00004687 }
4688
4689 list.add (module);
4690 return true; // Keep iterating over all "library" elements in the root node
4691 });
4692
4693 if (log)
4694 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4695 } else {
4696 return Error (0, ErrorType::eErrorTypeGeneric);
4697 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004698
4699 return Error();
4700}
4701
Aidan Doddsc0c83852015-05-08 09:36:31 +00004702lldb::ModuleSP
Stephane Sezerc6845a02015-08-20 22:07:48 +00004703ProcessGDBRemote::LoadModuleAtAddress (const FileSpec &file, lldb::addr_t base_addr, bool value_is_offset)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004704{
4705 Target &target = m_process->GetTarget();
4706 ModuleList &modules = target.GetImages();
4707 ModuleSP module_sp;
4708
4709 bool changed = false;
4710
4711 ModuleSpec module_spec (file, target.GetArchitecture());
4712 if ((module_sp = modules.FindFirstModule (module_spec)))
4713 {
Stephane Sezerc6845a02015-08-20 22:07:48 +00004714 module_sp->SetLoadAddress (target, base_addr, value_is_offset, changed);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004715 }
4716 else if ((module_sp = target.GetSharedModule (module_spec)))
4717 {
Stephane Sezerc6845a02015-08-20 22:07:48 +00004718 module_sp->SetLoadAddress (target, base_addr, value_is_offset, changed);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004719 }
4720
4721 return module_sp;
4722}
4723
4724size_t
4725ProcessGDBRemote::LoadModules ()
4726{
4727 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4728
4729 // request a list of loaded libraries from GDBServer
4730 GDBLoadedModuleInfoList module_list;
4731 if (GetLoadedModuleList (module_list).Fail())
4732 return 0;
4733
4734 // get a list of all the modules
4735 ModuleList new_modules;
4736
4737 for (GDBLoadedModuleInfoList::LoadedModuleInfo & modInfo : module_list.m_list)
4738 {
4739 std::string mod_name;
4740 lldb::addr_t mod_base;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004741 bool mod_base_is_offset;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004742
4743 bool valid = true;
4744 valid &= modInfo.get_name (mod_name);
4745 valid &= modInfo.get_base (mod_base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004746 valid &= modInfo.get_base_is_offset (mod_base_is_offset);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004747 if (!valid)
4748 continue;
4749
4750 // hack (cleaner way to get file name only?) (win/unix compat?)
Vince Harron4cc8d202015-05-10 08:33:58 +00004751 size_t marker = mod_name.rfind ('/');
Aidan Doddsc0c83852015-05-08 09:36:31 +00004752 if (marker == std::string::npos)
4753 marker = 0;
4754 else
4755 marker += 1;
4756
4757 FileSpec file (mod_name.c_str()+marker, true);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004758 lldb::ModuleSP module_sp = LoadModuleAtAddress (file, mod_base, mod_base_is_offset);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004759
4760 if (module_sp.get())
4761 new_modules.Append (module_sp);
4762 }
4763
4764 if (new_modules.GetSize() > 0)
4765 {
4766 Target & target = m_target;
4767
4768 new_modules.ForEach ([&target](const lldb::ModuleSP module_sp) -> bool
4769 {
4770 lldb_private::ObjectFile * obj = module_sp->GetObjectFile ();
4771 if (!obj)
4772 return true;
4773
4774 if (obj->GetType () != ObjectFile::Type::eTypeExecutable)
4775 return true;
4776
4777 lldb::ModuleSP module_copy_sp = module_sp;
4778 target.SetExecutableModule (module_copy_sp, false);
4779 return false;
4780 });
4781
4782 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4783 loaded_modules.AppendIfNeeded (new_modules);
4784 m_process->GetTarget().ModulesDidLoad (new_modules);
4785 }
4786
4787 return new_modules.GetSize();
4788}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004789
Tamas Berghammer783bfc82015-06-18 20:43:56 +00004790Error
4791ProcessGDBRemote::GetFileLoadAddress(const FileSpec& file, bool& is_loaded, lldb::addr_t& load_addr)
4792{
4793 is_loaded = false;
4794 load_addr = LLDB_INVALID_ADDRESS;
4795
4796 std::string file_path = file.GetPath(false);
4797 if (file_path.empty ())
4798 return Error("Empty file name specified");
4799
4800 StreamString packet;
4801 packet.PutCString("qFileLoadAddress:");
4802 packet.PutCStringAsRawHex8(file_path.c_str());
4803
4804 StringExtractorGDBRemote response;
4805 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString().c_str(), response, false) != GDBRemoteCommunication::PacketResult::Success)
4806 return Error("Sending qFileLoadAddress packet failed");
4807
4808 if (response.IsErrorResponse())
4809 {
4810 if (response.GetError() == 1)
4811 {
4812 // The file is not loaded into the inferior
4813 is_loaded = false;
4814 load_addr = LLDB_INVALID_ADDRESS;
4815 return Error();
4816 }
4817
4818 return Error("Fetching file load address from remote server returned an error");
4819 }
4820
4821 if (response.IsNormalResponse())
4822 {
4823 is_loaded = true;
4824 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
4825 return Error();
4826 }
4827
4828 return Error("Unknown error happened during sending the load address packet");
4829}
4830
Greg Clayton0b90be12015-06-23 21:27:50 +00004831
4832void
4833ProcessGDBRemote::ModulesDidLoad (ModuleList &module_list)
4834{
4835 // We must call the lldb_private::Process::ModulesDidLoad () first before we do anything
4836 Process::ModulesDidLoad (module_list);
4837
4838 // After loading shared libraries, we can ask our remote GDB server if
4839 // it needs any symbols.
4840 m_gdb_comm.ServeSymbolLookups(this);
4841}
4842
4843
Greg Claytone034a042015-05-21 20:52:06 +00004844class CommandObjectProcessGDBRemoteSpeedTest: public CommandObjectParsed
4845{
4846public:
4847 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter) :
4848 CommandObjectParsed (interpreter,
4849 "process plugin packet speed-test",
4850 "Tests packet speeds of various sizes to determine the performance characteristics of the GDB remote connection. ",
4851 NULL),
4852 m_option_group (interpreter),
4853 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),
4854 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),
4855 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),
4856 m_json (LLDB_OPT_SET_1, false, "json", 'j', "Print the output as JSON data for easy parsing.", false, true)
4857 {
4858 m_option_group.Append (&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4859 m_option_group.Append (&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4860 m_option_group.Append (&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4861 m_option_group.Append (&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4862 m_option_group.Finalize();
4863 }
4864
4865 ~CommandObjectProcessGDBRemoteSpeedTest ()
4866 {
4867 }
4868
4869
4870 Options *
4871 GetOptions () override
4872 {
4873 return &m_option_group;
4874 }
4875
4876 bool
4877 DoExecute (Args& command, CommandReturnObject &result) override
4878 {
4879 const size_t argc = command.GetArgumentCount();
4880 if (argc == 0)
4881 {
4882 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4883 if (process)
4884 {
4885 StreamSP output_stream_sp (m_interpreter.GetDebugger().GetAsyncOutputStream());
4886 result.SetImmediateOutputStream (output_stream_sp);
4887
4888 const uint32_t num_packets = (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
4889 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
4890 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
4891 const bool json = m_json.GetOptionValue().GetCurrentValue();
4892 if (output_stream_sp)
4893 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, *output_stream_sp);
4894 else
4895 {
4896 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, result.GetOutputStream());
4897 }
4898 result.SetStatus (eReturnStatusSuccessFinishResult);
4899 return true;
4900 }
4901 }
4902 else
4903 {
4904 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
4905 }
4906 result.SetStatus (eReturnStatusFailed);
4907 return false;
4908 }
4909protected:
4910 OptionGroupOptions m_option_group;
4911 OptionGroupUInt64 m_num_packets;
4912 OptionGroupUInt64 m_max_send;
4913 OptionGroupUInt64 m_max_recv;
4914 OptionGroupBoolean m_json;
4915
4916};
4917
Greg Clayton02686b82012-10-15 22:42:16 +00004918class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00004919{
4920private:
4921
4922public:
Greg Clayton02686b82012-10-15 22:42:16 +00004923 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00004924 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00004925 "process plugin packet history",
4926 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00004927 NULL)
4928 {
4929 }
4930
Greg Clayton02686b82012-10-15 22:42:16 +00004931 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton998255b2012-10-13 02:07:45 +00004932 {
4933 }
4934
4935 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004936 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton998255b2012-10-13 02:07:45 +00004937 {
Greg Clayton02686b82012-10-15 22:42:16 +00004938 const size_t argc = command.GetArgumentCount();
4939 if (argc == 0)
4940 {
4941 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4942 if (process)
4943 {
4944 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
4945 result.SetStatus (eReturnStatusSuccessFinishResult);
4946 return true;
4947 }
4948 }
4949 else
4950 {
4951 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
4952 }
4953 result.SetStatus (eReturnStatusFailed);
4954 return false;
4955 }
4956};
4957
Jason Molenda6076bf42014-05-06 04:34:52 +00004958class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed
4959{
4960private:
4961
4962public:
4963 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) :
4964 CommandObjectParsed (interpreter,
4965 "process plugin packet xfer-size",
4966 "Maximum size that lldb will try to read/write one one chunk.",
4967 NULL)
4968 {
4969 }
4970
4971 ~CommandObjectProcessGDBRemotePacketXferSize ()
4972 {
4973 }
4974
4975 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004976 DoExecute (Args& command, CommandReturnObject &result) override
Jason Molenda6076bf42014-05-06 04:34:52 +00004977 {
4978 const size_t argc = command.GetArgumentCount();
4979 if (argc == 0)
4980 {
4981 result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str());
4982 result.SetStatus (eReturnStatusFailed);
4983 return false;
4984 }
4985
4986 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4987 if (process)
4988 {
4989 const char *packet_size = command.GetArgumentAtIndex(0);
4990 errno = 0;
4991 uint64_t user_specified_max = strtoul (packet_size, NULL, 10);
4992 if (errno == 0 && user_specified_max != 0)
4993 {
4994 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max);
4995 result.SetStatus (eReturnStatusSuccessFinishResult);
4996 return true;
4997 }
4998 }
4999 result.SetStatus (eReturnStatusFailed);
5000 return false;
5001 }
5002};
5003
5004
Greg Clayton02686b82012-10-15 22:42:16 +00005005class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
5006{
5007private:
5008
5009public:
5010 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
5011 CommandObjectParsed (interpreter,
5012 "process plugin packet send",
5013 "Send a custom packet through the GDB remote protocol and print the answer. "
5014 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
5015 NULL)
5016 {
5017 }
5018
5019 ~CommandObjectProcessGDBRemotePacketSend ()
5020 {
5021 }
5022
5023 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005024 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton02686b82012-10-15 22:42:16 +00005025 {
5026 const size_t argc = command.GetArgumentCount();
5027 if (argc == 0)
5028 {
5029 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
5030 result.SetStatus (eReturnStatusFailed);
5031 return false;
5032 }
5033
5034 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5035 if (process)
5036 {
Han Ming Ong84145852012-11-26 20:42:03 +00005037 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00005038 {
Han Ming Ong84145852012-11-26 20:42:03 +00005039 const char *packet_cstr = command.GetArgumentAtIndex(0);
5040 bool send_async = true;
5041 StringExtractorGDBRemote response;
5042 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
5043 result.SetStatus (eReturnStatusSuccessFinishResult);
5044 Stream &output_strm = result.GetOutputStream();
5045 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00005046 std::string &response_str = response.GetStringRef();
5047
Han Ming Ong399289e2013-06-21 19:56:59 +00005048 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00005049 {
5050 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
5051 }
5052
Han Ming Ong84145852012-11-26 20:42:03 +00005053 if (response_str.empty())
5054 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
5055 else
5056 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00005057 }
Greg Clayton02686b82012-10-15 22:42:16 +00005058 }
Greg Clayton998255b2012-10-13 02:07:45 +00005059 return true;
5060 }
5061};
5062
Greg Claytonba4a0a52013-02-01 23:03:47 +00005063class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
5064{
5065private:
5066
5067public:
5068 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
5069 CommandObjectRaw (interpreter,
5070 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00005071 "Send a qRcmd packet through the GDB remote protocol and print the response."
5072 "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 +00005073 NULL)
5074 {
5075 }
5076
5077 ~CommandObjectProcessGDBRemotePacketMonitor ()
5078 {
5079 }
5080
5081 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005082 DoExecute (const char *command, CommandReturnObject &result) override
Greg Claytonba4a0a52013-02-01 23:03:47 +00005083 {
5084 if (command == NULL || command[0] == '\0')
5085 {
5086 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
5087 result.SetStatus (eReturnStatusFailed);
5088 return false;
5089 }
5090
5091 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5092 if (process)
5093 {
5094 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00005095 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00005096 packet.PutBytesAsRawHex8(command, strlen(command));
5097 const char *packet_cstr = packet.GetString().c_str();
5098
5099 bool send_async = true;
5100 StringExtractorGDBRemote response;
5101 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
5102 result.SetStatus (eReturnStatusSuccessFinishResult);
5103 Stream &output_strm = result.GetOutputStream();
5104 output_strm.Printf (" packet: %s\n", packet_cstr);
5105 const std::string &response_str = response.GetStringRef();
5106
5107 if (response_str.empty())
5108 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
5109 else
5110 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
5111 }
5112 return true;
5113 }
5114};
5115
Greg Clayton02686b82012-10-15 22:42:16 +00005116class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
5117{
5118private:
5119
5120public:
5121 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
5122 CommandObjectMultiword (interpreter,
5123 "process plugin packet",
5124 "Commands that deal with GDB remote packets.",
5125 NULL)
5126 {
5127 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
5128 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00005129 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Jason Molenda6076bf42014-05-06 04:34:52 +00005130 LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter)));
Greg Claytone034a042015-05-21 20:52:06 +00005131 LoadSubCommand ("speed-test", CommandObjectSP (new CommandObjectProcessGDBRemoteSpeedTest (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00005132 }
5133
5134 ~CommandObjectProcessGDBRemotePacket ()
5135 {
5136 }
5137};
Greg Clayton998255b2012-10-13 02:07:45 +00005138
5139class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
5140{
5141public:
5142 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
5143 CommandObjectMultiword (interpreter,
5144 "process plugin",
5145 "A set of commands for operating on a ProcessGDBRemote process.",
5146 "process plugin <subcommand> [<subcommand-options>]")
5147 {
5148 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
5149 }
5150
5151 ~CommandObjectMultiwordProcessGDBRemote ()
5152 {
5153 }
5154};
5155
Greg Clayton998255b2012-10-13 02:07:45 +00005156CommandObject *
5157ProcessGDBRemote::GetPluginCommandObject()
5158{
5159 if (!m_command_sp)
5160 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
5161 return m_command_sp.get();
5162}