blob: 8f2efa2cf730613ae6e60b99c190d42fce441dc2 [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
Daniel Malea93a64302012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
Virgile Bellob2f1fb22013-08-23 12:44:05 +000011#include "lldb/Host/Config.h"
Daniel Malea93a64302012-12-05 00:20:57 +000012
Chris Lattner30fdc8d2010-06-08 16:52:24 +000013// C Includes
14#include <errno.h>
Stephen Wilsona78867b2011-03-25 18:16:28 +000015#include <stdlib.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000016#ifndef LLDB_DISABLE_POSIX
Sean Callanan224f6f52012-07-19 18:07:36 +000017#include <netinet/in.h>
Greg Clayton2a48f522011-05-14 01:50:35 +000018#include <sys/mman.h> // for mmap
Virgile Bellob2f1fb22013-08-23 12:44:05 +000019#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include <sys/stat.h>
Greg Clayton2a48f522011-05-14 01:50:35 +000021#include <sys/types.h>
Stephen Wilsondc916862011-03-30 00:12:40 +000022#include <time.h>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000023
24// C++ Includes
25#include <algorithm>
26#include <map>
Benjamin Kramer3f69fa62015-04-03 10:55:00 +000027#include <mutex>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000028
Johnny Chen01a67862011-10-14 00:42:25 +000029#include "lldb/Breakpoint/Watchpoint.h"
Jim Ingham40af72e2010-06-15 19:49:27 +000030#include "lldb/Interpreter/Args.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000031#include "lldb/Core/ArchSpec.h"
32#include "lldb/Core/Debugger.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000033#include "lldb/Host/ConnectionFileDescriptor.h"
Greg Clayton53239f02011-02-08 05:05:52 +000034#include "lldb/Host/FileSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000035#include "lldb/Core/Module.h"
Greg Clayton1f746072012-08-29 21:13:06 +000036#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000037#include "lldb/Core/PluginManager.h"
38#include "lldb/Core/State.h"
Greg Claytond451c1a2012-04-13 21:24:18 +000039#include "lldb/Core/StreamFile.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000040#include "lldb/Core/StreamString.h"
41#include "lldb/Core/Timer.h"
Greg Clayton70b57652011-05-15 01:25:55 +000042#include "lldb/Core/Value.h"
Greg Claytond04f0ed2015-05-26 18:00:51 +000043#include "lldb/DataFormatters/FormatManager.h"
Zachary Turner39de3112014-09-09 20:54:56 +000044#include "lldb/Host/HostThread.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000045#include "lldb/Host/StringConvert.h"
Jason Molendad1fae142012-09-29 08:03:33 +000046#include "lldb/Host/Symbols.h"
Zachary Turner39de3112014-09-09 20:54:56 +000047#include "lldb/Host/ThreadLauncher.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000048#include "lldb/Host/TimeValue.h"
Greg Claytond04f0ed2015-05-26 18:00:51 +000049#include "lldb/Host/XML.h"
Greg Clayton02686b82012-10-15 22:42:16 +000050#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton1d19a2f2012-10-19 22:22:57 +000051#include "lldb/Interpreter/CommandObject.h"
52#include "lldb/Interpreter/CommandObjectMultiword.h"
Greg Clayton02686b82012-10-15 22:42:16 +000053#include "lldb/Interpreter/CommandReturnObject.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000054#include "lldb/Interpreter/OptionValueProperties.h"
Greg Claytone034a042015-05-21 20:52:06 +000055#include "lldb/Interpreter/Options.h"
56#include "lldb/Interpreter/OptionGroupBoolean.h"
57#include "lldb/Interpreter/OptionGroupUInt64.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000058#include "lldb/Interpreter/Property.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000059#include "lldb/Symbol/ObjectFile.h"
60#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"
Todd Fialaaf245d12014-06-30 21:05:18 +000069#include "Plugins/Process/Utility/FreeBSDSignals.h"
Peter Collingbourne99f9aa02011-06-03 20:40:38 +000070#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000071#include "Plugins/Process/Utility/LinuxSignals.h"
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +000072#include "Plugins/Process/Utility/MipsLinuxSignals.h"
Jason Molendac42d2432012-07-25 03:40:06 +000073#include "Plugins/Process/Utility/StopInfoMachException.h"
Jim Ingham43c555d2012-07-04 00:35:43 +000074#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
Greg Claytonc982c762010-07-09 20:39:50 +000075#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000076#include "GDBRemoteRegisterContext.h"
77#include "ProcessGDBRemote.h"
78#include "ProcessGDBRemoteLog.h"
79#include "ThreadGDBRemote.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000080
Tamas Berghammerdb264a62015-03-31 09:52:22 +000081#define DEBUGSERVER_BASENAME "debugserver"
82using namespace lldb;
83using namespace lldb_private;
84using namespace lldb_private::process_gdb_remote;
Jason Molenda5e8534e2012-10-03 01:29:34 +000085
Greg Claytonc1422c12012-04-09 22:46:21 +000086namespace lldb
87{
88 // Provide a function that can easily dump the packet history if we know a
89 // ProcessGDBRemote * value (which we can get from logs or from debugging).
90 // We need the function in the lldb namespace so it makes it into the final
91 // executable since the LLDB shared library only exports stuff in the lldb
92 // namespace. This allows you to attach with a debugger and call this
93 // function and get the packet history dumped to a file.
94 void
95 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
96 {
Tamas Berghammerdb264a62015-03-31 09:52:22 +000097 StreamFile strm;
98 Error error (strm.GetFile().Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate));
Greg Claytond451c1a2012-04-13 21:24:18 +000099 if (error.Success())
100 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
Greg Claytonc1422c12012-04-09 22:46:21 +0000101 }
Filipe Cabecinhasc34f7762012-05-23 16:27:09 +0000102}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000103
Greg Clayton7f982402013-07-15 22:54:20 +0000104namespace {
Steve Pucci5ec012d2014-01-16 22:18:14 +0000105
Greg Clayton7f982402013-07-15 22:54:20 +0000106 static PropertyDefinition
107 g_properties[] =
108 {
109 { "packet-timeout" , OptionValue::eTypeUInt64 , true , 1, NULL, NULL, "Specify the default packet timeout in seconds." },
Greg Claytonef8180a2013-10-15 00:14:28 +0000110 { "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 +0000111 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
112 };
113
114 enum
115 {
Greg Claytonef8180a2013-10-15 00:14:28 +0000116 ePropertyPacketTimeout,
117 ePropertyTargetDefinitionFile
Greg Clayton7f982402013-07-15 22:54:20 +0000118 };
119
120 class PluginProperties : public Properties
121 {
122 public:
123
124 static ConstString
125 GetSettingName ()
126 {
127 return ProcessGDBRemote::GetPluginNameStatic();
128 }
129
130 PluginProperties() :
131 Properties ()
132 {
133 m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
134 m_collection_sp->Initialize(g_properties);
135 }
136
137 virtual
138 ~PluginProperties()
139 {
140 }
141
142 uint64_t
143 GetPacketTimeout()
144 {
145 const uint32_t idx = ePropertyPacketTimeout;
146 return m_collection_sp->GetPropertyAtIndexAsUInt64(NULL, idx, g_properties[idx].default_uint_value);
147 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000148
149 bool
150 SetPacketTimeout(uint64_t timeout)
151 {
152 const uint32_t idx = ePropertyPacketTimeout;
153 return m_collection_sp->SetPropertyAtIndexAsUInt64(NULL, idx, timeout);
154 }
155
Greg Claytonef8180a2013-10-15 00:14:28 +0000156 FileSpec
157 GetTargetDefinitionFile () const
158 {
159 const uint32_t idx = ePropertyTargetDefinitionFile;
160 return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
161 }
Greg Clayton7f982402013-07-15 22:54:20 +0000162 };
163
164 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
165
166 static const ProcessKDPPropertiesSP &
167 GetGlobalPluginProperties()
168 {
169 static ProcessKDPPropertiesSP g_settings_sp;
170 if (!g_settings_sp)
171 g_settings_sp.reset (new PluginProperties ());
172 return g_settings_sp;
173 }
174
175} // anonymous namespace end
176
Aidan Doddsc0c83852015-05-08 09:36:31 +0000177class ProcessGDBRemote::GDBLoadedModuleInfoList
178{
179public:
180
181 class LoadedModuleInfo
182 {
183 public:
184
185 enum e_data_point
186 {
187 e_has_name = 0,
188 e_has_base ,
189 e_has_dynamic ,
190 e_has_link_map ,
191 e_num
192 };
193
194 LoadedModuleInfo ()
195 {
196 for (uint32_t i = 0; i < e_num; ++i)
197 m_has[i] = false;
198 };
199
200 void set_name (const std::string & name)
201 {
202 m_name = name;
203 m_has[e_has_name] = true;
204 }
205 bool get_name (std::string & out) const
206 {
207 out = m_name;
208 return m_has[e_has_name];
209 }
210
211 void set_base (const lldb::addr_t base)
212 {
213 m_base = base;
214 m_has[e_has_base] = true;
215 }
216 bool get_base (lldb::addr_t & out) const
217 {
218 out = m_base;
219 return m_has[e_has_base];
220 }
221
222 void set_link_map (const lldb::addr_t addr)
223 {
224 m_link_map = addr;
225 m_has[e_has_link_map] = true;
226 }
227 bool get_link_map (lldb::addr_t & out) const
228 {
229 out = m_link_map;
230 return m_has[e_has_link_map];
231 }
232
233 void set_dynamic (const lldb::addr_t addr)
234 {
235 m_dynamic = addr;
236 m_has[e_has_dynamic] = true;
237 }
238 bool get_dynamic (lldb::addr_t & out) const
239 {
240 out = m_dynamic;
241 return m_has[e_has_dynamic];
242 }
243
244 bool has_info (e_data_point datum)
245 {
246 assert (datum < e_num);
247 return m_has[datum];
248 }
249
250 protected:
251
252 bool m_has[e_num];
253 std::string m_name;
254 lldb::addr_t m_link_map;
255 lldb::addr_t m_base;
256 lldb::addr_t m_dynamic;
257 };
258
259 GDBLoadedModuleInfoList ()
260 : m_list ()
261 , m_link_map (LLDB_INVALID_ADDRESS)
262 {}
263
264 void add (const LoadedModuleInfo & mod)
265 {
266 m_list.push_back (mod);
267 }
268
269 void clear ()
270 {
271 m_list.clear ();
272 }
273
274 std::vector<LoadedModuleInfo> m_list;
275 lldb::addr_t m_link_map;
276};
277
Greg Claytonfda4fab2014-01-10 22:24:11 +0000278// TODO Randomly assigning a port is unsafe. We should get an unused
279// ephemeral port from the kernel and make sure we reserve it before passing
280// it to debugserver.
281
282#if defined (__APPLE__)
283#define LOW_PORT (IPPORT_RESERVED)
284#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
285#else
286#define LOW_PORT (1024u)
287#define HIGH_PORT (49151u)
288#endif
289
Todd Fiala013434e2014-07-09 01:29:05 +0000290#if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000291static bool rand_initialized = false;
292
Greg Claytonfda4fab2014-01-10 22:24:11 +0000293static inline uint16_t
294get_random_port ()
295{
296 if (!rand_initialized)
297 {
298 time_t seed = time(NULL);
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000299
Greg Claytonfda4fab2014-01-10 22:24:11 +0000300 rand_initialized = true;
301 srand(seed);
302 }
303 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
304}
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000305#endif
Greg Claytonfda4fab2014-01-10 22:24:11 +0000306
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000307ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000308ProcessGDBRemote::GetPluginNameStatic()
309{
Greg Clayton57abc5d2013-05-10 21:47:16 +0000310 static ConstString g_name("gdb-remote");
311 return g_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000312}
313
314const char *
315ProcessGDBRemote::GetPluginDescriptionStatic()
316{
317 return "GDB Remote protocol based debugging plug-in.";
318}
319
320void
321ProcessGDBRemote::Terminate()
322{
323 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
324}
325
326
Greg Claytonc3776bf2012-02-09 06:16:32 +0000327lldb::ProcessSP
328ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000329{
Greg Claytonc3776bf2012-02-09 06:16:32 +0000330 lldb::ProcessSP process_sp;
331 if (crash_file_path == NULL)
332 process_sp.reset (new ProcessGDBRemote (target, listener));
333 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000334}
335
336bool
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000337ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000338{
Greg Clayton596ed242011-10-21 21:41:45 +0000339 if (plugin_specified_by_name)
340 return true;
341
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000342 // For now we are just making sure the file exists for a given module
Greg Claytonaa149cb2011-08-11 02:48:45 +0000343 Module *exe_module = target.GetExecutableModulePointer();
344 if (exe_module)
Greg Claytonc3776bf2012-02-09 06:16:32 +0000345 {
346 ObjectFile *exe_objfile = exe_module->GetObjectFile();
347 // We can't debug core files...
348 switch (exe_objfile->GetType())
349 {
350 case ObjectFile::eTypeInvalid:
351 case ObjectFile::eTypeCoreFile:
352 case ObjectFile::eTypeDebugInfo:
353 case ObjectFile::eTypeObjectFile:
354 case ObjectFile::eTypeSharedLibrary:
355 case ObjectFile::eTypeStubLibrary:
Greg Clayton23f8c952014-03-24 23:10:19 +0000356 case ObjectFile::eTypeJIT:
Greg Claytonc3776bf2012-02-09 06:16:32 +0000357 return false;
358 case ObjectFile::eTypeExecutable:
359 case ObjectFile::eTypeDynamicLinker:
360 case ObjectFile::eTypeUnknown:
361 break;
362 }
Greg Claytonaa149cb2011-08-11 02:48:45 +0000363 return exe_module->GetFileSpec().Exists();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000364 }
Jim Ingham5aee1622010-08-09 23:31:02 +0000365 // However, if there is no executable module, we return true since we might be preparing to attach.
366 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000367}
368
369//----------------------------------------------------------------------
370// ProcessGDBRemote constructor
371//----------------------------------------------------------------------
372ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
373 Process (target, listener),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000374 m_flags (0),
Tamas Berghammere13c2732015-02-11 10:29:30 +0000375 m_gdb_comm (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000376 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton09c3e3d2011-12-06 04:51:14 +0000377 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000378 m_register_info (),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000379 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
Jim Ingham455fa5c2012-11-01 01:15:33 +0000380 m_async_thread_state_mutex(Mutex::eMutexTypeRecursive),
Greg Clayton9e920902012-04-10 02:25:43 +0000381 m_thread_ids (),
Greg Clayton71fc2a32011-02-12 06:28:37 +0000382 m_continue_c_tids (),
383 m_continue_C_tids (),
384 m_continue_s_tids (),
385 m_continue_S_tids (),
Jason Molenda6076bf42014-05-06 04:34:52 +0000386 m_max_memory_size (0),
387 m_remote_stub_max_memory_size (0),
Greg Clayton4116e932012-05-15 02:33:01 +0000388 m_addr_to_mmap_size (),
389 m_thread_create_bp_sp (),
Jim Ingham43c555d2012-07-04 00:35:43 +0000390 m_waiting_for_attach (false),
Jason Molenda5e8534e2012-10-03 01:29:34 +0000391 m_destroy_tried_resuming (false),
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000392 m_command_sp (),
Ewan Crawford78baa192015-05-13 09:18:18 +0000393 m_breakpoint_pc_offset (0),
394 m_initial_tid (LLDB_INVALID_THREAD_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000395{
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000396 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
397 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Inghamb1e2e842012-04-12 18:49:31 +0000398 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Greg Clayton7f982402013-07-15 22:54:20 +0000399 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
400 if (timeout_seconds > 0)
401 m_gdb_comm.SetPacketTimeout(timeout_seconds);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000402}
403
404//----------------------------------------------------------------------
405// Destructor
406//----------------------------------------------------------------------
407ProcessGDBRemote::~ProcessGDBRemote()
408{
409 // m_mach_process.UnregisterNotificationCallbacks (this);
410 Clear();
Greg Clayton1ed54f52011-10-01 00:45:15 +0000411 // We need to call finalize on the process before destroying ourselves
412 // to make sure all of the broadcaster cleanup goes as planned. If we
413 // destruct this class, then Process::~Process() might have problems
414 // trying to fully destroy the broadcaster.
415 Finalize();
Jim Ingham455fa5c2012-11-01 01:15:33 +0000416
417 // The general Finalize is going to try to destroy the process and that SHOULD
418 // shut down the async thread. However, if we don't kill it it will get stranded and
419 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
420 StopAsyncThread();
421 KillDebugserverProcess();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000422}
423
424//----------------------------------------------------------------------
425// PluginInterface
426//----------------------------------------------------------------------
Greg Clayton57abc5d2013-05-10 21:47:16 +0000427ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000428ProcessGDBRemote::GetPluginName()
429{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000430 return GetPluginNameStatic();
431}
432
433uint32_t
434ProcessGDBRemote::GetPluginVersion()
435{
436 return 1;
437}
438
Greg Claytonef8180a2013-10-15 00:14:28 +0000439bool
440ProcessGDBRemote::ParsePythonTargetDefinition(const FileSpec &target_definition_fspec)
441{
442 ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
443 Error error;
Zachary Turner0641ca12015-03-17 20:04:04 +0000444 StructuredData::ObjectSP module_object_sp(interpreter->LoadPluginModule(target_definition_fspec, error));
Greg Claytonef8180a2013-10-15 00:14:28 +0000445 if (module_object_sp)
446 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000447 StructuredData::DictionarySP target_definition_sp(
448 interpreter->GetDynamicSettings(module_object_sp, &GetTarget(), "gdb-server-target-definition", error));
Greg Claytonef8180a2013-10-15 00:14:28 +0000449
Zachary Turner0641ca12015-03-17 20:04:04 +0000450 if (target_definition_sp)
Greg Claytonef8180a2013-10-15 00:14:28 +0000451 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000452 StructuredData::ObjectSP target_object(target_definition_sp->GetValueForKey("host-info"));
453 if (target_object)
Greg Clayton312bcbe2013-10-17 01:10:23 +0000454 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000455 if (auto host_info_dict = target_object->GetAsDictionary())
Greg Clayton312bcbe2013-10-17 01:10:23 +0000456 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000457 StructuredData::ObjectSP triple_value = host_info_dict->GetValueForKey("triple");
458 if (auto triple_string_value = triple_value->GetAsString())
459 {
460 std::string triple_string = triple_string_value->GetValue();
461 ArchSpec host_arch(triple_string.c_str());
462 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture()))
463 {
464 GetTarget().SetArchitecture(host_arch);
465 }
466 }
Greg Clayton312bcbe2013-10-17 01:10:23 +0000467 }
Greg Clayton312bcbe2013-10-17 01:10:23 +0000468 }
Zachary Turner0641ca12015-03-17 20:04:04 +0000469 m_breakpoint_pc_offset = 0;
470 StructuredData::ObjectSP breakpoint_pc_offset_value = target_definition_sp->GetValueForKey("breakpoint-pc-offset");
471 if (breakpoint_pc_offset_value)
472 {
473 if (auto breakpoint_pc_int_value = breakpoint_pc_offset_value->GetAsInteger())
474 m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
475 }
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000476
Greg Claytond04f0ed2015-05-26 18:00:51 +0000477 if (m_register_info.SetRegisterInfo(*target_definition_sp, GetTarget().GetArchitecture()) > 0)
Greg Claytonef8180a2013-10-15 00:14:28 +0000478 {
479 return true;
480 }
481 }
482 }
483 return false;
484}
485
Greg Claytond04f0ed2015-05-26 18:00:51 +0000486static size_t
487SplitCommaSeparatedRegisterNumberString(const llvm::StringRef &comma_separated_regiter_numbers, std::vector<uint32_t> &regnums, int base)
488{
489 regnums.clear();
490 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
491 value_pair.second = comma_separated_regiter_numbers;
492 do
493 {
494 value_pair = value_pair.second.split(',');
495 if (!value_pair.first.empty())
496 {
497 uint32_t reg = StringConvert::ToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, base);
498 if (reg != LLDB_INVALID_REGNUM)
499 regnums.push_back (reg);
500 }
501 } while (!value_pair.second.empty());
502 return regnums.size();
503}
504
Greg Claytonef8180a2013-10-15 00:14:28 +0000505
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000506void
Greg Clayton513c26c2011-01-29 07:10:55 +0000507ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000508{
Greg Clayton513c26c2011-01-29 07:10:55 +0000509 if (!force && m_register_info.GetNumRegisters() > 0)
510 return;
511
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000512 m_register_info.Clear();
Greg Claytond04f0ed2015-05-26 18:00:51 +0000513
514 // Check if qHostInfo specified a specific packet timeout for this connection.
515 // If so then lets update our setting so the user knows what the timeout is
516 // and can see it.
517 const uint32_t host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
518 if (host_packet_timeout)
519 {
520 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout);
521 }
522
523 if (GetGDBServerRegisterInfo ())
524 return;
525
526 char packet[128];
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000527 uint32_t reg_offset = 0;
528 uint32_t reg_num = 0;
Greg Clayton23f59502012-07-17 03:23:13 +0000529 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Greg Clayton576d8832011-03-22 04:00:09 +0000530 response_type == StringExtractorGDBRemote::eResponse;
531 ++reg_num)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000532 {
Greg Clayton513c26c2011-01-29 07:10:55 +0000533 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
Andy Gibbsa297a972013-06-19 19:04:53 +0000534 assert (packet_len < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000535 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000536 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000537 {
Greg Clayton576d8832011-03-22 04:00:09 +0000538 response_type = response.GetResponseType();
539 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000540 {
541 std::string name;
542 std::string value;
543 ConstString reg_name;
544 ConstString alt_name;
545 ConstString set_name;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000546 std::vector<uint32_t> value_regs;
547 std::vector<uint32_t> invalidate_regs;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000548 RegisterInfo reg_info = { NULL, // Name
549 NULL, // Alt name
550 0, // byte size
551 reg_offset, // offset
552 eEncodingUint, // encoding
553 eFormatHex, // formate
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000554 {
555 LLDB_INVALID_REGNUM, // GCC reg num
556 LLDB_INVALID_REGNUM, // DWARF reg num
557 LLDB_INVALID_REGNUM, // generic reg num
Jason Molendafbcb7f22010-09-10 07:49:16 +0000558 reg_num, // GDB reg num
559 reg_num // native register number
Greg Clayton435d85a2012-02-29 19:27:27 +0000560 },
561 NULL,
562 NULL
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000563 };
564
565 while (response.GetNameColonValue(name, value))
566 {
567 if (name.compare("name") == 0)
568 {
569 reg_name.SetCString(value.c_str());
570 }
571 else if (name.compare("alt-name") == 0)
572 {
573 alt_name.SetCString(value.c_str());
574 }
575 else if (name.compare("bitsize") == 0)
576 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000577 reg_info.byte_size = StringConvert::ToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000578 }
579 else if (name.compare("offset") == 0)
580 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000581 uint32_t offset = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda743e86a2010-06-11 23:44:18 +0000582 if (reg_offset != offset)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000583 {
584 reg_offset = offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000585 }
586 }
587 else if (name.compare("encoding") == 0)
588 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000589 const Encoding encoding = Args::StringToEncoding (value.c_str());
590 if (encoding != eEncodingInvalid)
591 reg_info.encoding = encoding;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000592 }
593 else if (name.compare("format") == 0)
594 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000595 Format format = eFormatInvalid;
596 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
597 reg_info.format = format;
598 else if (value.compare("binary") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000599 reg_info.format = eFormatBinary;
600 else if (value.compare("decimal") == 0)
601 reg_info.format = eFormatDecimal;
602 else if (value.compare("hex") == 0)
603 reg_info.format = eFormatHex;
604 else if (value.compare("float") == 0)
605 reg_info.format = eFormatFloat;
606 else if (value.compare("vector-sint8") == 0)
607 reg_info.format = eFormatVectorOfSInt8;
608 else if (value.compare("vector-uint8") == 0)
609 reg_info.format = eFormatVectorOfUInt8;
610 else if (value.compare("vector-sint16") == 0)
611 reg_info.format = eFormatVectorOfSInt16;
612 else if (value.compare("vector-uint16") == 0)
613 reg_info.format = eFormatVectorOfUInt16;
614 else if (value.compare("vector-sint32") == 0)
615 reg_info.format = eFormatVectorOfSInt32;
616 else if (value.compare("vector-uint32") == 0)
617 reg_info.format = eFormatVectorOfUInt32;
618 else if (value.compare("vector-float32") == 0)
619 reg_info.format = eFormatVectorOfFloat32;
620 else if (value.compare("vector-uint128") == 0)
621 reg_info.format = eFormatVectorOfUInt128;
622 }
623 else if (name.compare("set") == 0)
624 {
625 set_name.SetCString(value.c_str());
626 }
627 else if (name.compare("gcc") == 0)
628 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000629 reg_info.kinds[eRegisterKindGCC] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000630 }
631 else if (name.compare("dwarf") == 0)
632 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000633 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000634 }
635 else if (name.compare("generic") == 0)
636 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000637 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000638 }
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000639 else if (name.compare("container-regs") == 0)
640 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000641 SplitCommaSeparatedRegisterNumberString(value, value_regs, 16);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000642 }
643 else if (name.compare("invalidate-regs") == 0)
644 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000645 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 16);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000646 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000647 }
648
Jason Molenda743e86a2010-06-11 23:44:18 +0000649 reg_info.byte_offset = reg_offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000650 assert (reg_info.byte_size != 0);
651 reg_offset += reg_info.byte_size;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000652 if (!value_regs.empty())
653 {
654 value_regs.push_back(LLDB_INVALID_REGNUM);
655 reg_info.value_regs = value_regs.data();
656 }
657 if (!invalidate_regs.empty())
658 {
659 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
660 reg_info.invalidate_regs = invalidate_regs.data();
661 }
662
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000663 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
664 }
Todd Fiala1a634402014-01-08 07:52:40 +0000665 else
666 {
667 break; // ensure exit before reg_num is incremented
668 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000669 }
670 else
671 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000672 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000673 }
674 }
675
Greg Claytond04f0ed2015-05-26 18:00:51 +0000676 if (m_register_info.GetNumRegisters() > 0)
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000677 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000678 m_register_info.Finalize(GetTarget().GetArchitecture());
679 return;
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000680 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000681
Greg Claytond04f0ed2015-05-26 18:00:51 +0000682 FileSpec target_definition_fspec = GetGlobalPluginProperties()->GetTargetDefinitionFile ();
Greg Clayton312bcbe2013-10-17 01:10:23 +0000683
Greg Claytond04f0ed2015-05-26 18:00:51 +0000684 if (target_definition_fspec)
685 {
686 // See if we can get register definitions from a python file
687 if (ParsePythonTargetDefinition (target_definition_fspec))
688 return;
Greg Claytonef8180a2013-10-15 00:14:28 +0000689 }
690
Johnny Chen2fa9de12012-05-14 18:44:23 +0000691 // We didn't get anything if the accumulated reg_num is zero. See if we are
692 // debugging ARM and fill with a hard coded register set until we can get an
693 // updated debugserver down on the devices.
694 // On the other hand, if the accumulated reg_num is positive, see if we can
695 // add composite registers to the existing primordial ones.
Greg Claytond04f0ed2015-05-26 18:00:51 +0000696 bool from_scratch = (m_register_info.GetNumRegisters() == 0);
Johnny Chen2fa9de12012-05-14 18:44:23 +0000697
698 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000699 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
700 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
701
702 // Use the process' architecture instead of the host arch, if available
703 ArchSpec remote_arch;
704 if (remote_process_arch.IsValid ())
705 remote_arch = remote_process_arch;
706 else
707 remote_arch = remote_host_arch;
708
Johnny Chen2fa9de12012-05-14 18:44:23 +0000709 if (!target_arch.IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000710 {
Johnny Chen2fa9de12012-05-14 18:44:23 +0000711 if (remote_arch.IsValid()
712 && remote_arch.GetMachine() == llvm::Triple::arm
713 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
714 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000715 }
Johnny Chen2fa9de12012-05-14 18:44:23 +0000716 else if (target_arch.GetMachine() == llvm::Triple::arm)
717 {
718 m_register_info.HardcodeARMRegisters(from_scratch);
719 }
720
721 // At this point, we can finalize our register info.
Greg Claytond04f0ed2015-05-26 18:00:51 +0000722 m_register_info.Finalize (GetTarget().GetArchitecture());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000723}
724
725Error
726ProcessGDBRemote::WillLaunch (Module* module)
727{
728 return WillLaunchOrAttach ();
729}
730
731Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000732ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000733{
734 return WillLaunchOrAttach ();
735}
736
737Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000738ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000739{
740 return WillLaunchOrAttach ();
741}
742
743Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000744ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +0000745{
Todd Fialaaf245d12014-06-30 21:05:18 +0000746 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Claytonb766a732011-02-04 01:58:07 +0000747 Error error (WillLaunchOrAttach ());
748
749 if (error.Fail())
750 return error;
751
Greg Clayton2289fa42011-04-30 01:09:13 +0000752 error = ConnectToDebugserver (remote_url);
Greg Claytonb766a732011-02-04 01:58:07 +0000753
754 if (error.Fail())
755 return error;
756 StartAsyncThread ();
757
Greg Claytonc574ede2011-03-10 02:26:48 +0000758 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonb766a732011-02-04 01:58:07 +0000759 if (pid == LLDB_INVALID_PROCESS_ID)
760 {
761 // We don't have a valid process ID, so note that we are connected
762 // and could now request to launch or attach, or get remote process
763 // listings...
764 SetPrivateState (eStateConnected);
765 }
766 else
767 {
768 // We have a valid process
769 SetID (pid);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000770 GetThreadList();
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000771 StringExtractorGDBRemote response;
772 if (m_gdb_comm.GetStopReply(response))
Greg Claytonb766a732011-02-04 01:58:07 +0000773 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000774 SetLastStopPacket(response);
Ewan Crawford78baa192015-05-13 09:18:18 +0000775
776 // '?' Packets must be handled differently in non-stop mode
777 if (GetTarget().GetNonStopModeEnabled())
778 HandleStopReplySequence();
779
Jason Molendac62bd7b2013-12-21 05:20:36 +0000780 if (!m_target.GetArchitecture().IsValid())
781 {
782 if (m_gdb_comm.GetProcessArchitecture().IsValid())
783 {
784 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
785 }
786 else
787 {
788 m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
789 }
Carlo Kok74389122013-10-14 07:09:13 +0000790 }
791
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000792 const StateType state = SetThreadStopInfo (response);
Greg Claytonb766a732011-02-04 01:58:07 +0000793 if (state == eStateStopped)
794 {
795 SetPrivateState (state);
796 }
797 else
Daniel Malead01b2952012-11-29 21:49:15 +0000798 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 +0000799 }
800 else
Daniel Malead01b2952012-11-29 21:49:15 +0000801 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 +0000802 }
Jason Molenda16d127c2012-05-03 22:37:30 +0000803
Todd Fialaaf245d12014-06-30 21:05:18 +0000804 if (log)
805 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");
806
807
808 if (error.Success()
Jason Molenda16d127c2012-05-03 22:37:30 +0000809 && !GetTarget().GetArchitecture().IsValid()
810 && m_gdb_comm.GetHostArchitecture().IsValid())
811 {
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000812 // Prefer the *process'* architecture over that of the *host*, if available.
813 if (m_gdb_comm.GetProcessArchitecture().IsValid())
814 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
815 else
816 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molenda16d127c2012-05-03 22:37:30 +0000817 }
818
Todd Fialaaf245d12014-06-30 21:05:18 +0000819 if (log)
820 log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": normalized target architecture triple: %s", __FUNCTION__, GetID (), GetTarget ().GetArchitecture ().GetTriple ().getTriple ().c_str ());
821
822 // Set the Unix signals properly for the target.
823 // FIXME Add a gdb-remote packet to discover dynamically.
824 if (error.Success ())
825 {
Tamas Berghammerac839822015-03-04 11:34:10 +0000826 const ArchSpec arch_spec = m_gdb_comm.GetHostArchitecture();
Todd Fialaaf245d12014-06-30 21:05:18 +0000827 if (arch_spec.IsValid ())
828 {
829 if (log)
830 log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": determining unix signals type based on architecture %s, triple %s", __FUNCTION__, GetID (), arch_spec.GetArchitectureName () ? arch_spec.GetArchitectureName () : "<null>", arch_spec.GetTriple ().getTriple ().c_str ());
831
832 switch (arch_spec.GetTriple ().getOS ())
833 {
834 case llvm::Triple::Linux:
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +0000835 if (arch_spec.GetTriple ().getArch () == llvm::Triple::mips64 || arch_spec.GetTriple ().getArch () == llvm::Triple::mips64el)
836 SetUnixSignals (UnixSignalsSP (new process_linux::MipsLinuxSignals ()));
837 else
838 SetUnixSignals (UnixSignalsSP (new process_linux::LinuxSignals ()));
Todd Fialaaf245d12014-06-30 21:05:18 +0000839 if (log)
840 log->Printf ("ProcessGDBRemote::%s using Linux unix signals type for pid %" PRIu64, __FUNCTION__, GetID ());
841 break;
842 case llvm::Triple::OpenBSD:
843 case llvm::Triple::FreeBSD:
844 case llvm::Triple::NetBSD:
Todd Fiala4ceced32014-08-29 17:35:57 +0000845 SetUnixSignals (UnixSignalsSP (new FreeBSDSignals ()));
Todd Fialaaf245d12014-06-30 21:05:18 +0000846 if (log)
847 log->Printf ("ProcessGDBRemote::%s using *BSD unix signals type for pid %" PRIu64, __FUNCTION__, GetID ());
848 break;
849 default:
Todd Fiala4ceced32014-08-29 17:35:57 +0000850 SetUnixSignals (UnixSignalsSP (new UnixSignals ()));
Todd Fialaaf245d12014-06-30 21:05:18 +0000851 if (log)
852 log->Printf ("ProcessGDBRemote::%s using generic unix signals type for pid %" PRIu64, __FUNCTION__, GetID ());
853 break;
854 }
855 }
856 }
857
Greg Claytonb766a732011-02-04 01:58:07 +0000858 return error;
859}
860
861Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000862ProcessGDBRemote::WillLaunchOrAttach ()
863{
864 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000865 m_stdio_communication.Clear ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000866 return error;
867}
868
869//----------------------------------------------------------------------
870// Process Control
871//----------------------------------------------------------------------
872Error
Jean-Daniel Dupas7782de92013-12-09 22:52:50 +0000873ProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000874{
Todd Fiala75f47c32014-10-11 21:42:09 +0000875 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton4957bf62010-09-30 21:49:03 +0000876 Error error;
Greg Clayton982c9762011-11-03 21:22:33 +0000877
Todd Fiala75f47c32014-10-11 21:42:09 +0000878 if (log)
879 log->Printf ("ProcessGDBRemote::%s() entered", __FUNCTION__);
880
Greg Clayton982c9762011-11-03 21:22:33 +0000881 uint32_t launch_flags = launch_info.GetFlags().Get();
882 const char *stdin_path = NULL;
883 const char *stdout_path = NULL;
884 const char *stderr_path = NULL;
885 const char *working_dir = launch_info.GetWorkingDirectory();
886
Zachary Turner696b5282014-08-14 16:01:25 +0000887 const FileAction *file_action;
Greg Clayton982c9762011-11-03 21:22:33 +0000888 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
889 if (file_action)
890 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000891 if (file_action->GetAction() == FileAction::eFileActionOpen)
Greg Clayton982c9762011-11-03 21:22:33 +0000892 stdin_path = file_action->GetPath();
893 }
894 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
895 if (file_action)
896 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000897 if (file_action->GetAction() == FileAction::eFileActionOpen)
Greg Clayton982c9762011-11-03 21:22:33 +0000898 stdout_path = file_action->GetPath();
899 }
900 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
901 if (file_action)
902 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000903 if (file_action->GetAction() == FileAction::eFileActionOpen)
Greg Clayton982c9762011-11-03 21:22:33 +0000904 stderr_path = file_action->GetPath();
905 }
906
Todd Fiala75f47c32014-10-11 21:42:09 +0000907 if (log)
908 {
909 if (stdin_path || stdout_path || stderr_path)
Vince Harron4a8abd32015-02-13 19:15:24 +0000910 log->Printf ("ProcessGDBRemote::%s provided with STDIO paths via launch_info: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000911 __FUNCTION__,
912 stdin_path ? stdin_path : "<null>",
913 stdout_path ? stdout_path : "<null>",
914 stderr_path ? stderr_path : "<null>");
915 else
916 log->Printf ("ProcessGDBRemote::%s no STDIO paths given via launch_info", __FUNCTION__);
917 }
918
Vince Harrondf3f00f2015-02-10 21:09:04 +0000919 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
920 if (stdin_path || disable_stdio)
921 {
922 // the inferior will be reading stdin from the specified file
923 // or stdio is completely disabled
924 m_stdin_forward = false;
925 }
926 else
927 {
928 m_stdin_forward = true;
929 }
930
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000931 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
932 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
933 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000934
Greg Clayton982c9762011-11-03 21:22:33 +0000935 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000936 if (object_file)
937 {
Greg Clayton71337622011-02-24 22:24:29 +0000938 // Make sure we aren't already connected?
939 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000940 {
Greg Clayton91a9b2472013-12-04 19:19:12 +0000941 error = LaunchAndConnectToDebugserver (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000942 }
943
944 if (error.Success())
945 {
946 lldb_utility::PseudoTerminal pty;
947 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000948
Greg Claytonf58c2692011-06-24 22:32:10 +0000949 PlatformSP platform_sp (m_target.GetPlatform());
Vince Harrondf3f00f2015-02-10 21:09:04 +0000950 if (disable_stdio)
Greg Clayton71337622011-02-24 22:24:29 +0000951 {
Vince Harrondf3f00f2015-02-10 21:09:04 +0000952 // set to /dev/null unless redirected to a file above
953 if (!stdin_path)
954 stdin_path = "/dev/null";
955 if (!stdout_path)
956 stdout_path = "/dev/null";
957 if (!stderr_path)
958 stderr_path = "/dev/null";
959 }
960 else if (platform_sp && platform_sp->IsHost())
961 {
962 // If the debugserver is local and we aren't disabling STDIO, lets use
963 // a pseudo terminal to instead of relying on the 'O' packets for stdio
964 // since 'O' packets can really slow down debugging if the inferior
965 // does a lot of output.
Greg Clayton71337622011-02-24 22:24:29 +0000966 const char *slave_name = NULL;
967 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000968 {
Greg Clayton71337622011-02-24 22:24:29 +0000969 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
970 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000971 }
Greg Clayton71337622011-02-24 22:24:29 +0000972 if (stdin_path == NULL)
973 stdin_path = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000974
Greg Clayton71337622011-02-24 22:24:29 +0000975 if (stdout_path == NULL)
976 stdout_path = slave_name;
977
978 if (stderr_path == NULL)
979 stderr_path = slave_name;
Todd Fiala75f47c32014-10-11 21:42:09 +0000980
981 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +0000982 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 +0000983 __FUNCTION__,
984 stdin_path ? stdin_path : "<null>",
985 stdout_path ? stdout_path : "<null>",
986 stderr_path ? stderr_path : "<null>");
Greg Clayton71337622011-02-24 22:24:29 +0000987 }
988
Todd Fiala75f47c32014-10-11 21:42:09 +0000989 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +0000990 log->Printf ("ProcessGDBRemote::%s final STDIO paths after all adjustments: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000991 __FUNCTION__,
992 stdin_path ? stdin_path : "<null>",
993 stdout_path ? stdout_path : "<null>",
994 stderr_path ? stderr_path : "<null>");
995
996 if (stdin_path)
Greg Clayton71337622011-02-24 22:24:29 +0000997 m_gdb_comm.SetSTDIN (stdin_path);
998 if (stdout_path)
999 m_gdb_comm.SetSTDOUT (stdout_path);
1000 if (stderr_path)
1001 m_gdb_comm.SetSTDERR (stderr_path);
1002
1003 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
Jim Ingham106d0282014-06-25 02:32:56 +00001004 m_gdb_comm.SetDetachOnError (launch_flags & eLaunchFlagDetachOnError);
Greg Clayton71337622011-02-24 22:24:29 +00001005
Greg Claytonc4103b32011-05-08 04:53:50 +00001006 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Clayton71337622011-02-24 22:24:29 +00001007
Jason Molendaa3329782014-03-29 18:54:20 +00001008 const char * launch_event_data = launch_info.GetLaunchEventData();
1009 if (launch_event_data != NULL && *launch_event_data != '\0')
1010 m_gdb_comm.SendLaunchEventDataPacket (launch_event_data);
1011
Greg Clayton71337622011-02-24 22:24:29 +00001012 if (working_dir && working_dir[0])
1013 {
1014 m_gdb_comm.SetWorkingDir (working_dir);
1015 }
1016
1017 // Send the environment and the program + arguments after we connect
Greg Clayton982c9762011-11-03 21:22:33 +00001018 const Args &environment = launch_info.GetEnvironmentEntries();
1019 if (environment.GetArgumentCount())
Greg Clayton71337622011-02-24 22:24:29 +00001020 {
Greg Clayton982c9762011-11-03 21:22:33 +00001021 size_t num_environment_entries = environment.GetArgumentCount();
1022 for (size_t i=0; i<num_environment_entries; ++i)
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001023 {
Greg Clayton982c9762011-11-03 21:22:33 +00001024 const char *env_entry = environment.GetArgumentAtIndex(i);
1025 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Clayton71337622011-02-24 22:24:29 +00001026 break;
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001027 }
Greg Clayton71337622011-02-24 22:24:29 +00001028 }
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001029
Greg Clayton71337622011-02-24 22:24:29 +00001030 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001031 // Scope for the scoped timeout object
1032 GDBRemoteCommunication::ScopedTimeout timeout (m_gdb_comm, 10);
1033
1034 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
1035 if (arg_packet_err == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001036 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001037 std::string error_str;
1038 if (m_gdb_comm.GetLaunchSuccess (error_str))
1039 {
1040 SetID (m_gdb_comm.GetCurrentProcessID ());
1041 }
1042 else
1043 {
1044 error.SetErrorString (error_str.c_str());
1045 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001046 }
1047 else
1048 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001049 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001050 }
Greg Clayton71337622011-02-24 22:24:29 +00001051 }
Tamas Berghammer912800c2015-02-24 10:23:39 +00001052
Greg Clayton71337622011-02-24 22:24:29 +00001053 if (GetID() == LLDB_INVALID_PROCESS_ID)
1054 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001055 if (log)
1056 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton71337622011-02-24 22:24:29 +00001057 KillDebugserverProcess ();
1058 return error;
1059 }
1060
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001061 StringExtractorGDBRemote response;
1062 if (m_gdb_comm.GetStopReply(response))
Greg Clayton71337622011-02-24 22:24:29 +00001063 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001064 SetLastStopPacket(response);
Ewan Crawford78baa192015-05-13 09:18:18 +00001065 // '?' Packets must be handled differently in non-stop mode
1066 if (GetTarget().GetNonStopModeEnabled())
1067 HandleStopReplySequence();
1068
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001069 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
1070
1071 if (process_arch.IsValid())
Jason Molendac62bd7b2013-12-21 05:20:36 +00001072 {
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001073 m_target.MergeArchitecture(process_arch);
1074 }
1075 else
1076 {
1077 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
1078 if (host_arch.IsValid())
1079 m_target.MergeArchitecture(host_arch);
Carlo Kok74389122013-10-14 07:09:13 +00001080 }
1081
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001082 SetPrivateState (SetThreadStopInfo (response));
Greg Clayton71337622011-02-24 22:24:29 +00001083
1084 if (!disable_stdio)
1085 {
1086 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Claytonee95ed52011-11-17 22:14:31 +00001087 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Clayton71337622011-02-24 22:24:29 +00001088 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001089 }
1090 }
Greg Claytonc235ac72011-08-09 05:20:29 +00001091 else
1092 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001093 if (log)
1094 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytonc235ac72011-08-09 05:20:29 +00001095 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001096 }
1097 else
1098 {
1099 // Set our user ID to an invalid process ID.
1100 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton982c9762011-11-03 21:22:33 +00001101 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
1102 exe_module->GetFileSpec().GetFilename().AsCString(),
1103 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001104 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001105 return error;
Greg Clayton4957bf62010-09-30 21:49:03 +00001106
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001107}
1108
1109
1110Error
Greg Claytonb766a732011-02-04 01:58:07 +00001111ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001112{
1113 Error error;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001114 // Only connect if we have a valid connect URL
Vince Harron1b5a74e2015-01-21 22:42:49 +00001115 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton00fe87b2013-12-05 22:58:22 +00001116
1117 if (connect_url && connect_url[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001118 {
Vince Harron1b5a74e2015-01-21 22:42:49 +00001119 if (log)
1120 log->Printf("ProcessGDBRemote::%s Connecting to %s", __FUNCTION__, connect_url);
Greg Clayton00fe87b2013-12-05 22:58:22 +00001121 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
1122 if (conn_ap.get())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001123 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001124 const uint32_t max_retry_count = 50;
1125 uint32_t retry_count = 0;
1126 while (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001127 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001128 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
1129 {
1130 m_gdb_comm.SetConnection (conn_ap.release());
1131 break;
1132 }
1133 else if (error.WasInterrupted())
1134 {
1135 // If we were interrupted, don't keep retrying.
1136 break;
1137 }
1138
1139 retry_count++;
1140
1141 if (retry_count >= max_retry_count)
1142 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001143
Greg Clayton00fe87b2013-12-05 22:58:22 +00001144 usleep (100000);
1145 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001146 }
1147 }
1148
1149 if (!m_gdb_comm.IsConnected())
1150 {
1151 if (error.Success())
1152 error.SetErrorString("not connected to remote gdb server");
1153 return error;
1154 }
1155
Greg Clayton32e0a752011-03-30 18:16:51 +00001156 // We always seem to be able to open a connection to a local port
1157 // so we need to make sure we can then send data to it. If we can't
1158 // then we aren't actually connected to anything, so try and do the
1159 // handshake with the remote GDB server and make sure that goes
1160 // alright.
Greg Claytonfb909312013-11-23 01:58:15 +00001161 if (!m_gdb_comm.HandshakeWithServer (&error))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001162 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001163 m_gdb_comm.Disconnect();
1164 if (error.Success())
1165 error.SetErrorString("not connected to remote gdb server");
1166 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001167 }
Ewan Crawford78baa192015-05-13 09:18:18 +00001168
1169 // Send $QNonStop:1 packet on startup if required
1170 if (GetTarget().GetNonStopModeEnabled())
1171 m_gdb_comm.SetNonStopMode(true);
1172
Greg Clayton32e0a752011-03-30 18:16:51 +00001173 m_gdb_comm.GetThreadSuffixSupported ();
Greg Clayton44633992012-04-10 03:22:03 +00001174 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001175 m_gdb_comm.GetHostInfo ();
1176 m_gdb_comm.GetVContSupported ('c');
Jim Inghamcd16df92012-07-20 21:37:13 +00001177 m_gdb_comm.GetVAttachOrWaitSupported();
Ewan Crawford78baa192015-05-13 09:18:18 +00001178
1179 // Ask the remote server for the default thread id
1180 if (GetTarget().GetNonStopModeEnabled())
1181 m_gdb_comm.GetDefaultThreadId(m_initial_tid);
1182
1183
Jim Ingham03afad82012-07-02 05:40:07 +00001184 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1185 for (size_t idx = 0; idx < num_cmds; idx++)
1186 {
1187 StringExtractorGDBRemote response;
Jim Ingham03afad82012-07-02 05:40:07 +00001188 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1189 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001190 return error;
1191}
1192
1193void
Jim Inghambb006ce2014-08-02 00:33:35 +00001194ProcessGDBRemote::DidLaunchOrAttach (ArchSpec& process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001195{
Greg Clayton5160ce52013-03-27 23:08:40 +00001196 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001197 if (log)
1198 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton93d3c8332011-02-16 04:46:07 +00001199 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001200 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001201 BuildDynamicRegisterInfo (false);
Greg Clayton3af9ea52010-11-18 05:57:03 +00001202
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001203 // See if the GDB server supports the qHostInfo information
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001204
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001205
1206 // See if the GDB server supports the qProcessInfo packet, if so
1207 // prefer that over the Host information as it will be more specific
1208 // to our process.
1209
Todd Fiala75f47c32014-10-11 21:42:09 +00001210 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1211 if (remote_process_arch.IsValid())
1212 {
1213 process_arch = remote_process_arch;
1214 if (log)
1215 log->Printf ("ProcessGDBRemote::%s gdb-remote had process architecture, using %s %s",
1216 __FUNCTION__,
1217 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1218 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1219 }
Jim Inghambb006ce2014-08-02 00:33:35 +00001220 else
Todd Fiala75f47c32014-10-11 21:42:09 +00001221 {
Jim Inghambb006ce2014-08-02 00:33:35 +00001222 process_arch = m_gdb_comm.GetHostArchitecture();
Todd Fiala75f47c32014-10-11 21:42:09 +00001223 if (log)
1224 log->Printf ("ProcessGDBRemote::%s gdb-remote did not have process architecture, using gdb-remote host architecture %s %s",
1225 __FUNCTION__,
1226 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1227 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1228 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001229
Jim Inghambb006ce2014-08-02 00:33:35 +00001230 if (process_arch.IsValid())
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001231 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001232 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Greg Claytond314e812011-03-23 00:09:55 +00001233 if (target_arch.IsValid())
1234 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001235 if (log)
1236 log->Printf ("ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1237 __FUNCTION__,
1238 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1239 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
1240
1241 // If the remote host is ARM and we have apple as the vendor, then
Greg Claytond314e812011-03-23 00:09:55 +00001242 // ARM executables and shared libraries can have mixed ARM architectures.
1243 // You can have an armv6 executable, and if the host is armv7, then the
1244 // system will load the best possible architecture for all shared libraries
1245 // it has, so we really need to take the remote host architecture as our
1246 // defacto architecture in this case.
1247
Jim Inghambb006ce2014-08-02 00:33:35 +00001248 if (process_arch.GetMachine() == llvm::Triple::arm &&
1249 process_arch.GetTriple().getVendor() == llvm::Triple::Apple)
Greg Claytond314e812011-03-23 00:09:55 +00001250 {
Jason Molenda921c01b2014-08-03 21:42:52 +00001251 GetTarget().SetArchitecture (process_arch);
Todd Fiala75f47c32014-10-11 21:42:09 +00001252 if (log)
1253 log->Printf ("ProcessGDBRemote::%s remote process is ARM/Apple, setting target arch to %s %s",
1254 __FUNCTION__,
1255 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1256 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001257 }
1258 else
1259 {
1260 // Fill in what is missing in the triple
Jim Inghambb006ce2014-08-02 00:33:35 +00001261 const llvm::Triple &remote_triple = process_arch.GetTriple();
Tamas Berghammere724af12015-03-13 10:32:37 +00001262 llvm::Triple new_target_triple = target_arch.GetTriple();
1263 if (new_target_triple.getVendorName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001264 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001265 new_target_triple.setVendor (remote_triple.getVendor());
Greg Claytond314e812011-03-23 00:09:55 +00001266
Tamas Berghammere724af12015-03-13 10:32:37 +00001267 if (new_target_triple.getOSName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001268 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001269 new_target_triple.setOS (remote_triple.getOS());
Greg Claytond314e812011-03-23 00:09:55 +00001270
Tamas Berghammere724af12015-03-13 10:32:37 +00001271 if (new_target_triple.getEnvironmentName().size() == 0)
1272 new_target_triple.setEnvironment (remote_triple.getEnvironment());
Greg Clayton70b57652011-05-15 01:25:55 +00001273 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001274
Tamas Berghammere724af12015-03-13 10:32:37 +00001275 ArchSpec new_target_arch = target_arch;
1276 new_target_arch.SetTriple(new_target_triple);
1277 GetTarget().SetArchitecture(new_target_arch);
1278 }
Greg Claytond314e812011-03-23 00:09:55 +00001279 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001280
1281 if (log)
1282 log->Printf ("ProcessGDBRemote::%s final target arch after adjustments for remote architecture: %s %s",
1283 __FUNCTION__,
1284 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1285 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001286 }
1287 else
1288 {
1289 // The target doesn't have a valid architecture yet, set it from
1290 // the architecture we got from the remote GDB server
Jason Molenda921c01b2014-08-03 21:42:52 +00001291 GetTarget().SetArchitecture (process_arch);
Greg Claytond314e812011-03-23 00:09:55 +00001292 }
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001293 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001294 }
1295}
1296
1297void
1298ProcessGDBRemote::DidLaunch ()
1299{
Jim Inghambb006ce2014-08-02 00:33:35 +00001300 ArchSpec process_arch;
1301 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001302}
1303
1304Error
Han Ming Ong84647042012-02-25 01:07:38 +00001305ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1306{
Todd Fiala75f47c32014-10-11 21:42:09 +00001307 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001308 Error error;
Todd Fiala75f47c32014-10-11 21:42:09 +00001309
1310 if (log)
1311 log->Printf ("ProcessGDBRemote::%s()", __FUNCTION__);
1312
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001313 // Clear out and clean up from any current state
1314 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001315 if (attach_pid != LLDB_INVALID_PROCESS_ID)
1316 {
Greg Clayton71337622011-02-24 22:24:29 +00001317 // Make sure we aren't already connected?
1318 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001319 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001320 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001321
1322 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001323 {
Greg Clayton71337622011-02-24 22:24:29 +00001324 const char *error_string = error.AsCString();
1325 if (error_string == NULL)
1326 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1327
1328 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001329 }
Greg Clayton71337622011-02-24 22:24:29 +00001330 }
1331
1332 if (error.Success())
1333 {
Jim Ingham106d0282014-06-25 02:32:56 +00001334 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
Todd Fiala75f47c32014-10-11 21:42:09 +00001335
Greg Clayton71337622011-02-24 22:24:29 +00001336 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001337 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Greg Clayton3b608422011-11-19 02:11:30 +00001338 SetID (attach_pid);
Greg Clayton71337622011-02-24 22:24:29 +00001339 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001340 }
1341 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001342
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001343 return error;
1344}
1345
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001346Error
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001347ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001348{
1349 Error error;
1350 // Clear out and clean up from any current state
1351 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001352
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001353 if (process_name && process_name[0])
1354 {
Greg Clayton71337622011-02-24 22:24:29 +00001355 // Make sure we aren't already connected?
1356 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001357 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001358 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001359
Greg Clayton71337622011-02-24 22:24:29 +00001360 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001361 {
Greg Clayton71337622011-02-24 22:24:29 +00001362 const char *error_string = error.AsCString();
1363 if (error_string == NULL)
1364 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001365
Greg Clayton71337622011-02-24 22:24:29 +00001366 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001367 }
Greg Clayton71337622011-02-24 22:24:29 +00001368 }
1369
1370 if (error.Success())
1371 {
1372 StreamString packet;
1373
Jim Ingham106d0282014-06-25 02:32:56 +00001374 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1375
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001376 if (attach_info.GetWaitForLaunch())
Jim Inghamcd16df92012-07-20 21:37:13 +00001377 {
1378 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1379 {
1380 packet.PutCString ("vAttachWait");
1381 }
1382 else
1383 {
1384 if (attach_info.GetIgnoreExisting())
1385 packet.PutCString("vAttachWait");
1386 else
1387 packet.PutCString ("vAttachOrWait");
1388 }
1389 }
Greg Clayton71337622011-02-24 22:24:29 +00001390 else
1391 packet.PutCString("vAttachName");
1392 packet.PutChar(';');
1393 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1394
1395 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1396
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001397 }
1398 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001399 return error;
1400}
1401
Greg Clayton5df78fa2015-05-23 03:54:53 +00001402void
1403ProcessGDBRemote::DidExit ()
Greg Claytonfbb76342013-11-20 21:07:01 +00001404{
Greg Clayton5df78fa2015-05-23 03:54:53 +00001405 // When we exit, disconnect from the GDB server communications
Greg Claytonfbb76342013-11-20 21:07:01 +00001406 m_gdb_comm.Disconnect();
Greg Claytonfbb76342013-11-20 21:07:01 +00001407}
1408
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001409void
Jim Inghambb006ce2014-08-02 00:33:35 +00001410ProcessGDBRemote::DidAttach (ArchSpec &process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001411{
Jim Inghambb006ce2014-08-02 00:33:35 +00001412 // If you can figure out what the architecture is, fill it in here.
1413 process_arch.Clear();
1414 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001415}
1416
Greg Clayton90ba8112012-12-05 00:16:59 +00001417
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001418Error
1419ProcessGDBRemote::WillResume ()
1420{
Greg Clayton71fc2a32011-02-12 06:28:37 +00001421 m_continue_c_tids.clear();
1422 m_continue_C_tids.clear();
1423 m_continue_s_tids.clear();
1424 m_continue_S_tids.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001425 return Error();
1426}
1427
1428Error
1429ProcessGDBRemote::DoResume ()
1430{
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001431 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001432 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001433 if (log)
1434 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytone5219662010-12-03 06:02:24 +00001435
1436 Listener listener ("gdb-remote.resume-packet-sent");
1437 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1438 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00001439 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1440
Greg Claytond1d06e42013-04-20 00:27:58 +00001441 const size_t num_threads = GetThreadList().GetSize();
1442
Greg Clayton71fc2a32011-02-12 06:28:37 +00001443 StreamString continue_packet;
1444 bool continue_packet_error = false;
1445 if (m_gdb_comm.HasAnyVContSupport ())
1446 {
Ewan Crawford78baa192015-05-13 09:18:18 +00001447 if (!GetTarget().GetNonStopModeEnabled() &&
1448 (m_continue_c_tids.size() == num_threads ||
Greg Claytone98008c2014-02-13 23:34:38 +00001449 (m_continue_c_tids.empty() &&
1450 m_continue_C_tids.empty() &&
1451 m_continue_s_tids.empty() &&
Ewan Crawford78baa192015-05-13 09:18:18 +00001452 m_continue_S_tids.empty())))
Greg Clayton71fc2a32011-02-12 06:28:37 +00001453 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001454 // All threads are continuing, just send a "c" packet
1455 continue_packet.PutCString ("c");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001456 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001457 else
1458 {
1459 continue_packet.PutCString ("vCont");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001460
Greg Claytond1d06e42013-04-20 00:27:58 +00001461 if (!m_continue_c_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001462 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001463 if (m_gdb_comm.GetVContSupported ('c'))
1464 {
1465 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)
1466 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1467 }
1468 else
1469 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001470 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001471
1472 if (!continue_packet_error && !m_continue_C_tids.empty())
1473 {
1474 if (m_gdb_comm.GetVContSupported ('C'))
1475 {
1476 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)
1477 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1478 }
1479 else
1480 continue_packet_error = true;
1481 }
Greg Claytone5219662010-12-03 06:02:24 +00001482
Greg Claytond1d06e42013-04-20 00:27:58 +00001483 if (!continue_packet_error && !m_continue_s_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001484 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001485 if (m_gdb_comm.GetVContSupported ('s'))
1486 {
1487 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)
1488 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1489 }
1490 else
1491 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001492 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001493
1494 if (!continue_packet_error && !m_continue_S_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001495 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001496 if (m_gdb_comm.GetVContSupported ('S'))
1497 {
1498 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)
1499 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1500 }
1501 else
1502 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001503 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001504
1505 if (continue_packet_error)
1506 continue_packet.GetString().clear();
Greg Clayton71fc2a32011-02-12 06:28:37 +00001507 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001508 }
1509 else
1510 continue_packet_error = true;
1511
1512 if (continue_packet_error)
1513 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001514 // Either no vCont support, or we tried to use part of the vCont
1515 // packet that wasn't supported by the remote GDB server.
1516 // We need to try and make a simple packet that can do our continue
Greg Clayton71fc2a32011-02-12 06:28:37 +00001517 const size_t num_continue_c_tids = m_continue_c_tids.size();
1518 const size_t num_continue_C_tids = m_continue_C_tids.size();
1519 const size_t num_continue_s_tids = m_continue_s_tids.size();
1520 const size_t num_continue_S_tids = m_continue_S_tids.size();
1521 if (num_continue_c_tids > 0)
1522 {
1523 if (num_continue_c_tids == num_threads)
1524 {
1525 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001526 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001527 continue_packet.PutChar ('c');
1528 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001529 }
1530 else if (num_continue_c_tids == 1 &&
1531 num_continue_C_tids == 0 &&
1532 num_continue_s_tids == 0 &&
1533 num_continue_S_tids == 0 )
1534 {
1535 // Only one thread is continuing
Greg Clayton8b82f082011-04-12 05:54:46 +00001536 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001537 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001538 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001539 }
1540 }
1541
Greg Clayton0c74e782011-06-24 03:21:43 +00001542 if (continue_packet_error && num_continue_C_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001543 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001544 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1545 num_continue_C_tids > 0 &&
1546 num_continue_s_tids == 0 &&
1547 num_continue_S_tids == 0 )
Greg Clayton71fc2a32011-02-12 06:28:37 +00001548 {
1549 const int continue_signo = m_continue_C_tids.front().second;
Greg Clayton0c74e782011-06-24 03:21:43 +00001550 // Only one thread is continuing
Greg Clayton71fc2a32011-02-12 06:28:37 +00001551 if (num_continue_C_tids > 1)
1552 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001553 // More that one thread with a signal, yet we don't have
1554 // vCont support and we are being asked to resume each
1555 // thread with a signal, we need to make sure they are
1556 // all the same signal, or we can't issue the continue
1557 // accurately with the current support...
1558 if (num_continue_C_tids > 1)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001559 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001560 continue_packet_error = false;
1561 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1562 {
1563 if (m_continue_C_tids[i].second != continue_signo)
1564 continue_packet_error = true;
1565 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001566 }
Greg Clayton0c74e782011-06-24 03:21:43 +00001567 if (!continue_packet_error)
1568 m_gdb_comm.SetCurrentThreadForRun (-1);
1569 }
1570 else
1571 {
1572 // Set the continue thread ID
1573 continue_packet_error = false;
1574 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001575 }
1576 if (!continue_packet_error)
1577 {
1578 // Add threads continuing with the same signo...
Greg Clayton71fc2a32011-02-12 06:28:37 +00001579 continue_packet.Printf("C%2.2x", continue_signo);
1580 }
1581 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001582 }
1583
Greg Clayton0c74e782011-06-24 03:21:43 +00001584 if (continue_packet_error && num_continue_s_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001585 {
1586 if (num_continue_s_tids == num_threads)
1587 {
1588 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001589 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001590 continue_packet.PutChar ('s');
1591 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001592 }
1593 else if (num_continue_c_tids == 0 &&
1594 num_continue_C_tids == 0 &&
1595 num_continue_s_tids == 1 &&
1596 num_continue_S_tids == 0 )
1597 {
1598 // Only one thread is stepping
Greg Clayton8b82f082011-04-12 05:54:46 +00001599 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001600 continue_packet.PutChar ('s');
Greg Clayton0c74e782011-06-24 03:21:43 +00001601 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001602 }
1603 }
1604
1605 if (!continue_packet_error && num_continue_S_tids > 0)
1606 {
1607 if (num_continue_S_tids == num_threads)
1608 {
1609 const int step_signo = m_continue_S_tids.front().second;
1610 // Are all threads trying to step with the same signal?
Greg Clayton0c74e782011-06-24 03:21:43 +00001611 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001612 if (num_continue_S_tids > 1)
1613 {
1614 for (size_t i=1; i<num_threads; ++i)
1615 {
1616 if (m_continue_S_tids[i].second != step_signo)
1617 continue_packet_error = true;
1618 }
1619 }
1620 if (!continue_packet_error)
1621 {
1622 // Add threads stepping with the same signo...
Greg Clayton8b82f082011-04-12 05:54:46 +00001623 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001624 continue_packet.Printf("S%2.2x", step_signo);
1625 }
1626 }
1627 else if (num_continue_c_tids == 0 &&
1628 num_continue_C_tids == 0 &&
1629 num_continue_s_tids == 0 &&
1630 num_continue_S_tids == 1 )
1631 {
1632 // Only one thread is stepping with signal
Greg Clayton8b82f082011-04-12 05:54:46 +00001633 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001634 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Clayton0c74e782011-06-24 03:21:43 +00001635 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001636 }
1637 }
1638 }
1639
1640 if (continue_packet_error)
1641 {
1642 error.SetErrorString ("can't make continue packet for this resume");
1643 }
1644 else
1645 {
1646 EventSP event_sp;
1647 TimeValue timeout;
1648 timeout = TimeValue::Now();
1649 timeout.OffsetWithSeconds (5);
Zachary Turneracee96a2014-09-23 18:32:09 +00001650 if (!m_async_thread.IsJoinable())
Jim Inghamb1e2e842012-04-12 18:49:31 +00001651 {
1652 error.SetErrorString ("Trying to resume but the async thread is dead.");
1653 if (log)
1654 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1655 return error;
1656 }
1657
Greg Clayton71fc2a32011-02-12 06:28:37 +00001658 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1659
1660 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Inghamb1e2e842012-04-12 18:49:31 +00001661 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001662 error.SetErrorString("Resume timed out.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00001663 if (log)
1664 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1665 }
1666 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1667 {
1668 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1669 if (log)
1670 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1671 return error;
1672 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001673 }
Greg Claytone5219662010-12-03 06:02:24 +00001674 }
1675
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001676 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001677}
1678
Greg Clayton9e920902012-04-10 02:25:43 +00001679void
Ewan Crawford78baa192015-05-13 09:18:18 +00001680ProcessGDBRemote::HandleStopReplySequence ()
1681{
1682 while(true)
1683 {
1684 // Send vStopped
1685 StringExtractorGDBRemote response;
1686 m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false);
1687
1688 // OK represents end of signal list
1689 if (response.IsOKResponse())
1690 break;
1691
1692 // If not OK or a normal packet we have a problem
1693 if (!response.IsNormalResponse())
1694 break;
1695
1696 SetLastStopPacket(response);
1697 }
1698}
1699
1700void
Greg Clayton9e920902012-04-10 02:25:43 +00001701ProcessGDBRemote::ClearThreadIDList ()
1702{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001703 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001704 m_thread_ids.clear();
1705}
1706
1707bool
1708ProcessGDBRemote::UpdateThreadIDList ()
1709{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001710 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001711 bool sequence_mutex_unavailable = false;
1712 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1713 if (sequence_mutex_unavailable)
1714 {
Greg Clayton9e920902012-04-10 02:25:43 +00001715 return false; // We just didn't get the list
1716 }
1717 return true;
1718}
1719
Greg Clayton9fc13552012-04-10 00:18:59 +00001720bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001721ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001722{
1723 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +00001724 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Clayton73b472d2010-10-27 03:32:59 +00001725 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +00001726 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton9e920902012-04-10 02:25:43 +00001727
1728 size_t num_thread_ids = m_thread_ids.size();
1729 // The "m_thread_ids" thread ID list should always be updated after each stop
1730 // reply packet, but in case it isn't, update it here.
1731 if (num_thread_ids == 0)
1732 {
1733 if (!UpdateThreadIDList ())
1734 return false;
1735 num_thread_ids = m_thread_ids.size();
1736 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001737
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001738 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001739 if (num_thread_ids > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001740 {
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001741 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001742 {
Greg Clayton9e920902012-04-10 02:25:43 +00001743 tid_t tid = m_thread_ids[i];
Greg Clayton160c9d82013-05-01 21:54:04 +00001744 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001745 if (!thread_sp)
Jim Inghamdee1bc92013-06-22 00:27:45 +00001746 {
Jim Ingham4f465cf2012-10-10 18:32:14 +00001747 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001748 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1749 log->Printf(
1750 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001751 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001752 thread_sp->GetID());
1753 }
1754 else
1755 {
1756 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1757 log->Printf(
1758 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001759 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001760 thread_sp->GetID());
1761 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001762 new_thread_list.AddThread(thread_sp);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001763 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001764 }
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001765
1766 // Whatever that is left in old_thread_list_copy are not
1767 // present in new_thread_list. Remove non-existent threads from internal id table.
1768 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1769 for (size_t i=0; i<old_num_thread_ids; i++)
1770 {
1771 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1772 if (old_thread_sp)
1773 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001774 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001775 m_thread_id_to_index_id_map.erase(old_thread_id);
1776 }
1777 }
1778
Greg Clayton9fc13552012-04-10 00:18:59 +00001779 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001780}
1781
1782
1783StateType
1784ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1785{
Greg Claytondd0e5a52011-06-02 22:22:38 +00001786 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001787 const char stop_type = stop_packet.GetChar();
1788 switch (stop_type)
1789 {
1790 case 'T':
1791 case 'S':
1792 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00001793 // This is a bit of a hack, but is is required. If we did exec, we
1794 // need to clear our thread lists and also know to rebuild our dynamic
1795 // register info before we lookup and threads and populate the expedited
1796 // register values so we need to know this right away so we can cleanup
1797 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00001798 const uint32_t stop_id = GetStopID();
1799 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00001800 {
1801 // Our first stop, make sure we have a process ID, and also make
1802 // sure we know about our registers
1803 if (GetID() == LLDB_INVALID_PROCESS_ID)
1804 {
Greg Claytonc574ede2011-03-10 02:26:48 +00001805 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00001806 if (pid != LLDB_INVALID_PROCESS_ID)
1807 SetID (pid);
1808 }
1809 BuildDynamicRegisterInfo (true);
1810 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001811 // Stop with signal and thread info
1812 const uint8_t signo = stop_packet.GetHexU8();
1813 std::string name;
1814 std::string value;
1815 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00001816 std::string reason;
1817 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001818 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00001819 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001820 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001821 ThreadSP thread_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001822 ThreadGDBRemote *gdb_thread = NULL;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001823
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001824 while (stop_packet.GetNameColonValue(name, value))
1825 {
1826 if (name.compare("metype") == 0)
1827 {
1828 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001829 exc_type = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001830 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001831 else if (name.compare("medata") == 0)
1832 {
1833 // exception data in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001834 exc_data.push_back(StringConvert::ToUInt64 (value.c_str(), 0, 16));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001835 }
1836 else if (name.compare("thread") == 0)
1837 {
1838 // thread in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001839 lldb::tid_t tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001840 // m_thread_list_real does have its own mutex, but we need to
1841 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1842 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1843 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1844 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
Greg Clayton160c9d82013-05-01 21:54:04 +00001845
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001846 if (!thread_sp)
Greg Claytond1d06e42013-04-20 00:27:58 +00001847 {
Greg Claytone576ab22011-02-15 00:19:15 +00001848 // Create the thread if we need to
Jim Ingham4f465cf2012-10-10 18:32:14 +00001849 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001850 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
1851 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1852 log->Printf ("ProcessGDBRemote::%s Adding new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1853 __FUNCTION__,
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001854 static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001855 thread_sp->GetID());
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001856
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001857 m_thread_list_real.AddThread(thread_sp);
Greg Claytone576ab22011-02-15 00:19:15 +00001858 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001859 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1860
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001861 }
Greg Clayton9e920902012-04-10 02:25:43 +00001862 else if (name.compare("threads") == 0)
1863 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001864 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001865 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00001866 // A comma separated list of all threads in the current
1867 // process that includes the thread for this stop reply
1868 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00001869 size_t comma_pos;
1870 lldb::tid_t tid;
1871 while ((comma_pos = value.find(',')) != std::string::npos)
1872 {
1873 value[comma_pos] = '\0';
1874 // thread in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001875 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00001876 if (tid != LLDB_INVALID_THREAD_ID)
1877 m_thread_ids.push_back (tid);
1878 value.erase(0, comma_pos + 1);
Greg Clayton9e920902012-04-10 02:25:43 +00001879 }
Vince Harron5275aaa2015-01-15 20:08:35 +00001880 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00001881 if (tid != LLDB_INVALID_THREAD_ID)
1882 m_thread_ids.push_back (tid);
1883 }
Greg Claytonde9d0492011-01-08 03:17:57 +00001884 else if (name.compare("hexname") == 0)
1885 {
1886 StringExtractor name_extractor;
1887 // Swap "value" over into "name_extractor"
1888 name_extractor.GetStringRef().swap(value);
1889 // Now convert the HEX bytes into a string value
1890 name_extractor.GetHexByteString (value);
1891 thread_name.swap (value);
1892 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001893 else if (name.compare("name") == 0)
1894 {
1895 thread_name.swap (value);
1896 }
Greg Clayton6f35f5c2010-09-09 06:32:46 +00001897 else if (name.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001898 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001899 thread_dispatch_qaddr = StringConvert::ToUInt64 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001900 }
Greg Claytona658fd22011-06-04 01:26:29 +00001901 else if (name.compare("reason") == 0)
1902 {
1903 reason.swap(value);
1904 }
1905 else if (name.compare("description") == 0)
1906 {
1907 StringExtractor desc_extractor;
1908 // Swap "value" over into "name_extractor"
1909 desc_extractor.GetStringRef().swap(value);
1910 // Now convert the HEX bytes into a string value
Chaoren Lin28e57422015-02-03 01:51:25 +00001911 desc_extractor.GetHexByteString (value);
1912 description.swap(value);
Greg Claytona658fd22011-06-04 01:26:29 +00001913 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001914 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1915 {
1916 // We have a register number that contains an expedited
1917 // register value. Lets supply this register to our thread
1918 // so it won't have to go and read it.
Greg Clayton160c9d82013-05-01 21:54:04 +00001919 if (gdb_thread)
Greg Clayton3e06bd92011-01-09 21:07:35 +00001920 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001921 uint32_t reg = StringConvert::ToUInt32 (name.c_str(), UINT32_MAX, 16);
Greg Clayton3e06bd92011-01-09 21:07:35 +00001922
1923 if (reg != UINT32_MAX)
1924 {
1925 StringExtractor reg_value_extractor;
1926 // Swap "value" over into "reg_value_extractor"
1927 reg_value_extractor.GetStringRef().swap(value);
Greg Clayton160c9d82013-05-01 21:54:04 +00001928 if (!gdb_thread->PrivateSetRegisterValue (reg, reg_value_extractor))
Greg Claytone576ab22011-02-15 00:19:15 +00001929 {
1930 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1931 name.c_str(),
1932 reg,
1933 reg,
1934 reg_value_extractor.GetStringRef().c_str(),
1935 stop_packet.GetStringRef().c_str());
1936 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001937 }
1938 }
1939 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001940 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001941
Hafiz Abid Qadeer673b4a32014-02-20 10:23:20 +00001942 // If the response is old style 'S' packet which does not provide us with thread information
1943 // then update the thread list and choose the first one.
1944 if (!thread_sp)
1945 {
1946 UpdateThreadIDList ();
1947
1948 if (!m_thread_ids.empty ())
1949 {
1950 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1951 thread_sp = m_thread_list_real.FindThreadByProtocolID (m_thread_ids.front (), false);
1952 if (thread_sp)
1953 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get ());
1954 }
1955 }
1956
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001957 if (thread_sp)
1958 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001959 // Clear the stop info just in case we don't set it to anything
1960 thread_sp->SetStopInfo (StopInfoSP());
1961
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001962 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Inghamdd2fe7a2011-01-28 02:23:12 +00001963 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001964 if (exc_type != 0)
1965 {
Greg Clayton1a65ae12011-01-25 23:55:37 +00001966 const size_t exc_data_size = exc_data.size();
Greg Claytonf4b47e12010-08-04 01:40:35 +00001967
Greg Clayton160c9d82013-05-01 21:54:04 +00001968 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1969 exc_type,
1970 exc_data_size,
1971 exc_data_size >= 1 ? exc_data[0] : 0,
1972 exc_data_size >= 2 ? exc_data[1] : 0,
1973 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001974 }
Greg Claytona658fd22011-06-04 01:26:29 +00001975 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001976 {
Greg Claytona658fd22011-06-04 01:26:29 +00001977 bool handled = false;
Greg Clayton8cda7f02013-05-21 21:55:59 +00001978 bool did_exec = false;
Greg Claytona658fd22011-06-04 01:26:29 +00001979 if (!reason.empty())
1980 {
1981 if (reason.compare("trace") == 0)
1982 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001983 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Greg Claytona658fd22011-06-04 01:26:29 +00001984 handled = true;
1985 }
1986 else if (reason.compare("breakpoint") == 0)
1987 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001988 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1989 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Claytona658fd22011-06-04 01:26:29 +00001990 if (bp_site_sp)
1991 {
1992 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1993 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1994 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
Jim Ingham54cc6e42012-07-11 21:41:19 +00001995 handled = true;
Greg Clayton160c9d82013-05-01 21:54:04 +00001996 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00001997 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001998 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00001999 }
2000 else
2001 {
2002 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00002003 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00002004 }
2005 }
Greg Claytona658fd22011-06-04 01:26:29 +00002006 }
2007 else if (reason.compare("trap") == 0)
2008 {
2009 // Let the trap just use the standard signal stop reason below...
2010 }
2011 else if (reason.compare("watchpoint") == 0)
2012 {
Chaoren Lin18fe6402015-02-03 01:51:47 +00002013 StringExtractor desc_extractor(description.c_str());
2014 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
2015 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
2016 watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
2017 if (wp_addr != LLDB_INVALID_ADDRESS)
2018 {
2019 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2020 if (wp_sp)
2021 {
2022 wp_sp->SetHardwareIndex(wp_index);
2023 watch_id = wp_sp->GetID();
2024 }
2025 }
2026 if (watch_id == LLDB_INVALID_WATCH_ID)
2027 {
2028 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_WATCHPOINTS));
2029 if (log) log->Printf ("failed to find watchpoint");
2030 }
Greg Clayton160c9d82013-05-01 21:54:04 +00002031 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
Greg Claytona658fd22011-06-04 01:26:29 +00002032 handled = true;
2033 }
2034 else if (reason.compare("exception") == 0)
2035 {
Greg Clayton160c9d82013-05-01 21:54:04 +00002036 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00002037 handled = true;
2038 }
Greg Clayton15fc2be2013-05-21 01:00:52 +00002039 else if (reason.compare("exec") == 0)
2040 {
Greg Clayton8cda7f02013-05-21 21:55:59 +00002041 did_exec = true;
Greg Clayton15fc2be2013-05-21 01:00:52 +00002042 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
2043 handled = true;
2044 }
Greg Claytona658fd22011-06-04 01:26:29 +00002045 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00002046
Jim Ingham40083a42014-02-24 19:49:46 +00002047 if (!handled && signo && did_exec == false)
Greg Claytona658fd22011-06-04 01:26:29 +00002048 {
2049 if (signo == SIGTRAP)
2050 {
2051 // Currently we are going to assume SIGTRAP means we are either
2052 // hitting a breakpoint or hardware single stepping.
Jim Ingham54cc6e42012-07-11 21:41:19 +00002053 handled = true;
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +00002054 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
Greg Clayton160c9d82013-05-01 21:54:04 +00002055 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00002056
Greg Claytona658fd22011-06-04 01:26:29 +00002057 if (bp_site_sp)
2058 {
2059 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2060 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2061 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
Greg Clayton160c9d82013-05-01 21:54:04 +00002062 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00002063 {
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +00002064 if(m_breakpoint_pc_offset != 0)
2065 thread_sp->GetRegisterContext()->SetPC(pc);
Greg Clayton160c9d82013-05-01 21:54:04 +00002066 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00002067 }
2068 else
2069 {
2070 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00002071 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00002072 }
2073 }
Jim Ingham54cc6e42012-07-11 21:41:19 +00002074 else
Greg Claytona658fd22011-06-04 01:26:29 +00002075 {
Jim Ingham4dc613b2012-10-27 02:52:04 +00002076 // If we were stepping then assume the stop was the result of the trace. If we were
2077 // not stepping then report the SIGTRAP.
2078 // FIXME: We are still missing the case where we single step over a trap instruction.
Greg Clayton160c9d82013-05-01 21:54:04 +00002079 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
2080 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Jim Ingham4dc613b2012-10-27 02:52:04 +00002081 else
Greg Clayton160c9d82013-05-01 21:54:04 +00002082 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo));
Greg Claytona658fd22011-06-04 01:26:29 +00002083 }
2084 }
2085 if (!handled)
Greg Clayton160c9d82013-05-01 21:54:04 +00002086 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Jason Molenda8214b012013-04-25 01:33:46 +00002087 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00002088
Greg Claytona658fd22011-06-04 01:26:29 +00002089 if (!description.empty())
2090 {
Greg Clayton160c9d82013-05-01 21:54:04 +00002091 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
Greg Claytona658fd22011-06-04 01:26:29 +00002092 if (stop_info_sp)
2093 {
Pavel Labath48fca3b2015-05-15 10:14:51 +00002094 const char *stop_info_desc = stop_info_sp->GetDescription();
2095 if (!stop_info_desc || !stop_info_desc[0])
2096 stop_info_sp->SetDescription (description.c_str());
Greg Clayton3418c852011-08-10 02:10:13 +00002097 }
Greg Claytona658fd22011-06-04 01:26:29 +00002098 else
2099 {
Greg Clayton160c9d82013-05-01 21:54:04 +00002100 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00002101 }
2102 }
2103 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002104 }
2105 return eStateStopped;
2106 }
2107 break;
2108
2109 case 'W':
Todd Fialaff6131a2014-05-19 04:57:23 +00002110 case 'X':
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002111 // process exited
2112 return eStateExited;
2113
2114 default:
2115 break;
2116 }
2117 return eStateInvalid;
2118}
2119
2120void
2121ProcessGDBRemote::RefreshStateAfterStop ()
2122{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002123 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00002124 m_thread_ids.clear();
2125 // Set the thread stop info. It might have a "threads" key whose value is
2126 // a list of all thread IDs in the current process, so m_thread_ids might
2127 // get set.
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002128
2129 // Scope for the lock
2130 {
2131 // Lock the thread stack while we access it
2132 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
2133 // Get the number of stop packets on the stack
2134 int nItems = m_stop_packet_stack.size();
2135 // Iterate over them
2136 for (int i = 0; i < nItems; i++)
2137 {
2138 // Get the thread stop info
2139 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2140 // Process thread stop info
2141 SetThreadStopInfo(stop_info);
2142 }
2143 // Clear the thread stop stack
2144 m_stop_packet_stack.clear();
2145 }
2146
Greg Clayton9e920902012-04-10 02:25:43 +00002147 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2148 if (m_thread_ids.empty())
2149 {
2150 // No, we need to fetch the thread list manually
2151 UpdateThreadIDList();
2152 }
2153
Ewan Crawford78baa192015-05-13 09:18:18 +00002154 // If we have queried for a default thread id
2155 if (m_initial_tid != LLDB_INVALID_THREAD_ID)
2156 {
2157 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2158 m_initial_tid = LLDB_INVALID_THREAD_ID;
2159 }
2160
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002161 // Let all threads recover from stopping and do any clean up based
2162 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002163 m_thread_list_real.RefreshStateAfterStop();
Greg Clayton9e920902012-04-10 02:25:43 +00002164
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002165}
2166
2167Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002168ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002169{
2170 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002171
Greg Clayton6ed95942011-01-22 07:12:45 +00002172 bool timed_out = false;
2173 Mutex::Locker locker;
Greg Clayton513c26c2011-01-29 07:10:55 +00002174
2175 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002176 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002177 // We are being asked to halt during an attach. We need to just close
2178 // our file handle and debugserver will go away, and we can be done...
2179 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00002180 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002181 else
2182 {
Greg Clayton2687cd12012-03-29 01:55:41 +00002183 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton513c26c2011-01-29 07:10:55 +00002184 {
2185 if (timed_out)
2186 error.SetErrorString("timed out sending interrupt packet");
2187 else
2188 error.SetErrorString("unknown error sending interrupt packet");
2189 }
Greg Clayton2687cd12012-03-29 01:55:41 +00002190
2191 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton513c26c2011-01-29 07:10:55 +00002192 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002193 return error;
2194}
2195
2196Error
Jim Inghamacff8952013-05-02 00:27:30 +00002197ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002198{
2199 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002200 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00002201 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00002202 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2203
Jim Inghamacff8952013-05-02 00:27:30 +00002204 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002205 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002206 {
Jim Inghamacff8952013-05-02 00:27:30 +00002207 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002208 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
2209 else
Jim Inghamacff8952013-05-02 00:27:30 +00002210 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00002211 }
Jim Inghamacff8952013-05-02 00:27:30 +00002212
2213 if (!error.Success())
2214 return error;
2215
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002216 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00002217 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002218
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002219 SetPrivateState (eStateDetached);
2220 ResumePrivateStateThread();
2221
2222 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00002223 return error;
2224}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002225
Jim Ingham43c555d2012-07-04 00:35:43 +00002226
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002227Error
2228ProcessGDBRemote::DoDestroy ()
2229{
2230 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002231 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002232 if (log)
2233 log->Printf ("ProcessGDBRemote::DoDestroy()");
2234
Jim Ingham43c555d2012-07-04 00:35:43 +00002235 // There is a bug in older iOS debugservers where they don't shut down the process
2236 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
2237 // this can cause problems with restarting. So we check to see if any of our threads are stopped
2238 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
2239 // destroy it again.
2240 //
2241 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
2242 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
2243 // the debugservers with this bug are equal. There really should be a better way to test this!
2244 //
2245 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
2246 // get called here to destroy again and we're still at a breakpoint or exception, then we should
2247 // just do the straight-forward kill.
2248 //
2249 // And of course, if we weren't able to stop the process by the time we get here, it isn't
2250 // necessary (or helpful) to do any of this.
2251
2252 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
2253 {
2254 PlatformSP platform_sp = GetTarget().GetPlatform();
2255
2256 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2257 if (platform_sp
2258 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00002259 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00002260 {
2261 if (m_destroy_tried_resuming)
2262 {
2263 if (log)
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002264 log->PutCString ("ProcessGDBRemote::DoDestroy() - Tried resuming to destroy once already, not doing it again.");
Jim Ingham43c555d2012-07-04 00:35:43 +00002265 }
2266 else
2267 {
2268 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
2269 // but we really need it to happen here and it doesn't matter if we do it twice.
2270 m_thread_list.DiscardThreadPlans();
2271 DisableAllBreakpointSites();
2272
2273 bool stop_looks_like_crash = false;
2274 ThreadList &threads = GetThreadList();
2275
2276 {
Jim Ingham45350372012-09-11 00:08:52 +00002277 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002278
2279 size_t num_threads = threads.GetSize();
2280 for (size_t i = 0; i < num_threads; i++)
2281 {
2282 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002283 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002284 StopReason reason = eStopReasonInvalid;
2285 if (stop_info_sp)
2286 reason = stop_info_sp->GetStopReason();
2287 if (reason == eStopReasonBreakpoint
2288 || reason == eStopReasonException)
2289 {
2290 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002291 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
2292 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00002293 stop_info_sp->GetDescription());
2294 stop_looks_like_crash = true;
2295 break;
2296 }
2297 }
2298 }
2299
2300 if (stop_looks_like_crash)
2301 {
2302 if (log)
2303 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
2304 m_destroy_tried_resuming = true;
2305
2306 // If we are going to run again before killing, it would be good to suspend all the threads
2307 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
2308 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
2309 // have to run the risk of letting those threads proceed a bit.
2310
2311 {
Jim Ingham45350372012-09-11 00:08:52 +00002312 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002313
2314 size_t num_threads = threads.GetSize();
2315 for (size_t i = 0; i < num_threads; i++)
2316 {
2317 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002318 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002319 StopReason reason = eStopReasonInvalid;
2320 if (stop_info_sp)
2321 reason = stop_info_sp->GetStopReason();
2322 if (reason != eStopReasonBreakpoint
2323 && reason != eStopReasonException)
2324 {
2325 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002326 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
2327 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00002328 thread_sp->SetResumeState(eStateSuspended);
2329 }
2330 }
2331 }
2332 Resume ();
Jason Molendaede31932015-04-17 05:01:58 +00002333 return Destroy(false);
Jim Ingham43c555d2012-07-04 00:35:43 +00002334 }
2335 }
2336 }
2337 }
2338
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002339 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00002340 int exit_status = SIGABRT;
2341 std::string exit_string;
2342
Greg Clayton6ed95942011-01-22 07:12:45 +00002343 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002344 {
Jim Inghamaab78372011-10-28 01:11:35 +00002345 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00002346 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002347 StringExtractorGDBRemote response;
2348 bool send_async = true;
Tamas Berghammer912800c2015-02-24 10:23:39 +00002349 GDBRemoteCommunication::ScopedTimeout (m_gdb_comm, 3);
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002350
Greg Clayton3dedae12013-12-06 21:45:27 +00002351 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton513c26c2011-01-29 07:10:55 +00002352 {
2353 char packet_cmd = response.GetChar(0);
2354
2355 if (packet_cmd == 'W' || packet_cmd == 'X')
2356 {
Jim Inghameac0aa42014-02-21 22:36:11 +00002357#if defined(__APPLE__)
Jim Ingham9d67cc52014-02-21 22:35:29 +00002358 // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off
2359 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill
2360 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns
2361 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap
2362 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of
2363 // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2364 // Anyway, so call waitpid here to finally reap it.
2365 PlatformSP platform_sp(GetTarget().GetPlatform());
2366 if (platform_sp && platform_sp->IsHost())
2367 {
2368 int status;
2369 ::pid_t reap_pid;
2370 reap_pid = waitpid (GetID(), &status, WNOHANG);
2371 if (log)
2372 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2373 }
2374#endif
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002375 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002376 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00002377 exit_status = response.GetHexU8();
2378 }
2379 else
2380 {
2381 if (log)
2382 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2383 exit_string.assign("got unexpected response to k packet: ");
2384 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00002385 }
2386 }
2387 else
2388 {
Jim Inghambabfc382012-06-06 00:32:39 +00002389 if (log)
2390 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2391 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00002392 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002393 }
Jim Inghambabfc382012-06-06 00:32:39 +00002394 else
2395 {
2396 if (log)
Ed Masteb3a53332014-03-17 17:05:22 +00002397 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching");
Jim Inghamcfc09352012-07-27 23:57:19 +00002398 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00002399 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002400 }
Jim Inghambabfc382012-06-06 00:32:39 +00002401 else
2402 {
2403 // If we missed setting the exit status on the way out, do it here.
2404 // NB set exit status can be called multiple times, the first one sets the status.
2405 exit_string.assign("destroying when not connected to debugserver");
2406 }
2407
2408 SetExitStatus(exit_status, exit_string.c_str());
2409
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002410 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002411 KillDebugserverProcess ();
2412 return error;
2413}
2414
Greg Clayton8cda7f02013-05-21 21:55:59 +00002415void
2416ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2417{
Greg Clayton8cda7f02013-05-21 21:55:59 +00002418 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2419 if (did_exec)
2420 {
2421 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2422 if (log)
2423 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2424
2425 m_thread_list_real.Clear();
2426 m_thread_list.Clear();
2427 BuildDynamicRegisterInfo (true);
2428 m_gdb_comm.ResetDiscoverableSettings();
2429 }
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002430
2431 // Scope the lock
2432 {
2433 // Lock the thread stack while we access it
2434 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
2435 // Add this stop packet to the stop packet stack
2436 // This stack will get popped and examined when we switch to the
2437 // Stopped state
2438 m_stop_packet_stack.push_back(response);
2439 }
Greg Clayton8cda7f02013-05-21 21:55:59 +00002440}
2441
2442
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002443//------------------------------------------------------------------
2444// Process Queries
2445//------------------------------------------------------------------
2446
2447bool
2448ProcessGDBRemote::IsAlive ()
2449{
Greg Clayton10177aa2010-12-08 05:08:21 +00002450 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002451}
2452
2453addr_t
2454ProcessGDBRemote::GetImageInfoAddress()
2455{
Aidan Doddsc0c83852015-05-08 09:36:31 +00002456 // request the link map address via the $qShlibInfoAddr packet
2457 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2458
2459 // the loaded module list can also provides a link map address
2460 if (addr == LLDB_INVALID_ADDRESS)
2461 {
2462 GDBLoadedModuleInfoList list;
2463 if (GetLoadedModuleList (list).Success())
2464 addr = list.m_link_map;
2465 }
2466
2467 return addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002468}
2469
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002470//------------------------------------------------------------------
2471// Process Memory
2472//------------------------------------------------------------------
2473size_t
2474ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2475{
Jason Molenda6076bf42014-05-06 04:34:52 +00002476 GetMaxMemorySize ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002477 if (size > m_max_memory_size)
2478 {
2479 // Keep memory read sizes down to a sane limit. This function will be
2480 // called multiple times in order to complete the task by
2481 // lldb_private::Process so it is ok to do this.
2482 size = m_max_memory_size;
2483 }
2484
2485 char packet[64];
Jason Molenda6076bf42014-05-06 04:34:52 +00002486 int packet_len;
2487 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2488 if (binary_memory_read)
2489 {
2490 packet_len = ::snprintf (packet, sizeof(packet), "x0x%" PRIx64 ",0x%" PRIx64, (uint64_t)addr, (uint64_t)size);
2491 }
2492 else
2493 {
2494 packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
2495 }
Andy Gibbsa297a972013-06-19 19:04:53 +00002496 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002497 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002498 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002499 {
Greg Clayton576d8832011-03-22 04:00:09 +00002500 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002501 {
2502 error.Clear();
Jason Molenda6076bf42014-05-06 04:34:52 +00002503 if (binary_memory_read)
2504 {
2505 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any
2506 // 0x7d character escaping that was present in the packet
2507
2508 size_t data_received_size = response.GetBytesLeft();
2509 if (data_received_size > size)
2510 {
2511 // Don't write past the end of BUF if the remote debug server gave us too
2512 // much data for some reason.
2513 data_received_size = size;
2514 }
2515 memcpy (buf, response.GetStringRef().data(), data_received_size);
2516 return data_received_size;
2517 }
2518 else
2519 {
2520 return response.GetHexBytes(buf, size, '\xdd');
2521 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002522 }
Greg Clayton576d8832011-03-22 04:00:09 +00002523 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002524 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002525 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002526 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002527 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002528 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002529 }
2530 else
2531 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002532 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002533 }
2534 return 0;
2535}
2536
2537size_t
2538ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2539{
Jason Molenda6076bf42014-05-06 04:34:52 +00002540 GetMaxMemorySize ();
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002541 if (size > m_max_memory_size)
2542 {
2543 // Keep memory read sizes down to a sane limit. This function will be
2544 // called multiple times in order to complete the task by
2545 // lldb_private::Process so it is ok to do this.
2546 size = m_max_memory_size;
2547 }
2548
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002549 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00002550 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Clayton7fb56d02011-02-01 01:31:41 +00002551 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002552 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002553 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002554 {
Greg Clayton576d8832011-03-22 04:00:09 +00002555 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002556 {
2557 error.Clear();
2558 return size;
2559 }
Greg Clayton576d8832011-03-22 04:00:09 +00002560 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002561 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002562 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002563 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002564 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002565 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 +00002566 }
2567 else
2568 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002569 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002570 }
2571 return 0;
2572}
2573
2574lldb::addr_t
2575ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2576{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00002577 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_EXPRESSIONS));
Greg Clayton2a48f522011-05-14 01:50:35 +00002578 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2579
Greg Clayton70b57652011-05-15 01:25:55 +00002580 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton2a48f522011-05-14 01:50:35 +00002581 switch (supported)
2582 {
2583 case eLazyBoolCalculate:
2584 case eLazyBoolYes:
2585 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2586 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2587 return allocated_addr;
2588
2589 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002590 // Call mmap() to create memory in the inferior..
2591 unsigned prot = 0;
2592 if (permissions & lldb::ePermissionsReadable)
2593 prot |= eMmapProtRead;
2594 if (permissions & lldb::ePermissionsWritable)
2595 prot |= eMmapProtWrite;
2596 if (permissions & lldb::ePermissionsExecutable)
2597 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00002598
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002599 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2600 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2601 m_addr_to_mmap_size[allocated_addr] = size;
2602 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002603 {
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002604 allocated_addr = LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00002605 if (log)
2606 log->Printf ("ProcessGDBRemote::%s no direct stub support for memory allocation, and InferiorCallMmap also failed - is stub missing register context save/restore capability?", __FUNCTION__);
2607 }
Greg Clayton2a48f522011-05-14 01:50:35 +00002608 break;
2609 }
2610
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002611 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00002612 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002613 else
2614 error.Clear();
2615 return allocated_addr;
2616}
2617
2618Error
Greg Clayton46fb5582011-11-18 07:03:08 +00002619ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2620 MemoryRegionInfo &region_info)
2621{
2622
2623 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2624 return error;
2625}
2626
2627Error
Johnny Chen64637202012-05-23 21:09:52 +00002628ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2629{
2630
2631 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2632 return error;
2633}
2634
2635Error
Enrico Granataf04a2192012-07-13 23:18:48 +00002636ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2637{
2638 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2639 return error;
2640}
2641
2642Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002643ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2644{
2645 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00002646 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2647
2648 switch (supported)
2649 {
2650 case eLazyBoolCalculate:
2651 // We should never be deallocating memory without allocating memory
2652 // first so we should never get eLazyBoolCalculate
2653 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2654 break;
2655
2656 case eLazyBoolYes:
2657 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00002658 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002659 break;
2660
2661 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002662 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00002663 {
2664 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002665 if (pos != m_addr_to_mmap_size.end() &&
2666 InferiorCallMunmap(this, addr, pos->second))
2667 m_addr_to_mmap_size.erase (pos);
2668 else
Daniel Malead01b2952012-11-29 21:49:15 +00002669 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002670 }
2671 break;
2672 }
2673
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002674 return error;
2675}
2676
2677
2678//------------------------------------------------------------------
2679// Process STDIO
2680//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002681size_t
2682ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2683{
2684 if (m_stdio_communication.IsConnected())
2685 {
2686 ConnectionStatus status;
2687 m_stdio_communication.Write(src, src_len, status, NULL);
2688 }
Vince Harrondf3f00f2015-02-10 21:09:04 +00002689 else if (m_stdin_forward)
Vince Harrone0be4252015-02-06 18:32:57 +00002690 {
2691 m_gdb_comm.SendStdinNotification(src, src_len);
2692 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002693 return 0;
2694}
2695
2696Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002697ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002698{
2699 Error error;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002700 assert(bp_site != NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002701
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002702 // Get logging info
2703 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002704 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002705
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002706 // Get the breakpoint address
2707 const addr_t addr = bp_site->GetLoadAddress();
2708
2709 // Log that a breakpoint was requested
2710 if (log)
2711 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
2712
2713 // Breakpoint already exists and is enabled
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002714 if (bp_site->IsEnabled())
2715 {
2716 if (log)
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002717 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 +00002718 return error;
2719 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002720
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002721 // Get the software breakpoint trap opcode size
2722 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2723
2724 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
2725 // is supported by the remote stub. These are set to true by default, and later set to false
2726 // only after we receive an unimplemented response when sending a breakpoint packet. This means
2727 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
2728 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
2729 // indicates if the user specifically asked for hardware breakpoints. If true then we will
2730 // skip over software breakpoints.
2731 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
2732 {
2733 // Try to send off a software breakpoint packet ($Z0)
2734 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002735 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002736 // The breakpoint was placed successfully
2737 bp_site->SetEnabled(true);
2738 bp_site->SetType(BreakpointSite::eExternal);
Greg Claytoneb023e72013-10-11 19:48:25 +00002739 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002740 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002741
2742 // SendGDBStoppointTypePacket() will return an error if it was unable to set this
2743 // breakpoint. We need to differentiate between a error specific to placing this breakpoint
2744 // or if we have learned that this breakpoint type is unsupported. To do this, we
2745 // must test the support boolean for this breakpoint type to see if it now indicates that
2746 // this breakpoint type is unsupported. If they are still supported then we should return
2747 // with the error code. If they are now unsupported, then we would like to fall through
2748 // and try another form of breakpoint.
2749 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
2750 return error;
2751
2752 // We reach here when software breakpoints have been found to be unsupported. For future
2753 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
2754 // known not to be supported.
2755 if (log)
2756 log->Printf("Software breakpoints are unsupported");
2757
2758 // So we will fall through and try a hardware breakpoint
2759 }
2760
2761 // The process of setting a hardware breakpoint is much the same as above. We check the
2762 // supported boolean for this breakpoint type, and if it is thought to be supported then we
2763 // will try to set this breakpoint with a hardware breakpoint.
2764 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
2765 {
2766 // Try to send off a hardware breakpoint packet ($Z1)
2767 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002768 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002769 // The breakpoint was placed successfully
2770 bp_site->SetEnabled(true);
2771 bp_site->SetType(BreakpointSite::eHardware);
2772 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002773 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002774
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002775 // Check if the error was something other then an unsupported breakpoint type
2776 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
2777 {
2778 // Unable to set this hardware breakpoint
2779 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
2780 return error;
2781 }
2782
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002783 // We will reach here when the stub gives an unsupported response to a hardware breakpoint
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002784 if (log)
2785 log->Printf("Hardware breakpoints are unsupported");
2786
2787 // Finally we will falling through to a #trap style breakpoint
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002788 }
2789
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002790 // Don't fall through when hardware breakpoints were specifically requested
2791 if (bp_site->HardwareRequired())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002792 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002793 error.SetErrorString("hardware breakpoints are not supported");
2794 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002795 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002796
2797 // As a last resort we want to place a manual breakpoint. An instruction
2798 // is placed into the process memory using memory write packets.
2799 return EnableSoftwareBreakpoint(bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002800}
2801
2802Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002803ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002804{
2805 Error error;
2806 assert (bp_site != NULL);
2807 addr_t addr = bp_site->GetLoadAddress();
2808 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00002809 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002810 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002811 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002812
2813 if (bp_site->IsEnabled())
2814 {
2815 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2816
Greg Clayton8b82f082011-04-12 05:54:46 +00002817 BreakpointSite::Type bp_type = bp_site->GetType();
2818 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002819 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002820 case BreakpointSite::eSoftware:
2821 error = DisableSoftwareBreakpoint (bp_site);
2822 break;
2823
2824 case BreakpointSite::eHardware:
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002825 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00002826 error.SetErrorToGenericError();
2827 break;
2828
2829 case BreakpointSite::eExternal:
Jim Inghama04ef752014-03-07 11:18:02 +00002830 {
2831 GDBStoppointType stoppoint_type;
2832 if (bp_site->IsHardware())
2833 stoppoint_type = eBreakpointHardware;
2834 else
2835 stoppoint_type = eBreakpointSoftware;
2836
2837 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00002838 error.SetErrorToGenericError();
Jim Inghama04ef752014-03-07 11:18:02 +00002839 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002840 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002841 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002842 if (error.Success())
2843 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002844 }
2845 else
2846 {
2847 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002848 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 +00002849 return error;
2850 }
2851
2852 if (error.Success())
2853 error.SetErrorToGenericError();
2854 return error;
2855}
2856
Johnny Chen11309a32011-09-06 22:38:36 +00002857// Pre-requisite: wp != NULL.
2858static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00002859GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00002860{
2861 assert(wp);
2862 bool watch_read = wp->WatchpointRead();
2863 bool watch_write = wp->WatchpointWrite();
2864
2865 // watch_read and watch_write cannot both be false.
2866 assert(watch_read || watch_write);
2867 if (watch_read && watch_write)
2868 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00002869 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00002870 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00002871 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00002872 return eWatchpointWrite;
2873}
2874
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002875Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002876ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002877{
2878 Error error;
2879 if (wp)
2880 {
2881 user_id_t watchID = wp->GetID();
2882 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00002883 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002884 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002885 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002886 if (wp->IsEnabled())
2887 {
2888 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002889 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 +00002890 return error;
2891 }
Johnny Chen11309a32011-09-06 22:38:36 +00002892
2893 GDBStoppointType type = GetGDBStoppointType(wp);
2894 // Pass down an appropriate z/Z packet...
2895 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002896 {
Johnny Chen11309a32011-09-06 22:38:36 +00002897 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2898 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002899 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002900 return error;
2901 }
2902 else
2903 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002904 }
Johnny Chen11309a32011-09-06 22:38:36 +00002905 else
2906 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002907 }
2908 else
2909 {
Johnny Chen01a67862011-10-14 00:42:25 +00002910 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002911 }
2912 if (error.Success())
2913 error.SetErrorToGenericError();
2914 return error;
2915}
2916
2917Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002918ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002919{
2920 Error error;
2921 if (wp)
2922 {
2923 user_id_t watchID = wp->GetID();
2924
Greg Clayton5160ce52013-03-27 23:08:40 +00002925 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002926
2927 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00002928
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002929 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002930 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002931
Johnny Chen11309a32011-09-06 22:38:36 +00002932 if (!wp->IsEnabled())
2933 {
2934 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002935 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 +00002936 // See also 'class WatchpointSentry' within StopInfo.cpp.
2937 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2938 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00002939 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002940 return error;
2941 }
2942
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002943 if (wp->IsHardware())
2944 {
Johnny Chen11309a32011-09-06 22:38:36 +00002945 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002946 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00002947 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2948 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002949 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002950 return error;
2951 }
2952 else
2953 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002954 }
2955 // TODO: clear software watchpoints if we implement them
2956 }
2957 else
2958 {
Johnny Chen01a67862011-10-14 00:42:25 +00002959 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002960 }
2961 if (error.Success())
2962 error.SetErrorToGenericError();
2963 return error;
2964}
2965
2966void
2967ProcessGDBRemote::Clear()
2968{
2969 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002970 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002971 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002972}
2973
2974Error
2975ProcessGDBRemote::DoSignal (int signo)
2976{
2977 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002978 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002979 if (log)
2980 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2981
2982 if (!m_gdb_comm.SendAsyncSignal (signo))
2983 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2984 return error;
2985}
2986
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002987Error
Greg Clayton91a9b2472013-12-04 19:19:12 +00002988ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002989{
2990 Error error;
2991 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2992 {
2993 // If we locate debugserver, keep that located version around
2994 static FileSpec g_debugserver_file_spec;
2995
Han Ming Ong84647042012-02-25 01:07:38 +00002996 ProcessLaunchInfo debugserver_launch_info;
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00002997 // Make debugserver run in its own session so signals generated by
2998 // special terminal key sequences (^C) don't affect debugserver.
2999 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3000
Greg Clayton91a9b2472013-12-04 19:19:12 +00003001 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
3002 debugserver_launch_info.SetUserID(process_info.GetUserID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003003
Todd Fiala013434e2014-07-09 01:29:05 +00003004#if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__) || defined (__aarch64__))
Greg Claytonfda4fab2014-01-10 22:24:11 +00003005 // On iOS, still do a local connection using a random port
Greg Clayton16810922014-02-27 19:38:18 +00003006 const char *hostname = "127.0.0.1";
Greg Claytonfda4fab2014-01-10 22:24:11 +00003007 uint16_t port = get_random_port ();
3008#else
3009 // Set hostname being NULL to do the reverse connect where debugserver
3010 // will bind to port zero and it will communicate back to us the port
3011 // that we will connect to
3012 const char *hostname = NULL;
3013 uint16_t port = 0;
3014#endif
3015
3016 error = m_gdb_comm.StartDebugserverProcess (hostname,
3017 port,
Greg Clayton00fe87b2013-12-05 22:58:22 +00003018 debugserver_launch_info,
3019 port);
Greg Clayton91a9b2472013-12-04 19:19:12 +00003020
3021 if (error.Success ())
3022 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003023 else
Greg Clayton91a9b2472013-12-04 19:19:12 +00003024 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003025
3026 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3027 StartAsyncThread ();
Greg Clayton91a9b2472013-12-04 19:19:12 +00003028
3029 if (error.Fail())
3030 {
3031 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
3032
3033 if (log)
3034 log->Printf("failed to start debugserver process: %s", error.AsCString());
3035 return error;
3036 }
3037
Greg Clayton00fe87b2013-12-05 22:58:22 +00003038 if (m_gdb_comm.IsConnected())
3039 {
3040 // Finish the connection process by doing the handshake without connecting (send NULL URL)
3041 ConnectToDebugserver (NULL);
3042 }
3043 else
3044 {
Greg Claytonfda4fab2014-01-10 22:24:11 +00003045 StreamString connect_url;
3046 connect_url.Printf("connect://%s:%u", hostname, port);
3047 error = ConnectToDebugserver (connect_url.GetString().c_str());
Greg Clayton00fe87b2013-12-05 22:58:22 +00003048 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00003049
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003050 }
3051 return error;
3052}
3053
3054bool
3055ProcessGDBRemote::MonitorDebugserverProcess
3056(
3057 void *callback_baton,
3058 lldb::pid_t debugserver_pid,
Greg Claytone4e45922011-11-16 05:37:56 +00003059 bool exited, // True if the process did exit
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003060 int signo, // Zero for no signal
3061 int exit_status // Exit value of process if signal is zero
3062)
3063{
Greg Claytone4e45922011-11-16 05:37:56 +00003064 // The baton is a "ProcessGDBRemote *". Now this class might be gone
3065 // and might not exist anymore, so we need to carefully try to get the
3066 // target for this process first since we have a race condition when
3067 // we are done running between getting the notice that the inferior
3068 // process has died and the debugserver that was debugging this process.
3069 // In our test suite, we are also continually running process after
3070 // process, so we must be very careful to make sure:
3071 // 1 - process object hasn't been deleted already
3072 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003073
3074 // "debugserver_pid" argument passed in is the process ID for
3075 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00003076 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003077
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003078 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton6779606a2011-01-22 23:43:18 +00003079
Greg Claytone4e45922011-11-16 05:37:56 +00003080 // Get a shared pointer to the target that has a matching process pointer.
3081 // This target could be gone, or the target could already have a new process
3082 // object inside of it
3083 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
3084
Greg Clayton6779606a2011-01-22 23:43:18 +00003085 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003086 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 +00003087
Greg Claytone4e45922011-11-16 05:37:56 +00003088 if (target_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003089 {
Greg Claytone4e45922011-11-16 05:37:56 +00003090 // We found a process in a target that matches, but another thread
3091 // might be in the process of launching a new process that will
3092 // soon replace it, so get a shared pointer to the process so we
3093 // can keep it alive.
3094 ProcessSP process_sp (target_sp->GetProcessSP());
3095 // Now we have a shared pointer to the process that can't go away on us
3096 // so we now make sure it was the same as the one passed in, and also make
3097 // sure that our previous "process *" didn't get deleted and have a new
3098 // "process *" created in its place with the same pointer. To verify this
3099 // we make sure the process has our debugserver process ID. If we pass all
3100 // of these tests, then we are sure that this process is the one we were
3101 // looking for.
3102 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003103 {
Greg Claytone4e45922011-11-16 05:37:56 +00003104 // Sleep for a half a second to make sure our inferior process has
3105 // time to set its exit status before we set it incorrectly when
3106 // both the debugserver and the inferior process shut down.
3107 usleep (500000);
3108 // If our process hasn't yet exited, debugserver might have died.
3109 // If the process did exit, the we are reaping it.
3110 const StateType state = process->GetState();
3111
3112 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
3113 state != eStateInvalid &&
3114 state != eStateUnloaded &&
3115 state != eStateExited &&
3116 state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003117 {
Greg Claytone4e45922011-11-16 05:37:56 +00003118 char error_str[1024];
3119 if (signo)
3120 {
3121 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
3122 if (signal_cstr)
3123 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3124 else
3125 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
3126 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003127 else
Greg Claytone4e45922011-11-16 05:37:56 +00003128 {
3129 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
3130 }
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003131
Greg Claytone4e45922011-11-16 05:37:56 +00003132 process->SetExitStatus (-1, error_str);
3133 }
3134 // Debugserver has exited we need to let our ProcessGDBRemote
3135 // know that it no longer has a debugserver instance
3136 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003137 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003138 }
3139 return true;
3140}
3141
3142void
3143ProcessGDBRemote::KillDebugserverProcess ()
3144{
Greg Claytonfbb76342013-11-20 21:07:01 +00003145 m_gdb_comm.Disconnect();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003146 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3147 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003148 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003149 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3150 }
3151}
3152
3153void
3154ProcessGDBRemote::Initialize()
3155{
Davide Italianoc8d69822015-04-03 04:24:32 +00003156 static std::once_flag g_once_flag;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003157
Davide Italianoc8d69822015-04-03 04:24:32 +00003158 std::call_once(g_once_flag, []()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003159 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003160 PluginManager::RegisterPlugin (GetPluginNameStatic(),
3161 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00003162 CreateInstance,
3163 DebuggerInitialize);
Davide Italianoc8d69822015-04-03 04:24:32 +00003164 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003165}
3166
Greg Clayton7f982402013-07-15 22:54:20 +00003167void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003168ProcessGDBRemote::DebuggerInitialize (Debugger &debugger)
Greg Clayton7f982402013-07-15 22:54:20 +00003169{
3170 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
3171 {
3172 const bool is_global_setting = true;
3173 PluginManager::CreateSettingForProcessPlugin (debugger,
3174 GetGlobalPluginProperties()->GetValueProperties(),
3175 ConstString ("Properties for the gdb-remote process plug-in."),
3176 is_global_setting);
3177 }
3178}
3179
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003180bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003181ProcessGDBRemote::StartAsyncThread ()
3182{
Greg Clayton5160ce52013-03-27 23:08:40 +00003183 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003184
3185 if (log)
3186 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003187
3188 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003189 if (!m_async_thread.IsJoinable())
Jim Ingham455fa5c2012-11-01 01:15:33 +00003190 {
3191 // Create a thread that watches our internal state and controls which
3192 // events make it to clients (into the DCProcess event queue).
Zachary Turner39de3112014-09-09 20:54:56 +00003193
3194 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003195 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003196 else if (log)
3197 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was already running.", __FUNCTION__);
Zachary Turner39de3112014-09-09 20:54:56 +00003198
Zachary Turneracee96a2014-09-23 18:32:09 +00003199 return m_async_thread.IsJoinable();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003200}
3201
3202void
3203ProcessGDBRemote::StopAsyncThread ()
3204{
Greg Clayton5160ce52013-03-27 23:08:40 +00003205 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003206
3207 if (log)
3208 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
3209
Jim Ingham455fa5c2012-11-01 01:15:33 +00003210 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003211 if (m_async_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003212 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00003213 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
3214
3215 // This will shut down the async thread.
3216 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3217
3218 // Stop the stdio thread
Zachary Turner39de3112014-09-09 20:54:56 +00003219 m_async_thread.Join(nullptr);
Pavel Labatha55a9532015-03-11 09:53:42 +00003220 m_async_thread.Reset();
Jim Ingham455fa5c2012-11-01 01:15:33 +00003221 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003222 else if (log)
3223 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003224}
3225
3226
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003227thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003228ProcessGDBRemote::AsyncThread (void *arg)
3229{
3230 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
3231
Greg Clayton5160ce52013-03-27 23:08:40 +00003232 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003233 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003234 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003235
3236 Listener listener ("ProcessGDBRemote::AsyncThread");
3237 EventSP event_sp;
3238 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
3239 eBroadcastBitAsyncThreadShouldExit;
3240
3241 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
3242 {
Greg Clayton71337622011-02-24 22:24:29 +00003243 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
3244
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003245 bool done = false;
3246 while (!done)
3247 {
3248 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003249 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003250 if (listener.WaitForEvent (NULL, event_sp))
3251 {
3252 const uint32_t event_type = event_sp->GetType();
Greg Clayton71337622011-02-24 22:24:29 +00003253 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003254 {
Greg Clayton71337622011-02-24 22:24:29 +00003255 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003256 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003257
Greg Clayton71337622011-02-24 22:24:29 +00003258 switch (event_type)
3259 {
3260 case eBroadcastBitAsyncContinue:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003261 {
Greg Clayton71337622011-02-24 22:24:29 +00003262 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003263
Greg Clayton71337622011-02-24 22:24:29 +00003264 if (continue_packet)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003265 {
Greg Clayton71337622011-02-24 22:24:29 +00003266 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
3267 const size_t continue_cstr_len = continue_packet->GetByteSize ();
3268 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003269 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003270
Greg Clayton71337622011-02-24 22:24:29 +00003271 if (::strstr (continue_cstr, "vAttach") == NULL)
3272 process->SetPrivateState(eStateRunning);
3273 StringExtractorGDBRemote response;
3274 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003275
Greg Clayton0772ded2012-05-16 02:48:06 +00003276 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
3277 // The thread ID list might be contained within the "response", or the stop reply packet that
3278 // caused the stop. So clear it now before we give the stop reply packet to the process
3279 // using the process->SetLastStopPacket()...
3280 process->ClearThreadIDList ();
3281
Greg Clayton71337622011-02-24 22:24:29 +00003282 switch (stop_state)
3283 {
3284 case eStateStopped:
3285 case eStateCrashed:
3286 case eStateSuspended:
Greg Clayton09c3e3d2011-12-06 04:51:14 +00003287 process->SetLastStopPacket (response);
Greg Clayton71337622011-02-24 22:24:29 +00003288 process->SetPrivateState (stop_state);
3289 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003290
Greg Clayton71337622011-02-24 22:24:29 +00003291 case eStateExited:
Jason Molendaa3329782014-03-29 18:54:20 +00003292 {
Greg Clayton09c3e3d2011-12-06 04:51:14 +00003293 process->SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00003294 process->ClearThreadIDList();
Greg Clayton71337622011-02-24 22:24:29 +00003295 response.SetFilePos(1);
Jason Molendaa3329782014-03-29 18:54:20 +00003296
3297 int exit_status = response.GetHexU8();
3298 const char *desc_cstr = NULL;
3299 StringExtractor extractor;
3300 std::string desc_string;
3301 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';')
3302 {
3303 std::string desc_token;
3304 while (response.GetNameColonValue (desc_token, desc_string))
3305 {
3306 if (desc_token == "description")
3307 {
3308 extractor.GetStringRef().swap(desc_string);
3309 extractor.SetFilePos(0);
3310 extractor.GetHexByteString (desc_string);
3311 desc_cstr = desc_string.c_str();
3312 }
3313 }
3314 }
3315 process->SetExitStatus(exit_status, desc_cstr);
Greg Clayton71337622011-02-24 22:24:29 +00003316 done = true;
3317 break;
Jason Molendaa3329782014-03-29 18:54:20 +00003318 }
Greg Clayton71337622011-02-24 22:24:29 +00003319 case eStateInvalid:
3320 process->SetExitStatus(-1, "lost connection");
3321 break;
3322
3323 default:
3324 process->SetPrivateState (stop_state);
3325 break;
3326 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003327 }
3328 }
Greg Clayton71337622011-02-24 22:24:29 +00003329 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003330
Greg Clayton71337622011-02-24 22:24:29 +00003331 case eBroadcastBitAsyncThreadShouldExit:
3332 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003333 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Clayton71337622011-02-24 22:24:29 +00003334 done = true;
3335 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003336
Greg Clayton71337622011-02-24 22:24:29 +00003337 default:
3338 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003339 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
Greg Clayton71337622011-02-24 22:24:29 +00003340 done = true;
3341 break;
3342 }
3343 }
3344 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
3345 {
3346 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
3347 {
3348 process->SetExitStatus (-1, "lost connection");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003349 done = true;
Greg Clayton71337622011-02-24 22:24:29 +00003350 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003351 }
3352 }
3353 else
3354 {
3355 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003356 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003357 done = true;
3358 }
3359 }
3360 }
3361
3362 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003363 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003364
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003365 return NULL;
3366}
3367
Greg Claytone996fd32011-03-08 22:40:15 +00003368//uint32_t
3369//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3370//{
3371// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
3372// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
3373// if (m_local_debugserver)
3374// {
3375// return Host::ListProcessesMatchingName (name, matches, pids);
3376// }
3377// else
3378// {
3379// // FIXME: Implement talking to the remote debugserver.
3380// return 0;
3381// }
3382//
3383//}
3384//
Jim Ingham1c823b42011-01-22 01:33:44 +00003385bool
3386ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003387 StoppointCallbackContext *context,
Jim Ingham1c823b42011-01-22 01:33:44 +00003388 lldb::user_id_t break_id,
3389 lldb::user_id_t break_loc_id)
3390{
3391 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3392 // run so I can stop it if that's what I want to do.
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003393 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00003394 if (log)
3395 log->Printf("Hit New Thread Notification breakpoint.");
3396 return false;
3397}
3398
3399
3400bool
3401ProcessGDBRemote::StartNoticingNewThreads()
3402{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003403 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00003404 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003405 {
Greg Clayton4116e932012-05-15 02:33:01 +00003406 if (log && log->GetVerbose())
3407 log->Printf("Enabled noticing new thread breakpoint.");
3408 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003409 }
Greg Clayton4116e932012-05-15 02:33:01 +00003410 else
Jim Ingham1c823b42011-01-22 01:33:44 +00003411 {
Greg Clayton4116e932012-05-15 02:33:01 +00003412 PlatformSP platform_sp (m_target.GetPlatform());
3413 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003414 {
Greg Clayton4116e932012-05-15 02:33:01 +00003415 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3416 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003417 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00003418 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00003419 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3420 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003421 }
3422 else
3423 {
3424 if (log)
3425 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00003426 }
3427 }
3428 }
Greg Clayton4116e932012-05-15 02:33:01 +00003429 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00003430}
3431
3432bool
3433ProcessGDBRemote::StopNoticingNewThreads()
3434{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003435 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00003436 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00003437 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00003438
3439 if (m_thread_create_bp_sp)
3440 m_thread_create_bp_sp->SetEnabled(false);
3441
Jim Ingham1c823b42011-01-22 01:33:44 +00003442 return true;
3443}
3444
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003445DynamicLoader *
Jason Molenda5e8534e2012-10-03 01:29:34 +00003446ProcessGDBRemote::GetDynamicLoader ()
3447{
3448 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00003449 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00003450 return m_dyld_ap.get();
3451}
Jim Ingham1c823b42011-01-22 01:33:44 +00003452
Jason Molendaa3329782014-03-29 18:54:20 +00003453Error
3454ProcessGDBRemote::SendEventData(const char *data)
3455{
3456 int return_value;
3457 bool was_supported;
3458
3459 Error error;
3460
3461 return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported);
3462 if (return_value != 0)
3463 {
3464 if (!was_supported)
3465 error.SetErrorString("Sending events is not supported for this process.");
3466 else
3467 error.SetErrorStringWithFormat("Error sending event data: %d.", return_value);
3468 }
3469 return error;
3470}
3471
Steve Pucci03904ac2014-03-04 23:18:46 +00003472const DataBufferSP
3473ProcessGDBRemote::GetAuxvData()
3474{
3475 DataBufferSP buf;
3476 if (m_gdb_comm.GetQXferAuxvReadSupported())
3477 {
3478 std::string response_string;
3479 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success)
3480 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length()));
3481 }
3482 return buf;
3483}
3484
Jason Molenda705b1802014-06-13 02:37:02 +00003485StructuredData::ObjectSP
3486ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid)
3487{
3488 StructuredData::ObjectSP object_sp;
3489
3490 if (m_gdb_comm.GetThreadExtendedInfoSupported())
3491 {
3492 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3493 SystemRuntime *runtime = GetSystemRuntime();
3494 if (runtime)
3495 {
3496 runtime->AddThreadExtendedInfoPacketHints (args_dict);
3497 }
3498 args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid);
3499
3500 StreamString packet;
3501 packet << "jThreadExtendedInfo:";
3502 args_dict->Dump (packet);
3503
3504 // FIXME the final character of a JSON dictionary, '}', is the escape
3505 // character in gdb-remote binary mode. lldb currently doesn't escape
3506 // these characters in its packet output -- so we add the quoted version
3507 // of the } character here manually in case we talk to a debugserver which
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003508 // un-escapes the characters at packet read time.
Jason Molenda705b1802014-06-13 02:37:02 +00003509 packet << (char) (0x7d ^ 0x20);
3510
3511 StringExtractorGDBRemote response;
3512 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
3513 {
3514 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
3515 if (response_type == StringExtractorGDBRemote::eResponse)
3516 {
3517 if (!response.Empty())
3518 {
3519 // The packet has already had the 0x7d xor quoting stripped out at the
3520 // GDBRemoteCommunication packet receive level.
3521 object_sp = StructuredData::ParseJSON (response.GetStringRef());
3522 }
3523 }
3524 }
3525 }
3526 return object_sp;
3527}
3528
Jason Molenda6076bf42014-05-06 04:34:52 +00003529// Establish the largest memory read/write payloads we should use.
3530// If the remote stub has a max packet size, stay under that size.
3531//
3532// If the remote stub's max packet size is crazy large, use a
3533// reasonable largeish default.
3534//
3535// If the remote stub doesn't advertise a max packet size, use a
3536// conservative default.
3537
3538void
3539ProcessGDBRemote::GetMaxMemorySize()
3540{
3541 const uint64_t reasonable_largeish_default = 128 * 1024;
3542 const uint64_t conservative_default = 512;
3543
3544 if (m_max_memory_size == 0)
3545 {
3546 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
3547 if (stub_max_size != UINT64_MAX && stub_max_size != 0)
3548 {
3549 // Save the stub's claimed maximum packet size
3550 m_remote_stub_max_memory_size = stub_max_size;
3551
3552 // Even if the stub says it can support ginormous packets,
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003553 // don't exceed our reasonable largeish default packet size.
Jason Molenda6076bf42014-05-06 04:34:52 +00003554 if (stub_max_size > reasonable_largeish_default)
3555 {
3556 stub_max_size = reasonable_largeish_default;
3557 }
3558
3559 m_max_memory_size = stub_max_size;
3560 }
3561 else
3562 {
3563 m_max_memory_size = conservative_default;
3564 }
3565 }
3566}
3567
3568void
3569ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max)
3570{
3571 if (user_specified_max != 0)
3572 {
3573 GetMaxMemorySize ();
3574
3575 if (m_remote_stub_max_memory_size != 0)
3576 {
3577 if (m_remote_stub_max_memory_size < user_specified_max)
3578 {
3579 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a packet size too big, go as big
3580 // as the remote stub says we can go.
3581 }
3582 else
3583 {
3584 m_max_memory_size = user_specified_max; // user's packet size is good
3585 }
3586 }
3587 else
3588 {
3589 m_max_memory_size = user_specified_max; // user's packet size is probably fine
3590 }
3591 }
3592}
3593
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003594bool
3595ProcessGDBRemote::GetModuleSpec(const FileSpec& module_file_spec,
3596 const ArchSpec& arch,
3597 ModuleSpec &module_spec)
3598{
3599 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PLATFORM);
3600
3601 if (!m_gdb_comm.GetModuleInfo (module_file_spec, arch, module_spec))
3602 {
3603 if (log)
3604 log->Printf ("ProcessGDBRemote::%s - failed to get module info for %s:%s",
3605 __FUNCTION__, module_file_spec.GetPath ().c_str (),
3606 arch.GetTriple ().getTriple ().c_str ());
3607 return false;
3608 }
3609
3610 if (log)
3611 {
3612 StreamString stream;
3613 module_spec.Dump (stream);
3614 log->Printf ("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
3615 __FUNCTION__, module_file_spec.GetPath ().c_str (),
3616 arch.GetTriple ().getTriple ().c_str (), stream.GetString ().c_str ());
3617 }
3618
3619 return true;
3620}
3621
Colin Rileyc3c95b22015-04-16 15:51:33 +00003622namespace {
3623
3624typedef std::vector<std::string> stringVec;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003625
3626typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
Greg Claytond04f0ed2015-05-26 18:00:51 +00003627struct RegisterSetInfo
3628{
3629 ConstString name;
3630};
Colin Rileyc3c95b22015-04-16 15:51:33 +00003631
Greg Claytond04f0ed2015-05-26 18:00:51 +00003632typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
3633
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003634struct GdbServerTargetInfo
3635{
Greg Claytond04f0ed2015-05-26 18:00:51 +00003636 std::string arch;
3637 std::string osabi;
3638 stringVec includes;
3639 RegisterSetMap reg_set_map;
3640 XMLNode feature_node;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003641};
Greg Claytond04f0ed2015-05-26 18:00:51 +00003642
Colin Rileyc3c95b22015-04-16 15:51:33 +00003643bool
Greg Claytond04f0ed2015-05-26 18:00:51 +00003644ParseRegisters (XMLNode feature_node, GdbServerTargetInfo &target_info, GDBRemoteDynamicRegisterInfo &dyn_reg_info)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003645{
Greg Claytond04f0ed2015-05-26 18:00:51 +00003646 if (!feature_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003647 return false;
Greg Claytond04f0ed2015-05-26 18:00:51 +00003648
3649 uint32_t prev_reg_num = 0;
3650 uint32_t reg_offset = 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003651
Greg Claytond04f0ed2015-05-26 18:00:51 +00003652 feature_node.ForEachChildElementWithName("reg", [&target_info, &dyn_reg_info, &prev_reg_num, &reg_offset](const XMLNode &reg_node) -> bool {
3653 std::string name;
3654 std::string gdb_group;
3655 std::string gdb_type;
3656 ConstString reg_name;
3657 ConstString alt_name;
3658 ConstString set_name;
3659 std::vector<uint32_t> value_regs;
3660 std::vector<uint32_t> invalidate_regs;
3661 bool encoding_set = false;
3662 bool format_set = false;
3663 RegisterInfo reg_info = { NULL, // Name
3664 NULL, // Alt name
3665 0, // byte size
3666 reg_offset, // offset
3667 eEncodingUint, // encoding
3668 eFormatHex, // formate
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003669 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00003670 LLDB_INVALID_REGNUM, // GCC reg num
3671 LLDB_INVALID_REGNUM, // DWARF reg num
3672 LLDB_INVALID_REGNUM, // generic reg num
3673 prev_reg_num, // GDB reg num
3674 prev_reg_num // native register number
3675 },
3676 NULL,
3677 NULL
3678 };
3679
3680 reg_node.ForEachAttribute([&target_info, &name, &gdb_group, &gdb_type, &reg_name, &alt_name, &set_name, &value_regs, &invalidate_regs, &encoding_set, &format_set, &reg_info, &prev_reg_num, &reg_offset](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
3681 if (name == "name")
3682 {
3683 reg_name.SetString(value);
3684 }
3685 else if (name == "bitsize")
3686 {
3687 reg_info.byte_size = StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
3688 }
3689 else if (name == "type")
3690 {
3691 gdb_type = value.str();
3692 }
3693 else if (name == "group")
3694 {
3695 gdb_group = value.str();
3696 }
3697 else if (name == "regnum")
3698 {
3699 const uint32_t regnum = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
3700 if (regnum != LLDB_INVALID_REGNUM)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003701 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00003702 reg_info.kinds[eRegisterKindGDB] = regnum;
3703 reg_info.kinds[eRegisterKindLLDB] = regnum;
3704 prev_reg_num = regnum;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003705 }
3706 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00003707 else if (name == "offset")
3708 {
3709 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
3710 }
3711 else if (name == "altname")
3712 {
3713 alt_name.SetString(value);
3714 }
3715 else if (name == "encoding")
3716 {
3717 encoding_set = true;
3718 reg_info.encoding = Args::StringToEncoding (value.data(), eEncodingUint);
3719 }
3720 else if (name == "format")
3721 {
3722 format_set = true;
3723 Format format = eFormatInvalid;
3724 if (Args::StringToFormat (value.data(), format, NULL).Success())
3725 reg_info.format = format;
3726 else if (value == "vector-sint8")
3727 reg_info.format = eFormatVectorOfSInt8;
3728 else if (value == "vector-uint8")
3729 reg_info.format = eFormatVectorOfUInt8;
3730 else if (value == "vector-sint16")
3731 reg_info.format = eFormatVectorOfSInt16;
3732 else if (value == "vector-uint16")
3733 reg_info.format = eFormatVectorOfUInt16;
3734 else if (value == "vector-sint32")
3735 reg_info.format = eFormatVectorOfSInt32;
3736 else if (value == "vector-uint32")
3737 reg_info.format = eFormatVectorOfUInt32;
3738 else if (value == "vector-float32")
3739 reg_info.format = eFormatVectorOfFloat32;
3740 else if (value == "vector-uint128")
3741 reg_info.format = eFormatVectorOfUInt128;
3742 }
3743 else if (name == "group_id")
3744 {
3745 const uint32_t set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
3746 RegisterSetMap::const_iterator pos = target_info.reg_set_map.find(set_id);
3747 if (pos != target_info.reg_set_map.end())
3748 set_name = pos->second.name;
3749 }
3750 else if (name == "gcc_regnum")
3751 {
3752 reg_info.kinds[eRegisterKindGCC] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
3753 }
3754 else if (name == "dwarf_regnum")
3755 {
3756 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
3757 }
3758 else if (name == "generic")
3759 {
3760 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister(value.data());
3761 }
3762 else if (name == "value_regnums")
3763 {
3764 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
3765 }
3766 else if (name == "invalidate_regnums")
3767 {
3768 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
3769 }
3770 else
3771 {
3772 printf("unhandled attribute %s = %s\n", name.data(), value.data());
3773 }
3774 return true; // Keep iterating through all attributes
3775 });
3776
3777 if (!gdb_type.empty() && !(encoding_set || format_set))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003778 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00003779 if (gdb_type.find("int") == 0)
3780 {
3781 reg_info.format = eFormatHex;
3782 reg_info.encoding = eEncodingUint;
3783 }
3784 else if (gdb_type == "data_ptr" || gdb_type == "code_ptr")
3785 {
3786 reg_info.format = eFormatAddressInfo;
3787 reg_info.encoding = eEncodingUint;
3788 }
3789 else if (gdb_type == "i387_ext" || gdb_type == "float")
3790 {
3791 reg_info.format = eFormatFloat;
3792 reg_info.encoding = eEncodingIEEE754;
3793 }
Colin Rileyc3c95b22015-04-16 15:51:33 +00003794 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00003795
3796 // Only update the register set name if we didn't get a "reg_set" attribute.
3797 // "set_name" will be empty if we didn't have a "reg_set" attribute.
3798 if (!set_name && !gdb_group.empty())
3799 set_name.SetCString(gdb_group.c_str());
3800
3801 reg_info.byte_offset = reg_offset;
3802 assert (reg_info.byte_size != 0);
3803 reg_offset += reg_info.byte_size;
3804 if (!value_regs.empty())
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003805 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00003806 value_regs.push_back(LLDB_INVALID_REGNUM);
3807 reg_info.value_regs = value_regs.data();
Colin Rileyc3c95b22015-04-16 15:51:33 +00003808 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00003809 if (!invalidate_regs.empty())
3810 {
3811 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
3812 reg_info.invalidate_regs = invalidate_regs.data();
3813 }
3814
3815 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
3816
3817 return true; // Keep iterating through all "reg" elements
3818 });
Colin Rileyc3c95b22015-04-16 15:51:33 +00003819 return true;
3820}
Greg Claytond04f0ed2015-05-26 18:00:51 +00003821
Colin Rileyc3c95b22015-04-16 15:51:33 +00003822} // namespace {}
3823
Colin Rileyc3c95b22015-04-16 15:51:33 +00003824
3825// query the target of gdb-remote for extended target information
3826// return: 'true' on success
3827// 'false' on failure
3828bool
Aidan Doddsc0c83852015-05-08 09:36:31 +00003829ProcessGDBRemote::GetGDBServerRegisterInfo ()
Colin Rileyc3c95b22015-04-16 15:51:33 +00003830{
Greg Claytond04f0ed2015-05-26 18:00:51 +00003831 // Make sure LLDB has an XML parser it can use first
3832 if (!XMLDocument::XMLEnabled())
3833 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003834
3835 // redirect libxml2's error handler since the default prints to stdout
Colin Rileyc3c95b22015-04-16 15:51:33 +00003836
3837 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003838
3839 // check that we have extended feature read support
3840 if ( !comm.GetQXferFeaturesReadSupported( ) )
3841 return false;
3842
3843 // request the target xml file
3844 std::string raw;
3845 lldb_private::Error lldberr;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003846 if (!comm.ReadExtFeature(ConstString("features"),
3847 ConstString("target.xml"),
3848 raw,
3849 lldberr))
3850 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003851 return false;
3852 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00003853
Colin Rileyc3c95b22015-04-16 15:51:33 +00003854
Greg Claytond04f0ed2015-05-26 18:00:51 +00003855 XMLDocument xml_document;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003856
Greg Claytond04f0ed2015-05-26 18:00:51 +00003857 if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml"))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003858 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00003859 GdbServerTargetInfo target_info;
3860
3861 XMLNode target_node = xml_document.GetRootElement("target");
3862 if (target_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003863 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00003864 XMLNode feature_node;
3865 target_node.ForEachChildElement([&target_info, this, &feature_node](const XMLNode &node) -> bool
3866 {
3867 llvm::StringRef name = node.GetName();
3868 if (name == "architecture")
3869 {
3870 node.GetElementText(target_info.arch);
3871 }
3872 else if (name == "osabi")
3873 {
3874 node.GetElementText(target_info.osabi);
3875 }
3876 else if (name == "xi:include")
3877 {
3878 llvm::StringRef href = node.GetAttributeValue("href");
3879 if (!href.empty())
3880 target_info.includes.push_back(href.str());
3881 }
3882 else if (name == "feature")
3883 {
3884 feature_node = node;
3885 }
3886 else if (name == "groups")
3887 {
3888 node.ForEachChildElementWithName("group", [&target_info](const XMLNode &node) -> bool {
3889 uint32_t set_id = UINT32_MAX;
3890 RegisterSetInfo set_info;
3891
3892 node.ForEachAttribute([&set_id, &set_info](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
3893 if (name == "id")
3894 set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
3895 if (name == "name")
3896 set_info.name = ConstString(value);
3897 return true; // Keep iterating through all attributes
3898 });
3899
3900 if (set_id != UINT32_MAX)
3901 target_info.reg_set_map[set_id] = set_info;
3902 return true; // Keep iterating through all "group" elements
3903 });
3904 }
3905 return true; // Keep iterating through all children of the target_node
3906 });
3907
3908 if (feature_node)
3909 {
3910 ParseRegisters(feature_node, target_info, this->m_register_info);
3911 }
3912
3913 for (const auto &include : target_info.includes)
3914 {
3915 // request register file
3916 std::string xml_data;
3917 if (!comm.ReadExtFeature(ConstString("features"),
3918 ConstString(include),
3919 xml_data,
3920 lldberr))
3921 continue;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003922
Greg Claytond04f0ed2015-05-26 18:00:51 +00003923 XMLDocument include_xml_document;
3924 include_xml_document.ParseMemory(xml_data.data(), xml_data.size(), include.c_str());
3925 XMLNode include_feature_node = include_xml_document.GetRootElement("feature");
3926 if (include_feature_node)
3927 {
3928 ParseRegisters(include_feature_node, target_info, this->m_register_info);
3929 }
3930 }
3931 this->m_register_info.Finalize(GetTarget().GetArchitecture());
Colin Rileyc3c95b22015-04-16 15:51:33 +00003932 }
3933 }
3934
Greg Claytond04f0ed2015-05-26 18:00:51 +00003935 return m_register_info.GetNumRegisters() > 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003936}
3937
Aidan Doddsc0c83852015-05-08 09:36:31 +00003938Error
3939ProcessGDBRemote::GetLoadedModuleList (GDBLoadedModuleInfoList & list)
3940{
Greg Claytond04f0ed2015-05-26 18:00:51 +00003941 // Make sure LLDB has an XML parser it can use first
3942 if (!XMLDocument::XMLEnabled())
3943 return Error (0, ErrorType::eErrorTypeGeneric);
3944
Aidan Doddsc0c83852015-05-08 09:36:31 +00003945 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS);
3946 if (log)
3947 log->Printf ("ProcessGDBRemote::%s", __FUNCTION__);
3948
Aidan Doddsc0c83852015-05-08 09:36:31 +00003949 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Aidan Doddsc0c83852015-05-08 09:36:31 +00003950
3951 // check that we have extended feature read support
3952 if (!comm.GetQXferLibrariesSVR4ReadSupported ())
3953 return Error (0, ErrorType::eErrorTypeGeneric);
3954
3955 list.clear ();
3956
3957 // request the loaded library list
3958 std::string raw;
3959 lldb_private::Error lldberr;
3960 if (!comm.ReadExtFeature (ConstString ("libraries-svr4"), ConstString (""), raw, lldberr))
3961 return Error (0, ErrorType::eErrorTypeGeneric);
3962
3963 // parse the xml file in memory
3964 if (log)
3965 log->Printf ("parsing: %s", raw.c_str());
Greg Claytond04f0ed2015-05-26 18:00:51 +00003966 XMLDocument doc;
3967
3968 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
Aidan Doddsc0c83852015-05-08 09:36:31 +00003969 return Error (0, ErrorType::eErrorTypeGeneric);
3970
Greg Claytond04f0ed2015-05-26 18:00:51 +00003971 XMLNode root_element = doc.GetRootElement("library-list-svr4");
3972 if (!root_element)
Aidan Doddsc0c83852015-05-08 09:36:31 +00003973 return Error();
3974
3975 // main link map structure
Greg Claytond04f0ed2015-05-26 18:00:51 +00003976 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
3977 if (!main_lm.empty())
Aidan Doddsc0c83852015-05-08 09:36:31 +00003978 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00003979 list.m_link_map = StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
Aidan Doddsc0c83852015-05-08 09:36:31 +00003980 }
3981
Greg Claytond04f0ed2015-05-26 18:00:51 +00003982 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
Aidan Doddsc0c83852015-05-08 09:36:31 +00003983
3984 GDBLoadedModuleInfoList::LoadedModuleInfo module;
3985
Greg Claytond04f0ed2015-05-26 18:00:51 +00003986 library.ForEachAttribute([log, &module](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
3987
3988 if (name == "name")
3989 module.set_name (value.str());
3990 else if (name == "lm")
Aidan Doddsc0c83852015-05-08 09:36:31 +00003991 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00003992 // the address of the link_map struct.
3993 module.set_link_map(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
Aidan Doddsc0c83852015-05-08 09:36:31 +00003994 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00003995 else if (name == "l_addr")
Aidan Doddsc0c83852015-05-08 09:36:31 +00003996 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00003997 // the displacement as read from the field 'l_addr' of the link_map struct.
3998 module.set_base(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
3999
Aidan Doddsc0c83852015-05-08 09:36:31 +00004000 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004001 else if (name == "l_ld")
Aidan Doddsc0c83852015-05-08 09:36:31 +00004002 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004003 // the memory address of the libraries PT_DYAMIC section.
4004 module.set_dynamic(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
Aidan Doddsc0c83852015-05-08 09:36:31 +00004005 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004006
4007 return true; // Keep iterating over all properties of "library"
4008 });
Aidan Doddsc0c83852015-05-08 09:36:31 +00004009
4010 if (log)
4011 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004012 std::string name;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004013 lldb::addr_t lm=0, base=0, ld=0;
4014
4015 module.get_name (name);
4016 module.get_link_map (lm);
4017 module.get_base (base);
4018 module.get_dynamic (ld);
4019
4020 log->Printf ("found (link_map:0x08%" PRIx64 ", base:0x08%" PRIx64 ", ld:0x08%" PRIx64 ", name:'%s')", lm, base, ld, name.c_str());
4021 }
4022
4023 list.add (module);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004024 return true; // Keep iterating over all "library" elements in the root node
4025 });
Aidan Doddsc0c83852015-05-08 09:36:31 +00004026
4027 if (log)
4028 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4029
4030 return Error();
4031}
4032
Aidan Doddsc0c83852015-05-08 09:36:31 +00004033lldb::ModuleSP
4034ProcessGDBRemote::LoadModuleAtAddress (const FileSpec &file, lldb::addr_t base_addr)
4035{
4036 Target &target = m_process->GetTarget();
4037 ModuleList &modules = target.GetImages();
4038 ModuleSP module_sp;
4039
4040 bool changed = false;
4041
4042 ModuleSpec module_spec (file, target.GetArchitecture());
4043 if ((module_sp = modules.FindFirstModule (module_spec)))
4044 {
4045 module_sp->SetLoadAddress (target, base_addr, true, changed);
4046 }
4047 else if ((module_sp = target.GetSharedModule (module_spec)))
4048 {
4049 module_sp->SetLoadAddress (target, base_addr, true, changed);
4050 }
4051
4052 return module_sp;
4053}
4054
4055size_t
4056ProcessGDBRemote::LoadModules ()
4057{
4058 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4059
4060 // request a list of loaded libraries from GDBServer
4061 GDBLoadedModuleInfoList module_list;
4062 if (GetLoadedModuleList (module_list).Fail())
4063 return 0;
4064
4065 // get a list of all the modules
4066 ModuleList new_modules;
4067
4068 for (GDBLoadedModuleInfoList::LoadedModuleInfo & modInfo : module_list.m_list)
4069 {
4070 std::string mod_name;
4071 lldb::addr_t mod_base;
4072
4073 bool valid = true;
4074 valid &= modInfo.get_name (mod_name);
4075 valid &= modInfo.get_base (mod_base);
4076 if (!valid)
4077 continue;
4078
4079 // hack (cleaner way to get file name only?) (win/unix compat?)
Vince Harron4cc8d202015-05-10 08:33:58 +00004080 size_t marker = mod_name.rfind ('/');
Aidan Doddsc0c83852015-05-08 09:36:31 +00004081 if (marker == std::string::npos)
4082 marker = 0;
4083 else
4084 marker += 1;
4085
4086 FileSpec file (mod_name.c_str()+marker, true);
4087 lldb::ModuleSP module_sp = LoadModuleAtAddress (file, mod_base);
4088
4089 if (module_sp.get())
4090 new_modules.Append (module_sp);
4091 }
4092
4093 if (new_modules.GetSize() > 0)
4094 {
4095 Target & target = m_target;
4096
4097 new_modules.ForEach ([&target](const lldb::ModuleSP module_sp) -> bool
4098 {
4099 lldb_private::ObjectFile * obj = module_sp->GetObjectFile ();
4100 if (!obj)
4101 return true;
4102
4103 if (obj->GetType () != ObjectFile::Type::eTypeExecutable)
4104 return true;
4105
4106 lldb::ModuleSP module_copy_sp = module_sp;
4107 target.SetExecutableModule (module_copy_sp, false);
4108 return false;
4109 });
4110
4111 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4112 loaded_modules.AppendIfNeeded (new_modules);
4113 m_process->GetTarget().ModulesDidLoad (new_modules);
4114 }
4115
4116 return new_modules.GetSize();
4117}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004118
Greg Claytone034a042015-05-21 20:52:06 +00004119class CommandObjectProcessGDBRemoteSpeedTest: public CommandObjectParsed
4120{
4121public:
4122 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter) :
4123 CommandObjectParsed (interpreter,
4124 "process plugin packet speed-test",
4125 "Tests packet speeds of various sizes to determine the performance characteristics of the GDB remote connection. ",
4126 NULL),
4127 m_option_group (interpreter),
4128 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),
4129 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),
4130 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),
4131 m_json (LLDB_OPT_SET_1, false, "json", 'j', "Print the output as JSON data for easy parsing.", false, true)
4132 {
4133 m_option_group.Append (&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4134 m_option_group.Append (&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4135 m_option_group.Append (&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4136 m_option_group.Append (&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4137 m_option_group.Finalize();
4138 }
4139
4140 ~CommandObjectProcessGDBRemoteSpeedTest ()
4141 {
4142 }
4143
4144
4145 Options *
4146 GetOptions () override
4147 {
4148 return &m_option_group;
4149 }
4150
4151 bool
4152 DoExecute (Args& command, CommandReturnObject &result) override
4153 {
4154 const size_t argc = command.GetArgumentCount();
4155 if (argc == 0)
4156 {
4157 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4158 if (process)
4159 {
4160 StreamSP output_stream_sp (m_interpreter.GetDebugger().GetAsyncOutputStream());
4161 result.SetImmediateOutputStream (output_stream_sp);
4162
4163 const uint32_t num_packets = (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
4164 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
4165 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
4166 const bool json = m_json.GetOptionValue().GetCurrentValue();
4167 if (output_stream_sp)
4168 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, *output_stream_sp);
4169 else
4170 {
4171 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, result.GetOutputStream());
4172 }
4173 result.SetStatus (eReturnStatusSuccessFinishResult);
4174 return true;
4175 }
4176 }
4177 else
4178 {
4179 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
4180 }
4181 result.SetStatus (eReturnStatusFailed);
4182 return false;
4183 }
4184protected:
4185 OptionGroupOptions m_option_group;
4186 OptionGroupUInt64 m_num_packets;
4187 OptionGroupUInt64 m_max_send;
4188 OptionGroupUInt64 m_max_recv;
4189 OptionGroupBoolean m_json;
4190
4191};
4192
Greg Clayton02686b82012-10-15 22:42:16 +00004193class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00004194{
4195private:
4196
4197public:
Greg Clayton02686b82012-10-15 22:42:16 +00004198 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00004199 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00004200 "process plugin packet history",
4201 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00004202 NULL)
4203 {
4204 }
4205
Greg Clayton02686b82012-10-15 22:42:16 +00004206 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton998255b2012-10-13 02:07:45 +00004207 {
4208 }
4209
4210 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004211 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton998255b2012-10-13 02:07:45 +00004212 {
Greg Clayton02686b82012-10-15 22:42:16 +00004213 const size_t argc = command.GetArgumentCount();
4214 if (argc == 0)
4215 {
4216 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4217 if (process)
4218 {
4219 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
4220 result.SetStatus (eReturnStatusSuccessFinishResult);
4221 return true;
4222 }
4223 }
4224 else
4225 {
4226 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
4227 }
4228 result.SetStatus (eReturnStatusFailed);
4229 return false;
4230 }
4231};
4232
Jason Molenda6076bf42014-05-06 04:34:52 +00004233class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed
4234{
4235private:
4236
4237public:
4238 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) :
4239 CommandObjectParsed (interpreter,
4240 "process plugin packet xfer-size",
4241 "Maximum size that lldb will try to read/write one one chunk.",
4242 NULL)
4243 {
4244 }
4245
4246 ~CommandObjectProcessGDBRemotePacketXferSize ()
4247 {
4248 }
4249
4250 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004251 DoExecute (Args& command, CommandReturnObject &result) override
Jason Molenda6076bf42014-05-06 04:34:52 +00004252 {
4253 const size_t argc = command.GetArgumentCount();
4254 if (argc == 0)
4255 {
4256 result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str());
4257 result.SetStatus (eReturnStatusFailed);
4258 return false;
4259 }
4260
4261 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4262 if (process)
4263 {
4264 const char *packet_size = command.GetArgumentAtIndex(0);
4265 errno = 0;
4266 uint64_t user_specified_max = strtoul (packet_size, NULL, 10);
4267 if (errno == 0 && user_specified_max != 0)
4268 {
4269 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max);
4270 result.SetStatus (eReturnStatusSuccessFinishResult);
4271 return true;
4272 }
4273 }
4274 result.SetStatus (eReturnStatusFailed);
4275 return false;
4276 }
4277};
4278
4279
Greg Clayton02686b82012-10-15 22:42:16 +00004280class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
4281{
4282private:
4283
4284public:
4285 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
4286 CommandObjectParsed (interpreter,
4287 "process plugin packet send",
4288 "Send a custom packet through the GDB remote protocol and print the answer. "
4289 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
4290 NULL)
4291 {
4292 }
4293
4294 ~CommandObjectProcessGDBRemotePacketSend ()
4295 {
4296 }
4297
4298 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004299 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton02686b82012-10-15 22:42:16 +00004300 {
4301 const size_t argc = command.GetArgumentCount();
4302 if (argc == 0)
4303 {
4304 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
4305 result.SetStatus (eReturnStatusFailed);
4306 return false;
4307 }
4308
4309 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4310 if (process)
4311 {
Han Ming Ong84145852012-11-26 20:42:03 +00004312 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00004313 {
Han Ming Ong84145852012-11-26 20:42:03 +00004314 const char *packet_cstr = command.GetArgumentAtIndex(0);
4315 bool send_async = true;
4316 StringExtractorGDBRemote response;
4317 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
4318 result.SetStatus (eReturnStatusSuccessFinishResult);
4319 Stream &output_strm = result.GetOutputStream();
4320 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00004321 std::string &response_str = response.GetStringRef();
4322
Han Ming Ong399289e2013-06-21 19:56:59 +00004323 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00004324 {
4325 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
4326 }
4327
Han Ming Ong84145852012-11-26 20:42:03 +00004328 if (response_str.empty())
4329 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
4330 else
4331 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00004332 }
Greg Clayton02686b82012-10-15 22:42:16 +00004333 }
Greg Clayton998255b2012-10-13 02:07:45 +00004334 return true;
4335 }
4336};
4337
Greg Claytonba4a0a52013-02-01 23:03:47 +00004338class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
4339{
4340private:
4341
4342public:
4343 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
4344 CommandObjectRaw (interpreter,
4345 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00004346 "Send a qRcmd packet through the GDB remote protocol and print the response."
4347 "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 +00004348 NULL)
4349 {
4350 }
4351
4352 ~CommandObjectProcessGDBRemotePacketMonitor ()
4353 {
4354 }
4355
4356 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004357 DoExecute (const char *command, CommandReturnObject &result) override
Greg Claytonba4a0a52013-02-01 23:03:47 +00004358 {
4359 if (command == NULL || command[0] == '\0')
4360 {
4361 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
4362 result.SetStatus (eReturnStatusFailed);
4363 return false;
4364 }
4365
4366 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4367 if (process)
4368 {
4369 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00004370 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00004371 packet.PutBytesAsRawHex8(command, strlen(command));
4372 const char *packet_cstr = packet.GetString().c_str();
4373
4374 bool send_async = true;
4375 StringExtractorGDBRemote response;
4376 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
4377 result.SetStatus (eReturnStatusSuccessFinishResult);
4378 Stream &output_strm = result.GetOutputStream();
4379 output_strm.Printf (" packet: %s\n", packet_cstr);
4380 const std::string &response_str = response.GetStringRef();
4381
4382 if (response_str.empty())
4383 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
4384 else
4385 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
4386 }
4387 return true;
4388 }
4389};
4390
Greg Clayton02686b82012-10-15 22:42:16 +00004391class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
4392{
4393private:
4394
4395public:
4396 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
4397 CommandObjectMultiword (interpreter,
4398 "process plugin packet",
4399 "Commands that deal with GDB remote packets.",
4400 NULL)
4401 {
4402 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
4403 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00004404 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Jason Molenda6076bf42014-05-06 04:34:52 +00004405 LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter)));
Greg Claytone034a042015-05-21 20:52:06 +00004406 LoadSubCommand ("speed-test", CommandObjectSP (new CommandObjectProcessGDBRemoteSpeedTest (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00004407 }
4408
4409 ~CommandObjectProcessGDBRemotePacket ()
4410 {
4411 }
4412};
Greg Clayton998255b2012-10-13 02:07:45 +00004413
4414class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
4415{
4416public:
4417 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
4418 CommandObjectMultiword (interpreter,
4419 "process plugin",
4420 "A set of commands for operating on a ProcessGDBRemote process.",
4421 "process plugin <subcommand> [<subcommand-options>]")
4422 {
4423 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
4424 }
4425
4426 ~CommandObjectMultiwordProcessGDBRemote ()
4427 {
4428 }
4429};
4430
Greg Clayton998255b2012-10-13 02:07:45 +00004431CommandObject *
4432ProcessGDBRemote::GetPluginCommandObject()
4433{
4434 if (!m_command_sp)
4435 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
4436 return m_command_sp.get();
4437}