blob: 2d5b76c3a9de8e804f48d2538135c9ed00b529bd [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"
Jason Molenda21586c82015-09-09 03:36:24 +000059#include "lldb/Target/ABI.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000060#include "lldb/Target/DynamicLoader.h"
61#include "lldb/Target/Target.h"
62#include "lldb/Target/TargetList.h"
Greg Clayton2a48f522011-05-14 01:50:35 +000063#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molenda705b1802014-06-13 02:37:02 +000064#include "lldb/Target/SystemRuntime.h"
Jason Molendaa34a0c62010-06-09 21:28:42 +000065#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000066
67// Project includes
68#include "lldb/Host/Host.h"
Chaoren Lin98d0a4b2015-07-14 01:09:28 +000069#include "Plugins/Process/Utility/GDBRemoteSignals.h"
Peter Collingbourne99f9aa02011-06-03 20:40:38 +000070#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Jason Molendac42d2432012-07-25 03:40:06 +000071#include "Plugins/Process/Utility/StopInfoMachException.h"
Jim Ingham43c555d2012-07-04 00:35:43 +000072#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
Greg Claytonc982c762010-07-09 20:39:50 +000073#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000074#include "GDBRemoteRegisterContext.h"
75#include "ProcessGDBRemote.h"
76#include "ProcessGDBRemoteLog.h"
77#include "ThreadGDBRemote.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000078
Tamas Berghammerdb264a62015-03-31 09:52:22 +000079#define DEBUGSERVER_BASENAME "debugserver"
80using namespace lldb;
81using namespace lldb_private;
82using namespace lldb_private::process_gdb_remote;
Jason Molenda5e8534e2012-10-03 01:29:34 +000083
Greg Claytonc1422c12012-04-09 22:46:21 +000084namespace lldb
85{
86 // Provide a function that can easily dump the packet history if we know a
87 // ProcessGDBRemote * value (which we can get from logs or from debugging).
88 // We need the function in the lldb namespace so it makes it into the final
89 // executable since the LLDB shared library only exports stuff in the lldb
90 // namespace. This allows you to attach with a debugger and call this
91 // function and get the packet history dumped to a file.
92 void
93 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
94 {
Tamas Berghammerdb264a62015-03-31 09:52:22 +000095 StreamFile strm;
96 Error error (strm.GetFile().Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate));
Greg Claytond451c1a2012-04-13 21:24:18 +000097 if (error.Success())
98 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
Greg Claytonc1422c12012-04-09 22:46:21 +000099 }
Filipe Cabecinhasc34f7762012-05-23 16:27:09 +0000100}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000101
Greg Clayton7f982402013-07-15 22:54:20 +0000102namespace {
Steve Pucci5ec012d2014-01-16 22:18:14 +0000103
Greg Clayton7f982402013-07-15 22:54:20 +0000104 static PropertyDefinition
105 g_properties[] =
106 {
107 { "packet-timeout" , OptionValue::eTypeUInt64 , true , 1, NULL, NULL, "Specify the default packet timeout in seconds." },
Greg Claytonef8180a2013-10-15 00:14:28 +0000108 { "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 +0000109 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
110 };
111
112 enum
113 {
Greg Claytonef8180a2013-10-15 00:14:28 +0000114 ePropertyPacketTimeout,
115 ePropertyTargetDefinitionFile
Greg Clayton7f982402013-07-15 22:54:20 +0000116 };
117
118 class PluginProperties : public Properties
119 {
120 public:
121
122 static ConstString
123 GetSettingName ()
124 {
125 return ProcessGDBRemote::GetPluginNameStatic();
126 }
127
128 PluginProperties() :
129 Properties ()
130 {
131 m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
132 m_collection_sp->Initialize(g_properties);
133 }
134
135 virtual
136 ~PluginProperties()
137 {
138 }
139
140 uint64_t
141 GetPacketTimeout()
142 {
143 const uint32_t idx = ePropertyPacketTimeout;
144 return m_collection_sp->GetPropertyAtIndexAsUInt64(NULL, idx, g_properties[idx].default_uint_value);
145 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000146
147 bool
148 SetPacketTimeout(uint64_t timeout)
149 {
150 const uint32_t idx = ePropertyPacketTimeout;
151 return m_collection_sp->SetPropertyAtIndexAsUInt64(NULL, idx, timeout);
152 }
153
Greg Claytonef8180a2013-10-15 00:14:28 +0000154 FileSpec
155 GetTargetDefinitionFile () const
156 {
157 const uint32_t idx = ePropertyTargetDefinitionFile;
158 return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
159 }
Greg Clayton7f982402013-07-15 22:54:20 +0000160 };
161
162 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
163
164 static const ProcessKDPPropertiesSP &
165 GetGlobalPluginProperties()
166 {
167 static ProcessKDPPropertiesSP g_settings_sp;
168 if (!g_settings_sp)
169 g_settings_sp.reset (new PluginProperties ());
170 return g_settings_sp;
171 }
172
173} // anonymous namespace end
174
Aidan Doddsc0c83852015-05-08 09:36:31 +0000175class ProcessGDBRemote::GDBLoadedModuleInfoList
176{
177public:
178
179 class LoadedModuleInfo
180 {
181 public:
182
183 enum e_data_point
184 {
185 e_has_name = 0,
186 e_has_base ,
187 e_has_dynamic ,
188 e_has_link_map ,
189 e_num
190 };
191
192 LoadedModuleInfo ()
193 {
194 for (uint32_t i = 0; i < e_num; ++i)
195 m_has[i] = false;
Pavel Labathcb213b32015-07-22 08:12:01 +0000196 }
Aidan Doddsc0c83852015-05-08 09:36:31 +0000197
198 void set_name (const std::string & name)
199 {
200 m_name = name;
201 m_has[e_has_name] = true;
202 }
203 bool get_name (std::string & out) const
204 {
205 out = m_name;
206 return m_has[e_has_name];
207 }
208
209 void set_base (const lldb::addr_t base)
210 {
211 m_base = base;
212 m_has[e_has_base] = true;
213 }
214 bool get_base (lldb::addr_t & out) const
215 {
216 out = m_base;
217 return m_has[e_has_base];
218 }
219
Stephane Sezerc6845a02015-08-20 22:07:48 +0000220 void set_base_is_offset (bool is_offset)
221 {
222 m_base_is_offset = is_offset;
223 }
224 bool get_base_is_offset(bool & out) const
225 {
226 out = m_base_is_offset;
227 return m_has[e_has_base];
228 }
229
Aidan Doddsc0c83852015-05-08 09:36:31 +0000230 void set_link_map (const lldb::addr_t addr)
231 {
232 m_link_map = addr;
233 m_has[e_has_link_map] = true;
234 }
235 bool get_link_map (lldb::addr_t & out) const
236 {
237 out = m_link_map;
238 return m_has[e_has_link_map];
239 }
240
241 void set_dynamic (const lldb::addr_t addr)
242 {
243 m_dynamic = addr;
244 m_has[e_has_dynamic] = true;
245 }
246 bool get_dynamic (lldb::addr_t & out) const
247 {
248 out = m_dynamic;
249 return m_has[e_has_dynamic];
250 }
251
252 bool has_info (e_data_point datum)
253 {
254 assert (datum < e_num);
255 return m_has[datum];
256 }
257
258 protected:
259
260 bool m_has[e_num];
261 std::string m_name;
262 lldb::addr_t m_link_map;
263 lldb::addr_t m_base;
Stephane Sezerc6845a02015-08-20 22:07:48 +0000264 bool m_base_is_offset;
Aidan Doddsc0c83852015-05-08 09:36:31 +0000265 lldb::addr_t m_dynamic;
266 };
267
268 GDBLoadedModuleInfoList ()
269 : m_list ()
270 , m_link_map (LLDB_INVALID_ADDRESS)
271 {}
272
273 void add (const LoadedModuleInfo & mod)
274 {
275 m_list.push_back (mod);
276 }
277
278 void clear ()
279 {
280 m_list.clear ();
281 }
282
283 std::vector<LoadedModuleInfo> m_list;
284 lldb::addr_t m_link_map;
285};
286
Greg Claytonfda4fab2014-01-10 22:24:11 +0000287// TODO Randomly assigning a port is unsafe. We should get an unused
288// ephemeral port from the kernel and make sure we reserve it before passing
289// it to debugserver.
290
291#if defined (__APPLE__)
292#define LOW_PORT (IPPORT_RESERVED)
293#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
294#else
295#define LOW_PORT (1024u)
296#define HIGH_PORT (49151u)
297#endif
298
Todd Fiala013434e2014-07-09 01:29:05 +0000299#if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000300static bool rand_initialized = false;
301
Greg Claytonfda4fab2014-01-10 22:24:11 +0000302static inline uint16_t
303get_random_port ()
304{
305 if (!rand_initialized)
306 {
307 time_t seed = time(NULL);
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000308
Greg Claytonfda4fab2014-01-10 22:24:11 +0000309 rand_initialized = true;
310 srand(seed);
311 }
312 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
313}
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000314#endif
Greg Claytonfda4fab2014-01-10 22:24:11 +0000315
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000316ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000317ProcessGDBRemote::GetPluginNameStatic()
318{
Greg Clayton57abc5d2013-05-10 21:47:16 +0000319 static ConstString g_name("gdb-remote");
320 return g_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000321}
322
323const char *
324ProcessGDBRemote::GetPluginDescriptionStatic()
325{
326 return "GDB Remote protocol based debugging plug-in.";
327}
328
329void
330ProcessGDBRemote::Terminate()
331{
332 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
333}
334
335
Greg Claytonc3776bf2012-02-09 06:16:32 +0000336lldb::ProcessSP
Zachary Turner7529df92015-09-01 20:02:29 +0000337ProcessGDBRemote::CreateInstance (lldb::TargetSP target_sp, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000338{
Greg Claytonc3776bf2012-02-09 06:16:32 +0000339 lldb::ProcessSP process_sp;
340 if (crash_file_path == NULL)
Zachary Turner7529df92015-09-01 20:02:29 +0000341 process_sp.reset (new ProcessGDBRemote (target_sp, listener));
Greg Claytonc3776bf2012-02-09 06:16:32 +0000342 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000343}
344
345bool
Zachary Turner7529df92015-09-01 20:02:29 +0000346ProcessGDBRemote::CanDebug (lldb::TargetSP target_sp, bool plugin_specified_by_name)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000347{
Greg Clayton596ed242011-10-21 21:41:45 +0000348 if (plugin_specified_by_name)
349 return true;
350
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000351 // For now we are just making sure the file exists for a given module
Zachary Turner7529df92015-09-01 20:02:29 +0000352 Module *exe_module = target_sp->GetExecutableModulePointer();
Greg Claytonaa149cb2011-08-11 02:48:45 +0000353 if (exe_module)
Greg Claytonc3776bf2012-02-09 06:16:32 +0000354 {
355 ObjectFile *exe_objfile = exe_module->GetObjectFile();
356 // We can't debug core files...
357 switch (exe_objfile->GetType())
358 {
359 case ObjectFile::eTypeInvalid:
360 case ObjectFile::eTypeCoreFile:
361 case ObjectFile::eTypeDebugInfo:
362 case ObjectFile::eTypeObjectFile:
363 case ObjectFile::eTypeSharedLibrary:
364 case ObjectFile::eTypeStubLibrary:
Greg Clayton23f8c952014-03-24 23:10:19 +0000365 case ObjectFile::eTypeJIT:
Greg Claytonc3776bf2012-02-09 06:16:32 +0000366 return false;
367 case ObjectFile::eTypeExecutable:
368 case ObjectFile::eTypeDynamicLinker:
369 case ObjectFile::eTypeUnknown:
370 break;
371 }
Greg Claytonaa149cb2011-08-11 02:48:45 +0000372 return exe_module->GetFileSpec().Exists();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000373 }
Jim Ingham5aee1622010-08-09 23:31:02 +0000374 // However, if there is no executable module, we return true since we might be preparing to attach.
375 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000376}
377
378//----------------------------------------------------------------------
379// ProcessGDBRemote constructor
380//----------------------------------------------------------------------
Zachary Turner7529df92015-09-01 20:02:29 +0000381ProcessGDBRemote::ProcessGDBRemote(lldb::TargetSP target_sp, Listener &listener) :
382 Process (target_sp, listener),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000383 m_flags (0),
Tamas Berghammere13c2732015-02-11 10:29:30 +0000384 m_gdb_comm (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000385 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Bhushan D. Attarde1e271df2015-07-24 04:06:20 +0000386 m_last_stop_packet_mutex (Mutex::eMutexTypeRecursive),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000387 m_register_info (),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000388 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
Pavel Labath50556852015-09-03 09:36:22 +0000389 m_async_listener("lldb.process.gdb-remote.async-listener"),
Jim Ingham455fa5c2012-11-01 01:15:33 +0000390 m_async_thread_state_mutex(Mutex::eMutexTypeRecursive),
Greg Clayton9e920902012-04-10 02:25:43 +0000391 m_thread_ids (),
Greg Clayton2e309072015-07-17 23:42:28 +0000392 m_jstopinfo_sp (),
393 m_jthreadsinfo_sp (),
Greg Clayton71fc2a32011-02-12 06:28:37 +0000394 m_continue_c_tids (),
395 m_continue_C_tids (),
396 m_continue_s_tids (),
397 m_continue_S_tids (),
Jason Molenda6076bf42014-05-06 04:34:52 +0000398 m_max_memory_size (0),
399 m_remote_stub_max_memory_size (0),
Greg Clayton4116e932012-05-15 02:33:01 +0000400 m_addr_to_mmap_size (),
401 m_thread_create_bp_sp (),
Jim Ingham43c555d2012-07-04 00:35:43 +0000402 m_waiting_for_attach (false),
Jason Molenda5e8534e2012-10-03 01:29:34 +0000403 m_destroy_tried_resuming (false),
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000404 m_command_sp (),
Ewan Crawford78baa192015-05-13 09:18:18 +0000405 m_breakpoint_pc_offset (0),
406 m_initial_tid (LLDB_INVALID_THREAD_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000407{
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000408 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
409 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Inghamb1e2e842012-04-12 18:49:31 +0000410 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Pavel Labath50556852015-09-03 09:36:22 +0000411
412 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_ASYNC));
413
414 const uint32_t async_event_mask = eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
415
416 if (m_async_listener.StartListeningForEvents(&m_async_broadcaster, async_event_mask) != async_event_mask)
417 {
418 if (log)
419 log->Printf("ProcessGDBRemote::%s failed to listen for m_async_broadcaster events", __FUNCTION__);
420 }
421
422 const uint32_t gdb_event_mask = Communication::eBroadcastBitReadThreadDidExit |
423 GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify;
424 if (m_async_listener.StartListeningForEvents(&m_gdb_comm, gdb_event_mask) != gdb_event_mask)
425 {
426 if (log)
427 log->Printf("ProcessGDBRemote::%s failed to listen for m_gdb_comm events", __FUNCTION__);
428 }
429
Greg Clayton7f982402013-07-15 22:54:20 +0000430 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
431 if (timeout_seconds > 0)
432 m_gdb_comm.SetPacketTimeout(timeout_seconds);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000433}
434
435//----------------------------------------------------------------------
436// Destructor
437//----------------------------------------------------------------------
438ProcessGDBRemote::~ProcessGDBRemote()
439{
440 // m_mach_process.UnregisterNotificationCallbacks (this);
441 Clear();
Greg Clayton1ed54f52011-10-01 00:45:15 +0000442 // We need to call finalize on the process before destroying ourselves
443 // to make sure all of the broadcaster cleanup goes as planned. If we
444 // destruct this class, then Process::~Process() might have problems
445 // trying to fully destroy the broadcaster.
446 Finalize();
Jim Ingham455fa5c2012-11-01 01:15:33 +0000447
448 // The general Finalize is going to try to destroy the process and that SHOULD
449 // shut down the async thread. However, if we don't kill it it will get stranded and
450 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
451 StopAsyncThread();
452 KillDebugserverProcess();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000453}
454
455//----------------------------------------------------------------------
456// PluginInterface
457//----------------------------------------------------------------------
Greg Clayton57abc5d2013-05-10 21:47:16 +0000458ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000459ProcessGDBRemote::GetPluginName()
460{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000461 return GetPluginNameStatic();
462}
463
464uint32_t
465ProcessGDBRemote::GetPluginVersion()
466{
467 return 1;
468}
469
Greg Claytonef8180a2013-10-15 00:14:28 +0000470bool
471ProcessGDBRemote::ParsePythonTargetDefinition(const FileSpec &target_definition_fspec)
472{
473 ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
474 Error error;
Zachary Turner0641ca12015-03-17 20:04:04 +0000475 StructuredData::ObjectSP module_object_sp(interpreter->LoadPluginModule(target_definition_fspec, error));
Greg Claytonef8180a2013-10-15 00:14:28 +0000476 if (module_object_sp)
477 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000478 StructuredData::DictionarySP target_definition_sp(
479 interpreter->GetDynamicSettings(module_object_sp, &GetTarget(), "gdb-server-target-definition", error));
Greg Claytonef8180a2013-10-15 00:14:28 +0000480
Zachary Turner0641ca12015-03-17 20:04:04 +0000481 if (target_definition_sp)
Greg Claytonef8180a2013-10-15 00:14:28 +0000482 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000483 StructuredData::ObjectSP target_object(target_definition_sp->GetValueForKey("host-info"));
484 if (target_object)
Greg Clayton312bcbe2013-10-17 01:10:23 +0000485 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000486 if (auto host_info_dict = target_object->GetAsDictionary())
Greg Clayton312bcbe2013-10-17 01:10:23 +0000487 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000488 StructuredData::ObjectSP triple_value = host_info_dict->GetValueForKey("triple");
489 if (auto triple_string_value = triple_value->GetAsString())
490 {
491 std::string triple_string = triple_string_value->GetValue();
492 ArchSpec host_arch(triple_string.c_str());
493 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture()))
494 {
495 GetTarget().SetArchitecture(host_arch);
496 }
497 }
Greg Clayton312bcbe2013-10-17 01:10:23 +0000498 }
Greg Clayton312bcbe2013-10-17 01:10:23 +0000499 }
Zachary Turner0641ca12015-03-17 20:04:04 +0000500 m_breakpoint_pc_offset = 0;
501 StructuredData::ObjectSP breakpoint_pc_offset_value = target_definition_sp->GetValueForKey("breakpoint-pc-offset");
502 if (breakpoint_pc_offset_value)
503 {
504 if (auto breakpoint_pc_int_value = breakpoint_pc_offset_value->GetAsInteger())
505 m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
506 }
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000507
Greg Claytond04f0ed2015-05-26 18:00:51 +0000508 if (m_register_info.SetRegisterInfo(*target_definition_sp, GetTarget().GetArchitecture()) > 0)
Greg Claytonef8180a2013-10-15 00:14:28 +0000509 {
510 return true;
511 }
512 }
513 }
514 return false;
515}
516
Jason Molenda21586c82015-09-09 03:36:24 +0000517// If the remote stub didn't give us eh_frame or DWARF register numbers for a register,
518// see if the ABI can provide them.
519// DWARF and eh_frame register numbers are defined as a part of the ABI.
520static void
521AugmentRegisterInfoViaABI (RegisterInfo &reg_info, ConstString reg_name, ABISP abi_sp)
522{
523 if (reg_info.kinds[eRegisterKindEHFrame] == LLDB_INVALID_REGNUM
524 || reg_info.kinds[eRegisterKindDWARF] == LLDB_INVALID_REGNUM)
525 {
526 if (abi_sp)
527 {
528 RegisterInfo abi_reg_info;
529 if (abi_sp->GetRegisterInfoByName (reg_name, abi_reg_info))
530 {
531 if (reg_info.kinds[eRegisterKindEHFrame] == LLDB_INVALID_REGNUM
532 && abi_reg_info.kinds[eRegisterKindEHFrame] != LLDB_INVALID_REGNUM)
533 {
534 reg_info.kinds[eRegisterKindEHFrame] = abi_reg_info.kinds[eRegisterKindEHFrame];
535 }
536 if (reg_info.kinds[eRegisterKindDWARF] == LLDB_INVALID_REGNUM
537 && abi_reg_info.kinds[eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
538 {
539 reg_info.kinds[eRegisterKindDWARF] = abi_reg_info.kinds[eRegisterKindDWARF];
540 }
541 }
542 }
543 }
544}
545
Greg Claytond04f0ed2015-05-26 18:00:51 +0000546static size_t
547SplitCommaSeparatedRegisterNumberString(const llvm::StringRef &comma_separated_regiter_numbers, std::vector<uint32_t> &regnums, int base)
548{
549 regnums.clear();
550 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
551 value_pair.second = comma_separated_regiter_numbers;
552 do
553 {
554 value_pair = value_pair.second.split(',');
555 if (!value_pair.first.empty())
556 {
557 uint32_t reg = StringConvert::ToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, base);
558 if (reg != LLDB_INVALID_REGNUM)
559 regnums.push_back (reg);
560 }
561 } while (!value_pair.second.empty());
562 return regnums.size();
563}
564
Greg Claytonef8180a2013-10-15 00:14:28 +0000565
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000566void
Greg Clayton513c26c2011-01-29 07:10:55 +0000567ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000568{
Greg Clayton513c26c2011-01-29 07:10:55 +0000569 if (!force && m_register_info.GetNumRegisters() > 0)
570 return;
571
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000572 m_register_info.Clear();
Greg Claytond04f0ed2015-05-26 18:00:51 +0000573
574 // Check if qHostInfo specified a specific packet timeout for this connection.
575 // If so then lets update our setting so the user knows what the timeout is
576 // and can see it.
577 const uint32_t host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
578 if (host_packet_timeout)
579 {
580 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout);
581 }
582
Ewan Crawford0c996a92015-06-30 13:08:44 +0000583 // Register info search order:
584 // 1 - Use the target definition python file if one is specified.
585 // 2 - If the target definition doesn't have any of the info from the target.xml (registers) then proceed to read the target.xml.
586 // 3 - Fall back on the qRegisterInfo packets.
587
588 FileSpec target_definition_fspec = GetGlobalPluginProperties()->GetTargetDefinitionFile ();
Jason Molenda91e468c2015-08-20 04:29:46 +0000589 if (!target_definition_fspec.Exists())
590 {
591 // If the filename doesn't exist, it may be a ~ not having been expanded - try to resolve it.
592 target_definition_fspec.ResolvePath();
593 }
Ewan Crawford0c996a92015-06-30 13:08:44 +0000594 if (target_definition_fspec)
595 {
596 // See if we can get register definitions from a python file
597 if (ParsePythonTargetDefinition (target_definition_fspec))
Jason Molenda5543abb2015-08-20 03:05:09 +0000598 {
Ewan Crawford0c996a92015-06-30 13:08:44 +0000599 return;
Jason Molenda5543abb2015-08-20 03:05:09 +0000600 }
601 else
602 {
603 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
604 stream_sp->Printf ("ERROR: target description file %s failed to parse.\n", target_definition_fspec.GetPath().c_str());
605 }
Ewan Crawford0c996a92015-06-30 13:08:44 +0000606 }
607
Greg Claytond04f0ed2015-05-26 18:00:51 +0000608 if (GetGDBServerRegisterInfo ())
609 return;
610
611 char packet[128];
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000612 uint32_t reg_offset = 0;
613 uint32_t reg_num = 0;
Greg Clayton23f59502012-07-17 03:23:13 +0000614 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Greg Clayton576d8832011-03-22 04:00:09 +0000615 response_type == StringExtractorGDBRemote::eResponse;
616 ++reg_num)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000617 {
Greg Clayton513c26c2011-01-29 07:10:55 +0000618 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
Andy Gibbsa297a972013-06-19 19:04:53 +0000619 assert (packet_len < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000620 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000621 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000622 {
Greg Clayton576d8832011-03-22 04:00:09 +0000623 response_type = response.GetResponseType();
624 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000625 {
626 std::string name;
627 std::string value;
628 ConstString reg_name;
629 ConstString alt_name;
630 ConstString set_name;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000631 std::vector<uint32_t> value_regs;
632 std::vector<uint32_t> invalidate_regs;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000633 RegisterInfo reg_info = { NULL, // Name
634 NULL, // Alt name
635 0, // byte size
636 reg_offset, // offset
637 eEncodingUint, // encoding
Jason Molendabf67a302015-09-01 05:17:01 +0000638 eFormatHex, // format
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000639 {
Jason Molendabf67a302015-09-01 05:17:01 +0000640 LLDB_INVALID_REGNUM, // eh_frame reg num
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000641 LLDB_INVALID_REGNUM, // DWARF reg num
642 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda63bd0db2015-09-15 23:20:34 +0000643 reg_num, // process plugin reg num
Jason Molendafbcb7f22010-09-10 07:49:16 +0000644 reg_num // native register number
Greg Clayton435d85a2012-02-29 19:27:27 +0000645 },
646 NULL,
647 NULL
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000648 };
649
650 while (response.GetNameColonValue(name, value))
651 {
652 if (name.compare("name") == 0)
653 {
654 reg_name.SetCString(value.c_str());
655 }
656 else if (name.compare("alt-name") == 0)
657 {
658 alt_name.SetCString(value.c_str());
659 }
660 else if (name.compare("bitsize") == 0)
661 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000662 reg_info.byte_size = StringConvert::ToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000663 }
664 else if (name.compare("offset") == 0)
665 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000666 uint32_t offset = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda743e86a2010-06-11 23:44:18 +0000667 if (reg_offset != offset)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000668 {
669 reg_offset = offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000670 }
671 }
672 else if (name.compare("encoding") == 0)
673 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000674 const Encoding encoding = Args::StringToEncoding (value.c_str());
675 if (encoding != eEncodingInvalid)
676 reg_info.encoding = encoding;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000677 }
678 else if (name.compare("format") == 0)
679 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000680 Format format = eFormatInvalid;
681 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
682 reg_info.format = format;
683 else if (value.compare("binary") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000684 reg_info.format = eFormatBinary;
685 else if (value.compare("decimal") == 0)
686 reg_info.format = eFormatDecimal;
687 else if (value.compare("hex") == 0)
688 reg_info.format = eFormatHex;
689 else if (value.compare("float") == 0)
690 reg_info.format = eFormatFloat;
691 else if (value.compare("vector-sint8") == 0)
692 reg_info.format = eFormatVectorOfSInt8;
693 else if (value.compare("vector-uint8") == 0)
694 reg_info.format = eFormatVectorOfUInt8;
695 else if (value.compare("vector-sint16") == 0)
696 reg_info.format = eFormatVectorOfSInt16;
697 else if (value.compare("vector-uint16") == 0)
698 reg_info.format = eFormatVectorOfUInt16;
699 else if (value.compare("vector-sint32") == 0)
700 reg_info.format = eFormatVectorOfSInt32;
701 else if (value.compare("vector-uint32") == 0)
702 reg_info.format = eFormatVectorOfUInt32;
703 else if (value.compare("vector-float32") == 0)
704 reg_info.format = eFormatVectorOfFloat32;
705 else if (value.compare("vector-uint128") == 0)
706 reg_info.format = eFormatVectorOfUInt128;
707 }
708 else if (name.compare("set") == 0)
709 {
710 set_name.SetCString(value.c_str());
711 }
Jason Molendaa18f7072015-08-15 01:21:01 +0000712 else if (name.compare("gcc") == 0 || name.compare("ehframe") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000713 {
Jason Molendaa18f7072015-08-15 01:21:01 +0000714 reg_info.kinds[eRegisterKindEHFrame] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000715 }
716 else if (name.compare("dwarf") == 0)
717 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000718 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000719 }
720 else if (name.compare("generic") == 0)
721 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000722 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000723 }
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000724 else if (name.compare("container-regs") == 0)
725 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000726 SplitCommaSeparatedRegisterNumberString(value, value_regs, 16);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000727 }
728 else if (name.compare("invalidate-regs") == 0)
729 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000730 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 16);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000731 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000732 }
733
Jason Molenda743e86a2010-06-11 23:44:18 +0000734 reg_info.byte_offset = reg_offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000735 assert (reg_info.byte_size != 0);
736 reg_offset += reg_info.byte_size;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000737 if (!value_regs.empty())
738 {
739 value_regs.push_back(LLDB_INVALID_REGNUM);
740 reg_info.value_regs = value_regs.data();
741 }
742 if (!invalidate_regs.empty())
743 {
744 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
745 reg_info.invalidate_regs = invalidate_regs.data();
746 }
747
Jason Molenda21586c82015-09-09 03:36:24 +0000748 AugmentRegisterInfoViaABI (reg_info, reg_name, GetABI ());
749
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000750 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
751 }
Todd Fiala1a634402014-01-08 07:52:40 +0000752 else
753 {
754 break; // ensure exit before reg_num is incremented
755 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000756 }
757 else
758 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000759 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000760 }
761 }
762
Greg Claytond04f0ed2015-05-26 18:00:51 +0000763 if (m_register_info.GetNumRegisters() > 0)
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000764 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000765 m_register_info.Finalize(GetTarget().GetArchitecture());
766 return;
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000767 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000768
Johnny Chen2fa9de12012-05-14 18:44:23 +0000769 // We didn't get anything if the accumulated reg_num is zero. See if we are
770 // debugging ARM and fill with a hard coded register set until we can get an
771 // updated debugserver down on the devices.
772 // On the other hand, if the accumulated reg_num is positive, see if we can
773 // add composite registers to the existing primordial ones.
Greg Claytond04f0ed2015-05-26 18:00:51 +0000774 bool from_scratch = (m_register_info.GetNumRegisters() == 0);
Johnny Chen2fa9de12012-05-14 18:44:23 +0000775
776 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000777 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
778 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
779
780 // Use the process' architecture instead of the host arch, if available
781 ArchSpec remote_arch;
782 if (remote_process_arch.IsValid ())
783 remote_arch = remote_process_arch;
784 else
785 remote_arch = remote_host_arch;
786
Johnny Chen2fa9de12012-05-14 18:44:23 +0000787 if (!target_arch.IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000788 {
Johnny Chen2fa9de12012-05-14 18:44:23 +0000789 if (remote_arch.IsValid()
Jason Molenda6d9fe8c2015-08-21 00:13:37 +0000790 && (remote_arch.GetMachine() == llvm::Triple::arm || remote_arch.GetMachine() == llvm::Triple::thumb)
Johnny Chen2fa9de12012-05-14 18:44:23 +0000791 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
792 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000793 }
Jason Molenda6d9fe8c2015-08-21 00:13:37 +0000794 else if (target_arch.GetMachine() == llvm::Triple::arm
795 || target_arch.GetMachine() == llvm::Triple::thumb)
Johnny Chen2fa9de12012-05-14 18:44:23 +0000796 {
797 m_register_info.HardcodeARMRegisters(from_scratch);
798 }
799
800 // At this point, we can finalize our register info.
Greg Claytond04f0ed2015-05-26 18:00:51 +0000801 m_register_info.Finalize (GetTarget().GetArchitecture());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000802}
803
804Error
805ProcessGDBRemote::WillLaunch (Module* module)
806{
807 return WillLaunchOrAttach ();
808}
809
810Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000811ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000812{
813 return WillLaunchOrAttach ();
814}
815
816Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000817ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000818{
819 return WillLaunchOrAttach ();
820}
821
822Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000823ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +0000824{
Todd Fialaaf245d12014-06-30 21:05:18 +0000825 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Claytonb766a732011-02-04 01:58:07 +0000826 Error error (WillLaunchOrAttach ());
827
828 if (error.Fail())
829 return error;
830
Greg Clayton2289fa42011-04-30 01:09:13 +0000831 error = ConnectToDebugserver (remote_url);
Greg Claytonb766a732011-02-04 01:58:07 +0000832
833 if (error.Fail())
834 return error;
835 StartAsyncThread ();
836
Greg Claytonc574ede2011-03-10 02:26:48 +0000837 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonb766a732011-02-04 01:58:07 +0000838 if (pid == LLDB_INVALID_PROCESS_ID)
839 {
840 // We don't have a valid process ID, so note that we are connected
841 // and could now request to launch or attach, or get remote process
842 // listings...
843 SetPrivateState (eStateConnected);
844 }
845 else
846 {
847 // We have a valid process
848 SetID (pid);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000849 GetThreadList();
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000850 StringExtractorGDBRemote response;
851 if (m_gdb_comm.GetStopReply(response))
Greg Claytonb766a732011-02-04 01:58:07 +0000852 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000853 SetLastStopPacket(response);
Ewan Crawford78baa192015-05-13 09:18:18 +0000854
855 // '?' Packets must be handled differently in non-stop mode
856 if (GetTarget().GetNonStopModeEnabled())
857 HandleStopReplySequence();
858
Zachary Turner7529df92015-09-01 20:02:29 +0000859 Target &target = GetTarget();
860 if (!target.GetArchitecture().IsValid())
Jason Molendac62bd7b2013-12-21 05:20:36 +0000861 {
862 if (m_gdb_comm.GetProcessArchitecture().IsValid())
863 {
Zachary Turner7529df92015-09-01 20:02:29 +0000864 target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
Jason Molendac62bd7b2013-12-21 05:20:36 +0000865 }
866 else
867 {
Zachary Turner7529df92015-09-01 20:02:29 +0000868 target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molendac62bd7b2013-12-21 05:20:36 +0000869 }
Carlo Kok74389122013-10-14 07:09:13 +0000870 }
871
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000872 const StateType state = SetThreadStopInfo (response);
Greg Clayton2e309072015-07-17 23:42:28 +0000873 if (state != eStateInvalid)
Greg Claytonb766a732011-02-04 01:58:07 +0000874 {
875 SetPrivateState (state);
876 }
877 else
Daniel Malead01b2952012-11-29 21:49:15 +0000878 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 +0000879 }
880 else
Daniel Malead01b2952012-11-29 21:49:15 +0000881 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 +0000882 }
Jason Molenda16d127c2012-05-03 22:37:30 +0000883
Todd Fialaaf245d12014-06-30 21:05:18 +0000884 if (log)
885 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");
886
887
888 if (error.Success()
Jason Molenda16d127c2012-05-03 22:37:30 +0000889 && !GetTarget().GetArchitecture().IsValid()
890 && m_gdb_comm.GetHostArchitecture().IsValid())
891 {
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000892 // Prefer the *process'* architecture over that of the *host*, if available.
893 if (m_gdb_comm.GetProcessArchitecture().IsValid())
894 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
895 else
896 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molenda16d127c2012-05-03 22:37:30 +0000897 }
898
Todd Fialaaf245d12014-06-30 21:05:18 +0000899 if (log)
900 log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": normalized target architecture triple: %s", __FUNCTION__, GetID (), GetTarget ().GetArchitecture ().GetTriple ().getTriple ().c_str ());
901
Chaoren Lin98d0a4b2015-07-14 01:09:28 +0000902 if (error.Success())
Jaydeep Patil6fc590d2015-07-30 05:06:51 +0000903 {
904 PlatformSP platform_sp = GetTarget().GetPlatform();
905 if (platform_sp && platform_sp->IsConnected())
906 SetUnixSignals(platform_sp->GetUnixSignals());
907 else
908 SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
909 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000910
Greg Claytonb766a732011-02-04 01:58:07 +0000911 return error;
912}
913
914Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000915ProcessGDBRemote::WillLaunchOrAttach ()
916{
917 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000918 m_stdio_communication.Clear ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000919 return error;
920}
921
922//----------------------------------------------------------------------
923// Process Control
924//----------------------------------------------------------------------
925Error
Jean-Daniel Dupas7782de92013-12-09 22:52:50 +0000926ProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000927{
Todd Fiala75f47c32014-10-11 21:42:09 +0000928 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton4957bf62010-09-30 21:49:03 +0000929 Error error;
Greg Clayton982c9762011-11-03 21:22:33 +0000930
Todd Fiala75f47c32014-10-11 21:42:09 +0000931 if (log)
932 log->Printf ("ProcessGDBRemote::%s() entered", __FUNCTION__);
933
Greg Clayton982c9762011-11-03 21:22:33 +0000934 uint32_t launch_flags = launch_info.GetFlags().Get();
Chaoren Lind3173f32015-05-29 19:52:29 +0000935 FileSpec stdin_file_spec{};
936 FileSpec stdout_file_spec{};
937 FileSpec stderr_file_spec{};
938 FileSpec working_dir = launch_info.GetWorkingDirectory();
Greg Clayton982c9762011-11-03 21:22:33 +0000939
Zachary Turner696b5282014-08-14 16:01:25 +0000940 const FileAction *file_action;
Greg Clayton982c9762011-11-03 21:22:33 +0000941 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
942 if (file_action)
943 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000944 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000945 stdin_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000946 }
947 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
948 if (file_action)
949 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000950 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000951 stdout_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000952 }
953 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
954 if (file_action)
955 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000956 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000957 stderr_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000958 }
959
Todd Fiala75f47c32014-10-11 21:42:09 +0000960 if (log)
961 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000962 if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
Vince Harron4a8abd32015-02-13 19:15:24 +0000963 log->Printf ("ProcessGDBRemote::%s provided with STDIO paths via launch_info: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000964 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000965 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
966 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
967 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Todd Fiala75f47c32014-10-11 21:42:09 +0000968 else
969 log->Printf ("ProcessGDBRemote::%s no STDIO paths given via launch_info", __FUNCTION__);
970 }
971
Vince Harrondf3f00f2015-02-10 21:09:04 +0000972 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Chaoren Lind3173f32015-05-29 19:52:29 +0000973 if (stdin_file_spec || disable_stdio)
Vince Harrondf3f00f2015-02-10 21:09:04 +0000974 {
975 // the inferior will be reading stdin from the specified file
976 // or stdio is completely disabled
977 m_stdin_forward = false;
978 }
979 else
980 {
981 m_stdin_forward = true;
982 }
983
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000984 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
985 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
986 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000987
Greg Clayton982c9762011-11-03 21:22:33 +0000988 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000989 if (object_file)
990 {
Greg Clayton71337622011-02-24 22:24:29 +0000991 // Make sure we aren't already connected?
992 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000993 {
Greg Clayton91a9b2472013-12-04 19:19:12 +0000994 error = LaunchAndConnectToDebugserver (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000995 }
996
997 if (error.Success())
998 {
999 lldb_utility::PseudoTerminal pty;
1000 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Clayton5f2a4f92011-03-02 21:34:46 +00001001
Zachary Turner7529df92015-09-01 20:02:29 +00001002 PlatformSP platform_sp (GetTarget().GetPlatform());
Vince Harrondf3f00f2015-02-10 21:09:04 +00001003 if (disable_stdio)
Greg Clayton71337622011-02-24 22:24:29 +00001004 {
Vince Harrondf3f00f2015-02-10 21:09:04 +00001005 // set to /dev/null unless redirected to a file above
Chaoren Lind3173f32015-05-29 19:52:29 +00001006 if (!stdin_file_spec)
1007 stdin_file_spec.SetFile("/dev/null", false);
1008 if (!stdout_file_spec)
1009 stdout_file_spec.SetFile("/dev/null", false);
1010 if (!stderr_file_spec)
1011 stderr_file_spec.SetFile("/dev/null", false);
Vince Harrondf3f00f2015-02-10 21:09:04 +00001012 }
1013 else if (platform_sp && platform_sp->IsHost())
1014 {
1015 // If the debugserver is local and we aren't disabling STDIO, lets use
1016 // a pseudo terminal to instead of relying on the 'O' packets for stdio
1017 // since 'O' packets can really slow down debugging if the inferior
1018 // does a lot of output.
Chaoren Lind3173f32015-05-29 19:52:29 +00001019 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
1020 pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001021 {
Chaoren Lind3173f32015-05-29 19:52:29 +00001022 FileSpec slave_name{pty.GetSlaveName(NULL, 0), false};
1023
1024 if (!stdin_file_spec)
1025 stdin_file_spec = slave_name;
1026
1027 if (!stdout_file_spec)
1028 stdout_file_spec = slave_name;
1029
1030 if (!stderr_file_spec)
1031 stderr_file_spec = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001032 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001033 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +00001034 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 +00001035 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +00001036 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
1037 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
1038 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Greg Clayton71337622011-02-24 22:24:29 +00001039 }
1040
Todd Fiala75f47c32014-10-11 21:42:09 +00001041 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +00001042 log->Printf ("ProcessGDBRemote::%s final STDIO paths after all adjustments: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +00001043 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +00001044 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
1045 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
1046 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Todd Fiala75f47c32014-10-11 21:42:09 +00001047
Chaoren Lind3173f32015-05-29 19:52:29 +00001048 if (stdin_file_spec)
1049 m_gdb_comm.SetSTDIN(stdin_file_spec);
1050 if (stdout_file_spec)
1051 m_gdb_comm.SetSTDOUT(stdout_file_spec);
1052 if (stderr_file_spec)
1053 m_gdb_comm.SetSTDERR(stderr_file_spec);
Greg Clayton71337622011-02-24 22:24:29 +00001054
1055 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
Jim Ingham106d0282014-06-25 02:32:56 +00001056 m_gdb_comm.SetDetachOnError (launch_flags & eLaunchFlagDetachOnError);
Greg Clayton71337622011-02-24 22:24:29 +00001057
Zachary Turner7529df92015-09-01 20:02:29 +00001058 m_gdb_comm.SendLaunchArchPacket (GetTarget().GetArchitecture().GetArchitectureName());
Greg Clayton71337622011-02-24 22:24:29 +00001059
Jason Molendaa3329782014-03-29 18:54:20 +00001060 const char * launch_event_data = launch_info.GetLaunchEventData();
1061 if (launch_event_data != NULL && *launch_event_data != '\0')
1062 m_gdb_comm.SendLaunchEventDataPacket (launch_event_data);
1063
Chaoren Lind3173f32015-05-29 19:52:29 +00001064 if (working_dir)
Greg Clayton71337622011-02-24 22:24:29 +00001065 {
1066 m_gdb_comm.SetWorkingDir (working_dir);
1067 }
1068
1069 // Send the environment and the program + arguments after we connect
Greg Clayton982c9762011-11-03 21:22:33 +00001070 const Args &environment = launch_info.GetEnvironmentEntries();
1071 if (environment.GetArgumentCount())
Greg Clayton71337622011-02-24 22:24:29 +00001072 {
Greg Clayton982c9762011-11-03 21:22:33 +00001073 size_t num_environment_entries = environment.GetArgumentCount();
1074 for (size_t i=0; i<num_environment_entries; ++i)
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001075 {
Greg Clayton982c9762011-11-03 21:22:33 +00001076 const char *env_entry = environment.GetArgumentAtIndex(i);
1077 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Clayton71337622011-02-24 22:24:29 +00001078 break;
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001079 }
Greg Clayton71337622011-02-24 22:24:29 +00001080 }
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001081
Greg Clayton71337622011-02-24 22:24:29 +00001082 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001083 // Scope for the scoped timeout object
1084 GDBRemoteCommunication::ScopedTimeout timeout (m_gdb_comm, 10);
1085
1086 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
1087 if (arg_packet_err == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001088 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001089 std::string error_str;
1090 if (m_gdb_comm.GetLaunchSuccess (error_str))
1091 {
1092 SetID (m_gdb_comm.GetCurrentProcessID ());
1093 }
1094 else
1095 {
1096 error.SetErrorString (error_str.c_str());
1097 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001098 }
1099 else
1100 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001101 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001102 }
Greg Clayton71337622011-02-24 22:24:29 +00001103 }
Tamas Berghammer912800c2015-02-24 10:23:39 +00001104
Greg Clayton71337622011-02-24 22:24:29 +00001105 if (GetID() == LLDB_INVALID_PROCESS_ID)
1106 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001107 if (log)
1108 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton71337622011-02-24 22:24:29 +00001109 KillDebugserverProcess ();
1110 return error;
1111 }
1112
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001113 StringExtractorGDBRemote response;
1114 if (m_gdb_comm.GetStopReply(response))
Greg Clayton71337622011-02-24 22:24:29 +00001115 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001116 SetLastStopPacket(response);
Ewan Crawford78baa192015-05-13 09:18:18 +00001117 // '?' Packets must be handled differently in non-stop mode
1118 if (GetTarget().GetNonStopModeEnabled())
1119 HandleStopReplySequence();
1120
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001121 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
1122
1123 if (process_arch.IsValid())
Jason Molendac62bd7b2013-12-21 05:20:36 +00001124 {
Zachary Turner7529df92015-09-01 20:02:29 +00001125 GetTarget().MergeArchitecture(process_arch);
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001126 }
1127 else
1128 {
1129 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
1130 if (host_arch.IsValid())
Zachary Turner7529df92015-09-01 20:02:29 +00001131 GetTarget().MergeArchitecture(host_arch);
Carlo Kok74389122013-10-14 07:09:13 +00001132 }
1133
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001134 SetPrivateState (SetThreadStopInfo (response));
Greg Clayton71337622011-02-24 22:24:29 +00001135
1136 if (!disable_stdio)
1137 {
1138 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Claytonee95ed52011-11-17 22:14:31 +00001139 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Clayton71337622011-02-24 22:24:29 +00001140 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001141 }
1142 }
Greg Claytonc235ac72011-08-09 05:20:29 +00001143 else
1144 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001145 if (log)
1146 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytonc235ac72011-08-09 05:20:29 +00001147 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001148 }
1149 else
1150 {
1151 // Set our user ID to an invalid process ID.
1152 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton982c9762011-11-03 21:22:33 +00001153 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
1154 exe_module->GetFileSpec().GetFilename().AsCString(),
1155 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001156 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001157 return error;
Greg Clayton4957bf62010-09-30 21:49:03 +00001158
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001159}
1160
1161
1162Error
Greg Claytonb766a732011-02-04 01:58:07 +00001163ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001164{
1165 Error error;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001166 // Only connect if we have a valid connect URL
Vince Harron1b5a74e2015-01-21 22:42:49 +00001167 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton00fe87b2013-12-05 22:58:22 +00001168
1169 if (connect_url && connect_url[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001170 {
Vince Harron1b5a74e2015-01-21 22:42:49 +00001171 if (log)
1172 log->Printf("ProcessGDBRemote::%s Connecting to %s", __FUNCTION__, connect_url);
Greg Clayton00fe87b2013-12-05 22:58:22 +00001173 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
1174 if (conn_ap.get())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001175 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001176 const uint32_t max_retry_count = 50;
1177 uint32_t retry_count = 0;
1178 while (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001179 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001180 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
1181 {
1182 m_gdb_comm.SetConnection (conn_ap.release());
1183 break;
1184 }
1185 else if (error.WasInterrupted())
1186 {
1187 // If we were interrupted, don't keep retrying.
1188 break;
1189 }
1190
1191 retry_count++;
1192
1193 if (retry_count >= max_retry_count)
1194 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001195
Greg Clayton00fe87b2013-12-05 22:58:22 +00001196 usleep (100000);
1197 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001198 }
1199 }
1200
1201 if (!m_gdb_comm.IsConnected())
1202 {
1203 if (error.Success())
1204 error.SetErrorString("not connected to remote gdb server");
1205 return error;
1206 }
1207
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001208
1209 // Start the communications read thread so all incoming data can be
1210 // parsed into packets and queued as they arrive.
1211 if (GetTarget().GetNonStopModeEnabled())
1212 m_gdb_comm.StartReadThread();
1213
Greg Clayton32e0a752011-03-30 18:16:51 +00001214 // We always seem to be able to open a connection to a local port
1215 // so we need to make sure we can then send data to it. If we can't
1216 // then we aren't actually connected to anything, so try and do the
1217 // handshake with the remote GDB server and make sure that goes
1218 // alright.
Greg Claytonfb909312013-11-23 01:58:15 +00001219 if (!m_gdb_comm.HandshakeWithServer (&error))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001220 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001221 m_gdb_comm.Disconnect();
1222 if (error.Success())
1223 error.SetErrorString("not connected to remote gdb server");
1224 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001225 }
Ewan Crawford78baa192015-05-13 09:18:18 +00001226
1227 // Send $QNonStop:1 packet on startup if required
1228 if (GetTarget().GetNonStopModeEnabled())
Ewan Crawfordaa7eda72015-06-24 15:14:26 +00001229 GetTarget().SetNonStopModeEnabled (m_gdb_comm.SetNonStopMode(true));
Ewan Crawford78baa192015-05-13 09:18:18 +00001230
Greg Claytonb30c50c2015-05-29 00:01:55 +00001231 m_gdb_comm.GetEchoSupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001232 m_gdb_comm.GetThreadSuffixSupported ();
Greg Clayton44633992012-04-10 03:22:03 +00001233 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001234 m_gdb_comm.GetHostInfo ();
1235 m_gdb_comm.GetVContSupported ('c');
Jim Inghamcd16df92012-07-20 21:37:13 +00001236 m_gdb_comm.GetVAttachOrWaitSupported();
Ewan Crawford78baa192015-05-13 09:18:18 +00001237
1238 // Ask the remote server for the default thread id
1239 if (GetTarget().GetNonStopModeEnabled())
1240 m_gdb_comm.GetDefaultThreadId(m_initial_tid);
1241
1242
Jim Ingham03afad82012-07-02 05:40:07 +00001243 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1244 for (size_t idx = 0; idx < num_cmds; idx++)
1245 {
1246 StringExtractorGDBRemote response;
Jim Ingham03afad82012-07-02 05:40:07 +00001247 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1248 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001249 return error;
1250}
1251
1252void
Jim Inghambb006ce2014-08-02 00:33:35 +00001253ProcessGDBRemote::DidLaunchOrAttach (ArchSpec& process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001254{
Greg Clayton5160ce52013-03-27 23:08:40 +00001255 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001256 if (log)
1257 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton93d3c8332011-02-16 04:46:07 +00001258 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001259 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001260 BuildDynamicRegisterInfo (false);
Greg Clayton3af9ea52010-11-18 05:57:03 +00001261
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001262 // See if the GDB server supports the qHostInfo information
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001263
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001264
1265 // See if the GDB server supports the qProcessInfo packet, if so
1266 // prefer that over the Host information as it will be more specific
1267 // to our process.
1268
Todd Fiala75f47c32014-10-11 21:42:09 +00001269 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1270 if (remote_process_arch.IsValid())
1271 {
1272 process_arch = remote_process_arch;
1273 if (log)
1274 log->Printf ("ProcessGDBRemote::%s gdb-remote had process architecture, using %s %s",
1275 __FUNCTION__,
1276 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1277 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1278 }
Jim Inghambb006ce2014-08-02 00:33:35 +00001279 else
Todd Fiala75f47c32014-10-11 21:42:09 +00001280 {
Jim Inghambb006ce2014-08-02 00:33:35 +00001281 process_arch = m_gdb_comm.GetHostArchitecture();
Todd Fiala75f47c32014-10-11 21:42:09 +00001282 if (log)
1283 log->Printf ("ProcessGDBRemote::%s gdb-remote did not have process architecture, using gdb-remote host architecture %s %s",
1284 __FUNCTION__,
1285 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1286 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1287 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001288
Jim Inghambb006ce2014-08-02 00:33:35 +00001289 if (process_arch.IsValid())
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001290 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001291 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Greg Claytond314e812011-03-23 00:09:55 +00001292 if (target_arch.IsValid())
1293 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001294 if (log)
1295 log->Printf ("ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1296 __FUNCTION__,
1297 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1298 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
1299
1300 // If the remote host is ARM and we have apple as the vendor, then
Greg Claytond314e812011-03-23 00:09:55 +00001301 // ARM executables and shared libraries can have mixed ARM architectures.
1302 // You can have an armv6 executable, and if the host is armv7, then the
1303 // system will load the best possible architecture for all shared libraries
1304 // it has, so we really need to take the remote host architecture as our
1305 // defacto architecture in this case.
1306
Jason Molenda6d9fe8c2015-08-21 00:13:37 +00001307 if ((process_arch.GetMachine() == llvm::Triple::arm || process_arch.GetMachine() == llvm::Triple::thumb)
1308 && process_arch.GetTriple().getVendor() == llvm::Triple::Apple)
Greg Claytond314e812011-03-23 00:09:55 +00001309 {
Jason Molenda921c01b2014-08-03 21:42:52 +00001310 GetTarget().SetArchitecture (process_arch);
Todd Fiala75f47c32014-10-11 21:42:09 +00001311 if (log)
1312 log->Printf ("ProcessGDBRemote::%s remote process is ARM/Apple, setting target arch to %s %s",
1313 __FUNCTION__,
1314 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1315 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001316 }
1317 else
1318 {
1319 // Fill in what is missing in the triple
Jim Inghambb006ce2014-08-02 00:33:35 +00001320 const llvm::Triple &remote_triple = process_arch.GetTriple();
Tamas Berghammere724af12015-03-13 10:32:37 +00001321 llvm::Triple new_target_triple = target_arch.GetTriple();
1322 if (new_target_triple.getVendorName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001323 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001324 new_target_triple.setVendor (remote_triple.getVendor());
Greg Claytond314e812011-03-23 00:09:55 +00001325
Tamas Berghammere724af12015-03-13 10:32:37 +00001326 if (new_target_triple.getOSName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001327 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001328 new_target_triple.setOS (remote_triple.getOS());
Greg Claytond314e812011-03-23 00:09:55 +00001329
Tamas Berghammere724af12015-03-13 10:32:37 +00001330 if (new_target_triple.getEnvironmentName().size() == 0)
1331 new_target_triple.setEnvironment (remote_triple.getEnvironment());
Greg Clayton70b57652011-05-15 01:25:55 +00001332 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001333
Tamas Berghammere724af12015-03-13 10:32:37 +00001334 ArchSpec new_target_arch = target_arch;
1335 new_target_arch.SetTriple(new_target_triple);
1336 GetTarget().SetArchitecture(new_target_arch);
1337 }
Greg Claytond314e812011-03-23 00:09:55 +00001338 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001339
1340 if (log)
1341 log->Printf ("ProcessGDBRemote::%s final target arch after adjustments for remote architecture: %s %s",
1342 __FUNCTION__,
1343 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1344 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001345 }
1346 else
1347 {
1348 // The target doesn't have a valid architecture yet, set it from
1349 // the architecture we got from the remote GDB server
Jason Molenda921c01b2014-08-03 21:42:52 +00001350 GetTarget().SetArchitecture (process_arch);
Greg Claytond314e812011-03-23 00:09:55 +00001351 }
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001352 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001353 }
1354}
1355
1356void
1357ProcessGDBRemote::DidLaunch ()
1358{
Jim Inghambb006ce2014-08-02 00:33:35 +00001359 ArchSpec process_arch;
1360 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001361}
1362
1363Error
Han Ming Ong84647042012-02-25 01:07:38 +00001364ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1365{
Todd Fiala75f47c32014-10-11 21:42:09 +00001366 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001367 Error error;
Todd Fiala75f47c32014-10-11 21:42:09 +00001368
1369 if (log)
1370 log->Printf ("ProcessGDBRemote::%s()", __FUNCTION__);
1371
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001372 // Clear out and clean up from any current state
1373 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001374 if (attach_pid != LLDB_INVALID_PROCESS_ID)
1375 {
Greg Clayton71337622011-02-24 22:24:29 +00001376 // Make sure we aren't already connected?
1377 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001378 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001379 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001380
1381 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001382 {
Greg Clayton71337622011-02-24 22:24:29 +00001383 const char *error_string = error.AsCString();
1384 if (error_string == NULL)
1385 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1386
1387 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001388 }
Greg Clayton71337622011-02-24 22:24:29 +00001389 }
1390
1391 if (error.Success())
1392 {
Jim Ingham106d0282014-06-25 02:32:56 +00001393 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
Todd Fiala75f47c32014-10-11 21:42:09 +00001394
Greg Clayton71337622011-02-24 22:24:29 +00001395 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001396 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Greg Clayton3b608422011-11-19 02:11:30 +00001397 SetID (attach_pid);
Greg Clayton71337622011-02-24 22:24:29 +00001398 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001399 }
1400 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001401
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001402 return error;
1403}
1404
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001405Error
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001406ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001407{
1408 Error error;
1409 // Clear out and clean up from any current state
1410 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001411
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001412 if (process_name && process_name[0])
1413 {
Greg Clayton71337622011-02-24 22:24:29 +00001414 // Make sure we aren't already connected?
1415 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001416 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001417 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001418
Greg Clayton71337622011-02-24 22:24:29 +00001419 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001420 {
Greg Clayton71337622011-02-24 22:24:29 +00001421 const char *error_string = error.AsCString();
1422 if (error_string == NULL)
1423 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001424
Greg Clayton71337622011-02-24 22:24:29 +00001425 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001426 }
Greg Clayton71337622011-02-24 22:24:29 +00001427 }
1428
1429 if (error.Success())
1430 {
1431 StreamString packet;
1432
Jim Ingham106d0282014-06-25 02:32:56 +00001433 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1434
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001435 if (attach_info.GetWaitForLaunch())
Jim Inghamcd16df92012-07-20 21:37:13 +00001436 {
1437 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1438 {
1439 packet.PutCString ("vAttachWait");
1440 }
1441 else
1442 {
1443 if (attach_info.GetIgnoreExisting())
1444 packet.PutCString("vAttachWait");
1445 else
1446 packet.PutCString ("vAttachOrWait");
1447 }
1448 }
Greg Clayton71337622011-02-24 22:24:29 +00001449 else
1450 packet.PutCString("vAttachName");
1451 packet.PutChar(';');
1452 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1453
1454 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1455
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001456 }
1457 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001458 return error;
1459}
1460
Greg Clayton5df78fa2015-05-23 03:54:53 +00001461void
1462ProcessGDBRemote::DidExit ()
Greg Claytonfbb76342013-11-20 21:07:01 +00001463{
Greg Clayton5df78fa2015-05-23 03:54:53 +00001464 // When we exit, disconnect from the GDB server communications
Greg Claytonfbb76342013-11-20 21:07:01 +00001465 m_gdb_comm.Disconnect();
Greg Claytonfbb76342013-11-20 21:07:01 +00001466}
1467
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001468void
Jim Inghambb006ce2014-08-02 00:33:35 +00001469ProcessGDBRemote::DidAttach (ArchSpec &process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001470{
Jim Inghambb006ce2014-08-02 00:33:35 +00001471 // If you can figure out what the architecture is, fill it in here.
1472 process_arch.Clear();
1473 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001474}
1475
Greg Clayton90ba8112012-12-05 00:16:59 +00001476
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001477Error
1478ProcessGDBRemote::WillResume ()
1479{
Greg Clayton71fc2a32011-02-12 06:28:37 +00001480 m_continue_c_tids.clear();
1481 m_continue_C_tids.clear();
1482 m_continue_s_tids.clear();
1483 m_continue_S_tids.clear();
Greg Clayton2e309072015-07-17 23:42:28 +00001484 m_jstopinfo_sp.reset();
1485 m_jthreadsinfo_sp.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001486 return Error();
1487}
1488
1489Error
1490ProcessGDBRemote::DoResume ()
1491{
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001492 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001493 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001494 if (log)
1495 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytone5219662010-12-03 06:02:24 +00001496
1497 Listener listener ("gdb-remote.resume-packet-sent");
1498 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1499 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00001500 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1501
Greg Claytond1d06e42013-04-20 00:27:58 +00001502 const size_t num_threads = GetThreadList().GetSize();
1503
Greg Clayton71fc2a32011-02-12 06:28:37 +00001504 StreamString continue_packet;
1505 bool continue_packet_error = false;
1506 if (m_gdb_comm.HasAnyVContSupport ())
1507 {
Ewan Crawford78baa192015-05-13 09:18:18 +00001508 if (!GetTarget().GetNonStopModeEnabled() &&
1509 (m_continue_c_tids.size() == num_threads ||
Greg Claytone98008c2014-02-13 23:34:38 +00001510 (m_continue_c_tids.empty() &&
1511 m_continue_C_tids.empty() &&
1512 m_continue_s_tids.empty() &&
Ewan Crawford78baa192015-05-13 09:18:18 +00001513 m_continue_S_tids.empty())))
Greg Clayton71fc2a32011-02-12 06:28:37 +00001514 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001515 // All threads are continuing, just send a "c" packet
1516 continue_packet.PutCString ("c");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001517 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001518 else
1519 {
1520 continue_packet.PutCString ("vCont");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001521
Greg Claytond1d06e42013-04-20 00:27:58 +00001522 if (!m_continue_c_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001523 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001524 if (m_gdb_comm.GetVContSupported ('c'))
1525 {
1526 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)
1527 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1528 }
1529 else
1530 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001531 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001532
1533 if (!continue_packet_error && !m_continue_C_tids.empty())
1534 {
1535 if (m_gdb_comm.GetVContSupported ('C'))
1536 {
1537 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)
1538 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1539 }
1540 else
1541 continue_packet_error = true;
1542 }
Greg Claytone5219662010-12-03 06:02:24 +00001543
Greg Claytond1d06e42013-04-20 00:27:58 +00001544 if (!continue_packet_error && !m_continue_s_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001545 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001546 if (m_gdb_comm.GetVContSupported ('s'))
1547 {
1548 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)
1549 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1550 }
1551 else
1552 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001553 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001554
1555 if (!continue_packet_error && !m_continue_S_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001556 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001557 if (m_gdb_comm.GetVContSupported ('S'))
1558 {
1559 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)
1560 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1561 }
1562 else
1563 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001564 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001565
1566 if (continue_packet_error)
1567 continue_packet.GetString().clear();
Greg Clayton71fc2a32011-02-12 06:28:37 +00001568 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001569 }
1570 else
1571 continue_packet_error = true;
1572
1573 if (continue_packet_error)
1574 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001575 // Either no vCont support, or we tried to use part of the vCont
1576 // packet that wasn't supported by the remote GDB server.
1577 // We need to try and make a simple packet that can do our continue
Greg Clayton71fc2a32011-02-12 06:28:37 +00001578 const size_t num_continue_c_tids = m_continue_c_tids.size();
1579 const size_t num_continue_C_tids = m_continue_C_tids.size();
1580 const size_t num_continue_s_tids = m_continue_s_tids.size();
1581 const size_t num_continue_S_tids = m_continue_S_tids.size();
1582 if (num_continue_c_tids > 0)
1583 {
1584 if (num_continue_c_tids == num_threads)
1585 {
1586 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001587 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001588 continue_packet.PutChar ('c');
1589 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001590 }
1591 else if (num_continue_c_tids == 1 &&
1592 num_continue_C_tids == 0 &&
1593 num_continue_s_tids == 0 &&
1594 num_continue_S_tids == 0 )
1595 {
1596 // Only one thread is continuing
Greg Clayton8b82f082011-04-12 05:54:46 +00001597 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001598 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001599 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001600 }
1601 }
1602
Greg Clayton0c74e782011-06-24 03:21:43 +00001603 if (continue_packet_error && num_continue_C_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001604 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001605 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1606 num_continue_C_tids > 0 &&
1607 num_continue_s_tids == 0 &&
1608 num_continue_S_tids == 0 )
Greg Clayton71fc2a32011-02-12 06:28:37 +00001609 {
1610 const int continue_signo = m_continue_C_tids.front().second;
Greg Clayton0c74e782011-06-24 03:21:43 +00001611 // Only one thread is continuing
Greg Clayton71fc2a32011-02-12 06:28:37 +00001612 if (num_continue_C_tids > 1)
1613 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001614 // More that one thread with a signal, yet we don't have
1615 // vCont support and we are being asked to resume each
1616 // thread with a signal, we need to make sure they are
1617 // all the same signal, or we can't issue the continue
1618 // accurately with the current support...
1619 if (num_continue_C_tids > 1)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001620 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001621 continue_packet_error = false;
1622 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1623 {
1624 if (m_continue_C_tids[i].second != continue_signo)
1625 continue_packet_error = true;
1626 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001627 }
Greg Clayton0c74e782011-06-24 03:21:43 +00001628 if (!continue_packet_error)
1629 m_gdb_comm.SetCurrentThreadForRun (-1);
1630 }
1631 else
1632 {
1633 // Set the continue thread ID
1634 continue_packet_error = false;
1635 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001636 }
1637 if (!continue_packet_error)
1638 {
1639 // Add threads continuing with the same signo...
Greg Clayton71fc2a32011-02-12 06:28:37 +00001640 continue_packet.Printf("C%2.2x", continue_signo);
1641 }
1642 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001643 }
1644
Greg Clayton0c74e782011-06-24 03:21:43 +00001645 if (continue_packet_error && num_continue_s_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001646 {
1647 if (num_continue_s_tids == num_threads)
1648 {
1649 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001650 m_gdb_comm.SetCurrentThreadForRun (-1);
Ewan Crawford76df2882015-06-23 12:32:06 +00001651
1652 // If in Non-Stop-Mode use vCont when stepping
1653 if (GetTarget().GetNonStopModeEnabled())
1654 {
1655 if (m_gdb_comm.GetVContSupported('s'))
1656 continue_packet.PutCString("vCont;s");
1657 else
1658 continue_packet.PutChar('s');
1659 }
1660 else
1661 continue_packet.PutChar('s');
1662
Greg Clayton0c74e782011-06-24 03:21:43 +00001663 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001664 }
1665 else if (num_continue_c_tids == 0 &&
1666 num_continue_C_tids == 0 &&
1667 num_continue_s_tids == 1 &&
1668 num_continue_S_tids == 0 )
1669 {
1670 // Only one thread is stepping
Greg Clayton8b82f082011-04-12 05:54:46 +00001671 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001672 continue_packet.PutChar ('s');
Greg Clayton0c74e782011-06-24 03:21:43 +00001673 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001674 }
1675 }
1676
1677 if (!continue_packet_error && num_continue_S_tids > 0)
1678 {
1679 if (num_continue_S_tids == num_threads)
1680 {
1681 const int step_signo = m_continue_S_tids.front().second;
1682 // Are all threads trying to step with the same signal?
Greg Clayton0c74e782011-06-24 03:21:43 +00001683 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001684 if (num_continue_S_tids > 1)
1685 {
1686 for (size_t i=1; i<num_threads; ++i)
1687 {
1688 if (m_continue_S_tids[i].second != step_signo)
1689 continue_packet_error = true;
1690 }
1691 }
1692 if (!continue_packet_error)
1693 {
1694 // Add threads stepping with the same signo...
Greg Clayton8b82f082011-04-12 05:54:46 +00001695 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001696 continue_packet.Printf("S%2.2x", step_signo);
1697 }
1698 }
1699 else if (num_continue_c_tids == 0 &&
1700 num_continue_C_tids == 0 &&
1701 num_continue_s_tids == 0 &&
1702 num_continue_S_tids == 1 )
1703 {
1704 // Only one thread is stepping with signal
Greg Clayton8b82f082011-04-12 05:54:46 +00001705 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001706 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Clayton0c74e782011-06-24 03:21:43 +00001707 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001708 }
1709 }
1710 }
1711
1712 if (continue_packet_error)
1713 {
1714 error.SetErrorString ("can't make continue packet for this resume");
1715 }
1716 else
1717 {
1718 EventSP event_sp;
1719 TimeValue timeout;
1720 timeout = TimeValue::Now();
1721 timeout.OffsetWithSeconds (5);
Zachary Turneracee96a2014-09-23 18:32:09 +00001722 if (!m_async_thread.IsJoinable())
Jim Inghamb1e2e842012-04-12 18:49:31 +00001723 {
1724 error.SetErrorString ("Trying to resume but the async thread is dead.");
1725 if (log)
1726 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1727 return error;
1728 }
1729
Greg Clayton71fc2a32011-02-12 06:28:37 +00001730 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1731
1732 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Inghamb1e2e842012-04-12 18:49:31 +00001733 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001734 error.SetErrorString("Resume timed out.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00001735 if (log)
1736 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1737 }
1738 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1739 {
1740 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1741 if (log)
1742 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1743 return error;
1744 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001745 }
Greg Claytone5219662010-12-03 06:02:24 +00001746 }
1747
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001748 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001749}
1750
Greg Clayton9e920902012-04-10 02:25:43 +00001751void
Ewan Crawford78baa192015-05-13 09:18:18 +00001752ProcessGDBRemote::HandleStopReplySequence ()
1753{
1754 while(true)
1755 {
1756 // Send vStopped
1757 StringExtractorGDBRemote response;
1758 m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false);
1759
1760 // OK represents end of signal list
1761 if (response.IsOKResponse())
1762 break;
1763
1764 // If not OK or a normal packet we have a problem
1765 if (!response.IsNormalResponse())
1766 break;
1767
1768 SetLastStopPacket(response);
1769 }
1770}
1771
1772void
Greg Clayton9e920902012-04-10 02:25:43 +00001773ProcessGDBRemote::ClearThreadIDList ()
1774{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001775 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001776 m_thread_ids.clear();
1777}
1778
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001779size_t
1780ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue (std::string &value)
1781{
1782 m_thread_ids.clear();
1783 size_t comma_pos;
1784 lldb::tid_t tid;
1785 while ((comma_pos = value.find(',')) != std::string::npos)
1786 {
1787 value[comma_pos] = '\0';
1788 // thread in big endian hex
1789 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1790 if (tid != LLDB_INVALID_THREAD_ID)
1791 m_thread_ids.push_back (tid);
1792 value.erase(0, comma_pos + 1);
1793 }
1794 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1795 if (tid != LLDB_INVALID_THREAD_ID)
1796 m_thread_ids.push_back (tid);
1797 return m_thread_ids.size();
1798}
1799
Greg Clayton9e920902012-04-10 02:25:43 +00001800bool
1801ProcessGDBRemote::UpdateThreadIDList ()
1802{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001803 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001804
Greg Clayton2e309072015-07-17 23:42:28 +00001805 if (m_jthreadsinfo_sp)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001806 {
1807 // If we have the JSON threads info, we can get the thread list from that
Greg Clayton2e309072015-07-17 23:42:28 +00001808 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001809 if (thread_infos && thread_infos->GetSize() > 0)
1810 {
1811 m_thread_ids.clear();
1812 thread_infos->ForEach([this](StructuredData::Object* object) -> bool {
1813 StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1814 if (thread_dict)
1815 {
1816 // Set the thread stop info from the JSON dictionary
1817 SetThreadStopInfo (thread_dict);
1818 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1819 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1820 m_thread_ids.push_back(tid);
1821 }
1822 return true; // Keep iterating through all thread_info objects
1823 });
1824 }
1825 if (!m_thread_ids.empty())
1826 return true;
1827 }
1828 else
1829 {
1830 // See if we can get the thread IDs from the current stop reply packets
1831 // that might contain a "threads" key/value pair
1832
1833 // Lock the thread stack while we access it
1834 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
1835 // Get the number of stop packets on the stack
1836 int nItems = m_stop_packet_stack.size();
1837 // Iterate over them
1838 for (int i = 0; i < nItems; i++)
1839 {
1840 // Get the thread stop info
1841 StringExtractorGDBRemote &stop_info = m_stop_packet_stack[i];
1842 const std::string &stop_info_str = stop_info.GetStringRef();
1843 const size_t threads_pos = stop_info_str.find(";threads:");
1844 if (threads_pos != std::string::npos)
1845 {
1846 const size_t start = threads_pos + strlen(";threads:");
1847 const size_t end = stop_info_str.find(';', start);
1848 if (end != std::string::npos)
1849 {
1850 std::string value = stop_info_str.substr(start, end - start);
1851 if (UpdateThreadIDsFromStopReplyThreadsValue(value))
1852 return true;
1853 }
1854 }
1855 }
1856 }
1857
Greg Clayton9e920902012-04-10 02:25:43 +00001858 bool sequence_mutex_unavailable = false;
1859 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1860 if (sequence_mutex_unavailable)
1861 {
Greg Clayton9e920902012-04-10 02:25:43 +00001862 return false; // We just didn't get the list
1863 }
1864 return true;
1865}
1866
Greg Clayton9fc13552012-04-10 00:18:59 +00001867bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001868ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001869{
1870 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +00001871 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Clayton73b472d2010-10-27 03:32:59 +00001872 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +00001873 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton9e920902012-04-10 02:25:43 +00001874
1875 size_t num_thread_ids = m_thread_ids.size();
1876 // The "m_thread_ids" thread ID list should always be updated after each stop
1877 // reply packet, but in case it isn't, update it here.
1878 if (num_thread_ids == 0)
1879 {
1880 if (!UpdateThreadIDList ())
1881 return false;
1882 num_thread_ids = m_thread_ids.size();
1883 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001884
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001885 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001886 if (num_thread_ids > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001887 {
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001888 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001889 {
Greg Clayton9e920902012-04-10 02:25:43 +00001890 tid_t tid = m_thread_ids[i];
Greg Clayton160c9d82013-05-01 21:54:04 +00001891 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001892 if (!thread_sp)
Jim Inghamdee1bc92013-06-22 00:27:45 +00001893 {
Jim Ingham4f465cf2012-10-10 18:32:14 +00001894 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001895 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1896 log->Printf(
1897 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001898 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001899 thread_sp->GetID());
1900 }
1901 else
1902 {
1903 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1904 log->Printf(
1905 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001906 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001907 thread_sp->GetID());
1908 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001909 new_thread_list.AddThread(thread_sp);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001910 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001911 }
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001912
1913 // Whatever that is left in old_thread_list_copy are not
1914 // present in new_thread_list. Remove non-existent threads from internal id table.
1915 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1916 for (size_t i=0; i<old_num_thread_ids; i++)
1917 {
1918 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1919 if (old_thread_sp)
1920 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001921 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001922 m_thread_id_to_index_id_map.erase(old_thread_id);
1923 }
1924 }
1925
Greg Clayton9fc13552012-04-10 00:18:59 +00001926 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001927}
1928
Greg Clayton2e309072015-07-17 23:42:28 +00001929
Greg Clayton358cf1e2015-06-25 21:46:34 +00001930bool
Greg Clayton2e309072015-07-17 23:42:28 +00001931ProcessGDBRemote::GetThreadStopInfoFromJSON (ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001932{
1933 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet
Greg Clayton2e309072015-07-17 23:42:28 +00001934 if (thread_infos_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001935 {
Greg Clayton2e309072015-07-17 23:42:28 +00001936 StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
Greg Clayton358cf1e2015-06-25 21:46:34 +00001937 if (thread_infos)
1938 {
1939 lldb::tid_t tid;
1940 const size_t n = thread_infos->GetSize();
1941 for (size_t i=0; i<n; ++i)
1942 {
1943 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1944 if (thread_dict)
1945 {
1946 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid, LLDB_INVALID_THREAD_ID))
1947 {
1948 if (tid == thread->GetID())
Greg Clayton2e309072015-07-17 23:42:28 +00001949 return (bool)SetThreadStopInfo(thread_dict);
Greg Clayton358cf1e2015-06-25 21:46:34 +00001950 }
1951 }
1952 }
1953 }
1954 }
Greg Clayton2e309072015-07-17 23:42:28 +00001955 return false;
1956}
1957
1958bool
1959ProcessGDBRemote::CalculateThreadStopInfo (ThreadGDBRemote *thread)
1960{
1961 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet
1962 if (GetThreadStopInfoFromJSON (thread, m_jthreadsinfo_sp))
1963 return true;
1964
1965 // See if we got thread stop info for any threads valid stop info reasons threads
1966 // via the "jstopinfo" packet stop reply packet key/value pair?
1967 if (m_jstopinfo_sp)
1968 {
1969 // If we have "jstopinfo" then we have stop descriptions for all threads
1970 // that have stop reasons, and if there is no entry for a thread, then
1971 // it has no stop reason.
1972 thread->GetRegisterContext()->InvalidateIfNeeded(true);
1973 if (!GetThreadStopInfoFromJSON (thread, m_jstopinfo_sp))
1974 {
1975 thread->SetStopInfo (StopInfoSP());
1976 }
1977 return true;
1978 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00001979
1980 // Fall back to using the qThreadStopInfo packet
1981 StringExtractorGDBRemote stop_packet;
1982 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1983 return SetThreadStopInfo (stop_packet) == eStateStopped;
1984 return false;
1985}
1986
1987
1988ThreadSP
1989ProcessGDBRemote::SetThreadStopInfo (lldb::tid_t tid,
1990 ExpeditedRegisterMap &expedited_register_map,
1991 uint8_t signo,
1992 const std::string &thread_name,
1993 const std::string &reason,
1994 const std::string &description,
1995 uint32_t exc_type,
1996 const std::vector<addr_t> &exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001997 addr_t thread_dispatch_qaddr,
1998 bool queue_vars_valid, // Set to true if queue_name, queue_kind and queue_serial are valid
1999 std::string &queue_name,
2000 QueueKind queue_kind,
2001 uint64_t queue_serial)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002002{
2003 ThreadSP thread_sp;
2004 if (tid != LLDB_INVALID_THREAD_ID)
2005 {
2006 // Scope for "locker" below
2007 {
2008 // m_thread_list_real does have its own mutex, but we need to
2009 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
2010 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
2011 Mutex::Locker locker (m_thread_list_real.GetMutex ());
2012 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
2013
2014 if (!thread_sp)
2015 {
2016 // Create the thread if we need to
2017 thread_sp.reset (new ThreadGDBRemote (*this, tid));
2018 m_thread_list_real.AddThread(thread_sp);
2019 }
2020 }
2021
2022 if (thread_sp)
2023 {
2024 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
2025 gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002026
Greg Clayton358cf1e2015-06-25 21:46:34 +00002027 for (const auto &pair : expedited_register_map)
2028 {
2029 StringExtractor reg_value_extractor;
2030 reg_value_extractor.GetStringRef() = pair.second;
2031 gdb_thread->PrivateSetRegisterValue (pair.first, reg_value_extractor);
2032 }
2033
Greg Clayton358cf1e2015-06-25 21:46:34 +00002034 thread_sp->SetName (thread_name.empty() ? NULL : thread_name.c_str());
2035
2036 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002037 // Check if the GDB server was able to provide the queue name, kind and serial number
2038 if (queue_vars_valid)
2039 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind, queue_serial);
2040 else
2041 gdb_thread->ClearQueueInfo();
2042
Greg Clayton2e309072015-07-17 23:42:28 +00002043 // Make sure we update our thread stop reason just once
2044 if (!thread_sp->StopInfoIsUpToDate())
Greg Clayton358cf1e2015-06-25 21:46:34 +00002045 {
Greg Clayton2e309072015-07-17 23:42:28 +00002046 thread_sp->SetStopInfo (StopInfoSP());
Greg Clayton358cf1e2015-06-25 21:46:34 +00002047
Greg Clayton2e309072015-07-17 23:42:28 +00002048 if (exc_type != 0)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002049 {
Greg Clayton2e309072015-07-17 23:42:28 +00002050 const size_t exc_data_size = exc_data.size();
2051
2052 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
2053 exc_type,
2054 exc_data_size,
2055 exc_data_size >= 1 ? exc_data[0] : 0,
2056 exc_data_size >= 2 ? exc_data[1] : 0,
2057 exc_data_size >= 3 ? exc_data[2] : 0));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002058 }
Greg Clayton2e309072015-07-17 23:42:28 +00002059 else
Greg Clayton358cf1e2015-06-25 21:46:34 +00002060 {
Greg Clayton2e309072015-07-17 23:42:28 +00002061 bool handled = false;
2062 bool did_exec = false;
2063 if (!reason.empty())
Greg Clayton358cf1e2015-06-25 21:46:34 +00002064 {
Greg Clayton2e309072015-07-17 23:42:28 +00002065 if (reason.compare("trace") == 0)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002066 {
Greg Clayton2e309072015-07-17 23:42:28 +00002067 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
2068 handled = true;
2069 }
2070 else if (reason.compare("breakpoint") == 0)
2071 {
2072 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
2073 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2074 if (bp_site_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002075 {
Greg Clayton2e309072015-07-17 23:42:28 +00002076 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2077 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2078 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2079 handled = true;
2080 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2081 {
2082 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2083 }
2084 else
2085 {
2086 StopInfoSP invalid_stop_info_sp;
2087 thread_sp->SetStopInfo (invalid_stop_info_sp);
2088 }
2089 }
2090 }
2091 else if (reason.compare("trap") == 0)
2092 {
2093 // Let the trap just use the standard signal stop reason below...
2094 }
2095 else if (reason.compare("watchpoint") == 0)
2096 {
2097 StringExtractor desc_extractor(description.c_str());
2098 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
2099 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
Jaydeep Patil83143502015-08-13 03:44:09 +00002100 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
Greg Clayton2e309072015-07-17 23:42:28 +00002101 watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
2102 if (wp_addr != LLDB_INVALID_ADDRESS)
2103 {
2104 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2105 if (wp_sp)
2106 {
2107 wp_sp->SetHardwareIndex(wp_index);
2108 watch_id = wp_sp->GetID();
2109 }
2110 }
2111 if (watch_id == LLDB_INVALID_WATCH_ID)
2112 {
2113 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_WATCHPOINTS));
2114 if (log) log->Printf ("failed to find watchpoint");
2115 }
Jaydeep Patil83143502015-08-13 03:44:09 +00002116 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id, wp_hit_addr));
Greg Clayton2e309072015-07-17 23:42:28 +00002117 handled = true;
2118 }
2119 else if (reason.compare("exception") == 0)
2120 {
2121 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
2122 handled = true;
2123 }
2124 else if (reason.compare("exec") == 0)
2125 {
2126 did_exec = true;
2127 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
2128 handled = true;
2129 }
2130 }
2131
2132 if (!handled && signo && did_exec == false)
2133 {
2134 if (signo == SIGTRAP)
2135 {
2136 // Currently we are going to assume SIGTRAP means we are either
2137 // hitting a breakpoint or hardware single stepping.
2138 handled = true;
2139 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
2140 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2141
2142 if (bp_site_sp)
2143 {
2144 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2145 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2146 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2147 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2148 {
2149 if(m_breakpoint_pc_offset != 0)
2150 thread_sp->GetRegisterContext()->SetPC(pc);
2151 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2152 }
2153 else
2154 {
2155 StopInfoSP invalid_stop_info_sp;
2156 thread_sp->SetStopInfo (invalid_stop_info_sp);
2157 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002158 }
2159 else
2160 {
Greg Clayton2e309072015-07-17 23:42:28 +00002161 // If we were stepping then assume the stop was the result of the trace. If we were
2162 // not stepping then report the SIGTRAP.
2163 // FIXME: We are still missing the case where we single step over a trap instruction.
2164 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
2165 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
2166 else
2167 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo, description.c_str()));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002168 }
2169 }
Greg Clayton2e309072015-07-17 23:42:28 +00002170 if (!handled)
2171 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo, description.c_str()));
2172 }
2173
2174 if (!description.empty())
2175 {
2176 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
2177 if (stop_info_sp)
2178 {
2179 const char *stop_info_desc = stop_info_sp->GetDescription();
2180 if (!stop_info_desc || !stop_info_desc[0])
2181 stop_info_sp->SetDescription (description.c_str());
2182 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002183 else
2184 {
Greg Clayton2e309072015-07-17 23:42:28 +00002185 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002186 }
2187 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002188 }
2189 }
2190 }
2191 }
2192 return thread_sp;
2193}
2194
Greg Clayton2e309072015-07-17 23:42:28 +00002195lldb::ThreadSP
Greg Clayton358cf1e2015-06-25 21:46:34 +00002196ProcessGDBRemote::SetThreadStopInfo (StructuredData::Dictionary *thread_dict)
2197{
2198 static ConstString g_key_tid("tid");
2199 static ConstString g_key_name("name");
2200 static ConstString g_key_reason("reason");
2201 static ConstString g_key_metype("metype");
2202 static ConstString g_key_medata("medata");
2203 static ConstString g_key_qaddr("qaddr");
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002204 static ConstString g_key_queue_name("qname");
2205 static ConstString g_key_queue_kind("qkind");
2206 static ConstString g_key_queue_serial("qserial");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002207 static ConstString g_key_registers("registers");
2208 static ConstString g_key_memory("memory");
2209 static ConstString g_key_address("address");
2210 static ConstString g_key_bytes("bytes");
2211 static ConstString g_key_description("description");
Pavel Labath4a4bb122015-07-16 14:14:35 +00002212 static ConstString g_key_signal("signal");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002213
2214 // Stop with signal and thread info
2215 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2216 uint8_t signo = 0;
2217 std::string value;
2218 std::string thread_name;
2219 std::string reason;
2220 std::string description;
2221 uint32_t exc_type = 0;
2222 std::vector<addr_t> exc_data;
2223 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2224 ExpeditedRegisterMap expedited_register_map;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002225 bool queue_vars_valid = false;
2226 std::string queue_name;
2227 QueueKind queue_kind = eQueueKindUnknown;
2228 uint64_t queue_serial = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002229 // Iterate through all of the thread dictionary key/value pairs from the structured data dictionary
2230
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002231 thread_dict->ForEach([this,
2232 &tid,
2233 &expedited_register_map,
2234 &thread_name,
2235 &signo,
2236 &reason,
2237 &description,
2238 &exc_type,
2239 &exc_data,
2240 &thread_dispatch_qaddr,
2241 &queue_vars_valid,
2242 &queue_name,
2243 &queue_kind,
2244 &queue_serial]
2245 (ConstString key, StructuredData::Object* object) -> bool
Greg Clayton358cf1e2015-06-25 21:46:34 +00002246 {
2247 if (key == g_key_tid)
2248 {
2249 // thread in big endian hex
2250 tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
2251 }
2252 else if (key == g_key_metype)
2253 {
2254 // exception type in big endian hex
2255 exc_type = object->GetIntegerValue(0);
2256 }
2257 else if (key == g_key_medata)
2258 {
2259 // exception data in big endian hex
2260 StructuredData::Array *array = object->GetAsArray();
2261 if (array)
2262 {
2263 array->ForEach([&exc_data](StructuredData::Object* object) -> bool {
2264 exc_data.push_back(object->GetIntegerValue());
2265 return true; // Keep iterating through all array items
2266 });
2267 }
2268 }
2269 else if (key == g_key_name)
2270 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002271 thread_name = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002272 }
2273 else if (key == g_key_qaddr)
2274 {
2275 thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
2276 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002277 else if (key == g_key_queue_name)
2278 {
2279 queue_vars_valid = true;
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002280 queue_name = object->GetStringValue();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002281 }
2282 else if (key == g_key_queue_kind)
2283 {
2284 std::string queue_kind_str = object->GetStringValue();
2285 if (queue_kind_str == "serial")
2286 {
2287 queue_vars_valid = true;
2288 queue_kind = eQueueKindSerial;
2289 }
2290 else if (queue_kind_str == "concurrent")
2291 {
2292 queue_vars_valid = true;
2293 queue_kind = eQueueKindConcurrent;
2294 }
2295 }
2296 else if (key == g_key_queue_serial)
2297 {
2298 queue_serial = object->GetIntegerValue(0);
2299 if (queue_serial != 0)
2300 queue_vars_valid = true;
2301 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002302 else if (key == g_key_reason)
2303 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002304 reason = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002305 }
2306 else if (key == g_key_description)
2307 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002308 description = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002309 }
2310 else if (key == g_key_registers)
2311 {
2312 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2313
2314 if (registers_dict)
2315 {
2316 registers_dict->ForEach([&expedited_register_map](ConstString key, StructuredData::Object* object) -> bool {
2317 const uint32_t reg = StringConvert::ToUInt32 (key.GetCString(), UINT32_MAX, 10);
2318 if (reg != UINT32_MAX)
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002319 expedited_register_map[reg] = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002320 return true; // Keep iterating through all array items
2321 });
2322 }
2323 }
2324 else if (key == g_key_memory)
2325 {
2326 StructuredData::Array *array = object->GetAsArray();
2327 if (array)
2328 {
2329 array->ForEach([this](StructuredData::Object* object) -> bool {
2330 StructuredData::Dictionary *mem_cache_dict = object->GetAsDictionary();
2331 if (mem_cache_dict)
2332 {
2333 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2334 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>("address", mem_cache_addr))
2335 {
2336 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
2337 {
2338 StringExtractor bytes;
2339 if (mem_cache_dict->GetValueForKeyAsString("bytes", bytes.GetStringRef()))
2340 {
2341 bytes.SetFilePos(0);
2342
2343 const size_t byte_size = bytes.GetStringRef().size()/2;
2344 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2345 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2346 if (bytes_copied == byte_size)
2347 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2348 }
2349 }
2350 }
2351 }
2352 return true; // Keep iterating through all array items
2353 });
2354 }
2355
2356 }
Pavel Labath4a4bb122015-07-16 14:14:35 +00002357 else if (key == g_key_signal)
2358 signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002359 return true; // Keep iterating through all dictionary key/value pairs
2360 });
2361
Greg Clayton2e309072015-07-17 23:42:28 +00002362 return SetThreadStopInfo (tid,
2363 expedited_register_map,
2364 signo,
2365 thread_name,
2366 reason,
2367 description,
2368 exc_type,
2369 exc_data,
2370 thread_dispatch_qaddr,
2371 queue_vars_valid,
2372 queue_name,
2373 queue_kind,
2374 queue_serial);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002375}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002376
2377StateType
2378ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
2379{
Greg Claytondd0e5a52011-06-02 22:22:38 +00002380 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002381 const char stop_type = stop_packet.GetChar();
2382 switch (stop_type)
2383 {
2384 case 'T':
2385 case 'S':
2386 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00002387 // This is a bit of a hack, but is is required. If we did exec, we
2388 // need to clear our thread lists and also know to rebuild our dynamic
2389 // register info before we lookup and threads and populate the expedited
2390 // register values so we need to know this right away so we can cleanup
2391 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00002392 const uint32_t stop_id = GetStopID();
2393 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00002394 {
2395 // Our first stop, make sure we have a process ID, and also make
2396 // sure we know about our registers
2397 if (GetID() == LLDB_INVALID_PROCESS_ID)
2398 {
Greg Claytonc574ede2011-03-10 02:26:48 +00002399 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00002400 if (pid != LLDB_INVALID_PROCESS_ID)
2401 SetID (pid);
2402 }
2403 BuildDynamicRegisterInfo (true);
2404 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002405 // Stop with signal and thread info
Greg Clayton358cf1e2015-06-25 21:46:34 +00002406 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002407 const uint8_t signo = stop_packet.GetHexU8();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002408 std::string key;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002409 std::string value;
2410 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00002411 std::string reason;
2412 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002413 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00002414 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002415 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton0b90be12015-06-23 21:27:50 +00002416 bool queue_vars_valid = false; // says if locals below that start with "queue_" are valid
2417 std::string queue_name;
2418 QueueKind queue_kind = eQueueKindUnknown;
2419 uint64_t queue_serial = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002420 ExpeditedRegisterMap expedited_register_map;
2421 while (stop_packet.GetNameColonValue(key, value))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002422 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002423 if (key.compare("metype") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002424 {
2425 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002426 exc_type = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002427 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002428 else if (key.compare("medata") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002429 {
2430 // exception data in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002431 exc_data.push_back(StringConvert::ToUInt64 (value.c_str(), 0, 16));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002432 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002433 else if (key.compare("thread") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002434 {
2435 // thread in big endian hex
Greg Clayton358cf1e2015-06-25 21:46:34 +00002436 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002437 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002438 else if (key.compare("threads") == 0)
Greg Clayton9e920902012-04-10 02:25:43 +00002439 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002440 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00002441 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00002442 // A comma separated list of all threads in the current
2443 // process that includes the thread for this stop reply
2444 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00002445 size_t comma_pos;
2446 lldb::tid_t tid;
2447 while ((comma_pos = value.find(',')) != std::string::npos)
2448 {
2449 value[comma_pos] = '\0';
2450 // thread in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002451 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00002452 if (tid != LLDB_INVALID_THREAD_ID)
2453 m_thread_ids.push_back (tid);
2454 value.erase(0, comma_pos + 1);
Greg Clayton9e920902012-04-10 02:25:43 +00002455 }
Vince Harron5275aaa2015-01-15 20:08:35 +00002456 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00002457 if (tid != LLDB_INVALID_THREAD_ID)
2458 m_thread_ids.push_back (tid);
2459 }
Greg Clayton2e309072015-07-17 23:42:28 +00002460 else if (key.compare("jstopinfo") == 0)
Greg Claytona5801ad2015-07-15 22:59:03 +00002461 {
2462 StringExtractor json_extractor;
2463 // Swap "value" over into "name_extractor"
2464 json_extractor.GetStringRef().swap(value);
2465 // Now convert the HEX bytes into a string value
2466 json_extractor.GetHexByteString (value);
2467
2468 // This JSON contains thread IDs and thread stop info for all threads.
2469 // It doesn't contain expedited registers, memory or queue info.
Greg Clayton2e309072015-07-17 23:42:28 +00002470 m_jstopinfo_sp = StructuredData::ParseJSON (value);
Greg Claytona5801ad2015-07-15 22:59:03 +00002471 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002472 else if (key.compare("hexname") == 0)
Greg Claytonde9d0492011-01-08 03:17:57 +00002473 {
2474 StringExtractor name_extractor;
2475 // Swap "value" over into "name_extractor"
2476 name_extractor.GetStringRef().swap(value);
2477 // Now convert the HEX bytes into a string value
2478 name_extractor.GetHexByteString (value);
2479 thread_name.swap (value);
2480 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002481 else if (key.compare("name") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002482 {
2483 thread_name.swap (value);
2484 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002485 else if (key.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002486 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002487 thread_dispatch_qaddr = StringConvert::ToUInt64 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002488 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002489 else if (key.compare("qname") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002490 {
2491 queue_vars_valid = true;
2492 StringExtractor name_extractor;
2493 // Swap "value" over into "name_extractor"
2494 name_extractor.GetStringRef().swap(value);
2495 // Now convert the HEX bytes into a string value
2496 name_extractor.GetHexByteString (value);
2497 queue_name.swap (value);
2498 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002499 else if (key.compare("qkind") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002500 {
Greg Clayton0b90be12015-06-23 21:27:50 +00002501 if (value == "serial")
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002502 {
2503 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002504 queue_kind = eQueueKindSerial;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002505 }
Greg Clayton0b90be12015-06-23 21:27:50 +00002506 else if (value == "concurrent")
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002507 {
2508 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002509 queue_kind = eQueueKindConcurrent;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002510 }
Greg Clayton0b90be12015-06-23 21:27:50 +00002511 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002512 else if (key.compare("qserial") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002513 {
Greg Clayton0b90be12015-06-23 21:27:50 +00002514 queue_serial = StringConvert::ToUInt64 (value.c_str(), 0, 0);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002515 if (queue_serial != 0)
2516 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002517 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002518 else if (key.compare("reason") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002519 {
2520 reason.swap(value);
2521 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002522 else if (key.compare("description") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002523 {
2524 StringExtractor desc_extractor;
2525 // Swap "value" over into "name_extractor"
2526 desc_extractor.GetStringRef().swap(value);
2527 // Now convert the HEX bytes into a string value
Chaoren Lin28e57422015-02-03 01:51:25 +00002528 desc_extractor.GetHexByteString (value);
2529 description.swap(value);
Greg Claytona658fd22011-06-04 01:26:29 +00002530 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002531 else if (key.compare("memory") == 0)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002532 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002533 // Expedited memory. GDB servers can choose to send back expedited memory
2534 // that can populate the L1 memory cache in the process so that things like
2535 // the frame pointer backchain can be expedited. This will help stack
2536 // backtracing be more efficient by not having to send as many memory read
2537 // requests down the remote GDB server.
Chaoren Lin7a306082015-06-23 03:17:01 +00002538
Greg Clayton358cf1e2015-06-25 21:46:34 +00002539 // Key/value pair format: memory:<addr>=<bytes>;
2540 // <addr> is a number whose base will be interpreted by the prefix:
2541 // "0x[0-9a-fA-F]+" for hex
2542 // "0[0-7]+" for octal
2543 // "[1-9]+" for decimal
2544 // <bytes> is native endian ASCII hex bytes just like the register values
2545 llvm::StringRef value_ref(value);
2546 std::pair<llvm::StringRef, llvm::StringRef> pair;
2547 pair = value_ref.split('=');
2548 if (!pair.first.empty() && !pair.second.empty())
2549 {
2550 std::string addr_str(pair.first.str());
2551 const lldb::addr_t mem_cache_addr = StringConvert::ToUInt64(addr_str.c_str(), LLDB_INVALID_ADDRESS, 0);
2552 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002553 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002554 StringExtractor bytes;
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002555 bytes.GetStringRef() = pair.second.str();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002556 const size_t byte_size = bytes.GetStringRef().size()/2;
2557 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2558 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2559 if (bytes_copied == byte_size)
2560 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
Greg Clayton3e06bd92011-01-09 21:07:35 +00002561 }
2562 }
2563 }
Jaydeep Patil725666c2015-08-13 03:46:01 +00002564 else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 || key.compare("awatch") == 0)
2565 {
2566 // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2567 lldb::addr_t wp_addr = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
2568 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2569 uint32_t wp_index = LLDB_INVALID_INDEX32;
2570
2571 if (wp_sp)
2572 wp_index = wp_sp->GetHardwareIndex();
2573
2574 reason = "watchpoint";
2575 StreamString ostr;
2576 ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
2577 description = ostr.GetString().c_str();
2578 }
Stephane Sezer2618e912015-08-21 16:51:56 +00002579 else if (key.compare("library") == 0)
2580 {
2581 LoadModules();
2582 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002583 else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1]))
2584 {
2585 uint32_t reg = StringConvert::ToUInt32 (key.c_str(), UINT32_MAX, 16);
2586 if (reg != UINT32_MAX)
2587 expedited_register_map[reg] = std::move(value);
2588 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002589 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002590
Bhushan D. Attarde1e271df2015-07-24 04:06:20 +00002591 if (tid == LLDB_INVALID_THREAD_ID)
2592 {
2593 // A thread id may be invalid if the response is old style 'S' packet which does not provide the
2594 // thread information. So update the thread list and choose the first one.
2595 UpdateThreadIDList ();
2596
2597 if (!m_thread_ids.empty ())
2598 {
2599 tid = m_thread_ids.front ();
2600 }
2601 }
2602
Greg Clayton358cf1e2015-06-25 21:46:34 +00002603 ThreadSP thread_sp = SetThreadStopInfo (tid,
2604 expedited_register_map,
2605 signo,
2606 thread_name,
2607 reason,
2608 description,
2609 exc_type,
2610 exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002611 thread_dispatch_qaddr,
2612 queue_vars_valid,
2613 queue_name,
2614 queue_kind,
2615 queue_serial);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002616
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002617 return eStateStopped;
2618 }
2619 break;
2620
2621 case 'W':
Todd Fialaff6131a2014-05-19 04:57:23 +00002622 case 'X':
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002623 // process exited
2624 return eStateExited;
2625
2626 default:
2627 break;
2628 }
2629 return eStateInvalid;
2630}
2631
2632void
2633ProcessGDBRemote::RefreshStateAfterStop ()
2634{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002635 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00002636 m_thread_ids.clear();
2637 // Set the thread stop info. It might have a "threads" key whose value is
2638 // a list of all thread IDs in the current process, so m_thread_ids might
2639 // get set.
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002640
2641 // Scope for the lock
2642 {
2643 // Lock the thread stack while we access it
2644 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
2645 // Get the number of stop packets on the stack
2646 int nItems = m_stop_packet_stack.size();
2647 // Iterate over them
2648 for (int i = 0; i < nItems; i++)
2649 {
2650 // Get the thread stop info
2651 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2652 // Process thread stop info
2653 SetThreadStopInfo(stop_info);
2654 }
2655 // Clear the thread stop stack
2656 m_stop_packet_stack.clear();
2657 }
2658
Greg Clayton9e920902012-04-10 02:25:43 +00002659 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2660 if (m_thread_ids.empty())
2661 {
2662 // No, we need to fetch the thread list manually
2663 UpdateThreadIDList();
2664 }
2665
Ewan Crawford78baa192015-05-13 09:18:18 +00002666 // If we have queried for a default thread id
2667 if (m_initial_tid != LLDB_INVALID_THREAD_ID)
2668 {
2669 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2670 m_initial_tid = LLDB_INVALID_THREAD_ID;
2671 }
2672
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002673 // Let all threads recover from stopping and do any clean up based
2674 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002675 m_thread_list_real.RefreshStateAfterStop();
Greg Clayton9e920902012-04-10 02:25:43 +00002676
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002677}
2678
2679Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002680ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002681{
2682 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002683
Greg Clayton6ed95942011-01-22 07:12:45 +00002684 bool timed_out = false;
2685 Mutex::Locker locker;
Greg Clayton513c26c2011-01-29 07:10:55 +00002686
2687 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002688 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002689 // We are being asked to halt during an attach. We need to just close
2690 // our file handle and debugserver will go away, and we can be done...
2691 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00002692 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002693 else
2694 {
Greg Clayton2687cd12012-03-29 01:55:41 +00002695 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton513c26c2011-01-29 07:10:55 +00002696 {
2697 if (timed_out)
2698 error.SetErrorString("timed out sending interrupt packet");
2699 else
2700 error.SetErrorString("unknown error sending interrupt packet");
2701 }
Greg Clayton2687cd12012-03-29 01:55:41 +00002702
2703 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton513c26c2011-01-29 07:10:55 +00002704 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002705 return error;
2706}
2707
2708Error
Jim Inghamacff8952013-05-02 00:27:30 +00002709ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002710{
2711 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002712 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00002713 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00002714 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2715
Jim Inghamacff8952013-05-02 00:27:30 +00002716 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002717 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002718 {
Jim Inghamacff8952013-05-02 00:27:30 +00002719 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002720 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
2721 else
Jim Inghamacff8952013-05-02 00:27:30 +00002722 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00002723 }
Jim Inghamacff8952013-05-02 00:27:30 +00002724
2725 if (!error.Success())
2726 return error;
2727
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002728 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00002729 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002730
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002731 SetPrivateState (eStateDetached);
2732 ResumePrivateStateThread();
2733
2734 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00002735 return error;
2736}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002737
Jim Ingham43c555d2012-07-04 00:35:43 +00002738
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002739Error
2740ProcessGDBRemote::DoDestroy ()
2741{
2742 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002743 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002744 if (log)
2745 log->Printf ("ProcessGDBRemote::DoDestroy()");
2746
Jim Ingham43c555d2012-07-04 00:35:43 +00002747 // There is a bug in older iOS debugservers where they don't shut down the process
2748 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
2749 // this can cause problems with restarting. So we check to see if any of our threads are stopped
2750 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
2751 // destroy it again.
2752 //
2753 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
2754 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
2755 // the debugservers with this bug are equal. There really should be a better way to test this!
2756 //
2757 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
2758 // get called here to destroy again and we're still at a breakpoint or exception, then we should
2759 // just do the straight-forward kill.
2760 //
2761 // And of course, if we weren't able to stop the process by the time we get here, it isn't
2762 // necessary (or helpful) to do any of this.
2763
2764 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
2765 {
2766 PlatformSP platform_sp = GetTarget().GetPlatform();
2767
2768 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2769 if (platform_sp
2770 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00002771 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00002772 {
2773 if (m_destroy_tried_resuming)
2774 {
2775 if (log)
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002776 log->PutCString ("ProcessGDBRemote::DoDestroy() - Tried resuming to destroy once already, not doing it again.");
Jim Ingham43c555d2012-07-04 00:35:43 +00002777 }
2778 else
2779 {
2780 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
2781 // but we really need it to happen here and it doesn't matter if we do it twice.
2782 m_thread_list.DiscardThreadPlans();
2783 DisableAllBreakpointSites();
2784
2785 bool stop_looks_like_crash = false;
2786 ThreadList &threads = GetThreadList();
2787
2788 {
Jim Ingham45350372012-09-11 00:08:52 +00002789 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002790
2791 size_t num_threads = threads.GetSize();
2792 for (size_t i = 0; i < num_threads; i++)
2793 {
2794 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002795 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002796 StopReason reason = eStopReasonInvalid;
2797 if (stop_info_sp)
2798 reason = stop_info_sp->GetStopReason();
2799 if (reason == eStopReasonBreakpoint
2800 || reason == eStopReasonException)
2801 {
2802 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002803 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
2804 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00002805 stop_info_sp->GetDescription());
2806 stop_looks_like_crash = true;
2807 break;
2808 }
2809 }
2810 }
2811
2812 if (stop_looks_like_crash)
2813 {
2814 if (log)
2815 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
2816 m_destroy_tried_resuming = true;
2817
2818 // If we are going to run again before killing, it would be good to suspend all the threads
2819 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
2820 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
2821 // have to run the risk of letting those threads proceed a bit.
2822
2823 {
Jim Ingham45350372012-09-11 00:08:52 +00002824 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002825
2826 size_t num_threads = threads.GetSize();
2827 for (size_t i = 0; i < num_threads; i++)
2828 {
2829 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002830 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002831 StopReason reason = eStopReasonInvalid;
2832 if (stop_info_sp)
2833 reason = stop_info_sp->GetStopReason();
2834 if (reason != eStopReasonBreakpoint
2835 && reason != eStopReasonException)
2836 {
2837 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002838 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
2839 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00002840 thread_sp->SetResumeState(eStateSuspended);
2841 }
2842 }
2843 }
2844 Resume ();
Jason Molendaede31932015-04-17 05:01:58 +00002845 return Destroy(false);
Jim Ingham43c555d2012-07-04 00:35:43 +00002846 }
2847 }
2848 }
2849 }
2850
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002851 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00002852 int exit_status = SIGABRT;
2853 std::string exit_string;
2854
Greg Clayton6ed95942011-01-22 07:12:45 +00002855 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002856 {
Jim Inghamaab78372011-10-28 01:11:35 +00002857 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00002858 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002859 StringExtractorGDBRemote response;
2860 bool send_async = true;
Tamas Berghammer912800c2015-02-24 10:23:39 +00002861 GDBRemoteCommunication::ScopedTimeout (m_gdb_comm, 3);
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002862
Greg Clayton3dedae12013-12-06 21:45:27 +00002863 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton513c26c2011-01-29 07:10:55 +00002864 {
2865 char packet_cmd = response.GetChar(0);
2866
2867 if (packet_cmd == 'W' || packet_cmd == 'X')
2868 {
Jim Inghameac0aa42014-02-21 22:36:11 +00002869#if defined(__APPLE__)
Jim Ingham9d67cc52014-02-21 22:35:29 +00002870 // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off
2871 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill
2872 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns
2873 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap
2874 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of
2875 // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2876 // Anyway, so call waitpid here to finally reap it.
2877 PlatformSP platform_sp(GetTarget().GetPlatform());
2878 if (platform_sp && platform_sp->IsHost())
2879 {
2880 int status;
2881 ::pid_t reap_pid;
2882 reap_pid = waitpid (GetID(), &status, WNOHANG);
2883 if (log)
2884 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2885 }
2886#endif
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002887 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002888 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00002889 exit_status = response.GetHexU8();
2890 }
2891 else
2892 {
2893 if (log)
2894 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2895 exit_string.assign("got unexpected response to k packet: ");
2896 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00002897 }
2898 }
2899 else
2900 {
Jim Inghambabfc382012-06-06 00:32:39 +00002901 if (log)
2902 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2903 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00002904 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002905 }
Jim Inghambabfc382012-06-06 00:32:39 +00002906 else
2907 {
2908 if (log)
Ed Masteb3a53332014-03-17 17:05:22 +00002909 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching");
Jim Inghamcfc09352012-07-27 23:57:19 +00002910 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00002911 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002912 }
Jim Inghambabfc382012-06-06 00:32:39 +00002913 else
2914 {
2915 // If we missed setting the exit status on the way out, do it here.
2916 // NB set exit status can be called multiple times, the first one sets the status.
2917 exit_string.assign("destroying when not connected to debugserver");
2918 }
2919
2920 SetExitStatus(exit_status, exit_string.c_str());
2921
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002922 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002923 KillDebugserverProcess ();
2924 return error;
2925}
2926
Greg Clayton8cda7f02013-05-21 21:55:59 +00002927void
2928ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2929{
Greg Clayton8cda7f02013-05-21 21:55:59 +00002930 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2931 if (did_exec)
2932 {
2933 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2934 if (log)
2935 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2936
2937 m_thread_list_real.Clear();
2938 m_thread_list.Clear();
2939 BuildDynamicRegisterInfo (true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002940 m_gdb_comm.ResetDiscoverableSettings (did_exec);
Greg Clayton8cda7f02013-05-21 21:55:59 +00002941 }
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002942
2943 // Scope the lock
2944 {
2945 // Lock the thread stack while we access it
2946 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
Greg Clayton2e309072015-07-17 23:42:28 +00002947
2948 // We are are not using non-stop mode, there can only be one last stop
2949 // reply packet, so clear the list.
2950 if (GetTarget().GetNonStopModeEnabled() == false)
2951 m_stop_packet_stack.clear();
2952
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002953 // Add this stop packet to the stop packet stack
2954 // This stack will get popped and examined when we switch to the
2955 // Stopped state
2956 m_stop_packet_stack.push_back(response);
2957 }
Greg Clayton8cda7f02013-05-21 21:55:59 +00002958}
2959
Chaoren Linc963a222015-09-01 16:58:45 +00002960void
2961ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp)
2962{
2963 Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
2964}
2965
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002966//------------------------------------------------------------------
2967// Process Queries
2968//------------------------------------------------------------------
2969
2970bool
2971ProcessGDBRemote::IsAlive ()
2972{
Greg Clayton10177aa2010-12-08 05:08:21 +00002973 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002974}
2975
2976addr_t
2977ProcessGDBRemote::GetImageInfoAddress()
2978{
Aidan Doddsc0c83852015-05-08 09:36:31 +00002979 // request the link map address via the $qShlibInfoAddr packet
2980 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2981
2982 // the loaded module list can also provides a link map address
2983 if (addr == LLDB_INVALID_ADDRESS)
2984 {
2985 GDBLoadedModuleInfoList list;
2986 if (GetLoadedModuleList (list).Success())
2987 addr = list.m_link_map;
2988 }
2989
2990 return addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002991}
2992
Greg Clayton2e309072015-07-17 23:42:28 +00002993void
2994ProcessGDBRemote::WillPublicStop ()
2995{
2996 // See if the GDB remote client supports the JSON threads info.
2997 // If so, we gather stop info for all threads, expedited registers,
2998 // expedited memory, runtime queue information (iOS and MacOSX only),
2999 // and more. Expediting memory will help stack backtracing be much
3000 // faster. Expediting registers will make sure we don't have to read
3001 // the thread registers for GPRs.
3002 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
3003
3004 if (m_jthreadsinfo_sp)
3005 {
3006 // Now set the stop info for each thread and also expedite any registers
3007 // and memory that was in the jThreadsInfo response.
3008 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
3009 if (thread_infos)
3010 {
3011 const size_t n = thread_infos->GetSize();
3012 for (size_t i=0; i<n; ++i)
3013 {
3014 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
3015 if (thread_dict)
3016 SetThreadStopInfo(thread_dict);
3017 }
3018 }
3019 }
3020}
3021
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003022//------------------------------------------------------------------
3023// Process Memory
3024//------------------------------------------------------------------
3025size_t
3026ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
3027{
Jason Molenda6076bf42014-05-06 04:34:52 +00003028 GetMaxMemorySize ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003029 if (size > m_max_memory_size)
3030 {
3031 // Keep memory read sizes down to a sane limit. This function will be
3032 // called multiple times in order to complete the task by
3033 // lldb_private::Process so it is ok to do this.
3034 size = m_max_memory_size;
3035 }
3036
3037 char packet[64];
Jason Molenda6076bf42014-05-06 04:34:52 +00003038 int packet_len;
3039 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
3040 if (binary_memory_read)
3041 {
3042 packet_len = ::snprintf (packet, sizeof(packet), "x0x%" PRIx64 ",0x%" PRIx64, (uint64_t)addr, (uint64_t)size);
3043 }
3044 else
3045 {
3046 packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
3047 }
Andy Gibbsa297a972013-06-19 19:04:53 +00003048 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003049 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003050 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003051 {
Greg Clayton576d8832011-03-22 04:00:09 +00003052 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003053 {
3054 error.Clear();
Jason Molenda6076bf42014-05-06 04:34:52 +00003055 if (binary_memory_read)
3056 {
3057 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any
3058 // 0x7d character escaping that was present in the packet
3059
3060 size_t data_received_size = response.GetBytesLeft();
3061 if (data_received_size > size)
3062 {
3063 // Don't write past the end of BUF if the remote debug server gave us too
3064 // much data for some reason.
3065 data_received_size = size;
3066 }
3067 memcpy (buf, response.GetStringRef().data(), data_received_size);
3068 return data_received_size;
3069 }
3070 else
3071 {
3072 return response.GetHexBytes(buf, size, '\xdd');
3073 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003074 }
Greg Clayton576d8832011-03-22 04:00:09 +00003075 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00003076 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00003077 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00003078 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003079 else
Greg Clayton9944cd72012-09-19 01:46:31 +00003080 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003081 }
3082 else
3083 {
Jim Ingham35579dd2013-06-03 19:34:01 +00003084 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003085 }
3086 return 0;
3087}
3088
3089size_t
3090ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
3091{
Jason Molenda6076bf42014-05-06 04:34:52 +00003092 GetMaxMemorySize ();
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00003093 if (size > m_max_memory_size)
3094 {
3095 // Keep memory read sizes down to a sane limit. This function will be
3096 // called multiple times in order to complete the task by
3097 // lldb_private::Process so it is ok to do this.
3098 size = m_max_memory_size;
3099 }
3100
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003101 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00003102 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Clayton7fb56d02011-02-01 01:31:41 +00003103 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003104 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003105 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003106 {
Greg Clayton576d8832011-03-22 04:00:09 +00003107 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003108 {
3109 error.Clear();
3110 return size;
3111 }
Greg Clayton576d8832011-03-22 04:00:09 +00003112 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00003113 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00003114 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00003115 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003116 else
Greg Clayton9944cd72012-09-19 01:46:31 +00003117 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 +00003118 }
3119 else
3120 {
Jim Ingham35579dd2013-06-03 19:34:01 +00003121 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003122 }
3123 return 0;
3124}
3125
3126lldb::addr_t
3127ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
3128{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003129 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_EXPRESSIONS));
Greg Clayton2a48f522011-05-14 01:50:35 +00003130 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
3131
Greg Clayton70b57652011-05-15 01:25:55 +00003132 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton2a48f522011-05-14 01:50:35 +00003133 switch (supported)
3134 {
3135 case eLazyBoolCalculate:
3136 case eLazyBoolYes:
3137 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
3138 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
3139 return allocated_addr;
3140
3141 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003142 // Call mmap() to create memory in the inferior..
3143 unsigned prot = 0;
3144 if (permissions & lldb::ePermissionsReadable)
3145 prot |= eMmapProtRead;
3146 if (permissions & lldb::ePermissionsWritable)
3147 prot |= eMmapProtWrite;
3148 if (permissions & lldb::ePermissionsExecutable)
3149 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00003150
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003151 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
3152 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
3153 m_addr_to_mmap_size[allocated_addr] = size;
3154 else
Todd Fialaaf245d12014-06-30 21:05:18 +00003155 {
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003156 allocated_addr = LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00003157 if (log)
3158 log->Printf ("ProcessGDBRemote::%s no direct stub support for memory allocation, and InferiorCallMmap also failed - is stub missing register context save/restore capability?", __FUNCTION__);
3159 }
Greg Clayton2a48f522011-05-14 01:50:35 +00003160 break;
3161 }
3162
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003163 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00003164 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003165 else
3166 error.Clear();
3167 return allocated_addr;
3168}
3169
3170Error
Greg Clayton46fb5582011-11-18 07:03:08 +00003171ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
3172 MemoryRegionInfo &region_info)
3173{
3174
3175 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
3176 return error;
3177}
3178
3179Error
Johnny Chen64637202012-05-23 21:09:52 +00003180ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
3181{
3182
3183 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
3184 return error;
3185}
3186
3187Error
Enrico Granataf04a2192012-07-13 23:18:48 +00003188ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
3189{
Jaydeep Patil725666c2015-08-13 03:46:01 +00003190 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after, GetTarget().GetArchitecture()));
Enrico Granataf04a2192012-07-13 23:18:48 +00003191 return error;
3192}
3193
3194Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003195ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
3196{
3197 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00003198 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
3199
3200 switch (supported)
3201 {
3202 case eLazyBoolCalculate:
3203 // We should never be deallocating memory without allocating memory
3204 // first so we should never get eLazyBoolCalculate
3205 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
3206 break;
3207
3208 case eLazyBoolYes:
3209 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00003210 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003211 break;
3212
3213 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003214 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00003215 {
3216 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003217 if (pos != m_addr_to_mmap_size.end() &&
3218 InferiorCallMunmap(this, addr, pos->second))
3219 m_addr_to_mmap_size.erase (pos);
3220 else
Daniel Malead01b2952012-11-29 21:49:15 +00003221 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003222 }
3223 break;
3224 }
3225
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003226 return error;
3227}
3228
3229
3230//------------------------------------------------------------------
3231// Process STDIO
3232//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003233size_t
3234ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
3235{
3236 if (m_stdio_communication.IsConnected())
3237 {
3238 ConnectionStatus status;
3239 m_stdio_communication.Write(src, src_len, status, NULL);
3240 }
Vince Harrondf3f00f2015-02-10 21:09:04 +00003241 else if (m_stdin_forward)
Vince Harrone0be4252015-02-06 18:32:57 +00003242 {
3243 m_gdb_comm.SendStdinNotification(src, src_len);
3244 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003245 return 0;
3246}
3247
3248Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003249ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003250{
3251 Error error;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003252 assert(bp_site != NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003253
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003254 // Get logging info
3255 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003256 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003257
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003258 // Get the breakpoint address
3259 const addr_t addr = bp_site->GetLoadAddress();
3260
3261 // Log that a breakpoint was requested
3262 if (log)
3263 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
3264
3265 // Breakpoint already exists and is enabled
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003266 if (bp_site->IsEnabled())
3267 {
3268 if (log)
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003269 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 +00003270 return error;
3271 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003272
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003273 // Get the software breakpoint trap opcode size
3274 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3275
3276 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
3277 // is supported by the remote stub. These are set to true by default, and later set to false
3278 // only after we receive an unimplemented response when sending a breakpoint packet. This means
3279 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
3280 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
3281 // indicates if the user specifically asked for hardware breakpoints. If true then we will
3282 // skip over software breakpoints.
3283 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
3284 {
3285 // Try to send off a software breakpoint packet ($Z0)
3286 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003287 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003288 // The breakpoint was placed successfully
3289 bp_site->SetEnabled(true);
3290 bp_site->SetType(BreakpointSite::eExternal);
Greg Claytoneb023e72013-10-11 19:48:25 +00003291 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003292 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003293
3294 // SendGDBStoppointTypePacket() will return an error if it was unable to set this
3295 // breakpoint. We need to differentiate between a error specific to placing this breakpoint
3296 // or if we have learned that this breakpoint type is unsupported. To do this, we
3297 // must test the support boolean for this breakpoint type to see if it now indicates that
3298 // this breakpoint type is unsupported. If they are still supported then we should return
3299 // with the error code. If they are now unsupported, then we would like to fall through
3300 // and try another form of breakpoint.
3301 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
3302 return error;
3303
3304 // We reach here when software breakpoints have been found to be unsupported. For future
3305 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
3306 // known not to be supported.
3307 if (log)
3308 log->Printf("Software breakpoints are unsupported");
3309
3310 // So we will fall through and try a hardware breakpoint
3311 }
3312
3313 // The process of setting a hardware breakpoint is much the same as above. We check the
3314 // supported boolean for this breakpoint type, and if it is thought to be supported then we
3315 // will try to set this breakpoint with a hardware breakpoint.
3316 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3317 {
3318 // Try to send off a hardware breakpoint packet ($Z1)
3319 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003320 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003321 // The breakpoint was placed successfully
3322 bp_site->SetEnabled(true);
3323 bp_site->SetType(BreakpointSite::eHardware);
3324 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003325 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003326
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003327 // Check if the error was something other then an unsupported breakpoint type
3328 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3329 {
3330 // Unable to set this hardware breakpoint
3331 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
3332 return error;
3333 }
3334
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003335 // We will reach here when the stub gives an unsupported response to a hardware breakpoint
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003336 if (log)
3337 log->Printf("Hardware breakpoints are unsupported");
3338
3339 // Finally we will falling through to a #trap style breakpoint
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003340 }
3341
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003342 // Don't fall through when hardware breakpoints were specifically requested
3343 if (bp_site->HardwareRequired())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003344 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003345 error.SetErrorString("hardware breakpoints are not supported");
3346 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003347 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003348
3349 // As a last resort we want to place a manual breakpoint. An instruction
3350 // is placed into the process memory using memory write packets.
3351 return EnableSoftwareBreakpoint(bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003352}
3353
3354Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003355ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003356{
3357 Error error;
3358 assert (bp_site != NULL);
3359 addr_t addr = bp_site->GetLoadAddress();
3360 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00003361 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003362 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003363 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003364
3365 if (bp_site->IsEnabled())
3366 {
3367 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
3368
Greg Clayton8b82f082011-04-12 05:54:46 +00003369 BreakpointSite::Type bp_type = bp_site->GetType();
3370 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003371 {
Greg Clayton8b82f082011-04-12 05:54:46 +00003372 case BreakpointSite::eSoftware:
3373 error = DisableSoftwareBreakpoint (bp_site);
3374 break;
3375
3376 case BreakpointSite::eHardware:
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003377 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003378 error.SetErrorToGenericError();
3379 break;
3380
3381 case BreakpointSite::eExternal:
Jim Inghama04ef752014-03-07 11:18:02 +00003382 {
3383 GDBStoppointType stoppoint_type;
3384 if (bp_site->IsHardware())
3385 stoppoint_type = eBreakpointHardware;
3386 else
3387 stoppoint_type = eBreakpointSoftware;
3388
3389 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003390 error.SetErrorToGenericError();
Jim Inghama04ef752014-03-07 11:18:02 +00003391 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003392 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003393 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003394 if (error.Success())
3395 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003396 }
3397 else
3398 {
3399 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003400 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 +00003401 return error;
3402 }
3403
3404 if (error.Success())
3405 error.SetErrorToGenericError();
3406 return error;
3407}
3408
Johnny Chen11309a32011-09-06 22:38:36 +00003409// Pre-requisite: wp != NULL.
3410static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00003411GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00003412{
3413 assert(wp);
3414 bool watch_read = wp->WatchpointRead();
3415 bool watch_write = wp->WatchpointWrite();
3416
3417 // watch_read and watch_write cannot both be false.
3418 assert(watch_read || watch_write);
3419 if (watch_read && watch_write)
3420 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00003421 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00003422 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00003423 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00003424 return eWatchpointWrite;
3425}
3426
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003427Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003428ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003429{
3430 Error error;
3431 if (wp)
3432 {
3433 user_id_t watchID = wp->GetID();
3434 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00003435 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003436 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003437 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003438 if (wp->IsEnabled())
3439 {
3440 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003441 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 +00003442 return error;
3443 }
Johnny Chen11309a32011-09-06 22:38:36 +00003444
3445 GDBStoppointType type = GetGDBStoppointType(wp);
3446 // Pass down an appropriate z/Z packet...
3447 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003448 {
Johnny Chen11309a32011-09-06 22:38:36 +00003449 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
3450 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003451 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003452 return error;
3453 }
3454 else
3455 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003456 }
Johnny Chen11309a32011-09-06 22:38:36 +00003457 else
3458 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003459 }
3460 else
3461 {
Johnny Chen01a67862011-10-14 00:42:25 +00003462 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003463 }
3464 if (error.Success())
3465 error.SetErrorToGenericError();
3466 return error;
3467}
3468
3469Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003470ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003471{
3472 Error error;
3473 if (wp)
3474 {
3475 user_id_t watchID = wp->GetID();
3476
Greg Clayton5160ce52013-03-27 23:08:40 +00003477 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003478
3479 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00003480
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003481 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003482 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003483
Johnny Chen11309a32011-09-06 22:38:36 +00003484 if (!wp->IsEnabled())
3485 {
3486 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003487 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 +00003488 // See also 'class WatchpointSentry' within StopInfo.cpp.
3489 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
3490 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00003491 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003492 return error;
3493 }
3494
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003495 if (wp->IsHardware())
3496 {
Johnny Chen11309a32011-09-06 22:38:36 +00003497 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003498 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00003499 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
3500 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003501 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003502 return error;
3503 }
3504 else
3505 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003506 }
3507 // TODO: clear software watchpoints if we implement them
3508 }
3509 else
3510 {
Johnny Chen01a67862011-10-14 00:42:25 +00003511 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003512 }
3513 if (error.Success())
3514 error.SetErrorToGenericError();
3515 return error;
3516}
3517
3518void
3519ProcessGDBRemote::Clear()
3520{
3521 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00003522 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003523 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003524}
3525
3526Error
3527ProcessGDBRemote::DoSignal (int signo)
3528{
3529 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00003530 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003531 if (log)
3532 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
3533
3534 if (!m_gdb_comm.SendAsyncSignal (signo))
3535 error.SetErrorStringWithFormat("failed to send signal %i", signo);
3536 return error;
3537}
3538
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003539Error
Greg Clayton91a9b2472013-12-04 19:19:12 +00003540ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003541{
3542 Error error;
3543 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
3544 {
3545 // If we locate debugserver, keep that located version around
3546 static FileSpec g_debugserver_file_spec;
3547
Han Ming Ong84647042012-02-25 01:07:38 +00003548 ProcessLaunchInfo debugserver_launch_info;
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00003549 // Make debugserver run in its own session so signals generated by
3550 // special terminal key sequences (^C) don't affect debugserver.
3551 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3552
Greg Clayton91a9b2472013-12-04 19:19:12 +00003553 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
3554 debugserver_launch_info.SetUserID(process_info.GetUserID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003555
Todd Fiala013434e2014-07-09 01:29:05 +00003556#if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__) || defined (__aarch64__))
Greg Claytonfda4fab2014-01-10 22:24:11 +00003557 // On iOS, still do a local connection using a random port
Greg Clayton16810922014-02-27 19:38:18 +00003558 const char *hostname = "127.0.0.1";
Greg Claytonfda4fab2014-01-10 22:24:11 +00003559 uint16_t port = get_random_port ();
3560#else
3561 // Set hostname being NULL to do the reverse connect where debugserver
3562 // will bind to port zero and it will communicate back to us the port
3563 // that we will connect to
3564 const char *hostname = NULL;
3565 uint16_t port = 0;
3566#endif
3567
3568 error = m_gdb_comm.StartDebugserverProcess (hostname,
3569 port,
Greg Clayton00fe87b2013-12-05 22:58:22 +00003570 debugserver_launch_info,
3571 port);
Greg Clayton91a9b2472013-12-04 19:19:12 +00003572
3573 if (error.Success ())
3574 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003575 else
Greg Clayton91a9b2472013-12-04 19:19:12 +00003576 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003577
3578 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3579 StartAsyncThread ();
Greg Clayton91a9b2472013-12-04 19:19:12 +00003580
3581 if (error.Fail())
3582 {
3583 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
3584
3585 if (log)
3586 log->Printf("failed to start debugserver process: %s", error.AsCString());
3587 return error;
3588 }
3589
Greg Clayton00fe87b2013-12-05 22:58:22 +00003590 if (m_gdb_comm.IsConnected())
3591 {
3592 // Finish the connection process by doing the handshake without connecting (send NULL URL)
3593 ConnectToDebugserver (NULL);
3594 }
3595 else
3596 {
Greg Claytonfda4fab2014-01-10 22:24:11 +00003597 StreamString connect_url;
3598 connect_url.Printf("connect://%s:%u", hostname, port);
3599 error = ConnectToDebugserver (connect_url.GetString().c_str());
Greg Clayton00fe87b2013-12-05 22:58:22 +00003600 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00003601
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003602 }
3603 return error;
3604}
3605
3606bool
3607ProcessGDBRemote::MonitorDebugserverProcess
3608(
3609 void *callback_baton,
3610 lldb::pid_t debugserver_pid,
Greg Claytone4e45922011-11-16 05:37:56 +00003611 bool exited, // True if the process did exit
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003612 int signo, // Zero for no signal
3613 int exit_status // Exit value of process if signal is zero
3614)
3615{
Greg Claytone4e45922011-11-16 05:37:56 +00003616 // The baton is a "ProcessGDBRemote *". Now this class might be gone
3617 // and might not exist anymore, so we need to carefully try to get the
3618 // target for this process first since we have a race condition when
3619 // we are done running between getting the notice that the inferior
3620 // process has died and the debugserver that was debugging this process.
3621 // In our test suite, we are also continually running process after
3622 // process, so we must be very careful to make sure:
3623 // 1 - process object hasn't been deleted already
3624 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003625
3626 // "debugserver_pid" argument passed in is the process ID for
3627 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00003628 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003629
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003630 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton6779606a2011-01-22 23:43:18 +00003631
Greg Claytone4e45922011-11-16 05:37:56 +00003632 // Get a shared pointer to the target that has a matching process pointer.
3633 // This target could be gone, or the target could already have a new process
3634 // object inside of it
3635 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
3636
Greg Clayton6779606a2011-01-22 23:43:18 +00003637 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003638 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 +00003639
Greg Claytone4e45922011-11-16 05:37:56 +00003640 if (target_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003641 {
Greg Claytone4e45922011-11-16 05:37:56 +00003642 // We found a process in a target that matches, but another thread
3643 // might be in the process of launching a new process that will
3644 // soon replace it, so get a shared pointer to the process so we
3645 // can keep it alive.
3646 ProcessSP process_sp (target_sp->GetProcessSP());
3647 // Now we have a shared pointer to the process that can't go away on us
3648 // so we now make sure it was the same as the one passed in, and also make
3649 // sure that our previous "process *" didn't get deleted and have a new
3650 // "process *" created in its place with the same pointer. To verify this
3651 // we make sure the process has our debugserver process ID. If we pass all
3652 // of these tests, then we are sure that this process is the one we were
3653 // looking for.
3654 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003655 {
Greg Claytone4e45922011-11-16 05:37:56 +00003656 // Sleep for a half a second to make sure our inferior process has
3657 // time to set its exit status before we set it incorrectly when
3658 // both the debugserver and the inferior process shut down.
3659 usleep (500000);
3660 // If our process hasn't yet exited, debugserver might have died.
3661 // If the process did exit, the we are reaping it.
3662 const StateType state = process->GetState();
3663
3664 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
3665 state != eStateInvalid &&
3666 state != eStateUnloaded &&
3667 state != eStateExited &&
3668 state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003669 {
Greg Claytone4e45922011-11-16 05:37:56 +00003670 char error_str[1024];
3671 if (signo)
3672 {
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00003673 const char *signal_cstr = process->GetUnixSignals()->GetSignalAsCString(signo);
Greg Claytone4e45922011-11-16 05:37:56 +00003674 if (signal_cstr)
3675 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3676 else
3677 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
3678 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003679 else
Greg Claytone4e45922011-11-16 05:37:56 +00003680 {
3681 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
3682 }
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003683
Greg Claytone4e45922011-11-16 05:37:56 +00003684 process->SetExitStatus (-1, error_str);
3685 }
3686 // Debugserver has exited we need to let our ProcessGDBRemote
3687 // know that it no longer has a debugserver instance
3688 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003689 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003690 }
3691 return true;
3692}
3693
3694void
3695ProcessGDBRemote::KillDebugserverProcess ()
3696{
Greg Claytonfbb76342013-11-20 21:07:01 +00003697 m_gdb_comm.Disconnect();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003698 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3699 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003700 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003701 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3702 }
3703}
3704
3705void
3706ProcessGDBRemote::Initialize()
3707{
Davide Italianoc8d69822015-04-03 04:24:32 +00003708 static std::once_flag g_once_flag;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003709
Davide Italianoc8d69822015-04-03 04:24:32 +00003710 std::call_once(g_once_flag, []()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003711 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003712 PluginManager::RegisterPlugin (GetPluginNameStatic(),
3713 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00003714 CreateInstance,
3715 DebuggerInitialize);
Davide Italianoc8d69822015-04-03 04:24:32 +00003716 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003717}
3718
Greg Clayton7f982402013-07-15 22:54:20 +00003719void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003720ProcessGDBRemote::DebuggerInitialize (Debugger &debugger)
Greg Clayton7f982402013-07-15 22:54:20 +00003721{
3722 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
3723 {
3724 const bool is_global_setting = true;
3725 PluginManager::CreateSettingForProcessPlugin (debugger,
3726 GetGlobalPluginProperties()->GetValueProperties(),
3727 ConstString ("Properties for the gdb-remote process plug-in."),
3728 is_global_setting);
3729 }
3730}
3731
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003732bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003733ProcessGDBRemote::StartAsyncThread ()
3734{
Greg Clayton5160ce52013-03-27 23:08:40 +00003735 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003736
3737 if (log)
3738 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003739
3740 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003741 if (!m_async_thread.IsJoinable())
Jim Ingham455fa5c2012-11-01 01:15:33 +00003742 {
3743 // Create a thread that watches our internal state and controls which
3744 // events make it to clients (into the DCProcess event queue).
Zachary Turner39de3112014-09-09 20:54:56 +00003745
3746 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003747 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003748 else if (log)
3749 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was already running.", __FUNCTION__);
Zachary Turner39de3112014-09-09 20:54:56 +00003750
Zachary Turneracee96a2014-09-23 18:32:09 +00003751 return m_async_thread.IsJoinable();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003752}
3753
3754void
3755ProcessGDBRemote::StopAsyncThread ()
3756{
Greg Clayton5160ce52013-03-27 23:08:40 +00003757 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003758
3759 if (log)
3760 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
3761
Jim Ingham455fa5c2012-11-01 01:15:33 +00003762 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003763 if (m_async_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003764 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00003765 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
3766
3767 // This will shut down the async thread.
3768 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3769
3770 // Stop the stdio thread
Zachary Turner39de3112014-09-09 20:54:56 +00003771 m_async_thread.Join(nullptr);
Pavel Labatha55a9532015-03-11 09:53:42 +00003772 m_async_thread.Reset();
Jim Ingham455fa5c2012-11-01 01:15:33 +00003773 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003774 else if (log)
3775 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003776}
3777
Ewan Crawford76df2882015-06-23 12:32:06 +00003778bool
3779ProcessGDBRemote::HandleNotifyPacket (StringExtractorGDBRemote &packet)
3780{
3781 // get the packet at a string
3782 const std::string &pkt = packet.GetStringRef();
3783 // skip %stop:
3784 StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
3785
3786 // pass as a thread stop info packet
3787 SetLastStopPacket(stop_info);
3788
3789 // check for more stop reasons
3790 HandleStopReplySequence();
3791
3792 // if the process is stopped then we need to fake a resume
3793 // so that we can stop properly with the new break. This
3794 // is possible due to SetPrivateState() broadcasting the
3795 // state change as a side effect.
3796 if (GetPrivateState() == lldb::StateType::eStateStopped)
3797 {
3798 SetPrivateState(lldb::StateType::eStateRunning);
3799 }
3800
3801 // since we have some stopped packets we can halt the process
3802 SetPrivateState(lldb::StateType::eStateStopped);
3803
3804 return true;
3805}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003806
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003807thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003808ProcessGDBRemote::AsyncThread (void *arg)
3809{
3810 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
3811
Greg Clayton5160ce52013-03-27 23:08:40 +00003812 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003813 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003814 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003815
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003816 EventSP event_sp;
Pavel Labath50556852015-09-03 09:36:22 +00003817 bool done = false;
3818 while (!done)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003819 {
Pavel Labath50556852015-09-03 09:36:22 +00003820 if (log)
3821 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
3822 if (process->m_async_listener.WaitForEvent (NULL, event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003823 {
Pavel Labath50556852015-09-03 09:36:22 +00003824 const uint32_t event_type = event_sp->GetType();
3825 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003826 {
3827 if (log)
Pavel Labath50556852015-09-03 09:36:22 +00003828 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
3829
3830 switch (event_type)
3831 {
3832 case eBroadcastBitAsyncContinue:
3833 {
3834 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
3835
3836 if (continue_packet)
3837 {
3838 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
3839 const size_t continue_cstr_len = continue_packet->GetByteSize ();
3840 if (log)
3841 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
3842
3843 if (::strstr (continue_cstr, "vAttach") == NULL)
3844 process->SetPrivateState(eStateRunning);
3845 StringExtractorGDBRemote response;
3846
3847 // If in Non-Stop-Mode
3848 if (process->GetTarget().GetNonStopModeEnabled())
3849 {
3850 // send the vCont packet
3851 if (!process->GetGDBRemote().SendvContPacket(process, continue_cstr, continue_cstr_len, response))
3852 {
3853 // Something went wrong
3854 done = true;
3855 break;
3856 }
3857 }
3858 // If in All-Stop-Mode
3859 else
3860 {
3861 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
3862
3863 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
3864 // The thread ID list might be contained within the "response", or the stop reply packet that
3865 // caused the stop. So clear it now before we give the stop reply packet to the process
3866 // using the process->SetLastStopPacket()...
3867 process->ClearThreadIDList ();
3868
3869 switch (stop_state)
3870 {
3871 case eStateStopped:
3872 case eStateCrashed:
3873 case eStateSuspended:
3874 process->SetLastStopPacket (response);
3875 process->SetPrivateState (stop_state);
3876 break;
3877
3878 case eStateExited:
3879 {
3880 process->SetLastStopPacket (response);
3881 process->ClearThreadIDList();
3882 response.SetFilePos(1);
3883
3884 int exit_status = response.GetHexU8();
3885 const char *desc_cstr = NULL;
3886 StringExtractor extractor;
3887 std::string desc_string;
3888 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';')
3889 {
3890 std::string desc_token;
3891 while (response.GetNameColonValue (desc_token, desc_string))
3892 {
3893 if (desc_token == "description")
3894 {
3895 extractor.GetStringRef().swap(desc_string);
3896 extractor.SetFilePos(0);
3897 extractor.GetHexByteString (desc_string);
3898 desc_cstr = desc_string.c_str();
3899 }
3900 }
3901 }
3902 process->SetExitStatus(exit_status, desc_cstr);
3903 done = true;
3904 break;
3905 }
3906 case eStateInvalid:
3907 {
3908 // Check to see if we were trying to attach and if we got back
3909 // the "E87" error code from debugserver -- this indicates that
3910 // the process is not debuggable. Return a slightly more helpful
3911 // error message about why the attach failed.
3912 if (::strstr (continue_cstr, "vAttach") != NULL
3913 && response.GetError() == 0x87)
3914 {
3915 process->SetExitStatus(-1, "cannot attach to process due to System Integrity Protection");
3916 }
3917 // E01 code from vAttach means that the attach failed
3918 if (::strstr (continue_cstr, "vAttach") != NULL
3919 && response.GetError() == 0x1)
3920 {
3921 process->SetExitStatus(-1, "unable to attach");
3922 }
3923 else
3924 {
3925 process->SetExitStatus(-1, "lost connection");
3926 }
3927 break;
3928 }
3929
3930 default:
3931 process->SetPrivateState (stop_state);
3932 break;
3933 } // switch(stop_state)
3934 } // else // if in All-stop-mode
3935 } // if (continue_packet)
3936 } // case eBroadcastBitAysncContinue
3937 break;
3938
3939 case eBroadcastBitAsyncThreadShouldExit:
3940 if (log)
3941 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
3942 done = true;
3943 break;
3944
3945 default:
3946 if (log)
3947 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
3948 done = true;
3949 break;
3950 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003951 }
Pavel Labath50556852015-09-03 09:36:22 +00003952 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
3953 {
3954 switch (event_type)
3955 {
3956 case Communication::eBroadcastBitReadThreadDidExit:
3957 process->SetExitStatus (-1, "lost connection");
3958 done = true;
3959 break;
3960
3961 case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify:
3962 {
3963 lldb_private::Event *event = event_sp.get();
3964 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event);
3965 StringExtractorGDBRemote notify((const char*)continue_packet->GetBytes());
3966 // Hand this over to the process to handle
3967 process->HandleNotifyPacket(notify);
3968 break;
3969 }
3970
3971 default:
3972 if (log)
3973 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
3974 done = true;
3975 break;
3976 }
3977 }
3978 }
3979 else
3980 {
3981 if (log)
3982 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
3983 done = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003984 }
3985 }
3986
3987 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003988 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003989
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003990 return NULL;
3991}
3992
Greg Claytone996fd32011-03-08 22:40:15 +00003993//uint32_t
3994//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3995//{
3996// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
3997// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
3998// if (m_local_debugserver)
3999// {
4000// return Host::ListProcessesMatchingName (name, matches, pids);
4001// }
4002// else
4003// {
4004// // FIXME: Implement talking to the remote debugserver.
4005// return 0;
4006// }
4007//
4008//}
4009//
Jim Ingham1c823b42011-01-22 01:33:44 +00004010bool
4011ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004012 StoppointCallbackContext *context,
Jim Ingham1c823b42011-01-22 01:33:44 +00004013 lldb::user_id_t break_id,
4014 lldb::user_id_t break_loc_id)
4015{
4016 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
4017 // run so I can stop it if that's what I want to do.
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004018 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00004019 if (log)
4020 log->Printf("Hit New Thread Notification breakpoint.");
4021 return false;
4022}
4023
4024
4025bool
4026ProcessGDBRemote::StartNoticingNewThreads()
4027{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004028 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00004029 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00004030 {
Greg Clayton4116e932012-05-15 02:33:01 +00004031 if (log && log->GetVerbose())
4032 log->Printf("Enabled noticing new thread breakpoint.");
4033 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00004034 }
Greg Clayton4116e932012-05-15 02:33:01 +00004035 else
Jim Ingham1c823b42011-01-22 01:33:44 +00004036 {
Zachary Turner7529df92015-09-01 20:02:29 +00004037 PlatformSP platform_sp (GetTarget().GetPlatform());
Greg Clayton4116e932012-05-15 02:33:01 +00004038 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00004039 {
Zachary Turner7529df92015-09-01 20:02:29 +00004040 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(GetTarget());
Greg Clayton4116e932012-05-15 02:33:01 +00004041 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00004042 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00004043 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00004044 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
4045 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00004046 }
4047 else
4048 {
4049 if (log)
4050 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00004051 }
4052 }
4053 }
Greg Clayton4116e932012-05-15 02:33:01 +00004054 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00004055}
4056
4057bool
4058ProcessGDBRemote::StopNoticingNewThreads()
4059{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004060 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00004061 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00004062 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00004063
4064 if (m_thread_create_bp_sp)
4065 m_thread_create_bp_sp->SetEnabled(false);
4066
Jim Ingham1c823b42011-01-22 01:33:44 +00004067 return true;
4068}
4069
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004070DynamicLoader *
Jason Molenda5e8534e2012-10-03 01:29:34 +00004071ProcessGDBRemote::GetDynamicLoader ()
4072{
4073 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00004074 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00004075 return m_dyld_ap.get();
4076}
Jim Ingham1c823b42011-01-22 01:33:44 +00004077
Jason Molendaa3329782014-03-29 18:54:20 +00004078Error
4079ProcessGDBRemote::SendEventData(const char *data)
4080{
4081 int return_value;
4082 bool was_supported;
4083
4084 Error error;
4085
4086 return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported);
4087 if (return_value != 0)
4088 {
4089 if (!was_supported)
4090 error.SetErrorString("Sending events is not supported for this process.");
4091 else
4092 error.SetErrorStringWithFormat("Error sending event data: %d.", return_value);
4093 }
4094 return error;
4095}
4096
Steve Pucci03904ac2014-03-04 23:18:46 +00004097const DataBufferSP
4098ProcessGDBRemote::GetAuxvData()
4099{
4100 DataBufferSP buf;
4101 if (m_gdb_comm.GetQXferAuxvReadSupported())
4102 {
4103 std::string response_string;
4104 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success)
4105 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length()));
4106 }
4107 return buf;
4108}
4109
Jason Molenda705b1802014-06-13 02:37:02 +00004110StructuredData::ObjectSP
4111ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid)
4112{
4113 StructuredData::ObjectSP object_sp;
4114
4115 if (m_gdb_comm.GetThreadExtendedInfoSupported())
4116 {
4117 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4118 SystemRuntime *runtime = GetSystemRuntime();
4119 if (runtime)
4120 {
4121 runtime->AddThreadExtendedInfoPacketHints (args_dict);
4122 }
4123 args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid);
4124
4125 StreamString packet;
4126 packet << "jThreadExtendedInfo:";
4127 args_dict->Dump (packet);
4128
4129 // FIXME the final character of a JSON dictionary, '}', is the escape
4130 // character in gdb-remote binary mode. lldb currently doesn't escape
4131 // these characters in its packet output -- so we add the quoted version
4132 // of the } character here manually in case we talk to a debugserver which
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004133 // un-escapes the characters at packet read time.
Jason Molenda705b1802014-06-13 02:37:02 +00004134 packet << (char) (0x7d ^ 0x20);
4135
4136 StringExtractorGDBRemote response;
4137 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4138 {
4139 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4140 if (response_type == StringExtractorGDBRemote::eResponse)
4141 {
4142 if (!response.Empty())
4143 {
Jason Molenda20ee21b2015-07-10 23:15:22 +00004144 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4145 }
4146 }
4147 }
4148 }
4149 return object_sp;
4150}
4151
4152StructuredData::ObjectSP
4153ProcessGDBRemote::GetLoadedDynamicLibrariesInfos (lldb::addr_t image_list_address, lldb::addr_t image_count)
4154{
4155 StructuredData::ObjectSP object_sp;
4156
4157 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported())
4158 {
4159 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4160 args_dict->GetAsDictionary()->AddIntegerItem ("image_list_address", image_list_address);
4161 args_dict->GetAsDictionary()->AddIntegerItem ("image_count", image_count);
4162
4163 StreamString packet;
4164 packet << "jGetLoadedDynamicLibrariesInfos:";
4165 args_dict->Dump (packet);
4166
4167 // FIXME the final character of a JSON dictionary, '}', is the escape
4168 // character in gdb-remote binary mode. lldb currently doesn't escape
4169 // these characters in its packet output -- so we add the quoted version
4170 // of the } character here manually in case we talk to a debugserver which
4171 // un-escapes the characters at packet read time.
4172 packet << (char) (0x7d ^ 0x20);
4173
4174 StringExtractorGDBRemote response;
4175 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4176 {
4177 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4178 if (response_type == StringExtractorGDBRemote::eResponse)
4179 {
4180 if (!response.Empty())
4181 {
Jason Molenda705b1802014-06-13 02:37:02 +00004182 // The packet has already had the 0x7d xor quoting stripped out at the
4183 // GDBRemoteCommunication packet receive level.
4184 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4185 }
4186 }
4187 }
4188 }
4189 return object_sp;
4190}
4191
Jason Molenda20ee21b2015-07-10 23:15:22 +00004192
Jason Molenda6076bf42014-05-06 04:34:52 +00004193// Establish the largest memory read/write payloads we should use.
4194// If the remote stub has a max packet size, stay under that size.
4195//
4196// If the remote stub's max packet size is crazy large, use a
4197// reasonable largeish default.
4198//
4199// If the remote stub doesn't advertise a max packet size, use a
4200// conservative default.
4201
4202void
4203ProcessGDBRemote::GetMaxMemorySize()
4204{
4205 const uint64_t reasonable_largeish_default = 128 * 1024;
4206 const uint64_t conservative_default = 512;
4207
4208 if (m_max_memory_size == 0)
4209 {
4210 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4211 if (stub_max_size != UINT64_MAX && stub_max_size != 0)
4212 {
4213 // Save the stub's claimed maximum packet size
4214 m_remote_stub_max_memory_size = stub_max_size;
4215
4216 // Even if the stub says it can support ginormous packets,
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004217 // don't exceed our reasonable largeish default packet size.
Jason Molenda6076bf42014-05-06 04:34:52 +00004218 if (stub_max_size > reasonable_largeish_default)
4219 {
4220 stub_max_size = reasonable_largeish_default;
4221 }
4222
4223 m_max_memory_size = stub_max_size;
4224 }
4225 else
4226 {
4227 m_max_memory_size = conservative_default;
4228 }
4229 }
4230}
4231
4232void
4233ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max)
4234{
4235 if (user_specified_max != 0)
4236 {
4237 GetMaxMemorySize ();
4238
4239 if (m_remote_stub_max_memory_size != 0)
4240 {
4241 if (m_remote_stub_max_memory_size < user_specified_max)
4242 {
4243 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a packet size too big, go as big
4244 // as the remote stub says we can go.
4245 }
4246 else
4247 {
4248 m_max_memory_size = user_specified_max; // user's packet size is good
4249 }
4250 }
4251 else
4252 {
4253 m_max_memory_size = user_specified_max; // user's packet size is probably fine
4254 }
4255 }
4256}
4257
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004258bool
4259ProcessGDBRemote::GetModuleSpec(const FileSpec& module_file_spec,
4260 const ArchSpec& arch,
4261 ModuleSpec &module_spec)
4262{
4263 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PLATFORM);
4264
4265 if (!m_gdb_comm.GetModuleInfo (module_file_spec, arch, module_spec))
4266 {
4267 if (log)
4268 log->Printf ("ProcessGDBRemote::%s - failed to get module info for %s:%s",
4269 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4270 arch.GetTriple ().getTriple ().c_str ());
4271 return false;
4272 }
4273
4274 if (log)
4275 {
4276 StreamString stream;
4277 module_spec.Dump (stream);
4278 log->Printf ("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4279 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4280 arch.GetTriple ().getTriple ().c_str (), stream.GetString ().c_str ());
4281 }
4282
4283 return true;
4284}
4285
Colin Rileyc3c95b22015-04-16 15:51:33 +00004286namespace {
4287
4288typedef std::vector<std::string> stringVec;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004289
4290typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004291struct RegisterSetInfo
4292{
4293 ConstString name;
4294};
Colin Rileyc3c95b22015-04-16 15:51:33 +00004295
Greg Claytond04f0ed2015-05-26 18:00:51 +00004296typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4297
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004298struct GdbServerTargetInfo
4299{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004300 std::string arch;
4301 std::string osabi;
4302 stringVec includes;
4303 RegisterSetMap reg_set_map;
4304 XMLNode feature_node;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004305};
Greg Claytond04f0ed2015-05-26 18:00:51 +00004306
Colin Rileyc3c95b22015-04-16 15:51:33 +00004307bool
Jason Molenda21586c82015-09-09 03:36:24 +00004308ParseRegisters (XMLNode feature_node, GdbServerTargetInfo &target_info, GDBRemoteDynamicRegisterInfo &dyn_reg_info, ABISP abi_sp)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004309{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004310 if (!feature_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004311 return false;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004312
Jason Molenda63bd0db2015-09-15 23:20:34 +00004313 uint32_t cur_reg_num = 0;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004314 uint32_t reg_offset = 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004315
Jason Molenda63bd0db2015-09-15 23:20:34 +00004316 feature_node.ForEachChildElementWithName("reg", [&target_info, &dyn_reg_info, &cur_reg_num, &reg_offset, &abi_sp](const XMLNode &reg_node) -> bool {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004317 std::string gdb_group;
4318 std::string gdb_type;
4319 ConstString reg_name;
4320 ConstString alt_name;
4321 ConstString set_name;
4322 std::vector<uint32_t> value_regs;
4323 std::vector<uint32_t> invalidate_regs;
4324 bool encoding_set = false;
4325 bool format_set = false;
4326 RegisterInfo reg_info = { NULL, // Name
4327 NULL, // Alt name
4328 0, // byte size
4329 reg_offset, // offset
4330 eEncodingUint, // encoding
Jason Molendabf67a302015-09-01 05:17:01 +00004331 eFormatHex, // format
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004332 {
Jason Molendabf67a302015-09-01 05:17:01 +00004333 LLDB_INVALID_REGNUM, // eh_frame reg num
Greg Claytond04f0ed2015-05-26 18:00:51 +00004334 LLDB_INVALID_REGNUM, // DWARF reg num
4335 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda63bd0db2015-09-15 23:20:34 +00004336 cur_reg_num, // process plugin reg num
4337 cur_reg_num // native register number
Greg Claytond04f0ed2015-05-26 18:00:51 +00004338 },
4339 NULL,
4340 NULL
4341 };
4342
Jason Molenda63bd0db2015-09-15 23:20:34 +00004343 reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type, &reg_name, &alt_name, &set_name, &value_regs, &invalidate_regs, &encoding_set, &format_set, &reg_info, &cur_reg_num, &reg_offset](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004344 if (name == "name")
4345 {
4346 reg_name.SetString(value);
4347 }
4348 else if (name == "bitsize")
4349 {
4350 reg_info.byte_size = StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
4351 }
4352 else if (name == "type")
4353 {
4354 gdb_type = value.str();
4355 }
4356 else if (name == "group")
4357 {
4358 gdb_group = value.str();
4359 }
4360 else if (name == "regnum")
4361 {
4362 const uint32_t regnum = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4363 if (regnum != LLDB_INVALID_REGNUM)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004364 {
Jason Molenda63bd0db2015-09-15 23:20:34 +00004365 reg_info.kinds[eRegisterKindProcessPlugin] = regnum;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004366 }
4367 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004368 else if (name == "offset")
4369 {
4370 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4371 }
4372 else if (name == "altname")
4373 {
4374 alt_name.SetString(value);
4375 }
4376 else if (name == "encoding")
4377 {
4378 encoding_set = true;
4379 reg_info.encoding = Args::StringToEncoding (value.data(), eEncodingUint);
4380 }
4381 else if (name == "format")
4382 {
4383 format_set = true;
4384 Format format = eFormatInvalid;
4385 if (Args::StringToFormat (value.data(), format, NULL).Success())
4386 reg_info.format = format;
4387 else if (value == "vector-sint8")
4388 reg_info.format = eFormatVectorOfSInt8;
4389 else if (value == "vector-uint8")
4390 reg_info.format = eFormatVectorOfUInt8;
4391 else if (value == "vector-sint16")
4392 reg_info.format = eFormatVectorOfSInt16;
4393 else if (value == "vector-uint16")
4394 reg_info.format = eFormatVectorOfUInt16;
4395 else if (value == "vector-sint32")
4396 reg_info.format = eFormatVectorOfSInt32;
4397 else if (value == "vector-uint32")
4398 reg_info.format = eFormatVectorOfUInt32;
4399 else if (value == "vector-float32")
4400 reg_info.format = eFormatVectorOfFloat32;
4401 else if (value == "vector-uint128")
4402 reg_info.format = eFormatVectorOfUInt128;
4403 }
4404 else if (name == "group_id")
4405 {
4406 const uint32_t set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4407 RegisterSetMap::const_iterator pos = target_info.reg_set_map.find(set_id);
4408 if (pos != target_info.reg_set_map.end())
4409 set_name = pos->second.name;
4410 }
Jason Molendaa18f7072015-08-15 01:21:01 +00004411 else if (name == "gcc_regnum" || name == "ehframe_regnum")
Greg Claytond04f0ed2015-05-26 18:00:51 +00004412 {
Jason Molendaa18f7072015-08-15 01:21:01 +00004413 reg_info.kinds[eRegisterKindEHFrame] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004414 }
4415 else if (name == "dwarf_regnum")
4416 {
4417 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4418 }
4419 else if (name == "generic")
4420 {
4421 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister(value.data());
4422 }
4423 else if (name == "value_regnums")
4424 {
4425 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
4426 }
4427 else if (name == "invalidate_regnums")
4428 {
4429 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
4430 }
4431 else
4432 {
4433 printf("unhandled attribute %s = %s\n", name.data(), value.data());
4434 }
4435 return true; // Keep iterating through all attributes
4436 });
4437
4438 if (!gdb_type.empty() && !(encoding_set || format_set))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004439 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004440 if (gdb_type.find("int") == 0)
4441 {
4442 reg_info.format = eFormatHex;
4443 reg_info.encoding = eEncodingUint;
4444 }
4445 else if (gdb_type == "data_ptr" || gdb_type == "code_ptr")
4446 {
4447 reg_info.format = eFormatAddressInfo;
4448 reg_info.encoding = eEncodingUint;
4449 }
4450 else if (gdb_type == "i387_ext" || gdb_type == "float")
4451 {
4452 reg_info.format = eFormatFloat;
4453 reg_info.encoding = eEncodingIEEE754;
4454 }
Colin Rileyc3c95b22015-04-16 15:51:33 +00004455 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004456
4457 // Only update the register set name if we didn't get a "reg_set" attribute.
4458 // "set_name" will be empty if we didn't have a "reg_set" attribute.
4459 if (!set_name && !gdb_group.empty())
4460 set_name.SetCString(gdb_group.c_str());
4461
4462 reg_info.byte_offset = reg_offset;
4463 assert (reg_info.byte_size != 0);
4464 reg_offset += reg_info.byte_size;
4465 if (!value_regs.empty())
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004466 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004467 value_regs.push_back(LLDB_INVALID_REGNUM);
4468 reg_info.value_regs = value_regs.data();
Colin Rileyc3c95b22015-04-16 15:51:33 +00004469 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004470 if (!invalidate_regs.empty())
4471 {
4472 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
4473 reg_info.invalidate_regs = invalidate_regs.data();
4474 }
4475
Jason Molenda63bd0db2015-09-15 23:20:34 +00004476 ++cur_reg_num;
Jason Molenda21586c82015-09-09 03:36:24 +00004477 AugmentRegisterInfoViaABI (reg_info, reg_name, abi_sp);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004478 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
4479
4480 return true; // Keep iterating through all "reg" elements
4481 });
Colin Rileyc3c95b22015-04-16 15:51:33 +00004482 return true;
4483}
Greg Claytond04f0ed2015-05-26 18:00:51 +00004484
Colin Rileyc3c95b22015-04-16 15:51:33 +00004485} // namespace {}
4486
Colin Rileyc3c95b22015-04-16 15:51:33 +00004487
4488// query the target of gdb-remote for extended target information
4489// return: 'true' on success
4490// 'false' on failure
4491bool
Aidan Doddsc0c83852015-05-08 09:36:31 +00004492ProcessGDBRemote::GetGDBServerRegisterInfo ()
Colin Rileyc3c95b22015-04-16 15:51:33 +00004493{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004494 // Make sure LLDB has an XML parser it can use first
4495 if (!XMLDocument::XMLEnabled())
4496 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004497
4498 // redirect libxml2's error handler since the default prints to stdout
Colin Rileyc3c95b22015-04-16 15:51:33 +00004499
4500 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004501
4502 // check that we have extended feature read support
4503 if ( !comm.GetQXferFeaturesReadSupported( ) )
4504 return false;
4505
4506 // request the target xml file
4507 std::string raw;
4508 lldb_private::Error lldberr;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004509 if (!comm.ReadExtFeature(ConstString("features"),
4510 ConstString("target.xml"),
4511 raw,
4512 lldberr))
4513 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00004514 return false;
4515 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004516
Colin Rileyc3c95b22015-04-16 15:51:33 +00004517
Greg Claytond04f0ed2015-05-26 18:00:51 +00004518 XMLDocument xml_document;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004519
Greg Claytond04f0ed2015-05-26 18:00:51 +00004520 if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml"))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004521 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004522 GdbServerTargetInfo target_info;
4523
4524 XMLNode target_node = xml_document.GetRootElement("target");
4525 if (target_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004526 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004527 XMLNode feature_node;
4528 target_node.ForEachChildElement([&target_info, this, &feature_node](const XMLNode &node) -> bool
4529 {
4530 llvm::StringRef name = node.GetName();
4531 if (name == "architecture")
4532 {
4533 node.GetElementText(target_info.arch);
4534 }
4535 else if (name == "osabi")
4536 {
4537 node.GetElementText(target_info.osabi);
4538 }
Ewan Crawford682e8422015-06-26 09:38:27 +00004539 else if (name == "xi:include" || name == "include")
Greg Claytond04f0ed2015-05-26 18:00:51 +00004540 {
4541 llvm::StringRef href = node.GetAttributeValue("href");
4542 if (!href.empty())
4543 target_info.includes.push_back(href.str());
4544 }
4545 else if (name == "feature")
4546 {
4547 feature_node = node;
4548 }
4549 else if (name == "groups")
4550 {
4551 node.ForEachChildElementWithName("group", [&target_info](const XMLNode &node) -> bool {
4552 uint32_t set_id = UINT32_MAX;
4553 RegisterSetInfo set_info;
4554
4555 node.ForEachAttribute([&set_id, &set_info](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
4556 if (name == "id")
4557 set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4558 if (name == "name")
4559 set_info.name = ConstString(value);
4560 return true; // Keep iterating through all attributes
4561 });
4562
4563 if (set_id != UINT32_MAX)
4564 target_info.reg_set_map[set_id] = set_info;
4565 return true; // Keep iterating through all "group" elements
4566 });
4567 }
4568 return true; // Keep iterating through all children of the target_node
4569 });
4570
4571 if (feature_node)
4572 {
Jason Molenda21586c82015-09-09 03:36:24 +00004573 ParseRegisters(feature_node, target_info, this->m_register_info, GetABI());
Greg Claytond04f0ed2015-05-26 18:00:51 +00004574 }
4575
4576 for (const auto &include : target_info.includes)
4577 {
4578 // request register file
4579 std::string xml_data;
4580 if (!comm.ReadExtFeature(ConstString("features"),
4581 ConstString(include),
4582 xml_data,
4583 lldberr))
4584 continue;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004585
Greg Claytond04f0ed2015-05-26 18:00:51 +00004586 XMLDocument include_xml_document;
4587 include_xml_document.ParseMemory(xml_data.data(), xml_data.size(), include.c_str());
4588 XMLNode include_feature_node = include_xml_document.GetRootElement("feature");
4589 if (include_feature_node)
4590 {
Jason Molenda21586c82015-09-09 03:36:24 +00004591 ParseRegisters(include_feature_node, target_info, this->m_register_info, GetABI());
Greg Claytond04f0ed2015-05-26 18:00:51 +00004592 }
4593 }
4594 this->m_register_info.Finalize(GetTarget().GetArchitecture());
Colin Rileyc3c95b22015-04-16 15:51:33 +00004595 }
4596 }
4597
Greg Claytond04f0ed2015-05-26 18:00:51 +00004598 return m_register_info.GetNumRegisters() > 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004599}
4600
Aidan Doddsc0c83852015-05-08 09:36:31 +00004601Error
4602ProcessGDBRemote::GetLoadedModuleList (GDBLoadedModuleInfoList & list)
4603{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004604 // Make sure LLDB has an XML parser it can use first
4605 if (!XMLDocument::XMLEnabled())
4606 return Error (0, ErrorType::eErrorTypeGeneric);
4607
Aidan Doddsc0c83852015-05-08 09:36:31 +00004608 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS);
4609 if (log)
4610 log->Printf ("ProcessGDBRemote::%s", __FUNCTION__);
4611
Aidan Doddsc0c83852015-05-08 09:36:31 +00004612 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004613
4614 // check that we have extended feature read support
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004615 if (comm.GetQXferLibrariesSVR4ReadSupported ()) {
4616 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004617
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004618 // request the loaded library list
4619 std::string raw;
4620 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004621
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004622 if (!comm.ReadExtFeature (ConstString ("libraries-svr4"), ConstString (""), raw, lldberr))
4623 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004624
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004625 // parse the xml file in memory
4626 if (log)
4627 log->Printf ("parsing: %s", raw.c_str());
4628 XMLDocument doc;
4629
4630 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4631 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004632
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004633 XMLNode root_element = doc.GetRootElement("library-list-svr4");
4634 if (!root_element)
4635 return Error();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004636
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004637 // main link map structure
4638 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4639 if (!main_lm.empty())
4640 {
4641 list.m_link_map = StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
4642 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004643
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004644 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
Aidan Doddsc0c83852015-05-08 09:36:31 +00004645
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004646 GDBLoadedModuleInfoList::LoadedModuleInfo module;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004647
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004648 library.ForEachAttribute([log, &module](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004649
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004650 if (name == "name")
4651 module.set_name (value.str());
4652 else if (name == "lm")
4653 {
4654 // the address of the link_map struct.
4655 module.set_link_map(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4656 }
4657 else if (name == "l_addr")
4658 {
4659 // the displacement as read from the field 'l_addr' of the link_map struct.
4660 module.set_base(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
Stephane Sezerc6845a02015-08-20 22:07:48 +00004661 // base address is always a displacement, not an absolute value.
4662 module.set_base_is_offset(true);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004663 }
4664 else if (name == "l_ld")
4665 {
4666 // the memory address of the libraries PT_DYAMIC section.
4667 module.set_dynamic(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4668 }
4669
4670 return true; // Keep iterating over all properties of "library"
4671 });
4672
4673 if (log)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004674 {
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004675 std::string name;
4676 lldb::addr_t lm=0, base=0, ld=0;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004677 bool base_is_offset;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004678
4679 module.get_name (name);
4680 module.get_link_map (lm);
4681 module.get_base (base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004682 module.get_base_is_offset (base_is_offset);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004683 module.get_dynamic (ld);
4684
Stephane Sezerc6845a02015-08-20 22:07:48 +00004685 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 +00004686 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004687
4688 list.add (module);
4689 return true; // Keep iterating over all "library" elements in the root node
Greg Claytond04f0ed2015-05-26 18:00:51 +00004690 });
Aidan Doddsc0c83852015-05-08 09:36:31 +00004691
4692 if (log)
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004693 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4694 } else if (comm.GetQXferLibrariesReadSupported ()) {
4695 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004696
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004697 // request the loaded library list
4698 std::string raw;
4699 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004700
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004701 if (!comm.ReadExtFeature (ConstString ("libraries"), ConstString (""), raw, lldberr))
4702 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004703
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004704 if (log)
4705 log->Printf ("parsing: %s", raw.c_str());
4706 XMLDocument doc;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004707
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004708 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4709 return Error (0, ErrorType::eErrorTypeGeneric);
4710
4711 XMLNode root_element = doc.GetRootElement("library-list");
4712 if (!root_element)
4713 return Error();
4714
4715 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
4716 GDBLoadedModuleInfoList::LoadedModuleInfo module;
4717
4718 llvm::StringRef name = library.GetAttributeValue("name");
4719 module.set_name(name.str());
4720
4721 // The base address of a given library will be the address of its
4722 // first section. Most remotes send only one section for Windows
4723 // targets for example.
4724 const XMLNode &section = library.FindFirstChildElementWithName("section");
4725 llvm::StringRef address = section.GetAttributeValue("address");
4726 module.set_base(StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0));
Stephane Sezerc6845a02015-08-20 22:07:48 +00004727 // These addresses are absolute values.
4728 module.set_base_is_offset(false);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004729
4730 if (log)
4731 {
4732 std::string name;
4733 lldb::addr_t base = 0;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004734 bool base_is_offset;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004735 module.get_name (name);
4736 module.get_base (base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004737 module.get_base_is_offset (base_is_offset);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004738
Stephane Sezerc6845a02015-08-20 22:07:48 +00004739 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 +00004740 }
4741
4742 list.add (module);
4743 return true; // Keep iterating over all "library" elements in the root node
4744 });
4745
4746 if (log)
4747 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4748 } else {
4749 return Error (0, ErrorType::eErrorTypeGeneric);
4750 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004751
4752 return Error();
4753}
4754
Aidan Doddsc0c83852015-05-08 09:36:31 +00004755lldb::ModuleSP
Stephane Sezerc6845a02015-08-20 22:07:48 +00004756ProcessGDBRemote::LoadModuleAtAddress (const FileSpec &file, lldb::addr_t base_addr, bool value_is_offset)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004757{
4758 Target &target = m_process->GetTarget();
4759 ModuleList &modules = target.GetImages();
4760 ModuleSP module_sp;
4761
4762 bool changed = false;
4763
4764 ModuleSpec module_spec (file, target.GetArchitecture());
4765 if ((module_sp = modules.FindFirstModule (module_spec)))
4766 {
Stephane Sezerc6845a02015-08-20 22:07:48 +00004767 module_sp->SetLoadAddress (target, base_addr, value_is_offset, changed);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004768 }
4769 else if ((module_sp = target.GetSharedModule (module_spec)))
4770 {
Stephane Sezerc6845a02015-08-20 22:07:48 +00004771 module_sp->SetLoadAddress (target, base_addr, value_is_offset, changed);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004772 }
4773
4774 return module_sp;
4775}
4776
4777size_t
4778ProcessGDBRemote::LoadModules ()
4779{
4780 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4781
4782 // request a list of loaded libraries from GDBServer
4783 GDBLoadedModuleInfoList module_list;
4784 if (GetLoadedModuleList (module_list).Fail())
4785 return 0;
4786
4787 // get a list of all the modules
4788 ModuleList new_modules;
4789
4790 for (GDBLoadedModuleInfoList::LoadedModuleInfo & modInfo : module_list.m_list)
4791 {
4792 std::string mod_name;
4793 lldb::addr_t mod_base;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004794 bool mod_base_is_offset;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004795
4796 bool valid = true;
4797 valid &= modInfo.get_name (mod_name);
4798 valid &= modInfo.get_base (mod_base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004799 valid &= modInfo.get_base_is_offset (mod_base_is_offset);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004800 if (!valid)
4801 continue;
4802
4803 // hack (cleaner way to get file name only?) (win/unix compat?)
Vince Harron4cc8d202015-05-10 08:33:58 +00004804 size_t marker = mod_name.rfind ('/');
Aidan Doddsc0c83852015-05-08 09:36:31 +00004805 if (marker == std::string::npos)
4806 marker = 0;
4807 else
4808 marker += 1;
4809
4810 FileSpec file (mod_name.c_str()+marker, true);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004811 lldb::ModuleSP module_sp = LoadModuleAtAddress (file, mod_base, mod_base_is_offset);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004812
4813 if (module_sp.get())
4814 new_modules.Append (module_sp);
4815 }
4816
4817 if (new_modules.GetSize() > 0)
4818 {
Zachary Turner7529df92015-09-01 20:02:29 +00004819 Target &target = GetTarget();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004820
4821 new_modules.ForEach ([&target](const lldb::ModuleSP module_sp) -> bool
4822 {
4823 lldb_private::ObjectFile * obj = module_sp->GetObjectFile ();
4824 if (!obj)
4825 return true;
4826
4827 if (obj->GetType () != ObjectFile::Type::eTypeExecutable)
4828 return true;
4829
4830 lldb::ModuleSP module_copy_sp = module_sp;
4831 target.SetExecutableModule (module_copy_sp, false);
4832 return false;
4833 });
4834
4835 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4836 loaded_modules.AppendIfNeeded (new_modules);
4837 m_process->GetTarget().ModulesDidLoad (new_modules);
4838 }
4839
4840 return new_modules.GetSize();
4841}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004842
Tamas Berghammer783bfc82015-06-18 20:43:56 +00004843Error
4844ProcessGDBRemote::GetFileLoadAddress(const FileSpec& file, bool& is_loaded, lldb::addr_t& load_addr)
4845{
4846 is_loaded = false;
4847 load_addr = LLDB_INVALID_ADDRESS;
4848
4849 std::string file_path = file.GetPath(false);
4850 if (file_path.empty ())
4851 return Error("Empty file name specified");
4852
4853 StreamString packet;
4854 packet.PutCString("qFileLoadAddress:");
4855 packet.PutCStringAsRawHex8(file_path.c_str());
4856
4857 StringExtractorGDBRemote response;
4858 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString().c_str(), response, false) != GDBRemoteCommunication::PacketResult::Success)
4859 return Error("Sending qFileLoadAddress packet failed");
4860
4861 if (response.IsErrorResponse())
4862 {
4863 if (response.GetError() == 1)
4864 {
4865 // The file is not loaded into the inferior
4866 is_loaded = false;
4867 load_addr = LLDB_INVALID_ADDRESS;
4868 return Error();
4869 }
4870
4871 return Error("Fetching file load address from remote server returned an error");
4872 }
4873
4874 if (response.IsNormalResponse())
4875 {
4876 is_loaded = true;
4877 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
4878 return Error();
4879 }
4880
4881 return Error("Unknown error happened during sending the load address packet");
4882}
4883
Greg Clayton0b90be12015-06-23 21:27:50 +00004884
4885void
4886ProcessGDBRemote::ModulesDidLoad (ModuleList &module_list)
4887{
4888 // We must call the lldb_private::Process::ModulesDidLoad () first before we do anything
4889 Process::ModulesDidLoad (module_list);
4890
4891 // After loading shared libraries, we can ask our remote GDB server if
4892 // it needs any symbols.
4893 m_gdb_comm.ServeSymbolLookups(this);
4894}
4895
4896
Greg Claytone034a042015-05-21 20:52:06 +00004897class CommandObjectProcessGDBRemoteSpeedTest: public CommandObjectParsed
4898{
4899public:
4900 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter) :
4901 CommandObjectParsed (interpreter,
4902 "process plugin packet speed-test",
4903 "Tests packet speeds of various sizes to determine the performance characteristics of the GDB remote connection. ",
4904 NULL),
4905 m_option_group (interpreter),
4906 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),
4907 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),
4908 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),
4909 m_json (LLDB_OPT_SET_1, false, "json", 'j', "Print the output as JSON data for easy parsing.", false, true)
4910 {
4911 m_option_group.Append (&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4912 m_option_group.Append (&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4913 m_option_group.Append (&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4914 m_option_group.Append (&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4915 m_option_group.Finalize();
4916 }
4917
4918 ~CommandObjectProcessGDBRemoteSpeedTest ()
4919 {
4920 }
4921
4922
4923 Options *
4924 GetOptions () override
4925 {
4926 return &m_option_group;
4927 }
4928
4929 bool
4930 DoExecute (Args& command, CommandReturnObject &result) override
4931 {
4932 const size_t argc = command.GetArgumentCount();
4933 if (argc == 0)
4934 {
4935 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4936 if (process)
4937 {
4938 StreamSP output_stream_sp (m_interpreter.GetDebugger().GetAsyncOutputStream());
4939 result.SetImmediateOutputStream (output_stream_sp);
4940
4941 const uint32_t num_packets = (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
4942 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
4943 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
4944 const bool json = m_json.GetOptionValue().GetCurrentValue();
4945 if (output_stream_sp)
4946 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, *output_stream_sp);
4947 else
4948 {
4949 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, result.GetOutputStream());
4950 }
4951 result.SetStatus (eReturnStatusSuccessFinishResult);
4952 return true;
4953 }
4954 }
4955 else
4956 {
4957 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
4958 }
4959 result.SetStatus (eReturnStatusFailed);
4960 return false;
4961 }
4962protected:
4963 OptionGroupOptions m_option_group;
4964 OptionGroupUInt64 m_num_packets;
4965 OptionGroupUInt64 m_max_send;
4966 OptionGroupUInt64 m_max_recv;
4967 OptionGroupBoolean m_json;
4968
4969};
4970
Greg Clayton02686b82012-10-15 22:42:16 +00004971class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00004972{
4973private:
4974
4975public:
Greg Clayton02686b82012-10-15 22:42:16 +00004976 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00004977 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00004978 "process plugin packet history",
4979 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00004980 NULL)
4981 {
4982 }
4983
Greg Clayton02686b82012-10-15 22:42:16 +00004984 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton998255b2012-10-13 02:07:45 +00004985 {
4986 }
4987
4988 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004989 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton998255b2012-10-13 02:07:45 +00004990 {
Greg Clayton02686b82012-10-15 22:42:16 +00004991 const size_t argc = command.GetArgumentCount();
4992 if (argc == 0)
4993 {
4994 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4995 if (process)
4996 {
4997 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
4998 result.SetStatus (eReturnStatusSuccessFinishResult);
4999 return true;
5000 }
5001 }
5002 else
5003 {
5004 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
5005 }
5006 result.SetStatus (eReturnStatusFailed);
5007 return false;
5008 }
5009};
5010
Jason Molenda6076bf42014-05-06 04:34:52 +00005011class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed
5012{
5013private:
5014
5015public:
5016 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) :
5017 CommandObjectParsed (interpreter,
5018 "process plugin packet xfer-size",
5019 "Maximum size that lldb will try to read/write one one chunk.",
5020 NULL)
5021 {
5022 }
5023
5024 ~CommandObjectProcessGDBRemotePacketXferSize ()
5025 {
5026 }
5027
5028 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005029 DoExecute (Args& command, CommandReturnObject &result) override
Jason Molenda6076bf42014-05-06 04:34:52 +00005030 {
5031 const size_t argc = command.GetArgumentCount();
5032 if (argc == 0)
5033 {
5034 result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str());
5035 result.SetStatus (eReturnStatusFailed);
5036 return false;
5037 }
5038
5039 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5040 if (process)
5041 {
5042 const char *packet_size = command.GetArgumentAtIndex(0);
5043 errno = 0;
5044 uint64_t user_specified_max = strtoul (packet_size, NULL, 10);
5045 if (errno == 0 && user_specified_max != 0)
5046 {
5047 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max);
5048 result.SetStatus (eReturnStatusSuccessFinishResult);
5049 return true;
5050 }
5051 }
5052 result.SetStatus (eReturnStatusFailed);
5053 return false;
5054 }
5055};
5056
5057
Greg Clayton02686b82012-10-15 22:42:16 +00005058class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
5059{
5060private:
5061
5062public:
5063 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
5064 CommandObjectParsed (interpreter,
5065 "process plugin packet send",
5066 "Send a custom packet through the GDB remote protocol and print the answer. "
5067 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
5068 NULL)
5069 {
5070 }
5071
5072 ~CommandObjectProcessGDBRemotePacketSend ()
5073 {
5074 }
5075
5076 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005077 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton02686b82012-10-15 22:42:16 +00005078 {
5079 const size_t argc = command.GetArgumentCount();
5080 if (argc == 0)
5081 {
5082 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
5083 result.SetStatus (eReturnStatusFailed);
5084 return false;
5085 }
5086
5087 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5088 if (process)
5089 {
Han Ming Ong84145852012-11-26 20:42:03 +00005090 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00005091 {
Han Ming Ong84145852012-11-26 20:42:03 +00005092 const char *packet_cstr = command.GetArgumentAtIndex(0);
5093 bool send_async = true;
5094 StringExtractorGDBRemote response;
5095 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
5096 result.SetStatus (eReturnStatusSuccessFinishResult);
5097 Stream &output_strm = result.GetOutputStream();
5098 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00005099 std::string &response_str = response.GetStringRef();
5100
Han Ming Ong399289e2013-06-21 19:56:59 +00005101 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00005102 {
5103 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
5104 }
5105
Han Ming Ong84145852012-11-26 20:42:03 +00005106 if (response_str.empty())
5107 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
5108 else
5109 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00005110 }
Greg Clayton02686b82012-10-15 22:42:16 +00005111 }
Greg Clayton998255b2012-10-13 02:07:45 +00005112 return true;
5113 }
5114};
5115
Greg Claytonba4a0a52013-02-01 23:03:47 +00005116class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
5117{
5118private:
5119
5120public:
5121 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
5122 CommandObjectRaw (interpreter,
5123 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00005124 "Send a qRcmd packet through the GDB remote protocol and print the response."
5125 "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 +00005126 NULL)
5127 {
5128 }
5129
5130 ~CommandObjectProcessGDBRemotePacketMonitor ()
5131 {
5132 }
5133
5134 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005135 DoExecute (const char *command, CommandReturnObject &result) override
Greg Claytonba4a0a52013-02-01 23:03:47 +00005136 {
5137 if (command == NULL || command[0] == '\0')
5138 {
5139 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
5140 result.SetStatus (eReturnStatusFailed);
5141 return false;
5142 }
5143
5144 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5145 if (process)
5146 {
5147 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00005148 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00005149 packet.PutBytesAsRawHex8(command, strlen(command));
5150 const char *packet_cstr = packet.GetString().c_str();
5151
5152 bool send_async = true;
5153 StringExtractorGDBRemote response;
5154 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
5155 result.SetStatus (eReturnStatusSuccessFinishResult);
5156 Stream &output_strm = result.GetOutputStream();
5157 output_strm.Printf (" packet: %s\n", packet_cstr);
5158 const std::string &response_str = response.GetStringRef();
5159
5160 if (response_str.empty())
5161 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
5162 else
5163 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
5164 }
5165 return true;
5166 }
5167};
5168
Greg Clayton02686b82012-10-15 22:42:16 +00005169class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
5170{
5171private:
5172
5173public:
5174 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
5175 CommandObjectMultiword (interpreter,
5176 "process plugin packet",
5177 "Commands that deal with GDB remote packets.",
5178 NULL)
5179 {
5180 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
5181 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00005182 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Jason Molenda6076bf42014-05-06 04:34:52 +00005183 LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter)));
Greg Claytone034a042015-05-21 20:52:06 +00005184 LoadSubCommand ("speed-test", CommandObjectSP (new CommandObjectProcessGDBRemoteSpeedTest (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00005185 }
5186
5187 ~CommandObjectProcessGDBRemotePacket ()
5188 {
5189 }
5190};
Greg Clayton998255b2012-10-13 02:07:45 +00005191
5192class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
5193{
5194public:
5195 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
5196 CommandObjectMultiword (interpreter,
5197 "process plugin",
5198 "A set of commands for operating on a ProcessGDBRemote process.",
5199 "process plugin <subcommand> [<subcommand-options>]")
5200 {
5201 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
5202 }
5203
5204 ~CommandObjectMultiwordProcessGDBRemote ()
5205 {
5206 }
5207};
5208
Greg Clayton998255b2012-10-13 02:07:45 +00005209CommandObject *
5210ProcessGDBRemote::GetPluginCommandObject()
5211{
5212 if (!m_command_sp)
5213 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
5214 return m_command_sp.get();
5215}