blob: aac3df162c128bbf2506971a009e2c93f2775144 [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
Jason Molendabf67a302015-09-01 05:17:01 +0000588 eFormatHex, // format
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000589 {
Jason Molendabf67a302015-09-01 05:17:01 +0000590 LLDB_INVALID_REGNUM, // eh_frame reg num
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000591 LLDB_INVALID_REGNUM, // DWARF reg num
592 LLDB_INVALID_REGNUM, // generic reg num
Jason Molendabf67a302015-09-01 05:17:01 +0000593 reg_num, // stabs reg num
Jason Molendafbcb7f22010-09-10 07:49:16 +0000594 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()
Jason Molenda6d9fe8c2015-08-21 00:13:37 +0000738 && (remote_arch.GetMachine() == llvm::Triple::arm || remote_arch.GetMachine() == llvm::Triple::thumb)
Johnny Chen2fa9de12012-05-14 18:44:23 +0000739 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
740 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000741 }
Jason Molenda6d9fe8c2015-08-21 00:13:37 +0000742 else if (target_arch.GetMachine() == llvm::Triple::arm
743 || target_arch.GetMachine() == llvm::Triple::thumb)
Johnny Chen2fa9de12012-05-14 18:44:23 +0000744 {
745 m_register_info.HardcodeARMRegisters(from_scratch);
746 }
747
748 // At this point, we can finalize our register info.
Greg Claytond04f0ed2015-05-26 18:00:51 +0000749 m_register_info.Finalize (GetTarget().GetArchitecture());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000750}
751
752Error
753ProcessGDBRemote::WillLaunch (Module* module)
754{
755 return WillLaunchOrAttach ();
756}
757
758Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000759ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000760{
761 return WillLaunchOrAttach ();
762}
763
764Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000765ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000766{
767 return WillLaunchOrAttach ();
768}
769
770Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000771ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +0000772{
Todd Fialaaf245d12014-06-30 21:05:18 +0000773 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Claytonb766a732011-02-04 01:58:07 +0000774 Error error (WillLaunchOrAttach ());
775
776 if (error.Fail())
777 return error;
778
Greg Clayton2289fa42011-04-30 01:09:13 +0000779 error = ConnectToDebugserver (remote_url);
Greg Claytonb766a732011-02-04 01:58:07 +0000780
781 if (error.Fail())
782 return error;
783 StartAsyncThread ();
784
Greg Claytonc574ede2011-03-10 02:26:48 +0000785 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonb766a732011-02-04 01:58:07 +0000786 if (pid == LLDB_INVALID_PROCESS_ID)
787 {
788 // We don't have a valid process ID, so note that we are connected
789 // and could now request to launch or attach, or get remote process
790 // listings...
791 SetPrivateState (eStateConnected);
792 }
793 else
794 {
795 // We have a valid process
796 SetID (pid);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000797 GetThreadList();
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000798 StringExtractorGDBRemote response;
799 if (m_gdb_comm.GetStopReply(response))
Greg Claytonb766a732011-02-04 01:58:07 +0000800 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000801 SetLastStopPacket(response);
Ewan Crawford78baa192015-05-13 09:18:18 +0000802
803 // '?' Packets must be handled differently in non-stop mode
804 if (GetTarget().GetNonStopModeEnabled())
805 HandleStopReplySequence();
806
Jason Molendac62bd7b2013-12-21 05:20:36 +0000807 if (!m_target.GetArchitecture().IsValid())
808 {
809 if (m_gdb_comm.GetProcessArchitecture().IsValid())
810 {
811 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
812 }
813 else
814 {
815 m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
816 }
Carlo Kok74389122013-10-14 07:09:13 +0000817 }
818
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000819 const StateType state = SetThreadStopInfo (response);
Greg Clayton2e309072015-07-17 23:42:28 +0000820 if (state != eStateInvalid)
Greg Claytonb766a732011-02-04 01:58:07 +0000821 {
822 SetPrivateState (state);
823 }
824 else
Daniel Malead01b2952012-11-29 21:49:15 +0000825 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 +0000826 }
827 else
Daniel Malead01b2952012-11-29 21:49:15 +0000828 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 +0000829 }
Jason Molenda16d127c2012-05-03 22:37:30 +0000830
Todd Fialaaf245d12014-06-30 21:05:18 +0000831 if (log)
832 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");
833
834
835 if (error.Success()
Jason Molenda16d127c2012-05-03 22:37:30 +0000836 && !GetTarget().GetArchitecture().IsValid()
837 && m_gdb_comm.GetHostArchitecture().IsValid())
838 {
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000839 // Prefer the *process'* architecture over that of the *host*, if available.
840 if (m_gdb_comm.GetProcessArchitecture().IsValid())
841 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
842 else
843 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molenda16d127c2012-05-03 22:37:30 +0000844 }
845
Todd Fialaaf245d12014-06-30 21:05:18 +0000846 if (log)
847 log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": normalized target architecture triple: %s", __FUNCTION__, GetID (), GetTarget ().GetArchitecture ().GetTriple ().getTriple ().c_str ());
848
Chaoren Lin98d0a4b2015-07-14 01:09:28 +0000849 if (error.Success())
Jaydeep Patil6fc590d2015-07-30 05:06:51 +0000850 {
851 PlatformSP platform_sp = GetTarget().GetPlatform();
852 if (platform_sp && platform_sp->IsConnected())
853 SetUnixSignals(platform_sp->GetUnixSignals());
854 else
855 SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
856 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000857
Greg Claytonb766a732011-02-04 01:58:07 +0000858 return error;
859}
860
861Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000862ProcessGDBRemote::WillLaunchOrAttach ()
863{
864 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000865 m_stdio_communication.Clear ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000866 return error;
867}
868
869//----------------------------------------------------------------------
870// Process Control
871//----------------------------------------------------------------------
872Error
Jean-Daniel Dupas7782de92013-12-09 22:52:50 +0000873ProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000874{
Todd Fiala75f47c32014-10-11 21:42:09 +0000875 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton4957bf62010-09-30 21:49:03 +0000876 Error error;
Greg Clayton982c9762011-11-03 21:22:33 +0000877
Todd Fiala75f47c32014-10-11 21:42:09 +0000878 if (log)
879 log->Printf ("ProcessGDBRemote::%s() entered", __FUNCTION__);
880
Greg Clayton982c9762011-11-03 21:22:33 +0000881 uint32_t launch_flags = launch_info.GetFlags().Get();
Chaoren Lind3173f32015-05-29 19:52:29 +0000882 FileSpec stdin_file_spec{};
883 FileSpec stdout_file_spec{};
884 FileSpec stderr_file_spec{};
885 FileSpec working_dir = launch_info.GetWorkingDirectory();
Greg Clayton982c9762011-11-03 21:22:33 +0000886
Zachary Turner696b5282014-08-14 16:01:25 +0000887 const FileAction *file_action;
Greg Clayton982c9762011-11-03 21:22:33 +0000888 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
889 if (file_action)
890 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000891 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000892 stdin_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000893 }
894 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
895 if (file_action)
896 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000897 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000898 stdout_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000899 }
900 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
901 if (file_action)
902 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000903 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000904 stderr_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000905 }
906
Todd Fiala75f47c32014-10-11 21:42:09 +0000907 if (log)
908 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000909 if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
Vince Harron4a8abd32015-02-13 19:15:24 +0000910 log->Printf ("ProcessGDBRemote::%s provided with STDIO paths via launch_info: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000911 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000912 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
913 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
914 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Todd Fiala75f47c32014-10-11 21:42:09 +0000915 else
916 log->Printf ("ProcessGDBRemote::%s no STDIO paths given via launch_info", __FUNCTION__);
917 }
918
Vince Harrondf3f00f2015-02-10 21:09:04 +0000919 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Chaoren Lind3173f32015-05-29 19:52:29 +0000920 if (stdin_file_spec || disable_stdio)
Vince Harrondf3f00f2015-02-10 21:09:04 +0000921 {
922 // the inferior will be reading stdin from the specified file
923 // or stdio is completely disabled
924 m_stdin_forward = false;
925 }
926 else
927 {
928 m_stdin_forward = true;
929 }
930
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000931 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
932 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
933 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000934
Greg Clayton982c9762011-11-03 21:22:33 +0000935 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000936 if (object_file)
937 {
Greg Clayton71337622011-02-24 22:24:29 +0000938 // Make sure we aren't already connected?
939 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000940 {
Greg Clayton91a9b2472013-12-04 19:19:12 +0000941 error = LaunchAndConnectToDebugserver (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000942 }
943
944 if (error.Success())
945 {
946 lldb_utility::PseudoTerminal pty;
947 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000948
Greg Claytonf58c2692011-06-24 22:32:10 +0000949 PlatformSP platform_sp (m_target.GetPlatform());
Vince Harrondf3f00f2015-02-10 21:09:04 +0000950 if (disable_stdio)
Greg Clayton71337622011-02-24 22:24:29 +0000951 {
Vince Harrondf3f00f2015-02-10 21:09:04 +0000952 // set to /dev/null unless redirected to a file above
Chaoren Lind3173f32015-05-29 19:52:29 +0000953 if (!stdin_file_spec)
954 stdin_file_spec.SetFile("/dev/null", false);
955 if (!stdout_file_spec)
956 stdout_file_spec.SetFile("/dev/null", false);
957 if (!stderr_file_spec)
958 stderr_file_spec.SetFile("/dev/null", false);
Vince Harrondf3f00f2015-02-10 21:09:04 +0000959 }
960 else if (platform_sp && platform_sp->IsHost())
961 {
962 // If the debugserver is local and we aren't disabling STDIO, lets use
963 // a pseudo terminal to instead of relying on the 'O' packets for stdio
964 // since 'O' packets can really slow down debugging if the inferior
965 // does a lot of output.
Chaoren Lind3173f32015-05-29 19:52:29 +0000966 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
967 pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000968 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000969 FileSpec slave_name{pty.GetSlaveName(NULL, 0), false};
970
971 if (!stdin_file_spec)
972 stdin_file_spec = slave_name;
973
974 if (!stdout_file_spec)
975 stdout_file_spec = slave_name;
976
977 if (!stderr_file_spec)
978 stderr_file_spec = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000979 }
Todd Fiala75f47c32014-10-11 21:42:09 +0000980 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +0000981 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 +0000982 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000983 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
984 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
985 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Greg Clayton71337622011-02-24 22:24:29 +0000986 }
987
Todd Fiala75f47c32014-10-11 21:42:09 +0000988 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +0000989 log->Printf ("ProcessGDBRemote::%s final STDIO paths after all adjustments: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000990 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000991 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
992 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
993 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Todd Fiala75f47c32014-10-11 21:42:09 +0000994
Chaoren Lind3173f32015-05-29 19:52:29 +0000995 if (stdin_file_spec)
996 m_gdb_comm.SetSTDIN(stdin_file_spec);
997 if (stdout_file_spec)
998 m_gdb_comm.SetSTDOUT(stdout_file_spec);
999 if (stderr_file_spec)
1000 m_gdb_comm.SetSTDERR(stderr_file_spec);
Greg Clayton71337622011-02-24 22:24:29 +00001001
1002 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
Jim Ingham106d0282014-06-25 02:32:56 +00001003 m_gdb_comm.SetDetachOnError (launch_flags & eLaunchFlagDetachOnError);
Greg Clayton71337622011-02-24 22:24:29 +00001004
Greg Claytonc4103b32011-05-08 04:53:50 +00001005 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Clayton71337622011-02-24 22:24:29 +00001006
Jason Molendaa3329782014-03-29 18:54:20 +00001007 const char * launch_event_data = launch_info.GetLaunchEventData();
1008 if (launch_event_data != NULL && *launch_event_data != '\0')
1009 m_gdb_comm.SendLaunchEventDataPacket (launch_event_data);
1010
Chaoren Lind3173f32015-05-29 19:52:29 +00001011 if (working_dir)
Greg Clayton71337622011-02-24 22:24:29 +00001012 {
1013 m_gdb_comm.SetWorkingDir (working_dir);
1014 }
1015
1016 // Send the environment and the program + arguments after we connect
Greg Clayton982c9762011-11-03 21:22:33 +00001017 const Args &environment = launch_info.GetEnvironmentEntries();
1018 if (environment.GetArgumentCount())
Greg Clayton71337622011-02-24 22:24:29 +00001019 {
Greg Clayton982c9762011-11-03 21:22:33 +00001020 size_t num_environment_entries = environment.GetArgumentCount();
1021 for (size_t i=0; i<num_environment_entries; ++i)
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001022 {
Greg Clayton982c9762011-11-03 21:22:33 +00001023 const char *env_entry = environment.GetArgumentAtIndex(i);
1024 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Clayton71337622011-02-24 22:24:29 +00001025 break;
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001026 }
Greg Clayton71337622011-02-24 22:24:29 +00001027 }
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001028
Greg Clayton71337622011-02-24 22:24:29 +00001029 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001030 // Scope for the scoped timeout object
1031 GDBRemoteCommunication::ScopedTimeout timeout (m_gdb_comm, 10);
1032
1033 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
1034 if (arg_packet_err == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001035 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001036 std::string error_str;
1037 if (m_gdb_comm.GetLaunchSuccess (error_str))
1038 {
1039 SetID (m_gdb_comm.GetCurrentProcessID ());
1040 }
1041 else
1042 {
1043 error.SetErrorString (error_str.c_str());
1044 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001045 }
1046 else
1047 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001048 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001049 }
Greg Clayton71337622011-02-24 22:24:29 +00001050 }
Tamas Berghammer912800c2015-02-24 10:23:39 +00001051
Greg Clayton71337622011-02-24 22:24:29 +00001052 if (GetID() == LLDB_INVALID_PROCESS_ID)
1053 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001054 if (log)
1055 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton71337622011-02-24 22:24:29 +00001056 KillDebugserverProcess ();
1057 return error;
1058 }
1059
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001060 StringExtractorGDBRemote response;
1061 if (m_gdb_comm.GetStopReply(response))
Greg Clayton71337622011-02-24 22:24:29 +00001062 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001063 SetLastStopPacket(response);
Ewan Crawford78baa192015-05-13 09:18:18 +00001064 // '?' Packets must be handled differently in non-stop mode
1065 if (GetTarget().GetNonStopModeEnabled())
1066 HandleStopReplySequence();
1067
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001068 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
1069
1070 if (process_arch.IsValid())
Jason Molendac62bd7b2013-12-21 05:20:36 +00001071 {
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001072 m_target.MergeArchitecture(process_arch);
1073 }
1074 else
1075 {
1076 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
1077 if (host_arch.IsValid())
1078 m_target.MergeArchitecture(host_arch);
Carlo Kok74389122013-10-14 07:09:13 +00001079 }
1080
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001081 SetPrivateState (SetThreadStopInfo (response));
Greg Clayton71337622011-02-24 22:24:29 +00001082
1083 if (!disable_stdio)
1084 {
1085 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Claytonee95ed52011-11-17 22:14:31 +00001086 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Clayton71337622011-02-24 22:24:29 +00001087 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001088 }
1089 }
Greg Claytonc235ac72011-08-09 05:20:29 +00001090 else
1091 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001092 if (log)
1093 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytonc235ac72011-08-09 05:20:29 +00001094 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001095 }
1096 else
1097 {
1098 // Set our user ID to an invalid process ID.
1099 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton982c9762011-11-03 21:22:33 +00001100 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
1101 exe_module->GetFileSpec().GetFilename().AsCString(),
1102 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001103 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001104 return error;
Greg Clayton4957bf62010-09-30 21:49:03 +00001105
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001106}
1107
1108
1109Error
Greg Claytonb766a732011-02-04 01:58:07 +00001110ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001111{
1112 Error error;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001113 // Only connect if we have a valid connect URL
Vince Harron1b5a74e2015-01-21 22:42:49 +00001114 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton00fe87b2013-12-05 22:58:22 +00001115
1116 if (connect_url && connect_url[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001117 {
Vince Harron1b5a74e2015-01-21 22:42:49 +00001118 if (log)
1119 log->Printf("ProcessGDBRemote::%s Connecting to %s", __FUNCTION__, connect_url);
Greg Clayton00fe87b2013-12-05 22:58:22 +00001120 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
1121 if (conn_ap.get())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001122 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001123 const uint32_t max_retry_count = 50;
1124 uint32_t retry_count = 0;
1125 while (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001126 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001127 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
1128 {
1129 m_gdb_comm.SetConnection (conn_ap.release());
1130 break;
1131 }
1132 else if (error.WasInterrupted())
1133 {
1134 // If we were interrupted, don't keep retrying.
1135 break;
1136 }
1137
1138 retry_count++;
1139
1140 if (retry_count >= max_retry_count)
1141 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001142
Greg Clayton00fe87b2013-12-05 22:58:22 +00001143 usleep (100000);
1144 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001145 }
1146 }
1147
1148 if (!m_gdb_comm.IsConnected())
1149 {
1150 if (error.Success())
1151 error.SetErrorString("not connected to remote gdb server");
1152 return error;
1153 }
1154
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001155
1156 // Start the communications read thread so all incoming data can be
1157 // parsed into packets and queued as they arrive.
1158 if (GetTarget().GetNonStopModeEnabled())
1159 m_gdb_comm.StartReadThread();
1160
Greg Clayton32e0a752011-03-30 18:16:51 +00001161 // We always seem to be able to open a connection to a local port
1162 // so we need to make sure we can then send data to it. If we can't
1163 // then we aren't actually connected to anything, so try and do the
1164 // handshake with the remote GDB server and make sure that goes
1165 // alright.
Greg Claytonfb909312013-11-23 01:58:15 +00001166 if (!m_gdb_comm.HandshakeWithServer (&error))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001167 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001168 m_gdb_comm.Disconnect();
1169 if (error.Success())
1170 error.SetErrorString("not connected to remote gdb server");
1171 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001172 }
Ewan Crawford78baa192015-05-13 09:18:18 +00001173
1174 // Send $QNonStop:1 packet on startup if required
1175 if (GetTarget().GetNonStopModeEnabled())
Ewan Crawfordaa7eda72015-06-24 15:14:26 +00001176 GetTarget().SetNonStopModeEnabled (m_gdb_comm.SetNonStopMode(true));
Ewan Crawford78baa192015-05-13 09:18:18 +00001177
Greg Claytonb30c50c2015-05-29 00:01:55 +00001178 m_gdb_comm.GetEchoSupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001179 m_gdb_comm.GetThreadSuffixSupported ();
Greg Clayton44633992012-04-10 03:22:03 +00001180 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001181 m_gdb_comm.GetHostInfo ();
1182 m_gdb_comm.GetVContSupported ('c');
Jim Inghamcd16df92012-07-20 21:37:13 +00001183 m_gdb_comm.GetVAttachOrWaitSupported();
Ewan Crawford78baa192015-05-13 09:18:18 +00001184
1185 // Ask the remote server for the default thread id
1186 if (GetTarget().GetNonStopModeEnabled())
1187 m_gdb_comm.GetDefaultThreadId(m_initial_tid);
1188
1189
Jim Ingham03afad82012-07-02 05:40:07 +00001190 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1191 for (size_t idx = 0; idx < num_cmds; idx++)
1192 {
1193 StringExtractorGDBRemote response;
Jim Ingham03afad82012-07-02 05:40:07 +00001194 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1195 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001196 return error;
1197}
1198
1199void
Jim Inghambb006ce2014-08-02 00:33:35 +00001200ProcessGDBRemote::DidLaunchOrAttach (ArchSpec& process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001201{
Greg Clayton5160ce52013-03-27 23:08:40 +00001202 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001203 if (log)
1204 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton93d3c8332011-02-16 04:46:07 +00001205 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001206 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001207 BuildDynamicRegisterInfo (false);
Greg Clayton3af9ea52010-11-18 05:57:03 +00001208
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001209 // See if the GDB server supports the qHostInfo information
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001210
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001211
1212 // See if the GDB server supports the qProcessInfo packet, if so
1213 // prefer that over the Host information as it will be more specific
1214 // to our process.
1215
Todd Fiala75f47c32014-10-11 21:42:09 +00001216 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1217 if (remote_process_arch.IsValid())
1218 {
1219 process_arch = remote_process_arch;
1220 if (log)
1221 log->Printf ("ProcessGDBRemote::%s gdb-remote had process architecture, using %s %s",
1222 __FUNCTION__,
1223 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1224 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1225 }
Jim Inghambb006ce2014-08-02 00:33:35 +00001226 else
Todd Fiala75f47c32014-10-11 21:42:09 +00001227 {
Jim Inghambb006ce2014-08-02 00:33:35 +00001228 process_arch = m_gdb_comm.GetHostArchitecture();
Todd Fiala75f47c32014-10-11 21:42:09 +00001229 if (log)
1230 log->Printf ("ProcessGDBRemote::%s gdb-remote did not have process architecture, using gdb-remote host architecture %s %s",
1231 __FUNCTION__,
1232 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1233 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1234 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001235
Jim Inghambb006ce2014-08-02 00:33:35 +00001236 if (process_arch.IsValid())
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001237 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001238 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Greg Claytond314e812011-03-23 00:09:55 +00001239 if (target_arch.IsValid())
1240 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001241 if (log)
1242 log->Printf ("ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1243 __FUNCTION__,
1244 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1245 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
1246
1247 // If the remote host is ARM and we have apple as the vendor, then
Greg Claytond314e812011-03-23 00:09:55 +00001248 // ARM executables and shared libraries can have mixed ARM architectures.
1249 // You can have an armv6 executable, and if the host is armv7, then the
1250 // system will load the best possible architecture for all shared libraries
1251 // it has, so we really need to take the remote host architecture as our
1252 // defacto architecture in this case.
1253
Jason Molenda6d9fe8c2015-08-21 00:13:37 +00001254 if ((process_arch.GetMachine() == llvm::Triple::arm || process_arch.GetMachine() == llvm::Triple::thumb)
1255 && process_arch.GetTriple().getVendor() == llvm::Triple::Apple)
Greg Claytond314e812011-03-23 00:09:55 +00001256 {
Jason Molenda921c01b2014-08-03 21:42:52 +00001257 GetTarget().SetArchitecture (process_arch);
Todd Fiala75f47c32014-10-11 21:42:09 +00001258 if (log)
1259 log->Printf ("ProcessGDBRemote::%s remote process is ARM/Apple, setting target arch to %s %s",
1260 __FUNCTION__,
1261 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1262 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001263 }
1264 else
1265 {
1266 // Fill in what is missing in the triple
Jim Inghambb006ce2014-08-02 00:33:35 +00001267 const llvm::Triple &remote_triple = process_arch.GetTriple();
Tamas Berghammere724af12015-03-13 10:32:37 +00001268 llvm::Triple new_target_triple = target_arch.GetTriple();
1269 if (new_target_triple.getVendorName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001270 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001271 new_target_triple.setVendor (remote_triple.getVendor());
Greg Claytond314e812011-03-23 00:09:55 +00001272
Tamas Berghammere724af12015-03-13 10:32:37 +00001273 if (new_target_triple.getOSName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001274 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001275 new_target_triple.setOS (remote_triple.getOS());
Greg Claytond314e812011-03-23 00:09:55 +00001276
Tamas Berghammere724af12015-03-13 10:32:37 +00001277 if (new_target_triple.getEnvironmentName().size() == 0)
1278 new_target_triple.setEnvironment (remote_triple.getEnvironment());
Greg Clayton70b57652011-05-15 01:25:55 +00001279 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001280
Tamas Berghammere724af12015-03-13 10:32:37 +00001281 ArchSpec new_target_arch = target_arch;
1282 new_target_arch.SetTriple(new_target_triple);
1283 GetTarget().SetArchitecture(new_target_arch);
1284 }
Greg Claytond314e812011-03-23 00:09:55 +00001285 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001286
1287 if (log)
1288 log->Printf ("ProcessGDBRemote::%s final target arch after adjustments for remote architecture: %s %s",
1289 __FUNCTION__,
1290 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1291 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001292 }
1293 else
1294 {
1295 // The target doesn't have a valid architecture yet, set it from
1296 // the architecture we got from the remote GDB server
Jason Molenda921c01b2014-08-03 21:42:52 +00001297 GetTarget().SetArchitecture (process_arch);
Greg Claytond314e812011-03-23 00:09:55 +00001298 }
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001299 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001300 }
1301}
1302
1303void
1304ProcessGDBRemote::DidLaunch ()
1305{
Jim Inghambb006ce2014-08-02 00:33:35 +00001306 ArchSpec process_arch;
1307 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001308}
1309
1310Error
Han Ming Ong84647042012-02-25 01:07:38 +00001311ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1312{
Todd Fiala75f47c32014-10-11 21:42:09 +00001313 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001314 Error error;
Todd Fiala75f47c32014-10-11 21:42:09 +00001315
1316 if (log)
1317 log->Printf ("ProcessGDBRemote::%s()", __FUNCTION__);
1318
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001319 // Clear out and clean up from any current state
1320 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001321 if (attach_pid != LLDB_INVALID_PROCESS_ID)
1322 {
Greg Clayton71337622011-02-24 22:24:29 +00001323 // Make sure we aren't already connected?
1324 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001325 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001326 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001327
1328 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001329 {
Greg Clayton71337622011-02-24 22:24:29 +00001330 const char *error_string = error.AsCString();
1331 if (error_string == NULL)
1332 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1333
1334 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001335 }
Greg Clayton71337622011-02-24 22:24:29 +00001336 }
1337
1338 if (error.Success())
1339 {
Jim Ingham106d0282014-06-25 02:32:56 +00001340 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
Todd Fiala75f47c32014-10-11 21:42:09 +00001341
Greg Clayton71337622011-02-24 22:24:29 +00001342 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001343 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Greg Clayton3b608422011-11-19 02:11:30 +00001344 SetID (attach_pid);
Greg Clayton71337622011-02-24 22:24:29 +00001345 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001346 }
1347 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001348
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001349 return error;
1350}
1351
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001352Error
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001353ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001354{
1355 Error error;
1356 // Clear out and clean up from any current state
1357 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001358
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001359 if (process_name && process_name[0])
1360 {
Greg Clayton71337622011-02-24 22:24:29 +00001361 // Make sure we aren't already connected?
1362 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001363 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001364 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001365
Greg Clayton71337622011-02-24 22:24:29 +00001366 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001367 {
Greg Clayton71337622011-02-24 22:24:29 +00001368 const char *error_string = error.AsCString();
1369 if (error_string == NULL)
1370 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001371
Greg Clayton71337622011-02-24 22:24:29 +00001372 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001373 }
Greg Clayton71337622011-02-24 22:24:29 +00001374 }
1375
1376 if (error.Success())
1377 {
1378 StreamString packet;
1379
Jim Ingham106d0282014-06-25 02:32:56 +00001380 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1381
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001382 if (attach_info.GetWaitForLaunch())
Jim Inghamcd16df92012-07-20 21:37:13 +00001383 {
1384 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1385 {
1386 packet.PutCString ("vAttachWait");
1387 }
1388 else
1389 {
1390 if (attach_info.GetIgnoreExisting())
1391 packet.PutCString("vAttachWait");
1392 else
1393 packet.PutCString ("vAttachOrWait");
1394 }
1395 }
Greg Clayton71337622011-02-24 22:24:29 +00001396 else
1397 packet.PutCString("vAttachName");
1398 packet.PutChar(';');
1399 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1400
1401 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1402
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001403 }
1404 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001405 return error;
1406}
1407
Greg Clayton5df78fa2015-05-23 03:54:53 +00001408void
1409ProcessGDBRemote::DidExit ()
Greg Claytonfbb76342013-11-20 21:07:01 +00001410{
Greg Clayton5df78fa2015-05-23 03:54:53 +00001411 // When we exit, disconnect from the GDB server communications
Greg Claytonfbb76342013-11-20 21:07:01 +00001412 m_gdb_comm.Disconnect();
Greg Claytonfbb76342013-11-20 21:07:01 +00001413}
1414
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001415void
Jim Inghambb006ce2014-08-02 00:33:35 +00001416ProcessGDBRemote::DidAttach (ArchSpec &process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001417{
Jim Inghambb006ce2014-08-02 00:33:35 +00001418 // If you can figure out what the architecture is, fill it in here.
1419 process_arch.Clear();
1420 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001421}
1422
Greg Clayton90ba8112012-12-05 00:16:59 +00001423
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001424Error
1425ProcessGDBRemote::WillResume ()
1426{
Greg Clayton71fc2a32011-02-12 06:28:37 +00001427 m_continue_c_tids.clear();
1428 m_continue_C_tids.clear();
1429 m_continue_s_tids.clear();
1430 m_continue_S_tids.clear();
Greg Clayton2e309072015-07-17 23:42:28 +00001431 m_jstopinfo_sp.reset();
1432 m_jthreadsinfo_sp.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001433 return Error();
1434}
1435
1436Error
1437ProcessGDBRemote::DoResume ()
1438{
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001439 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001440 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001441 if (log)
1442 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytone5219662010-12-03 06:02:24 +00001443
1444 Listener listener ("gdb-remote.resume-packet-sent");
1445 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1446 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00001447 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1448
Greg Claytond1d06e42013-04-20 00:27:58 +00001449 const size_t num_threads = GetThreadList().GetSize();
1450
Greg Clayton71fc2a32011-02-12 06:28:37 +00001451 StreamString continue_packet;
1452 bool continue_packet_error = false;
1453 if (m_gdb_comm.HasAnyVContSupport ())
1454 {
Ewan Crawford78baa192015-05-13 09:18:18 +00001455 if (!GetTarget().GetNonStopModeEnabled() &&
1456 (m_continue_c_tids.size() == num_threads ||
Greg Claytone98008c2014-02-13 23:34:38 +00001457 (m_continue_c_tids.empty() &&
1458 m_continue_C_tids.empty() &&
1459 m_continue_s_tids.empty() &&
Ewan Crawford78baa192015-05-13 09:18:18 +00001460 m_continue_S_tids.empty())))
Greg Clayton71fc2a32011-02-12 06:28:37 +00001461 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001462 // All threads are continuing, just send a "c" packet
1463 continue_packet.PutCString ("c");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001464 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001465 else
1466 {
1467 continue_packet.PutCString ("vCont");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001468
Greg Claytond1d06e42013-04-20 00:27:58 +00001469 if (!m_continue_c_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001470 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001471 if (m_gdb_comm.GetVContSupported ('c'))
1472 {
1473 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)
1474 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1475 }
1476 else
1477 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001478 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001479
1480 if (!continue_packet_error && !m_continue_C_tids.empty())
1481 {
1482 if (m_gdb_comm.GetVContSupported ('C'))
1483 {
1484 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)
1485 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1486 }
1487 else
1488 continue_packet_error = true;
1489 }
Greg Claytone5219662010-12-03 06:02:24 +00001490
Greg Claytond1d06e42013-04-20 00:27:58 +00001491 if (!continue_packet_error && !m_continue_s_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001492 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001493 if (m_gdb_comm.GetVContSupported ('s'))
1494 {
1495 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)
1496 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1497 }
1498 else
1499 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001500 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001501
1502 if (!continue_packet_error && !m_continue_S_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001503 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001504 if (m_gdb_comm.GetVContSupported ('S'))
1505 {
1506 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)
1507 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1508 }
1509 else
1510 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001511 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001512
1513 if (continue_packet_error)
1514 continue_packet.GetString().clear();
Greg Clayton71fc2a32011-02-12 06:28:37 +00001515 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001516 }
1517 else
1518 continue_packet_error = true;
1519
1520 if (continue_packet_error)
1521 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001522 // Either no vCont support, or we tried to use part of the vCont
1523 // packet that wasn't supported by the remote GDB server.
1524 // We need to try and make a simple packet that can do our continue
Greg Clayton71fc2a32011-02-12 06:28:37 +00001525 const size_t num_continue_c_tids = m_continue_c_tids.size();
1526 const size_t num_continue_C_tids = m_continue_C_tids.size();
1527 const size_t num_continue_s_tids = m_continue_s_tids.size();
1528 const size_t num_continue_S_tids = m_continue_S_tids.size();
1529 if (num_continue_c_tids > 0)
1530 {
1531 if (num_continue_c_tids == num_threads)
1532 {
1533 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001534 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001535 continue_packet.PutChar ('c');
1536 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001537 }
1538 else if (num_continue_c_tids == 1 &&
1539 num_continue_C_tids == 0 &&
1540 num_continue_s_tids == 0 &&
1541 num_continue_S_tids == 0 )
1542 {
1543 // Only one thread is continuing
Greg Clayton8b82f082011-04-12 05:54:46 +00001544 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001545 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001546 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001547 }
1548 }
1549
Greg Clayton0c74e782011-06-24 03:21:43 +00001550 if (continue_packet_error && num_continue_C_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001551 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001552 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1553 num_continue_C_tids > 0 &&
1554 num_continue_s_tids == 0 &&
1555 num_continue_S_tids == 0 )
Greg Clayton71fc2a32011-02-12 06:28:37 +00001556 {
1557 const int continue_signo = m_continue_C_tids.front().second;
Greg Clayton0c74e782011-06-24 03:21:43 +00001558 // Only one thread is continuing
Greg Clayton71fc2a32011-02-12 06:28:37 +00001559 if (num_continue_C_tids > 1)
1560 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001561 // More that one thread with a signal, yet we don't have
1562 // vCont support and we are being asked to resume each
1563 // thread with a signal, we need to make sure they are
1564 // all the same signal, or we can't issue the continue
1565 // accurately with the current support...
1566 if (num_continue_C_tids > 1)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001567 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001568 continue_packet_error = false;
1569 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1570 {
1571 if (m_continue_C_tids[i].second != continue_signo)
1572 continue_packet_error = true;
1573 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001574 }
Greg Clayton0c74e782011-06-24 03:21:43 +00001575 if (!continue_packet_error)
1576 m_gdb_comm.SetCurrentThreadForRun (-1);
1577 }
1578 else
1579 {
1580 // Set the continue thread ID
1581 continue_packet_error = false;
1582 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001583 }
1584 if (!continue_packet_error)
1585 {
1586 // Add threads continuing with the same signo...
Greg Clayton71fc2a32011-02-12 06:28:37 +00001587 continue_packet.Printf("C%2.2x", continue_signo);
1588 }
1589 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001590 }
1591
Greg Clayton0c74e782011-06-24 03:21:43 +00001592 if (continue_packet_error && num_continue_s_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001593 {
1594 if (num_continue_s_tids == num_threads)
1595 {
1596 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001597 m_gdb_comm.SetCurrentThreadForRun (-1);
Ewan Crawford76df2882015-06-23 12:32:06 +00001598
1599 // If in Non-Stop-Mode use vCont when stepping
1600 if (GetTarget().GetNonStopModeEnabled())
1601 {
1602 if (m_gdb_comm.GetVContSupported('s'))
1603 continue_packet.PutCString("vCont;s");
1604 else
1605 continue_packet.PutChar('s');
1606 }
1607 else
1608 continue_packet.PutChar('s');
1609
Greg Clayton0c74e782011-06-24 03:21:43 +00001610 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001611 }
1612 else if (num_continue_c_tids == 0 &&
1613 num_continue_C_tids == 0 &&
1614 num_continue_s_tids == 1 &&
1615 num_continue_S_tids == 0 )
1616 {
1617 // Only one thread is stepping
Greg Clayton8b82f082011-04-12 05:54:46 +00001618 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001619 continue_packet.PutChar ('s');
Greg Clayton0c74e782011-06-24 03:21:43 +00001620 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001621 }
1622 }
1623
1624 if (!continue_packet_error && num_continue_S_tids > 0)
1625 {
1626 if (num_continue_S_tids == num_threads)
1627 {
1628 const int step_signo = m_continue_S_tids.front().second;
1629 // Are all threads trying to step with the same signal?
Greg Clayton0c74e782011-06-24 03:21:43 +00001630 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001631 if (num_continue_S_tids > 1)
1632 {
1633 for (size_t i=1; i<num_threads; ++i)
1634 {
1635 if (m_continue_S_tids[i].second != step_signo)
1636 continue_packet_error = true;
1637 }
1638 }
1639 if (!continue_packet_error)
1640 {
1641 // Add threads stepping with the same signo...
Greg Clayton8b82f082011-04-12 05:54:46 +00001642 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001643 continue_packet.Printf("S%2.2x", step_signo);
1644 }
1645 }
1646 else if (num_continue_c_tids == 0 &&
1647 num_continue_C_tids == 0 &&
1648 num_continue_s_tids == 0 &&
1649 num_continue_S_tids == 1 )
1650 {
1651 // Only one thread is stepping with signal
Greg Clayton8b82f082011-04-12 05:54:46 +00001652 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001653 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Clayton0c74e782011-06-24 03:21:43 +00001654 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001655 }
1656 }
1657 }
1658
1659 if (continue_packet_error)
1660 {
1661 error.SetErrorString ("can't make continue packet for this resume");
1662 }
1663 else
1664 {
1665 EventSP event_sp;
1666 TimeValue timeout;
1667 timeout = TimeValue::Now();
1668 timeout.OffsetWithSeconds (5);
Zachary Turneracee96a2014-09-23 18:32:09 +00001669 if (!m_async_thread.IsJoinable())
Jim Inghamb1e2e842012-04-12 18:49:31 +00001670 {
1671 error.SetErrorString ("Trying to resume but the async thread is dead.");
1672 if (log)
1673 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1674 return error;
1675 }
1676
Greg Clayton71fc2a32011-02-12 06:28:37 +00001677 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1678
1679 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Inghamb1e2e842012-04-12 18:49:31 +00001680 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001681 error.SetErrorString("Resume timed out.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00001682 if (log)
1683 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1684 }
1685 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1686 {
1687 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1688 if (log)
1689 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1690 return error;
1691 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001692 }
Greg Claytone5219662010-12-03 06:02:24 +00001693 }
1694
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001695 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001696}
1697
Greg Clayton9e920902012-04-10 02:25:43 +00001698void
Ewan Crawford78baa192015-05-13 09:18:18 +00001699ProcessGDBRemote::HandleStopReplySequence ()
1700{
1701 while(true)
1702 {
1703 // Send vStopped
1704 StringExtractorGDBRemote response;
1705 m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false);
1706
1707 // OK represents end of signal list
1708 if (response.IsOKResponse())
1709 break;
1710
1711 // If not OK or a normal packet we have a problem
1712 if (!response.IsNormalResponse())
1713 break;
1714
1715 SetLastStopPacket(response);
1716 }
1717}
1718
1719void
Greg Clayton9e920902012-04-10 02:25:43 +00001720ProcessGDBRemote::ClearThreadIDList ()
1721{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001722 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001723 m_thread_ids.clear();
1724}
1725
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001726size_t
1727ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue (std::string &value)
1728{
1729 m_thread_ids.clear();
1730 size_t comma_pos;
1731 lldb::tid_t tid;
1732 while ((comma_pos = value.find(',')) != std::string::npos)
1733 {
1734 value[comma_pos] = '\0';
1735 // thread in big endian hex
1736 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1737 if (tid != LLDB_INVALID_THREAD_ID)
1738 m_thread_ids.push_back (tid);
1739 value.erase(0, comma_pos + 1);
1740 }
1741 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1742 if (tid != LLDB_INVALID_THREAD_ID)
1743 m_thread_ids.push_back (tid);
1744 return m_thread_ids.size();
1745}
1746
Greg Clayton9e920902012-04-10 02:25:43 +00001747bool
1748ProcessGDBRemote::UpdateThreadIDList ()
1749{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001750 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001751
Greg Clayton2e309072015-07-17 23:42:28 +00001752 if (m_jthreadsinfo_sp)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001753 {
1754 // If we have the JSON threads info, we can get the thread list from that
Greg Clayton2e309072015-07-17 23:42:28 +00001755 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001756 if (thread_infos && thread_infos->GetSize() > 0)
1757 {
1758 m_thread_ids.clear();
1759 thread_infos->ForEach([this](StructuredData::Object* object) -> bool {
1760 StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1761 if (thread_dict)
1762 {
1763 // Set the thread stop info from the JSON dictionary
1764 SetThreadStopInfo (thread_dict);
1765 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1766 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1767 m_thread_ids.push_back(tid);
1768 }
1769 return true; // Keep iterating through all thread_info objects
1770 });
1771 }
1772 if (!m_thread_ids.empty())
1773 return true;
1774 }
1775 else
1776 {
1777 // See if we can get the thread IDs from the current stop reply packets
1778 // that might contain a "threads" key/value pair
1779
1780 // Lock the thread stack while we access it
1781 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
1782 // Get the number of stop packets on the stack
1783 int nItems = m_stop_packet_stack.size();
1784 // Iterate over them
1785 for (int i = 0; i < nItems; i++)
1786 {
1787 // Get the thread stop info
1788 StringExtractorGDBRemote &stop_info = m_stop_packet_stack[i];
1789 const std::string &stop_info_str = stop_info.GetStringRef();
1790 const size_t threads_pos = stop_info_str.find(";threads:");
1791 if (threads_pos != std::string::npos)
1792 {
1793 const size_t start = threads_pos + strlen(";threads:");
1794 const size_t end = stop_info_str.find(';', start);
1795 if (end != std::string::npos)
1796 {
1797 std::string value = stop_info_str.substr(start, end - start);
1798 if (UpdateThreadIDsFromStopReplyThreadsValue(value))
1799 return true;
1800 }
1801 }
1802 }
1803 }
1804
Greg Clayton9e920902012-04-10 02:25:43 +00001805 bool sequence_mutex_unavailable = false;
1806 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1807 if (sequence_mutex_unavailable)
1808 {
Greg Clayton9e920902012-04-10 02:25:43 +00001809 return false; // We just didn't get the list
1810 }
1811 return true;
1812}
1813
Greg Clayton9fc13552012-04-10 00:18:59 +00001814bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001815ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001816{
1817 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +00001818 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Clayton73b472d2010-10-27 03:32:59 +00001819 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +00001820 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton9e920902012-04-10 02:25:43 +00001821
1822 size_t num_thread_ids = m_thread_ids.size();
1823 // The "m_thread_ids" thread ID list should always be updated after each stop
1824 // reply packet, but in case it isn't, update it here.
1825 if (num_thread_ids == 0)
1826 {
1827 if (!UpdateThreadIDList ())
1828 return false;
1829 num_thread_ids = m_thread_ids.size();
1830 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001831
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001832 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001833 if (num_thread_ids > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001834 {
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001835 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001836 {
Greg Clayton9e920902012-04-10 02:25:43 +00001837 tid_t tid = m_thread_ids[i];
Greg Clayton160c9d82013-05-01 21:54:04 +00001838 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001839 if (!thread_sp)
Jim Inghamdee1bc92013-06-22 00:27:45 +00001840 {
Jim Ingham4f465cf2012-10-10 18:32:14 +00001841 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001842 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1843 log->Printf(
1844 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001845 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001846 thread_sp->GetID());
1847 }
1848 else
1849 {
1850 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1851 log->Printf(
1852 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001853 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001854 thread_sp->GetID());
1855 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001856 new_thread_list.AddThread(thread_sp);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001857 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001858 }
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001859
1860 // Whatever that is left in old_thread_list_copy are not
1861 // present in new_thread_list. Remove non-existent threads from internal id table.
1862 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1863 for (size_t i=0; i<old_num_thread_ids; i++)
1864 {
1865 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1866 if (old_thread_sp)
1867 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001868 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001869 m_thread_id_to_index_id_map.erase(old_thread_id);
1870 }
1871 }
1872
Greg Clayton9fc13552012-04-10 00:18:59 +00001873 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001874}
1875
Greg Clayton2e309072015-07-17 23:42:28 +00001876
Greg Clayton358cf1e2015-06-25 21:46:34 +00001877bool
Greg Clayton2e309072015-07-17 23:42:28 +00001878ProcessGDBRemote::GetThreadStopInfoFromJSON (ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001879{
1880 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet
Greg Clayton2e309072015-07-17 23:42:28 +00001881 if (thread_infos_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001882 {
Greg Clayton2e309072015-07-17 23:42:28 +00001883 StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
Greg Clayton358cf1e2015-06-25 21:46:34 +00001884 if (thread_infos)
1885 {
1886 lldb::tid_t tid;
1887 const size_t n = thread_infos->GetSize();
1888 for (size_t i=0; i<n; ++i)
1889 {
1890 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1891 if (thread_dict)
1892 {
1893 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid, LLDB_INVALID_THREAD_ID))
1894 {
1895 if (tid == thread->GetID())
Greg Clayton2e309072015-07-17 23:42:28 +00001896 return (bool)SetThreadStopInfo(thread_dict);
Greg Clayton358cf1e2015-06-25 21:46:34 +00001897 }
1898 }
1899 }
1900 }
1901 }
Greg Clayton2e309072015-07-17 23:42:28 +00001902 return false;
1903}
1904
1905bool
1906ProcessGDBRemote::CalculateThreadStopInfo (ThreadGDBRemote *thread)
1907{
1908 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet
1909 if (GetThreadStopInfoFromJSON (thread, m_jthreadsinfo_sp))
1910 return true;
1911
1912 // See if we got thread stop info for any threads valid stop info reasons threads
1913 // via the "jstopinfo" packet stop reply packet key/value pair?
1914 if (m_jstopinfo_sp)
1915 {
1916 // If we have "jstopinfo" then we have stop descriptions for all threads
1917 // that have stop reasons, and if there is no entry for a thread, then
1918 // it has no stop reason.
1919 thread->GetRegisterContext()->InvalidateIfNeeded(true);
1920 if (!GetThreadStopInfoFromJSON (thread, m_jstopinfo_sp))
1921 {
1922 thread->SetStopInfo (StopInfoSP());
1923 }
1924 return true;
1925 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00001926
1927 // Fall back to using the qThreadStopInfo packet
1928 StringExtractorGDBRemote stop_packet;
1929 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1930 return SetThreadStopInfo (stop_packet) == eStateStopped;
1931 return false;
1932}
1933
1934
1935ThreadSP
1936ProcessGDBRemote::SetThreadStopInfo (lldb::tid_t tid,
1937 ExpeditedRegisterMap &expedited_register_map,
1938 uint8_t signo,
1939 const std::string &thread_name,
1940 const std::string &reason,
1941 const std::string &description,
1942 uint32_t exc_type,
1943 const std::vector<addr_t> &exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001944 addr_t thread_dispatch_qaddr,
1945 bool queue_vars_valid, // Set to true if queue_name, queue_kind and queue_serial are valid
1946 std::string &queue_name,
1947 QueueKind queue_kind,
1948 uint64_t queue_serial)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001949{
1950 ThreadSP thread_sp;
1951 if (tid != LLDB_INVALID_THREAD_ID)
1952 {
1953 // Scope for "locker" below
1954 {
1955 // m_thread_list_real does have its own mutex, but we need to
1956 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1957 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1958 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1959 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1960
1961 if (!thread_sp)
1962 {
1963 // Create the thread if we need to
1964 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1965 m_thread_list_real.AddThread(thread_sp);
1966 }
1967 }
1968
1969 if (thread_sp)
1970 {
1971 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1972 gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001973
Greg Clayton358cf1e2015-06-25 21:46:34 +00001974 for (const auto &pair : expedited_register_map)
1975 {
1976 StringExtractor reg_value_extractor;
1977 reg_value_extractor.GetStringRef() = pair.second;
1978 gdb_thread->PrivateSetRegisterValue (pair.first, reg_value_extractor);
1979 }
1980
Greg Clayton358cf1e2015-06-25 21:46:34 +00001981 thread_sp->SetName (thread_name.empty() ? NULL : thread_name.c_str());
1982
1983 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001984 // Check if the GDB server was able to provide the queue name, kind and serial number
1985 if (queue_vars_valid)
1986 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind, queue_serial);
1987 else
1988 gdb_thread->ClearQueueInfo();
1989
Greg Clayton2e309072015-07-17 23:42:28 +00001990 // Make sure we update our thread stop reason just once
1991 if (!thread_sp->StopInfoIsUpToDate())
Greg Clayton358cf1e2015-06-25 21:46:34 +00001992 {
Greg Clayton2e309072015-07-17 23:42:28 +00001993 thread_sp->SetStopInfo (StopInfoSP());
Greg Clayton358cf1e2015-06-25 21:46:34 +00001994
Greg Clayton2e309072015-07-17 23:42:28 +00001995 if (exc_type != 0)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001996 {
Greg Clayton2e309072015-07-17 23:42:28 +00001997 const size_t exc_data_size = exc_data.size();
1998
1999 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
2000 exc_type,
2001 exc_data_size,
2002 exc_data_size >= 1 ? exc_data[0] : 0,
2003 exc_data_size >= 2 ? exc_data[1] : 0,
2004 exc_data_size >= 3 ? exc_data[2] : 0));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002005 }
Greg Clayton2e309072015-07-17 23:42:28 +00002006 else
Greg Clayton358cf1e2015-06-25 21:46:34 +00002007 {
Greg Clayton2e309072015-07-17 23:42:28 +00002008 bool handled = false;
2009 bool did_exec = false;
2010 if (!reason.empty())
Greg Clayton358cf1e2015-06-25 21:46:34 +00002011 {
Greg Clayton2e309072015-07-17 23:42:28 +00002012 if (reason.compare("trace") == 0)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002013 {
Greg Clayton2e309072015-07-17 23:42:28 +00002014 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
2015 handled = true;
2016 }
2017 else if (reason.compare("breakpoint") == 0)
2018 {
2019 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
2020 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2021 if (bp_site_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002022 {
Greg Clayton2e309072015-07-17 23:42:28 +00002023 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2024 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2025 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2026 handled = true;
2027 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2028 {
2029 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2030 }
2031 else
2032 {
2033 StopInfoSP invalid_stop_info_sp;
2034 thread_sp->SetStopInfo (invalid_stop_info_sp);
2035 }
2036 }
2037 }
2038 else if (reason.compare("trap") == 0)
2039 {
2040 // Let the trap just use the standard signal stop reason below...
2041 }
2042 else if (reason.compare("watchpoint") == 0)
2043 {
2044 StringExtractor desc_extractor(description.c_str());
2045 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
2046 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
Jaydeep Patil83143502015-08-13 03:44:09 +00002047 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
Greg Clayton2e309072015-07-17 23:42:28 +00002048 watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
2049 if (wp_addr != LLDB_INVALID_ADDRESS)
2050 {
2051 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2052 if (wp_sp)
2053 {
2054 wp_sp->SetHardwareIndex(wp_index);
2055 watch_id = wp_sp->GetID();
2056 }
2057 }
2058 if (watch_id == LLDB_INVALID_WATCH_ID)
2059 {
2060 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_WATCHPOINTS));
2061 if (log) log->Printf ("failed to find watchpoint");
2062 }
Jaydeep Patil83143502015-08-13 03:44:09 +00002063 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id, wp_hit_addr));
Greg Clayton2e309072015-07-17 23:42:28 +00002064 handled = true;
2065 }
2066 else if (reason.compare("exception") == 0)
2067 {
2068 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
2069 handled = true;
2070 }
2071 else if (reason.compare("exec") == 0)
2072 {
2073 did_exec = true;
2074 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
2075 handled = true;
2076 }
2077 }
2078
2079 if (!handled && signo && did_exec == false)
2080 {
2081 if (signo == SIGTRAP)
2082 {
2083 // Currently we are going to assume SIGTRAP means we are either
2084 // hitting a breakpoint or hardware single stepping.
2085 handled = true;
2086 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
2087 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2088
2089 if (bp_site_sp)
2090 {
2091 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2092 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2093 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2094 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2095 {
2096 if(m_breakpoint_pc_offset != 0)
2097 thread_sp->GetRegisterContext()->SetPC(pc);
2098 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2099 }
2100 else
2101 {
2102 StopInfoSP invalid_stop_info_sp;
2103 thread_sp->SetStopInfo (invalid_stop_info_sp);
2104 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002105 }
2106 else
2107 {
Greg Clayton2e309072015-07-17 23:42:28 +00002108 // If we were stepping then assume the stop was the result of the trace. If we were
2109 // not stepping then report the SIGTRAP.
2110 // FIXME: We are still missing the case where we single step over a trap instruction.
2111 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
2112 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
2113 else
2114 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo, description.c_str()));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002115 }
2116 }
Greg Clayton2e309072015-07-17 23:42:28 +00002117 if (!handled)
2118 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo, description.c_str()));
2119 }
2120
2121 if (!description.empty())
2122 {
2123 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
2124 if (stop_info_sp)
2125 {
2126 const char *stop_info_desc = stop_info_sp->GetDescription();
2127 if (!stop_info_desc || !stop_info_desc[0])
2128 stop_info_sp->SetDescription (description.c_str());
2129 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002130 else
2131 {
Greg Clayton2e309072015-07-17 23:42:28 +00002132 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002133 }
2134 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002135 }
2136 }
2137 }
2138 }
2139 return thread_sp;
2140}
2141
Greg Clayton2e309072015-07-17 23:42:28 +00002142lldb::ThreadSP
Greg Clayton358cf1e2015-06-25 21:46:34 +00002143ProcessGDBRemote::SetThreadStopInfo (StructuredData::Dictionary *thread_dict)
2144{
2145 static ConstString g_key_tid("tid");
2146 static ConstString g_key_name("name");
2147 static ConstString g_key_reason("reason");
2148 static ConstString g_key_metype("metype");
2149 static ConstString g_key_medata("medata");
2150 static ConstString g_key_qaddr("qaddr");
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002151 static ConstString g_key_queue_name("qname");
2152 static ConstString g_key_queue_kind("qkind");
2153 static ConstString g_key_queue_serial("qserial");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002154 static ConstString g_key_registers("registers");
2155 static ConstString g_key_memory("memory");
2156 static ConstString g_key_address("address");
2157 static ConstString g_key_bytes("bytes");
2158 static ConstString g_key_description("description");
Pavel Labath4a4bb122015-07-16 14:14:35 +00002159 static ConstString g_key_signal("signal");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002160
2161 // Stop with signal and thread info
2162 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2163 uint8_t signo = 0;
2164 std::string value;
2165 std::string thread_name;
2166 std::string reason;
2167 std::string description;
2168 uint32_t exc_type = 0;
2169 std::vector<addr_t> exc_data;
2170 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2171 ExpeditedRegisterMap expedited_register_map;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002172 bool queue_vars_valid = false;
2173 std::string queue_name;
2174 QueueKind queue_kind = eQueueKindUnknown;
2175 uint64_t queue_serial = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002176 // Iterate through all of the thread dictionary key/value pairs from the structured data dictionary
2177
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002178 thread_dict->ForEach([this,
2179 &tid,
2180 &expedited_register_map,
2181 &thread_name,
2182 &signo,
2183 &reason,
2184 &description,
2185 &exc_type,
2186 &exc_data,
2187 &thread_dispatch_qaddr,
2188 &queue_vars_valid,
2189 &queue_name,
2190 &queue_kind,
2191 &queue_serial]
2192 (ConstString key, StructuredData::Object* object) -> bool
Greg Clayton358cf1e2015-06-25 21:46:34 +00002193 {
2194 if (key == g_key_tid)
2195 {
2196 // thread in big endian hex
2197 tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
2198 }
2199 else if (key == g_key_metype)
2200 {
2201 // exception type in big endian hex
2202 exc_type = object->GetIntegerValue(0);
2203 }
2204 else if (key == g_key_medata)
2205 {
2206 // exception data in big endian hex
2207 StructuredData::Array *array = object->GetAsArray();
2208 if (array)
2209 {
2210 array->ForEach([&exc_data](StructuredData::Object* object) -> bool {
2211 exc_data.push_back(object->GetIntegerValue());
2212 return true; // Keep iterating through all array items
2213 });
2214 }
2215 }
2216 else if (key == g_key_name)
2217 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002218 thread_name = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002219 }
2220 else if (key == g_key_qaddr)
2221 {
2222 thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
2223 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002224 else if (key == g_key_queue_name)
2225 {
2226 queue_vars_valid = true;
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002227 queue_name = object->GetStringValue();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002228 }
2229 else if (key == g_key_queue_kind)
2230 {
2231 std::string queue_kind_str = object->GetStringValue();
2232 if (queue_kind_str == "serial")
2233 {
2234 queue_vars_valid = true;
2235 queue_kind = eQueueKindSerial;
2236 }
2237 else if (queue_kind_str == "concurrent")
2238 {
2239 queue_vars_valid = true;
2240 queue_kind = eQueueKindConcurrent;
2241 }
2242 }
2243 else if (key == g_key_queue_serial)
2244 {
2245 queue_serial = object->GetIntegerValue(0);
2246 if (queue_serial != 0)
2247 queue_vars_valid = true;
2248 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002249 else if (key == g_key_reason)
2250 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002251 reason = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002252 }
2253 else if (key == g_key_description)
2254 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002255 description = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002256 }
2257 else if (key == g_key_registers)
2258 {
2259 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2260
2261 if (registers_dict)
2262 {
2263 registers_dict->ForEach([&expedited_register_map](ConstString key, StructuredData::Object* object) -> bool {
2264 const uint32_t reg = StringConvert::ToUInt32 (key.GetCString(), UINT32_MAX, 10);
2265 if (reg != UINT32_MAX)
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002266 expedited_register_map[reg] = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002267 return true; // Keep iterating through all array items
2268 });
2269 }
2270 }
2271 else if (key == g_key_memory)
2272 {
2273 StructuredData::Array *array = object->GetAsArray();
2274 if (array)
2275 {
2276 array->ForEach([this](StructuredData::Object* object) -> bool {
2277 StructuredData::Dictionary *mem_cache_dict = object->GetAsDictionary();
2278 if (mem_cache_dict)
2279 {
2280 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2281 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>("address", mem_cache_addr))
2282 {
2283 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
2284 {
2285 StringExtractor bytes;
2286 if (mem_cache_dict->GetValueForKeyAsString("bytes", bytes.GetStringRef()))
2287 {
2288 bytes.SetFilePos(0);
2289
2290 const size_t byte_size = bytes.GetStringRef().size()/2;
2291 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2292 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2293 if (bytes_copied == byte_size)
2294 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2295 }
2296 }
2297 }
2298 }
2299 return true; // Keep iterating through all array items
2300 });
2301 }
2302
2303 }
Pavel Labath4a4bb122015-07-16 14:14:35 +00002304 else if (key == g_key_signal)
2305 signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002306 return true; // Keep iterating through all dictionary key/value pairs
2307 });
2308
Greg Clayton2e309072015-07-17 23:42:28 +00002309 return SetThreadStopInfo (tid,
2310 expedited_register_map,
2311 signo,
2312 thread_name,
2313 reason,
2314 description,
2315 exc_type,
2316 exc_data,
2317 thread_dispatch_qaddr,
2318 queue_vars_valid,
2319 queue_name,
2320 queue_kind,
2321 queue_serial);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002322}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002323
2324StateType
2325ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
2326{
Greg Claytondd0e5a52011-06-02 22:22:38 +00002327 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002328 const char stop_type = stop_packet.GetChar();
2329 switch (stop_type)
2330 {
2331 case 'T':
2332 case 'S':
2333 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00002334 // This is a bit of a hack, but is is required. If we did exec, we
2335 // need to clear our thread lists and also know to rebuild our dynamic
2336 // register info before we lookup and threads and populate the expedited
2337 // register values so we need to know this right away so we can cleanup
2338 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00002339 const uint32_t stop_id = GetStopID();
2340 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00002341 {
2342 // Our first stop, make sure we have a process ID, and also make
2343 // sure we know about our registers
2344 if (GetID() == LLDB_INVALID_PROCESS_ID)
2345 {
Greg Claytonc574ede2011-03-10 02:26:48 +00002346 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00002347 if (pid != LLDB_INVALID_PROCESS_ID)
2348 SetID (pid);
2349 }
2350 BuildDynamicRegisterInfo (true);
2351 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002352 // Stop with signal and thread info
Greg Clayton358cf1e2015-06-25 21:46:34 +00002353 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002354 const uint8_t signo = stop_packet.GetHexU8();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002355 std::string key;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002356 std::string value;
2357 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00002358 std::string reason;
2359 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002360 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00002361 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002362 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton0b90be12015-06-23 21:27:50 +00002363 bool queue_vars_valid = false; // says if locals below that start with "queue_" are valid
2364 std::string queue_name;
2365 QueueKind queue_kind = eQueueKindUnknown;
2366 uint64_t queue_serial = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002367 ExpeditedRegisterMap expedited_register_map;
2368 while (stop_packet.GetNameColonValue(key, value))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002369 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002370 if (key.compare("metype") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002371 {
2372 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002373 exc_type = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002374 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002375 else if (key.compare("medata") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002376 {
2377 // exception data in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002378 exc_data.push_back(StringConvert::ToUInt64 (value.c_str(), 0, 16));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002379 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002380 else if (key.compare("thread") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002381 {
2382 // thread in big endian hex
Greg Clayton358cf1e2015-06-25 21:46:34 +00002383 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002384 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002385 else if (key.compare("threads") == 0)
Greg Clayton9e920902012-04-10 02:25:43 +00002386 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002387 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00002388 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00002389 // A comma separated list of all threads in the current
2390 // process that includes the thread for this stop reply
2391 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00002392 size_t comma_pos;
2393 lldb::tid_t tid;
2394 while ((comma_pos = value.find(',')) != std::string::npos)
2395 {
2396 value[comma_pos] = '\0';
2397 // thread in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002398 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00002399 if (tid != LLDB_INVALID_THREAD_ID)
2400 m_thread_ids.push_back (tid);
2401 value.erase(0, comma_pos + 1);
Greg Clayton9e920902012-04-10 02:25:43 +00002402 }
Vince Harron5275aaa2015-01-15 20:08:35 +00002403 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00002404 if (tid != LLDB_INVALID_THREAD_ID)
2405 m_thread_ids.push_back (tid);
2406 }
Greg Clayton2e309072015-07-17 23:42:28 +00002407 else if (key.compare("jstopinfo") == 0)
Greg Claytona5801ad2015-07-15 22:59:03 +00002408 {
2409 StringExtractor json_extractor;
2410 // Swap "value" over into "name_extractor"
2411 json_extractor.GetStringRef().swap(value);
2412 // Now convert the HEX bytes into a string value
2413 json_extractor.GetHexByteString (value);
2414
2415 // This JSON contains thread IDs and thread stop info for all threads.
2416 // It doesn't contain expedited registers, memory or queue info.
Greg Clayton2e309072015-07-17 23:42:28 +00002417 m_jstopinfo_sp = StructuredData::ParseJSON (value);
Greg Claytona5801ad2015-07-15 22:59:03 +00002418 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002419 else if (key.compare("hexname") == 0)
Greg Claytonde9d0492011-01-08 03:17:57 +00002420 {
2421 StringExtractor name_extractor;
2422 // Swap "value" over into "name_extractor"
2423 name_extractor.GetStringRef().swap(value);
2424 // Now convert the HEX bytes into a string value
2425 name_extractor.GetHexByteString (value);
2426 thread_name.swap (value);
2427 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002428 else if (key.compare("name") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002429 {
2430 thread_name.swap (value);
2431 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002432 else if (key.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002433 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002434 thread_dispatch_qaddr = StringConvert::ToUInt64 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002435 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002436 else if (key.compare("qname") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002437 {
2438 queue_vars_valid = true;
2439 StringExtractor name_extractor;
2440 // Swap "value" over into "name_extractor"
2441 name_extractor.GetStringRef().swap(value);
2442 // Now convert the HEX bytes into a string value
2443 name_extractor.GetHexByteString (value);
2444 queue_name.swap (value);
2445 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002446 else if (key.compare("qkind") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002447 {
Greg Clayton0b90be12015-06-23 21:27:50 +00002448 if (value == "serial")
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002449 {
2450 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002451 queue_kind = eQueueKindSerial;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002452 }
Greg Clayton0b90be12015-06-23 21:27:50 +00002453 else if (value == "concurrent")
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002454 {
2455 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002456 queue_kind = eQueueKindConcurrent;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002457 }
Greg Clayton0b90be12015-06-23 21:27:50 +00002458 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002459 else if (key.compare("qserial") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002460 {
Greg Clayton0b90be12015-06-23 21:27:50 +00002461 queue_serial = StringConvert::ToUInt64 (value.c_str(), 0, 0);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002462 if (queue_serial != 0)
2463 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002464 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002465 else if (key.compare("reason") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002466 {
2467 reason.swap(value);
2468 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002469 else if (key.compare("description") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002470 {
2471 StringExtractor desc_extractor;
2472 // Swap "value" over into "name_extractor"
2473 desc_extractor.GetStringRef().swap(value);
2474 // Now convert the HEX bytes into a string value
Chaoren Lin28e57422015-02-03 01:51:25 +00002475 desc_extractor.GetHexByteString (value);
2476 description.swap(value);
Greg Claytona658fd22011-06-04 01:26:29 +00002477 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002478 else if (key.compare("memory") == 0)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002479 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002480 // Expedited memory. GDB servers can choose to send back expedited memory
2481 // that can populate the L1 memory cache in the process so that things like
2482 // the frame pointer backchain can be expedited. This will help stack
2483 // backtracing be more efficient by not having to send as many memory read
2484 // requests down the remote GDB server.
Chaoren Lin7a306082015-06-23 03:17:01 +00002485
Greg Clayton358cf1e2015-06-25 21:46:34 +00002486 // Key/value pair format: memory:<addr>=<bytes>;
2487 // <addr> is a number whose base will be interpreted by the prefix:
2488 // "0x[0-9a-fA-F]+" for hex
2489 // "0[0-7]+" for octal
2490 // "[1-9]+" for decimal
2491 // <bytes> is native endian ASCII hex bytes just like the register values
2492 llvm::StringRef value_ref(value);
2493 std::pair<llvm::StringRef, llvm::StringRef> pair;
2494 pair = value_ref.split('=');
2495 if (!pair.first.empty() && !pair.second.empty())
2496 {
2497 std::string addr_str(pair.first.str());
2498 const lldb::addr_t mem_cache_addr = StringConvert::ToUInt64(addr_str.c_str(), LLDB_INVALID_ADDRESS, 0);
2499 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002500 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002501 StringExtractor bytes;
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002502 bytes.GetStringRef() = pair.second.str();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002503 const size_t byte_size = bytes.GetStringRef().size()/2;
2504 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2505 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2506 if (bytes_copied == byte_size)
2507 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
Greg Clayton3e06bd92011-01-09 21:07:35 +00002508 }
2509 }
2510 }
Jaydeep Patil725666c2015-08-13 03:46:01 +00002511 else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 || key.compare("awatch") == 0)
2512 {
2513 // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2514 lldb::addr_t wp_addr = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
2515 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2516 uint32_t wp_index = LLDB_INVALID_INDEX32;
2517
2518 if (wp_sp)
2519 wp_index = wp_sp->GetHardwareIndex();
2520
2521 reason = "watchpoint";
2522 StreamString ostr;
2523 ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
2524 description = ostr.GetString().c_str();
2525 }
Stephane Sezer2618e912015-08-21 16:51:56 +00002526 else if (key.compare("library") == 0)
2527 {
2528 LoadModules();
2529 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002530 else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1]))
2531 {
2532 uint32_t reg = StringConvert::ToUInt32 (key.c_str(), UINT32_MAX, 16);
2533 if (reg != UINT32_MAX)
2534 expedited_register_map[reg] = std::move(value);
2535 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002536 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002537
Bhushan D. Attarde1e271df2015-07-24 04:06:20 +00002538 if (tid == LLDB_INVALID_THREAD_ID)
2539 {
2540 // A thread id may be invalid if the response is old style 'S' packet which does not provide the
2541 // thread information. So update the thread list and choose the first one.
2542 UpdateThreadIDList ();
2543
2544 if (!m_thread_ids.empty ())
2545 {
2546 tid = m_thread_ids.front ();
2547 }
2548 }
2549
Greg Clayton358cf1e2015-06-25 21:46:34 +00002550 ThreadSP thread_sp = SetThreadStopInfo (tid,
2551 expedited_register_map,
2552 signo,
2553 thread_name,
2554 reason,
2555 description,
2556 exc_type,
2557 exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002558 thread_dispatch_qaddr,
2559 queue_vars_valid,
2560 queue_name,
2561 queue_kind,
2562 queue_serial);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002563
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002564 return eStateStopped;
2565 }
2566 break;
2567
2568 case 'W':
Todd Fialaff6131a2014-05-19 04:57:23 +00002569 case 'X':
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002570 // process exited
2571 return eStateExited;
2572
2573 default:
2574 break;
2575 }
2576 return eStateInvalid;
2577}
2578
2579void
2580ProcessGDBRemote::RefreshStateAfterStop ()
2581{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002582 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00002583 m_thread_ids.clear();
2584 // Set the thread stop info. It might have a "threads" key whose value is
2585 // a list of all thread IDs in the current process, so m_thread_ids might
2586 // get set.
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002587
2588 // Scope for the lock
2589 {
2590 // Lock the thread stack while we access it
2591 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
2592 // Get the number of stop packets on the stack
2593 int nItems = m_stop_packet_stack.size();
2594 // Iterate over them
2595 for (int i = 0; i < nItems; i++)
2596 {
2597 // Get the thread stop info
2598 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2599 // Process thread stop info
2600 SetThreadStopInfo(stop_info);
2601 }
2602 // Clear the thread stop stack
2603 m_stop_packet_stack.clear();
2604 }
2605
Greg Clayton9e920902012-04-10 02:25:43 +00002606 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2607 if (m_thread_ids.empty())
2608 {
2609 // No, we need to fetch the thread list manually
2610 UpdateThreadIDList();
2611 }
2612
Ewan Crawford78baa192015-05-13 09:18:18 +00002613 // If we have queried for a default thread id
2614 if (m_initial_tid != LLDB_INVALID_THREAD_ID)
2615 {
2616 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2617 m_initial_tid = LLDB_INVALID_THREAD_ID;
2618 }
2619
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002620 // Let all threads recover from stopping and do any clean up based
2621 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002622 m_thread_list_real.RefreshStateAfterStop();
Greg Clayton9e920902012-04-10 02:25:43 +00002623
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002624}
2625
2626Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002627ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002628{
2629 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002630
Greg Clayton6ed95942011-01-22 07:12:45 +00002631 bool timed_out = false;
2632 Mutex::Locker locker;
Greg Clayton513c26c2011-01-29 07:10:55 +00002633
2634 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002635 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002636 // We are being asked to halt during an attach. We need to just close
2637 // our file handle and debugserver will go away, and we can be done...
2638 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00002639 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002640 else
2641 {
Greg Clayton2687cd12012-03-29 01:55:41 +00002642 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton513c26c2011-01-29 07:10:55 +00002643 {
2644 if (timed_out)
2645 error.SetErrorString("timed out sending interrupt packet");
2646 else
2647 error.SetErrorString("unknown error sending interrupt packet");
2648 }
Greg Clayton2687cd12012-03-29 01:55:41 +00002649
2650 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton513c26c2011-01-29 07:10:55 +00002651 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002652 return error;
2653}
2654
2655Error
Jim Inghamacff8952013-05-02 00:27:30 +00002656ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002657{
2658 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002659 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00002660 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00002661 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2662
Jim Inghamacff8952013-05-02 00:27:30 +00002663 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002664 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002665 {
Jim Inghamacff8952013-05-02 00:27:30 +00002666 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002667 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
2668 else
Jim Inghamacff8952013-05-02 00:27:30 +00002669 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00002670 }
Jim Inghamacff8952013-05-02 00:27:30 +00002671
2672 if (!error.Success())
2673 return error;
2674
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002675 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00002676 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002677
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002678 SetPrivateState (eStateDetached);
2679 ResumePrivateStateThread();
2680
2681 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00002682 return error;
2683}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002684
Jim Ingham43c555d2012-07-04 00:35:43 +00002685
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002686Error
2687ProcessGDBRemote::DoDestroy ()
2688{
2689 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002690 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002691 if (log)
2692 log->Printf ("ProcessGDBRemote::DoDestroy()");
2693
Jim Ingham43c555d2012-07-04 00:35:43 +00002694 // There is a bug in older iOS debugservers where they don't shut down the process
2695 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
2696 // this can cause problems with restarting. So we check to see if any of our threads are stopped
2697 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
2698 // destroy it again.
2699 //
2700 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
2701 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
2702 // the debugservers with this bug are equal. There really should be a better way to test this!
2703 //
2704 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
2705 // get called here to destroy again and we're still at a breakpoint or exception, then we should
2706 // just do the straight-forward kill.
2707 //
2708 // And of course, if we weren't able to stop the process by the time we get here, it isn't
2709 // necessary (or helpful) to do any of this.
2710
2711 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
2712 {
2713 PlatformSP platform_sp = GetTarget().GetPlatform();
2714
2715 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2716 if (platform_sp
2717 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00002718 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00002719 {
2720 if (m_destroy_tried_resuming)
2721 {
2722 if (log)
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002723 log->PutCString ("ProcessGDBRemote::DoDestroy() - Tried resuming to destroy once already, not doing it again.");
Jim Ingham43c555d2012-07-04 00:35:43 +00002724 }
2725 else
2726 {
2727 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
2728 // but we really need it to happen here and it doesn't matter if we do it twice.
2729 m_thread_list.DiscardThreadPlans();
2730 DisableAllBreakpointSites();
2731
2732 bool stop_looks_like_crash = false;
2733 ThreadList &threads = GetThreadList();
2734
2735 {
Jim Ingham45350372012-09-11 00:08:52 +00002736 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002737
2738 size_t num_threads = threads.GetSize();
2739 for (size_t i = 0; i < num_threads; i++)
2740 {
2741 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002742 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002743 StopReason reason = eStopReasonInvalid;
2744 if (stop_info_sp)
2745 reason = stop_info_sp->GetStopReason();
2746 if (reason == eStopReasonBreakpoint
2747 || reason == eStopReasonException)
2748 {
2749 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002750 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
2751 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00002752 stop_info_sp->GetDescription());
2753 stop_looks_like_crash = true;
2754 break;
2755 }
2756 }
2757 }
2758
2759 if (stop_looks_like_crash)
2760 {
2761 if (log)
2762 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
2763 m_destroy_tried_resuming = true;
2764
2765 // If we are going to run again before killing, it would be good to suspend all the threads
2766 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
2767 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
2768 // have to run the risk of letting those threads proceed a bit.
2769
2770 {
Jim Ingham45350372012-09-11 00:08:52 +00002771 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002772
2773 size_t num_threads = threads.GetSize();
2774 for (size_t i = 0; i < num_threads; i++)
2775 {
2776 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002777 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002778 StopReason reason = eStopReasonInvalid;
2779 if (stop_info_sp)
2780 reason = stop_info_sp->GetStopReason();
2781 if (reason != eStopReasonBreakpoint
2782 && reason != eStopReasonException)
2783 {
2784 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002785 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
2786 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00002787 thread_sp->SetResumeState(eStateSuspended);
2788 }
2789 }
2790 }
2791 Resume ();
Jason Molendaede31932015-04-17 05:01:58 +00002792 return Destroy(false);
Jim Ingham43c555d2012-07-04 00:35:43 +00002793 }
2794 }
2795 }
2796 }
2797
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002798 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00002799 int exit_status = SIGABRT;
2800 std::string exit_string;
2801
Greg Clayton6ed95942011-01-22 07:12:45 +00002802 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002803 {
Jim Inghamaab78372011-10-28 01:11:35 +00002804 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00002805 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002806 StringExtractorGDBRemote response;
2807 bool send_async = true;
Tamas Berghammer912800c2015-02-24 10:23:39 +00002808 GDBRemoteCommunication::ScopedTimeout (m_gdb_comm, 3);
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002809
Greg Clayton3dedae12013-12-06 21:45:27 +00002810 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton513c26c2011-01-29 07:10:55 +00002811 {
2812 char packet_cmd = response.GetChar(0);
2813
2814 if (packet_cmd == 'W' || packet_cmd == 'X')
2815 {
Jim Inghameac0aa42014-02-21 22:36:11 +00002816#if defined(__APPLE__)
Jim Ingham9d67cc52014-02-21 22:35:29 +00002817 // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off
2818 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill
2819 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns
2820 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap
2821 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of
2822 // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2823 // Anyway, so call waitpid here to finally reap it.
2824 PlatformSP platform_sp(GetTarget().GetPlatform());
2825 if (platform_sp && platform_sp->IsHost())
2826 {
2827 int status;
2828 ::pid_t reap_pid;
2829 reap_pid = waitpid (GetID(), &status, WNOHANG);
2830 if (log)
2831 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2832 }
2833#endif
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002834 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002835 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00002836 exit_status = response.GetHexU8();
2837 }
2838 else
2839 {
2840 if (log)
2841 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2842 exit_string.assign("got unexpected response to k packet: ");
2843 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00002844 }
2845 }
2846 else
2847 {
Jim Inghambabfc382012-06-06 00:32:39 +00002848 if (log)
2849 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2850 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00002851 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002852 }
Jim Inghambabfc382012-06-06 00:32:39 +00002853 else
2854 {
2855 if (log)
Ed Masteb3a53332014-03-17 17:05:22 +00002856 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching");
Jim Inghamcfc09352012-07-27 23:57:19 +00002857 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00002858 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002859 }
Jim Inghambabfc382012-06-06 00:32:39 +00002860 else
2861 {
2862 // If we missed setting the exit status on the way out, do it here.
2863 // NB set exit status can be called multiple times, the first one sets the status.
2864 exit_string.assign("destroying when not connected to debugserver");
2865 }
2866
2867 SetExitStatus(exit_status, exit_string.c_str());
2868
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002869 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002870 KillDebugserverProcess ();
2871 return error;
2872}
2873
Greg Clayton8cda7f02013-05-21 21:55:59 +00002874void
2875ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2876{
Greg Clayton8cda7f02013-05-21 21:55:59 +00002877 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2878 if (did_exec)
2879 {
2880 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2881 if (log)
2882 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2883
2884 m_thread_list_real.Clear();
2885 m_thread_list.Clear();
2886 BuildDynamicRegisterInfo (true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002887 m_gdb_comm.ResetDiscoverableSettings (did_exec);
Greg Clayton8cda7f02013-05-21 21:55:59 +00002888 }
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002889
2890 // Scope the lock
2891 {
2892 // Lock the thread stack while we access it
2893 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
Greg Clayton2e309072015-07-17 23:42:28 +00002894
2895 // We are are not using non-stop mode, there can only be one last stop
2896 // reply packet, so clear the list.
2897 if (GetTarget().GetNonStopModeEnabled() == false)
2898 m_stop_packet_stack.clear();
2899
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002900 // Add this stop packet to the stop packet stack
2901 // This stack will get popped and examined when we switch to the
2902 // Stopped state
2903 m_stop_packet_stack.push_back(response);
2904 }
Greg Clayton8cda7f02013-05-21 21:55:59 +00002905}
2906
Chaoren Linc963a222015-09-01 16:58:45 +00002907void
2908ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp)
2909{
2910 Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
2911}
2912
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002913//------------------------------------------------------------------
2914// Process Queries
2915//------------------------------------------------------------------
2916
2917bool
2918ProcessGDBRemote::IsAlive ()
2919{
Greg Clayton10177aa2010-12-08 05:08:21 +00002920 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002921}
2922
2923addr_t
2924ProcessGDBRemote::GetImageInfoAddress()
2925{
Aidan Doddsc0c83852015-05-08 09:36:31 +00002926 // request the link map address via the $qShlibInfoAddr packet
2927 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2928
2929 // the loaded module list can also provides a link map address
2930 if (addr == LLDB_INVALID_ADDRESS)
2931 {
2932 GDBLoadedModuleInfoList list;
2933 if (GetLoadedModuleList (list).Success())
2934 addr = list.m_link_map;
2935 }
2936
2937 return addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002938}
2939
Greg Clayton2e309072015-07-17 23:42:28 +00002940void
2941ProcessGDBRemote::WillPublicStop ()
2942{
2943 // See if the GDB remote client supports the JSON threads info.
2944 // If so, we gather stop info for all threads, expedited registers,
2945 // expedited memory, runtime queue information (iOS and MacOSX only),
2946 // and more. Expediting memory will help stack backtracing be much
2947 // faster. Expediting registers will make sure we don't have to read
2948 // the thread registers for GPRs.
2949 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
2950
2951 if (m_jthreadsinfo_sp)
2952 {
2953 // Now set the stop info for each thread and also expedite any registers
2954 // and memory that was in the jThreadsInfo response.
2955 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
2956 if (thread_infos)
2957 {
2958 const size_t n = thread_infos->GetSize();
2959 for (size_t i=0; i<n; ++i)
2960 {
2961 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
2962 if (thread_dict)
2963 SetThreadStopInfo(thread_dict);
2964 }
2965 }
2966 }
2967}
2968
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002969//------------------------------------------------------------------
2970// Process Memory
2971//------------------------------------------------------------------
2972size_t
2973ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2974{
Jason Molenda6076bf42014-05-06 04:34:52 +00002975 GetMaxMemorySize ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002976 if (size > m_max_memory_size)
2977 {
2978 // Keep memory read sizes down to a sane limit. This function will be
2979 // called multiple times in order to complete the task by
2980 // lldb_private::Process so it is ok to do this.
2981 size = m_max_memory_size;
2982 }
2983
2984 char packet[64];
Jason Molenda6076bf42014-05-06 04:34:52 +00002985 int packet_len;
2986 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2987 if (binary_memory_read)
2988 {
2989 packet_len = ::snprintf (packet, sizeof(packet), "x0x%" PRIx64 ",0x%" PRIx64, (uint64_t)addr, (uint64_t)size);
2990 }
2991 else
2992 {
2993 packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
2994 }
Andy Gibbsa297a972013-06-19 19:04:53 +00002995 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002996 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002997 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002998 {
Greg Clayton576d8832011-03-22 04:00:09 +00002999 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003000 {
3001 error.Clear();
Jason Molenda6076bf42014-05-06 04:34:52 +00003002 if (binary_memory_read)
3003 {
3004 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any
3005 // 0x7d character escaping that was present in the packet
3006
3007 size_t data_received_size = response.GetBytesLeft();
3008 if (data_received_size > size)
3009 {
3010 // Don't write past the end of BUF if the remote debug server gave us too
3011 // much data for some reason.
3012 data_received_size = size;
3013 }
3014 memcpy (buf, response.GetStringRef().data(), data_received_size);
3015 return data_received_size;
3016 }
3017 else
3018 {
3019 return response.GetHexBytes(buf, size, '\xdd');
3020 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003021 }
Greg Clayton576d8832011-03-22 04:00:09 +00003022 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00003023 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00003024 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00003025 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003026 else
Greg Clayton9944cd72012-09-19 01:46:31 +00003027 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003028 }
3029 else
3030 {
Jim Ingham35579dd2013-06-03 19:34:01 +00003031 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003032 }
3033 return 0;
3034}
3035
3036size_t
3037ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
3038{
Jason Molenda6076bf42014-05-06 04:34:52 +00003039 GetMaxMemorySize ();
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00003040 if (size > m_max_memory_size)
3041 {
3042 // Keep memory read sizes down to a sane limit. This function will be
3043 // called multiple times in order to complete the task by
3044 // lldb_private::Process so it is ok to do this.
3045 size = m_max_memory_size;
3046 }
3047
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003048 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00003049 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Clayton7fb56d02011-02-01 01:31:41 +00003050 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003051 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003052 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003053 {
Greg Clayton576d8832011-03-22 04:00:09 +00003054 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003055 {
3056 error.Clear();
3057 return size;
3058 }
Greg Clayton576d8832011-03-22 04:00:09 +00003059 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00003060 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00003061 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00003062 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003063 else
Greg Clayton9944cd72012-09-19 01:46:31 +00003064 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 +00003065 }
3066 else
3067 {
Jim Ingham35579dd2013-06-03 19:34:01 +00003068 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003069 }
3070 return 0;
3071}
3072
3073lldb::addr_t
3074ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
3075{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003076 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_EXPRESSIONS));
Greg Clayton2a48f522011-05-14 01:50:35 +00003077 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
3078
Greg Clayton70b57652011-05-15 01:25:55 +00003079 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton2a48f522011-05-14 01:50:35 +00003080 switch (supported)
3081 {
3082 case eLazyBoolCalculate:
3083 case eLazyBoolYes:
3084 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
3085 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
3086 return allocated_addr;
3087
3088 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003089 // Call mmap() to create memory in the inferior..
3090 unsigned prot = 0;
3091 if (permissions & lldb::ePermissionsReadable)
3092 prot |= eMmapProtRead;
3093 if (permissions & lldb::ePermissionsWritable)
3094 prot |= eMmapProtWrite;
3095 if (permissions & lldb::ePermissionsExecutable)
3096 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00003097
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003098 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
3099 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
3100 m_addr_to_mmap_size[allocated_addr] = size;
3101 else
Todd Fialaaf245d12014-06-30 21:05:18 +00003102 {
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003103 allocated_addr = LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00003104 if (log)
3105 log->Printf ("ProcessGDBRemote::%s no direct stub support for memory allocation, and InferiorCallMmap also failed - is stub missing register context save/restore capability?", __FUNCTION__);
3106 }
Greg Clayton2a48f522011-05-14 01:50:35 +00003107 break;
3108 }
3109
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003110 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00003111 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003112 else
3113 error.Clear();
3114 return allocated_addr;
3115}
3116
3117Error
Greg Clayton46fb5582011-11-18 07:03:08 +00003118ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
3119 MemoryRegionInfo &region_info)
3120{
3121
3122 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
3123 return error;
3124}
3125
3126Error
Johnny Chen64637202012-05-23 21:09:52 +00003127ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
3128{
3129
3130 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
3131 return error;
3132}
3133
3134Error
Enrico Granataf04a2192012-07-13 23:18:48 +00003135ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
3136{
Jaydeep Patil725666c2015-08-13 03:46:01 +00003137 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after, GetTarget().GetArchitecture()));
Enrico Granataf04a2192012-07-13 23:18:48 +00003138 return error;
3139}
3140
3141Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003142ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
3143{
3144 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00003145 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
3146
3147 switch (supported)
3148 {
3149 case eLazyBoolCalculate:
3150 // We should never be deallocating memory without allocating memory
3151 // first so we should never get eLazyBoolCalculate
3152 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
3153 break;
3154
3155 case eLazyBoolYes:
3156 if (!m_gdb_comm.DeallocateMemory (addr))
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 break;
3159
3160 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003161 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00003162 {
3163 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003164 if (pos != m_addr_to_mmap_size.end() &&
3165 InferiorCallMunmap(this, addr, pos->second))
3166 m_addr_to_mmap_size.erase (pos);
3167 else
Daniel Malead01b2952012-11-29 21:49:15 +00003168 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003169 }
3170 break;
3171 }
3172
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003173 return error;
3174}
3175
3176
3177//------------------------------------------------------------------
3178// Process STDIO
3179//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003180size_t
3181ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
3182{
3183 if (m_stdio_communication.IsConnected())
3184 {
3185 ConnectionStatus status;
3186 m_stdio_communication.Write(src, src_len, status, NULL);
3187 }
Vince Harrondf3f00f2015-02-10 21:09:04 +00003188 else if (m_stdin_forward)
Vince Harrone0be4252015-02-06 18:32:57 +00003189 {
3190 m_gdb_comm.SendStdinNotification(src, src_len);
3191 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003192 return 0;
3193}
3194
3195Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003196ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003197{
3198 Error error;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003199 assert(bp_site != NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003200
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003201 // Get logging info
3202 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003203 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003204
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003205 // Get the breakpoint address
3206 const addr_t addr = bp_site->GetLoadAddress();
3207
3208 // Log that a breakpoint was requested
3209 if (log)
3210 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
3211
3212 // Breakpoint already exists and is enabled
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003213 if (bp_site->IsEnabled())
3214 {
3215 if (log)
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003216 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 +00003217 return error;
3218 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003219
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003220 // Get the software breakpoint trap opcode size
3221 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3222
3223 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
3224 // is supported by the remote stub. These are set to true by default, and later set to false
3225 // only after we receive an unimplemented response when sending a breakpoint packet. This means
3226 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
3227 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
3228 // indicates if the user specifically asked for hardware breakpoints. If true then we will
3229 // skip over software breakpoints.
3230 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
3231 {
3232 // Try to send off a software breakpoint packet ($Z0)
3233 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003234 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003235 // The breakpoint was placed successfully
3236 bp_site->SetEnabled(true);
3237 bp_site->SetType(BreakpointSite::eExternal);
Greg Claytoneb023e72013-10-11 19:48:25 +00003238 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003239 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003240
3241 // SendGDBStoppointTypePacket() will return an error if it was unable to set this
3242 // breakpoint. We need to differentiate between a error specific to placing this breakpoint
3243 // or if we have learned that this breakpoint type is unsupported. To do this, we
3244 // must test the support boolean for this breakpoint type to see if it now indicates that
3245 // this breakpoint type is unsupported. If they are still supported then we should return
3246 // with the error code. If they are now unsupported, then we would like to fall through
3247 // and try another form of breakpoint.
3248 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
3249 return error;
3250
3251 // We reach here when software breakpoints have been found to be unsupported. For future
3252 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
3253 // known not to be supported.
3254 if (log)
3255 log->Printf("Software breakpoints are unsupported");
3256
3257 // So we will fall through and try a hardware breakpoint
3258 }
3259
3260 // The process of setting a hardware breakpoint is much the same as above. We check the
3261 // supported boolean for this breakpoint type, and if it is thought to be supported then we
3262 // will try to set this breakpoint with a hardware breakpoint.
3263 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3264 {
3265 // Try to send off a hardware breakpoint packet ($Z1)
3266 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003267 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003268 // The breakpoint was placed successfully
3269 bp_site->SetEnabled(true);
3270 bp_site->SetType(BreakpointSite::eHardware);
3271 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003272 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003273
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003274 // Check if the error was something other then an unsupported breakpoint type
3275 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3276 {
3277 // Unable to set this hardware breakpoint
3278 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
3279 return error;
3280 }
3281
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003282 // We will reach here when the stub gives an unsupported response to a hardware breakpoint
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003283 if (log)
3284 log->Printf("Hardware breakpoints are unsupported");
3285
3286 // Finally we will falling through to a #trap style breakpoint
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003287 }
3288
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003289 // Don't fall through when hardware breakpoints were specifically requested
3290 if (bp_site->HardwareRequired())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003291 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003292 error.SetErrorString("hardware breakpoints are not supported");
3293 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003294 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003295
3296 // As a last resort we want to place a manual breakpoint. An instruction
3297 // is placed into the process memory using memory write packets.
3298 return EnableSoftwareBreakpoint(bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003299}
3300
3301Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003302ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003303{
3304 Error error;
3305 assert (bp_site != NULL);
3306 addr_t addr = bp_site->GetLoadAddress();
3307 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00003308 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003309 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003310 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003311
3312 if (bp_site->IsEnabled())
3313 {
3314 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
3315
Greg Clayton8b82f082011-04-12 05:54:46 +00003316 BreakpointSite::Type bp_type = bp_site->GetType();
3317 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003318 {
Greg Clayton8b82f082011-04-12 05:54:46 +00003319 case BreakpointSite::eSoftware:
3320 error = DisableSoftwareBreakpoint (bp_site);
3321 break;
3322
3323 case BreakpointSite::eHardware:
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003324 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003325 error.SetErrorToGenericError();
3326 break;
3327
3328 case BreakpointSite::eExternal:
Jim Inghama04ef752014-03-07 11:18:02 +00003329 {
3330 GDBStoppointType stoppoint_type;
3331 if (bp_site->IsHardware())
3332 stoppoint_type = eBreakpointHardware;
3333 else
3334 stoppoint_type = eBreakpointSoftware;
3335
3336 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003337 error.SetErrorToGenericError();
Jim Inghama04ef752014-03-07 11:18:02 +00003338 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003339 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003340 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003341 if (error.Success())
3342 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003343 }
3344 else
3345 {
3346 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003347 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 +00003348 return error;
3349 }
3350
3351 if (error.Success())
3352 error.SetErrorToGenericError();
3353 return error;
3354}
3355
Johnny Chen11309a32011-09-06 22:38:36 +00003356// Pre-requisite: wp != NULL.
3357static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00003358GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00003359{
3360 assert(wp);
3361 bool watch_read = wp->WatchpointRead();
3362 bool watch_write = wp->WatchpointWrite();
3363
3364 // watch_read and watch_write cannot both be false.
3365 assert(watch_read || watch_write);
3366 if (watch_read && watch_write)
3367 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00003368 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00003369 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00003370 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00003371 return eWatchpointWrite;
3372}
3373
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003374Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003375ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003376{
3377 Error error;
3378 if (wp)
3379 {
3380 user_id_t watchID = wp->GetID();
3381 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00003382 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003383 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003384 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003385 if (wp->IsEnabled())
3386 {
3387 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003388 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 +00003389 return error;
3390 }
Johnny Chen11309a32011-09-06 22:38:36 +00003391
3392 GDBStoppointType type = GetGDBStoppointType(wp);
3393 // Pass down an appropriate z/Z packet...
3394 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003395 {
Johnny Chen11309a32011-09-06 22:38:36 +00003396 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
3397 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003398 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003399 return error;
3400 }
3401 else
3402 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003403 }
Johnny Chen11309a32011-09-06 22:38:36 +00003404 else
3405 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003406 }
3407 else
3408 {
Johnny Chen01a67862011-10-14 00:42:25 +00003409 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003410 }
3411 if (error.Success())
3412 error.SetErrorToGenericError();
3413 return error;
3414}
3415
3416Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003417ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003418{
3419 Error error;
3420 if (wp)
3421 {
3422 user_id_t watchID = wp->GetID();
3423
Greg Clayton5160ce52013-03-27 23:08:40 +00003424 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003425
3426 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00003427
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003428 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003429 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003430
Johnny Chen11309a32011-09-06 22:38:36 +00003431 if (!wp->IsEnabled())
3432 {
3433 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003434 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 +00003435 // See also 'class WatchpointSentry' within StopInfo.cpp.
3436 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
3437 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00003438 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003439 return error;
3440 }
3441
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003442 if (wp->IsHardware())
3443 {
Johnny Chen11309a32011-09-06 22:38:36 +00003444 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003445 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00003446 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
3447 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003448 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003449 return error;
3450 }
3451 else
3452 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003453 }
3454 // TODO: clear software watchpoints if we implement them
3455 }
3456 else
3457 {
Johnny Chen01a67862011-10-14 00:42:25 +00003458 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003459 }
3460 if (error.Success())
3461 error.SetErrorToGenericError();
3462 return error;
3463}
3464
3465void
3466ProcessGDBRemote::Clear()
3467{
3468 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00003469 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003470 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003471}
3472
3473Error
3474ProcessGDBRemote::DoSignal (int signo)
3475{
3476 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00003477 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003478 if (log)
3479 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
3480
3481 if (!m_gdb_comm.SendAsyncSignal (signo))
3482 error.SetErrorStringWithFormat("failed to send signal %i", signo);
3483 return error;
3484}
3485
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003486Error
Greg Clayton91a9b2472013-12-04 19:19:12 +00003487ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003488{
3489 Error error;
3490 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
3491 {
3492 // If we locate debugserver, keep that located version around
3493 static FileSpec g_debugserver_file_spec;
3494
Han Ming Ong84647042012-02-25 01:07:38 +00003495 ProcessLaunchInfo debugserver_launch_info;
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00003496 // Make debugserver run in its own session so signals generated by
3497 // special terminal key sequences (^C) don't affect debugserver.
3498 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3499
Greg Clayton91a9b2472013-12-04 19:19:12 +00003500 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
3501 debugserver_launch_info.SetUserID(process_info.GetUserID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003502
Todd Fiala013434e2014-07-09 01:29:05 +00003503#if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__) || defined (__aarch64__))
Greg Claytonfda4fab2014-01-10 22:24:11 +00003504 // On iOS, still do a local connection using a random port
Greg Clayton16810922014-02-27 19:38:18 +00003505 const char *hostname = "127.0.0.1";
Greg Claytonfda4fab2014-01-10 22:24:11 +00003506 uint16_t port = get_random_port ();
3507#else
3508 // Set hostname being NULL to do the reverse connect where debugserver
3509 // will bind to port zero and it will communicate back to us the port
3510 // that we will connect to
3511 const char *hostname = NULL;
3512 uint16_t port = 0;
3513#endif
3514
3515 error = m_gdb_comm.StartDebugserverProcess (hostname,
3516 port,
Greg Clayton00fe87b2013-12-05 22:58:22 +00003517 debugserver_launch_info,
3518 port);
Greg Clayton91a9b2472013-12-04 19:19:12 +00003519
3520 if (error.Success ())
3521 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003522 else
Greg Clayton91a9b2472013-12-04 19:19:12 +00003523 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003524
3525 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3526 StartAsyncThread ();
Greg Clayton91a9b2472013-12-04 19:19:12 +00003527
3528 if (error.Fail())
3529 {
3530 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
3531
3532 if (log)
3533 log->Printf("failed to start debugserver process: %s", error.AsCString());
3534 return error;
3535 }
3536
Greg Clayton00fe87b2013-12-05 22:58:22 +00003537 if (m_gdb_comm.IsConnected())
3538 {
3539 // Finish the connection process by doing the handshake without connecting (send NULL URL)
3540 ConnectToDebugserver (NULL);
3541 }
3542 else
3543 {
Greg Claytonfda4fab2014-01-10 22:24:11 +00003544 StreamString connect_url;
3545 connect_url.Printf("connect://%s:%u", hostname, port);
3546 error = ConnectToDebugserver (connect_url.GetString().c_str());
Greg Clayton00fe87b2013-12-05 22:58:22 +00003547 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00003548
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003549 }
3550 return error;
3551}
3552
3553bool
3554ProcessGDBRemote::MonitorDebugserverProcess
3555(
3556 void *callback_baton,
3557 lldb::pid_t debugserver_pid,
Greg Claytone4e45922011-11-16 05:37:56 +00003558 bool exited, // True if the process did exit
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003559 int signo, // Zero for no signal
3560 int exit_status // Exit value of process if signal is zero
3561)
3562{
Greg Claytone4e45922011-11-16 05:37:56 +00003563 // The baton is a "ProcessGDBRemote *". Now this class might be gone
3564 // and might not exist anymore, so we need to carefully try to get the
3565 // target for this process first since we have a race condition when
3566 // we are done running between getting the notice that the inferior
3567 // process has died and the debugserver that was debugging this process.
3568 // In our test suite, we are also continually running process after
3569 // process, so we must be very careful to make sure:
3570 // 1 - process object hasn't been deleted already
3571 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003572
3573 // "debugserver_pid" argument passed in is the process ID for
3574 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00003575 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003576
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003577 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton6779606a2011-01-22 23:43:18 +00003578
Greg Claytone4e45922011-11-16 05:37:56 +00003579 // Get a shared pointer to the target that has a matching process pointer.
3580 // This target could be gone, or the target could already have a new process
3581 // object inside of it
3582 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
3583
Greg Clayton6779606a2011-01-22 23:43:18 +00003584 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003585 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 +00003586
Greg Claytone4e45922011-11-16 05:37:56 +00003587 if (target_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003588 {
Greg Claytone4e45922011-11-16 05:37:56 +00003589 // We found a process in a target that matches, but another thread
3590 // might be in the process of launching a new process that will
3591 // soon replace it, so get a shared pointer to the process so we
3592 // can keep it alive.
3593 ProcessSP process_sp (target_sp->GetProcessSP());
3594 // Now we have a shared pointer to the process that can't go away on us
3595 // so we now make sure it was the same as the one passed in, and also make
3596 // sure that our previous "process *" didn't get deleted and have a new
3597 // "process *" created in its place with the same pointer. To verify this
3598 // we make sure the process has our debugserver process ID. If we pass all
3599 // of these tests, then we are sure that this process is the one we were
3600 // looking for.
3601 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003602 {
Greg Claytone4e45922011-11-16 05:37:56 +00003603 // Sleep for a half a second to make sure our inferior process has
3604 // time to set its exit status before we set it incorrectly when
3605 // both the debugserver and the inferior process shut down.
3606 usleep (500000);
3607 // If our process hasn't yet exited, debugserver might have died.
3608 // If the process did exit, the we are reaping it.
3609 const StateType state = process->GetState();
3610
3611 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
3612 state != eStateInvalid &&
3613 state != eStateUnloaded &&
3614 state != eStateExited &&
3615 state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003616 {
Greg Claytone4e45922011-11-16 05:37:56 +00003617 char error_str[1024];
3618 if (signo)
3619 {
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00003620 const char *signal_cstr = process->GetUnixSignals()->GetSignalAsCString(signo);
Greg Claytone4e45922011-11-16 05:37:56 +00003621 if (signal_cstr)
3622 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3623 else
3624 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
3625 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003626 else
Greg Claytone4e45922011-11-16 05:37:56 +00003627 {
3628 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
3629 }
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003630
Greg Claytone4e45922011-11-16 05:37:56 +00003631 process->SetExitStatus (-1, error_str);
3632 }
3633 // Debugserver has exited we need to let our ProcessGDBRemote
3634 // know that it no longer has a debugserver instance
3635 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003636 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003637 }
3638 return true;
3639}
3640
3641void
3642ProcessGDBRemote::KillDebugserverProcess ()
3643{
Greg Claytonfbb76342013-11-20 21:07:01 +00003644 m_gdb_comm.Disconnect();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003645 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3646 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003647 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003648 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3649 }
3650}
3651
3652void
3653ProcessGDBRemote::Initialize()
3654{
Davide Italianoc8d69822015-04-03 04:24:32 +00003655 static std::once_flag g_once_flag;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003656
Davide Italianoc8d69822015-04-03 04:24:32 +00003657 std::call_once(g_once_flag, []()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003658 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003659 PluginManager::RegisterPlugin (GetPluginNameStatic(),
3660 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00003661 CreateInstance,
3662 DebuggerInitialize);
Davide Italianoc8d69822015-04-03 04:24:32 +00003663 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003664}
3665
Greg Clayton7f982402013-07-15 22:54:20 +00003666void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003667ProcessGDBRemote::DebuggerInitialize (Debugger &debugger)
Greg Clayton7f982402013-07-15 22:54:20 +00003668{
3669 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
3670 {
3671 const bool is_global_setting = true;
3672 PluginManager::CreateSettingForProcessPlugin (debugger,
3673 GetGlobalPluginProperties()->GetValueProperties(),
3674 ConstString ("Properties for the gdb-remote process plug-in."),
3675 is_global_setting);
3676 }
3677}
3678
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003679bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003680ProcessGDBRemote::StartAsyncThread ()
3681{
Greg Clayton5160ce52013-03-27 23:08:40 +00003682 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003683
3684 if (log)
3685 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003686
3687 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003688 if (!m_async_thread.IsJoinable())
Jim Ingham455fa5c2012-11-01 01:15:33 +00003689 {
3690 // Create a thread that watches our internal state and controls which
3691 // events make it to clients (into the DCProcess event queue).
Zachary Turner39de3112014-09-09 20:54:56 +00003692
3693 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003694 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003695 else if (log)
3696 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was already running.", __FUNCTION__);
Zachary Turner39de3112014-09-09 20:54:56 +00003697
Zachary Turneracee96a2014-09-23 18:32:09 +00003698 return m_async_thread.IsJoinable();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003699}
3700
3701void
3702ProcessGDBRemote::StopAsyncThread ()
3703{
Greg Clayton5160ce52013-03-27 23:08:40 +00003704 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003705
3706 if (log)
3707 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
3708
Jim Ingham455fa5c2012-11-01 01:15:33 +00003709 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003710 if (m_async_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003711 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00003712 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
3713
3714 // This will shut down the async thread.
3715 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3716
3717 // Stop the stdio thread
Zachary Turner39de3112014-09-09 20:54:56 +00003718 m_async_thread.Join(nullptr);
Pavel Labatha55a9532015-03-11 09:53:42 +00003719 m_async_thread.Reset();
Jim Ingham455fa5c2012-11-01 01:15:33 +00003720 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003721 else if (log)
3722 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003723}
3724
Ewan Crawford76df2882015-06-23 12:32:06 +00003725bool
3726ProcessGDBRemote::HandleNotifyPacket (StringExtractorGDBRemote &packet)
3727{
3728 // get the packet at a string
3729 const std::string &pkt = packet.GetStringRef();
3730 // skip %stop:
3731 StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
3732
3733 // pass as a thread stop info packet
3734 SetLastStopPacket(stop_info);
3735
3736 // check for more stop reasons
3737 HandleStopReplySequence();
3738
3739 // if the process is stopped then we need to fake a resume
3740 // so that we can stop properly with the new break. This
3741 // is possible due to SetPrivateState() broadcasting the
3742 // state change as a side effect.
3743 if (GetPrivateState() == lldb::StateType::eStateStopped)
3744 {
3745 SetPrivateState(lldb::StateType::eStateRunning);
3746 }
3747
3748 // since we have some stopped packets we can halt the process
3749 SetPrivateState(lldb::StateType::eStateStopped);
3750
3751 return true;
3752}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003753
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003754thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003755ProcessGDBRemote::AsyncThread (void *arg)
3756{
3757 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
3758
Greg Clayton5160ce52013-03-27 23:08:40 +00003759 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003760 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003761 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003762
3763 Listener listener ("ProcessGDBRemote::AsyncThread");
3764 EventSP event_sp;
3765 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
3766 eBroadcastBitAsyncThreadShouldExit;
3767
3768 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
3769 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003770 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit |
3771 GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify);
3772
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003773 bool done = false;
3774 while (!done)
3775 {
3776 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003777 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003778 if (listener.WaitForEvent (NULL, event_sp))
3779 {
3780 const uint32_t event_type = event_sp->GetType();
Greg Clayton71337622011-02-24 22:24:29 +00003781 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003782 {
Greg Clayton71337622011-02-24 22:24:29 +00003783 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003784 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 +00003785
Greg Clayton71337622011-02-24 22:24:29 +00003786 switch (event_type)
3787 {
3788 case eBroadcastBitAsyncContinue:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003789 {
Greg Clayton71337622011-02-24 22:24:29 +00003790 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003791
Greg Clayton71337622011-02-24 22:24:29 +00003792 if (continue_packet)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003793 {
Greg Clayton71337622011-02-24 22:24:29 +00003794 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
3795 const size_t continue_cstr_len = continue_packet->GetByteSize ();
3796 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003797 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003798
Greg Clayton71337622011-02-24 22:24:29 +00003799 if (::strstr (continue_cstr, "vAttach") == NULL)
3800 process->SetPrivateState(eStateRunning);
3801 StringExtractorGDBRemote response;
Ewan Crawford76df2882015-06-23 12:32:06 +00003802
3803 // If in Non-Stop-Mode
3804 if (process->GetTarget().GetNonStopModeEnabled())
Greg Clayton71337622011-02-24 22:24:29 +00003805 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003806 // send the vCont packet
3807 if (!process->GetGDBRemote().SendvContPacket(process, continue_cstr, continue_cstr_len, response))
Jason Molendaa3329782014-03-29 18:54:20 +00003808 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003809 // Something went wrong
3810 done = true;
3811 break;
3812 }
3813 }
3814 // If in All-Stop-Mode
3815 else
3816 {
3817 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
3818
3819 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
3820 // The thread ID list might be contained within the "response", or the stop reply packet that
3821 // caused the stop. So clear it now before we give the stop reply packet to the process
3822 // using the process->SetLastStopPacket()...
3823 process->ClearThreadIDList ();
3824
3825 switch (stop_state)
3826 {
3827 case eStateStopped:
3828 case eStateCrashed:
3829 case eStateSuspended:
3830 process->SetLastStopPacket (response);
3831 process->SetPrivateState (stop_state);
3832 break;
3833
3834 case eStateExited:
3835 {
3836 process->SetLastStopPacket (response);
3837 process->ClearThreadIDList();
3838 response.SetFilePos(1);
3839
3840 int exit_status = response.GetHexU8();
3841 const char *desc_cstr = NULL;
3842 StringExtractor extractor;
3843 std::string desc_string;
3844 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';')
Jason Molendaa3329782014-03-29 18:54:20 +00003845 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003846 std::string desc_token;
3847 while (response.GetNameColonValue (desc_token, desc_string))
Jason Molendaa3329782014-03-29 18:54:20 +00003848 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003849 if (desc_token == "description")
3850 {
3851 extractor.GetStringRef().swap(desc_string);
3852 extractor.SetFilePos(0);
3853 extractor.GetHexByteString (desc_string);
3854 desc_cstr = desc_string.c_str();
3855 }
Jason Molendaa3329782014-03-29 18:54:20 +00003856 }
3857 }
Ewan Crawford76df2882015-06-23 12:32:06 +00003858 process->SetExitStatus(exit_status, desc_cstr);
3859 done = true;
3860 break;
Jason Molendaa3329782014-03-29 18:54:20 +00003861 }
Ewan Crawford76df2882015-06-23 12:32:06 +00003862 case eStateInvalid:
Jason Molenda752e1e82015-07-29 01:42:16 +00003863 {
3864 // Check to see if we were trying to attach and if we got back
3865 // the "E87" error code from debugserver -- this indicates that
3866 // the process is not debuggable. Return a slightly more helpful
3867 // error message about why the attach failed.
3868 if (::strstr (continue_cstr, "vAttach") != NULL
3869 && response.GetError() == 0x87)
3870 {
3871 process->SetExitStatus(-1, "cannot attach to process due to System Integrity Protection");
3872 }
3873 // E01 code from vAttach means that the attach failed
3874 if (::strstr (continue_cstr, "vAttach") != NULL
3875 && response.GetError() == 0x1)
3876 {
3877 process->SetExitStatus(-1, "unable to attach");
3878 }
3879 else
3880 {
3881 process->SetExitStatus(-1, "lost connection");
3882 }
3883 break;
3884 }
Greg Clayton71337622011-02-24 22:24:29 +00003885
Ewan Crawford76df2882015-06-23 12:32:06 +00003886 default:
3887 process->SetPrivateState (stop_state);
3888 break;
3889 } // switch(stop_state)
3890 } // else // if in All-stop-mode
3891 } // if (continue_packet)
3892 } // case eBroadcastBitAysncContinue
Greg Clayton71337622011-02-24 22:24:29 +00003893 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003894
Greg Clayton71337622011-02-24 22:24:29 +00003895 case eBroadcastBitAsyncThreadShouldExit:
3896 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003897 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Clayton71337622011-02-24 22:24:29 +00003898 done = true;
3899 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003900
Greg Clayton71337622011-02-24 22:24:29 +00003901 default:
3902 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003903 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 +00003904 done = true;
3905 break;
3906 }
3907 }
3908 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
3909 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003910 switch (event_type)
Greg Clayton71337622011-02-24 22:24:29 +00003911 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003912 case Communication::eBroadcastBitReadThreadDidExit:
3913 process->SetExitStatus (-1, "lost connection");
3914 done = true;
3915 break;
3916
3917 case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify:
3918 {
3919 lldb_private::Event *event = event_sp.get();
3920 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event);
3921 StringExtractorGDBRemote notify((const char*)continue_packet->GetBytes());
3922 // Hand this over to the process to handle
3923 process->HandleNotifyPacket(notify);
3924 break;
3925 }
3926
3927 default:
3928 if (log)
3929 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
3930 done = true;
3931 break;
Greg Clayton71337622011-02-24 22:24:29 +00003932 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003933 }
3934 }
3935 else
3936 {
3937 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003938 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 +00003939 done = true;
3940 }
3941 }
3942 }
3943
3944 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003945 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003946
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003947 return NULL;
3948}
3949
Greg Claytone996fd32011-03-08 22:40:15 +00003950//uint32_t
3951//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3952//{
3953// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
3954// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
3955// if (m_local_debugserver)
3956// {
3957// return Host::ListProcessesMatchingName (name, matches, pids);
3958// }
3959// else
3960// {
3961// // FIXME: Implement talking to the remote debugserver.
3962// return 0;
3963// }
3964//
3965//}
3966//
Jim Ingham1c823b42011-01-22 01:33:44 +00003967bool
3968ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003969 StoppointCallbackContext *context,
Jim Ingham1c823b42011-01-22 01:33:44 +00003970 lldb::user_id_t break_id,
3971 lldb::user_id_t break_loc_id)
3972{
3973 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3974 // run so I can stop it if that's what I want to do.
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003975 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00003976 if (log)
3977 log->Printf("Hit New Thread Notification breakpoint.");
3978 return false;
3979}
3980
3981
3982bool
3983ProcessGDBRemote::StartNoticingNewThreads()
3984{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003985 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00003986 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003987 {
Greg Clayton4116e932012-05-15 02:33:01 +00003988 if (log && log->GetVerbose())
3989 log->Printf("Enabled noticing new thread breakpoint.");
3990 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003991 }
Greg Clayton4116e932012-05-15 02:33:01 +00003992 else
Jim Ingham1c823b42011-01-22 01:33:44 +00003993 {
Greg Clayton4116e932012-05-15 02:33:01 +00003994 PlatformSP platform_sp (m_target.GetPlatform());
3995 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003996 {
Greg Clayton4116e932012-05-15 02:33:01 +00003997 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3998 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003999 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00004000 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00004001 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
4002 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00004003 }
4004 else
4005 {
4006 if (log)
4007 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00004008 }
4009 }
4010 }
Greg Clayton4116e932012-05-15 02:33:01 +00004011 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00004012}
4013
4014bool
4015ProcessGDBRemote::StopNoticingNewThreads()
4016{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004017 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00004018 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00004019 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00004020
4021 if (m_thread_create_bp_sp)
4022 m_thread_create_bp_sp->SetEnabled(false);
4023
Jim Ingham1c823b42011-01-22 01:33:44 +00004024 return true;
4025}
4026
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004027DynamicLoader *
Jason Molenda5e8534e2012-10-03 01:29:34 +00004028ProcessGDBRemote::GetDynamicLoader ()
4029{
4030 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00004031 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00004032 return m_dyld_ap.get();
4033}
Jim Ingham1c823b42011-01-22 01:33:44 +00004034
Jason Molendaa3329782014-03-29 18:54:20 +00004035Error
4036ProcessGDBRemote::SendEventData(const char *data)
4037{
4038 int return_value;
4039 bool was_supported;
4040
4041 Error error;
4042
4043 return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported);
4044 if (return_value != 0)
4045 {
4046 if (!was_supported)
4047 error.SetErrorString("Sending events is not supported for this process.");
4048 else
4049 error.SetErrorStringWithFormat("Error sending event data: %d.", return_value);
4050 }
4051 return error;
4052}
4053
Steve Pucci03904ac2014-03-04 23:18:46 +00004054const DataBufferSP
4055ProcessGDBRemote::GetAuxvData()
4056{
4057 DataBufferSP buf;
4058 if (m_gdb_comm.GetQXferAuxvReadSupported())
4059 {
4060 std::string response_string;
4061 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success)
4062 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length()));
4063 }
4064 return buf;
4065}
4066
Jason Molenda705b1802014-06-13 02:37:02 +00004067StructuredData::ObjectSP
4068ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid)
4069{
4070 StructuredData::ObjectSP object_sp;
4071
4072 if (m_gdb_comm.GetThreadExtendedInfoSupported())
4073 {
4074 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4075 SystemRuntime *runtime = GetSystemRuntime();
4076 if (runtime)
4077 {
4078 runtime->AddThreadExtendedInfoPacketHints (args_dict);
4079 }
4080 args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid);
4081
4082 StreamString packet;
4083 packet << "jThreadExtendedInfo:";
4084 args_dict->Dump (packet);
4085
4086 // FIXME the final character of a JSON dictionary, '}', is the escape
4087 // character in gdb-remote binary mode. lldb currently doesn't escape
4088 // these characters in its packet output -- so we add the quoted version
4089 // of the } character here manually in case we talk to a debugserver which
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004090 // un-escapes the characters at packet read time.
Jason Molenda705b1802014-06-13 02:37:02 +00004091 packet << (char) (0x7d ^ 0x20);
4092
4093 StringExtractorGDBRemote response;
4094 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4095 {
4096 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4097 if (response_type == StringExtractorGDBRemote::eResponse)
4098 {
4099 if (!response.Empty())
4100 {
Jason Molenda20ee21b2015-07-10 23:15:22 +00004101 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4102 }
4103 }
4104 }
4105 }
4106 return object_sp;
4107}
4108
4109StructuredData::ObjectSP
4110ProcessGDBRemote::GetLoadedDynamicLibrariesInfos (lldb::addr_t image_list_address, lldb::addr_t image_count)
4111{
4112 StructuredData::ObjectSP object_sp;
4113
4114 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported())
4115 {
4116 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4117 args_dict->GetAsDictionary()->AddIntegerItem ("image_list_address", image_list_address);
4118 args_dict->GetAsDictionary()->AddIntegerItem ("image_count", image_count);
4119
4120 StreamString packet;
4121 packet << "jGetLoadedDynamicLibrariesInfos:";
4122 args_dict->Dump (packet);
4123
4124 // FIXME the final character of a JSON dictionary, '}', is the escape
4125 // character in gdb-remote binary mode. lldb currently doesn't escape
4126 // these characters in its packet output -- so we add the quoted version
4127 // of the } character here manually in case we talk to a debugserver which
4128 // un-escapes the characters at packet read time.
4129 packet << (char) (0x7d ^ 0x20);
4130
4131 StringExtractorGDBRemote response;
4132 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4133 {
4134 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4135 if (response_type == StringExtractorGDBRemote::eResponse)
4136 {
4137 if (!response.Empty())
4138 {
Jason Molenda705b1802014-06-13 02:37:02 +00004139 // The packet has already had the 0x7d xor quoting stripped out at the
4140 // GDBRemoteCommunication packet receive level.
4141 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4142 }
4143 }
4144 }
4145 }
4146 return object_sp;
4147}
4148
Jason Molenda20ee21b2015-07-10 23:15:22 +00004149
Jason Molenda6076bf42014-05-06 04:34:52 +00004150// Establish the largest memory read/write payloads we should use.
4151// If the remote stub has a max packet size, stay under that size.
4152//
4153// If the remote stub's max packet size is crazy large, use a
4154// reasonable largeish default.
4155//
4156// If the remote stub doesn't advertise a max packet size, use a
4157// conservative default.
4158
4159void
4160ProcessGDBRemote::GetMaxMemorySize()
4161{
4162 const uint64_t reasonable_largeish_default = 128 * 1024;
4163 const uint64_t conservative_default = 512;
4164
4165 if (m_max_memory_size == 0)
4166 {
4167 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4168 if (stub_max_size != UINT64_MAX && stub_max_size != 0)
4169 {
4170 // Save the stub's claimed maximum packet size
4171 m_remote_stub_max_memory_size = stub_max_size;
4172
4173 // Even if the stub says it can support ginormous packets,
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004174 // don't exceed our reasonable largeish default packet size.
Jason Molenda6076bf42014-05-06 04:34:52 +00004175 if (stub_max_size > reasonable_largeish_default)
4176 {
4177 stub_max_size = reasonable_largeish_default;
4178 }
4179
4180 m_max_memory_size = stub_max_size;
4181 }
4182 else
4183 {
4184 m_max_memory_size = conservative_default;
4185 }
4186 }
4187}
4188
4189void
4190ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max)
4191{
4192 if (user_specified_max != 0)
4193 {
4194 GetMaxMemorySize ();
4195
4196 if (m_remote_stub_max_memory_size != 0)
4197 {
4198 if (m_remote_stub_max_memory_size < user_specified_max)
4199 {
4200 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a packet size too big, go as big
4201 // as the remote stub says we can go.
4202 }
4203 else
4204 {
4205 m_max_memory_size = user_specified_max; // user's packet size is good
4206 }
4207 }
4208 else
4209 {
4210 m_max_memory_size = user_specified_max; // user's packet size is probably fine
4211 }
4212 }
4213}
4214
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004215bool
4216ProcessGDBRemote::GetModuleSpec(const FileSpec& module_file_spec,
4217 const ArchSpec& arch,
4218 ModuleSpec &module_spec)
4219{
4220 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PLATFORM);
4221
4222 if (!m_gdb_comm.GetModuleInfo (module_file_spec, arch, module_spec))
4223 {
4224 if (log)
4225 log->Printf ("ProcessGDBRemote::%s - failed to get module info for %s:%s",
4226 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4227 arch.GetTriple ().getTriple ().c_str ());
4228 return false;
4229 }
4230
4231 if (log)
4232 {
4233 StreamString stream;
4234 module_spec.Dump (stream);
4235 log->Printf ("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4236 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4237 arch.GetTriple ().getTriple ().c_str (), stream.GetString ().c_str ());
4238 }
4239
4240 return true;
4241}
4242
Colin Rileyc3c95b22015-04-16 15:51:33 +00004243namespace {
4244
4245typedef std::vector<std::string> stringVec;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004246
4247typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004248struct RegisterSetInfo
4249{
4250 ConstString name;
4251};
Colin Rileyc3c95b22015-04-16 15:51:33 +00004252
Greg Claytond04f0ed2015-05-26 18:00:51 +00004253typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4254
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004255struct GdbServerTargetInfo
4256{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004257 std::string arch;
4258 std::string osabi;
4259 stringVec includes;
4260 RegisterSetMap reg_set_map;
4261 XMLNode feature_node;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004262};
Greg Claytond04f0ed2015-05-26 18:00:51 +00004263
Colin Rileyc3c95b22015-04-16 15:51:33 +00004264bool
Greg Claytond04f0ed2015-05-26 18:00:51 +00004265ParseRegisters (XMLNode feature_node, GdbServerTargetInfo &target_info, GDBRemoteDynamicRegisterInfo &dyn_reg_info)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004266{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004267 if (!feature_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004268 return false;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004269
4270 uint32_t prev_reg_num = 0;
4271 uint32_t reg_offset = 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004272
Greg Claytond04f0ed2015-05-26 18:00:51 +00004273 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 +00004274 std::string gdb_group;
4275 std::string gdb_type;
4276 ConstString reg_name;
4277 ConstString alt_name;
4278 ConstString set_name;
4279 std::vector<uint32_t> value_regs;
4280 std::vector<uint32_t> invalidate_regs;
4281 bool encoding_set = false;
4282 bool format_set = false;
4283 RegisterInfo reg_info = { NULL, // Name
4284 NULL, // Alt name
4285 0, // byte size
4286 reg_offset, // offset
4287 eEncodingUint, // encoding
Jason Molendabf67a302015-09-01 05:17:01 +00004288 eFormatHex, // format
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004289 {
Jason Molendabf67a302015-09-01 05:17:01 +00004290 LLDB_INVALID_REGNUM, // eh_frame reg num
Greg Claytond04f0ed2015-05-26 18:00:51 +00004291 LLDB_INVALID_REGNUM, // DWARF reg num
4292 LLDB_INVALID_REGNUM, // generic reg num
Jason Molendabf67a302015-09-01 05:17:01 +00004293 prev_reg_num, // stabs reg num
Greg Claytond04f0ed2015-05-26 18:00:51 +00004294 prev_reg_num // native register number
4295 },
4296 NULL,
4297 NULL
4298 };
4299
Ewan Crawford682e8422015-06-26 09:38:27 +00004300 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 +00004301 if (name == "name")
4302 {
4303 reg_name.SetString(value);
4304 }
4305 else if (name == "bitsize")
4306 {
4307 reg_info.byte_size = StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
4308 }
4309 else if (name == "type")
4310 {
4311 gdb_type = value.str();
4312 }
4313 else if (name == "group")
4314 {
4315 gdb_group = value.str();
4316 }
4317 else if (name == "regnum")
4318 {
4319 const uint32_t regnum = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4320 if (regnum != LLDB_INVALID_REGNUM)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004321 {
Jason Molendaa18f7072015-08-15 01:21:01 +00004322 reg_info.kinds[eRegisterKindStabs] = regnum;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004323 reg_info.kinds[eRegisterKindLLDB] = regnum;
4324 prev_reg_num = regnum;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004325 }
4326 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004327 else if (name == "offset")
4328 {
4329 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4330 }
4331 else if (name == "altname")
4332 {
4333 alt_name.SetString(value);
4334 }
4335 else if (name == "encoding")
4336 {
4337 encoding_set = true;
4338 reg_info.encoding = Args::StringToEncoding (value.data(), eEncodingUint);
4339 }
4340 else if (name == "format")
4341 {
4342 format_set = true;
4343 Format format = eFormatInvalid;
4344 if (Args::StringToFormat (value.data(), format, NULL).Success())
4345 reg_info.format = format;
4346 else if (value == "vector-sint8")
4347 reg_info.format = eFormatVectorOfSInt8;
4348 else if (value == "vector-uint8")
4349 reg_info.format = eFormatVectorOfUInt8;
4350 else if (value == "vector-sint16")
4351 reg_info.format = eFormatVectorOfSInt16;
4352 else if (value == "vector-uint16")
4353 reg_info.format = eFormatVectorOfUInt16;
4354 else if (value == "vector-sint32")
4355 reg_info.format = eFormatVectorOfSInt32;
4356 else if (value == "vector-uint32")
4357 reg_info.format = eFormatVectorOfUInt32;
4358 else if (value == "vector-float32")
4359 reg_info.format = eFormatVectorOfFloat32;
4360 else if (value == "vector-uint128")
4361 reg_info.format = eFormatVectorOfUInt128;
4362 }
4363 else if (name == "group_id")
4364 {
4365 const uint32_t set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4366 RegisterSetMap::const_iterator pos = target_info.reg_set_map.find(set_id);
4367 if (pos != target_info.reg_set_map.end())
4368 set_name = pos->second.name;
4369 }
Jason Molendaa18f7072015-08-15 01:21:01 +00004370 else if (name == "gcc_regnum" || name == "ehframe_regnum")
Greg Claytond04f0ed2015-05-26 18:00:51 +00004371 {
Jason Molendaa18f7072015-08-15 01:21:01 +00004372 reg_info.kinds[eRegisterKindEHFrame] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004373 }
4374 else if (name == "dwarf_regnum")
4375 {
4376 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4377 }
4378 else if (name == "generic")
4379 {
4380 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister(value.data());
4381 }
4382 else if (name == "value_regnums")
4383 {
4384 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
4385 }
4386 else if (name == "invalidate_regnums")
4387 {
4388 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
4389 }
4390 else
4391 {
4392 printf("unhandled attribute %s = %s\n", name.data(), value.data());
4393 }
4394 return true; // Keep iterating through all attributes
4395 });
4396
4397 if (!gdb_type.empty() && !(encoding_set || format_set))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004398 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004399 if (gdb_type.find("int") == 0)
4400 {
4401 reg_info.format = eFormatHex;
4402 reg_info.encoding = eEncodingUint;
4403 }
4404 else if (gdb_type == "data_ptr" || gdb_type == "code_ptr")
4405 {
4406 reg_info.format = eFormatAddressInfo;
4407 reg_info.encoding = eEncodingUint;
4408 }
4409 else if (gdb_type == "i387_ext" || gdb_type == "float")
4410 {
4411 reg_info.format = eFormatFloat;
4412 reg_info.encoding = eEncodingIEEE754;
4413 }
Colin Rileyc3c95b22015-04-16 15:51:33 +00004414 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004415
4416 // Only update the register set name if we didn't get a "reg_set" attribute.
4417 // "set_name" will be empty if we didn't have a "reg_set" attribute.
4418 if (!set_name && !gdb_group.empty())
4419 set_name.SetCString(gdb_group.c_str());
4420
4421 reg_info.byte_offset = reg_offset;
4422 assert (reg_info.byte_size != 0);
4423 reg_offset += reg_info.byte_size;
4424 if (!value_regs.empty())
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004425 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004426 value_regs.push_back(LLDB_INVALID_REGNUM);
4427 reg_info.value_regs = value_regs.data();
Colin Rileyc3c95b22015-04-16 15:51:33 +00004428 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004429 if (!invalidate_regs.empty())
4430 {
4431 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
4432 reg_info.invalidate_regs = invalidate_regs.data();
4433 }
4434
Ewan Crawford682e8422015-06-26 09:38:27 +00004435 ++prev_reg_num;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004436 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
4437
4438 return true; // Keep iterating through all "reg" elements
4439 });
Colin Rileyc3c95b22015-04-16 15:51:33 +00004440 return true;
4441}
Greg Claytond04f0ed2015-05-26 18:00:51 +00004442
Colin Rileyc3c95b22015-04-16 15:51:33 +00004443} // namespace {}
4444
Colin Rileyc3c95b22015-04-16 15:51:33 +00004445
4446// query the target of gdb-remote for extended target information
4447// return: 'true' on success
4448// 'false' on failure
4449bool
Aidan Doddsc0c83852015-05-08 09:36:31 +00004450ProcessGDBRemote::GetGDBServerRegisterInfo ()
Colin Rileyc3c95b22015-04-16 15:51:33 +00004451{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004452 // Make sure LLDB has an XML parser it can use first
4453 if (!XMLDocument::XMLEnabled())
4454 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004455
4456 // redirect libxml2's error handler since the default prints to stdout
Colin Rileyc3c95b22015-04-16 15:51:33 +00004457
4458 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004459
4460 // check that we have extended feature read support
4461 if ( !comm.GetQXferFeaturesReadSupported( ) )
4462 return false;
4463
4464 // request the target xml file
4465 std::string raw;
4466 lldb_private::Error lldberr;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004467 if (!comm.ReadExtFeature(ConstString("features"),
4468 ConstString("target.xml"),
4469 raw,
4470 lldberr))
4471 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00004472 return false;
4473 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004474
Colin Rileyc3c95b22015-04-16 15:51:33 +00004475
Greg Claytond04f0ed2015-05-26 18:00:51 +00004476 XMLDocument xml_document;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004477
Greg Claytond04f0ed2015-05-26 18:00:51 +00004478 if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml"))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004479 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004480 GdbServerTargetInfo target_info;
4481
4482 XMLNode target_node = xml_document.GetRootElement("target");
4483 if (target_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004484 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004485 XMLNode feature_node;
4486 target_node.ForEachChildElement([&target_info, this, &feature_node](const XMLNode &node) -> bool
4487 {
4488 llvm::StringRef name = node.GetName();
4489 if (name == "architecture")
4490 {
4491 node.GetElementText(target_info.arch);
4492 }
4493 else if (name == "osabi")
4494 {
4495 node.GetElementText(target_info.osabi);
4496 }
Ewan Crawford682e8422015-06-26 09:38:27 +00004497 else if (name == "xi:include" || name == "include")
Greg Claytond04f0ed2015-05-26 18:00:51 +00004498 {
4499 llvm::StringRef href = node.GetAttributeValue("href");
4500 if (!href.empty())
4501 target_info.includes.push_back(href.str());
4502 }
4503 else if (name == "feature")
4504 {
4505 feature_node = node;
4506 }
4507 else if (name == "groups")
4508 {
4509 node.ForEachChildElementWithName("group", [&target_info](const XMLNode &node) -> bool {
4510 uint32_t set_id = UINT32_MAX;
4511 RegisterSetInfo set_info;
4512
4513 node.ForEachAttribute([&set_id, &set_info](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
4514 if (name == "id")
4515 set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4516 if (name == "name")
4517 set_info.name = ConstString(value);
4518 return true; // Keep iterating through all attributes
4519 });
4520
4521 if (set_id != UINT32_MAX)
4522 target_info.reg_set_map[set_id] = set_info;
4523 return true; // Keep iterating through all "group" elements
4524 });
4525 }
4526 return true; // Keep iterating through all children of the target_node
4527 });
4528
4529 if (feature_node)
4530 {
4531 ParseRegisters(feature_node, target_info, this->m_register_info);
4532 }
4533
4534 for (const auto &include : target_info.includes)
4535 {
4536 // request register file
4537 std::string xml_data;
4538 if (!comm.ReadExtFeature(ConstString("features"),
4539 ConstString(include),
4540 xml_data,
4541 lldberr))
4542 continue;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004543
Greg Claytond04f0ed2015-05-26 18:00:51 +00004544 XMLDocument include_xml_document;
4545 include_xml_document.ParseMemory(xml_data.data(), xml_data.size(), include.c_str());
4546 XMLNode include_feature_node = include_xml_document.GetRootElement("feature");
4547 if (include_feature_node)
4548 {
4549 ParseRegisters(include_feature_node, target_info, this->m_register_info);
4550 }
4551 }
4552 this->m_register_info.Finalize(GetTarget().GetArchitecture());
Colin Rileyc3c95b22015-04-16 15:51:33 +00004553 }
4554 }
4555
Greg Claytond04f0ed2015-05-26 18:00:51 +00004556 return m_register_info.GetNumRegisters() > 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004557}
4558
Aidan Doddsc0c83852015-05-08 09:36:31 +00004559Error
4560ProcessGDBRemote::GetLoadedModuleList (GDBLoadedModuleInfoList & list)
4561{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004562 // Make sure LLDB has an XML parser it can use first
4563 if (!XMLDocument::XMLEnabled())
4564 return Error (0, ErrorType::eErrorTypeGeneric);
4565
Aidan Doddsc0c83852015-05-08 09:36:31 +00004566 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS);
4567 if (log)
4568 log->Printf ("ProcessGDBRemote::%s", __FUNCTION__);
4569
Aidan Doddsc0c83852015-05-08 09:36:31 +00004570 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004571
4572 // check that we have extended feature read support
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004573 if (comm.GetQXferLibrariesSVR4ReadSupported ()) {
4574 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004575
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004576 // request the loaded library list
4577 std::string raw;
4578 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004579
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004580 if (!comm.ReadExtFeature (ConstString ("libraries-svr4"), ConstString (""), raw, lldberr))
4581 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004582
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004583 // parse the xml file in memory
4584 if (log)
4585 log->Printf ("parsing: %s", raw.c_str());
4586 XMLDocument doc;
4587
4588 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4589 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004590
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004591 XMLNode root_element = doc.GetRootElement("library-list-svr4");
4592 if (!root_element)
4593 return Error();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004594
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004595 // main link map structure
4596 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4597 if (!main_lm.empty())
4598 {
4599 list.m_link_map = StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
4600 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004601
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004602 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
Aidan Doddsc0c83852015-05-08 09:36:31 +00004603
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004604 GDBLoadedModuleInfoList::LoadedModuleInfo module;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004605
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004606 library.ForEachAttribute([log, &module](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004607
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004608 if (name == "name")
4609 module.set_name (value.str());
4610 else if (name == "lm")
4611 {
4612 // the address of the link_map struct.
4613 module.set_link_map(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4614 }
4615 else if (name == "l_addr")
4616 {
4617 // the displacement as read from the field 'l_addr' of the link_map struct.
4618 module.set_base(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
Stephane Sezerc6845a02015-08-20 22:07:48 +00004619 // base address is always a displacement, not an absolute value.
4620 module.set_base_is_offset(true);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004621 }
4622 else if (name == "l_ld")
4623 {
4624 // the memory address of the libraries PT_DYAMIC section.
4625 module.set_dynamic(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4626 }
4627
4628 return true; // Keep iterating over all properties of "library"
4629 });
4630
4631 if (log)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004632 {
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004633 std::string name;
4634 lldb::addr_t lm=0, base=0, ld=0;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004635 bool base_is_offset;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004636
4637 module.get_name (name);
4638 module.get_link_map (lm);
4639 module.get_base (base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004640 module.get_base_is_offset (base_is_offset);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004641 module.get_dynamic (ld);
4642
Stephane Sezerc6845a02015-08-20 22:07:48 +00004643 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 +00004644 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004645
4646 list.add (module);
4647 return true; // Keep iterating over all "library" elements in the root node
Greg Claytond04f0ed2015-05-26 18:00:51 +00004648 });
Aidan Doddsc0c83852015-05-08 09:36:31 +00004649
4650 if (log)
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004651 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4652 } else if (comm.GetQXferLibrariesReadSupported ()) {
4653 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004654
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004655 // request the loaded library list
4656 std::string raw;
4657 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004658
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004659 if (!comm.ReadExtFeature (ConstString ("libraries"), ConstString (""), raw, lldberr))
4660 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004661
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004662 if (log)
4663 log->Printf ("parsing: %s", raw.c_str());
4664 XMLDocument doc;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004665
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004666 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4667 return Error (0, ErrorType::eErrorTypeGeneric);
4668
4669 XMLNode root_element = doc.GetRootElement("library-list");
4670 if (!root_element)
4671 return Error();
4672
4673 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
4674 GDBLoadedModuleInfoList::LoadedModuleInfo module;
4675
4676 llvm::StringRef name = library.GetAttributeValue("name");
4677 module.set_name(name.str());
4678
4679 // The base address of a given library will be the address of its
4680 // first section. Most remotes send only one section for Windows
4681 // targets for example.
4682 const XMLNode &section = library.FindFirstChildElementWithName("section");
4683 llvm::StringRef address = section.GetAttributeValue("address");
4684 module.set_base(StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0));
Stephane Sezerc6845a02015-08-20 22:07:48 +00004685 // These addresses are absolute values.
4686 module.set_base_is_offset(false);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004687
4688 if (log)
4689 {
4690 std::string name;
4691 lldb::addr_t base = 0;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004692 bool base_is_offset;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004693 module.get_name (name);
4694 module.get_base (base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004695 module.get_base_is_offset (base_is_offset);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004696
Stephane Sezerc6845a02015-08-20 22:07:48 +00004697 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 +00004698 }
4699
4700 list.add (module);
4701 return true; // Keep iterating over all "library" elements in the root node
4702 });
4703
4704 if (log)
4705 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4706 } else {
4707 return Error (0, ErrorType::eErrorTypeGeneric);
4708 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004709
4710 return Error();
4711}
4712
Aidan Doddsc0c83852015-05-08 09:36:31 +00004713lldb::ModuleSP
Stephane Sezerc6845a02015-08-20 22:07:48 +00004714ProcessGDBRemote::LoadModuleAtAddress (const FileSpec &file, lldb::addr_t base_addr, bool value_is_offset)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004715{
4716 Target &target = m_process->GetTarget();
4717 ModuleList &modules = target.GetImages();
4718 ModuleSP module_sp;
4719
4720 bool changed = false;
4721
4722 ModuleSpec module_spec (file, target.GetArchitecture());
4723 if ((module_sp = modules.FindFirstModule (module_spec)))
4724 {
Stephane Sezerc6845a02015-08-20 22:07:48 +00004725 module_sp->SetLoadAddress (target, base_addr, value_is_offset, changed);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004726 }
4727 else if ((module_sp = target.GetSharedModule (module_spec)))
4728 {
Stephane Sezerc6845a02015-08-20 22:07:48 +00004729 module_sp->SetLoadAddress (target, base_addr, value_is_offset, changed);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004730 }
4731
4732 return module_sp;
4733}
4734
4735size_t
4736ProcessGDBRemote::LoadModules ()
4737{
4738 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4739
4740 // request a list of loaded libraries from GDBServer
4741 GDBLoadedModuleInfoList module_list;
4742 if (GetLoadedModuleList (module_list).Fail())
4743 return 0;
4744
4745 // get a list of all the modules
4746 ModuleList new_modules;
4747
4748 for (GDBLoadedModuleInfoList::LoadedModuleInfo & modInfo : module_list.m_list)
4749 {
4750 std::string mod_name;
4751 lldb::addr_t mod_base;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004752 bool mod_base_is_offset;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004753
4754 bool valid = true;
4755 valid &= modInfo.get_name (mod_name);
4756 valid &= modInfo.get_base (mod_base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004757 valid &= modInfo.get_base_is_offset (mod_base_is_offset);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004758 if (!valid)
4759 continue;
4760
4761 // hack (cleaner way to get file name only?) (win/unix compat?)
Vince Harron4cc8d202015-05-10 08:33:58 +00004762 size_t marker = mod_name.rfind ('/');
Aidan Doddsc0c83852015-05-08 09:36:31 +00004763 if (marker == std::string::npos)
4764 marker = 0;
4765 else
4766 marker += 1;
4767
4768 FileSpec file (mod_name.c_str()+marker, true);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004769 lldb::ModuleSP module_sp = LoadModuleAtAddress (file, mod_base, mod_base_is_offset);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004770
4771 if (module_sp.get())
4772 new_modules.Append (module_sp);
4773 }
4774
4775 if (new_modules.GetSize() > 0)
4776 {
4777 Target & target = m_target;
4778
4779 new_modules.ForEach ([&target](const lldb::ModuleSP module_sp) -> bool
4780 {
4781 lldb_private::ObjectFile * obj = module_sp->GetObjectFile ();
4782 if (!obj)
4783 return true;
4784
4785 if (obj->GetType () != ObjectFile::Type::eTypeExecutable)
4786 return true;
4787
4788 lldb::ModuleSP module_copy_sp = module_sp;
4789 target.SetExecutableModule (module_copy_sp, false);
4790 return false;
4791 });
4792
4793 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4794 loaded_modules.AppendIfNeeded (new_modules);
4795 m_process->GetTarget().ModulesDidLoad (new_modules);
4796 }
4797
4798 return new_modules.GetSize();
4799}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004800
Tamas Berghammer783bfc82015-06-18 20:43:56 +00004801Error
4802ProcessGDBRemote::GetFileLoadAddress(const FileSpec& file, bool& is_loaded, lldb::addr_t& load_addr)
4803{
4804 is_loaded = false;
4805 load_addr = LLDB_INVALID_ADDRESS;
4806
4807 std::string file_path = file.GetPath(false);
4808 if (file_path.empty ())
4809 return Error("Empty file name specified");
4810
4811 StreamString packet;
4812 packet.PutCString("qFileLoadAddress:");
4813 packet.PutCStringAsRawHex8(file_path.c_str());
4814
4815 StringExtractorGDBRemote response;
4816 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString().c_str(), response, false) != GDBRemoteCommunication::PacketResult::Success)
4817 return Error("Sending qFileLoadAddress packet failed");
4818
4819 if (response.IsErrorResponse())
4820 {
4821 if (response.GetError() == 1)
4822 {
4823 // The file is not loaded into the inferior
4824 is_loaded = false;
4825 load_addr = LLDB_INVALID_ADDRESS;
4826 return Error();
4827 }
4828
4829 return Error("Fetching file load address from remote server returned an error");
4830 }
4831
4832 if (response.IsNormalResponse())
4833 {
4834 is_loaded = true;
4835 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
4836 return Error();
4837 }
4838
4839 return Error("Unknown error happened during sending the load address packet");
4840}
4841
Greg Clayton0b90be12015-06-23 21:27:50 +00004842
4843void
4844ProcessGDBRemote::ModulesDidLoad (ModuleList &module_list)
4845{
4846 // We must call the lldb_private::Process::ModulesDidLoad () first before we do anything
4847 Process::ModulesDidLoad (module_list);
4848
4849 // After loading shared libraries, we can ask our remote GDB server if
4850 // it needs any symbols.
4851 m_gdb_comm.ServeSymbolLookups(this);
4852}
4853
4854
Greg Claytone034a042015-05-21 20:52:06 +00004855class CommandObjectProcessGDBRemoteSpeedTest: public CommandObjectParsed
4856{
4857public:
4858 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter) :
4859 CommandObjectParsed (interpreter,
4860 "process plugin packet speed-test",
4861 "Tests packet speeds of various sizes to determine the performance characteristics of the GDB remote connection. ",
4862 NULL),
4863 m_option_group (interpreter),
4864 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),
4865 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),
4866 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),
4867 m_json (LLDB_OPT_SET_1, false, "json", 'j', "Print the output as JSON data for easy parsing.", false, true)
4868 {
4869 m_option_group.Append (&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4870 m_option_group.Append (&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4871 m_option_group.Append (&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4872 m_option_group.Append (&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4873 m_option_group.Finalize();
4874 }
4875
4876 ~CommandObjectProcessGDBRemoteSpeedTest ()
4877 {
4878 }
4879
4880
4881 Options *
4882 GetOptions () override
4883 {
4884 return &m_option_group;
4885 }
4886
4887 bool
4888 DoExecute (Args& command, CommandReturnObject &result) override
4889 {
4890 const size_t argc = command.GetArgumentCount();
4891 if (argc == 0)
4892 {
4893 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4894 if (process)
4895 {
4896 StreamSP output_stream_sp (m_interpreter.GetDebugger().GetAsyncOutputStream());
4897 result.SetImmediateOutputStream (output_stream_sp);
4898
4899 const uint32_t num_packets = (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
4900 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
4901 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
4902 const bool json = m_json.GetOptionValue().GetCurrentValue();
4903 if (output_stream_sp)
4904 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, *output_stream_sp);
4905 else
4906 {
4907 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, result.GetOutputStream());
4908 }
4909 result.SetStatus (eReturnStatusSuccessFinishResult);
4910 return true;
4911 }
4912 }
4913 else
4914 {
4915 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
4916 }
4917 result.SetStatus (eReturnStatusFailed);
4918 return false;
4919 }
4920protected:
4921 OptionGroupOptions m_option_group;
4922 OptionGroupUInt64 m_num_packets;
4923 OptionGroupUInt64 m_max_send;
4924 OptionGroupUInt64 m_max_recv;
4925 OptionGroupBoolean m_json;
4926
4927};
4928
Greg Clayton02686b82012-10-15 22:42:16 +00004929class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00004930{
4931private:
4932
4933public:
Greg Clayton02686b82012-10-15 22:42:16 +00004934 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00004935 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00004936 "process plugin packet history",
4937 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00004938 NULL)
4939 {
4940 }
4941
Greg Clayton02686b82012-10-15 22:42:16 +00004942 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton998255b2012-10-13 02:07:45 +00004943 {
4944 }
4945
4946 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004947 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton998255b2012-10-13 02:07:45 +00004948 {
Greg Clayton02686b82012-10-15 22:42:16 +00004949 const size_t argc = command.GetArgumentCount();
4950 if (argc == 0)
4951 {
4952 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4953 if (process)
4954 {
4955 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
4956 result.SetStatus (eReturnStatusSuccessFinishResult);
4957 return true;
4958 }
4959 }
4960 else
4961 {
4962 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
4963 }
4964 result.SetStatus (eReturnStatusFailed);
4965 return false;
4966 }
4967};
4968
Jason Molenda6076bf42014-05-06 04:34:52 +00004969class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed
4970{
4971private:
4972
4973public:
4974 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) :
4975 CommandObjectParsed (interpreter,
4976 "process plugin packet xfer-size",
4977 "Maximum size that lldb will try to read/write one one chunk.",
4978 NULL)
4979 {
4980 }
4981
4982 ~CommandObjectProcessGDBRemotePacketXferSize ()
4983 {
4984 }
4985
4986 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004987 DoExecute (Args& command, CommandReturnObject &result) override
Jason Molenda6076bf42014-05-06 04:34:52 +00004988 {
4989 const size_t argc = command.GetArgumentCount();
4990 if (argc == 0)
4991 {
4992 result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str());
4993 result.SetStatus (eReturnStatusFailed);
4994 return false;
4995 }
4996
4997 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4998 if (process)
4999 {
5000 const char *packet_size = command.GetArgumentAtIndex(0);
5001 errno = 0;
5002 uint64_t user_specified_max = strtoul (packet_size, NULL, 10);
5003 if (errno == 0 && user_specified_max != 0)
5004 {
5005 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max);
5006 result.SetStatus (eReturnStatusSuccessFinishResult);
5007 return true;
5008 }
5009 }
5010 result.SetStatus (eReturnStatusFailed);
5011 return false;
5012 }
5013};
5014
5015
Greg Clayton02686b82012-10-15 22:42:16 +00005016class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
5017{
5018private:
5019
5020public:
5021 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
5022 CommandObjectParsed (interpreter,
5023 "process plugin packet send",
5024 "Send a custom packet through the GDB remote protocol and print the answer. "
5025 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
5026 NULL)
5027 {
5028 }
5029
5030 ~CommandObjectProcessGDBRemotePacketSend ()
5031 {
5032 }
5033
5034 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005035 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton02686b82012-10-15 22:42:16 +00005036 {
5037 const size_t argc = command.GetArgumentCount();
5038 if (argc == 0)
5039 {
5040 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
5041 result.SetStatus (eReturnStatusFailed);
5042 return false;
5043 }
5044
5045 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5046 if (process)
5047 {
Han Ming Ong84145852012-11-26 20:42:03 +00005048 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00005049 {
Han Ming Ong84145852012-11-26 20:42:03 +00005050 const char *packet_cstr = command.GetArgumentAtIndex(0);
5051 bool send_async = true;
5052 StringExtractorGDBRemote response;
5053 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
5054 result.SetStatus (eReturnStatusSuccessFinishResult);
5055 Stream &output_strm = result.GetOutputStream();
5056 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00005057 std::string &response_str = response.GetStringRef();
5058
Han Ming Ong399289e2013-06-21 19:56:59 +00005059 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00005060 {
5061 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
5062 }
5063
Han Ming Ong84145852012-11-26 20:42:03 +00005064 if (response_str.empty())
5065 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
5066 else
5067 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00005068 }
Greg Clayton02686b82012-10-15 22:42:16 +00005069 }
Greg Clayton998255b2012-10-13 02:07:45 +00005070 return true;
5071 }
5072};
5073
Greg Claytonba4a0a52013-02-01 23:03:47 +00005074class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
5075{
5076private:
5077
5078public:
5079 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
5080 CommandObjectRaw (interpreter,
5081 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00005082 "Send a qRcmd packet through the GDB remote protocol and print the response."
5083 "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 +00005084 NULL)
5085 {
5086 }
5087
5088 ~CommandObjectProcessGDBRemotePacketMonitor ()
5089 {
5090 }
5091
5092 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005093 DoExecute (const char *command, CommandReturnObject &result) override
Greg Claytonba4a0a52013-02-01 23:03:47 +00005094 {
5095 if (command == NULL || command[0] == '\0')
5096 {
5097 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
5098 result.SetStatus (eReturnStatusFailed);
5099 return false;
5100 }
5101
5102 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5103 if (process)
5104 {
5105 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00005106 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00005107 packet.PutBytesAsRawHex8(command, strlen(command));
5108 const char *packet_cstr = packet.GetString().c_str();
5109
5110 bool send_async = true;
5111 StringExtractorGDBRemote response;
5112 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
5113 result.SetStatus (eReturnStatusSuccessFinishResult);
5114 Stream &output_strm = result.GetOutputStream();
5115 output_strm.Printf (" packet: %s\n", packet_cstr);
5116 const std::string &response_str = response.GetStringRef();
5117
5118 if (response_str.empty())
5119 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
5120 else
5121 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
5122 }
5123 return true;
5124 }
5125};
5126
Greg Clayton02686b82012-10-15 22:42:16 +00005127class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
5128{
5129private:
5130
5131public:
5132 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
5133 CommandObjectMultiword (interpreter,
5134 "process plugin packet",
5135 "Commands that deal with GDB remote packets.",
5136 NULL)
5137 {
5138 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
5139 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00005140 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Jason Molenda6076bf42014-05-06 04:34:52 +00005141 LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter)));
Greg Claytone034a042015-05-21 20:52:06 +00005142 LoadSubCommand ("speed-test", CommandObjectSP (new CommandObjectProcessGDBRemoteSpeedTest (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00005143 }
5144
5145 ~CommandObjectProcessGDBRemotePacket ()
5146 {
5147 }
5148};
Greg Clayton998255b2012-10-13 02:07:45 +00005149
5150class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
5151{
5152public:
5153 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
5154 CommandObjectMultiword (interpreter,
5155 "process plugin",
5156 "A set of commands for operating on a ProcessGDBRemote process.",
5157 "process plugin <subcommand> [<subcommand-options>]")
5158 {
5159 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
5160 }
5161
5162 ~CommandObjectMultiwordProcessGDBRemote ()
5163 {
5164 }
5165};
5166
Greg Clayton998255b2012-10-13 02:07:45 +00005167CommandObject *
5168ProcessGDBRemote::GetPluginCommandObject()
5169{
5170 if (!m_command_sp)
5171 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
5172 return m_command_sp.get();
5173}