blob: 895fc05aa36ee6f5a93f220dcdb8a91e3cce09a3 [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());
Ryan Brown65d4d5c2015-09-16 21:20:44 +00002047 // If there's a memory thread backed by this thread, we need to use it to calcualte StopInfo.
2048 ThreadSP memory_thread_sp = m_thread_list.FindThreadByProtocolID(thread_sp->GetProtocolID());
2049 if (memory_thread_sp)
2050 thread_sp = memory_thread_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002051
Greg Clayton2e309072015-07-17 23:42:28 +00002052 if (exc_type != 0)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002053 {
Greg Clayton2e309072015-07-17 23:42:28 +00002054 const size_t exc_data_size = exc_data.size();
2055
2056 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
2057 exc_type,
2058 exc_data_size,
2059 exc_data_size >= 1 ? exc_data[0] : 0,
2060 exc_data_size >= 2 ? exc_data[1] : 0,
2061 exc_data_size >= 3 ? exc_data[2] : 0));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002062 }
Greg Clayton2e309072015-07-17 23:42:28 +00002063 else
Greg Clayton358cf1e2015-06-25 21:46:34 +00002064 {
Greg Clayton2e309072015-07-17 23:42:28 +00002065 bool handled = false;
2066 bool did_exec = false;
2067 if (!reason.empty())
Greg Clayton358cf1e2015-06-25 21:46:34 +00002068 {
Greg Clayton2e309072015-07-17 23:42:28 +00002069 if (reason.compare("trace") == 0)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002070 {
Greg Clayton2e309072015-07-17 23:42:28 +00002071 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
2072 handled = true;
2073 }
2074 else if (reason.compare("breakpoint") == 0)
2075 {
2076 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
2077 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2078 if (bp_site_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002079 {
Greg Clayton2e309072015-07-17 23:42:28 +00002080 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2081 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2082 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2083 handled = true;
2084 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2085 {
2086 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2087 }
2088 else
2089 {
2090 StopInfoSP invalid_stop_info_sp;
2091 thread_sp->SetStopInfo (invalid_stop_info_sp);
2092 }
2093 }
2094 }
2095 else if (reason.compare("trap") == 0)
2096 {
2097 // Let the trap just use the standard signal stop reason below...
2098 }
2099 else if (reason.compare("watchpoint") == 0)
2100 {
2101 StringExtractor desc_extractor(description.c_str());
2102 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
2103 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
Jaydeep Patil83143502015-08-13 03:44:09 +00002104 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
Greg Clayton2e309072015-07-17 23:42:28 +00002105 watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
2106 if (wp_addr != LLDB_INVALID_ADDRESS)
2107 {
Mohit K. Bhakkad5df85ce2015-10-09 15:05:45 +00002108 if (wp_hit_addr != LLDB_INVALID_ADDRESS)
2109 wp_addr = wp_hit_addr;
Greg Clayton2e309072015-07-17 23:42:28 +00002110 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2111 if (wp_sp)
2112 {
2113 wp_sp->SetHardwareIndex(wp_index);
2114 watch_id = wp_sp->GetID();
2115 }
2116 }
2117 if (watch_id == LLDB_INVALID_WATCH_ID)
2118 {
2119 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_WATCHPOINTS));
2120 if (log) log->Printf ("failed to find watchpoint");
2121 }
Jaydeep Patil83143502015-08-13 03:44:09 +00002122 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id, wp_hit_addr));
Greg Clayton2e309072015-07-17 23:42:28 +00002123 handled = true;
2124 }
2125 else if (reason.compare("exception") == 0)
2126 {
2127 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
2128 handled = true;
2129 }
2130 else if (reason.compare("exec") == 0)
2131 {
2132 did_exec = true;
2133 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
2134 handled = true;
2135 }
2136 }
2137
2138 if (!handled && signo && did_exec == false)
2139 {
2140 if (signo == SIGTRAP)
2141 {
2142 // Currently we are going to assume SIGTRAP means we are either
2143 // hitting a breakpoint or hardware single stepping.
2144 handled = true;
2145 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
2146 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2147
2148 if (bp_site_sp)
2149 {
2150 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2151 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2152 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2153 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2154 {
2155 if(m_breakpoint_pc_offset != 0)
2156 thread_sp->GetRegisterContext()->SetPC(pc);
2157 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2158 }
2159 else
2160 {
2161 StopInfoSP invalid_stop_info_sp;
2162 thread_sp->SetStopInfo (invalid_stop_info_sp);
2163 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002164 }
2165 else
2166 {
Greg Clayton2e309072015-07-17 23:42:28 +00002167 // If we were stepping then assume the stop was the result of the trace. If we were
2168 // not stepping then report the SIGTRAP.
2169 // FIXME: We are still missing the case where we single step over a trap instruction.
2170 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
2171 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
2172 else
2173 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo, description.c_str()));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002174 }
2175 }
Greg Clayton2e309072015-07-17 23:42:28 +00002176 if (!handled)
2177 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo, description.c_str()));
2178 }
2179
2180 if (!description.empty())
2181 {
2182 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
2183 if (stop_info_sp)
2184 {
2185 const char *stop_info_desc = stop_info_sp->GetDescription();
2186 if (!stop_info_desc || !stop_info_desc[0])
2187 stop_info_sp->SetDescription (description.c_str());
2188 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002189 else
2190 {
Greg Clayton2e309072015-07-17 23:42:28 +00002191 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002192 }
2193 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002194 }
2195 }
2196 }
2197 }
2198 return thread_sp;
2199}
2200
Greg Clayton2e309072015-07-17 23:42:28 +00002201lldb::ThreadSP
Greg Clayton358cf1e2015-06-25 21:46:34 +00002202ProcessGDBRemote::SetThreadStopInfo (StructuredData::Dictionary *thread_dict)
2203{
2204 static ConstString g_key_tid("tid");
2205 static ConstString g_key_name("name");
2206 static ConstString g_key_reason("reason");
2207 static ConstString g_key_metype("metype");
2208 static ConstString g_key_medata("medata");
2209 static ConstString g_key_qaddr("qaddr");
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002210 static ConstString g_key_queue_name("qname");
2211 static ConstString g_key_queue_kind("qkind");
2212 static ConstString g_key_queue_serial("qserial");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002213 static ConstString g_key_registers("registers");
2214 static ConstString g_key_memory("memory");
2215 static ConstString g_key_address("address");
2216 static ConstString g_key_bytes("bytes");
2217 static ConstString g_key_description("description");
Pavel Labath4a4bb122015-07-16 14:14:35 +00002218 static ConstString g_key_signal("signal");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002219
2220 // Stop with signal and thread info
2221 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2222 uint8_t signo = 0;
2223 std::string value;
2224 std::string thread_name;
2225 std::string reason;
2226 std::string description;
2227 uint32_t exc_type = 0;
2228 std::vector<addr_t> exc_data;
2229 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2230 ExpeditedRegisterMap expedited_register_map;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002231 bool queue_vars_valid = false;
2232 std::string queue_name;
2233 QueueKind queue_kind = eQueueKindUnknown;
2234 uint64_t queue_serial = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002235 // Iterate through all of the thread dictionary key/value pairs from the structured data dictionary
2236
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002237 thread_dict->ForEach([this,
2238 &tid,
2239 &expedited_register_map,
2240 &thread_name,
2241 &signo,
2242 &reason,
2243 &description,
2244 &exc_type,
2245 &exc_data,
2246 &thread_dispatch_qaddr,
2247 &queue_vars_valid,
2248 &queue_name,
2249 &queue_kind,
2250 &queue_serial]
2251 (ConstString key, StructuredData::Object* object) -> bool
Greg Clayton358cf1e2015-06-25 21:46:34 +00002252 {
2253 if (key == g_key_tid)
2254 {
2255 // thread in big endian hex
2256 tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
2257 }
2258 else if (key == g_key_metype)
2259 {
2260 // exception type in big endian hex
2261 exc_type = object->GetIntegerValue(0);
2262 }
2263 else if (key == g_key_medata)
2264 {
2265 // exception data in big endian hex
2266 StructuredData::Array *array = object->GetAsArray();
2267 if (array)
2268 {
2269 array->ForEach([&exc_data](StructuredData::Object* object) -> bool {
2270 exc_data.push_back(object->GetIntegerValue());
2271 return true; // Keep iterating through all array items
2272 });
2273 }
2274 }
2275 else if (key == g_key_name)
2276 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002277 thread_name = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002278 }
2279 else if (key == g_key_qaddr)
2280 {
2281 thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
2282 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002283 else if (key == g_key_queue_name)
2284 {
2285 queue_vars_valid = true;
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002286 queue_name = object->GetStringValue();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002287 }
2288 else if (key == g_key_queue_kind)
2289 {
2290 std::string queue_kind_str = object->GetStringValue();
2291 if (queue_kind_str == "serial")
2292 {
2293 queue_vars_valid = true;
2294 queue_kind = eQueueKindSerial;
2295 }
2296 else if (queue_kind_str == "concurrent")
2297 {
2298 queue_vars_valid = true;
2299 queue_kind = eQueueKindConcurrent;
2300 }
2301 }
2302 else if (key == g_key_queue_serial)
2303 {
2304 queue_serial = object->GetIntegerValue(0);
2305 if (queue_serial != 0)
2306 queue_vars_valid = true;
2307 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002308 else if (key == g_key_reason)
2309 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002310 reason = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002311 }
2312 else if (key == g_key_description)
2313 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002314 description = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002315 }
2316 else if (key == g_key_registers)
2317 {
2318 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2319
2320 if (registers_dict)
2321 {
2322 registers_dict->ForEach([&expedited_register_map](ConstString key, StructuredData::Object* object) -> bool {
2323 const uint32_t reg = StringConvert::ToUInt32 (key.GetCString(), UINT32_MAX, 10);
2324 if (reg != UINT32_MAX)
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002325 expedited_register_map[reg] = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002326 return true; // Keep iterating through all array items
2327 });
2328 }
2329 }
2330 else if (key == g_key_memory)
2331 {
2332 StructuredData::Array *array = object->GetAsArray();
2333 if (array)
2334 {
2335 array->ForEach([this](StructuredData::Object* object) -> bool {
2336 StructuredData::Dictionary *mem_cache_dict = object->GetAsDictionary();
2337 if (mem_cache_dict)
2338 {
2339 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2340 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>("address", mem_cache_addr))
2341 {
2342 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
2343 {
2344 StringExtractor bytes;
2345 if (mem_cache_dict->GetValueForKeyAsString("bytes", bytes.GetStringRef()))
2346 {
2347 bytes.SetFilePos(0);
2348
2349 const size_t byte_size = bytes.GetStringRef().size()/2;
2350 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2351 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2352 if (bytes_copied == byte_size)
2353 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2354 }
2355 }
2356 }
2357 }
2358 return true; // Keep iterating through all array items
2359 });
2360 }
2361
2362 }
Pavel Labath4a4bb122015-07-16 14:14:35 +00002363 else if (key == g_key_signal)
2364 signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002365 return true; // Keep iterating through all dictionary key/value pairs
2366 });
2367
Greg Clayton2e309072015-07-17 23:42:28 +00002368 return SetThreadStopInfo (tid,
2369 expedited_register_map,
2370 signo,
2371 thread_name,
2372 reason,
2373 description,
2374 exc_type,
2375 exc_data,
2376 thread_dispatch_qaddr,
2377 queue_vars_valid,
2378 queue_name,
2379 queue_kind,
2380 queue_serial);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002381}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002382
2383StateType
2384ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
2385{
Greg Claytondd0e5a52011-06-02 22:22:38 +00002386 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002387 const char stop_type = stop_packet.GetChar();
2388 switch (stop_type)
2389 {
2390 case 'T':
2391 case 'S':
2392 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00002393 // This is a bit of a hack, but is is required. If we did exec, we
2394 // need to clear our thread lists and also know to rebuild our dynamic
2395 // register info before we lookup and threads and populate the expedited
2396 // register values so we need to know this right away so we can cleanup
2397 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00002398 const uint32_t stop_id = GetStopID();
2399 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00002400 {
2401 // Our first stop, make sure we have a process ID, and also make
2402 // sure we know about our registers
2403 if (GetID() == LLDB_INVALID_PROCESS_ID)
2404 {
Greg Claytonc574ede2011-03-10 02:26:48 +00002405 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00002406 if (pid != LLDB_INVALID_PROCESS_ID)
2407 SetID (pid);
2408 }
2409 BuildDynamicRegisterInfo (true);
2410 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002411 // Stop with signal and thread info
Greg Clayton358cf1e2015-06-25 21:46:34 +00002412 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002413 const uint8_t signo = stop_packet.GetHexU8();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002414 std::string key;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002415 std::string value;
2416 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00002417 std::string reason;
2418 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002419 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00002420 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002421 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton0b90be12015-06-23 21:27:50 +00002422 bool queue_vars_valid = false; // says if locals below that start with "queue_" are valid
2423 std::string queue_name;
2424 QueueKind queue_kind = eQueueKindUnknown;
2425 uint64_t queue_serial = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002426 ExpeditedRegisterMap expedited_register_map;
2427 while (stop_packet.GetNameColonValue(key, value))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002428 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002429 if (key.compare("metype") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002430 {
2431 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002432 exc_type = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002433 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002434 else if (key.compare("medata") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002435 {
2436 // exception data in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002437 exc_data.push_back(StringConvert::ToUInt64 (value.c_str(), 0, 16));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002438 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002439 else if (key.compare("thread") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002440 {
2441 // thread in big endian hex
Greg Clayton358cf1e2015-06-25 21:46:34 +00002442 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002443 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002444 else if (key.compare("threads") == 0)
Greg Clayton9e920902012-04-10 02:25:43 +00002445 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002446 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00002447 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00002448 // A comma separated list of all threads in the current
2449 // process that includes the thread for this stop reply
2450 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00002451 size_t comma_pos;
2452 lldb::tid_t tid;
2453 while ((comma_pos = value.find(',')) != std::string::npos)
2454 {
2455 value[comma_pos] = '\0';
2456 // thread in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002457 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00002458 if (tid != LLDB_INVALID_THREAD_ID)
2459 m_thread_ids.push_back (tid);
2460 value.erase(0, comma_pos + 1);
Greg Clayton9e920902012-04-10 02:25:43 +00002461 }
Vince Harron5275aaa2015-01-15 20:08:35 +00002462 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00002463 if (tid != LLDB_INVALID_THREAD_ID)
2464 m_thread_ids.push_back (tid);
2465 }
Greg Clayton2e309072015-07-17 23:42:28 +00002466 else if (key.compare("jstopinfo") == 0)
Greg Claytona5801ad2015-07-15 22:59:03 +00002467 {
2468 StringExtractor json_extractor;
2469 // Swap "value" over into "name_extractor"
2470 json_extractor.GetStringRef().swap(value);
2471 // Now convert the HEX bytes into a string value
2472 json_extractor.GetHexByteString (value);
2473
2474 // This JSON contains thread IDs and thread stop info for all threads.
2475 // It doesn't contain expedited registers, memory or queue info.
Greg Clayton2e309072015-07-17 23:42:28 +00002476 m_jstopinfo_sp = StructuredData::ParseJSON (value);
Greg Claytona5801ad2015-07-15 22:59:03 +00002477 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002478 else if (key.compare("hexname") == 0)
Greg Claytonde9d0492011-01-08 03:17:57 +00002479 {
2480 StringExtractor name_extractor;
2481 // Swap "value" over into "name_extractor"
2482 name_extractor.GetStringRef().swap(value);
2483 // Now convert the HEX bytes into a string value
2484 name_extractor.GetHexByteString (value);
2485 thread_name.swap (value);
2486 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002487 else if (key.compare("name") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002488 {
2489 thread_name.swap (value);
2490 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002491 else if (key.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002492 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002493 thread_dispatch_qaddr = StringConvert::ToUInt64 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002494 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002495 else if (key.compare("qname") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002496 {
2497 queue_vars_valid = true;
2498 StringExtractor name_extractor;
2499 // Swap "value" over into "name_extractor"
2500 name_extractor.GetStringRef().swap(value);
2501 // Now convert the HEX bytes into a string value
2502 name_extractor.GetHexByteString (value);
2503 queue_name.swap (value);
2504 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002505 else if (key.compare("qkind") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002506 {
Greg Clayton0b90be12015-06-23 21:27:50 +00002507 if (value == "serial")
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002508 {
2509 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002510 queue_kind = eQueueKindSerial;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002511 }
Greg Clayton0b90be12015-06-23 21:27:50 +00002512 else if (value == "concurrent")
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002513 {
2514 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002515 queue_kind = eQueueKindConcurrent;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002516 }
Greg Clayton0b90be12015-06-23 21:27:50 +00002517 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002518 else if (key.compare("qserial") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002519 {
Greg Clayton0b90be12015-06-23 21:27:50 +00002520 queue_serial = StringConvert::ToUInt64 (value.c_str(), 0, 0);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002521 if (queue_serial != 0)
2522 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002523 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002524 else if (key.compare("reason") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002525 {
2526 reason.swap(value);
2527 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002528 else if (key.compare("description") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002529 {
2530 StringExtractor desc_extractor;
2531 // Swap "value" over into "name_extractor"
2532 desc_extractor.GetStringRef().swap(value);
2533 // Now convert the HEX bytes into a string value
Chaoren Lin28e57422015-02-03 01:51:25 +00002534 desc_extractor.GetHexByteString (value);
2535 description.swap(value);
Greg Claytona658fd22011-06-04 01:26:29 +00002536 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002537 else if (key.compare("memory") == 0)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002538 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002539 // Expedited memory. GDB servers can choose to send back expedited memory
2540 // that can populate the L1 memory cache in the process so that things like
2541 // the frame pointer backchain can be expedited. This will help stack
2542 // backtracing be more efficient by not having to send as many memory read
2543 // requests down the remote GDB server.
Chaoren Lin7a306082015-06-23 03:17:01 +00002544
Greg Clayton358cf1e2015-06-25 21:46:34 +00002545 // Key/value pair format: memory:<addr>=<bytes>;
2546 // <addr> is a number whose base will be interpreted by the prefix:
2547 // "0x[0-9a-fA-F]+" for hex
2548 // "0[0-7]+" for octal
2549 // "[1-9]+" for decimal
2550 // <bytes> is native endian ASCII hex bytes just like the register values
2551 llvm::StringRef value_ref(value);
2552 std::pair<llvm::StringRef, llvm::StringRef> pair;
2553 pair = value_ref.split('=');
2554 if (!pair.first.empty() && !pair.second.empty())
2555 {
2556 std::string addr_str(pair.first.str());
2557 const lldb::addr_t mem_cache_addr = StringConvert::ToUInt64(addr_str.c_str(), LLDB_INVALID_ADDRESS, 0);
2558 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002559 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002560 StringExtractor bytes;
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002561 bytes.GetStringRef() = pair.second.str();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002562 const size_t byte_size = bytes.GetStringRef().size()/2;
2563 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2564 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2565 if (bytes_copied == byte_size)
2566 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
Greg Clayton3e06bd92011-01-09 21:07:35 +00002567 }
2568 }
2569 }
Jaydeep Patil725666c2015-08-13 03:46:01 +00002570 else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 || key.compare("awatch") == 0)
2571 {
2572 // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2573 lldb::addr_t wp_addr = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
2574 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2575 uint32_t wp_index = LLDB_INVALID_INDEX32;
2576
2577 if (wp_sp)
2578 wp_index = wp_sp->GetHardwareIndex();
2579
2580 reason = "watchpoint";
2581 StreamString ostr;
2582 ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
2583 description = ostr.GetString().c_str();
2584 }
Stephane Sezer2618e912015-08-21 16:51:56 +00002585 else if (key.compare("library") == 0)
2586 {
2587 LoadModules();
2588 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002589 else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1]))
2590 {
2591 uint32_t reg = StringConvert::ToUInt32 (key.c_str(), UINT32_MAX, 16);
2592 if (reg != UINT32_MAX)
2593 expedited_register_map[reg] = std::move(value);
2594 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002595 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002596
Bhushan D. Attarde1e271df2015-07-24 04:06:20 +00002597 if (tid == LLDB_INVALID_THREAD_ID)
2598 {
2599 // A thread id may be invalid if the response is old style 'S' packet which does not provide the
2600 // thread information. So update the thread list and choose the first one.
2601 UpdateThreadIDList ();
2602
2603 if (!m_thread_ids.empty ())
2604 {
2605 tid = m_thread_ids.front ();
2606 }
2607 }
2608
Greg Clayton358cf1e2015-06-25 21:46:34 +00002609 ThreadSP thread_sp = SetThreadStopInfo (tid,
2610 expedited_register_map,
2611 signo,
2612 thread_name,
2613 reason,
2614 description,
2615 exc_type,
2616 exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002617 thread_dispatch_qaddr,
2618 queue_vars_valid,
2619 queue_name,
2620 queue_kind,
2621 queue_serial);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002622
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002623 return eStateStopped;
2624 }
2625 break;
2626
2627 case 'W':
Todd Fialaff6131a2014-05-19 04:57:23 +00002628 case 'X':
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002629 // process exited
2630 return eStateExited;
2631
2632 default:
2633 break;
2634 }
2635 return eStateInvalid;
2636}
2637
2638void
2639ProcessGDBRemote::RefreshStateAfterStop ()
2640{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002641 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00002642 m_thread_ids.clear();
2643 // Set the thread stop info. It might have a "threads" key whose value is
2644 // a list of all thread IDs in the current process, so m_thread_ids might
2645 // get set.
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002646
2647 // Scope for the lock
2648 {
2649 // Lock the thread stack while we access it
2650 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
2651 // Get the number of stop packets on the stack
2652 int nItems = m_stop_packet_stack.size();
2653 // Iterate over them
2654 for (int i = 0; i < nItems; i++)
2655 {
2656 // Get the thread stop info
2657 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2658 // Process thread stop info
2659 SetThreadStopInfo(stop_info);
2660 }
2661 // Clear the thread stop stack
2662 m_stop_packet_stack.clear();
2663 }
2664
Greg Clayton9e920902012-04-10 02:25:43 +00002665 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2666 if (m_thread_ids.empty())
2667 {
2668 // No, we need to fetch the thread list manually
2669 UpdateThreadIDList();
2670 }
2671
Ewan Crawford78baa192015-05-13 09:18:18 +00002672 // If we have queried for a default thread id
2673 if (m_initial_tid != LLDB_INVALID_THREAD_ID)
2674 {
2675 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2676 m_initial_tid = LLDB_INVALID_THREAD_ID;
2677 }
2678
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002679 // Let all threads recover from stopping and do any clean up based
2680 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002681 m_thread_list_real.RefreshStateAfterStop();
Greg Clayton9e920902012-04-10 02:25:43 +00002682
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002683}
2684
2685Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002686ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002687{
2688 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002689
Greg Clayton6ed95942011-01-22 07:12:45 +00002690 bool timed_out = false;
2691 Mutex::Locker locker;
Greg Clayton513c26c2011-01-29 07:10:55 +00002692
2693 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002694 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002695 // We are being asked to halt during an attach. We need to just close
2696 // our file handle and debugserver will go away, and we can be done...
2697 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00002698 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002699 else
2700 {
Greg Clayton2687cd12012-03-29 01:55:41 +00002701 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton513c26c2011-01-29 07:10:55 +00002702 {
2703 if (timed_out)
2704 error.SetErrorString("timed out sending interrupt packet");
2705 else
2706 error.SetErrorString("unknown error sending interrupt packet");
2707 }
Greg Clayton2687cd12012-03-29 01:55:41 +00002708
2709 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton513c26c2011-01-29 07:10:55 +00002710 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002711 return error;
2712}
2713
2714Error
Jim Inghamacff8952013-05-02 00:27:30 +00002715ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002716{
2717 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002718 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00002719 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00002720 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2721
Jim Inghamacff8952013-05-02 00:27:30 +00002722 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002723 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002724 {
Jim Inghamacff8952013-05-02 00:27:30 +00002725 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002726 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
2727 else
Jim Inghamacff8952013-05-02 00:27:30 +00002728 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00002729 }
Jim Inghamacff8952013-05-02 00:27:30 +00002730
2731 if (!error.Success())
2732 return error;
2733
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002734 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00002735 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002736
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002737 SetPrivateState (eStateDetached);
2738 ResumePrivateStateThread();
2739
2740 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00002741 return error;
2742}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002743
Jim Ingham43c555d2012-07-04 00:35:43 +00002744
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002745Error
2746ProcessGDBRemote::DoDestroy ()
2747{
2748 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002749 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002750 if (log)
2751 log->Printf ("ProcessGDBRemote::DoDestroy()");
2752
Jim Ingham43c555d2012-07-04 00:35:43 +00002753 // There is a bug in older iOS debugservers where they don't shut down the process
2754 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
2755 // this can cause problems with restarting. So we check to see if any of our threads are stopped
2756 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
2757 // destroy it again.
2758 //
2759 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
2760 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
2761 // the debugservers with this bug are equal. There really should be a better way to test this!
2762 //
2763 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
2764 // get called here to destroy again and we're still at a breakpoint or exception, then we should
2765 // just do the straight-forward kill.
2766 //
2767 // And of course, if we weren't able to stop the process by the time we get here, it isn't
2768 // necessary (or helpful) to do any of this.
2769
2770 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
2771 {
2772 PlatformSP platform_sp = GetTarget().GetPlatform();
2773
2774 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2775 if (platform_sp
2776 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00002777 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00002778 {
2779 if (m_destroy_tried_resuming)
2780 {
2781 if (log)
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002782 log->PutCString ("ProcessGDBRemote::DoDestroy() - Tried resuming to destroy once already, not doing it again.");
Jim Ingham43c555d2012-07-04 00:35:43 +00002783 }
2784 else
2785 {
2786 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
2787 // but we really need it to happen here and it doesn't matter if we do it twice.
2788 m_thread_list.DiscardThreadPlans();
2789 DisableAllBreakpointSites();
2790
2791 bool stop_looks_like_crash = false;
2792 ThreadList &threads = GetThreadList();
2793
2794 {
Jim Ingham45350372012-09-11 00:08:52 +00002795 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002796
2797 size_t num_threads = threads.GetSize();
2798 for (size_t i = 0; i < num_threads; i++)
2799 {
2800 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002801 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002802 StopReason reason = eStopReasonInvalid;
2803 if (stop_info_sp)
2804 reason = stop_info_sp->GetStopReason();
2805 if (reason == eStopReasonBreakpoint
2806 || reason == eStopReasonException)
2807 {
2808 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002809 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
2810 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00002811 stop_info_sp->GetDescription());
2812 stop_looks_like_crash = true;
2813 break;
2814 }
2815 }
2816 }
2817
2818 if (stop_looks_like_crash)
2819 {
2820 if (log)
2821 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
2822 m_destroy_tried_resuming = true;
2823
2824 // If we are going to run again before killing, it would be good to suspend all the threads
2825 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
2826 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
2827 // have to run the risk of letting those threads proceed a bit.
2828
2829 {
Jim Ingham45350372012-09-11 00:08:52 +00002830 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002831
2832 size_t num_threads = threads.GetSize();
2833 for (size_t i = 0; i < num_threads; i++)
2834 {
2835 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002836 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002837 StopReason reason = eStopReasonInvalid;
2838 if (stop_info_sp)
2839 reason = stop_info_sp->GetStopReason();
2840 if (reason != eStopReasonBreakpoint
2841 && reason != eStopReasonException)
2842 {
2843 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002844 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
2845 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00002846 thread_sp->SetResumeState(eStateSuspended);
2847 }
2848 }
2849 }
2850 Resume ();
Jason Molendaede31932015-04-17 05:01:58 +00002851 return Destroy(false);
Jim Ingham43c555d2012-07-04 00:35:43 +00002852 }
2853 }
2854 }
2855 }
2856
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002857 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00002858 int exit_status = SIGABRT;
2859 std::string exit_string;
2860
Greg Clayton6ed95942011-01-22 07:12:45 +00002861 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002862 {
Jim Inghamaab78372011-10-28 01:11:35 +00002863 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00002864 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002865 StringExtractorGDBRemote response;
2866 bool send_async = true;
Tamas Berghammer912800c2015-02-24 10:23:39 +00002867 GDBRemoteCommunication::ScopedTimeout (m_gdb_comm, 3);
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002868
Greg Clayton3dedae12013-12-06 21:45:27 +00002869 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton513c26c2011-01-29 07:10:55 +00002870 {
2871 char packet_cmd = response.GetChar(0);
2872
2873 if (packet_cmd == 'W' || packet_cmd == 'X')
2874 {
Jim Inghameac0aa42014-02-21 22:36:11 +00002875#if defined(__APPLE__)
Jim Ingham9d67cc52014-02-21 22:35:29 +00002876 // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off
2877 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill
2878 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns
2879 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap
2880 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of
2881 // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2882 // Anyway, so call waitpid here to finally reap it.
2883 PlatformSP platform_sp(GetTarget().GetPlatform());
2884 if (platform_sp && platform_sp->IsHost())
2885 {
2886 int status;
2887 ::pid_t reap_pid;
2888 reap_pid = waitpid (GetID(), &status, WNOHANG);
2889 if (log)
2890 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2891 }
2892#endif
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002893 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002894 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00002895 exit_status = response.GetHexU8();
2896 }
2897 else
2898 {
2899 if (log)
2900 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2901 exit_string.assign("got unexpected response to k packet: ");
2902 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00002903 }
2904 }
2905 else
2906 {
Jim Inghambabfc382012-06-06 00:32:39 +00002907 if (log)
2908 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2909 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00002910 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002911 }
Jim Inghambabfc382012-06-06 00:32:39 +00002912 else
2913 {
2914 if (log)
Ed Masteb3a53332014-03-17 17:05:22 +00002915 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching");
Jim Inghamcfc09352012-07-27 23:57:19 +00002916 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00002917 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002918 }
Jim Inghambabfc382012-06-06 00:32:39 +00002919 else
2920 {
2921 // If we missed setting the exit status on the way out, do it here.
2922 // NB set exit status can be called multiple times, the first one sets the status.
2923 exit_string.assign("destroying when not connected to debugserver");
2924 }
2925
2926 SetExitStatus(exit_status, exit_string.c_str());
2927
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002928 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002929 KillDebugserverProcess ();
2930 return error;
2931}
2932
Greg Clayton8cda7f02013-05-21 21:55:59 +00002933void
2934ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2935{
Greg Clayton8cda7f02013-05-21 21:55:59 +00002936 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2937 if (did_exec)
2938 {
2939 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2940 if (log)
2941 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2942
2943 m_thread_list_real.Clear();
2944 m_thread_list.Clear();
2945 BuildDynamicRegisterInfo (true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002946 m_gdb_comm.ResetDiscoverableSettings (did_exec);
Greg Clayton8cda7f02013-05-21 21:55:59 +00002947 }
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002948
2949 // Scope the lock
2950 {
2951 // Lock the thread stack while we access it
2952 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
Greg Clayton2e309072015-07-17 23:42:28 +00002953
2954 // We are are not using non-stop mode, there can only be one last stop
2955 // reply packet, so clear the list.
2956 if (GetTarget().GetNonStopModeEnabled() == false)
2957 m_stop_packet_stack.clear();
2958
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002959 // Add this stop packet to the stop packet stack
2960 // This stack will get popped and examined when we switch to the
2961 // Stopped state
2962 m_stop_packet_stack.push_back(response);
2963 }
Greg Clayton8cda7f02013-05-21 21:55:59 +00002964}
2965
Chaoren Linc963a222015-09-01 16:58:45 +00002966void
2967ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp)
2968{
2969 Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
2970}
2971
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002972//------------------------------------------------------------------
2973// Process Queries
2974//------------------------------------------------------------------
2975
2976bool
2977ProcessGDBRemote::IsAlive ()
2978{
Greg Clayton10177aa2010-12-08 05:08:21 +00002979 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002980}
2981
2982addr_t
2983ProcessGDBRemote::GetImageInfoAddress()
2984{
Aidan Doddsc0c83852015-05-08 09:36:31 +00002985 // request the link map address via the $qShlibInfoAddr packet
2986 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2987
2988 // the loaded module list can also provides a link map address
2989 if (addr == LLDB_INVALID_ADDRESS)
2990 {
2991 GDBLoadedModuleInfoList list;
2992 if (GetLoadedModuleList (list).Success())
2993 addr = list.m_link_map;
2994 }
2995
2996 return addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002997}
2998
Greg Clayton2e309072015-07-17 23:42:28 +00002999void
3000ProcessGDBRemote::WillPublicStop ()
3001{
3002 // See if the GDB remote client supports the JSON threads info.
3003 // If so, we gather stop info for all threads, expedited registers,
3004 // expedited memory, runtime queue information (iOS and MacOSX only),
3005 // and more. Expediting memory will help stack backtracing be much
3006 // faster. Expediting registers will make sure we don't have to read
3007 // the thread registers for GPRs.
3008 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
3009
3010 if (m_jthreadsinfo_sp)
3011 {
3012 // Now set the stop info for each thread and also expedite any registers
3013 // and memory that was in the jThreadsInfo response.
3014 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
3015 if (thread_infos)
3016 {
3017 const size_t n = thread_infos->GetSize();
3018 for (size_t i=0; i<n; ++i)
3019 {
3020 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
3021 if (thread_dict)
3022 SetThreadStopInfo(thread_dict);
3023 }
3024 }
3025 }
3026}
3027
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003028//------------------------------------------------------------------
3029// Process Memory
3030//------------------------------------------------------------------
3031size_t
3032ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
3033{
Jason Molenda6076bf42014-05-06 04:34:52 +00003034 GetMaxMemorySize ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003035 if (size > m_max_memory_size)
3036 {
3037 // Keep memory read sizes down to a sane limit. This function will be
3038 // called multiple times in order to complete the task by
3039 // lldb_private::Process so it is ok to do this.
3040 size = m_max_memory_size;
3041 }
3042
3043 char packet[64];
Jason Molenda6076bf42014-05-06 04:34:52 +00003044 int packet_len;
3045 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
3046 if (binary_memory_read)
3047 {
3048 packet_len = ::snprintf (packet, sizeof(packet), "x0x%" PRIx64 ",0x%" PRIx64, (uint64_t)addr, (uint64_t)size);
3049 }
3050 else
3051 {
3052 packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
3053 }
Andy Gibbsa297a972013-06-19 19:04:53 +00003054 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003055 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003056 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003057 {
Greg Clayton576d8832011-03-22 04:00:09 +00003058 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003059 {
3060 error.Clear();
Jason Molenda6076bf42014-05-06 04:34:52 +00003061 if (binary_memory_read)
3062 {
3063 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any
3064 // 0x7d character escaping that was present in the packet
3065
3066 size_t data_received_size = response.GetBytesLeft();
3067 if (data_received_size > size)
3068 {
3069 // Don't write past the end of BUF if the remote debug server gave us too
3070 // much data for some reason.
3071 data_received_size = size;
3072 }
3073 memcpy (buf, response.GetStringRef().data(), data_received_size);
3074 return data_received_size;
3075 }
3076 else
3077 {
3078 return response.GetHexBytes(buf, size, '\xdd');
3079 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003080 }
Greg Clayton576d8832011-03-22 04:00:09 +00003081 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00003082 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00003083 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00003084 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003085 else
Greg Clayton9944cd72012-09-19 01:46:31 +00003086 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003087 }
3088 else
3089 {
Jim Ingham35579dd2013-06-03 19:34:01 +00003090 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003091 }
3092 return 0;
3093}
3094
3095size_t
3096ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
3097{
Jason Molenda6076bf42014-05-06 04:34:52 +00003098 GetMaxMemorySize ();
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00003099 if (size > m_max_memory_size)
3100 {
3101 // Keep memory read sizes down to a sane limit. This function will be
3102 // called multiple times in order to complete the task by
3103 // lldb_private::Process so it is ok to do this.
3104 size = m_max_memory_size;
3105 }
3106
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003107 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00003108 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Clayton7fb56d02011-02-01 01:31:41 +00003109 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003110 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003111 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003112 {
Greg Clayton576d8832011-03-22 04:00:09 +00003113 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003114 {
3115 error.Clear();
3116 return size;
3117 }
Greg Clayton576d8832011-03-22 04:00:09 +00003118 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00003119 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00003120 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00003121 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003122 else
Greg Clayton9944cd72012-09-19 01:46:31 +00003123 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 +00003124 }
3125 else
3126 {
Jim Ingham35579dd2013-06-03 19:34:01 +00003127 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003128 }
3129 return 0;
3130}
3131
3132lldb::addr_t
3133ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
3134{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003135 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_EXPRESSIONS));
Greg Clayton2a48f522011-05-14 01:50:35 +00003136 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
3137
Greg Clayton70b57652011-05-15 01:25:55 +00003138 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton2a48f522011-05-14 01:50:35 +00003139 switch (supported)
3140 {
3141 case eLazyBoolCalculate:
3142 case eLazyBoolYes:
3143 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
3144 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
3145 return allocated_addr;
3146
3147 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003148 // Call mmap() to create memory in the inferior..
3149 unsigned prot = 0;
3150 if (permissions & lldb::ePermissionsReadable)
3151 prot |= eMmapProtRead;
3152 if (permissions & lldb::ePermissionsWritable)
3153 prot |= eMmapProtWrite;
3154 if (permissions & lldb::ePermissionsExecutable)
3155 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00003156
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003157 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
3158 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
3159 m_addr_to_mmap_size[allocated_addr] = size;
3160 else
Todd Fialaaf245d12014-06-30 21:05:18 +00003161 {
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003162 allocated_addr = LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00003163 if (log)
3164 log->Printf ("ProcessGDBRemote::%s no direct stub support for memory allocation, and InferiorCallMmap also failed - is stub missing register context save/restore capability?", __FUNCTION__);
3165 }
Greg Clayton2a48f522011-05-14 01:50:35 +00003166 break;
3167 }
3168
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003169 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00003170 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003171 else
3172 error.Clear();
3173 return allocated_addr;
3174}
3175
3176Error
Greg Clayton46fb5582011-11-18 07:03:08 +00003177ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
3178 MemoryRegionInfo &region_info)
3179{
3180
3181 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
3182 return error;
3183}
3184
3185Error
Johnny Chen64637202012-05-23 21:09:52 +00003186ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
3187{
3188
3189 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
3190 return error;
3191}
3192
3193Error
Enrico Granataf04a2192012-07-13 23:18:48 +00003194ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
3195{
Jaydeep Patil725666c2015-08-13 03:46:01 +00003196 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after, GetTarget().GetArchitecture()));
Enrico Granataf04a2192012-07-13 23:18:48 +00003197 return error;
3198}
3199
3200Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003201ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
3202{
3203 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00003204 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
3205
3206 switch (supported)
3207 {
3208 case eLazyBoolCalculate:
3209 // We should never be deallocating memory without allocating memory
3210 // first so we should never get eLazyBoolCalculate
3211 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
3212 break;
3213
3214 case eLazyBoolYes:
3215 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00003216 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003217 break;
3218
3219 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003220 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00003221 {
3222 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003223 if (pos != m_addr_to_mmap_size.end() &&
3224 InferiorCallMunmap(this, addr, pos->second))
3225 m_addr_to_mmap_size.erase (pos);
3226 else
Daniel Malead01b2952012-11-29 21:49:15 +00003227 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003228 }
3229 break;
3230 }
3231
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003232 return error;
3233}
3234
3235
3236//------------------------------------------------------------------
3237// Process STDIO
3238//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003239size_t
3240ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
3241{
3242 if (m_stdio_communication.IsConnected())
3243 {
3244 ConnectionStatus status;
3245 m_stdio_communication.Write(src, src_len, status, NULL);
3246 }
Vince Harrondf3f00f2015-02-10 21:09:04 +00003247 else if (m_stdin_forward)
Vince Harrone0be4252015-02-06 18:32:57 +00003248 {
3249 m_gdb_comm.SendStdinNotification(src, src_len);
3250 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003251 return 0;
3252}
3253
3254Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003255ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003256{
3257 Error error;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003258 assert(bp_site != NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003259
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003260 // Get logging info
3261 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003262 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003263
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003264 // Get the breakpoint address
3265 const addr_t addr = bp_site->GetLoadAddress();
3266
3267 // Log that a breakpoint was requested
3268 if (log)
3269 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
3270
3271 // Breakpoint already exists and is enabled
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003272 if (bp_site->IsEnabled())
3273 {
3274 if (log)
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003275 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 +00003276 return error;
3277 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003278
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003279 // Get the software breakpoint trap opcode size
3280 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3281
3282 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
3283 // is supported by the remote stub. These are set to true by default, and later set to false
3284 // only after we receive an unimplemented response when sending a breakpoint packet. This means
3285 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
3286 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
3287 // indicates if the user specifically asked for hardware breakpoints. If true then we will
3288 // skip over software breakpoints.
3289 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
3290 {
3291 // Try to send off a software breakpoint packet ($Z0)
3292 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003293 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003294 // The breakpoint was placed successfully
3295 bp_site->SetEnabled(true);
3296 bp_site->SetType(BreakpointSite::eExternal);
Greg Claytoneb023e72013-10-11 19:48:25 +00003297 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003298 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003299
3300 // SendGDBStoppointTypePacket() will return an error if it was unable to set this
3301 // breakpoint. We need to differentiate between a error specific to placing this breakpoint
3302 // or if we have learned that this breakpoint type is unsupported. To do this, we
3303 // must test the support boolean for this breakpoint type to see if it now indicates that
3304 // this breakpoint type is unsupported. If they are still supported then we should return
3305 // with the error code. If they are now unsupported, then we would like to fall through
3306 // and try another form of breakpoint.
3307 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
3308 return error;
3309
3310 // We reach here when software breakpoints have been found to be unsupported. For future
3311 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
3312 // known not to be supported.
3313 if (log)
3314 log->Printf("Software breakpoints are unsupported");
3315
3316 // So we will fall through and try a hardware breakpoint
3317 }
3318
3319 // The process of setting a hardware breakpoint is much the same as above. We check the
3320 // supported boolean for this breakpoint type, and if it is thought to be supported then we
3321 // will try to set this breakpoint with a hardware breakpoint.
3322 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3323 {
3324 // Try to send off a hardware breakpoint packet ($Z1)
3325 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003326 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003327 // The breakpoint was placed successfully
3328 bp_site->SetEnabled(true);
3329 bp_site->SetType(BreakpointSite::eHardware);
3330 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003331 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003332
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003333 // Check if the error was something other then an unsupported breakpoint type
3334 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3335 {
3336 // Unable to set this hardware breakpoint
3337 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
3338 return error;
3339 }
3340
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003341 // We will reach here when the stub gives an unsupported response to a hardware breakpoint
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003342 if (log)
3343 log->Printf("Hardware breakpoints are unsupported");
3344
3345 // Finally we will falling through to a #trap style breakpoint
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003346 }
3347
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003348 // Don't fall through when hardware breakpoints were specifically requested
3349 if (bp_site->HardwareRequired())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003350 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003351 error.SetErrorString("hardware breakpoints are not supported");
3352 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003353 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003354
3355 // As a last resort we want to place a manual breakpoint. An instruction
3356 // is placed into the process memory using memory write packets.
3357 return EnableSoftwareBreakpoint(bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003358}
3359
3360Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003361ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003362{
3363 Error error;
3364 assert (bp_site != NULL);
3365 addr_t addr = bp_site->GetLoadAddress();
3366 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00003367 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003368 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003369 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003370
3371 if (bp_site->IsEnabled())
3372 {
3373 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
3374
Greg Clayton8b82f082011-04-12 05:54:46 +00003375 BreakpointSite::Type bp_type = bp_site->GetType();
3376 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003377 {
Greg Clayton8b82f082011-04-12 05:54:46 +00003378 case BreakpointSite::eSoftware:
3379 error = DisableSoftwareBreakpoint (bp_site);
3380 break;
3381
3382 case BreakpointSite::eHardware:
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003383 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003384 error.SetErrorToGenericError();
3385 break;
3386
3387 case BreakpointSite::eExternal:
Jim Inghama04ef752014-03-07 11:18:02 +00003388 {
3389 GDBStoppointType stoppoint_type;
3390 if (bp_site->IsHardware())
3391 stoppoint_type = eBreakpointHardware;
3392 else
3393 stoppoint_type = eBreakpointSoftware;
3394
3395 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003396 error.SetErrorToGenericError();
Jim Inghama04ef752014-03-07 11:18:02 +00003397 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003398 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003399 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003400 if (error.Success())
3401 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003402 }
3403 else
3404 {
3405 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003406 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 +00003407 return error;
3408 }
3409
3410 if (error.Success())
3411 error.SetErrorToGenericError();
3412 return error;
3413}
3414
Johnny Chen11309a32011-09-06 22:38:36 +00003415// Pre-requisite: wp != NULL.
3416static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00003417GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00003418{
3419 assert(wp);
3420 bool watch_read = wp->WatchpointRead();
3421 bool watch_write = wp->WatchpointWrite();
3422
3423 // watch_read and watch_write cannot both be false.
3424 assert(watch_read || watch_write);
3425 if (watch_read && watch_write)
3426 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00003427 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00003428 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00003429 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00003430 return eWatchpointWrite;
3431}
3432
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003433Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003434ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003435{
3436 Error error;
3437 if (wp)
3438 {
3439 user_id_t watchID = wp->GetID();
3440 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00003441 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003442 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003443 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003444 if (wp->IsEnabled())
3445 {
3446 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003447 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 +00003448 return error;
3449 }
Johnny Chen11309a32011-09-06 22:38:36 +00003450
3451 GDBStoppointType type = GetGDBStoppointType(wp);
3452 // Pass down an appropriate z/Z packet...
3453 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003454 {
Johnny Chen11309a32011-09-06 22:38:36 +00003455 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
3456 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003457 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003458 return error;
3459 }
3460 else
3461 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003462 }
Johnny Chen11309a32011-09-06 22:38:36 +00003463 else
3464 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003465 }
3466 else
3467 {
Johnny Chen01a67862011-10-14 00:42:25 +00003468 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003469 }
3470 if (error.Success())
3471 error.SetErrorToGenericError();
3472 return error;
3473}
3474
3475Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003476ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003477{
3478 Error error;
3479 if (wp)
3480 {
3481 user_id_t watchID = wp->GetID();
3482
Greg Clayton5160ce52013-03-27 23:08:40 +00003483 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003484
3485 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00003486
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003487 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003488 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003489
Johnny Chen11309a32011-09-06 22:38:36 +00003490 if (!wp->IsEnabled())
3491 {
3492 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003493 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 +00003494 // See also 'class WatchpointSentry' within StopInfo.cpp.
3495 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
3496 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00003497 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003498 return error;
3499 }
3500
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003501 if (wp->IsHardware())
3502 {
Johnny Chen11309a32011-09-06 22:38:36 +00003503 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003504 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00003505 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
3506 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003507 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003508 return error;
3509 }
3510 else
3511 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003512 }
3513 // TODO: clear software watchpoints if we implement them
3514 }
3515 else
3516 {
Johnny Chen01a67862011-10-14 00:42:25 +00003517 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003518 }
3519 if (error.Success())
3520 error.SetErrorToGenericError();
3521 return error;
3522}
3523
3524void
3525ProcessGDBRemote::Clear()
3526{
3527 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00003528 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003529 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003530}
3531
3532Error
3533ProcessGDBRemote::DoSignal (int signo)
3534{
3535 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00003536 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003537 if (log)
3538 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
3539
3540 if (!m_gdb_comm.SendAsyncSignal (signo))
3541 error.SetErrorStringWithFormat("failed to send signal %i", signo);
3542 return error;
3543}
3544
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003545Error
Greg Clayton91a9b2472013-12-04 19:19:12 +00003546ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003547{
3548 Error error;
3549 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
3550 {
3551 // If we locate debugserver, keep that located version around
3552 static FileSpec g_debugserver_file_spec;
3553
Han Ming Ong84647042012-02-25 01:07:38 +00003554 ProcessLaunchInfo debugserver_launch_info;
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00003555 // Make debugserver run in its own session so signals generated by
3556 // special terminal key sequences (^C) don't affect debugserver.
3557 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3558
Greg Clayton91a9b2472013-12-04 19:19:12 +00003559 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
3560 debugserver_launch_info.SetUserID(process_info.GetUserID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003561
Todd Fiala013434e2014-07-09 01:29:05 +00003562#if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__) || defined (__aarch64__))
Greg Claytonfda4fab2014-01-10 22:24:11 +00003563 // On iOS, still do a local connection using a random port
Greg Clayton16810922014-02-27 19:38:18 +00003564 const char *hostname = "127.0.0.1";
Greg Claytonfda4fab2014-01-10 22:24:11 +00003565 uint16_t port = get_random_port ();
3566#else
3567 // Set hostname being NULL to do the reverse connect where debugserver
3568 // will bind to port zero and it will communicate back to us the port
3569 // that we will connect to
3570 const char *hostname = NULL;
3571 uint16_t port = 0;
3572#endif
3573
3574 error = m_gdb_comm.StartDebugserverProcess (hostname,
3575 port,
Greg Clayton00fe87b2013-12-05 22:58:22 +00003576 debugserver_launch_info,
3577 port);
Greg Clayton91a9b2472013-12-04 19:19:12 +00003578
3579 if (error.Success ())
3580 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003581 else
Greg Clayton91a9b2472013-12-04 19:19:12 +00003582 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003583
3584 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3585 StartAsyncThread ();
Greg Clayton91a9b2472013-12-04 19:19:12 +00003586
3587 if (error.Fail())
3588 {
3589 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
3590
3591 if (log)
3592 log->Printf("failed to start debugserver process: %s", error.AsCString());
3593 return error;
3594 }
3595
Greg Clayton00fe87b2013-12-05 22:58:22 +00003596 if (m_gdb_comm.IsConnected())
3597 {
3598 // Finish the connection process by doing the handshake without connecting (send NULL URL)
3599 ConnectToDebugserver (NULL);
3600 }
3601 else
3602 {
Greg Claytonfda4fab2014-01-10 22:24:11 +00003603 StreamString connect_url;
3604 connect_url.Printf("connect://%s:%u", hostname, port);
3605 error = ConnectToDebugserver (connect_url.GetString().c_str());
Greg Clayton00fe87b2013-12-05 22:58:22 +00003606 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00003607
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003608 }
3609 return error;
3610}
3611
3612bool
3613ProcessGDBRemote::MonitorDebugserverProcess
3614(
3615 void *callback_baton,
3616 lldb::pid_t debugserver_pid,
Greg Claytone4e45922011-11-16 05:37:56 +00003617 bool exited, // True if the process did exit
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003618 int signo, // Zero for no signal
3619 int exit_status // Exit value of process if signal is zero
3620)
3621{
Greg Claytone4e45922011-11-16 05:37:56 +00003622 // The baton is a "ProcessGDBRemote *". Now this class might be gone
3623 // and might not exist anymore, so we need to carefully try to get the
3624 // target for this process first since we have a race condition when
3625 // we are done running between getting the notice that the inferior
3626 // process has died and the debugserver that was debugging this process.
3627 // In our test suite, we are also continually running process after
3628 // process, so we must be very careful to make sure:
3629 // 1 - process object hasn't been deleted already
3630 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003631
3632 // "debugserver_pid" argument passed in is the process ID for
3633 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00003634 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003635
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003636 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton6779606a2011-01-22 23:43:18 +00003637
Greg Claytone4e45922011-11-16 05:37:56 +00003638 // Get a shared pointer to the target that has a matching process pointer.
3639 // This target could be gone, or the target could already have a new process
3640 // object inside of it
3641 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
3642
Greg Clayton6779606a2011-01-22 23:43:18 +00003643 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003644 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 +00003645
Greg Claytone4e45922011-11-16 05:37:56 +00003646 if (target_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003647 {
Greg Claytone4e45922011-11-16 05:37:56 +00003648 // We found a process in a target that matches, but another thread
3649 // might be in the process of launching a new process that will
3650 // soon replace it, so get a shared pointer to the process so we
3651 // can keep it alive.
3652 ProcessSP process_sp (target_sp->GetProcessSP());
3653 // Now we have a shared pointer to the process that can't go away on us
3654 // so we now make sure it was the same as the one passed in, and also make
3655 // sure that our previous "process *" didn't get deleted and have a new
3656 // "process *" created in its place with the same pointer. To verify this
3657 // we make sure the process has our debugserver process ID. If we pass all
3658 // of these tests, then we are sure that this process is the one we were
3659 // looking for.
3660 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003661 {
Greg Claytone4e45922011-11-16 05:37:56 +00003662 // Sleep for a half a second to make sure our inferior process has
3663 // time to set its exit status before we set it incorrectly when
3664 // both the debugserver and the inferior process shut down.
3665 usleep (500000);
3666 // If our process hasn't yet exited, debugserver might have died.
3667 // If the process did exit, the we are reaping it.
3668 const StateType state = process->GetState();
3669
3670 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
3671 state != eStateInvalid &&
3672 state != eStateUnloaded &&
3673 state != eStateExited &&
3674 state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003675 {
Greg Claytone4e45922011-11-16 05:37:56 +00003676 char error_str[1024];
3677 if (signo)
3678 {
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00003679 const char *signal_cstr = process->GetUnixSignals()->GetSignalAsCString(signo);
Greg Claytone4e45922011-11-16 05:37:56 +00003680 if (signal_cstr)
3681 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3682 else
3683 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
3684 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003685 else
Greg Claytone4e45922011-11-16 05:37:56 +00003686 {
3687 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
3688 }
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003689
Greg Claytone4e45922011-11-16 05:37:56 +00003690 process->SetExitStatus (-1, error_str);
3691 }
3692 // Debugserver has exited we need to let our ProcessGDBRemote
3693 // know that it no longer has a debugserver instance
3694 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003695 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003696 }
3697 return true;
3698}
3699
3700void
3701ProcessGDBRemote::KillDebugserverProcess ()
3702{
Greg Claytonfbb76342013-11-20 21:07:01 +00003703 m_gdb_comm.Disconnect();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003704 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3705 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003706 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003707 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3708 }
3709}
3710
3711void
3712ProcessGDBRemote::Initialize()
3713{
Davide Italianoc8d69822015-04-03 04:24:32 +00003714 static std::once_flag g_once_flag;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003715
Davide Italianoc8d69822015-04-03 04:24:32 +00003716 std::call_once(g_once_flag, []()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003717 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003718 PluginManager::RegisterPlugin (GetPluginNameStatic(),
3719 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00003720 CreateInstance,
3721 DebuggerInitialize);
Davide Italianoc8d69822015-04-03 04:24:32 +00003722 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003723}
3724
Greg Clayton7f982402013-07-15 22:54:20 +00003725void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003726ProcessGDBRemote::DebuggerInitialize (Debugger &debugger)
Greg Clayton7f982402013-07-15 22:54:20 +00003727{
3728 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
3729 {
3730 const bool is_global_setting = true;
3731 PluginManager::CreateSettingForProcessPlugin (debugger,
3732 GetGlobalPluginProperties()->GetValueProperties(),
3733 ConstString ("Properties for the gdb-remote process plug-in."),
3734 is_global_setting);
3735 }
3736}
3737
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003738bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003739ProcessGDBRemote::StartAsyncThread ()
3740{
Greg Clayton5160ce52013-03-27 23:08:40 +00003741 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003742
3743 if (log)
3744 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003745
3746 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003747 if (!m_async_thread.IsJoinable())
Jim Ingham455fa5c2012-11-01 01:15:33 +00003748 {
3749 // Create a thread that watches our internal state and controls which
3750 // events make it to clients (into the DCProcess event queue).
Zachary Turner39de3112014-09-09 20:54:56 +00003751
3752 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003753 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003754 else if (log)
3755 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was already running.", __FUNCTION__);
Zachary Turner39de3112014-09-09 20:54:56 +00003756
Zachary Turneracee96a2014-09-23 18:32:09 +00003757 return m_async_thread.IsJoinable();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003758}
3759
3760void
3761ProcessGDBRemote::StopAsyncThread ()
3762{
Greg Clayton5160ce52013-03-27 23:08:40 +00003763 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003764
3765 if (log)
3766 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
3767
Jim Ingham455fa5c2012-11-01 01:15:33 +00003768 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003769 if (m_async_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003770 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00003771 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
3772
3773 // This will shut down the async thread.
3774 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3775
3776 // Stop the stdio thread
Zachary Turner39de3112014-09-09 20:54:56 +00003777 m_async_thread.Join(nullptr);
Pavel Labatha55a9532015-03-11 09:53:42 +00003778 m_async_thread.Reset();
Jim Ingham455fa5c2012-11-01 01:15:33 +00003779 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003780 else if (log)
3781 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003782}
3783
Ewan Crawford76df2882015-06-23 12:32:06 +00003784bool
3785ProcessGDBRemote::HandleNotifyPacket (StringExtractorGDBRemote &packet)
3786{
3787 // get the packet at a string
3788 const std::string &pkt = packet.GetStringRef();
3789 // skip %stop:
3790 StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
3791
3792 // pass as a thread stop info packet
3793 SetLastStopPacket(stop_info);
3794
3795 // check for more stop reasons
3796 HandleStopReplySequence();
3797
3798 // if the process is stopped then we need to fake a resume
3799 // so that we can stop properly with the new break. This
3800 // is possible due to SetPrivateState() broadcasting the
3801 // state change as a side effect.
3802 if (GetPrivateState() == lldb::StateType::eStateStopped)
3803 {
3804 SetPrivateState(lldb::StateType::eStateRunning);
3805 }
3806
3807 // since we have some stopped packets we can halt the process
3808 SetPrivateState(lldb::StateType::eStateStopped);
3809
3810 return true;
3811}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003812
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003813thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003814ProcessGDBRemote::AsyncThread (void *arg)
3815{
3816 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
3817
Greg Clayton5160ce52013-03-27 23:08:40 +00003818 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003819 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003820 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003821
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003822 EventSP event_sp;
Pavel Labath50556852015-09-03 09:36:22 +00003823 bool done = false;
3824 while (!done)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003825 {
Pavel Labath50556852015-09-03 09:36:22 +00003826 if (log)
3827 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
3828 if (process->m_async_listener.WaitForEvent (NULL, event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003829 {
Pavel Labath50556852015-09-03 09:36:22 +00003830 const uint32_t event_type = event_sp->GetType();
3831 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003832 {
3833 if (log)
Pavel Labath50556852015-09-03 09:36:22 +00003834 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
3835
3836 switch (event_type)
3837 {
3838 case eBroadcastBitAsyncContinue:
3839 {
3840 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
3841
3842 if (continue_packet)
3843 {
3844 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
3845 const size_t continue_cstr_len = continue_packet->GetByteSize ();
3846 if (log)
3847 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
3848
3849 if (::strstr (continue_cstr, "vAttach") == NULL)
3850 process->SetPrivateState(eStateRunning);
3851 StringExtractorGDBRemote response;
3852
3853 // If in Non-Stop-Mode
3854 if (process->GetTarget().GetNonStopModeEnabled())
3855 {
3856 // send the vCont packet
3857 if (!process->GetGDBRemote().SendvContPacket(process, continue_cstr, continue_cstr_len, response))
3858 {
3859 // Something went wrong
3860 done = true;
3861 break;
3862 }
3863 }
3864 // If in All-Stop-Mode
3865 else
3866 {
3867 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
3868
3869 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
3870 // The thread ID list might be contained within the "response", or the stop reply packet that
3871 // caused the stop. So clear it now before we give the stop reply packet to the process
3872 // using the process->SetLastStopPacket()...
3873 process->ClearThreadIDList ();
3874
3875 switch (stop_state)
3876 {
3877 case eStateStopped:
3878 case eStateCrashed:
3879 case eStateSuspended:
3880 process->SetLastStopPacket (response);
3881 process->SetPrivateState (stop_state);
3882 break;
3883
3884 case eStateExited:
3885 {
3886 process->SetLastStopPacket (response);
3887 process->ClearThreadIDList();
3888 response.SetFilePos(1);
3889
3890 int exit_status = response.GetHexU8();
3891 const char *desc_cstr = NULL;
3892 StringExtractor extractor;
3893 std::string desc_string;
3894 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';')
3895 {
3896 std::string desc_token;
3897 while (response.GetNameColonValue (desc_token, desc_string))
3898 {
3899 if (desc_token == "description")
3900 {
3901 extractor.GetStringRef().swap(desc_string);
3902 extractor.SetFilePos(0);
3903 extractor.GetHexByteString (desc_string);
3904 desc_cstr = desc_string.c_str();
3905 }
3906 }
3907 }
3908 process->SetExitStatus(exit_status, desc_cstr);
3909 done = true;
3910 break;
3911 }
3912 case eStateInvalid:
3913 {
3914 // Check to see if we were trying to attach and if we got back
3915 // the "E87" error code from debugserver -- this indicates that
3916 // the process is not debuggable. Return a slightly more helpful
3917 // error message about why the attach failed.
3918 if (::strstr (continue_cstr, "vAttach") != NULL
3919 && response.GetError() == 0x87)
3920 {
3921 process->SetExitStatus(-1, "cannot attach to process due to System Integrity Protection");
3922 }
3923 // E01 code from vAttach means that the attach failed
3924 if (::strstr (continue_cstr, "vAttach") != NULL
3925 && response.GetError() == 0x1)
3926 {
3927 process->SetExitStatus(-1, "unable to attach");
3928 }
3929 else
3930 {
3931 process->SetExitStatus(-1, "lost connection");
3932 }
3933 break;
3934 }
3935
3936 default:
3937 process->SetPrivateState (stop_state);
3938 break;
3939 } // switch(stop_state)
3940 } // else // if in All-stop-mode
3941 } // if (continue_packet)
3942 } // case eBroadcastBitAysncContinue
3943 break;
3944
3945 case eBroadcastBitAsyncThreadShouldExit:
3946 if (log)
3947 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
3948 done = true;
3949 break;
3950
3951 default:
3952 if (log)
3953 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
3954 done = true;
3955 break;
3956 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003957 }
Pavel Labath50556852015-09-03 09:36:22 +00003958 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
3959 {
3960 switch (event_type)
3961 {
3962 case Communication::eBroadcastBitReadThreadDidExit:
3963 process->SetExitStatus (-1, "lost connection");
3964 done = true;
3965 break;
3966
3967 case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify:
3968 {
3969 lldb_private::Event *event = event_sp.get();
3970 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event);
3971 StringExtractorGDBRemote notify((const char*)continue_packet->GetBytes());
3972 // Hand this over to the process to handle
3973 process->HandleNotifyPacket(notify);
3974 break;
3975 }
3976
3977 default:
3978 if (log)
3979 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
3980 done = true;
3981 break;
3982 }
3983 }
3984 }
3985 else
3986 {
3987 if (log)
3988 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
3989 done = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003990 }
3991 }
3992
3993 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003994 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003995
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003996 return NULL;
3997}
3998
Greg Claytone996fd32011-03-08 22:40:15 +00003999//uint32_t
4000//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4001//{
4002// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
4003// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
4004// if (m_local_debugserver)
4005// {
4006// return Host::ListProcessesMatchingName (name, matches, pids);
4007// }
4008// else
4009// {
4010// // FIXME: Implement talking to the remote debugserver.
4011// return 0;
4012// }
4013//
4014//}
4015//
Jim Ingham1c823b42011-01-22 01:33:44 +00004016bool
4017ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004018 StoppointCallbackContext *context,
Jim Ingham1c823b42011-01-22 01:33:44 +00004019 lldb::user_id_t break_id,
4020 lldb::user_id_t break_loc_id)
4021{
4022 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
4023 // run so I can stop it if that's what I want to do.
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004024 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00004025 if (log)
4026 log->Printf("Hit New Thread Notification breakpoint.");
4027 return false;
4028}
4029
4030
4031bool
4032ProcessGDBRemote::StartNoticingNewThreads()
4033{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004034 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00004035 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00004036 {
Greg Clayton4116e932012-05-15 02:33:01 +00004037 if (log && log->GetVerbose())
4038 log->Printf("Enabled noticing new thread breakpoint.");
4039 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00004040 }
Greg Clayton4116e932012-05-15 02:33:01 +00004041 else
Jim Ingham1c823b42011-01-22 01:33:44 +00004042 {
Zachary Turner7529df92015-09-01 20:02:29 +00004043 PlatformSP platform_sp (GetTarget().GetPlatform());
Greg Clayton4116e932012-05-15 02:33:01 +00004044 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00004045 {
Zachary Turner7529df92015-09-01 20:02:29 +00004046 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(GetTarget());
Greg Clayton4116e932012-05-15 02:33:01 +00004047 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00004048 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00004049 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00004050 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
4051 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00004052 }
4053 else
4054 {
4055 if (log)
4056 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00004057 }
4058 }
4059 }
Greg Clayton4116e932012-05-15 02:33:01 +00004060 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00004061}
4062
4063bool
4064ProcessGDBRemote::StopNoticingNewThreads()
4065{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004066 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00004067 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00004068 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00004069
4070 if (m_thread_create_bp_sp)
4071 m_thread_create_bp_sp->SetEnabled(false);
4072
Jim Ingham1c823b42011-01-22 01:33:44 +00004073 return true;
4074}
4075
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004076DynamicLoader *
Jason Molenda5e8534e2012-10-03 01:29:34 +00004077ProcessGDBRemote::GetDynamicLoader ()
4078{
4079 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00004080 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00004081 return m_dyld_ap.get();
4082}
Jim Ingham1c823b42011-01-22 01:33:44 +00004083
Jason Molendaa3329782014-03-29 18:54:20 +00004084Error
4085ProcessGDBRemote::SendEventData(const char *data)
4086{
4087 int return_value;
4088 bool was_supported;
4089
4090 Error error;
4091
4092 return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported);
4093 if (return_value != 0)
4094 {
4095 if (!was_supported)
4096 error.SetErrorString("Sending events is not supported for this process.");
4097 else
4098 error.SetErrorStringWithFormat("Error sending event data: %d.", return_value);
4099 }
4100 return error;
4101}
4102
Steve Pucci03904ac2014-03-04 23:18:46 +00004103const DataBufferSP
4104ProcessGDBRemote::GetAuxvData()
4105{
4106 DataBufferSP buf;
4107 if (m_gdb_comm.GetQXferAuxvReadSupported())
4108 {
4109 std::string response_string;
4110 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success)
4111 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length()));
4112 }
4113 return buf;
4114}
4115
Jason Molenda705b1802014-06-13 02:37:02 +00004116StructuredData::ObjectSP
4117ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid)
4118{
4119 StructuredData::ObjectSP object_sp;
4120
4121 if (m_gdb_comm.GetThreadExtendedInfoSupported())
4122 {
4123 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4124 SystemRuntime *runtime = GetSystemRuntime();
4125 if (runtime)
4126 {
4127 runtime->AddThreadExtendedInfoPacketHints (args_dict);
4128 }
4129 args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid);
4130
4131 StreamString packet;
4132 packet << "jThreadExtendedInfo:";
4133 args_dict->Dump (packet);
4134
4135 // FIXME the final character of a JSON dictionary, '}', is the escape
4136 // character in gdb-remote binary mode. lldb currently doesn't escape
4137 // these characters in its packet output -- so we add the quoted version
4138 // of the } character here manually in case we talk to a debugserver which
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004139 // un-escapes the characters at packet read time.
Jason Molenda705b1802014-06-13 02:37:02 +00004140 packet << (char) (0x7d ^ 0x20);
4141
4142 StringExtractorGDBRemote response;
4143 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4144 {
4145 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4146 if (response_type == StringExtractorGDBRemote::eResponse)
4147 {
4148 if (!response.Empty())
4149 {
Jason Molenda20ee21b2015-07-10 23:15:22 +00004150 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4151 }
4152 }
4153 }
4154 }
4155 return object_sp;
4156}
4157
4158StructuredData::ObjectSP
4159ProcessGDBRemote::GetLoadedDynamicLibrariesInfos (lldb::addr_t image_list_address, lldb::addr_t image_count)
4160{
4161 StructuredData::ObjectSP object_sp;
4162
4163 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported())
4164 {
4165 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4166 args_dict->GetAsDictionary()->AddIntegerItem ("image_list_address", image_list_address);
4167 args_dict->GetAsDictionary()->AddIntegerItem ("image_count", image_count);
4168
4169 StreamString packet;
4170 packet << "jGetLoadedDynamicLibrariesInfos:";
4171 args_dict->Dump (packet);
4172
4173 // FIXME the final character of a JSON dictionary, '}', is the escape
4174 // character in gdb-remote binary mode. lldb currently doesn't escape
4175 // these characters in its packet output -- so we add the quoted version
4176 // of the } character here manually in case we talk to a debugserver which
4177 // un-escapes the characters at packet read time.
4178 packet << (char) (0x7d ^ 0x20);
4179
4180 StringExtractorGDBRemote response;
4181 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4182 {
4183 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4184 if (response_type == StringExtractorGDBRemote::eResponse)
4185 {
4186 if (!response.Empty())
4187 {
Jason Molenda705b1802014-06-13 02:37:02 +00004188 // The packet has already had the 0x7d xor quoting stripped out at the
4189 // GDBRemoteCommunication packet receive level.
4190 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4191 }
4192 }
4193 }
4194 }
4195 return object_sp;
4196}
4197
Jason Molenda20ee21b2015-07-10 23:15:22 +00004198
Jason Molenda6076bf42014-05-06 04:34:52 +00004199// Establish the largest memory read/write payloads we should use.
4200// If the remote stub has a max packet size, stay under that size.
4201//
4202// If the remote stub's max packet size is crazy large, use a
4203// reasonable largeish default.
4204//
4205// If the remote stub doesn't advertise a max packet size, use a
4206// conservative default.
4207
4208void
4209ProcessGDBRemote::GetMaxMemorySize()
4210{
4211 const uint64_t reasonable_largeish_default = 128 * 1024;
4212 const uint64_t conservative_default = 512;
4213
4214 if (m_max_memory_size == 0)
4215 {
4216 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4217 if (stub_max_size != UINT64_MAX && stub_max_size != 0)
4218 {
4219 // Save the stub's claimed maximum packet size
4220 m_remote_stub_max_memory_size = stub_max_size;
4221
4222 // Even if the stub says it can support ginormous packets,
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004223 // don't exceed our reasonable largeish default packet size.
Jason Molenda6076bf42014-05-06 04:34:52 +00004224 if (stub_max_size > reasonable_largeish_default)
4225 {
4226 stub_max_size = reasonable_largeish_default;
4227 }
4228
4229 m_max_memory_size = stub_max_size;
4230 }
4231 else
4232 {
4233 m_max_memory_size = conservative_default;
4234 }
4235 }
4236}
4237
4238void
4239ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max)
4240{
4241 if (user_specified_max != 0)
4242 {
4243 GetMaxMemorySize ();
4244
4245 if (m_remote_stub_max_memory_size != 0)
4246 {
4247 if (m_remote_stub_max_memory_size < user_specified_max)
4248 {
4249 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a packet size too big, go as big
4250 // as the remote stub says we can go.
4251 }
4252 else
4253 {
4254 m_max_memory_size = user_specified_max; // user's packet size is good
4255 }
4256 }
4257 else
4258 {
4259 m_max_memory_size = user_specified_max; // user's packet size is probably fine
4260 }
4261 }
4262}
4263
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004264bool
4265ProcessGDBRemote::GetModuleSpec(const FileSpec& module_file_spec,
4266 const ArchSpec& arch,
4267 ModuleSpec &module_spec)
4268{
4269 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PLATFORM);
4270
4271 if (!m_gdb_comm.GetModuleInfo (module_file_spec, arch, module_spec))
4272 {
4273 if (log)
4274 log->Printf ("ProcessGDBRemote::%s - failed to get module info for %s:%s",
4275 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4276 arch.GetTriple ().getTriple ().c_str ());
4277 return false;
4278 }
4279
4280 if (log)
4281 {
4282 StreamString stream;
4283 module_spec.Dump (stream);
4284 log->Printf ("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4285 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4286 arch.GetTriple ().getTriple ().c_str (), stream.GetString ().c_str ());
4287 }
4288
4289 return true;
4290}
4291
Colin Rileyc3c95b22015-04-16 15:51:33 +00004292namespace {
4293
4294typedef std::vector<std::string> stringVec;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004295
4296typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004297struct RegisterSetInfo
4298{
4299 ConstString name;
4300};
Colin Rileyc3c95b22015-04-16 15:51:33 +00004301
Greg Claytond04f0ed2015-05-26 18:00:51 +00004302typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4303
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004304struct GdbServerTargetInfo
4305{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004306 std::string arch;
4307 std::string osabi;
4308 stringVec includes;
4309 RegisterSetMap reg_set_map;
4310 XMLNode feature_node;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004311};
Greg Claytond04f0ed2015-05-26 18:00:51 +00004312
Colin Rileyc3c95b22015-04-16 15:51:33 +00004313bool
Jason Molenda21586c82015-09-09 03:36:24 +00004314ParseRegisters (XMLNode feature_node, GdbServerTargetInfo &target_info, GDBRemoteDynamicRegisterInfo &dyn_reg_info, ABISP abi_sp)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004315{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004316 if (!feature_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004317 return false;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004318
Jason Molenda63bd0db2015-09-15 23:20:34 +00004319 uint32_t cur_reg_num = 0;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004320 uint32_t reg_offset = 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004321
Jason Molenda63bd0db2015-09-15 23:20:34 +00004322 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 +00004323 std::string gdb_group;
4324 std::string gdb_type;
4325 ConstString reg_name;
4326 ConstString alt_name;
4327 ConstString set_name;
4328 std::vector<uint32_t> value_regs;
4329 std::vector<uint32_t> invalidate_regs;
4330 bool encoding_set = false;
4331 bool format_set = false;
4332 RegisterInfo reg_info = { NULL, // Name
4333 NULL, // Alt name
4334 0, // byte size
4335 reg_offset, // offset
4336 eEncodingUint, // encoding
Jason Molendabf67a302015-09-01 05:17:01 +00004337 eFormatHex, // format
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004338 {
Jason Molendabf67a302015-09-01 05:17:01 +00004339 LLDB_INVALID_REGNUM, // eh_frame reg num
Greg Claytond04f0ed2015-05-26 18:00:51 +00004340 LLDB_INVALID_REGNUM, // DWARF reg num
4341 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda63bd0db2015-09-15 23:20:34 +00004342 cur_reg_num, // process plugin reg num
4343 cur_reg_num // native register number
Greg Claytond04f0ed2015-05-26 18:00:51 +00004344 },
4345 NULL,
4346 NULL
4347 };
4348
Jason Molenda63bd0db2015-09-15 23:20:34 +00004349 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 +00004350 if (name == "name")
4351 {
4352 reg_name.SetString(value);
4353 }
4354 else if (name == "bitsize")
4355 {
4356 reg_info.byte_size = StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
4357 }
4358 else if (name == "type")
4359 {
4360 gdb_type = value.str();
4361 }
4362 else if (name == "group")
4363 {
4364 gdb_group = value.str();
4365 }
4366 else if (name == "regnum")
4367 {
4368 const uint32_t regnum = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4369 if (regnum != LLDB_INVALID_REGNUM)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004370 {
Jason Molenda63bd0db2015-09-15 23:20:34 +00004371 reg_info.kinds[eRegisterKindProcessPlugin] = regnum;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004372 }
4373 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004374 else if (name == "offset")
4375 {
4376 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4377 }
4378 else if (name == "altname")
4379 {
4380 alt_name.SetString(value);
4381 }
4382 else if (name == "encoding")
4383 {
4384 encoding_set = true;
4385 reg_info.encoding = Args::StringToEncoding (value.data(), eEncodingUint);
4386 }
4387 else if (name == "format")
4388 {
4389 format_set = true;
4390 Format format = eFormatInvalid;
4391 if (Args::StringToFormat (value.data(), format, NULL).Success())
4392 reg_info.format = format;
4393 else if (value == "vector-sint8")
4394 reg_info.format = eFormatVectorOfSInt8;
4395 else if (value == "vector-uint8")
4396 reg_info.format = eFormatVectorOfUInt8;
4397 else if (value == "vector-sint16")
4398 reg_info.format = eFormatVectorOfSInt16;
4399 else if (value == "vector-uint16")
4400 reg_info.format = eFormatVectorOfUInt16;
4401 else if (value == "vector-sint32")
4402 reg_info.format = eFormatVectorOfSInt32;
4403 else if (value == "vector-uint32")
4404 reg_info.format = eFormatVectorOfUInt32;
4405 else if (value == "vector-float32")
4406 reg_info.format = eFormatVectorOfFloat32;
4407 else if (value == "vector-uint128")
4408 reg_info.format = eFormatVectorOfUInt128;
4409 }
4410 else if (name == "group_id")
4411 {
4412 const uint32_t set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4413 RegisterSetMap::const_iterator pos = target_info.reg_set_map.find(set_id);
4414 if (pos != target_info.reg_set_map.end())
4415 set_name = pos->second.name;
4416 }
Jason Molendaa18f7072015-08-15 01:21:01 +00004417 else if (name == "gcc_regnum" || name == "ehframe_regnum")
Greg Claytond04f0ed2015-05-26 18:00:51 +00004418 {
Jason Molendaa18f7072015-08-15 01:21:01 +00004419 reg_info.kinds[eRegisterKindEHFrame] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004420 }
4421 else if (name == "dwarf_regnum")
4422 {
4423 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4424 }
4425 else if (name == "generic")
4426 {
4427 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister(value.data());
4428 }
4429 else if (name == "value_regnums")
4430 {
4431 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
4432 }
4433 else if (name == "invalidate_regnums")
4434 {
4435 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
4436 }
4437 else
4438 {
4439 printf("unhandled attribute %s = %s\n", name.data(), value.data());
4440 }
4441 return true; // Keep iterating through all attributes
4442 });
4443
4444 if (!gdb_type.empty() && !(encoding_set || format_set))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004445 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004446 if (gdb_type.find("int") == 0)
4447 {
4448 reg_info.format = eFormatHex;
4449 reg_info.encoding = eEncodingUint;
4450 }
4451 else if (gdb_type == "data_ptr" || gdb_type == "code_ptr")
4452 {
4453 reg_info.format = eFormatAddressInfo;
4454 reg_info.encoding = eEncodingUint;
4455 }
4456 else if (gdb_type == "i387_ext" || gdb_type == "float")
4457 {
4458 reg_info.format = eFormatFloat;
4459 reg_info.encoding = eEncodingIEEE754;
4460 }
Colin Rileyc3c95b22015-04-16 15:51:33 +00004461 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004462
4463 // Only update the register set name if we didn't get a "reg_set" attribute.
4464 // "set_name" will be empty if we didn't have a "reg_set" attribute.
4465 if (!set_name && !gdb_group.empty())
4466 set_name.SetCString(gdb_group.c_str());
4467
4468 reg_info.byte_offset = reg_offset;
4469 assert (reg_info.byte_size != 0);
4470 reg_offset += reg_info.byte_size;
4471 if (!value_regs.empty())
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004472 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004473 value_regs.push_back(LLDB_INVALID_REGNUM);
4474 reg_info.value_regs = value_regs.data();
Colin Rileyc3c95b22015-04-16 15:51:33 +00004475 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004476 if (!invalidate_regs.empty())
4477 {
4478 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
4479 reg_info.invalidate_regs = invalidate_regs.data();
4480 }
4481
Jason Molenda63bd0db2015-09-15 23:20:34 +00004482 ++cur_reg_num;
Jason Molenda21586c82015-09-09 03:36:24 +00004483 AugmentRegisterInfoViaABI (reg_info, reg_name, abi_sp);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004484 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
4485
4486 return true; // Keep iterating through all "reg" elements
4487 });
Colin Rileyc3c95b22015-04-16 15:51:33 +00004488 return true;
4489}
Greg Claytond04f0ed2015-05-26 18:00:51 +00004490
Colin Rileyc3c95b22015-04-16 15:51:33 +00004491} // namespace {}
4492
Colin Rileyc3c95b22015-04-16 15:51:33 +00004493
4494// query the target of gdb-remote for extended target information
4495// return: 'true' on success
4496// 'false' on failure
4497bool
Aidan Doddsc0c83852015-05-08 09:36:31 +00004498ProcessGDBRemote::GetGDBServerRegisterInfo ()
Colin Rileyc3c95b22015-04-16 15:51:33 +00004499{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004500 // Make sure LLDB has an XML parser it can use first
4501 if (!XMLDocument::XMLEnabled())
4502 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004503
4504 // redirect libxml2's error handler since the default prints to stdout
Colin Rileyc3c95b22015-04-16 15:51:33 +00004505
4506 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004507
4508 // check that we have extended feature read support
4509 if ( !comm.GetQXferFeaturesReadSupported( ) )
4510 return false;
4511
4512 // request the target xml file
4513 std::string raw;
4514 lldb_private::Error lldberr;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004515 if (!comm.ReadExtFeature(ConstString("features"),
4516 ConstString("target.xml"),
4517 raw,
4518 lldberr))
4519 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00004520 return false;
4521 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004522
Colin Rileyc3c95b22015-04-16 15:51:33 +00004523
Greg Claytond04f0ed2015-05-26 18:00:51 +00004524 XMLDocument xml_document;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004525
Greg Claytond04f0ed2015-05-26 18:00:51 +00004526 if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml"))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004527 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004528 GdbServerTargetInfo target_info;
4529
4530 XMLNode target_node = xml_document.GetRootElement("target");
4531 if (target_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004532 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004533 XMLNode feature_node;
4534 target_node.ForEachChildElement([&target_info, this, &feature_node](const XMLNode &node) -> bool
4535 {
4536 llvm::StringRef name = node.GetName();
4537 if (name == "architecture")
4538 {
4539 node.GetElementText(target_info.arch);
4540 }
4541 else if (name == "osabi")
4542 {
4543 node.GetElementText(target_info.osabi);
4544 }
Ewan Crawford682e8422015-06-26 09:38:27 +00004545 else if (name == "xi:include" || name == "include")
Greg Claytond04f0ed2015-05-26 18:00:51 +00004546 {
4547 llvm::StringRef href = node.GetAttributeValue("href");
4548 if (!href.empty())
4549 target_info.includes.push_back(href.str());
4550 }
4551 else if (name == "feature")
4552 {
4553 feature_node = node;
4554 }
4555 else if (name == "groups")
4556 {
4557 node.ForEachChildElementWithName("group", [&target_info](const XMLNode &node) -> bool {
4558 uint32_t set_id = UINT32_MAX;
4559 RegisterSetInfo set_info;
4560
4561 node.ForEachAttribute([&set_id, &set_info](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
4562 if (name == "id")
4563 set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4564 if (name == "name")
4565 set_info.name = ConstString(value);
4566 return true; // Keep iterating through all attributes
4567 });
4568
4569 if (set_id != UINT32_MAX)
4570 target_info.reg_set_map[set_id] = set_info;
4571 return true; // Keep iterating through all "group" elements
4572 });
4573 }
4574 return true; // Keep iterating through all children of the target_node
4575 });
4576
4577 if (feature_node)
4578 {
Jason Molenda21586c82015-09-09 03:36:24 +00004579 ParseRegisters(feature_node, target_info, this->m_register_info, GetABI());
Greg Claytond04f0ed2015-05-26 18:00:51 +00004580 }
4581
4582 for (const auto &include : target_info.includes)
4583 {
4584 // request register file
4585 std::string xml_data;
4586 if (!comm.ReadExtFeature(ConstString("features"),
4587 ConstString(include),
4588 xml_data,
4589 lldberr))
4590 continue;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004591
Greg Claytond04f0ed2015-05-26 18:00:51 +00004592 XMLDocument include_xml_document;
4593 include_xml_document.ParseMemory(xml_data.data(), xml_data.size(), include.c_str());
4594 XMLNode include_feature_node = include_xml_document.GetRootElement("feature");
4595 if (include_feature_node)
4596 {
Jason Molenda21586c82015-09-09 03:36:24 +00004597 ParseRegisters(include_feature_node, target_info, this->m_register_info, GetABI());
Greg Claytond04f0ed2015-05-26 18:00:51 +00004598 }
4599 }
4600 this->m_register_info.Finalize(GetTarget().GetArchitecture());
Colin Rileyc3c95b22015-04-16 15:51:33 +00004601 }
4602 }
4603
Greg Claytond04f0ed2015-05-26 18:00:51 +00004604 return m_register_info.GetNumRegisters() > 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004605}
4606
Aidan Doddsc0c83852015-05-08 09:36:31 +00004607Error
4608ProcessGDBRemote::GetLoadedModuleList (GDBLoadedModuleInfoList & list)
4609{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004610 // Make sure LLDB has an XML parser it can use first
4611 if (!XMLDocument::XMLEnabled())
4612 return Error (0, ErrorType::eErrorTypeGeneric);
4613
Aidan Doddsc0c83852015-05-08 09:36:31 +00004614 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS);
4615 if (log)
4616 log->Printf ("ProcessGDBRemote::%s", __FUNCTION__);
4617
Aidan Doddsc0c83852015-05-08 09:36:31 +00004618 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004619
4620 // check that we have extended feature read support
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004621 if (comm.GetQXferLibrariesSVR4ReadSupported ()) {
4622 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004623
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004624 // request the loaded library list
4625 std::string raw;
4626 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004627
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004628 if (!comm.ReadExtFeature (ConstString ("libraries-svr4"), ConstString (""), raw, lldberr))
4629 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004630
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004631 // parse the xml file in memory
4632 if (log)
4633 log->Printf ("parsing: %s", raw.c_str());
4634 XMLDocument doc;
4635
4636 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4637 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004638
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004639 XMLNode root_element = doc.GetRootElement("library-list-svr4");
4640 if (!root_element)
4641 return Error();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004642
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004643 // main link map structure
4644 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4645 if (!main_lm.empty())
4646 {
4647 list.m_link_map = StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
4648 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004649
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004650 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
Aidan Doddsc0c83852015-05-08 09:36:31 +00004651
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004652 GDBLoadedModuleInfoList::LoadedModuleInfo module;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004653
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004654 library.ForEachAttribute([log, &module](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004655
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004656 if (name == "name")
4657 module.set_name (value.str());
4658 else if (name == "lm")
4659 {
4660 // the address of the link_map struct.
4661 module.set_link_map(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4662 }
4663 else if (name == "l_addr")
4664 {
4665 // the displacement as read from the field 'l_addr' of the link_map struct.
4666 module.set_base(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
Stephane Sezerc6845a02015-08-20 22:07:48 +00004667 // base address is always a displacement, not an absolute value.
4668 module.set_base_is_offset(true);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004669 }
4670 else if (name == "l_ld")
4671 {
4672 // the memory address of the libraries PT_DYAMIC section.
4673 module.set_dynamic(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4674 }
4675
4676 return true; // Keep iterating over all properties of "library"
4677 });
4678
4679 if (log)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004680 {
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004681 std::string name;
4682 lldb::addr_t lm=0, base=0, ld=0;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004683 bool base_is_offset;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004684
4685 module.get_name (name);
4686 module.get_link_map (lm);
4687 module.get_base (base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004688 module.get_base_is_offset (base_is_offset);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004689 module.get_dynamic (ld);
4690
Stephane Sezerc6845a02015-08-20 22:07:48 +00004691 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 +00004692 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004693
4694 list.add (module);
4695 return true; // Keep iterating over all "library" elements in the root node
Greg Claytond04f0ed2015-05-26 18:00:51 +00004696 });
Aidan Doddsc0c83852015-05-08 09:36:31 +00004697
4698 if (log)
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004699 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4700 } else if (comm.GetQXferLibrariesReadSupported ()) {
4701 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004702
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004703 // request the loaded library list
4704 std::string raw;
4705 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004706
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004707 if (!comm.ReadExtFeature (ConstString ("libraries"), ConstString (""), raw, lldberr))
4708 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004709
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004710 if (log)
4711 log->Printf ("parsing: %s", raw.c_str());
4712 XMLDocument doc;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004713
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004714 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4715 return Error (0, ErrorType::eErrorTypeGeneric);
4716
4717 XMLNode root_element = doc.GetRootElement("library-list");
4718 if (!root_element)
4719 return Error();
4720
4721 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
4722 GDBLoadedModuleInfoList::LoadedModuleInfo module;
4723
4724 llvm::StringRef name = library.GetAttributeValue("name");
4725 module.set_name(name.str());
4726
4727 // The base address of a given library will be the address of its
4728 // first section. Most remotes send only one section for Windows
4729 // targets for example.
4730 const XMLNode &section = library.FindFirstChildElementWithName("section");
4731 llvm::StringRef address = section.GetAttributeValue("address");
4732 module.set_base(StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0));
Stephane Sezerc6845a02015-08-20 22:07:48 +00004733 // These addresses are absolute values.
4734 module.set_base_is_offset(false);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004735
4736 if (log)
4737 {
4738 std::string name;
4739 lldb::addr_t base = 0;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004740 bool base_is_offset;
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004741 module.get_name (name);
4742 module.get_base (base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004743 module.get_base_is_offset (base_is_offset);
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004744
Stephane Sezerc6845a02015-08-20 22:07:48 +00004745 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 +00004746 }
4747
4748 list.add (module);
4749 return true; // Keep iterating over all "library" elements in the root node
4750 });
4751
4752 if (log)
4753 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4754 } else {
4755 return Error (0, ErrorType::eErrorTypeGeneric);
4756 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004757
4758 return Error();
4759}
4760
Aidan Doddsc0c83852015-05-08 09:36:31 +00004761lldb::ModuleSP
Stephane Sezerc6845a02015-08-20 22:07:48 +00004762ProcessGDBRemote::LoadModuleAtAddress (const FileSpec &file, lldb::addr_t base_addr, bool value_is_offset)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004763{
4764 Target &target = m_process->GetTarget();
4765 ModuleList &modules = target.GetImages();
4766 ModuleSP module_sp;
4767
4768 bool changed = false;
4769
4770 ModuleSpec module_spec (file, target.GetArchitecture());
4771 if ((module_sp = modules.FindFirstModule (module_spec)))
4772 {
Stephane Sezerc6845a02015-08-20 22:07:48 +00004773 module_sp->SetLoadAddress (target, base_addr, value_is_offset, changed);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004774 }
4775 else if ((module_sp = target.GetSharedModule (module_spec)))
4776 {
Stephane Sezerc6845a02015-08-20 22:07:48 +00004777 module_sp->SetLoadAddress (target, base_addr, value_is_offset, changed);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004778 }
4779
4780 return module_sp;
4781}
4782
4783size_t
4784ProcessGDBRemote::LoadModules ()
4785{
4786 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4787
4788 // request a list of loaded libraries from GDBServer
4789 GDBLoadedModuleInfoList module_list;
4790 if (GetLoadedModuleList (module_list).Fail())
4791 return 0;
4792
4793 // get a list of all the modules
4794 ModuleList new_modules;
4795
4796 for (GDBLoadedModuleInfoList::LoadedModuleInfo & modInfo : module_list.m_list)
4797 {
4798 std::string mod_name;
4799 lldb::addr_t mod_base;
Stephane Sezerc6845a02015-08-20 22:07:48 +00004800 bool mod_base_is_offset;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004801
4802 bool valid = true;
4803 valid &= modInfo.get_name (mod_name);
4804 valid &= modInfo.get_base (mod_base);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004805 valid &= modInfo.get_base_is_offset (mod_base_is_offset);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004806 if (!valid)
4807 continue;
4808
4809 // hack (cleaner way to get file name only?) (win/unix compat?)
Vince Harron4cc8d202015-05-10 08:33:58 +00004810 size_t marker = mod_name.rfind ('/');
Aidan Doddsc0c83852015-05-08 09:36:31 +00004811 if (marker == std::string::npos)
4812 marker = 0;
4813 else
4814 marker += 1;
4815
4816 FileSpec file (mod_name.c_str()+marker, true);
Stephane Sezerc6845a02015-08-20 22:07:48 +00004817 lldb::ModuleSP module_sp = LoadModuleAtAddress (file, mod_base, mod_base_is_offset);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004818
4819 if (module_sp.get())
4820 new_modules.Append (module_sp);
4821 }
4822
4823 if (new_modules.GetSize() > 0)
4824 {
Zachary Turner7529df92015-09-01 20:02:29 +00004825 Target &target = GetTarget();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004826
4827 new_modules.ForEach ([&target](const lldb::ModuleSP module_sp) -> bool
4828 {
4829 lldb_private::ObjectFile * obj = module_sp->GetObjectFile ();
4830 if (!obj)
4831 return true;
4832
4833 if (obj->GetType () != ObjectFile::Type::eTypeExecutable)
4834 return true;
4835
4836 lldb::ModuleSP module_copy_sp = module_sp;
4837 target.SetExecutableModule (module_copy_sp, false);
4838 return false;
4839 });
4840
4841 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4842 loaded_modules.AppendIfNeeded (new_modules);
4843 m_process->GetTarget().ModulesDidLoad (new_modules);
4844 }
4845
4846 return new_modules.GetSize();
4847}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004848
Tamas Berghammer783bfc82015-06-18 20:43:56 +00004849Error
4850ProcessGDBRemote::GetFileLoadAddress(const FileSpec& file, bool& is_loaded, lldb::addr_t& load_addr)
4851{
4852 is_loaded = false;
4853 load_addr = LLDB_INVALID_ADDRESS;
4854
4855 std::string file_path = file.GetPath(false);
4856 if (file_path.empty ())
4857 return Error("Empty file name specified");
4858
4859 StreamString packet;
4860 packet.PutCString("qFileLoadAddress:");
4861 packet.PutCStringAsRawHex8(file_path.c_str());
4862
4863 StringExtractorGDBRemote response;
4864 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString().c_str(), response, false) != GDBRemoteCommunication::PacketResult::Success)
4865 return Error("Sending qFileLoadAddress packet failed");
4866
4867 if (response.IsErrorResponse())
4868 {
4869 if (response.GetError() == 1)
4870 {
4871 // The file is not loaded into the inferior
4872 is_loaded = false;
4873 load_addr = LLDB_INVALID_ADDRESS;
4874 return Error();
4875 }
4876
4877 return Error("Fetching file load address from remote server returned an error");
4878 }
4879
4880 if (response.IsNormalResponse())
4881 {
4882 is_loaded = true;
4883 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
4884 return Error();
4885 }
4886
4887 return Error("Unknown error happened during sending the load address packet");
4888}
4889
Greg Clayton0b90be12015-06-23 21:27:50 +00004890
4891void
4892ProcessGDBRemote::ModulesDidLoad (ModuleList &module_list)
4893{
4894 // We must call the lldb_private::Process::ModulesDidLoad () first before we do anything
4895 Process::ModulesDidLoad (module_list);
4896
4897 // After loading shared libraries, we can ask our remote GDB server if
4898 // it needs any symbols.
4899 m_gdb_comm.ServeSymbolLookups(this);
4900}
4901
4902
Greg Claytone034a042015-05-21 20:52:06 +00004903class CommandObjectProcessGDBRemoteSpeedTest: public CommandObjectParsed
4904{
4905public:
4906 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter) :
4907 CommandObjectParsed (interpreter,
4908 "process plugin packet speed-test",
4909 "Tests packet speeds of various sizes to determine the performance characteristics of the GDB remote connection. ",
4910 NULL),
4911 m_option_group (interpreter),
4912 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),
4913 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),
4914 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),
4915 m_json (LLDB_OPT_SET_1, false, "json", 'j', "Print the output as JSON data for easy parsing.", false, true)
4916 {
4917 m_option_group.Append (&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4918 m_option_group.Append (&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4919 m_option_group.Append (&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4920 m_option_group.Append (&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4921 m_option_group.Finalize();
4922 }
4923
4924 ~CommandObjectProcessGDBRemoteSpeedTest ()
4925 {
4926 }
4927
4928
4929 Options *
4930 GetOptions () override
4931 {
4932 return &m_option_group;
4933 }
4934
4935 bool
4936 DoExecute (Args& command, CommandReturnObject &result) override
4937 {
4938 const size_t argc = command.GetArgumentCount();
4939 if (argc == 0)
4940 {
4941 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4942 if (process)
4943 {
4944 StreamSP output_stream_sp (m_interpreter.GetDebugger().GetAsyncOutputStream());
4945 result.SetImmediateOutputStream (output_stream_sp);
4946
4947 const uint32_t num_packets = (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
4948 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
4949 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
4950 const bool json = m_json.GetOptionValue().GetCurrentValue();
4951 if (output_stream_sp)
4952 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, *output_stream_sp);
4953 else
4954 {
4955 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, result.GetOutputStream());
4956 }
4957 result.SetStatus (eReturnStatusSuccessFinishResult);
4958 return true;
4959 }
4960 }
4961 else
4962 {
4963 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
4964 }
4965 result.SetStatus (eReturnStatusFailed);
4966 return false;
4967 }
4968protected:
4969 OptionGroupOptions m_option_group;
4970 OptionGroupUInt64 m_num_packets;
4971 OptionGroupUInt64 m_max_send;
4972 OptionGroupUInt64 m_max_recv;
4973 OptionGroupBoolean m_json;
4974
4975};
4976
Greg Clayton02686b82012-10-15 22:42:16 +00004977class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00004978{
4979private:
4980
4981public:
Greg Clayton02686b82012-10-15 22:42:16 +00004982 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00004983 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00004984 "process plugin packet history",
4985 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00004986 NULL)
4987 {
4988 }
4989
Greg Clayton02686b82012-10-15 22:42:16 +00004990 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton998255b2012-10-13 02:07:45 +00004991 {
4992 }
4993
4994 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004995 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton998255b2012-10-13 02:07:45 +00004996 {
Greg Clayton02686b82012-10-15 22:42:16 +00004997 const size_t argc = command.GetArgumentCount();
4998 if (argc == 0)
4999 {
5000 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5001 if (process)
5002 {
5003 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
5004 result.SetStatus (eReturnStatusSuccessFinishResult);
5005 return true;
5006 }
5007 }
5008 else
5009 {
5010 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
5011 }
5012 result.SetStatus (eReturnStatusFailed);
5013 return false;
5014 }
5015};
5016
Jason Molenda6076bf42014-05-06 04:34:52 +00005017class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed
5018{
5019private:
5020
5021public:
5022 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) :
5023 CommandObjectParsed (interpreter,
5024 "process plugin packet xfer-size",
5025 "Maximum size that lldb will try to read/write one one chunk.",
5026 NULL)
5027 {
5028 }
5029
5030 ~CommandObjectProcessGDBRemotePacketXferSize ()
5031 {
5032 }
5033
5034 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005035 DoExecute (Args& command, CommandReturnObject &result) override
Jason Molenda6076bf42014-05-06 04:34:52 +00005036 {
5037 const size_t argc = command.GetArgumentCount();
5038 if (argc == 0)
5039 {
5040 result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str());
5041 result.SetStatus (eReturnStatusFailed);
5042 return false;
5043 }
5044
5045 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5046 if (process)
5047 {
5048 const char *packet_size = command.GetArgumentAtIndex(0);
5049 errno = 0;
5050 uint64_t user_specified_max = strtoul (packet_size, NULL, 10);
5051 if (errno == 0 && user_specified_max != 0)
5052 {
5053 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max);
5054 result.SetStatus (eReturnStatusSuccessFinishResult);
5055 return true;
5056 }
5057 }
5058 result.SetStatus (eReturnStatusFailed);
5059 return false;
5060 }
5061};
5062
5063
Greg Clayton02686b82012-10-15 22:42:16 +00005064class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
5065{
5066private:
5067
5068public:
5069 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
5070 CommandObjectParsed (interpreter,
5071 "process plugin packet send",
5072 "Send a custom packet through the GDB remote protocol and print the answer. "
5073 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
5074 NULL)
5075 {
5076 }
5077
5078 ~CommandObjectProcessGDBRemotePacketSend ()
5079 {
5080 }
5081
5082 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005083 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton02686b82012-10-15 22:42:16 +00005084 {
5085 const size_t argc = command.GetArgumentCount();
5086 if (argc == 0)
5087 {
5088 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
5089 result.SetStatus (eReturnStatusFailed);
5090 return false;
5091 }
5092
5093 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5094 if (process)
5095 {
Han Ming Ong84145852012-11-26 20:42:03 +00005096 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00005097 {
Han Ming Ong84145852012-11-26 20:42:03 +00005098 const char *packet_cstr = command.GetArgumentAtIndex(0);
5099 bool send_async = true;
5100 StringExtractorGDBRemote response;
5101 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
5102 result.SetStatus (eReturnStatusSuccessFinishResult);
5103 Stream &output_strm = result.GetOutputStream();
5104 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00005105 std::string &response_str = response.GetStringRef();
5106
Han Ming Ong399289e2013-06-21 19:56:59 +00005107 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00005108 {
5109 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
5110 }
5111
Han Ming Ong84145852012-11-26 20:42:03 +00005112 if (response_str.empty())
5113 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
5114 else
5115 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00005116 }
Greg Clayton02686b82012-10-15 22:42:16 +00005117 }
Greg Clayton998255b2012-10-13 02:07:45 +00005118 return true;
5119 }
5120};
5121
Greg Claytonba4a0a52013-02-01 23:03:47 +00005122class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
5123{
5124private:
5125
5126public:
5127 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
5128 CommandObjectRaw (interpreter,
5129 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00005130 "Send a qRcmd packet through the GDB remote protocol and print the response."
5131 "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 +00005132 NULL)
5133 {
5134 }
5135
5136 ~CommandObjectProcessGDBRemotePacketMonitor ()
5137 {
5138 }
5139
5140 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005141 DoExecute (const char *command, CommandReturnObject &result) override
Greg Claytonba4a0a52013-02-01 23:03:47 +00005142 {
5143 if (command == NULL || command[0] == '\0')
5144 {
5145 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
5146 result.SetStatus (eReturnStatusFailed);
5147 return false;
5148 }
5149
5150 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5151 if (process)
5152 {
5153 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00005154 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00005155 packet.PutBytesAsRawHex8(command, strlen(command));
5156 const char *packet_cstr = packet.GetString().c_str();
5157
5158 bool send_async = true;
5159 StringExtractorGDBRemote response;
5160 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
5161 result.SetStatus (eReturnStatusSuccessFinishResult);
5162 Stream &output_strm = result.GetOutputStream();
5163 output_strm.Printf (" packet: %s\n", packet_cstr);
5164 const std::string &response_str = response.GetStringRef();
5165
5166 if (response_str.empty())
5167 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
5168 else
5169 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
5170 }
5171 return true;
5172 }
5173};
5174
Greg Clayton02686b82012-10-15 22:42:16 +00005175class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
5176{
5177private:
5178
5179public:
5180 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
5181 CommandObjectMultiword (interpreter,
5182 "process plugin packet",
5183 "Commands that deal with GDB remote packets.",
5184 NULL)
5185 {
5186 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
5187 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00005188 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Jason Molenda6076bf42014-05-06 04:34:52 +00005189 LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter)));
Greg Claytone034a042015-05-21 20:52:06 +00005190 LoadSubCommand ("speed-test", CommandObjectSP (new CommandObjectProcessGDBRemoteSpeedTest (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00005191 }
5192
5193 ~CommandObjectProcessGDBRemotePacket ()
5194 {
5195 }
5196};
Greg Clayton998255b2012-10-13 02:07:45 +00005197
5198class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
5199{
5200public:
5201 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
5202 CommandObjectMultiword (interpreter,
5203 "process plugin",
5204 "A set of commands for operating on a ProcessGDBRemote process.",
5205 "process plugin <subcommand> [<subcommand-options>]")
5206 {
5207 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
5208 }
5209
5210 ~CommandObjectMultiwordProcessGDBRemote ()
5211 {
5212 }
5213};
5214
Greg Clayton998255b2012-10-13 02:07:45 +00005215CommandObject *
5216ProcessGDBRemote::GetPluginCommandObject()
5217{
5218 if (!m_command_sp)
5219 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
5220 return m_command_sp.get();
5221}