blob: 4a60d68dd2388f79689c951abe170455bf49c9e1 [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
Zachary Turner7529df92015-09-01 20:02:29 +0000336ProcessGDBRemote::CreateInstance (lldb::TargetSP target_sp, 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)
Zachary Turner7529df92015-09-01 20:02:29 +0000340 process_sp.reset (new ProcessGDBRemote (target_sp, listener));
Greg Claytonc3776bf2012-02-09 06:16:32 +0000341 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000342}
343
344bool
Zachary Turner7529df92015-09-01 20:02:29 +0000345ProcessGDBRemote::CanDebug (lldb::TargetSP target_sp, 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
Zachary Turner7529df92015-09-01 20:02:29 +0000351 Module *exe_module = target_sp->GetExecutableModulePointer();
Greg Claytonaa149cb2011-08-11 02:48:45 +0000352 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//----------------------------------------------------------------------
Zachary Turner7529df92015-09-01 20:02:29 +0000380ProcessGDBRemote::ProcessGDBRemote(lldb::TargetSP target_sp, Listener &listener) :
381 Process (target_sp, 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"),
Pavel Labath50556852015-09-03 09:36:22 +0000388 m_async_listener("lldb.process.gdb-remote.async-listener"),
Jim Ingham455fa5c2012-11-01 01:15:33 +0000389 m_async_thread_state_mutex(Mutex::eMutexTypeRecursive),
Greg Clayton9e920902012-04-10 02:25:43 +0000390 m_thread_ids (),
Greg Clayton2e309072015-07-17 23:42:28 +0000391 m_jstopinfo_sp (),
392 m_jthreadsinfo_sp (),
Greg Clayton71fc2a32011-02-12 06:28:37 +0000393 m_continue_c_tids (),
394 m_continue_C_tids (),
395 m_continue_s_tids (),
396 m_continue_S_tids (),
Jason Molenda6076bf42014-05-06 04:34:52 +0000397 m_max_memory_size (0),
398 m_remote_stub_max_memory_size (0),
Greg Clayton4116e932012-05-15 02:33:01 +0000399 m_addr_to_mmap_size (),
400 m_thread_create_bp_sp (),
Jim Ingham43c555d2012-07-04 00:35:43 +0000401 m_waiting_for_attach (false),
Jason Molenda5e8534e2012-10-03 01:29:34 +0000402 m_destroy_tried_resuming (false),
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000403 m_command_sp (),
Ewan Crawford78baa192015-05-13 09:18:18 +0000404 m_breakpoint_pc_offset (0),
405 m_initial_tid (LLDB_INVALID_THREAD_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000406{
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000407 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
408 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Inghamb1e2e842012-04-12 18:49:31 +0000409 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Pavel Labath50556852015-09-03 09:36:22 +0000410
411 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_ASYNC));
412
413 const uint32_t async_event_mask = eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
414
415 if (m_async_listener.StartListeningForEvents(&m_async_broadcaster, async_event_mask) != async_event_mask)
416 {
417 if (log)
418 log->Printf("ProcessGDBRemote::%s failed to listen for m_async_broadcaster events", __FUNCTION__);
419 }
420
421 const uint32_t gdb_event_mask = Communication::eBroadcastBitReadThreadDidExit |
422 GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify;
423 if (m_async_listener.StartListeningForEvents(&m_gdb_comm, gdb_event_mask) != gdb_event_mask)
424 {
425 if (log)
426 log->Printf("ProcessGDBRemote::%s failed to listen for m_gdb_comm events", __FUNCTION__);
427 }
428
Greg Clayton7f982402013-07-15 22:54:20 +0000429 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
430 if (timeout_seconds > 0)
431 m_gdb_comm.SetPacketTimeout(timeout_seconds);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000432}
433
434//----------------------------------------------------------------------
435// Destructor
436//----------------------------------------------------------------------
437ProcessGDBRemote::~ProcessGDBRemote()
438{
439 // m_mach_process.UnregisterNotificationCallbacks (this);
440 Clear();
Greg Clayton1ed54f52011-10-01 00:45:15 +0000441 // We need to call finalize on the process before destroying ourselves
442 // to make sure all of the broadcaster cleanup goes as planned. If we
443 // destruct this class, then Process::~Process() might have problems
444 // trying to fully destroy the broadcaster.
445 Finalize();
Jim Ingham455fa5c2012-11-01 01:15:33 +0000446
447 // The general Finalize is going to try to destroy the process and that SHOULD
448 // shut down the async thread. However, if we don't kill it it will get stranded and
449 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
450 StopAsyncThread();
451 KillDebugserverProcess();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000452}
453
454//----------------------------------------------------------------------
455// PluginInterface
456//----------------------------------------------------------------------
Greg Clayton57abc5d2013-05-10 21:47:16 +0000457ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000458ProcessGDBRemote::GetPluginName()
459{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000460 return GetPluginNameStatic();
461}
462
463uint32_t
464ProcessGDBRemote::GetPluginVersion()
465{
466 return 1;
467}
468
Greg Claytonef8180a2013-10-15 00:14:28 +0000469bool
470ProcessGDBRemote::ParsePythonTargetDefinition(const FileSpec &target_definition_fspec)
471{
472 ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
473 Error error;
Zachary Turner0641ca12015-03-17 20:04:04 +0000474 StructuredData::ObjectSP module_object_sp(interpreter->LoadPluginModule(target_definition_fspec, error));
Greg Claytonef8180a2013-10-15 00:14:28 +0000475 if (module_object_sp)
476 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000477 StructuredData::DictionarySP target_definition_sp(
478 interpreter->GetDynamicSettings(module_object_sp, &GetTarget(), "gdb-server-target-definition", error));
Greg Claytonef8180a2013-10-15 00:14:28 +0000479
Zachary Turner0641ca12015-03-17 20:04:04 +0000480 if (target_definition_sp)
Greg Claytonef8180a2013-10-15 00:14:28 +0000481 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000482 StructuredData::ObjectSP target_object(target_definition_sp->GetValueForKey("host-info"));
483 if (target_object)
Greg Clayton312bcbe2013-10-17 01:10:23 +0000484 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000485 if (auto host_info_dict = target_object->GetAsDictionary())
Greg Clayton312bcbe2013-10-17 01:10:23 +0000486 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000487 StructuredData::ObjectSP triple_value = host_info_dict->GetValueForKey("triple");
488 if (auto triple_string_value = triple_value->GetAsString())
489 {
490 std::string triple_string = triple_string_value->GetValue();
491 ArchSpec host_arch(triple_string.c_str());
492 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture()))
493 {
494 GetTarget().SetArchitecture(host_arch);
495 }
496 }
Greg Clayton312bcbe2013-10-17 01:10:23 +0000497 }
Greg Clayton312bcbe2013-10-17 01:10:23 +0000498 }
Zachary Turner0641ca12015-03-17 20:04:04 +0000499 m_breakpoint_pc_offset = 0;
500 StructuredData::ObjectSP breakpoint_pc_offset_value = target_definition_sp->GetValueForKey("breakpoint-pc-offset");
501 if (breakpoint_pc_offset_value)
502 {
503 if (auto breakpoint_pc_int_value = breakpoint_pc_offset_value->GetAsInteger())
504 m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
505 }
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000506
Greg Claytond04f0ed2015-05-26 18:00:51 +0000507 if (m_register_info.SetRegisterInfo(*target_definition_sp, GetTarget().GetArchitecture()) > 0)
Greg Claytonef8180a2013-10-15 00:14:28 +0000508 {
509 return true;
510 }
511 }
512 }
513 return false;
514}
515
Greg Claytond04f0ed2015-05-26 18:00:51 +0000516static size_t
517SplitCommaSeparatedRegisterNumberString(const llvm::StringRef &comma_separated_regiter_numbers, std::vector<uint32_t> &regnums, int base)
518{
519 regnums.clear();
520 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
521 value_pair.second = comma_separated_regiter_numbers;
522 do
523 {
524 value_pair = value_pair.second.split(',');
525 if (!value_pair.first.empty())
526 {
527 uint32_t reg = StringConvert::ToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, base);
528 if (reg != LLDB_INVALID_REGNUM)
529 regnums.push_back (reg);
530 }
531 } while (!value_pair.second.empty());
532 return regnums.size();
533}
534
Greg Claytonef8180a2013-10-15 00:14:28 +0000535
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000536void
Greg Clayton513c26c2011-01-29 07:10:55 +0000537ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000538{
Greg Clayton513c26c2011-01-29 07:10:55 +0000539 if (!force && m_register_info.GetNumRegisters() > 0)
540 return;
541
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000542 m_register_info.Clear();
Greg Claytond04f0ed2015-05-26 18:00:51 +0000543
544 // Check if qHostInfo specified a specific packet timeout for this connection.
545 // If so then lets update our setting so the user knows what the timeout is
546 // and can see it.
547 const uint32_t host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
548 if (host_packet_timeout)
549 {
550 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout);
551 }
552
Ewan Crawford0c996a92015-06-30 13:08:44 +0000553 // Register info search order:
554 // 1 - Use the target definition python file if one is specified.
555 // 2 - If the target definition doesn't have any of the info from the target.xml (registers) then proceed to read the target.xml.
556 // 3 - Fall back on the qRegisterInfo packets.
557
558 FileSpec target_definition_fspec = GetGlobalPluginProperties()->GetTargetDefinitionFile ();
Jason Molenda91e468c2015-08-20 04:29:46 +0000559 if (!target_definition_fspec.Exists())
560 {
561 // If the filename doesn't exist, it may be a ~ not having been expanded - try to resolve it.
562 target_definition_fspec.ResolvePath();
563 }
Ewan Crawford0c996a92015-06-30 13:08:44 +0000564 if (target_definition_fspec)
565 {
566 // See if we can get register definitions from a python file
567 if (ParsePythonTargetDefinition (target_definition_fspec))
Jason Molenda5543abb2015-08-20 03:05:09 +0000568 {
Ewan Crawford0c996a92015-06-30 13:08:44 +0000569 return;
Jason Molenda5543abb2015-08-20 03:05:09 +0000570 }
571 else
572 {
573 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
574 stream_sp->Printf ("ERROR: target description file %s failed to parse.\n", target_definition_fspec.GetPath().c_str());
575 }
Ewan Crawford0c996a92015-06-30 13:08:44 +0000576 }
577
Greg Claytond04f0ed2015-05-26 18:00:51 +0000578 if (GetGDBServerRegisterInfo ())
579 return;
580
581 char packet[128];
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000582 uint32_t reg_offset = 0;
583 uint32_t reg_num = 0;
Greg Clayton23f59502012-07-17 03:23:13 +0000584 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Greg Clayton576d8832011-03-22 04:00:09 +0000585 response_type == StringExtractorGDBRemote::eResponse;
586 ++reg_num)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000587 {
Greg Clayton513c26c2011-01-29 07:10:55 +0000588 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
Andy Gibbsa297a972013-06-19 19:04:53 +0000589 assert (packet_len < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000590 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000591 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000592 {
Greg Clayton576d8832011-03-22 04:00:09 +0000593 response_type = response.GetResponseType();
594 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000595 {
596 std::string name;
597 std::string value;
598 ConstString reg_name;
599 ConstString alt_name;
600 ConstString set_name;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000601 std::vector<uint32_t> value_regs;
602 std::vector<uint32_t> invalidate_regs;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000603 RegisterInfo reg_info = { NULL, // Name
604 NULL, // Alt name
605 0, // byte size
606 reg_offset, // offset
607 eEncodingUint, // encoding
Jason Molendabf67a302015-09-01 05:17:01 +0000608 eFormatHex, // format
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000609 {
Jason Molendabf67a302015-09-01 05:17:01 +0000610 LLDB_INVALID_REGNUM, // eh_frame reg num
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000611 LLDB_INVALID_REGNUM, // DWARF reg num
612 LLDB_INVALID_REGNUM, // generic reg num
Jason Molendabf67a302015-09-01 05:17:01 +0000613 reg_num, // stabs reg num
Jason Molendafbcb7f22010-09-10 07:49:16 +0000614 reg_num // native register number
Greg Clayton435d85a2012-02-29 19:27:27 +0000615 },
616 NULL,
617 NULL
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000618 };
619
620 while (response.GetNameColonValue(name, value))
621 {
622 if (name.compare("name") == 0)
623 {
624 reg_name.SetCString(value.c_str());
625 }
626 else if (name.compare("alt-name") == 0)
627 {
628 alt_name.SetCString(value.c_str());
629 }
630 else if (name.compare("bitsize") == 0)
631 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000632 reg_info.byte_size = StringConvert::ToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000633 }
634 else if (name.compare("offset") == 0)
635 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000636 uint32_t offset = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda743e86a2010-06-11 23:44:18 +0000637 if (reg_offset != offset)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000638 {
639 reg_offset = offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000640 }
641 }
642 else if (name.compare("encoding") == 0)
643 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000644 const Encoding encoding = Args::StringToEncoding (value.c_str());
645 if (encoding != eEncodingInvalid)
646 reg_info.encoding = encoding;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000647 }
648 else if (name.compare("format") == 0)
649 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000650 Format format = eFormatInvalid;
651 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
652 reg_info.format = format;
653 else if (value.compare("binary") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000654 reg_info.format = eFormatBinary;
655 else if (value.compare("decimal") == 0)
656 reg_info.format = eFormatDecimal;
657 else if (value.compare("hex") == 0)
658 reg_info.format = eFormatHex;
659 else if (value.compare("float") == 0)
660 reg_info.format = eFormatFloat;
661 else if (value.compare("vector-sint8") == 0)
662 reg_info.format = eFormatVectorOfSInt8;
663 else if (value.compare("vector-uint8") == 0)
664 reg_info.format = eFormatVectorOfUInt8;
665 else if (value.compare("vector-sint16") == 0)
666 reg_info.format = eFormatVectorOfSInt16;
667 else if (value.compare("vector-uint16") == 0)
668 reg_info.format = eFormatVectorOfUInt16;
669 else if (value.compare("vector-sint32") == 0)
670 reg_info.format = eFormatVectorOfSInt32;
671 else if (value.compare("vector-uint32") == 0)
672 reg_info.format = eFormatVectorOfUInt32;
673 else if (value.compare("vector-float32") == 0)
674 reg_info.format = eFormatVectorOfFloat32;
675 else if (value.compare("vector-uint128") == 0)
676 reg_info.format = eFormatVectorOfUInt128;
677 }
678 else if (name.compare("set") == 0)
679 {
680 set_name.SetCString(value.c_str());
681 }
Jason Molendaa18f7072015-08-15 01:21:01 +0000682 else if (name.compare("gcc") == 0 || name.compare("ehframe") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000683 {
Jason Molendaa18f7072015-08-15 01:21:01 +0000684 reg_info.kinds[eRegisterKindEHFrame] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000685 }
686 else if (name.compare("dwarf") == 0)
687 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000688 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000689 }
690 else if (name.compare("generic") == 0)
691 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000692 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000693 }
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000694 else if (name.compare("container-regs") == 0)
695 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000696 SplitCommaSeparatedRegisterNumberString(value, value_regs, 16);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000697 }
698 else if (name.compare("invalidate-regs") == 0)
699 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000700 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 16);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000701 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000702 }
703
Jason Molenda743e86a2010-06-11 23:44:18 +0000704 reg_info.byte_offset = reg_offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000705 assert (reg_info.byte_size != 0);
706 reg_offset += reg_info.byte_size;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000707 if (!value_regs.empty())
708 {
709 value_regs.push_back(LLDB_INVALID_REGNUM);
710 reg_info.value_regs = value_regs.data();
711 }
712 if (!invalidate_regs.empty())
713 {
714 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
715 reg_info.invalidate_regs = invalidate_regs.data();
716 }
717
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000718 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
719 }
Todd Fiala1a634402014-01-08 07:52:40 +0000720 else
721 {
722 break; // ensure exit before reg_num is incremented
723 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000724 }
725 else
726 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000727 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000728 }
729 }
730
Greg Claytond04f0ed2015-05-26 18:00:51 +0000731 if (m_register_info.GetNumRegisters() > 0)
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000732 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000733 m_register_info.Finalize(GetTarget().GetArchitecture());
734 return;
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000735 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000736
Johnny Chen2fa9de12012-05-14 18:44:23 +0000737 // We didn't get anything if the accumulated reg_num is zero. See if we are
738 // debugging ARM and fill with a hard coded register set until we can get an
739 // updated debugserver down on the devices.
740 // On the other hand, if the accumulated reg_num is positive, see if we can
741 // add composite registers to the existing primordial ones.
Greg Claytond04f0ed2015-05-26 18:00:51 +0000742 bool from_scratch = (m_register_info.GetNumRegisters() == 0);
Johnny Chen2fa9de12012-05-14 18:44:23 +0000743
744 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000745 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
746 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
747
748 // Use the process' architecture instead of the host arch, if available
749 ArchSpec remote_arch;
750 if (remote_process_arch.IsValid ())
751 remote_arch = remote_process_arch;
752 else
753 remote_arch = remote_host_arch;
754
Johnny Chen2fa9de12012-05-14 18:44:23 +0000755 if (!target_arch.IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000756 {
Johnny Chen2fa9de12012-05-14 18:44:23 +0000757 if (remote_arch.IsValid()
Jason Molenda6d9fe8c2015-08-21 00:13:37 +0000758 && (remote_arch.GetMachine() == llvm::Triple::arm || remote_arch.GetMachine() == llvm::Triple::thumb)
Johnny Chen2fa9de12012-05-14 18:44:23 +0000759 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
760 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000761 }
Jason Molenda6d9fe8c2015-08-21 00:13:37 +0000762 else if (target_arch.GetMachine() == llvm::Triple::arm
763 || target_arch.GetMachine() == llvm::Triple::thumb)
Johnny Chen2fa9de12012-05-14 18:44:23 +0000764 {
765 m_register_info.HardcodeARMRegisters(from_scratch);
766 }
767
768 // At this point, we can finalize our register info.
Greg Claytond04f0ed2015-05-26 18:00:51 +0000769 m_register_info.Finalize (GetTarget().GetArchitecture());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000770}
771
772Error
773ProcessGDBRemote::WillLaunch (Module* module)
774{
775 return WillLaunchOrAttach ();
776}
777
778Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000779ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000780{
781 return WillLaunchOrAttach ();
782}
783
784Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000785ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000786{
787 return WillLaunchOrAttach ();
788}
789
790Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000791ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +0000792{
Todd Fialaaf245d12014-06-30 21:05:18 +0000793 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Claytonb766a732011-02-04 01:58:07 +0000794 Error error (WillLaunchOrAttach ());
795
796 if (error.Fail())
797 return error;
798
Greg Clayton2289fa42011-04-30 01:09:13 +0000799 error = ConnectToDebugserver (remote_url);
Greg Claytonb766a732011-02-04 01:58:07 +0000800
801 if (error.Fail())
802 return error;
803 StartAsyncThread ();
804
Greg Claytonc574ede2011-03-10 02:26:48 +0000805 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonb766a732011-02-04 01:58:07 +0000806 if (pid == LLDB_INVALID_PROCESS_ID)
807 {
808 // We don't have a valid process ID, so note that we are connected
809 // and could now request to launch or attach, or get remote process
810 // listings...
811 SetPrivateState (eStateConnected);
812 }
813 else
814 {
815 // We have a valid process
816 SetID (pid);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000817 GetThreadList();
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000818 StringExtractorGDBRemote response;
819 if (m_gdb_comm.GetStopReply(response))
Greg Claytonb766a732011-02-04 01:58:07 +0000820 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000821 SetLastStopPacket(response);
Ewan Crawford78baa192015-05-13 09:18:18 +0000822
823 // '?' Packets must be handled differently in non-stop mode
824 if (GetTarget().GetNonStopModeEnabled())
825 HandleStopReplySequence();
826
Zachary Turner7529df92015-09-01 20:02:29 +0000827 Target &target = GetTarget();
828 if (!target.GetArchitecture().IsValid())
Jason Molendac62bd7b2013-12-21 05:20:36 +0000829 {
830 if (m_gdb_comm.GetProcessArchitecture().IsValid())
831 {
Zachary Turner7529df92015-09-01 20:02:29 +0000832 target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
Jason Molendac62bd7b2013-12-21 05:20:36 +0000833 }
834 else
835 {
Zachary Turner7529df92015-09-01 20:02:29 +0000836 target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molendac62bd7b2013-12-21 05:20:36 +0000837 }
Carlo Kok74389122013-10-14 07:09:13 +0000838 }
839
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000840 const StateType state = SetThreadStopInfo (response);
Greg Clayton2e309072015-07-17 23:42:28 +0000841 if (state != eStateInvalid)
Greg Claytonb766a732011-02-04 01:58:07 +0000842 {
843 SetPrivateState (state);
844 }
845 else
Daniel Malead01b2952012-11-29 21:49:15 +0000846 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 +0000847 }
848 else
Daniel Malead01b2952012-11-29 21:49:15 +0000849 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 +0000850 }
Jason Molenda16d127c2012-05-03 22:37:30 +0000851
Todd Fialaaf245d12014-06-30 21:05:18 +0000852 if (log)
853 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");
854
855
856 if (error.Success()
Jason Molenda16d127c2012-05-03 22:37:30 +0000857 && !GetTarget().GetArchitecture().IsValid()
858 && m_gdb_comm.GetHostArchitecture().IsValid())
859 {
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000860 // Prefer the *process'* architecture over that of the *host*, if available.
861 if (m_gdb_comm.GetProcessArchitecture().IsValid())
862 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
863 else
864 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molenda16d127c2012-05-03 22:37:30 +0000865 }
866
Todd Fialaaf245d12014-06-30 21:05:18 +0000867 if (log)
868 log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": normalized target architecture triple: %s", __FUNCTION__, GetID (), GetTarget ().GetArchitecture ().GetTriple ().getTriple ().c_str ());
869
Chaoren Lin98d0a4b2015-07-14 01:09:28 +0000870 if (error.Success())
Jaydeep Patil6fc590d2015-07-30 05:06:51 +0000871 {
872 PlatformSP platform_sp = GetTarget().GetPlatform();
873 if (platform_sp && platform_sp->IsConnected())
874 SetUnixSignals(platform_sp->GetUnixSignals());
875 else
876 SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
877 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000878
Greg Claytonb766a732011-02-04 01:58:07 +0000879 return error;
880}
881
882Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000883ProcessGDBRemote::WillLaunchOrAttach ()
884{
885 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000886 m_stdio_communication.Clear ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000887 return error;
888}
889
890//----------------------------------------------------------------------
891// Process Control
892//----------------------------------------------------------------------
893Error
Jean-Daniel Dupas7782de92013-12-09 22:52:50 +0000894ProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000895{
Todd Fiala75f47c32014-10-11 21:42:09 +0000896 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton4957bf62010-09-30 21:49:03 +0000897 Error error;
Greg Clayton982c9762011-11-03 21:22:33 +0000898
Todd Fiala75f47c32014-10-11 21:42:09 +0000899 if (log)
900 log->Printf ("ProcessGDBRemote::%s() entered", __FUNCTION__);
901
Greg Clayton982c9762011-11-03 21:22:33 +0000902 uint32_t launch_flags = launch_info.GetFlags().Get();
Chaoren Lind3173f32015-05-29 19:52:29 +0000903 FileSpec stdin_file_spec{};
904 FileSpec stdout_file_spec{};
905 FileSpec stderr_file_spec{};
906 FileSpec working_dir = launch_info.GetWorkingDirectory();
Greg Clayton982c9762011-11-03 21:22:33 +0000907
Zachary Turner696b5282014-08-14 16:01:25 +0000908 const FileAction *file_action;
Greg Clayton982c9762011-11-03 21:22:33 +0000909 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
910 if (file_action)
911 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000912 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000913 stdin_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000914 }
915 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
916 if (file_action)
917 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000918 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000919 stdout_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000920 }
921 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
922 if (file_action)
923 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000924 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000925 stderr_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000926 }
927
Todd Fiala75f47c32014-10-11 21:42:09 +0000928 if (log)
929 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000930 if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
Vince Harron4a8abd32015-02-13 19:15:24 +0000931 log->Printf ("ProcessGDBRemote::%s provided with STDIO paths via launch_info: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000932 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000933 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
934 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
935 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Todd Fiala75f47c32014-10-11 21:42:09 +0000936 else
937 log->Printf ("ProcessGDBRemote::%s no STDIO paths given via launch_info", __FUNCTION__);
938 }
939
Vince Harrondf3f00f2015-02-10 21:09:04 +0000940 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Chaoren Lind3173f32015-05-29 19:52:29 +0000941 if (stdin_file_spec || disable_stdio)
Vince Harrondf3f00f2015-02-10 21:09:04 +0000942 {
943 // the inferior will be reading stdin from the specified file
944 // or stdio is completely disabled
945 m_stdin_forward = false;
946 }
947 else
948 {
949 m_stdin_forward = true;
950 }
951
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000952 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
953 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
954 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000955
Greg Clayton982c9762011-11-03 21:22:33 +0000956 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000957 if (object_file)
958 {
Greg Clayton71337622011-02-24 22:24:29 +0000959 // Make sure we aren't already connected?
960 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000961 {
Greg Clayton91a9b2472013-12-04 19:19:12 +0000962 error = LaunchAndConnectToDebugserver (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000963 }
964
965 if (error.Success())
966 {
967 lldb_utility::PseudoTerminal pty;
968 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000969
Zachary Turner7529df92015-09-01 20:02:29 +0000970 PlatformSP platform_sp (GetTarget().GetPlatform());
Vince Harrondf3f00f2015-02-10 21:09:04 +0000971 if (disable_stdio)
Greg Clayton71337622011-02-24 22:24:29 +0000972 {
Vince Harrondf3f00f2015-02-10 21:09:04 +0000973 // set to /dev/null unless redirected to a file above
Chaoren Lind3173f32015-05-29 19:52:29 +0000974 if (!stdin_file_spec)
975 stdin_file_spec.SetFile("/dev/null", false);
976 if (!stdout_file_spec)
977 stdout_file_spec.SetFile("/dev/null", false);
978 if (!stderr_file_spec)
979 stderr_file_spec.SetFile("/dev/null", false);
Vince Harrondf3f00f2015-02-10 21:09:04 +0000980 }
981 else if (platform_sp && platform_sp->IsHost())
982 {
983 // If the debugserver is local and we aren't disabling STDIO, lets use
984 // a pseudo terminal to instead of relying on the 'O' packets for stdio
985 // since 'O' packets can really slow down debugging if the inferior
986 // does a lot of output.
Chaoren Lind3173f32015-05-29 19:52:29 +0000987 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
988 pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000989 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000990 FileSpec slave_name{pty.GetSlaveName(NULL, 0), false};
991
992 if (!stdin_file_spec)
993 stdin_file_spec = slave_name;
994
995 if (!stdout_file_spec)
996 stdout_file_spec = slave_name;
997
998 if (!stderr_file_spec)
999 stderr_file_spec = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001000 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001001 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +00001002 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 +00001003 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +00001004 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
1005 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
1006 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Greg Clayton71337622011-02-24 22:24:29 +00001007 }
1008
Todd Fiala75f47c32014-10-11 21:42:09 +00001009 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +00001010 log->Printf ("ProcessGDBRemote::%s final STDIO paths after all adjustments: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +00001011 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +00001012 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
1013 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
1014 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Todd Fiala75f47c32014-10-11 21:42:09 +00001015
Chaoren Lind3173f32015-05-29 19:52:29 +00001016 if (stdin_file_spec)
1017 m_gdb_comm.SetSTDIN(stdin_file_spec);
1018 if (stdout_file_spec)
1019 m_gdb_comm.SetSTDOUT(stdout_file_spec);
1020 if (stderr_file_spec)
1021 m_gdb_comm.SetSTDERR(stderr_file_spec);
Greg Clayton71337622011-02-24 22:24:29 +00001022
1023 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
Jim Ingham106d0282014-06-25 02:32:56 +00001024 m_gdb_comm.SetDetachOnError (launch_flags & eLaunchFlagDetachOnError);
Greg Clayton71337622011-02-24 22:24:29 +00001025
Zachary Turner7529df92015-09-01 20:02:29 +00001026 m_gdb_comm.SendLaunchArchPacket (GetTarget().GetArchitecture().GetArchitectureName());
Greg Clayton71337622011-02-24 22:24:29 +00001027
Jason Molendaa3329782014-03-29 18:54:20 +00001028 const char * launch_event_data = launch_info.GetLaunchEventData();
1029 if (launch_event_data != NULL && *launch_event_data != '\0')
1030 m_gdb_comm.SendLaunchEventDataPacket (launch_event_data);
1031
Chaoren Lind3173f32015-05-29 19:52:29 +00001032 if (working_dir)
Greg Clayton71337622011-02-24 22:24:29 +00001033 {
1034 m_gdb_comm.SetWorkingDir (working_dir);
1035 }
1036
1037 // Send the environment and the program + arguments after we connect
Greg Clayton982c9762011-11-03 21:22:33 +00001038 const Args &environment = launch_info.GetEnvironmentEntries();
1039 if (environment.GetArgumentCount())
Greg Clayton71337622011-02-24 22:24:29 +00001040 {
Greg Clayton982c9762011-11-03 21:22:33 +00001041 size_t num_environment_entries = environment.GetArgumentCount();
1042 for (size_t i=0; i<num_environment_entries; ++i)
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001043 {
Greg Clayton982c9762011-11-03 21:22:33 +00001044 const char *env_entry = environment.GetArgumentAtIndex(i);
1045 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Clayton71337622011-02-24 22:24:29 +00001046 break;
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001047 }
Greg Clayton71337622011-02-24 22:24:29 +00001048 }
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001049
Greg Clayton71337622011-02-24 22:24:29 +00001050 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001051 // Scope for the scoped timeout object
1052 GDBRemoteCommunication::ScopedTimeout timeout (m_gdb_comm, 10);
1053
1054 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
1055 if (arg_packet_err == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001056 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001057 std::string error_str;
1058 if (m_gdb_comm.GetLaunchSuccess (error_str))
1059 {
1060 SetID (m_gdb_comm.GetCurrentProcessID ());
1061 }
1062 else
1063 {
1064 error.SetErrorString (error_str.c_str());
1065 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001066 }
1067 else
1068 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001069 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001070 }
Greg Clayton71337622011-02-24 22:24:29 +00001071 }
Tamas Berghammer912800c2015-02-24 10:23:39 +00001072
Greg Clayton71337622011-02-24 22:24:29 +00001073 if (GetID() == LLDB_INVALID_PROCESS_ID)
1074 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001075 if (log)
1076 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton71337622011-02-24 22:24:29 +00001077 KillDebugserverProcess ();
1078 return error;
1079 }
1080
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001081 StringExtractorGDBRemote response;
1082 if (m_gdb_comm.GetStopReply(response))
Greg Clayton71337622011-02-24 22:24:29 +00001083 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001084 SetLastStopPacket(response);
Ewan Crawford78baa192015-05-13 09:18:18 +00001085 // '?' Packets must be handled differently in non-stop mode
1086 if (GetTarget().GetNonStopModeEnabled())
1087 HandleStopReplySequence();
1088
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001089 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
1090
1091 if (process_arch.IsValid())
Jason Molendac62bd7b2013-12-21 05:20:36 +00001092 {
Zachary Turner7529df92015-09-01 20:02:29 +00001093 GetTarget().MergeArchitecture(process_arch);
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001094 }
1095 else
1096 {
1097 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
1098 if (host_arch.IsValid())
Zachary Turner7529df92015-09-01 20:02:29 +00001099 GetTarget().MergeArchitecture(host_arch);
Carlo Kok74389122013-10-14 07:09:13 +00001100 }
1101
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001102 SetPrivateState (SetThreadStopInfo (response));
Greg Clayton71337622011-02-24 22:24:29 +00001103
1104 if (!disable_stdio)
1105 {
1106 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Claytonee95ed52011-11-17 22:14:31 +00001107 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Clayton71337622011-02-24 22:24:29 +00001108 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001109 }
1110 }
Greg Claytonc235ac72011-08-09 05:20:29 +00001111 else
1112 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001113 if (log)
1114 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytonc235ac72011-08-09 05:20:29 +00001115 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001116 }
1117 else
1118 {
1119 // Set our user ID to an invalid process ID.
1120 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton982c9762011-11-03 21:22:33 +00001121 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
1122 exe_module->GetFileSpec().GetFilename().AsCString(),
1123 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001124 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001125 return error;
Greg Clayton4957bf62010-09-30 21:49:03 +00001126
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001127}
1128
1129
1130Error
Greg Claytonb766a732011-02-04 01:58:07 +00001131ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001132{
1133 Error error;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001134 // Only connect if we have a valid connect URL
Vince Harron1b5a74e2015-01-21 22:42:49 +00001135 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton00fe87b2013-12-05 22:58:22 +00001136
1137 if (connect_url && connect_url[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001138 {
Vince Harron1b5a74e2015-01-21 22:42:49 +00001139 if (log)
1140 log->Printf("ProcessGDBRemote::%s Connecting to %s", __FUNCTION__, connect_url);
Greg Clayton00fe87b2013-12-05 22:58:22 +00001141 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
1142 if (conn_ap.get())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001143 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001144 const uint32_t max_retry_count = 50;
1145 uint32_t retry_count = 0;
1146 while (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001147 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001148 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
1149 {
1150 m_gdb_comm.SetConnection (conn_ap.release());
1151 break;
1152 }
1153 else if (error.WasInterrupted())
1154 {
1155 // If we were interrupted, don't keep retrying.
1156 break;
1157 }
1158
1159 retry_count++;
1160
1161 if (retry_count >= max_retry_count)
1162 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001163
Greg Clayton00fe87b2013-12-05 22:58:22 +00001164 usleep (100000);
1165 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001166 }
1167 }
1168
1169 if (!m_gdb_comm.IsConnected())
1170 {
1171 if (error.Success())
1172 error.SetErrorString("not connected to remote gdb server");
1173 return error;
1174 }
1175
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001176
1177 // Start the communications read thread so all incoming data can be
1178 // parsed into packets and queued as they arrive.
1179 if (GetTarget().GetNonStopModeEnabled())
1180 m_gdb_comm.StartReadThread();
1181
Greg Clayton32e0a752011-03-30 18:16:51 +00001182 // We always seem to be able to open a connection to a local port
1183 // so we need to make sure we can then send data to it. If we can't
1184 // then we aren't actually connected to anything, so try and do the
1185 // handshake with the remote GDB server and make sure that goes
1186 // alright.
Greg Claytonfb909312013-11-23 01:58:15 +00001187 if (!m_gdb_comm.HandshakeWithServer (&error))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001188 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001189 m_gdb_comm.Disconnect();
1190 if (error.Success())
1191 error.SetErrorString("not connected to remote gdb server");
1192 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001193 }
Ewan Crawford78baa192015-05-13 09:18:18 +00001194
1195 // Send $QNonStop:1 packet on startup if required
1196 if (GetTarget().GetNonStopModeEnabled())
Ewan Crawfordaa7eda72015-06-24 15:14:26 +00001197 GetTarget().SetNonStopModeEnabled (m_gdb_comm.SetNonStopMode(true));
Ewan Crawford78baa192015-05-13 09:18:18 +00001198
Greg Claytonb30c50c2015-05-29 00:01:55 +00001199 m_gdb_comm.GetEchoSupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001200 m_gdb_comm.GetThreadSuffixSupported ();
Greg Clayton44633992012-04-10 03:22:03 +00001201 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001202 m_gdb_comm.GetHostInfo ();
1203 m_gdb_comm.GetVContSupported ('c');
Jim Inghamcd16df92012-07-20 21:37:13 +00001204 m_gdb_comm.GetVAttachOrWaitSupported();
Ewan Crawford78baa192015-05-13 09:18:18 +00001205
1206 // Ask the remote server for the default thread id
1207 if (GetTarget().GetNonStopModeEnabled())
1208 m_gdb_comm.GetDefaultThreadId(m_initial_tid);
1209
1210
Jim Ingham03afad82012-07-02 05:40:07 +00001211 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1212 for (size_t idx = 0; idx < num_cmds; idx++)
1213 {
1214 StringExtractorGDBRemote response;
Jim Ingham03afad82012-07-02 05:40:07 +00001215 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1216 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001217 return error;
1218}
1219
1220void
Jim Inghambb006ce2014-08-02 00:33:35 +00001221ProcessGDBRemote::DidLaunchOrAttach (ArchSpec& process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001222{
Greg Clayton5160ce52013-03-27 23:08:40 +00001223 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001224 if (log)
1225 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton93d3c8332011-02-16 04:46:07 +00001226 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001227 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001228 BuildDynamicRegisterInfo (false);
Greg Clayton3af9ea52010-11-18 05:57:03 +00001229
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001230 // See if the GDB server supports the qHostInfo information
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001231
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001232
1233 // See if the GDB server supports the qProcessInfo packet, if so
1234 // prefer that over the Host information as it will be more specific
1235 // to our process.
1236
Todd Fiala75f47c32014-10-11 21:42:09 +00001237 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1238 if (remote_process_arch.IsValid())
1239 {
1240 process_arch = remote_process_arch;
1241 if (log)
1242 log->Printf ("ProcessGDBRemote::%s gdb-remote had process architecture, using %s %s",
1243 __FUNCTION__,
1244 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1245 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1246 }
Jim Inghambb006ce2014-08-02 00:33:35 +00001247 else
Todd Fiala75f47c32014-10-11 21:42:09 +00001248 {
Jim Inghambb006ce2014-08-02 00:33:35 +00001249 process_arch = m_gdb_comm.GetHostArchitecture();
Todd Fiala75f47c32014-10-11 21:42:09 +00001250 if (log)
1251 log->Printf ("ProcessGDBRemote::%s gdb-remote did not have process architecture, using gdb-remote host architecture %s %s",
1252 __FUNCTION__,
1253 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1254 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1255 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001256
Jim Inghambb006ce2014-08-02 00:33:35 +00001257 if (process_arch.IsValid())
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001258 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001259 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Greg Claytond314e812011-03-23 00:09:55 +00001260 if (target_arch.IsValid())
1261 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001262 if (log)
1263 log->Printf ("ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1264 __FUNCTION__,
1265 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1266 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
1267
1268 // If the remote host is ARM and we have apple as the vendor, then
Greg Claytond314e812011-03-23 00:09:55 +00001269 // ARM executables and shared libraries can have mixed ARM architectures.
1270 // You can have an armv6 executable, and if the host is armv7, then the
1271 // system will load the best possible architecture for all shared libraries
1272 // it has, so we really need to take the remote host architecture as our
1273 // defacto architecture in this case.
1274
Jason Molenda6d9fe8c2015-08-21 00:13:37 +00001275 if ((process_arch.GetMachine() == llvm::Triple::arm || process_arch.GetMachine() == llvm::Triple::thumb)
1276 && process_arch.GetTriple().getVendor() == llvm::Triple::Apple)
Greg Claytond314e812011-03-23 00:09:55 +00001277 {
Jason Molenda921c01b2014-08-03 21:42:52 +00001278 GetTarget().SetArchitecture (process_arch);
Todd Fiala75f47c32014-10-11 21:42:09 +00001279 if (log)
1280 log->Printf ("ProcessGDBRemote::%s remote process is ARM/Apple, setting target arch to %s %s",
1281 __FUNCTION__,
1282 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1283 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001284 }
1285 else
1286 {
1287 // Fill in what is missing in the triple
Jim Inghambb006ce2014-08-02 00:33:35 +00001288 const llvm::Triple &remote_triple = process_arch.GetTriple();
Tamas Berghammere724af12015-03-13 10:32:37 +00001289 llvm::Triple new_target_triple = target_arch.GetTriple();
1290 if (new_target_triple.getVendorName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001291 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001292 new_target_triple.setVendor (remote_triple.getVendor());
Greg Claytond314e812011-03-23 00:09:55 +00001293
Tamas Berghammere724af12015-03-13 10:32:37 +00001294 if (new_target_triple.getOSName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001295 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001296 new_target_triple.setOS (remote_triple.getOS());
Greg Claytond314e812011-03-23 00:09:55 +00001297
Tamas Berghammere724af12015-03-13 10:32:37 +00001298 if (new_target_triple.getEnvironmentName().size() == 0)
1299 new_target_triple.setEnvironment (remote_triple.getEnvironment());
Greg Clayton70b57652011-05-15 01:25:55 +00001300 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001301
Tamas Berghammere724af12015-03-13 10:32:37 +00001302 ArchSpec new_target_arch = target_arch;
1303 new_target_arch.SetTriple(new_target_triple);
1304 GetTarget().SetArchitecture(new_target_arch);
1305 }
Greg Claytond314e812011-03-23 00:09:55 +00001306 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001307
1308 if (log)
1309 log->Printf ("ProcessGDBRemote::%s final target arch after adjustments for remote architecture: %s %s",
1310 __FUNCTION__,
1311 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1312 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001313 }
1314 else
1315 {
1316 // The target doesn't have a valid architecture yet, set it from
1317 // the architecture we got from the remote GDB server
Jason Molenda921c01b2014-08-03 21:42:52 +00001318 GetTarget().SetArchitecture (process_arch);
Greg Claytond314e812011-03-23 00:09:55 +00001319 }
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001320 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001321 }
1322}
1323
1324void
1325ProcessGDBRemote::DidLaunch ()
1326{
Jim Inghambb006ce2014-08-02 00:33:35 +00001327 ArchSpec process_arch;
1328 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001329}
1330
1331Error
Han Ming Ong84647042012-02-25 01:07:38 +00001332ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1333{
Todd Fiala75f47c32014-10-11 21:42:09 +00001334 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001335 Error error;
Todd Fiala75f47c32014-10-11 21:42:09 +00001336
1337 if (log)
1338 log->Printf ("ProcessGDBRemote::%s()", __FUNCTION__);
1339
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001340 // Clear out and clean up from any current state
1341 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001342 if (attach_pid != LLDB_INVALID_PROCESS_ID)
1343 {
Greg Clayton71337622011-02-24 22:24:29 +00001344 // Make sure we aren't already connected?
1345 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001346 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001347 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001348
1349 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001350 {
Greg Clayton71337622011-02-24 22:24:29 +00001351 const char *error_string = error.AsCString();
1352 if (error_string == NULL)
1353 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1354
1355 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001356 }
Greg Clayton71337622011-02-24 22:24:29 +00001357 }
1358
1359 if (error.Success())
1360 {
Jim Ingham106d0282014-06-25 02:32:56 +00001361 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
Todd Fiala75f47c32014-10-11 21:42:09 +00001362
Greg Clayton71337622011-02-24 22:24:29 +00001363 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001364 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Greg Clayton3b608422011-11-19 02:11:30 +00001365 SetID (attach_pid);
Greg Clayton71337622011-02-24 22:24:29 +00001366 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001367 }
1368 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001369
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001370 return error;
1371}
1372
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001373Error
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001374ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001375{
1376 Error error;
1377 // Clear out and clean up from any current state
1378 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001379
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001380 if (process_name && process_name[0])
1381 {
Greg Clayton71337622011-02-24 22:24:29 +00001382 // Make sure we aren't already connected?
1383 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001384 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001385 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001386
Greg Clayton71337622011-02-24 22:24:29 +00001387 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001388 {
Greg Clayton71337622011-02-24 22:24:29 +00001389 const char *error_string = error.AsCString();
1390 if (error_string == NULL)
1391 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001392
Greg Clayton71337622011-02-24 22:24:29 +00001393 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001394 }
Greg Clayton71337622011-02-24 22:24:29 +00001395 }
1396
1397 if (error.Success())
1398 {
1399 StreamString packet;
1400
Jim Ingham106d0282014-06-25 02:32:56 +00001401 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1402
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001403 if (attach_info.GetWaitForLaunch())
Jim Inghamcd16df92012-07-20 21:37:13 +00001404 {
1405 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1406 {
1407 packet.PutCString ("vAttachWait");
1408 }
1409 else
1410 {
1411 if (attach_info.GetIgnoreExisting())
1412 packet.PutCString("vAttachWait");
1413 else
1414 packet.PutCString ("vAttachOrWait");
1415 }
1416 }
Greg Clayton71337622011-02-24 22:24:29 +00001417 else
1418 packet.PutCString("vAttachName");
1419 packet.PutChar(';');
1420 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1421
1422 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1423
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001424 }
1425 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001426 return error;
1427}
1428
Greg Clayton5df78fa2015-05-23 03:54:53 +00001429void
1430ProcessGDBRemote::DidExit ()
Greg Claytonfbb76342013-11-20 21:07:01 +00001431{
Greg Clayton5df78fa2015-05-23 03:54:53 +00001432 // When we exit, disconnect from the GDB server communications
Greg Claytonfbb76342013-11-20 21:07:01 +00001433 m_gdb_comm.Disconnect();
Greg Claytonfbb76342013-11-20 21:07:01 +00001434}
1435
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001436void
Jim Inghambb006ce2014-08-02 00:33:35 +00001437ProcessGDBRemote::DidAttach (ArchSpec &process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001438{
Jim Inghambb006ce2014-08-02 00:33:35 +00001439 // If you can figure out what the architecture is, fill it in here.
1440 process_arch.Clear();
1441 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001442}
1443
Greg Clayton90ba8112012-12-05 00:16:59 +00001444
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001445Error
1446ProcessGDBRemote::WillResume ()
1447{
Greg Clayton71fc2a32011-02-12 06:28:37 +00001448 m_continue_c_tids.clear();
1449 m_continue_C_tids.clear();
1450 m_continue_s_tids.clear();
1451 m_continue_S_tids.clear();
Greg Clayton2e309072015-07-17 23:42:28 +00001452 m_jstopinfo_sp.reset();
1453 m_jthreadsinfo_sp.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001454 return Error();
1455}
1456
1457Error
1458ProcessGDBRemote::DoResume ()
1459{
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001460 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001461 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001462 if (log)
1463 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytone5219662010-12-03 06:02:24 +00001464
1465 Listener listener ("gdb-remote.resume-packet-sent");
1466 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1467 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00001468 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1469
Greg Claytond1d06e42013-04-20 00:27:58 +00001470 const size_t num_threads = GetThreadList().GetSize();
1471
Greg Clayton71fc2a32011-02-12 06:28:37 +00001472 StreamString continue_packet;
1473 bool continue_packet_error = false;
1474 if (m_gdb_comm.HasAnyVContSupport ())
1475 {
Ewan Crawford78baa192015-05-13 09:18:18 +00001476 if (!GetTarget().GetNonStopModeEnabled() &&
1477 (m_continue_c_tids.size() == num_threads ||
Greg Claytone98008c2014-02-13 23:34:38 +00001478 (m_continue_c_tids.empty() &&
1479 m_continue_C_tids.empty() &&
1480 m_continue_s_tids.empty() &&
Ewan Crawford78baa192015-05-13 09:18:18 +00001481 m_continue_S_tids.empty())))
Greg Clayton71fc2a32011-02-12 06:28:37 +00001482 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001483 // All threads are continuing, just send a "c" packet
1484 continue_packet.PutCString ("c");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001485 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001486 else
1487 {
1488 continue_packet.PutCString ("vCont");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001489
Greg Claytond1d06e42013-04-20 00:27:58 +00001490 if (!m_continue_c_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001491 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001492 if (m_gdb_comm.GetVContSupported ('c'))
1493 {
1494 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)
1495 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1496 }
1497 else
1498 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001499 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001500
1501 if (!continue_packet_error && !m_continue_C_tids.empty())
1502 {
1503 if (m_gdb_comm.GetVContSupported ('C'))
1504 {
1505 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)
1506 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1507 }
1508 else
1509 continue_packet_error = true;
1510 }
Greg Claytone5219662010-12-03 06:02:24 +00001511
Greg Claytond1d06e42013-04-20 00:27:58 +00001512 if (!continue_packet_error && !m_continue_s_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001513 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001514 if (m_gdb_comm.GetVContSupported ('s'))
1515 {
1516 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)
1517 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1518 }
1519 else
1520 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001521 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001522
1523 if (!continue_packet_error && !m_continue_S_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001524 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001525 if (m_gdb_comm.GetVContSupported ('S'))
1526 {
1527 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)
1528 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1529 }
1530 else
1531 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001532 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001533
1534 if (continue_packet_error)
1535 continue_packet.GetString().clear();
Greg Clayton71fc2a32011-02-12 06:28:37 +00001536 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001537 }
1538 else
1539 continue_packet_error = true;
1540
1541 if (continue_packet_error)
1542 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001543 // Either no vCont support, or we tried to use part of the vCont
1544 // packet that wasn't supported by the remote GDB server.
1545 // We need to try and make a simple packet that can do our continue
Greg Clayton71fc2a32011-02-12 06:28:37 +00001546 const size_t num_continue_c_tids = m_continue_c_tids.size();
1547 const size_t num_continue_C_tids = m_continue_C_tids.size();
1548 const size_t num_continue_s_tids = m_continue_s_tids.size();
1549 const size_t num_continue_S_tids = m_continue_S_tids.size();
1550 if (num_continue_c_tids > 0)
1551 {
1552 if (num_continue_c_tids == num_threads)
1553 {
1554 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001555 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001556 continue_packet.PutChar ('c');
1557 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001558 }
1559 else if (num_continue_c_tids == 1 &&
1560 num_continue_C_tids == 0 &&
1561 num_continue_s_tids == 0 &&
1562 num_continue_S_tids == 0 )
1563 {
1564 // Only one thread is continuing
Greg Clayton8b82f082011-04-12 05:54:46 +00001565 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001566 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001567 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001568 }
1569 }
1570
Greg Clayton0c74e782011-06-24 03:21:43 +00001571 if (continue_packet_error && num_continue_C_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001572 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001573 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1574 num_continue_C_tids > 0 &&
1575 num_continue_s_tids == 0 &&
1576 num_continue_S_tids == 0 )
Greg Clayton71fc2a32011-02-12 06:28:37 +00001577 {
1578 const int continue_signo = m_continue_C_tids.front().second;
Greg Clayton0c74e782011-06-24 03:21:43 +00001579 // Only one thread is continuing
Greg Clayton71fc2a32011-02-12 06:28:37 +00001580 if (num_continue_C_tids > 1)
1581 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001582 // More that one thread with a signal, yet we don't have
1583 // vCont support and we are being asked to resume each
1584 // thread with a signal, we need to make sure they are
1585 // all the same signal, or we can't issue the continue
1586 // accurately with the current support...
1587 if (num_continue_C_tids > 1)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001588 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001589 continue_packet_error = false;
1590 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1591 {
1592 if (m_continue_C_tids[i].second != continue_signo)
1593 continue_packet_error = true;
1594 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001595 }
Greg Clayton0c74e782011-06-24 03:21:43 +00001596 if (!continue_packet_error)
1597 m_gdb_comm.SetCurrentThreadForRun (-1);
1598 }
1599 else
1600 {
1601 // Set the continue thread ID
1602 continue_packet_error = false;
1603 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001604 }
1605 if (!continue_packet_error)
1606 {
1607 // Add threads continuing with the same signo...
Greg Clayton71fc2a32011-02-12 06:28:37 +00001608 continue_packet.Printf("C%2.2x", continue_signo);
1609 }
1610 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001611 }
1612
Greg Clayton0c74e782011-06-24 03:21:43 +00001613 if (continue_packet_error && num_continue_s_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001614 {
1615 if (num_continue_s_tids == num_threads)
1616 {
1617 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001618 m_gdb_comm.SetCurrentThreadForRun (-1);
Ewan Crawford76df2882015-06-23 12:32:06 +00001619
1620 // If in Non-Stop-Mode use vCont when stepping
1621 if (GetTarget().GetNonStopModeEnabled())
1622 {
1623 if (m_gdb_comm.GetVContSupported('s'))
1624 continue_packet.PutCString("vCont;s");
1625 else
1626 continue_packet.PutChar('s');
1627 }
1628 else
1629 continue_packet.PutChar('s');
1630
Greg Clayton0c74e782011-06-24 03:21:43 +00001631 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001632 }
1633 else if (num_continue_c_tids == 0 &&
1634 num_continue_C_tids == 0 &&
1635 num_continue_s_tids == 1 &&
1636 num_continue_S_tids == 0 )
1637 {
1638 // Only one thread is stepping
Greg Clayton8b82f082011-04-12 05:54:46 +00001639 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001640 continue_packet.PutChar ('s');
Greg Clayton0c74e782011-06-24 03:21:43 +00001641 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001642 }
1643 }
1644
1645 if (!continue_packet_error && num_continue_S_tids > 0)
1646 {
1647 if (num_continue_S_tids == num_threads)
1648 {
1649 const int step_signo = m_continue_S_tids.front().second;
1650 // Are all threads trying to step with the same signal?
Greg Clayton0c74e782011-06-24 03:21:43 +00001651 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001652 if (num_continue_S_tids > 1)
1653 {
1654 for (size_t i=1; i<num_threads; ++i)
1655 {
1656 if (m_continue_S_tids[i].second != step_signo)
1657 continue_packet_error = true;
1658 }
1659 }
1660 if (!continue_packet_error)
1661 {
1662 // Add threads stepping with the same signo...
Greg Clayton8b82f082011-04-12 05:54:46 +00001663 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001664 continue_packet.Printf("S%2.2x", step_signo);
1665 }
1666 }
1667 else if (num_continue_c_tids == 0 &&
1668 num_continue_C_tids == 0 &&
1669 num_continue_s_tids == 0 &&
1670 num_continue_S_tids == 1 )
1671 {
1672 // Only one thread is stepping with signal
Greg Clayton8b82f082011-04-12 05:54:46 +00001673 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001674 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Clayton0c74e782011-06-24 03:21:43 +00001675 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001676 }
1677 }
1678 }
1679
1680 if (continue_packet_error)
1681 {
1682 error.SetErrorString ("can't make continue packet for this resume");
1683 }
1684 else
1685 {
1686 EventSP event_sp;
1687 TimeValue timeout;
1688 timeout = TimeValue::Now();
1689 timeout.OffsetWithSeconds (5);
Zachary Turneracee96a2014-09-23 18:32:09 +00001690 if (!m_async_thread.IsJoinable())
Jim Inghamb1e2e842012-04-12 18:49:31 +00001691 {
1692 error.SetErrorString ("Trying to resume but the async thread is dead.");
1693 if (log)
1694 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1695 return error;
1696 }
1697
Greg Clayton71fc2a32011-02-12 06:28:37 +00001698 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1699
1700 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Inghamb1e2e842012-04-12 18:49:31 +00001701 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001702 error.SetErrorString("Resume timed out.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00001703 if (log)
1704 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1705 }
1706 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1707 {
1708 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1709 if (log)
1710 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1711 return error;
1712 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001713 }
Greg Claytone5219662010-12-03 06:02:24 +00001714 }
1715
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001716 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001717}
1718
Greg Clayton9e920902012-04-10 02:25:43 +00001719void
Ewan Crawford78baa192015-05-13 09:18:18 +00001720ProcessGDBRemote::HandleStopReplySequence ()
1721{
1722 while(true)
1723 {
1724 // Send vStopped
1725 StringExtractorGDBRemote response;
1726 m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false);
1727
1728 // OK represents end of signal list
1729 if (response.IsOKResponse())
1730 break;
1731
1732 // If not OK or a normal packet we have a problem
1733 if (!response.IsNormalResponse())
1734 break;
1735
1736 SetLastStopPacket(response);
1737 }
1738}
1739
1740void
Greg Clayton9e920902012-04-10 02:25:43 +00001741ProcessGDBRemote::ClearThreadIDList ()
1742{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001743 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001744 m_thread_ids.clear();
1745}
1746
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001747size_t
1748ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue (std::string &value)
1749{
1750 m_thread_ids.clear();
1751 size_t comma_pos;
1752 lldb::tid_t tid;
1753 while ((comma_pos = value.find(',')) != std::string::npos)
1754 {
1755 value[comma_pos] = '\0';
1756 // thread in big endian hex
1757 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1758 if (tid != LLDB_INVALID_THREAD_ID)
1759 m_thread_ids.push_back (tid);
1760 value.erase(0, comma_pos + 1);
1761 }
1762 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1763 if (tid != LLDB_INVALID_THREAD_ID)
1764 m_thread_ids.push_back (tid);
1765 return m_thread_ids.size();
1766}
1767
Greg Clayton9e920902012-04-10 02:25:43 +00001768bool
1769ProcessGDBRemote::UpdateThreadIDList ()
1770{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001771 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001772
Greg Clayton2e309072015-07-17 23:42:28 +00001773 if (m_jthreadsinfo_sp)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001774 {
1775 // If we have the JSON threads info, we can get the thread list from that
Greg Clayton2e309072015-07-17 23:42:28 +00001776 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001777 if (thread_infos && thread_infos->GetSize() > 0)
1778 {
1779 m_thread_ids.clear();
1780 thread_infos->ForEach([this](StructuredData::Object* object) -> bool {
1781 StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1782 if (thread_dict)
1783 {
1784 // Set the thread stop info from the JSON dictionary
1785 SetThreadStopInfo (thread_dict);
1786 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1787 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1788 m_thread_ids.push_back(tid);
1789 }
1790 return true; // Keep iterating through all thread_info objects
1791 });
1792 }
1793 if (!m_thread_ids.empty())
1794 return true;
1795 }
1796 else
1797 {
1798 // See if we can get the thread IDs from the current stop reply packets
1799 // that might contain a "threads" key/value pair
1800
1801 // Lock the thread stack while we access it
1802 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
1803 // Get the number of stop packets on the stack
1804 int nItems = m_stop_packet_stack.size();
1805 // Iterate over them
1806 for (int i = 0; i < nItems; i++)
1807 {
1808 // Get the thread stop info
1809 StringExtractorGDBRemote &stop_info = m_stop_packet_stack[i];
1810 const std::string &stop_info_str = stop_info.GetStringRef();
1811 const size_t threads_pos = stop_info_str.find(";threads:");
1812 if (threads_pos != std::string::npos)
1813 {
1814 const size_t start = threads_pos + strlen(";threads:");
1815 const size_t end = stop_info_str.find(';', start);
1816 if (end != std::string::npos)
1817 {
1818 std::string value = stop_info_str.substr(start, end - start);
1819 if (UpdateThreadIDsFromStopReplyThreadsValue(value))
1820 return true;
1821 }
1822 }
1823 }
1824 }
1825
Greg Clayton9e920902012-04-10 02:25:43 +00001826 bool sequence_mutex_unavailable = false;
1827 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1828 if (sequence_mutex_unavailable)
1829 {
Greg Clayton9e920902012-04-10 02:25:43 +00001830 return false; // We just didn't get the list
1831 }
1832 return true;
1833}
1834
Greg Clayton9fc13552012-04-10 00:18:59 +00001835bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001836ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001837{
1838 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +00001839 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Clayton73b472d2010-10-27 03:32:59 +00001840 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +00001841 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton9e920902012-04-10 02:25:43 +00001842
1843 size_t num_thread_ids = m_thread_ids.size();
1844 // The "m_thread_ids" thread ID list should always be updated after each stop
1845 // reply packet, but in case it isn't, update it here.
1846 if (num_thread_ids == 0)
1847 {
1848 if (!UpdateThreadIDList ())
1849 return false;
1850 num_thread_ids = m_thread_ids.size();
1851 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001852
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001853 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001854 if (num_thread_ids > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001855 {
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001856 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001857 {
Greg Clayton9e920902012-04-10 02:25:43 +00001858 tid_t tid = m_thread_ids[i];
Greg Clayton160c9d82013-05-01 21:54:04 +00001859 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001860 if (!thread_sp)
Jim Inghamdee1bc92013-06-22 00:27:45 +00001861 {
Jim Ingham4f465cf2012-10-10 18:32:14 +00001862 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001863 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1864 log->Printf(
1865 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001866 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001867 thread_sp->GetID());
1868 }
1869 else
1870 {
1871 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1872 log->Printf(
1873 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001874 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001875 thread_sp->GetID());
1876 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001877 new_thread_list.AddThread(thread_sp);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001878 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001879 }
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001880
1881 // Whatever that is left in old_thread_list_copy are not
1882 // present in new_thread_list. Remove non-existent threads from internal id table.
1883 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1884 for (size_t i=0; i<old_num_thread_ids; i++)
1885 {
1886 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1887 if (old_thread_sp)
1888 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001889 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001890 m_thread_id_to_index_id_map.erase(old_thread_id);
1891 }
1892 }
1893
Greg Clayton9fc13552012-04-10 00:18:59 +00001894 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001895}
1896
Greg Clayton2e309072015-07-17 23:42:28 +00001897
Greg Clayton358cf1e2015-06-25 21:46:34 +00001898bool
Greg Clayton2e309072015-07-17 23:42:28 +00001899ProcessGDBRemote::GetThreadStopInfoFromJSON (ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001900{
1901 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet
Greg Clayton2e309072015-07-17 23:42:28 +00001902 if (thread_infos_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001903 {
Greg Clayton2e309072015-07-17 23:42:28 +00001904 StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
Greg Clayton358cf1e2015-06-25 21:46:34 +00001905 if (thread_infos)
1906 {
1907 lldb::tid_t tid;
1908 const size_t n = thread_infos->GetSize();
1909 for (size_t i=0; i<n; ++i)
1910 {
1911 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1912 if (thread_dict)
1913 {
1914 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid, LLDB_INVALID_THREAD_ID))
1915 {
1916 if (tid == thread->GetID())
Greg Clayton2e309072015-07-17 23:42:28 +00001917 return (bool)SetThreadStopInfo(thread_dict);
Greg Clayton358cf1e2015-06-25 21:46:34 +00001918 }
1919 }
1920 }
1921 }
1922 }
Greg Clayton2e309072015-07-17 23:42:28 +00001923 return false;
1924}
1925
1926bool
1927ProcessGDBRemote::CalculateThreadStopInfo (ThreadGDBRemote *thread)
1928{
1929 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet
1930 if (GetThreadStopInfoFromJSON (thread, m_jthreadsinfo_sp))
1931 return true;
1932
1933 // See if we got thread stop info for any threads valid stop info reasons threads
1934 // via the "jstopinfo" packet stop reply packet key/value pair?
1935 if (m_jstopinfo_sp)
1936 {
1937 // If we have "jstopinfo" then we have stop descriptions for all threads
1938 // that have stop reasons, and if there is no entry for a thread, then
1939 // it has no stop reason.
1940 thread->GetRegisterContext()->InvalidateIfNeeded(true);
1941 if (!GetThreadStopInfoFromJSON (thread, m_jstopinfo_sp))
1942 {
1943 thread->SetStopInfo (StopInfoSP());
1944 }
1945 return true;
1946 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00001947
1948 // Fall back to using the qThreadStopInfo packet
1949 StringExtractorGDBRemote stop_packet;
1950 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1951 return SetThreadStopInfo (stop_packet) == eStateStopped;
1952 return false;
1953}
1954
1955
1956ThreadSP
1957ProcessGDBRemote::SetThreadStopInfo (lldb::tid_t tid,
1958 ExpeditedRegisterMap &expedited_register_map,
1959 uint8_t signo,
1960 const std::string &thread_name,
1961 const std::string &reason,
1962 const std::string &description,
1963 uint32_t exc_type,
1964 const std::vector<addr_t> &exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001965 addr_t thread_dispatch_qaddr,
1966 bool queue_vars_valid, // Set to true if queue_name, queue_kind and queue_serial are valid
1967 std::string &queue_name,
1968 QueueKind queue_kind,
1969 uint64_t queue_serial)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001970{
1971 ThreadSP thread_sp;
1972 if (tid != LLDB_INVALID_THREAD_ID)
1973 {
1974 // Scope for "locker" below
1975 {
1976 // m_thread_list_real does have its own mutex, but we need to
1977 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1978 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1979 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1980 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1981
1982 if (!thread_sp)
1983 {
1984 // Create the thread if we need to
1985 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1986 m_thread_list_real.AddThread(thread_sp);
1987 }
1988 }
1989
1990 if (thread_sp)
1991 {
1992 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1993 gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001994
Greg Clayton358cf1e2015-06-25 21:46:34 +00001995 for (const auto &pair : expedited_register_map)
1996 {
1997 StringExtractor reg_value_extractor;
1998 reg_value_extractor.GetStringRef() = pair.second;
1999 gdb_thread->PrivateSetRegisterValue (pair.first, reg_value_extractor);
2000 }
2001
Greg Clayton358cf1e2015-06-25 21:46:34 +00002002 thread_sp->SetName (thread_name.empty() ? NULL : thread_name.c_str());
2003
2004 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002005 // Check if the GDB server was able to provide the queue name, kind and serial number
2006 if (queue_vars_valid)
2007 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind, queue_serial);
2008 else
2009 gdb_thread->ClearQueueInfo();
2010
Greg Clayton2e309072015-07-17 23:42:28 +00002011 // Make sure we update our thread stop reason just once
2012 if (!thread_sp->StopInfoIsUpToDate())
Greg Clayton358cf1e2015-06-25 21:46:34 +00002013 {
Greg Clayton2e309072015-07-17 23:42:28 +00002014 thread_sp->SetStopInfo (StopInfoSP());
Greg Clayton358cf1e2015-06-25 21:46:34 +00002015
Greg Clayton2e309072015-07-17 23:42:28 +00002016 if (exc_type != 0)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002017 {
Greg Clayton2e309072015-07-17 23:42:28 +00002018 const size_t exc_data_size = exc_data.size();
2019
2020 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
2021 exc_type,
2022 exc_data_size,
2023 exc_data_size >= 1 ? exc_data[0] : 0,
2024 exc_data_size >= 2 ? exc_data[1] : 0,
2025 exc_data_size >= 3 ? exc_data[2] : 0));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002026 }
Greg Clayton2e309072015-07-17 23:42:28 +00002027 else
Greg Clayton358cf1e2015-06-25 21:46:34 +00002028 {
Greg Clayton2e309072015-07-17 23:42:28 +00002029 bool handled = false;
2030 bool did_exec = false;
2031 if (!reason.empty())
Greg Clayton358cf1e2015-06-25 21:46:34 +00002032 {
Greg Clayton2e309072015-07-17 23:42:28 +00002033 if (reason.compare("trace") == 0)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002034 {
Greg Clayton2e309072015-07-17 23:42:28 +00002035 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
2036 handled = true;
2037 }
2038 else if (reason.compare("breakpoint") == 0)
2039 {
2040 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
2041 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2042 if (bp_site_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002043 {
Greg Clayton2e309072015-07-17 23:42:28 +00002044 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2045 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2046 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2047 handled = true;
2048 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2049 {
2050 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2051 }
2052 else
2053 {
2054 StopInfoSP invalid_stop_info_sp;
2055 thread_sp->SetStopInfo (invalid_stop_info_sp);
2056 }
2057 }
2058 }
2059 else if (reason.compare("trap") == 0)
2060 {
2061 // Let the trap just use the standard signal stop reason below...
2062 }
2063 else if (reason.compare("watchpoint") == 0)
2064 {
2065 StringExtractor desc_extractor(description.c_str());
2066 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
2067 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
Jaydeep Patil83143502015-08-13 03:44:09 +00002068 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
Greg Clayton2e309072015-07-17 23:42:28 +00002069 watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
2070 if (wp_addr != LLDB_INVALID_ADDRESS)
2071 {
2072 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2073 if (wp_sp)
2074 {
2075 wp_sp->SetHardwareIndex(wp_index);
2076 watch_id = wp_sp->GetID();
2077 }
2078 }
2079 if (watch_id == LLDB_INVALID_WATCH_ID)
2080 {
2081 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_WATCHPOINTS));
2082 if (log) log->Printf ("failed to find watchpoint");
2083 }
Jaydeep Patil83143502015-08-13 03:44:09 +00002084 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id, wp_hit_addr));
Greg Clayton2e309072015-07-17 23:42:28 +00002085 handled = true;
2086 }
2087 else if (reason.compare("exception") == 0)
2088 {
2089 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
2090 handled = true;
2091 }
2092 else if (reason.compare("exec") == 0)
2093 {
2094 did_exec = true;
2095 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
2096 handled = true;
2097 }
2098 }
2099
2100 if (!handled && signo && did_exec == false)
2101 {
2102 if (signo == SIGTRAP)
2103 {
2104 // Currently we are going to assume SIGTRAP means we are either
2105 // hitting a breakpoint or hardware single stepping.
2106 handled = true;
2107 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
2108 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2109
2110 if (bp_site_sp)
2111 {
2112 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2113 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2114 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2115 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2116 {
2117 if(m_breakpoint_pc_offset != 0)
2118 thread_sp->GetRegisterContext()->SetPC(pc);
2119 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2120 }
2121 else
2122 {
2123 StopInfoSP invalid_stop_info_sp;
2124 thread_sp->SetStopInfo (invalid_stop_info_sp);
2125 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002126 }
2127 else
2128 {
Greg Clayton2e309072015-07-17 23:42:28 +00002129 // If we were stepping then assume the stop was the result of the trace. If we were
2130 // not stepping then report the SIGTRAP.
2131 // FIXME: We are still missing the case where we single step over a trap instruction.
2132 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
2133 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
2134 else
2135 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo, description.c_str()));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002136 }
2137 }
Greg Clayton2e309072015-07-17 23:42:28 +00002138 if (!handled)
2139 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo, description.c_str()));
2140 }
2141
2142 if (!description.empty())
2143 {
2144 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
2145 if (stop_info_sp)
2146 {
2147 const char *stop_info_desc = stop_info_sp->GetDescription();
2148 if (!stop_info_desc || !stop_info_desc[0])
2149 stop_info_sp->SetDescription (description.c_str());
2150 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002151 else
2152 {
Greg Clayton2e309072015-07-17 23:42:28 +00002153 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002154 }
2155 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002156 }
2157 }
2158 }
2159 }
2160 return thread_sp;
2161}
2162
Greg Clayton2e309072015-07-17 23:42:28 +00002163lldb::ThreadSP
Greg Clayton358cf1e2015-06-25 21:46:34 +00002164ProcessGDBRemote::SetThreadStopInfo (StructuredData::Dictionary *thread_dict)
2165{
2166 static ConstString g_key_tid("tid");
2167 static ConstString g_key_name("name");
2168 static ConstString g_key_reason("reason");
2169 static ConstString g_key_metype("metype");
2170 static ConstString g_key_medata("medata");
2171 static ConstString g_key_qaddr("qaddr");
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002172 static ConstString g_key_queue_name("qname");
2173 static ConstString g_key_queue_kind("qkind");
2174 static ConstString g_key_queue_serial("qserial");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002175 static ConstString g_key_registers("registers");
2176 static ConstString g_key_memory("memory");
2177 static ConstString g_key_address("address");
2178 static ConstString g_key_bytes("bytes");
2179 static ConstString g_key_description("description");
Pavel Labath4a4bb122015-07-16 14:14:35 +00002180 static ConstString g_key_signal("signal");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002181
2182 // Stop with signal and thread info
2183 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2184 uint8_t signo = 0;
2185 std::string value;
2186 std::string thread_name;
2187 std::string reason;
2188 std::string description;
2189 uint32_t exc_type = 0;
2190 std::vector<addr_t> exc_data;
2191 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2192 ExpeditedRegisterMap expedited_register_map;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002193 bool queue_vars_valid = false;
2194 std::string queue_name;
2195 QueueKind queue_kind = eQueueKindUnknown;
2196 uint64_t queue_serial = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002197 // Iterate through all of the thread dictionary key/value pairs from the structured data dictionary
2198
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002199 thread_dict->ForEach([this,
2200 &tid,
2201 &expedited_register_map,
2202 &thread_name,
2203 &signo,
2204 &reason,
2205 &description,
2206 &exc_type,
2207 &exc_data,
2208 &thread_dispatch_qaddr,
2209 &queue_vars_valid,
2210 &queue_name,
2211 &queue_kind,
2212 &queue_serial]
2213 (ConstString key, StructuredData::Object* object) -> bool
Greg Clayton358cf1e2015-06-25 21:46:34 +00002214 {
2215 if (key == g_key_tid)
2216 {
2217 // thread in big endian hex
2218 tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
2219 }
2220 else if (key == g_key_metype)
2221 {
2222 // exception type in big endian hex
2223 exc_type = object->GetIntegerValue(0);
2224 }
2225 else if (key == g_key_medata)
2226 {
2227 // exception data in big endian hex
2228 StructuredData::Array *array = object->GetAsArray();
2229 if (array)
2230 {
2231 array->ForEach([&exc_data](StructuredData::Object* object) -> bool {
2232 exc_data.push_back(object->GetIntegerValue());
2233 return true; // Keep iterating through all array items
2234 });
2235 }
2236 }
2237 else if (key == g_key_name)
2238 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002239 thread_name = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002240 }
2241 else if (key == g_key_qaddr)
2242 {
2243 thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
2244 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002245 else if (key == g_key_queue_name)
2246 {
2247 queue_vars_valid = true;
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002248 queue_name = object->GetStringValue();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002249 }
2250 else if (key == g_key_queue_kind)
2251 {
2252 std::string queue_kind_str = object->GetStringValue();
2253 if (queue_kind_str == "serial")
2254 {
2255 queue_vars_valid = true;
2256 queue_kind = eQueueKindSerial;
2257 }
2258 else if (queue_kind_str == "concurrent")
2259 {
2260 queue_vars_valid = true;
2261 queue_kind = eQueueKindConcurrent;
2262 }
2263 }
2264 else if (key == g_key_queue_serial)
2265 {
2266 queue_serial = object->GetIntegerValue(0);
2267 if (queue_serial != 0)
2268 queue_vars_valid = true;
2269 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002270 else if (key == g_key_reason)
2271 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002272 reason = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002273 }
2274 else if (key == g_key_description)
2275 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002276 description = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002277 }
2278 else if (key == g_key_registers)
2279 {
2280 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2281
2282 if (registers_dict)
2283 {
2284 registers_dict->ForEach([&expedited_register_map](ConstString key, StructuredData::Object* object) -> bool {
2285 const uint32_t reg = StringConvert::ToUInt32 (key.GetCString(), UINT32_MAX, 10);
2286 if (reg != UINT32_MAX)
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002287 expedited_register_map[reg] = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002288 return true; // Keep iterating through all array items
2289 });
2290 }
2291 }
2292 else if (key == g_key_memory)
2293 {
2294 StructuredData::Array *array = object->GetAsArray();
2295 if (array)
2296 {
2297 array->ForEach([this](StructuredData::Object* object) -> bool {
2298 StructuredData::Dictionary *mem_cache_dict = object->GetAsDictionary();
2299 if (mem_cache_dict)
2300 {
2301 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2302 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>("address", mem_cache_addr))
2303 {
2304 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
2305 {
2306 StringExtractor bytes;
2307 if (mem_cache_dict->GetValueForKeyAsString("bytes", bytes.GetStringRef()))
2308 {
2309 bytes.SetFilePos(0);
2310
2311 const size_t byte_size = bytes.GetStringRef().size()/2;
2312 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2313 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2314 if (bytes_copied == byte_size)
2315 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2316 }
2317 }
2318 }
2319 }
2320 return true; // Keep iterating through all array items
2321 });
2322 }
2323
2324 }
Pavel Labath4a4bb122015-07-16 14:14:35 +00002325 else if (key == g_key_signal)
2326 signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002327 return true; // Keep iterating through all dictionary key/value pairs
2328 });
2329
Greg Clayton2e309072015-07-17 23:42:28 +00002330 return SetThreadStopInfo (tid,
2331 expedited_register_map,
2332 signo,
2333 thread_name,
2334 reason,
2335 description,
2336 exc_type,
2337 exc_data,
2338 thread_dispatch_qaddr,
2339 queue_vars_valid,
2340 queue_name,
2341 queue_kind,
2342 queue_serial);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002343}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002344
2345StateType
2346ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
2347{
Greg Claytondd0e5a52011-06-02 22:22:38 +00002348 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002349 const char stop_type = stop_packet.GetChar();
2350 switch (stop_type)
2351 {
2352 case 'T':
2353 case 'S':
2354 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00002355 // This is a bit of a hack, but is is required. If we did exec, we
2356 // need to clear our thread lists and also know to rebuild our dynamic
2357 // register info before we lookup and threads and populate the expedited
2358 // register values so we need to know this right away so we can cleanup
2359 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00002360 const uint32_t stop_id = GetStopID();
2361 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00002362 {
2363 // Our first stop, make sure we have a process ID, and also make
2364 // sure we know about our registers
2365 if (GetID() == LLDB_INVALID_PROCESS_ID)
2366 {
Greg Claytonc574ede2011-03-10 02:26:48 +00002367 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00002368 if (pid != LLDB_INVALID_PROCESS_ID)
2369 SetID (pid);
2370 }
2371 BuildDynamicRegisterInfo (true);
2372 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002373 // Stop with signal and thread info
Greg Clayton358cf1e2015-06-25 21:46:34 +00002374 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002375 const uint8_t signo = stop_packet.GetHexU8();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002376 std::string key;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002377 std::string value;
2378 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00002379 std::string reason;
2380 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002381 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00002382 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002383 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton0b90be12015-06-23 21:27:50 +00002384 bool queue_vars_valid = false; // says if locals below that start with "queue_" are valid
2385 std::string queue_name;
2386 QueueKind queue_kind = eQueueKindUnknown;
2387 uint64_t queue_serial = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002388 ExpeditedRegisterMap expedited_register_map;
2389 while (stop_packet.GetNameColonValue(key, value))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002390 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002391 if (key.compare("metype") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002392 {
2393 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002394 exc_type = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002395 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002396 else if (key.compare("medata") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002397 {
2398 // exception data in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002399 exc_data.push_back(StringConvert::ToUInt64 (value.c_str(), 0, 16));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002400 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002401 else if (key.compare("thread") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002402 {
2403 // thread in big endian hex
Greg Clayton358cf1e2015-06-25 21:46:34 +00002404 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002405 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002406 else if (key.compare("threads") == 0)
Greg Clayton9e920902012-04-10 02:25:43 +00002407 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002408 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00002409 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00002410 // A comma separated list of all threads in the current
2411 // process that includes the thread for this stop reply
2412 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00002413 size_t comma_pos;
2414 lldb::tid_t tid;
2415 while ((comma_pos = value.find(',')) != std::string::npos)
2416 {
2417 value[comma_pos] = '\0';
2418 // thread in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002419 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00002420 if (tid != LLDB_INVALID_THREAD_ID)
2421 m_thread_ids.push_back (tid);
2422 value.erase(0, comma_pos + 1);
Greg Clayton9e920902012-04-10 02:25:43 +00002423 }
Vince Harron5275aaa2015-01-15 20:08:35 +00002424 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00002425 if (tid != LLDB_INVALID_THREAD_ID)
2426 m_thread_ids.push_back (tid);
2427 }
Greg Clayton2e309072015-07-17 23:42:28 +00002428 else if (key.compare("jstopinfo") == 0)
Greg Claytona5801ad2015-07-15 22:59:03 +00002429 {
2430 StringExtractor json_extractor;
2431 // Swap "value" over into "name_extractor"
2432 json_extractor.GetStringRef().swap(value);
2433 // Now convert the HEX bytes into a string value
2434 json_extractor.GetHexByteString (value);
2435
2436 // This JSON contains thread IDs and thread stop info for all threads.
2437 // It doesn't contain expedited registers, memory or queue info.
Greg Clayton2e309072015-07-17 23:42:28 +00002438 m_jstopinfo_sp = StructuredData::ParseJSON (value);
Greg Claytona5801ad2015-07-15 22:59:03 +00002439 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002440 else if (key.compare("hexname") == 0)
Greg Claytonde9d0492011-01-08 03:17:57 +00002441 {
2442 StringExtractor name_extractor;
2443 // Swap "value" over into "name_extractor"
2444 name_extractor.GetStringRef().swap(value);
2445 // Now convert the HEX bytes into a string value
2446 name_extractor.GetHexByteString (value);
2447 thread_name.swap (value);
2448 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002449 else if (key.compare("name") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002450 {
2451 thread_name.swap (value);
2452 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002453 else if (key.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002454 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002455 thread_dispatch_qaddr = StringConvert::ToUInt64 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002456 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002457 else if (key.compare("qname") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002458 {
2459 queue_vars_valid = true;
2460 StringExtractor name_extractor;
2461 // Swap "value" over into "name_extractor"
2462 name_extractor.GetStringRef().swap(value);
2463 // Now convert the HEX bytes into a string value
2464 name_extractor.GetHexByteString (value);
2465 queue_name.swap (value);
2466 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002467 else if (key.compare("qkind") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002468 {
Greg Clayton0b90be12015-06-23 21:27:50 +00002469 if (value == "serial")
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002470 {
2471 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002472 queue_kind = eQueueKindSerial;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002473 }
Greg Clayton0b90be12015-06-23 21:27:50 +00002474 else if (value == "concurrent")
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002475 {
2476 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002477 queue_kind = eQueueKindConcurrent;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002478 }
Greg Clayton0b90be12015-06-23 21:27:50 +00002479 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002480 else if (key.compare("qserial") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002481 {
Greg Clayton0b90be12015-06-23 21:27:50 +00002482 queue_serial = StringConvert::ToUInt64 (value.c_str(), 0, 0);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002483 if (queue_serial != 0)
2484 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002485 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002486 else if (key.compare("reason") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002487 {
2488 reason.swap(value);
2489 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002490 else if (key.compare("description") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002491 {
2492 StringExtractor desc_extractor;
2493 // Swap "value" over into "name_extractor"
2494 desc_extractor.GetStringRef().swap(value);
2495 // Now convert the HEX bytes into a string value
Chaoren Lin28e57422015-02-03 01:51:25 +00002496 desc_extractor.GetHexByteString (value);
2497 description.swap(value);
Greg Claytona658fd22011-06-04 01:26:29 +00002498 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002499 else if (key.compare("memory") == 0)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002500 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002501 // Expedited memory. GDB servers can choose to send back expedited memory
2502 // that can populate the L1 memory cache in the process so that things like
2503 // the frame pointer backchain can be expedited. This will help stack
2504 // backtracing be more efficient by not having to send as many memory read
2505 // requests down the remote GDB server.
Chaoren Lin7a306082015-06-23 03:17:01 +00002506
Greg Clayton358cf1e2015-06-25 21:46:34 +00002507 // Key/value pair format: memory:<addr>=<bytes>;
2508 // <addr> is a number whose base will be interpreted by the prefix:
2509 // "0x[0-9a-fA-F]+" for hex
2510 // "0[0-7]+" for octal
2511 // "[1-9]+" for decimal
2512 // <bytes> is native endian ASCII hex bytes just like the register values
2513 llvm::StringRef value_ref(value);
2514 std::pair<llvm::StringRef, llvm::StringRef> pair;
2515 pair = value_ref.split('=');
2516 if (!pair.first.empty() && !pair.second.empty())
2517 {
2518 std::string addr_str(pair.first.str());
2519 const lldb::addr_t mem_cache_addr = StringConvert::ToUInt64(addr_str.c_str(), LLDB_INVALID_ADDRESS, 0);
2520 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002521 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002522 StringExtractor bytes;
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002523 bytes.GetStringRef() = pair.second.str();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002524 const size_t byte_size = bytes.GetStringRef().size()/2;
2525 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2526 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2527 if (bytes_copied == byte_size)
2528 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
Greg Clayton3e06bd92011-01-09 21:07:35 +00002529 }
2530 }
2531 }
Jaydeep Patil725666c2015-08-13 03:46:01 +00002532 else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 || key.compare("awatch") == 0)
2533 {
2534 // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2535 lldb::addr_t wp_addr = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
2536 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2537 uint32_t wp_index = LLDB_INVALID_INDEX32;
2538
2539 if (wp_sp)
2540 wp_index = wp_sp->GetHardwareIndex();
2541
2542 reason = "watchpoint";
2543 StreamString ostr;
2544 ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
2545 description = ostr.GetString().c_str();
2546 }
Stephane Sezer2618e912015-08-21 16:51:56 +00002547 else if (key.compare("library") == 0)
2548 {
2549 LoadModules();
2550 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002551 else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1]))
2552 {
2553 uint32_t reg = StringConvert::ToUInt32 (key.c_str(), UINT32_MAX, 16);
2554 if (reg != UINT32_MAX)
2555 expedited_register_map[reg] = std::move(value);
2556 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002557 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002558
Bhushan D. Attarde1e271df2015-07-24 04:06:20 +00002559 if (tid == LLDB_INVALID_THREAD_ID)
2560 {
2561 // A thread id may be invalid if the response is old style 'S' packet which does not provide the
2562 // thread information. So update the thread list and choose the first one.
2563 UpdateThreadIDList ();
2564
2565 if (!m_thread_ids.empty ())
2566 {
2567 tid = m_thread_ids.front ();
2568 }
2569 }
2570
Greg Clayton358cf1e2015-06-25 21:46:34 +00002571 ThreadSP thread_sp = SetThreadStopInfo (tid,
2572 expedited_register_map,
2573 signo,
2574 thread_name,
2575 reason,
2576 description,
2577 exc_type,
2578 exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002579 thread_dispatch_qaddr,
2580 queue_vars_valid,
2581 queue_name,
2582 queue_kind,
2583 queue_serial);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002584
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002585 return eStateStopped;
2586 }
2587 break;
2588
2589 case 'W':
Todd Fialaff6131a2014-05-19 04:57:23 +00002590 case 'X':
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002591 // process exited
2592 return eStateExited;
2593
2594 default:
2595 break;
2596 }
2597 return eStateInvalid;
2598}
2599
2600void
2601ProcessGDBRemote::RefreshStateAfterStop ()
2602{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002603 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00002604 m_thread_ids.clear();
2605 // Set the thread stop info. It might have a "threads" key whose value is
2606 // a list of all thread IDs in the current process, so m_thread_ids might
2607 // get set.
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002608
2609 // Scope for the lock
2610 {
2611 // Lock the thread stack while we access it
2612 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
2613 // Get the number of stop packets on the stack
2614 int nItems = m_stop_packet_stack.size();
2615 // Iterate over them
2616 for (int i = 0; i < nItems; i++)
2617 {
2618 // Get the thread stop info
2619 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2620 // Process thread stop info
2621 SetThreadStopInfo(stop_info);
2622 }
2623 // Clear the thread stop stack
2624 m_stop_packet_stack.clear();
2625 }
2626
Greg Clayton9e920902012-04-10 02:25:43 +00002627 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2628 if (m_thread_ids.empty())
2629 {
2630 // No, we need to fetch the thread list manually
2631 UpdateThreadIDList();
2632 }
2633
Ewan Crawford78baa192015-05-13 09:18:18 +00002634 // If we have queried for a default thread id
2635 if (m_initial_tid != LLDB_INVALID_THREAD_ID)
2636 {
2637 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2638 m_initial_tid = LLDB_INVALID_THREAD_ID;
2639 }
2640
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002641 // Let all threads recover from stopping and do any clean up based
2642 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002643 m_thread_list_real.RefreshStateAfterStop();
Greg Clayton9e920902012-04-10 02:25:43 +00002644
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002645}
2646
2647Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002648ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002649{
2650 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002651
Greg Clayton6ed95942011-01-22 07:12:45 +00002652 bool timed_out = false;
2653 Mutex::Locker locker;
Greg Clayton513c26c2011-01-29 07:10:55 +00002654
2655 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002656 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002657 // We are being asked to halt during an attach. We need to just close
2658 // our file handle and debugserver will go away, and we can be done...
2659 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00002660 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002661 else
2662 {
Greg Clayton2687cd12012-03-29 01:55:41 +00002663 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton513c26c2011-01-29 07:10:55 +00002664 {
2665 if (timed_out)
2666 error.SetErrorString("timed out sending interrupt packet");
2667 else
2668 error.SetErrorString("unknown error sending interrupt packet");
2669 }
Greg Clayton2687cd12012-03-29 01:55:41 +00002670
2671 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton513c26c2011-01-29 07:10:55 +00002672 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002673 return error;
2674}
2675
2676Error
Jim Inghamacff8952013-05-02 00:27:30 +00002677ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002678{
2679 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002680 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00002681 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00002682 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2683
Jim Inghamacff8952013-05-02 00:27:30 +00002684 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002685 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002686 {
Jim Inghamacff8952013-05-02 00:27:30 +00002687 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002688 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
2689 else
Jim Inghamacff8952013-05-02 00:27:30 +00002690 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00002691 }
Jim Inghamacff8952013-05-02 00:27:30 +00002692
2693 if (!error.Success())
2694 return error;
2695
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002696 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00002697 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002698
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002699 SetPrivateState (eStateDetached);
2700 ResumePrivateStateThread();
2701
2702 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00002703 return error;
2704}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002705
Jim Ingham43c555d2012-07-04 00:35:43 +00002706
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002707Error
2708ProcessGDBRemote::DoDestroy ()
2709{
2710 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002711 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002712 if (log)
2713 log->Printf ("ProcessGDBRemote::DoDestroy()");
2714
Jim Ingham43c555d2012-07-04 00:35:43 +00002715 // There is a bug in older iOS debugservers where they don't shut down the process
2716 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
2717 // this can cause problems with restarting. So we check to see if any of our threads are stopped
2718 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
2719 // destroy it again.
2720 //
2721 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
2722 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
2723 // the debugservers with this bug are equal. There really should be a better way to test this!
2724 //
2725 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
2726 // get called here to destroy again and we're still at a breakpoint or exception, then we should
2727 // just do the straight-forward kill.
2728 //
2729 // And of course, if we weren't able to stop the process by the time we get here, it isn't
2730 // necessary (or helpful) to do any of this.
2731
2732 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
2733 {
2734 PlatformSP platform_sp = GetTarget().GetPlatform();
2735
2736 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2737 if (platform_sp
2738 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00002739 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00002740 {
2741 if (m_destroy_tried_resuming)
2742 {
2743 if (log)
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002744 log->PutCString ("ProcessGDBRemote::DoDestroy() - Tried resuming to destroy once already, not doing it again.");
Jim Ingham43c555d2012-07-04 00:35:43 +00002745 }
2746 else
2747 {
2748 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
2749 // but we really need it to happen here and it doesn't matter if we do it twice.
2750 m_thread_list.DiscardThreadPlans();
2751 DisableAllBreakpointSites();
2752
2753 bool stop_looks_like_crash = false;
2754 ThreadList &threads = GetThreadList();
2755
2756 {
Jim Ingham45350372012-09-11 00:08:52 +00002757 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002758
2759 size_t num_threads = threads.GetSize();
2760 for (size_t i = 0; i < num_threads; i++)
2761 {
2762 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002763 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002764 StopReason reason = eStopReasonInvalid;
2765 if (stop_info_sp)
2766 reason = stop_info_sp->GetStopReason();
2767 if (reason == eStopReasonBreakpoint
2768 || reason == eStopReasonException)
2769 {
2770 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002771 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
2772 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00002773 stop_info_sp->GetDescription());
2774 stop_looks_like_crash = true;
2775 break;
2776 }
2777 }
2778 }
2779
2780 if (stop_looks_like_crash)
2781 {
2782 if (log)
2783 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
2784 m_destroy_tried_resuming = true;
2785
2786 // If we are going to run again before killing, it would be good to suspend all the threads
2787 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
2788 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
2789 // have to run the risk of letting those threads proceed a bit.
2790
2791 {
Jim Ingham45350372012-09-11 00:08:52 +00002792 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002793
2794 size_t num_threads = threads.GetSize();
2795 for (size_t i = 0; i < num_threads; i++)
2796 {
2797 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002798 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002799 StopReason reason = eStopReasonInvalid;
2800 if (stop_info_sp)
2801 reason = stop_info_sp->GetStopReason();
2802 if (reason != eStopReasonBreakpoint
2803 && reason != eStopReasonException)
2804 {
2805 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002806 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
2807 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00002808 thread_sp->SetResumeState(eStateSuspended);
2809 }
2810 }
2811 }
2812 Resume ();
Jason Molendaede31932015-04-17 05:01:58 +00002813 return Destroy(false);
Jim Ingham43c555d2012-07-04 00:35:43 +00002814 }
2815 }
2816 }
2817 }
2818
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002819 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00002820 int exit_status = SIGABRT;
2821 std::string exit_string;
2822
Greg Clayton6ed95942011-01-22 07:12:45 +00002823 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002824 {
Jim Inghamaab78372011-10-28 01:11:35 +00002825 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00002826 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002827 StringExtractorGDBRemote response;
2828 bool send_async = true;
Tamas Berghammer912800c2015-02-24 10:23:39 +00002829 GDBRemoteCommunication::ScopedTimeout (m_gdb_comm, 3);
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002830
Greg Clayton3dedae12013-12-06 21:45:27 +00002831 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton513c26c2011-01-29 07:10:55 +00002832 {
2833 char packet_cmd = response.GetChar(0);
2834
2835 if (packet_cmd == 'W' || packet_cmd == 'X')
2836 {
Jim Inghameac0aa42014-02-21 22:36:11 +00002837#if defined(__APPLE__)
Jim Ingham9d67cc52014-02-21 22:35:29 +00002838 // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off
2839 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill
2840 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns
2841 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap
2842 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of
2843 // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2844 // Anyway, so call waitpid here to finally reap it.
2845 PlatformSP platform_sp(GetTarget().GetPlatform());
2846 if (platform_sp && platform_sp->IsHost())
2847 {
2848 int status;
2849 ::pid_t reap_pid;
2850 reap_pid = waitpid (GetID(), &status, WNOHANG);
2851 if (log)
2852 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2853 }
2854#endif
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002855 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002856 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00002857 exit_status = response.GetHexU8();
2858 }
2859 else
2860 {
2861 if (log)
2862 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2863 exit_string.assign("got unexpected response to k packet: ");
2864 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00002865 }
2866 }
2867 else
2868 {
Jim Inghambabfc382012-06-06 00:32:39 +00002869 if (log)
2870 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2871 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00002872 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002873 }
Jim Inghambabfc382012-06-06 00:32:39 +00002874 else
2875 {
2876 if (log)
Ed Masteb3a53332014-03-17 17:05:22 +00002877 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching");
Jim Inghamcfc09352012-07-27 23:57:19 +00002878 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00002879 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002880 }
Jim Inghambabfc382012-06-06 00:32:39 +00002881 else
2882 {
2883 // If we missed setting the exit status on the way out, do it here.
2884 // NB set exit status can be called multiple times, the first one sets the status.
2885 exit_string.assign("destroying when not connected to debugserver");
2886 }
2887
2888 SetExitStatus(exit_status, exit_string.c_str());
2889
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002890 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002891 KillDebugserverProcess ();
2892 return error;
2893}
2894
Greg Clayton8cda7f02013-05-21 21:55:59 +00002895void
2896ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2897{
Greg Clayton8cda7f02013-05-21 21:55:59 +00002898 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2899 if (did_exec)
2900 {
2901 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2902 if (log)
2903 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2904
2905 m_thread_list_real.Clear();
2906 m_thread_list.Clear();
2907 BuildDynamicRegisterInfo (true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002908 m_gdb_comm.ResetDiscoverableSettings (did_exec);
Greg Clayton8cda7f02013-05-21 21:55:59 +00002909 }
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002910
2911 // Scope the lock
2912 {
2913 // Lock the thread stack while we access it
2914 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
Greg Clayton2e309072015-07-17 23:42:28 +00002915
2916 // We are are not using non-stop mode, there can only be one last stop
2917 // reply packet, so clear the list.
2918 if (GetTarget().GetNonStopModeEnabled() == false)
2919 m_stop_packet_stack.clear();
2920
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002921 // Add this stop packet to the stop packet stack
2922 // This stack will get popped and examined when we switch to the
2923 // Stopped state
2924 m_stop_packet_stack.push_back(response);
2925 }
Greg Clayton8cda7f02013-05-21 21:55:59 +00002926}
2927
Chaoren Linc963a222015-09-01 16:58:45 +00002928void
2929ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp)
2930{
2931 Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
2932}
2933
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002934//------------------------------------------------------------------
2935// Process Queries
2936//------------------------------------------------------------------
2937
2938bool
2939ProcessGDBRemote::IsAlive ()
2940{
Greg Clayton10177aa2010-12-08 05:08:21 +00002941 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002942}
2943
2944addr_t
2945ProcessGDBRemote::GetImageInfoAddress()
2946{
Aidan Doddsc0c83852015-05-08 09:36:31 +00002947 // request the link map address via the $qShlibInfoAddr packet
2948 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2949
2950 // the loaded module list can also provides a link map address
2951 if (addr == LLDB_INVALID_ADDRESS)
2952 {
2953 GDBLoadedModuleInfoList list;
2954 if (GetLoadedModuleList (list).Success())
2955 addr = list.m_link_map;
2956 }
2957
2958 return addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002959}
2960
Greg Clayton2e309072015-07-17 23:42:28 +00002961void
2962ProcessGDBRemote::WillPublicStop ()
2963{
2964 // See if the GDB remote client supports the JSON threads info.
2965 // If so, we gather stop info for all threads, expedited registers,
2966 // expedited memory, runtime queue information (iOS and MacOSX only),
2967 // and more. Expediting memory will help stack backtracing be much
2968 // faster. Expediting registers will make sure we don't have to read
2969 // the thread registers for GPRs.
2970 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
2971
2972 if (m_jthreadsinfo_sp)
2973 {
2974 // Now set the stop info for each thread and also expedite any registers
2975 // and memory that was in the jThreadsInfo response.
2976 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
2977 if (thread_infos)
2978 {
2979 const size_t n = thread_infos->GetSize();
2980 for (size_t i=0; i<n; ++i)
2981 {
2982 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
2983 if (thread_dict)
2984 SetThreadStopInfo(thread_dict);
2985 }
2986 }
2987 }
2988}
2989
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002990//------------------------------------------------------------------
2991// Process Memory
2992//------------------------------------------------------------------
2993size_t
2994ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2995{
Jason Molenda6076bf42014-05-06 04:34:52 +00002996 GetMaxMemorySize ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002997 if (size > m_max_memory_size)
2998 {
2999 // Keep memory read sizes down to a sane limit. This function will be
3000 // called multiple times in order to complete the task by
3001 // lldb_private::Process so it is ok to do this.
3002 size = m_max_memory_size;
3003 }
3004
3005 char packet[64];
Jason Molenda6076bf42014-05-06 04:34:52 +00003006 int packet_len;
3007 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
3008 if (binary_memory_read)
3009 {
3010 packet_len = ::snprintf (packet, sizeof(packet), "x0x%" PRIx64 ",0x%" PRIx64, (uint64_t)addr, (uint64_t)size);
3011 }
3012 else
3013 {
3014 packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
3015 }
Andy Gibbsa297a972013-06-19 19:04:53 +00003016 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003017 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003018 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003019 {
Greg Clayton576d8832011-03-22 04:00:09 +00003020 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003021 {
3022 error.Clear();
Jason Molenda6076bf42014-05-06 04:34:52 +00003023 if (binary_memory_read)
3024 {
3025 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any
3026 // 0x7d character escaping that was present in the packet
3027
3028 size_t data_received_size = response.GetBytesLeft();
3029 if (data_received_size > size)
3030 {
3031 // Don't write past the end of BUF if the remote debug server gave us too
3032 // much data for some reason.
3033 data_received_size = size;
3034 }
3035 memcpy (buf, response.GetStringRef().data(), data_received_size);
3036 return data_received_size;
3037 }
3038 else
3039 {
3040 return response.GetHexBytes(buf, size, '\xdd');
3041 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003042 }
Greg Clayton576d8832011-03-22 04:00:09 +00003043 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00003044 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00003045 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00003046 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003047 else
Greg Clayton9944cd72012-09-19 01:46:31 +00003048 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003049 }
3050 else
3051 {
Jim Ingham35579dd2013-06-03 19:34:01 +00003052 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003053 }
3054 return 0;
3055}
3056
3057size_t
3058ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
3059{
Jason Molenda6076bf42014-05-06 04:34:52 +00003060 GetMaxMemorySize ();
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00003061 if (size > m_max_memory_size)
3062 {
3063 // Keep memory read sizes down to a sane limit. This function will be
3064 // called multiple times in order to complete the task by
3065 // lldb_private::Process so it is ok to do this.
3066 size = m_max_memory_size;
3067 }
3068
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003069 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00003070 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Clayton7fb56d02011-02-01 01:31:41 +00003071 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003072 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003073 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003074 {
Greg Clayton576d8832011-03-22 04:00:09 +00003075 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003076 {
3077 error.Clear();
3078 return size;
3079 }
Greg Clayton576d8832011-03-22 04:00:09 +00003080 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00003081 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00003082 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00003083 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003084 else
Greg Clayton9944cd72012-09-19 01:46:31 +00003085 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 +00003086 }
3087 else
3088 {
Jim Ingham35579dd2013-06-03 19:34:01 +00003089 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003090 }
3091 return 0;
3092}
3093
3094lldb::addr_t
3095ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
3096{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003097 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_EXPRESSIONS));
Greg Clayton2a48f522011-05-14 01:50:35 +00003098 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
3099
Greg Clayton70b57652011-05-15 01:25:55 +00003100 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton2a48f522011-05-14 01:50:35 +00003101 switch (supported)
3102 {
3103 case eLazyBoolCalculate:
3104 case eLazyBoolYes:
3105 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
3106 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
3107 return allocated_addr;
3108
3109 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003110 // Call mmap() to create memory in the inferior..
3111 unsigned prot = 0;
3112 if (permissions & lldb::ePermissionsReadable)
3113 prot |= eMmapProtRead;
3114 if (permissions & lldb::ePermissionsWritable)
3115 prot |= eMmapProtWrite;
3116 if (permissions & lldb::ePermissionsExecutable)
3117 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00003118
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003119 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
3120 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
3121 m_addr_to_mmap_size[allocated_addr] = size;
3122 else
Todd Fialaaf245d12014-06-30 21:05:18 +00003123 {
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003124 allocated_addr = LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00003125 if (log)
3126 log->Printf ("ProcessGDBRemote::%s no direct stub support for memory allocation, and InferiorCallMmap also failed - is stub missing register context save/restore capability?", __FUNCTION__);
3127 }
Greg Clayton2a48f522011-05-14 01:50:35 +00003128 break;
3129 }
3130
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003131 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00003132 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003133 else
3134 error.Clear();
3135 return allocated_addr;
3136}
3137
3138Error
Greg Clayton46fb5582011-11-18 07:03:08 +00003139ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
3140 MemoryRegionInfo &region_info)
3141{
3142
3143 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
3144 return error;
3145}
3146
3147Error
Johnny Chen64637202012-05-23 21:09:52 +00003148ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
3149{
3150
3151 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
3152 return error;
3153}
3154
3155Error
Enrico Granataf04a2192012-07-13 23:18:48 +00003156ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
3157{
Jaydeep Patil725666c2015-08-13 03:46:01 +00003158 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after, GetTarget().GetArchitecture()));
Enrico Granataf04a2192012-07-13 23:18:48 +00003159 return error;
3160}
3161
3162Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003163ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
3164{
3165 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00003166 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
3167
3168 switch (supported)
3169 {
3170 case eLazyBoolCalculate:
3171 // We should never be deallocating memory without allocating memory
3172 // first so we should never get eLazyBoolCalculate
3173 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
3174 break;
3175
3176 case eLazyBoolYes:
3177 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00003178 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003179 break;
3180
3181 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003182 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00003183 {
3184 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003185 if (pos != m_addr_to_mmap_size.end() &&
3186 InferiorCallMunmap(this, addr, pos->second))
3187 m_addr_to_mmap_size.erase (pos);
3188 else
Daniel Malead01b2952012-11-29 21:49:15 +00003189 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003190 }
3191 break;
3192 }
3193
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003194 return error;
3195}
3196
3197
3198//------------------------------------------------------------------
3199// Process STDIO
3200//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003201size_t
3202ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
3203{
3204 if (m_stdio_communication.IsConnected())
3205 {
3206 ConnectionStatus status;
3207 m_stdio_communication.Write(src, src_len, status, NULL);
3208 }
Vince Harrondf3f00f2015-02-10 21:09:04 +00003209 else if (m_stdin_forward)
Vince Harrone0be4252015-02-06 18:32:57 +00003210 {
3211 m_gdb_comm.SendStdinNotification(src, src_len);
3212 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003213 return 0;
3214}
3215
3216Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003217ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003218{
3219 Error error;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003220 assert(bp_site != NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003221
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003222 // Get logging info
3223 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003224 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003225
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003226 // Get the breakpoint address
3227 const addr_t addr = bp_site->GetLoadAddress();
3228
3229 // Log that a breakpoint was requested
3230 if (log)
3231 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
3232
3233 // Breakpoint already exists and is enabled
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003234 if (bp_site->IsEnabled())
3235 {
3236 if (log)
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003237 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 +00003238 return error;
3239 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003240
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003241 // Get the software breakpoint trap opcode size
3242 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3243
3244 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
3245 // is supported by the remote stub. These are set to true by default, and later set to false
3246 // only after we receive an unimplemented response when sending a breakpoint packet. This means
3247 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
3248 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
3249 // indicates if the user specifically asked for hardware breakpoints. If true then we will
3250 // skip over software breakpoints.
3251 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
3252 {
3253 // Try to send off a software breakpoint packet ($Z0)
3254 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003255 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003256 // The breakpoint was placed successfully
3257 bp_site->SetEnabled(true);
3258 bp_site->SetType(BreakpointSite::eExternal);
Greg Claytoneb023e72013-10-11 19:48:25 +00003259 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003260 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003261
3262 // SendGDBStoppointTypePacket() will return an error if it was unable to set this
3263 // breakpoint. We need to differentiate between a error specific to placing this breakpoint
3264 // or if we have learned that this breakpoint type is unsupported. To do this, we
3265 // must test the support boolean for this breakpoint type to see if it now indicates that
3266 // this breakpoint type is unsupported. If they are still supported then we should return
3267 // with the error code. If they are now unsupported, then we would like to fall through
3268 // and try another form of breakpoint.
3269 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
3270 return error;
3271
3272 // We reach here when software breakpoints have been found to be unsupported. For future
3273 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
3274 // known not to be supported.
3275 if (log)
3276 log->Printf("Software breakpoints are unsupported");
3277
3278 // So we will fall through and try a hardware breakpoint
3279 }
3280
3281 // The process of setting a hardware breakpoint is much the same as above. We check the
3282 // supported boolean for this breakpoint type, and if it is thought to be supported then we
3283 // will try to set this breakpoint with a hardware breakpoint.
3284 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3285 {
3286 // Try to send off a hardware breakpoint packet ($Z1)
3287 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003288 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003289 // The breakpoint was placed successfully
3290 bp_site->SetEnabled(true);
3291 bp_site->SetType(BreakpointSite::eHardware);
3292 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003293 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003294
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003295 // Check if the error was something other then an unsupported breakpoint type
3296 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3297 {
3298 // Unable to set this hardware breakpoint
3299 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
3300 return error;
3301 }
3302
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003303 // We will reach here when the stub gives an unsupported response to a hardware breakpoint
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003304 if (log)
3305 log->Printf("Hardware breakpoints are unsupported");
3306
3307 // Finally we will falling through to a #trap style breakpoint
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003308 }
3309
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003310 // Don't fall through when hardware breakpoints were specifically requested
3311 if (bp_site->HardwareRequired())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003312 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003313 error.SetErrorString("hardware breakpoints are not supported");
3314 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003315 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003316
3317 // As a last resort we want to place a manual breakpoint. An instruction
3318 // is placed into the process memory using memory write packets.
3319 return EnableSoftwareBreakpoint(bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003320}
3321
3322Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003323ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003324{
3325 Error error;
3326 assert (bp_site != NULL);
3327 addr_t addr = bp_site->GetLoadAddress();
3328 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00003329 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003330 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003331 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003332
3333 if (bp_site->IsEnabled())
3334 {
3335 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
3336
Greg Clayton8b82f082011-04-12 05:54:46 +00003337 BreakpointSite::Type bp_type = bp_site->GetType();
3338 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003339 {
Greg Clayton8b82f082011-04-12 05:54:46 +00003340 case BreakpointSite::eSoftware:
3341 error = DisableSoftwareBreakpoint (bp_site);
3342 break;
3343
3344 case BreakpointSite::eHardware:
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003345 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003346 error.SetErrorToGenericError();
3347 break;
3348
3349 case BreakpointSite::eExternal:
Jim Inghama04ef752014-03-07 11:18:02 +00003350 {
3351 GDBStoppointType stoppoint_type;
3352 if (bp_site->IsHardware())
3353 stoppoint_type = eBreakpointHardware;
3354 else
3355 stoppoint_type = eBreakpointSoftware;
3356
3357 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003358 error.SetErrorToGenericError();
Jim Inghama04ef752014-03-07 11:18:02 +00003359 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003360 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003361 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003362 if (error.Success())
3363 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003364 }
3365 else
3366 {
3367 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003368 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 +00003369 return error;
3370 }
3371
3372 if (error.Success())
3373 error.SetErrorToGenericError();
3374 return error;
3375}
3376
Johnny Chen11309a32011-09-06 22:38:36 +00003377// Pre-requisite: wp != NULL.
3378static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00003379GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00003380{
3381 assert(wp);
3382 bool watch_read = wp->WatchpointRead();
3383 bool watch_write = wp->WatchpointWrite();
3384
3385 // watch_read and watch_write cannot both be false.
3386 assert(watch_read || watch_write);
3387 if (watch_read && watch_write)
3388 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00003389 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00003390 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00003391 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00003392 return eWatchpointWrite;
3393}
3394
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003395Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003396ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003397{
3398 Error error;
3399 if (wp)
3400 {
3401 user_id_t watchID = wp->GetID();
3402 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00003403 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003404 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003405 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003406 if (wp->IsEnabled())
3407 {
3408 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003409 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 +00003410 return error;
3411 }
Johnny Chen11309a32011-09-06 22:38:36 +00003412
3413 GDBStoppointType type = GetGDBStoppointType(wp);
3414 // Pass down an appropriate z/Z packet...
3415 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003416 {
Johnny Chen11309a32011-09-06 22:38:36 +00003417 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
3418 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003419 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003420 return error;
3421 }
3422 else
3423 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003424 }
Johnny Chen11309a32011-09-06 22:38:36 +00003425 else
3426 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003427 }
3428 else
3429 {
Johnny Chen01a67862011-10-14 00:42:25 +00003430 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003431 }
3432 if (error.Success())
3433 error.SetErrorToGenericError();
3434 return error;
3435}
3436
3437Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003438ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003439{
3440 Error error;
3441 if (wp)
3442 {
3443 user_id_t watchID = wp->GetID();
3444
Greg Clayton5160ce52013-03-27 23:08:40 +00003445 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003446
3447 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00003448
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003449 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003450 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003451
Johnny Chen11309a32011-09-06 22:38:36 +00003452 if (!wp->IsEnabled())
3453 {
3454 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003455 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 +00003456 // See also 'class WatchpointSentry' within StopInfo.cpp.
3457 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
3458 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00003459 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003460 return error;
3461 }
3462
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003463 if (wp->IsHardware())
3464 {
Johnny Chen11309a32011-09-06 22:38:36 +00003465 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003466 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00003467 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
3468 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003469 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003470 return error;
3471 }
3472 else
3473 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003474 }
3475 // TODO: clear software watchpoints if we implement them
3476 }
3477 else
3478 {
Johnny Chen01a67862011-10-14 00:42:25 +00003479 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003480 }
3481 if (error.Success())
3482 error.SetErrorToGenericError();
3483 return error;
3484}
3485
3486void
3487ProcessGDBRemote::Clear()
3488{
3489 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00003490 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003491 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003492}
3493
3494Error
3495ProcessGDBRemote::DoSignal (int signo)
3496{
3497 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00003498 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003499 if (log)
3500 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
3501
3502 if (!m_gdb_comm.SendAsyncSignal (signo))
3503 error.SetErrorStringWithFormat("failed to send signal %i", signo);
3504 return error;
3505}
3506
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003507Error
Greg Clayton91a9b2472013-12-04 19:19:12 +00003508ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003509{
3510 Error error;
3511 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
3512 {
3513 // If we locate debugserver, keep that located version around
3514 static FileSpec g_debugserver_file_spec;
3515
Han Ming Ong84647042012-02-25 01:07:38 +00003516 ProcessLaunchInfo debugserver_launch_info;
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00003517 // Make debugserver run in its own session so signals generated by
3518 // special terminal key sequences (^C) don't affect debugserver.
3519 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3520
Greg Clayton91a9b2472013-12-04 19:19:12 +00003521 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
3522 debugserver_launch_info.SetUserID(process_info.GetUserID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003523
Todd Fiala013434e2014-07-09 01:29:05 +00003524#if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__) || defined (__aarch64__))
Greg Claytonfda4fab2014-01-10 22:24:11 +00003525 // On iOS, still do a local connection using a random port
Greg Clayton16810922014-02-27 19:38:18 +00003526 const char *hostname = "127.0.0.1";
Greg Claytonfda4fab2014-01-10 22:24:11 +00003527 uint16_t port = get_random_port ();
3528#else
3529 // Set hostname being NULL to do the reverse connect where debugserver
3530 // will bind to port zero and it will communicate back to us the port
3531 // that we will connect to
3532 const char *hostname = NULL;
3533 uint16_t port = 0;
3534#endif
3535
3536 error = m_gdb_comm.StartDebugserverProcess (hostname,
3537 port,
Greg Clayton00fe87b2013-12-05 22:58:22 +00003538 debugserver_launch_info,
3539 port);
Greg Clayton91a9b2472013-12-04 19:19:12 +00003540
3541 if (error.Success ())
3542 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003543 else
Greg Clayton91a9b2472013-12-04 19:19:12 +00003544 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003545
3546 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3547 StartAsyncThread ();
Greg Clayton91a9b2472013-12-04 19:19:12 +00003548
3549 if (error.Fail())
3550 {
3551 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
3552
3553 if (log)
3554 log->Printf("failed to start debugserver process: %s", error.AsCString());
3555 return error;
3556 }
3557
Greg Clayton00fe87b2013-12-05 22:58:22 +00003558 if (m_gdb_comm.IsConnected())
3559 {
3560 // Finish the connection process by doing the handshake without connecting (send NULL URL)
3561 ConnectToDebugserver (NULL);
3562 }
3563 else
3564 {
Greg Claytonfda4fab2014-01-10 22:24:11 +00003565 StreamString connect_url;
3566 connect_url.Printf("connect://%s:%u", hostname, port);
3567 error = ConnectToDebugserver (connect_url.GetString().c_str());
Greg Clayton00fe87b2013-12-05 22:58:22 +00003568 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00003569
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003570 }
3571 return error;
3572}
3573
3574bool
3575ProcessGDBRemote::MonitorDebugserverProcess
3576(
3577 void *callback_baton,
3578 lldb::pid_t debugserver_pid,
Greg Claytone4e45922011-11-16 05:37:56 +00003579 bool exited, // True if the process did exit
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003580 int signo, // Zero for no signal
3581 int exit_status // Exit value of process if signal is zero
3582)
3583{
Greg Claytone4e45922011-11-16 05:37:56 +00003584 // The baton is a "ProcessGDBRemote *". Now this class might be gone
3585 // and might not exist anymore, so we need to carefully try to get the
3586 // target for this process first since we have a race condition when
3587 // we are done running between getting the notice that the inferior
3588 // process has died and the debugserver that was debugging this process.
3589 // In our test suite, we are also continually running process after
3590 // process, so we must be very careful to make sure:
3591 // 1 - process object hasn't been deleted already
3592 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003593
3594 // "debugserver_pid" argument passed in is the process ID for
3595 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00003596 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003597
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003598 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton6779606a2011-01-22 23:43:18 +00003599
Greg Claytone4e45922011-11-16 05:37:56 +00003600 // Get a shared pointer to the target that has a matching process pointer.
3601 // This target could be gone, or the target could already have a new process
3602 // object inside of it
3603 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
3604
Greg Clayton6779606a2011-01-22 23:43:18 +00003605 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003606 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 +00003607
Greg Claytone4e45922011-11-16 05:37:56 +00003608 if (target_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003609 {
Greg Claytone4e45922011-11-16 05:37:56 +00003610 // We found a process in a target that matches, but another thread
3611 // might be in the process of launching a new process that will
3612 // soon replace it, so get a shared pointer to the process so we
3613 // can keep it alive.
3614 ProcessSP process_sp (target_sp->GetProcessSP());
3615 // Now we have a shared pointer to the process that can't go away on us
3616 // so we now make sure it was the same as the one passed in, and also make
3617 // sure that our previous "process *" didn't get deleted and have a new
3618 // "process *" created in its place with the same pointer. To verify this
3619 // we make sure the process has our debugserver process ID. If we pass all
3620 // of these tests, then we are sure that this process is the one we were
3621 // looking for.
3622 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003623 {
Greg Claytone4e45922011-11-16 05:37:56 +00003624 // Sleep for a half a second to make sure our inferior process has
3625 // time to set its exit status before we set it incorrectly when
3626 // both the debugserver and the inferior process shut down.
3627 usleep (500000);
3628 // If our process hasn't yet exited, debugserver might have died.
3629 // If the process did exit, the we are reaping it.
3630 const StateType state = process->GetState();
3631
3632 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
3633 state != eStateInvalid &&
3634 state != eStateUnloaded &&
3635 state != eStateExited &&
3636 state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003637 {
Greg Claytone4e45922011-11-16 05:37:56 +00003638 char error_str[1024];
3639 if (signo)
3640 {
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00003641 const char *signal_cstr = process->GetUnixSignals()->GetSignalAsCString(signo);
Greg Claytone4e45922011-11-16 05:37:56 +00003642 if (signal_cstr)
3643 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3644 else
3645 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
3646 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003647 else
Greg Claytone4e45922011-11-16 05:37:56 +00003648 {
3649 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
3650 }
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003651
Greg Claytone4e45922011-11-16 05:37:56 +00003652 process->SetExitStatus (-1, error_str);
3653 }
3654 // Debugserver has exited we need to let our ProcessGDBRemote
3655 // know that it no longer has a debugserver instance
3656 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003657 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003658 }
3659 return true;
3660}
3661
3662void
3663ProcessGDBRemote::KillDebugserverProcess ()
3664{
Greg Claytonfbb76342013-11-20 21:07:01 +00003665 m_gdb_comm.Disconnect();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003666 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3667 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003668 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003669 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3670 }
3671}
3672
3673void
3674ProcessGDBRemote::Initialize()
3675{
Davide Italianoc8d69822015-04-03 04:24:32 +00003676 static std::once_flag g_once_flag;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003677
Davide Italianoc8d69822015-04-03 04:24:32 +00003678 std::call_once(g_once_flag, []()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003679 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003680 PluginManager::RegisterPlugin (GetPluginNameStatic(),
3681 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00003682 CreateInstance,
3683 DebuggerInitialize);
Davide Italianoc8d69822015-04-03 04:24:32 +00003684 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003685}
3686
Greg Clayton7f982402013-07-15 22:54:20 +00003687void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003688ProcessGDBRemote::DebuggerInitialize (Debugger &debugger)
Greg Clayton7f982402013-07-15 22:54:20 +00003689{
3690 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
3691 {
3692 const bool is_global_setting = true;
3693 PluginManager::CreateSettingForProcessPlugin (debugger,
3694 GetGlobalPluginProperties()->GetValueProperties(),
3695 ConstString ("Properties for the gdb-remote process plug-in."),
3696 is_global_setting);
3697 }
3698}
3699
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003700bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003701ProcessGDBRemote::StartAsyncThread ()
3702{
Greg Clayton5160ce52013-03-27 23:08:40 +00003703 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003704
3705 if (log)
3706 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003707
3708 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003709 if (!m_async_thread.IsJoinable())
Jim Ingham455fa5c2012-11-01 01:15:33 +00003710 {
3711 // Create a thread that watches our internal state and controls which
3712 // events make it to clients (into the DCProcess event queue).
Zachary Turner39de3112014-09-09 20:54:56 +00003713
3714 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003715 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003716 else if (log)
3717 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was already running.", __FUNCTION__);
Zachary Turner39de3112014-09-09 20:54:56 +00003718
Zachary Turneracee96a2014-09-23 18:32:09 +00003719 return m_async_thread.IsJoinable();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003720}
3721
3722void
3723ProcessGDBRemote::StopAsyncThread ()
3724{
Greg Clayton5160ce52013-03-27 23:08:40 +00003725 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003726
3727 if (log)
3728 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
3729
Jim Ingham455fa5c2012-11-01 01:15:33 +00003730 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003731 if (m_async_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003732 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00003733 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
3734
3735 // This will shut down the async thread.
3736 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3737
3738 // Stop the stdio thread
Zachary Turner39de3112014-09-09 20:54:56 +00003739 m_async_thread.Join(nullptr);
Pavel Labatha55a9532015-03-11 09:53:42 +00003740 m_async_thread.Reset();
Jim Ingham455fa5c2012-11-01 01:15:33 +00003741 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003742 else if (log)
3743 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003744}
3745
Ewan Crawford76df2882015-06-23 12:32:06 +00003746bool
3747ProcessGDBRemote::HandleNotifyPacket (StringExtractorGDBRemote &packet)
3748{
3749 // get the packet at a string
3750 const std::string &pkt = packet.GetStringRef();
3751 // skip %stop:
3752 StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
3753
3754 // pass as a thread stop info packet
3755 SetLastStopPacket(stop_info);
3756
3757 // check for more stop reasons
3758 HandleStopReplySequence();
3759
3760 // if the process is stopped then we need to fake a resume
3761 // so that we can stop properly with the new break. This
3762 // is possible due to SetPrivateState() broadcasting the
3763 // state change as a side effect.
3764 if (GetPrivateState() == lldb::StateType::eStateStopped)
3765 {
3766 SetPrivateState(lldb::StateType::eStateRunning);
3767 }
3768
3769 // since we have some stopped packets we can halt the process
3770 SetPrivateState(lldb::StateType::eStateStopped);
3771
3772 return true;
3773}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003774
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003775thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003776ProcessGDBRemote::AsyncThread (void *arg)
3777{
3778 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
3779
Greg Clayton5160ce52013-03-27 23:08:40 +00003780 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003781 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003782 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003783
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003784 EventSP event_sp;
Pavel Labath50556852015-09-03 09:36:22 +00003785 bool done = false;
3786 while (!done)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003787 {
Pavel Labath50556852015-09-03 09:36:22 +00003788 if (log)
3789 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
3790 if (process->m_async_listener.WaitForEvent (NULL, event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003791 {
Pavel Labath50556852015-09-03 09:36:22 +00003792 const uint32_t event_type = event_sp->GetType();
3793 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003794 {
3795 if (log)
Pavel Labath50556852015-09-03 09:36:22 +00003796 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
3797
3798 switch (event_type)
3799 {
3800 case eBroadcastBitAsyncContinue:
3801 {
3802 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
3803
3804 if (continue_packet)
3805 {
3806 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
3807 const size_t continue_cstr_len = continue_packet->GetByteSize ();
3808 if (log)
3809 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
3810
3811 if (::strstr (continue_cstr, "vAttach") == NULL)
3812 process->SetPrivateState(eStateRunning);
3813 StringExtractorGDBRemote response;
3814
3815 // If in Non-Stop-Mode
3816 if (process->GetTarget().GetNonStopModeEnabled())
3817 {
3818 // send the vCont packet
3819 if (!process->GetGDBRemote().SendvContPacket(process, continue_cstr, continue_cstr_len, response))
3820 {
3821 // Something went wrong
3822 done = true;
3823 break;
3824 }
3825 }
3826 // If in All-Stop-Mode
3827 else
3828 {
3829 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
3830
3831 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
3832 // The thread ID list might be contained within the "response", or the stop reply packet that
3833 // caused the stop. So clear it now before we give the stop reply packet to the process
3834 // using the process->SetLastStopPacket()...
3835 process->ClearThreadIDList ();
3836
3837 switch (stop_state)
3838 {
3839 case eStateStopped:
3840 case eStateCrashed:
3841 case eStateSuspended:
3842 process->SetLastStopPacket (response);
3843 process->SetPrivateState (stop_state);
3844 break;
3845
3846 case eStateExited:
3847 {
3848 process->SetLastStopPacket (response);
3849 process->ClearThreadIDList();
3850 response.SetFilePos(1);
3851
3852 int exit_status = response.GetHexU8();
3853 const char *desc_cstr = NULL;
3854 StringExtractor extractor;
3855 std::string desc_string;
3856 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';')
3857 {
3858 std::string desc_token;
3859 while (response.GetNameColonValue (desc_token, desc_string))
3860 {
3861 if (desc_token == "description")
3862 {
3863 extractor.GetStringRef().swap(desc_string);
3864 extractor.SetFilePos(0);
3865 extractor.GetHexByteString (desc_string);
3866 desc_cstr = desc_string.c_str();
3867 }
3868 }
3869 }
3870 process->SetExitStatus(exit_status, desc_cstr);
3871 done = true;
3872 break;
3873 }
3874 case eStateInvalid:
3875 {
3876 // Check to see if we were trying to attach and if we got back
3877 // the "E87" error code from debugserver -- this indicates that
3878 // the process is not debuggable. Return a slightly more helpful
3879 // error message about why the attach failed.
3880 if (::strstr (continue_cstr, "vAttach") != NULL
3881 && response.GetError() == 0x87)
3882 {
3883 process->SetExitStatus(-1, "cannot attach to process due to System Integrity Protection");
3884 }
3885 // E01 code from vAttach means that the attach failed
3886 if (::strstr (continue_cstr, "vAttach") != NULL
3887 && response.GetError() == 0x1)
3888 {
3889 process->SetExitStatus(-1, "unable to attach");
3890 }
3891 else
3892 {
3893 process->SetExitStatus(-1, "lost connection");
3894 }
3895 break;
3896 }
3897
3898 default:
3899 process->SetPrivateState (stop_state);
3900 break;
3901 } // switch(stop_state)
3902 } // else // if in All-stop-mode
3903 } // if (continue_packet)
3904 } // case eBroadcastBitAysncContinue
3905 break;
3906
3907 case eBroadcastBitAsyncThreadShouldExit:
3908 if (log)
3909 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
3910 done = true;
3911 break;
3912
3913 default:
3914 if (log)
3915 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
3916 done = true;
3917 break;
3918 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003919 }
Pavel Labath50556852015-09-03 09:36:22 +00003920 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
3921 {
3922 switch (event_type)
3923 {
3924 case Communication::eBroadcastBitReadThreadDidExit:
3925 process->SetExitStatus (-1, "lost connection");
3926 done = true;
3927 break;
3928
3929 case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify:
3930 {
3931 lldb_private::Event *event = event_sp.get();
3932 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event);
3933 StringExtractorGDBRemote notify((const char*)continue_packet->GetBytes());
3934 // Hand this over to the process to handle
3935 process->HandleNotifyPacket(notify);
3936 break;
3937 }
3938
3939 default:
3940 if (log)
3941 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
3942 done = true;
3943 break;
3944 }
3945 }
3946 }
3947 else
3948 {
3949 if (log)
3950 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
3951 done = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003952 }
3953 }
3954
3955 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003956 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003957
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003958 return NULL;
3959}
3960
Greg Claytone996fd32011-03-08 22:40:15 +00003961//uint32_t
3962//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3963//{
3964// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
3965// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
3966// if (m_local_debugserver)
3967// {
3968// return Host::ListProcessesMatchingName (name, matches, pids);
3969// }
3970// else
3971// {
3972// // FIXME: Implement talking to the remote debugserver.
3973// return 0;
3974// }
3975//
3976//}
3977//
Jim Ingham1c823b42011-01-22 01:33:44 +00003978bool
3979ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003980 StoppointCallbackContext *context,
Jim Ingham1c823b42011-01-22 01:33:44 +00003981 lldb::user_id_t break_id,
3982 lldb::user_id_t break_loc_id)
3983{
3984 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3985 // run so I can stop it if that's what I want to do.
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003986 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00003987 if (log)
3988 log->Printf("Hit New Thread Notification breakpoint.");
3989 return false;
3990}
3991
3992
3993bool
3994ProcessGDBRemote::StartNoticingNewThreads()
3995{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003996 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00003997 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003998 {
Greg Clayton4116e932012-05-15 02:33:01 +00003999 if (log && log->GetVerbose())
4000 log->Printf("Enabled noticing new thread breakpoint.");
4001 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00004002 }
Greg Clayton4116e932012-05-15 02:33:01 +00004003 else
Jim Ingham1c823b42011-01-22 01:33:44 +00004004 {
Zachary Turner7529df92015-09-01 20:02:29 +00004005 PlatformSP platform_sp (GetTarget().GetPlatform());
Greg Clayton4116e932012-05-15 02:33:01 +00004006 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00004007 {
Zachary Turner7529df92015-09-01 20:02:29 +00004008 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(GetTarget());
Greg Clayton4116e932012-05-15 02:33:01 +00004009 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00004010 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00004011 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00004012 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
4013 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00004014 }
4015 else
4016 {
4017 if (log)
4018 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00004019 }
4020 }
4021 }
Greg Clayton4116e932012-05-15 02:33:01 +00004022 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00004023}
4024
4025bool
4026ProcessGDBRemote::StopNoticingNewThreads()
4027{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004028 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00004029 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00004030 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00004031
4032 if (m_thread_create_bp_sp)
4033 m_thread_create_bp_sp->SetEnabled(false);
4034
Jim Ingham1c823b42011-01-22 01:33:44 +00004035 return true;
4036}
4037
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004038DynamicLoader *
Jason Molenda5e8534e2012-10-03 01:29:34 +00004039ProcessGDBRemote::GetDynamicLoader ()
4040{
4041 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00004042 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00004043 return m_dyld_ap.get();
4044}
Jim Ingham1c823b42011-01-22 01:33:44 +00004045
Jason Molendaa3329782014-03-29 18:54:20 +00004046Error
4047ProcessGDBRemote::SendEventData(const char *data)
4048{
4049 int return_value;
4050 bool was_supported;
4051
4052 Error error;
4053
4054 return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported);
4055 if (return_value != 0)
4056 {
4057 if (!was_supported)
4058 error.SetErrorString("Sending events is not supported for this process.");
4059 else
4060 error.SetErrorStringWithFormat("Error sending event data: %d.", return_value);
4061 }
4062 return error;
4063}
4064
Steve Pucci03904ac2014-03-04 23:18:46 +00004065const DataBufferSP
4066ProcessGDBRemote::GetAuxvData()
4067{
4068 DataBufferSP buf;
4069 if (m_gdb_comm.GetQXferAuxvReadSupported())
4070 {
4071 std::string response_string;
4072 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success)
4073 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length()));
4074 }
4075 return buf;
4076}
4077
Jason Molenda705b1802014-06-13 02:37:02 +00004078StructuredData::ObjectSP
4079ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid)
4080{
4081 StructuredData::ObjectSP object_sp;
4082
4083 if (m_gdb_comm.GetThreadExtendedInfoSupported())
4084 {
4085 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4086 SystemRuntime *runtime = GetSystemRuntime();
4087 if (runtime)
4088 {
4089 runtime->AddThreadExtendedInfoPacketHints (args_dict);
4090 }
4091 args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid);
4092
4093 StreamString packet;
4094 packet << "jThreadExtendedInfo:";
4095 args_dict->Dump (packet);
4096
4097 // FIXME the final character of a JSON dictionary, '}', is the escape
4098 // character in gdb-remote binary mode. lldb currently doesn't escape
4099 // these characters in its packet output -- so we add the quoted version
4100 // of the } character here manually in case we talk to a debugserver which
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004101 // un-escapes the characters at packet read time.
Jason Molenda705b1802014-06-13 02:37:02 +00004102 packet << (char) (0x7d ^ 0x20);
4103
4104 StringExtractorGDBRemote response;
4105 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4106 {
4107 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4108 if (response_type == StringExtractorGDBRemote::eResponse)
4109 {
4110 if (!response.Empty())
4111 {
Jason Molenda20ee21b2015-07-10 23:15:22 +00004112 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4113 }
4114 }
4115 }
4116 }
4117 return object_sp;
4118}
4119
4120StructuredData::ObjectSP
4121ProcessGDBRemote::GetLoadedDynamicLibrariesInfos (lldb::addr_t image_list_address, lldb::addr_t image_count)
4122{
4123 StructuredData::ObjectSP object_sp;
4124
4125 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported())
4126 {
4127 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4128 args_dict->GetAsDictionary()->AddIntegerItem ("image_list_address", image_list_address);
4129 args_dict->GetAsDictionary()->AddIntegerItem ("image_count", image_count);
4130
4131 StreamString packet;
4132 packet << "jGetLoadedDynamicLibrariesInfos:";
4133 args_dict->Dump (packet);
4134
4135 // FIXME the final character of a JSON dictionary, '}', is the escape
4136 // character in gdb-remote binary mode. lldb currently doesn't escape
4137 // these characters in its packet output -- so we add the quoted version
4138 // of the } character here manually in case we talk to a debugserver which
4139 // un-escapes the characters at packet read time.
4140 packet << (char) (0x7d ^ 0x20);
4141
4142 StringExtractorGDBRemote response;
4143 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4144 {
4145 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4146 if (response_type == StringExtractorGDBRemote::eResponse)
4147 {
4148 if (!response.Empty())
4149 {
Jason Molenda705b1802014-06-13 02:37:02 +00004150 // The packet has already had the 0x7d xor quoting stripped out at the
4151 // GDBRemoteCommunication packet receive level.
4152 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4153 }
4154 }
4155 }
4156 }
4157 return object_sp;
4158}
4159
Jason Molenda20ee21b2015-07-10 23:15:22 +00004160
Jason Molenda6076bf42014-05-06 04:34:52 +00004161// Establish the largest memory read/write payloads we should use.
4162// If the remote stub has a max packet size, stay under that size.
4163//
4164// If the remote stub's max packet size is crazy large, use a
4165// reasonable largeish default.
4166//
4167// If the remote stub doesn't advertise a max packet size, use a
4168// conservative default.
4169
4170void
4171ProcessGDBRemote::GetMaxMemorySize()
4172{
4173 const uint64_t reasonable_largeish_default = 128 * 1024;
4174 const uint64_t conservative_default = 512;
4175
4176 if (m_max_memory_size == 0)
4177 {
4178 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4179 if (stub_max_size != UINT64_MAX && stub_max_size != 0)
4180 {
4181 // Save the stub's claimed maximum packet size
4182 m_remote_stub_max_memory_size = stub_max_size;
4183
4184 // Even if the stub says it can support ginormous packets,
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004185 // don't exceed our reasonable largeish default packet size.
Jason Molenda6076bf42014-05-06 04:34:52 +00004186 if (stub_max_size > reasonable_largeish_default)
4187 {
4188 stub_max_size = reasonable_largeish_default;
4189 }
4190
4191 m_max_memory_size = stub_max_size;
4192 }
4193 else
4194 {
4195 m_max_memory_size = conservative_default;
4196 }
4197 }
4198}
4199
4200void
4201ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max)
4202{
4203 if (user_specified_max != 0)
4204 {
4205 GetMaxMemorySize ();
4206
4207 if (m_remote_stub_max_memory_size != 0)
4208 {
4209 if (m_remote_stub_max_memory_size < user_specified_max)
4210 {
4211 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a packet size too big, go as big
4212 // as the remote stub says we can go.
4213 }
4214 else
4215 {
4216 m_max_memory_size = user_specified_max; // user's packet size is good
4217 }
4218 }
4219 else
4220 {
4221 m_max_memory_size = user_specified_max; // user's packet size is probably fine
4222 }
4223 }
4224}
4225
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004226bool
4227ProcessGDBRemote::GetModuleSpec(const FileSpec& module_file_spec,
4228 const ArchSpec& arch,
4229 ModuleSpec &module_spec)
4230{
4231 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PLATFORM);
4232
4233 if (!m_gdb_comm.GetModuleInfo (module_file_spec, arch, module_spec))
4234 {
4235 if (log)
4236 log->Printf ("ProcessGDBRemote::%s - failed to get module info for %s:%s",
4237 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4238 arch.GetTriple ().getTriple ().c_str ());
4239 return false;
4240 }
4241
4242 if (log)
4243 {
4244 StreamString stream;
4245 module_spec.Dump (stream);
4246 log->Printf ("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4247 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4248 arch.GetTriple ().getTriple ().c_str (), stream.GetString ().c_str ());
4249 }
4250
4251 return true;
4252}
4253
Colin Rileyc3c95b22015-04-16 15:51:33 +00004254namespace {
4255
4256typedef std::vector<std::string> stringVec;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004257
4258typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004259struct RegisterSetInfo
4260{
4261 ConstString name;
4262};
Colin Rileyc3c95b22015-04-16 15:51:33 +00004263
Greg Claytond04f0ed2015-05-26 18:00:51 +00004264typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4265
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004266struct GdbServerTargetInfo
4267{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004268 std::string arch;
4269 std::string osabi;
4270 stringVec includes;
4271 RegisterSetMap reg_set_map;
4272 XMLNode feature_node;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004273};
Greg Claytond04f0ed2015-05-26 18:00:51 +00004274
Colin Rileyc3c95b22015-04-16 15:51:33 +00004275bool
Greg Claytond04f0ed2015-05-26 18:00:51 +00004276ParseRegisters (XMLNode feature_node, GdbServerTargetInfo &target_info, GDBRemoteDynamicRegisterInfo &dyn_reg_info)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004277{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004278 if (!feature_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004279 return false;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004280
4281 uint32_t prev_reg_num = 0;
4282 uint32_t reg_offset = 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004283
Greg Claytond04f0ed2015-05-26 18:00:51 +00004284 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 +00004285 std::string gdb_group;
4286 std::string gdb_type;
4287 ConstString reg_name;
4288 ConstString alt_name;
4289 ConstString set_name;
4290 std::vector<uint32_t> value_regs;
4291 std::vector<uint32_t> invalidate_regs;
4292 bool encoding_set = false;
4293 bool format_set = false;
4294 RegisterInfo reg_info = { NULL, // Name
4295 NULL, // Alt name
4296 0, // byte size
4297 reg_offset, // offset
4298 eEncodingUint, // encoding
Jason Molendabf67a302015-09-01 05:17:01 +00004299 eFormatHex, // format
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004300 {
Jason Molendabf67a302015-09-01 05:17:01 +00004301 LLDB_INVALID_REGNUM, // eh_frame reg num
Greg Claytond04f0ed2015-05-26 18:00:51 +00004302 LLDB_INVALID_REGNUM, // DWARF reg num
4303 LLDB_INVALID_REGNUM, // generic reg num
Jason Molendabf67a302015-09-01 05:17:01 +00004304 prev_reg_num, // stabs reg num
Greg Claytond04f0ed2015-05-26 18:00:51 +00004305 prev_reg_num // native register number
4306 },
4307 NULL,
4308 NULL
4309 };
4310
Ewan Crawford682e8422015-06-26 09:38:27 +00004311 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 +00004312 if (name == "name")
4313 {
4314 reg_name.SetString(value);
4315 }
4316 else if (name == "bitsize")
4317 {
4318 reg_info.byte_size = StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
4319 }
4320 else if (name == "type")
4321 {
4322 gdb_type = value.str();
4323 }
4324 else if (name == "group")
4325 {
4326 gdb_group = value.str();
4327 }
4328 else if (name == "regnum")
4329 {
4330 const uint32_t regnum = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4331 if (regnum != LLDB_INVALID_REGNUM)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004332 {
Jason Molendaa18f7072015-08-15 01:21:01 +00004333 reg_info.kinds[eRegisterKindStabs] = regnum;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004334 reg_info.kinds[eRegisterKindLLDB] = regnum;
4335 prev_reg_num = regnum;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004336 }
4337 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004338 else if (name == "offset")
4339 {
4340 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4341 }
4342 else if (name == "altname")
4343 {
4344 alt_name.SetString(value);
4345 }
4346 else if (name == "encoding")
4347 {
4348 encoding_set = true;
4349 reg_info.encoding = Args::StringToEncoding (value.data(), eEncodingUint);
4350 }
4351 else if (name == "format")
4352 {
4353 format_set = true;
4354 Format format = eFormatInvalid;
4355 if (Args::StringToFormat (value.data(), format, NULL).Success())
4356 reg_info.format = format;
4357 else if (value == "vector-sint8")
4358 reg_info.format = eFormatVectorOfSInt8;
4359 else if (value == "vector-uint8")
4360 reg_info.format = eFormatVectorOfUInt8;
4361 else if (value == "vector-sint16")
4362 reg_info.format = eFormatVectorOfSInt16;
4363 else if (value == "vector-uint16")
4364 reg_info.format = eFormatVectorOfUInt16;
4365 else if (value == "vector-sint32")
4366 reg_info.format = eFormatVectorOfSInt32;
4367 else if (value == "vector-uint32")
4368 reg_info.format = eFormatVectorOfUInt32;
4369 else if (value == "vector-float32")
4370 reg_info.format = eFormatVectorOfFloat32;
4371 else if (value == "vector-uint128")
4372 reg_info.format = eFormatVectorOfUInt128;
4373 }
4374 else if (name == "group_id")
4375 {
4376 const uint32_t set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4377 RegisterSetMap::const_iterator pos = target_info.reg_set_map.find(set_id);
4378 if (pos != target_info.reg_set_map.end())
4379 set_name = pos->second.name;
4380 }
Jason Molendaa18f7072015-08-15 01:21:01 +00004381 else if (name == "gcc_regnum" || name == "ehframe_regnum")
Greg Claytond04f0ed2015-05-26 18:00:51 +00004382 {
Jason Molendaa18f7072015-08-15 01:21:01 +00004383 reg_info.kinds[eRegisterKindEHFrame] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004384 }
4385 else if (name == "dwarf_regnum")
4386 {
4387 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4388 }
4389 else if (name == "generic")
4390 {
4391 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister(value.data());
4392 }
4393 else if (name == "value_regnums")
4394 {
4395 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
4396 }
4397 else if (name == "invalidate_regnums")
4398 {
4399 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
4400 }
4401 else
4402 {
4403 printf("unhandled attribute %s = %s\n", name.data(), value.data());
4404 }
4405 return true; // Keep iterating through all attributes
4406 });
4407
4408 if (!gdb_type.empty() && !(encoding_set || format_set))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004409 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004410 if (gdb_type.find("int") == 0)
4411 {
4412 reg_info.format = eFormatHex;
4413 reg_info.encoding = eEncodingUint;
4414 }
4415 else if (gdb_type == "data_ptr" || gdb_type == "code_ptr")
4416 {
4417 reg_info.format = eFormatAddressInfo;
4418 reg_info.encoding = eEncodingUint;
4419 }
4420 else if (gdb_type == "i387_ext" || gdb_type == "float")
4421 {
4422 reg_info.format = eFormatFloat;
4423 reg_info.encoding = eEncodingIEEE754;
4424 }
Colin Rileyc3c95b22015-04-16 15:51:33 +00004425 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004426
4427 // Only update the register set name if we didn't get a "reg_set" attribute.
4428 // "set_name" will be empty if we didn't have a "reg_set" attribute.
4429 if (!set_name && !gdb_group.empty())
4430 set_name.SetCString(gdb_group.c_str());
4431
4432 reg_info.byte_offset = reg_offset;
4433 assert (reg_info.byte_size != 0);
4434 reg_offset += reg_info.byte_size;
4435 if (!value_regs.empty())
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004436 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004437 value_regs.push_back(LLDB_INVALID_REGNUM);
4438 reg_info.value_regs = value_regs.data();
Colin Rileyc3c95b22015-04-16 15:51:33 +00004439 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004440 if (!invalidate_regs.empty())
4441 {
4442 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
4443 reg_info.invalidate_regs = invalidate_regs.data();
4444 }
4445
Ewan Crawford682e8422015-06-26 09:38:27 +00004446 ++prev_reg_num;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004447 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
4448
4449 return true; // Keep iterating through all "reg" elements
4450 });
Colin Rileyc3c95b22015-04-16 15:51:33 +00004451 return true;
4452}
Greg Claytond04f0ed2015-05-26 18:00:51 +00004453
Colin Rileyc3c95b22015-04-16 15:51:33 +00004454} // namespace {}
4455
Colin Rileyc3c95b22015-04-16 15:51:33 +00004456
4457// query the target of gdb-remote for extended target information
4458// return: 'true' on success
4459// 'false' on failure
4460bool
Aidan Doddsc0c83852015-05-08 09:36:31 +00004461ProcessGDBRemote::GetGDBServerRegisterInfo ()
Colin Rileyc3c95b22015-04-16 15:51:33 +00004462{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004463 // Make sure LLDB has an XML parser it can use first
4464 if (!XMLDocument::XMLEnabled())
4465 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004466
4467 // redirect libxml2's error handler since the default prints to stdout
Colin Rileyc3c95b22015-04-16 15:51:33 +00004468
4469 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004470
4471 // check that we have extended feature read support
4472 if ( !comm.GetQXferFeaturesReadSupported( ) )
4473 return false;
4474
4475 // request the target xml file
4476 std::string raw;
4477 lldb_private::Error lldberr;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004478 if (!comm.ReadExtFeature(ConstString("features"),
4479 ConstString("target.xml"),
4480 raw,
4481 lldberr))
4482 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00004483 return false;
4484 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004485
Colin Rileyc3c95b22015-04-16 15:51:33 +00004486
Greg Claytond04f0ed2015-05-26 18:00:51 +00004487 XMLDocument xml_document;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004488
Greg Claytond04f0ed2015-05-26 18:00:51 +00004489 if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml"))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004490 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004491 GdbServerTargetInfo target_info;
4492
4493 XMLNode target_node = xml_document.GetRootElement("target");
4494 if (target_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004495 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004496 XMLNode feature_node;
4497 target_node.ForEachChildElement([&target_info, this, &feature_node](const XMLNode &node) -> bool
4498 {
4499 llvm::StringRef name = node.GetName();
4500 if (name == "architecture")
4501 {
4502 node.GetElementText(target_info.arch);
4503 }
4504 else if (name == "osabi")
4505 {
4506 node.GetElementText(target_info.osabi);
4507 }
Ewan Crawford682e8422015-06-26 09:38:27 +00004508 else if (name == "xi:include" || name == "include")
Greg Claytond04f0ed2015-05-26 18:00:51 +00004509 {
4510 llvm::StringRef href = node.GetAttributeValue("href");
4511 if (!href.empty())
4512 target_info.includes.push_back(href.str());
4513 }
4514 else if (name == "feature")
4515 {
4516 feature_node = node;
4517 }
4518 else if (name == "groups")
4519 {
4520 node.ForEachChildElementWithName("group", [&target_info](const XMLNode &node) -> bool {
4521 uint32_t set_id = UINT32_MAX;
4522 RegisterSetInfo set_info;
4523
4524 node.ForEachAttribute([&set_id, &set_info](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
4525 if (name == "id")
4526 set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4527 if (name == "name")
4528 set_info.name = ConstString(value);
4529 return true; // Keep iterating through all attributes
4530 });
4531
4532 if (set_id != UINT32_MAX)
4533 target_info.reg_set_map[set_id] = set_info;
4534 return true; // Keep iterating through all "group" elements
4535 });
4536 }
4537 return true; // Keep iterating through all children of the target_node
4538 });
4539
4540 if (feature_node)
4541 {
4542 ParseRegisters(feature_node, target_info, this->m_register_info);
4543 }
4544
4545 for (const auto &include : target_info.includes)
4546 {
4547 // request register file
4548 std::string xml_data;
4549 if (!comm.ReadExtFeature(ConstString("features"),
4550 ConstString(include),
4551 xml_data,
4552 lldberr))
4553 continue;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004554
Greg Claytond04f0ed2015-05-26 18:00:51 +00004555 XMLDocument include_xml_document;
4556 include_xml_document.ParseMemory(xml_data.data(), xml_data.size(), include.c_str());
4557 XMLNode include_feature_node = include_xml_document.GetRootElement("feature");
4558 if (include_feature_node)
4559 {
4560 ParseRegisters(include_feature_node, target_info, this->m_register_info);
4561 }
4562 }
4563 this->m_register_info.Finalize(GetTarget().GetArchitecture());
Colin Rileyc3c95b22015-04-16 15:51:33 +00004564 }
4565 }
4566
Greg Claytond04f0ed2015-05-26 18:00:51 +00004567 return m_register_info.GetNumRegisters() > 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004568}
4569
Aidan Doddsc0c83852015-05-08 09:36:31 +00004570Error
4571ProcessGDBRemote::GetLoadedModuleList (GDBLoadedModuleInfoList & list)
4572{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004573 // Make sure LLDB has an XML parser it can use first
4574 if (!XMLDocument::XMLEnabled())
4575 return Error (0, ErrorType::eErrorTypeGeneric);
4576
Aidan Doddsc0c83852015-05-08 09:36:31 +00004577 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS);
4578 if (log)
4579 log->Printf ("ProcessGDBRemote::%s", __FUNCTION__);
4580
Aidan Doddsc0c83852015-05-08 09:36:31 +00004581 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004582
4583 // check that we have extended feature read support
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004584 if (comm.GetQXferLibrariesSVR4ReadSupported ()) {
4585 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004586
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004587 // request the loaded library list
4588 std::string raw;
4589 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004590
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004591 if (!comm.ReadExtFeature (ConstString ("libraries-svr4"), ConstString (""), raw, lldberr))
4592 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004593
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004594 // parse the xml file in memory
4595 if (log)
4596 log->Printf ("parsing: %s", raw.c_str());
4597 XMLDocument doc;
4598
4599 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4600 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004601
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004602 XMLNode root_element = doc.GetRootElement("library-list-svr4");
4603 if (!root_element)
4604 return Error();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004605
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004606 // main link map structure
4607 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4608 if (!main_lm.empty())
4609 {
4610 list.m_link_map = StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
4611 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004612
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004613 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
Aidan Doddsc0c83852015-05-08 09:36:31 +00004614
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004615 GDBLoadedModuleInfoList::LoadedModuleInfo module;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004616
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004617 library.ForEachAttribute([log, &module](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004618
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004619 if (name == "name")
4620 module.set_name (value.str());
4621 else if (name == "lm")
4622 {
4623 // the address of the link_map struct.
4624 module.set_link_map(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4625 }
4626 else if (name == "l_addr")
4627 {
4628 // the displacement as read from the field 'l_addr' of the link_map struct.
4629 module.set_base(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
Stephane Sezerc6845a02015-08-20 22:07:48 +00004630 // base address is always a displacement, not an absolute value.
4631 module.set_base_is_offset(true);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004632 }
4633 else if (name == "l_ld")
4634 {
4635 // the memory address of the libraries PT_DYAMIC section.
4636 module.set_dynamic(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4637 }
4638
4639 return true; // Keep iterating over all properties of "library"
4640 });
4641
4642 if (log)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004643 {
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004644 std::string name;
4645 lldb::addr_t lm=0, base=0, ld=0;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004646 bool base_is_offset;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004647
4648 module.get_name (name);
4649 module.get_link_map (lm);
4650 module.get_base (base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004651 module.get_base_is_offset (base_is_offset);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004652 module.get_dynamic (ld);
4653
Stephane Sezerc6845a02015-08-20 22:07:48 +00004654 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 +00004655 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004656
4657 list.add (module);
4658 return true; // Keep iterating over all "library" elements in the root node
Greg Claytond04f0ed2015-05-26 18:00:51 +00004659 });
Aidan Doddsc0c83852015-05-08 09:36:31 +00004660
4661 if (log)
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004662 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4663 } else if (comm.GetQXferLibrariesReadSupported ()) {
4664 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004665
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004666 // request the loaded library list
4667 std::string raw;
4668 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004669
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004670 if (!comm.ReadExtFeature (ConstString ("libraries"), ConstString (""), raw, lldberr))
4671 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004672
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004673 if (log)
4674 log->Printf ("parsing: %s", raw.c_str());
4675 XMLDocument doc;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004676
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004677 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4678 return Error (0, ErrorType::eErrorTypeGeneric);
4679
4680 XMLNode root_element = doc.GetRootElement("library-list");
4681 if (!root_element)
4682 return Error();
4683
4684 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
4685 GDBLoadedModuleInfoList::LoadedModuleInfo module;
4686
4687 llvm::StringRef name = library.GetAttributeValue("name");
4688 module.set_name(name.str());
4689
4690 // The base address of a given library will be the address of its
4691 // first section. Most remotes send only one section for Windows
4692 // targets for example.
4693 const XMLNode &section = library.FindFirstChildElementWithName("section");
4694 llvm::StringRef address = section.GetAttributeValue("address");
4695 module.set_base(StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0));
Stephane Sezerc6845a02015-08-20 22:07:48 +00004696 // These addresses are absolute values.
4697 module.set_base_is_offset(false);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004698
4699 if (log)
4700 {
4701 std::string name;
4702 lldb::addr_t base = 0;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004703 bool base_is_offset;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004704 module.get_name (name);
4705 module.get_base (base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004706 module.get_base_is_offset (base_is_offset);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004707
Stephane Sezerc6845a02015-08-20 22:07:48 +00004708 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 +00004709 }
4710
4711 list.add (module);
4712 return true; // Keep iterating over all "library" elements in the root node
4713 });
4714
4715 if (log)
4716 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4717 } else {
4718 return Error (0, ErrorType::eErrorTypeGeneric);
4719 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004720
4721 return Error();
4722}
4723
Aidan Doddsc0c83852015-05-08 09:36:31 +00004724lldb::ModuleSP
Stephane Sezerc6845a02015-08-20 22:07:48 +00004725ProcessGDBRemote::LoadModuleAtAddress (const FileSpec &file, lldb::addr_t base_addr, bool value_is_offset)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004726{
4727 Target &target = m_process->GetTarget();
4728 ModuleList &modules = target.GetImages();
4729 ModuleSP module_sp;
4730
4731 bool changed = false;
4732
4733 ModuleSpec module_spec (file, target.GetArchitecture());
4734 if ((module_sp = modules.FindFirstModule (module_spec)))
4735 {
Stephane Sezerc6845a02015-08-20 22:07:48 +00004736 module_sp->SetLoadAddress (target, base_addr, value_is_offset, changed);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004737 }
4738 else if ((module_sp = target.GetSharedModule (module_spec)))
4739 {
Stephane Sezerc6845a02015-08-20 22:07:48 +00004740 module_sp->SetLoadAddress (target, base_addr, value_is_offset, changed);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004741 }
4742
4743 return module_sp;
4744}
4745
4746size_t
4747ProcessGDBRemote::LoadModules ()
4748{
4749 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4750
4751 // request a list of loaded libraries from GDBServer
4752 GDBLoadedModuleInfoList module_list;
4753 if (GetLoadedModuleList (module_list).Fail())
4754 return 0;
4755
4756 // get a list of all the modules
4757 ModuleList new_modules;
4758
4759 for (GDBLoadedModuleInfoList::LoadedModuleInfo & modInfo : module_list.m_list)
4760 {
4761 std::string mod_name;
4762 lldb::addr_t mod_base;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004763 bool mod_base_is_offset;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004764
4765 bool valid = true;
4766 valid &= modInfo.get_name (mod_name);
4767 valid &= modInfo.get_base (mod_base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004768 valid &= modInfo.get_base_is_offset (mod_base_is_offset);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004769 if (!valid)
4770 continue;
4771
4772 // hack (cleaner way to get file name only?) (win/unix compat?)
Vince Harron4cc8d202015-05-10 08:33:58 +00004773 size_t marker = mod_name.rfind ('/');
Aidan Doddsc0c83852015-05-08 09:36:31 +00004774 if (marker == std::string::npos)
4775 marker = 0;
4776 else
4777 marker += 1;
4778
4779 FileSpec file (mod_name.c_str()+marker, true);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004780 lldb::ModuleSP module_sp = LoadModuleAtAddress (file, mod_base, mod_base_is_offset);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004781
4782 if (module_sp.get())
4783 new_modules.Append (module_sp);
4784 }
4785
4786 if (new_modules.GetSize() > 0)
4787 {
Zachary Turner7529df92015-09-01 20:02:29 +00004788 Target &target = GetTarget();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004789
4790 new_modules.ForEach ([&target](const lldb::ModuleSP module_sp) -> bool
4791 {
4792 lldb_private::ObjectFile * obj = module_sp->GetObjectFile ();
4793 if (!obj)
4794 return true;
4795
4796 if (obj->GetType () != ObjectFile::Type::eTypeExecutable)
4797 return true;
4798
4799 lldb::ModuleSP module_copy_sp = module_sp;
4800 target.SetExecutableModule (module_copy_sp, false);
4801 return false;
4802 });
4803
4804 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4805 loaded_modules.AppendIfNeeded (new_modules);
4806 m_process->GetTarget().ModulesDidLoad (new_modules);
4807 }
4808
4809 return new_modules.GetSize();
4810}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004811
Tamas Berghammer783bfc82015-06-18 20:43:56 +00004812Error
4813ProcessGDBRemote::GetFileLoadAddress(const FileSpec& file, bool& is_loaded, lldb::addr_t& load_addr)
4814{
4815 is_loaded = false;
4816 load_addr = LLDB_INVALID_ADDRESS;
4817
4818 std::string file_path = file.GetPath(false);
4819 if (file_path.empty ())
4820 return Error("Empty file name specified");
4821
4822 StreamString packet;
4823 packet.PutCString("qFileLoadAddress:");
4824 packet.PutCStringAsRawHex8(file_path.c_str());
4825
4826 StringExtractorGDBRemote response;
4827 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString().c_str(), response, false) != GDBRemoteCommunication::PacketResult::Success)
4828 return Error("Sending qFileLoadAddress packet failed");
4829
4830 if (response.IsErrorResponse())
4831 {
4832 if (response.GetError() == 1)
4833 {
4834 // The file is not loaded into the inferior
4835 is_loaded = false;
4836 load_addr = LLDB_INVALID_ADDRESS;
4837 return Error();
4838 }
4839
4840 return Error("Fetching file load address from remote server returned an error");
4841 }
4842
4843 if (response.IsNormalResponse())
4844 {
4845 is_loaded = true;
4846 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
4847 return Error();
4848 }
4849
4850 return Error("Unknown error happened during sending the load address packet");
4851}
4852
Greg Clayton0b90be12015-06-23 21:27:50 +00004853
4854void
4855ProcessGDBRemote::ModulesDidLoad (ModuleList &module_list)
4856{
4857 // We must call the lldb_private::Process::ModulesDidLoad () first before we do anything
4858 Process::ModulesDidLoad (module_list);
4859
4860 // After loading shared libraries, we can ask our remote GDB server if
4861 // it needs any symbols.
4862 m_gdb_comm.ServeSymbolLookups(this);
4863}
4864
4865
Greg Claytone034a042015-05-21 20:52:06 +00004866class CommandObjectProcessGDBRemoteSpeedTest: public CommandObjectParsed
4867{
4868public:
4869 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter) :
4870 CommandObjectParsed (interpreter,
4871 "process plugin packet speed-test",
4872 "Tests packet speeds of various sizes to determine the performance characteristics of the GDB remote connection. ",
4873 NULL),
4874 m_option_group (interpreter),
4875 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),
4876 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),
4877 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),
4878 m_json (LLDB_OPT_SET_1, false, "json", 'j', "Print the output as JSON data for easy parsing.", false, true)
4879 {
4880 m_option_group.Append (&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4881 m_option_group.Append (&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4882 m_option_group.Append (&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4883 m_option_group.Append (&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4884 m_option_group.Finalize();
4885 }
4886
4887 ~CommandObjectProcessGDBRemoteSpeedTest ()
4888 {
4889 }
4890
4891
4892 Options *
4893 GetOptions () override
4894 {
4895 return &m_option_group;
4896 }
4897
4898 bool
4899 DoExecute (Args& command, CommandReturnObject &result) override
4900 {
4901 const size_t argc = command.GetArgumentCount();
4902 if (argc == 0)
4903 {
4904 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4905 if (process)
4906 {
4907 StreamSP output_stream_sp (m_interpreter.GetDebugger().GetAsyncOutputStream());
4908 result.SetImmediateOutputStream (output_stream_sp);
4909
4910 const uint32_t num_packets = (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
4911 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
4912 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
4913 const bool json = m_json.GetOptionValue().GetCurrentValue();
4914 if (output_stream_sp)
4915 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, *output_stream_sp);
4916 else
4917 {
4918 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, result.GetOutputStream());
4919 }
4920 result.SetStatus (eReturnStatusSuccessFinishResult);
4921 return true;
4922 }
4923 }
4924 else
4925 {
4926 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
4927 }
4928 result.SetStatus (eReturnStatusFailed);
4929 return false;
4930 }
4931protected:
4932 OptionGroupOptions m_option_group;
4933 OptionGroupUInt64 m_num_packets;
4934 OptionGroupUInt64 m_max_send;
4935 OptionGroupUInt64 m_max_recv;
4936 OptionGroupBoolean m_json;
4937
4938};
4939
Greg Clayton02686b82012-10-15 22:42:16 +00004940class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00004941{
4942private:
4943
4944public:
Greg Clayton02686b82012-10-15 22:42:16 +00004945 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00004946 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00004947 "process plugin packet history",
4948 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00004949 NULL)
4950 {
4951 }
4952
Greg Clayton02686b82012-10-15 22:42:16 +00004953 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton998255b2012-10-13 02:07:45 +00004954 {
4955 }
4956
4957 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004958 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton998255b2012-10-13 02:07:45 +00004959 {
Greg Clayton02686b82012-10-15 22:42:16 +00004960 const size_t argc = command.GetArgumentCount();
4961 if (argc == 0)
4962 {
4963 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4964 if (process)
4965 {
4966 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
4967 result.SetStatus (eReturnStatusSuccessFinishResult);
4968 return true;
4969 }
4970 }
4971 else
4972 {
4973 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
4974 }
4975 result.SetStatus (eReturnStatusFailed);
4976 return false;
4977 }
4978};
4979
Jason Molenda6076bf42014-05-06 04:34:52 +00004980class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed
4981{
4982private:
4983
4984public:
4985 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) :
4986 CommandObjectParsed (interpreter,
4987 "process plugin packet xfer-size",
4988 "Maximum size that lldb will try to read/write one one chunk.",
4989 NULL)
4990 {
4991 }
4992
4993 ~CommandObjectProcessGDBRemotePacketXferSize ()
4994 {
4995 }
4996
4997 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004998 DoExecute (Args& command, CommandReturnObject &result) override
Jason Molenda6076bf42014-05-06 04:34:52 +00004999 {
5000 const size_t argc = command.GetArgumentCount();
5001 if (argc == 0)
5002 {
5003 result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str());
5004 result.SetStatus (eReturnStatusFailed);
5005 return false;
5006 }
5007
5008 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5009 if (process)
5010 {
5011 const char *packet_size = command.GetArgumentAtIndex(0);
5012 errno = 0;
5013 uint64_t user_specified_max = strtoul (packet_size, NULL, 10);
5014 if (errno == 0 && user_specified_max != 0)
5015 {
5016 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max);
5017 result.SetStatus (eReturnStatusSuccessFinishResult);
5018 return true;
5019 }
5020 }
5021 result.SetStatus (eReturnStatusFailed);
5022 return false;
5023 }
5024};
5025
5026
Greg Clayton02686b82012-10-15 22:42:16 +00005027class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
5028{
5029private:
5030
5031public:
5032 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
5033 CommandObjectParsed (interpreter,
5034 "process plugin packet send",
5035 "Send a custom packet through the GDB remote protocol and print the answer. "
5036 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
5037 NULL)
5038 {
5039 }
5040
5041 ~CommandObjectProcessGDBRemotePacketSend ()
5042 {
5043 }
5044
5045 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005046 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton02686b82012-10-15 22:42:16 +00005047 {
5048 const size_t argc = command.GetArgumentCount();
5049 if (argc == 0)
5050 {
5051 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
5052 result.SetStatus (eReturnStatusFailed);
5053 return false;
5054 }
5055
5056 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5057 if (process)
5058 {
Han Ming Ong84145852012-11-26 20:42:03 +00005059 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00005060 {
Han Ming Ong84145852012-11-26 20:42:03 +00005061 const char *packet_cstr = command.GetArgumentAtIndex(0);
5062 bool send_async = true;
5063 StringExtractorGDBRemote response;
5064 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
5065 result.SetStatus (eReturnStatusSuccessFinishResult);
5066 Stream &output_strm = result.GetOutputStream();
5067 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00005068 std::string &response_str = response.GetStringRef();
5069
Han Ming Ong399289e2013-06-21 19:56:59 +00005070 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00005071 {
5072 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
5073 }
5074
Han Ming Ong84145852012-11-26 20:42:03 +00005075 if (response_str.empty())
5076 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
5077 else
5078 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00005079 }
Greg Clayton02686b82012-10-15 22:42:16 +00005080 }
Greg Clayton998255b2012-10-13 02:07:45 +00005081 return true;
5082 }
5083};
5084
Greg Claytonba4a0a52013-02-01 23:03:47 +00005085class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
5086{
5087private:
5088
5089public:
5090 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
5091 CommandObjectRaw (interpreter,
5092 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00005093 "Send a qRcmd packet through the GDB remote protocol and print the response."
5094 "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 +00005095 NULL)
5096 {
5097 }
5098
5099 ~CommandObjectProcessGDBRemotePacketMonitor ()
5100 {
5101 }
5102
5103 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005104 DoExecute (const char *command, CommandReturnObject &result) override
Greg Claytonba4a0a52013-02-01 23:03:47 +00005105 {
5106 if (command == NULL || command[0] == '\0')
5107 {
5108 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
5109 result.SetStatus (eReturnStatusFailed);
5110 return false;
5111 }
5112
5113 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5114 if (process)
5115 {
5116 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00005117 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00005118 packet.PutBytesAsRawHex8(command, strlen(command));
5119 const char *packet_cstr = packet.GetString().c_str();
5120
5121 bool send_async = true;
5122 StringExtractorGDBRemote response;
5123 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
5124 result.SetStatus (eReturnStatusSuccessFinishResult);
5125 Stream &output_strm = result.GetOutputStream();
5126 output_strm.Printf (" packet: %s\n", packet_cstr);
5127 const std::string &response_str = response.GetStringRef();
5128
5129 if (response_str.empty())
5130 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
5131 else
5132 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
5133 }
5134 return true;
5135 }
5136};
5137
Greg Clayton02686b82012-10-15 22:42:16 +00005138class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
5139{
5140private:
5141
5142public:
5143 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
5144 CommandObjectMultiword (interpreter,
5145 "process plugin packet",
5146 "Commands that deal with GDB remote packets.",
5147 NULL)
5148 {
5149 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
5150 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00005151 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Jason Molenda6076bf42014-05-06 04:34:52 +00005152 LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter)));
Greg Claytone034a042015-05-21 20:52:06 +00005153 LoadSubCommand ("speed-test", CommandObjectSP (new CommandObjectProcessGDBRemoteSpeedTest (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00005154 }
5155
5156 ~CommandObjectProcessGDBRemotePacket ()
5157 {
5158 }
5159};
Greg Clayton998255b2012-10-13 02:07:45 +00005160
5161class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
5162{
5163public:
5164 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
5165 CommandObjectMultiword (interpreter,
5166 "process plugin",
5167 "A set of commands for operating on a ProcessGDBRemote process.",
5168 "process plugin <subcommand> [<subcommand-options>]")
5169 {
5170 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
5171 }
5172
5173 ~CommandObjectMultiwordProcessGDBRemote ()
5174 {
5175 }
5176};
5177
Greg Clayton998255b2012-10-13 02:07:45 +00005178CommandObject *
5179ProcessGDBRemote::GetPluginCommandObject()
5180{
5181 if (!m_command_sp)
5182 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
5183 return m_command_sp.get();
5184}