blob: 1526b0911a18e1d07d08fce4de438efa25705822 [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
29// Other libraries and framework includes
Colin Rileyc3c95b22015-04-16 15:51:33 +000030#if defined( LIBXML2_DEFINED )
31#include <libxml/xmlreader.h>
32#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000033
Johnny Chen01a67862011-10-14 00:42:25 +000034#include "lldb/Breakpoint/Watchpoint.h"
Jim Ingham40af72e2010-06-15 19:49:27 +000035#include "lldb/Interpreter/Args.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000036#include "lldb/Core/ArchSpec.h"
37#include "lldb/Core/Debugger.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000038#include "lldb/Host/ConnectionFileDescriptor.h"
Greg Clayton53239f02011-02-08 05:05:52 +000039#include "lldb/Host/FileSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000040#include "lldb/Core/Module.h"
Greg Clayton1f746072012-08-29 21:13:06 +000041#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000042#include "lldb/Core/PluginManager.h"
43#include "lldb/Core/State.h"
Greg Claytond451c1a2012-04-13 21:24:18 +000044#include "lldb/Core/StreamFile.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000045#include "lldb/Core/StreamString.h"
46#include "lldb/Core/Timer.h"
Greg Clayton70b57652011-05-15 01:25:55 +000047#include "lldb/Core/Value.h"
Zachary Turner39de3112014-09-09 20:54:56 +000048#include "lldb/Host/HostThread.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000049#include "lldb/Host/StringConvert.h"
Jason Molendad1fae142012-09-29 08:03:33 +000050#include "lldb/Host/Symbols.h"
Zachary Turner39de3112014-09-09 20:54:56 +000051#include "lldb/Host/ThreadLauncher.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000052#include "lldb/Host/TimeValue.h"
Greg Clayton02686b82012-10-15 22:42:16 +000053#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton1d19a2f2012-10-19 22:22:57 +000054#include "lldb/Interpreter/CommandObject.h"
55#include "lldb/Interpreter/CommandObjectMultiword.h"
Greg Clayton02686b82012-10-15 22:42:16 +000056#include "lldb/Interpreter/CommandReturnObject.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000057#include "lldb/Interpreter/OptionValueProperties.h"
58#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 Claytonc982c762010-07-09 20:39:50 +0000377 m_last_stop_packet (),
Greg Clayton09c3e3d2011-12-06 04:51:14 +0000378 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000379 m_register_info (),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000380 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
Jim Ingham455fa5c2012-11-01 01:15:33 +0000381 m_async_thread_state_mutex(Mutex::eMutexTypeRecursive),
Greg Clayton9e920902012-04-10 02:25:43 +0000382 m_thread_ids (),
Greg Clayton71fc2a32011-02-12 06:28:37 +0000383 m_continue_c_tids (),
384 m_continue_C_tids (),
385 m_continue_s_tids (),
386 m_continue_S_tids (),
Jason Molenda6076bf42014-05-06 04:34:52 +0000387 m_max_memory_size (0),
388 m_remote_stub_max_memory_size (0),
Greg Clayton4116e932012-05-15 02:33:01 +0000389 m_addr_to_mmap_size (),
390 m_thread_create_bp_sp (),
Jim Ingham43c555d2012-07-04 00:35:43 +0000391 m_waiting_for_attach (false),
Jason Molenda5e8534e2012-10-03 01:29:34 +0000392 m_destroy_tried_resuming (false),
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000393 m_command_sp (),
Ewan Crawford78baa192015-05-13 09:18:18 +0000394 m_breakpoint_pc_offset (0),
395 m_initial_tid (LLDB_INVALID_THREAD_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000396{
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000397 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
398 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Inghamb1e2e842012-04-12 18:49:31 +0000399 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Greg Clayton7f982402013-07-15 22:54:20 +0000400 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
401 if (timeout_seconds > 0)
402 m_gdb_comm.SetPacketTimeout(timeout_seconds);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000403}
404
405//----------------------------------------------------------------------
406// Destructor
407//----------------------------------------------------------------------
408ProcessGDBRemote::~ProcessGDBRemote()
409{
410 // m_mach_process.UnregisterNotificationCallbacks (this);
411 Clear();
Greg Clayton1ed54f52011-10-01 00:45:15 +0000412 // We need to call finalize on the process before destroying ourselves
413 // to make sure all of the broadcaster cleanup goes as planned. If we
414 // destruct this class, then Process::~Process() might have problems
415 // trying to fully destroy the broadcaster.
416 Finalize();
Jim Ingham455fa5c2012-11-01 01:15:33 +0000417
418 // The general Finalize is going to try to destroy the process and that SHOULD
419 // shut down the async thread. However, if we don't kill it it will get stranded and
420 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
421 StopAsyncThread();
422 KillDebugserverProcess();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000423}
424
425//----------------------------------------------------------------------
426// PluginInterface
427//----------------------------------------------------------------------
Greg Clayton57abc5d2013-05-10 21:47:16 +0000428ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000429ProcessGDBRemote::GetPluginName()
430{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000431 return GetPluginNameStatic();
432}
433
434uint32_t
435ProcessGDBRemote::GetPluginVersion()
436{
437 return 1;
438}
439
Greg Claytonef8180a2013-10-15 00:14:28 +0000440bool
441ProcessGDBRemote::ParsePythonTargetDefinition(const FileSpec &target_definition_fspec)
442{
443 ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
444 Error error;
Zachary Turner0641ca12015-03-17 20:04:04 +0000445 StructuredData::ObjectSP module_object_sp(interpreter->LoadPluginModule(target_definition_fspec, error));
Greg Claytonef8180a2013-10-15 00:14:28 +0000446 if (module_object_sp)
447 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000448 StructuredData::DictionarySP target_definition_sp(
449 interpreter->GetDynamicSettings(module_object_sp, &GetTarget(), "gdb-server-target-definition", error));
Greg Claytonef8180a2013-10-15 00:14:28 +0000450
Zachary Turner0641ca12015-03-17 20:04:04 +0000451 if (target_definition_sp)
Greg Claytonef8180a2013-10-15 00:14:28 +0000452 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000453 StructuredData::ObjectSP target_object(target_definition_sp->GetValueForKey("host-info"));
454 if (target_object)
Greg Clayton312bcbe2013-10-17 01:10:23 +0000455 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000456 if (auto host_info_dict = target_object->GetAsDictionary())
Greg Clayton312bcbe2013-10-17 01:10:23 +0000457 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000458 StructuredData::ObjectSP triple_value = host_info_dict->GetValueForKey("triple");
459 if (auto triple_string_value = triple_value->GetAsString())
460 {
461 std::string triple_string = triple_string_value->GetValue();
462 ArchSpec host_arch(triple_string.c_str());
463 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture()))
464 {
465 GetTarget().SetArchitecture(host_arch);
466 }
467 }
Greg Clayton312bcbe2013-10-17 01:10:23 +0000468 }
Greg Clayton312bcbe2013-10-17 01:10:23 +0000469 }
Zachary Turner0641ca12015-03-17 20:04:04 +0000470 m_breakpoint_pc_offset = 0;
471 StructuredData::ObjectSP breakpoint_pc_offset_value = target_definition_sp->GetValueForKey("breakpoint-pc-offset");
472 if (breakpoint_pc_offset_value)
473 {
474 if (auto breakpoint_pc_int_value = breakpoint_pc_offset_value->GetAsInteger())
475 m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
476 }
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000477
Zachary Turner0641ca12015-03-17 20:04:04 +0000478 if (m_register_info.SetRegisterInfo(*target_definition_sp, GetTarget().GetArchitecture().GetByteOrder()) > 0)
Greg Claytonef8180a2013-10-15 00:14:28 +0000479 {
480 return true;
481 }
482 }
483 }
484 return false;
485}
486
487
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000488void
Greg Clayton513c26c2011-01-29 07:10:55 +0000489ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000490{
Greg Clayton513c26c2011-01-29 07:10:55 +0000491 if (!force && m_register_info.GetNumRegisters() > 0)
492 return;
493
494 char packet[128];
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000495 m_register_info.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000496 uint32_t reg_offset = 0;
497 uint32_t reg_num = 0;
Greg Clayton23f59502012-07-17 03:23:13 +0000498 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Greg Clayton576d8832011-03-22 04:00:09 +0000499 response_type == StringExtractorGDBRemote::eResponse;
500 ++reg_num)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000501 {
Greg Clayton513c26c2011-01-29 07:10:55 +0000502 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
Andy Gibbsa297a972013-06-19 19:04:53 +0000503 assert (packet_len < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000504 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000505 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000506 {
Greg Clayton576d8832011-03-22 04:00:09 +0000507 response_type = response.GetResponseType();
508 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000509 {
510 std::string name;
511 std::string value;
512 ConstString reg_name;
513 ConstString alt_name;
514 ConstString set_name;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000515 std::vector<uint32_t> value_regs;
516 std::vector<uint32_t> invalidate_regs;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000517 RegisterInfo reg_info = { NULL, // Name
518 NULL, // Alt name
519 0, // byte size
520 reg_offset, // offset
521 eEncodingUint, // encoding
522 eFormatHex, // formate
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000523 {
524 LLDB_INVALID_REGNUM, // GCC reg num
525 LLDB_INVALID_REGNUM, // DWARF reg num
526 LLDB_INVALID_REGNUM, // generic reg num
Jason Molendafbcb7f22010-09-10 07:49:16 +0000527 reg_num, // GDB reg num
528 reg_num // native register number
Greg Clayton435d85a2012-02-29 19:27:27 +0000529 },
530 NULL,
531 NULL
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000532 };
533
534 while (response.GetNameColonValue(name, value))
535 {
536 if (name.compare("name") == 0)
537 {
538 reg_name.SetCString(value.c_str());
539 }
540 else if (name.compare("alt-name") == 0)
541 {
542 alt_name.SetCString(value.c_str());
543 }
544 else if (name.compare("bitsize") == 0)
545 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000546 reg_info.byte_size = StringConvert::ToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000547 }
548 else if (name.compare("offset") == 0)
549 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000550 uint32_t offset = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda743e86a2010-06-11 23:44:18 +0000551 if (reg_offset != offset)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000552 {
553 reg_offset = offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000554 }
555 }
556 else if (name.compare("encoding") == 0)
557 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000558 const Encoding encoding = Args::StringToEncoding (value.c_str());
559 if (encoding != eEncodingInvalid)
560 reg_info.encoding = encoding;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000561 }
562 else if (name.compare("format") == 0)
563 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000564 Format format = eFormatInvalid;
565 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
566 reg_info.format = format;
567 else if (value.compare("binary") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000568 reg_info.format = eFormatBinary;
569 else if (value.compare("decimal") == 0)
570 reg_info.format = eFormatDecimal;
571 else if (value.compare("hex") == 0)
572 reg_info.format = eFormatHex;
573 else if (value.compare("float") == 0)
574 reg_info.format = eFormatFloat;
575 else if (value.compare("vector-sint8") == 0)
576 reg_info.format = eFormatVectorOfSInt8;
577 else if (value.compare("vector-uint8") == 0)
578 reg_info.format = eFormatVectorOfUInt8;
579 else if (value.compare("vector-sint16") == 0)
580 reg_info.format = eFormatVectorOfSInt16;
581 else if (value.compare("vector-uint16") == 0)
582 reg_info.format = eFormatVectorOfUInt16;
583 else if (value.compare("vector-sint32") == 0)
584 reg_info.format = eFormatVectorOfSInt32;
585 else if (value.compare("vector-uint32") == 0)
586 reg_info.format = eFormatVectorOfUInt32;
587 else if (value.compare("vector-float32") == 0)
588 reg_info.format = eFormatVectorOfFloat32;
589 else if (value.compare("vector-uint128") == 0)
590 reg_info.format = eFormatVectorOfUInt128;
591 }
592 else if (name.compare("set") == 0)
593 {
594 set_name.SetCString(value.c_str());
595 }
596 else if (name.compare("gcc") == 0)
597 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000598 reg_info.kinds[eRegisterKindGCC] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000599 }
600 else if (name.compare("dwarf") == 0)
601 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000602 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000603 }
604 else if (name.compare("generic") == 0)
605 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000606 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000607 }
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000608 else if (name.compare("container-regs") == 0)
609 {
610 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
611 value_pair.second = value;
612 do
613 {
614 value_pair = value_pair.second.split(',');
615 if (!value_pair.first.empty())
616 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000617 uint32_t reg = StringConvert::ToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
Greg Clayton0ba20242013-01-21 23:32:42 +0000618 if (reg != LLDB_INVALID_REGNUM)
619 value_regs.push_back (reg);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000620 }
621 } while (!value_pair.second.empty());
622 }
623 else if (name.compare("invalidate-regs") == 0)
624 {
625 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
626 value_pair.second = value;
627 do
628 {
629 value_pair = value_pair.second.split(',');
630 if (!value_pair.first.empty())
631 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000632 uint32_t reg = StringConvert::ToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
Greg Clayton0ba20242013-01-21 23:32:42 +0000633 if (reg != LLDB_INVALID_REGNUM)
634 invalidate_regs.push_back (reg);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000635 }
636 } while (!value_pair.second.empty());
637 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000638 }
639
Jason Molenda743e86a2010-06-11 23:44:18 +0000640 reg_info.byte_offset = reg_offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000641 assert (reg_info.byte_size != 0);
642 reg_offset += reg_info.byte_size;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000643 if (!value_regs.empty())
644 {
645 value_regs.push_back(LLDB_INVALID_REGNUM);
646 reg_info.value_regs = value_regs.data();
647 }
648 if (!invalidate_regs.empty())
649 {
650 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
651 reg_info.invalidate_regs = invalidate_regs.data();
652 }
653
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000654 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
655 }
Todd Fiala1a634402014-01-08 07:52:40 +0000656 else
657 {
658 break; // ensure exit before reg_num is incremented
659 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000660 }
661 else
662 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000663 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000664 }
665 }
666
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000667 // Check if qHostInfo specified a specific packet timeout for this connection.
668 // If so then lets update our setting so the user knows what the timeout is
669 // and can see it.
670 const uint32_t host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
671 if (host_packet_timeout)
672 {
673 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout);
674 }
675
676
Greg Claytonef8180a2013-10-15 00:14:28 +0000677 if (reg_num == 0)
678 {
Colin Rileyc3c95b22015-04-16 15:51:33 +0000679 // try to extract information from servers target.xml
Aidan Doddsc0c83852015-05-08 09:36:31 +0000680 if (GetGDBServerRegisterInfo ())
Colin Rileyc3c95b22015-04-16 15:51:33 +0000681 return;
682
Greg Claytonef8180a2013-10-15 00:14:28 +0000683 FileSpec target_definition_fspec = GetGlobalPluginProperties()->GetTargetDefinitionFile ();
Greg Clayton312bcbe2013-10-17 01:10:23 +0000684
685 if (target_definition_fspec)
Greg Claytonef8180a2013-10-15 00:14:28 +0000686 {
Greg Clayton312bcbe2013-10-17 01:10:23 +0000687 // See if we can get register definitions from a python file
688 if (ParsePythonTargetDefinition (target_definition_fspec))
689 return;
Greg Claytonef8180a2013-10-15 00:14:28 +0000690 }
691 }
692
Johnny Chen2fa9de12012-05-14 18:44:23 +0000693 // We didn't get anything if the accumulated reg_num is zero. See if we are
694 // debugging ARM and fill with a hard coded register set until we can get an
695 // updated debugserver down on the devices.
696 // On the other hand, if the accumulated reg_num is positive, see if we can
697 // add composite registers to the existing primordial ones.
698 bool from_scratch = (reg_num == 0);
699
700 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000701 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
702 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
703
704 // Use the process' architecture instead of the host arch, if available
705 ArchSpec remote_arch;
706 if (remote_process_arch.IsValid ())
707 remote_arch = remote_process_arch;
708 else
709 remote_arch = remote_host_arch;
710
Johnny Chen2fa9de12012-05-14 18:44:23 +0000711 if (!target_arch.IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000712 {
Johnny Chen2fa9de12012-05-14 18:44:23 +0000713 if (remote_arch.IsValid()
714 && remote_arch.GetMachine() == llvm::Triple::arm
715 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
716 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000717 }
Johnny Chen2fa9de12012-05-14 18:44:23 +0000718 else if (target_arch.GetMachine() == llvm::Triple::arm)
719 {
720 m_register_info.HardcodeARMRegisters(from_scratch);
721 }
722
723 // At this point, we can finalize our register info.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000724 m_register_info.Finalize ();
725}
726
727Error
728ProcessGDBRemote::WillLaunch (Module* module)
729{
730 return WillLaunchOrAttach ();
731}
732
733Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000734ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000735{
736 return WillLaunchOrAttach ();
737}
738
739Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000740ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000741{
742 return WillLaunchOrAttach ();
743}
744
745Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000746ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +0000747{
Todd Fialaaf245d12014-06-30 21:05:18 +0000748 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Claytonb766a732011-02-04 01:58:07 +0000749 Error error (WillLaunchOrAttach ());
750
751 if (error.Fail())
752 return error;
753
Greg Clayton2289fa42011-04-30 01:09:13 +0000754 error = ConnectToDebugserver (remote_url);
Greg Claytonb766a732011-02-04 01:58:07 +0000755
756 if (error.Fail())
757 return error;
758 StartAsyncThread ();
759
Greg Claytonc574ede2011-03-10 02:26:48 +0000760 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonb766a732011-02-04 01:58:07 +0000761 if (pid == LLDB_INVALID_PROCESS_ID)
762 {
763 // We don't have a valid process ID, so note that we are connected
764 // and could now request to launch or attach, or get remote process
765 // listings...
766 SetPrivateState (eStateConnected);
767 }
768 else
769 {
770 // We have a valid process
771 SetID (pid);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000772 GetThreadList();
Ewan Crawford78baa192015-05-13 09:18:18 +0000773 if (m_gdb_comm.GetStopReply(m_last_stop_packet))
Greg Claytonb766a732011-02-04 01:58:07 +0000774 {
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
Greg Claytondd0e5a52011-06-02 22:22:38 +0000792 const StateType state = SetThreadStopInfo (m_last_stop_packet);
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 Crawford78baa192015-05-13 09:18:18 +00001061 if (m_gdb_comm.GetStopReply(m_last_stop_packet))
Greg Clayton71337622011-02-24 22:24:29 +00001062 {
Ewan Crawford78baa192015-05-13 09:18:18 +00001063
1064 // '?' Packets must be handled differently in non-stop mode
1065 if (GetTarget().GetNonStopModeEnabled())
1066 HandleStopReplySequence();
1067
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001068 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
1069
1070 if (process_arch.IsValid())
Jason Molendac62bd7b2013-12-21 05:20:36 +00001071 {
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001072 m_target.MergeArchitecture(process_arch);
1073 }
1074 else
1075 {
1076 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
1077 if (host_arch.IsValid())
1078 m_target.MergeArchitecture(host_arch);
Carlo Kok74389122013-10-14 07:09:13 +00001079 }
1080
Greg Claytondd0e5a52011-06-02 22:22:38 +00001081 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Clayton71337622011-02-24 22:24:29 +00001082
1083 if (!disable_stdio)
1084 {
1085 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Claytonee95ed52011-11-17 22:14:31 +00001086 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Clayton71337622011-02-24 22:24:29 +00001087 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001088 }
1089 }
Greg Claytonc235ac72011-08-09 05:20:29 +00001090 else
1091 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001092 if (log)
1093 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytonc235ac72011-08-09 05:20:29 +00001094 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001095 }
1096 else
1097 {
1098 // Set our user ID to an invalid process ID.
1099 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton982c9762011-11-03 21:22:33 +00001100 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
1101 exe_module->GetFileSpec().GetFilename().AsCString(),
1102 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001103 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001104 return error;
Greg Clayton4957bf62010-09-30 21:49:03 +00001105
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001106}
1107
1108
1109Error
Greg Claytonb766a732011-02-04 01:58:07 +00001110ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001111{
1112 Error error;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001113 // Only connect if we have a valid connect URL
Vince Harron1b5a74e2015-01-21 22:42:49 +00001114 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton00fe87b2013-12-05 22:58:22 +00001115
1116 if (connect_url && connect_url[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001117 {
Vince Harron1b5a74e2015-01-21 22:42:49 +00001118 if (log)
1119 log->Printf("ProcessGDBRemote::%s Connecting to %s", __FUNCTION__, connect_url);
Greg Clayton00fe87b2013-12-05 22:58:22 +00001120 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
1121 if (conn_ap.get())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001122 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001123 const uint32_t max_retry_count = 50;
1124 uint32_t retry_count = 0;
1125 while (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001126 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001127 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
1128 {
1129 m_gdb_comm.SetConnection (conn_ap.release());
1130 break;
1131 }
1132 else if (error.WasInterrupted())
1133 {
1134 // If we were interrupted, don't keep retrying.
1135 break;
1136 }
1137
1138 retry_count++;
1139
1140 if (retry_count >= max_retry_count)
1141 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001142
Greg Clayton00fe87b2013-12-05 22:58:22 +00001143 usleep (100000);
1144 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001145 }
1146 }
1147
1148 if (!m_gdb_comm.IsConnected())
1149 {
1150 if (error.Success())
1151 error.SetErrorString("not connected to remote gdb server");
1152 return error;
1153 }
1154
Greg Clayton32e0a752011-03-30 18:16:51 +00001155 // We always seem to be able to open a connection to a local port
1156 // so we need to make sure we can then send data to it. If we can't
1157 // then we aren't actually connected to anything, so try and do the
1158 // handshake with the remote GDB server and make sure that goes
1159 // alright.
Greg Claytonfb909312013-11-23 01:58:15 +00001160 if (!m_gdb_comm.HandshakeWithServer (&error))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001161 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001162 m_gdb_comm.Disconnect();
1163 if (error.Success())
1164 error.SetErrorString("not connected to remote gdb server");
1165 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001166 }
Ewan Crawford78baa192015-05-13 09:18:18 +00001167
1168 // Send $QNonStop:1 packet on startup if required
1169 if (GetTarget().GetNonStopModeEnabled())
1170 m_gdb_comm.SetNonStopMode(true);
1171
Greg Clayton32e0a752011-03-30 18:16:51 +00001172 m_gdb_comm.GetThreadSuffixSupported ();
Greg Clayton44633992012-04-10 03:22:03 +00001173 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001174 m_gdb_comm.GetHostInfo ();
1175 m_gdb_comm.GetVContSupported ('c');
Jim Inghamcd16df92012-07-20 21:37:13 +00001176 m_gdb_comm.GetVAttachOrWaitSupported();
Ewan Crawford78baa192015-05-13 09:18:18 +00001177
1178 // Ask the remote server for the default thread id
1179 if (GetTarget().GetNonStopModeEnabled())
1180 m_gdb_comm.GetDefaultThreadId(m_initial_tid);
1181
1182
Jim Ingham03afad82012-07-02 05:40:07 +00001183 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1184 for (size_t idx = 0; idx < num_cmds; idx++)
1185 {
1186 StringExtractorGDBRemote response;
Jim Ingham03afad82012-07-02 05:40:07 +00001187 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1188 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001189 return error;
1190}
1191
1192void
Jim Inghambb006ce2014-08-02 00:33:35 +00001193ProcessGDBRemote::DidLaunchOrAttach (ArchSpec& process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001194{
Greg Clayton5160ce52013-03-27 23:08:40 +00001195 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001196 if (log)
1197 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton93d3c8332011-02-16 04:46:07 +00001198 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001199 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001200 BuildDynamicRegisterInfo (false);
Greg Clayton3af9ea52010-11-18 05:57:03 +00001201
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001202 // See if the GDB server supports the qHostInfo information
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001203
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001204
1205 // See if the GDB server supports the qProcessInfo packet, if so
1206 // prefer that over the Host information as it will be more specific
1207 // to our process.
1208
Todd Fiala75f47c32014-10-11 21:42:09 +00001209 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1210 if (remote_process_arch.IsValid())
1211 {
1212 process_arch = remote_process_arch;
1213 if (log)
1214 log->Printf ("ProcessGDBRemote::%s gdb-remote had process architecture, using %s %s",
1215 __FUNCTION__,
1216 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1217 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1218 }
Jim Inghambb006ce2014-08-02 00:33:35 +00001219 else
Todd Fiala75f47c32014-10-11 21:42:09 +00001220 {
Jim Inghambb006ce2014-08-02 00:33:35 +00001221 process_arch = m_gdb_comm.GetHostArchitecture();
Todd Fiala75f47c32014-10-11 21:42:09 +00001222 if (log)
1223 log->Printf ("ProcessGDBRemote::%s gdb-remote did not have process architecture, using gdb-remote host architecture %s %s",
1224 __FUNCTION__,
1225 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1226 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1227 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001228
Jim Inghambb006ce2014-08-02 00:33:35 +00001229 if (process_arch.IsValid())
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001230 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001231 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Greg Claytond314e812011-03-23 00:09:55 +00001232 if (target_arch.IsValid())
1233 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001234 if (log)
1235 log->Printf ("ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1236 __FUNCTION__,
1237 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1238 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
1239
1240 // If the remote host is ARM and we have apple as the vendor, then
Greg Claytond314e812011-03-23 00:09:55 +00001241 // ARM executables and shared libraries can have mixed ARM architectures.
1242 // You can have an armv6 executable, and if the host is armv7, then the
1243 // system will load the best possible architecture for all shared libraries
1244 // it has, so we really need to take the remote host architecture as our
1245 // defacto architecture in this case.
1246
Jim Inghambb006ce2014-08-02 00:33:35 +00001247 if (process_arch.GetMachine() == llvm::Triple::arm &&
1248 process_arch.GetTriple().getVendor() == llvm::Triple::Apple)
Greg Claytond314e812011-03-23 00:09:55 +00001249 {
Jason Molenda921c01b2014-08-03 21:42:52 +00001250 GetTarget().SetArchitecture (process_arch);
Todd Fiala75f47c32014-10-11 21:42:09 +00001251 if (log)
1252 log->Printf ("ProcessGDBRemote::%s remote process is ARM/Apple, setting target arch to %s %s",
1253 __FUNCTION__,
1254 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1255 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001256 }
1257 else
1258 {
1259 // Fill in what is missing in the triple
Jim Inghambb006ce2014-08-02 00:33:35 +00001260 const llvm::Triple &remote_triple = process_arch.GetTriple();
Tamas Berghammere724af12015-03-13 10:32:37 +00001261 llvm::Triple new_target_triple = target_arch.GetTriple();
1262 if (new_target_triple.getVendorName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001263 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001264 new_target_triple.setVendor (remote_triple.getVendor());
Greg Claytond314e812011-03-23 00:09:55 +00001265
Tamas Berghammere724af12015-03-13 10:32:37 +00001266 if (new_target_triple.getOSName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001267 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001268 new_target_triple.setOS (remote_triple.getOS());
Greg Claytond314e812011-03-23 00:09:55 +00001269
Tamas Berghammere724af12015-03-13 10:32:37 +00001270 if (new_target_triple.getEnvironmentName().size() == 0)
1271 new_target_triple.setEnvironment (remote_triple.getEnvironment());
Greg Clayton70b57652011-05-15 01:25:55 +00001272 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001273
Tamas Berghammere724af12015-03-13 10:32:37 +00001274 ArchSpec new_target_arch = target_arch;
1275 new_target_arch.SetTriple(new_target_triple);
1276 GetTarget().SetArchitecture(new_target_arch);
1277 }
Greg Claytond314e812011-03-23 00:09:55 +00001278 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001279
1280 if (log)
1281 log->Printf ("ProcessGDBRemote::%s final target arch after adjustments for remote architecture: %s %s",
1282 __FUNCTION__,
1283 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1284 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001285 }
1286 else
1287 {
1288 // The target doesn't have a valid architecture yet, set it from
1289 // the architecture we got from the remote GDB server
Jason Molenda921c01b2014-08-03 21:42:52 +00001290 GetTarget().SetArchitecture (process_arch);
Greg Claytond314e812011-03-23 00:09:55 +00001291 }
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001292 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001293 }
1294}
1295
1296void
1297ProcessGDBRemote::DidLaunch ()
1298{
Jim Inghambb006ce2014-08-02 00:33:35 +00001299 ArchSpec process_arch;
1300 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001301}
1302
1303Error
Han Ming Ong84647042012-02-25 01:07:38 +00001304ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1305{
Todd Fiala75f47c32014-10-11 21:42:09 +00001306 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001307 Error error;
Todd Fiala75f47c32014-10-11 21:42:09 +00001308
1309 if (log)
1310 log->Printf ("ProcessGDBRemote::%s()", __FUNCTION__);
1311
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001312 // Clear out and clean up from any current state
1313 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001314 if (attach_pid != LLDB_INVALID_PROCESS_ID)
1315 {
Greg Clayton71337622011-02-24 22:24:29 +00001316 // Make sure we aren't already connected?
1317 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001318 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001319 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001320
1321 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001322 {
Greg Clayton71337622011-02-24 22:24:29 +00001323 const char *error_string = error.AsCString();
1324 if (error_string == NULL)
1325 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1326
1327 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001328 }
Greg Clayton71337622011-02-24 22:24:29 +00001329 }
1330
1331 if (error.Success())
1332 {
Jim Ingham106d0282014-06-25 02:32:56 +00001333 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
Todd Fiala75f47c32014-10-11 21:42:09 +00001334
Greg Clayton71337622011-02-24 22:24:29 +00001335 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001336 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Greg Clayton3b608422011-11-19 02:11:30 +00001337 SetID (attach_pid);
Greg Clayton71337622011-02-24 22:24:29 +00001338 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001339 }
1340 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001341
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001342 return error;
1343}
1344
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001345Error
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001346ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001347{
1348 Error error;
1349 // Clear out and clean up from any current state
1350 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001351
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001352 if (process_name && process_name[0])
1353 {
Greg Clayton71337622011-02-24 22:24:29 +00001354 // Make sure we aren't already connected?
1355 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001356 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001357 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001358
Greg Clayton71337622011-02-24 22:24:29 +00001359 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001360 {
Greg Clayton71337622011-02-24 22:24:29 +00001361 const char *error_string = error.AsCString();
1362 if (error_string == NULL)
1363 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001364
Greg Clayton71337622011-02-24 22:24:29 +00001365 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001366 }
Greg Clayton71337622011-02-24 22:24:29 +00001367 }
1368
1369 if (error.Success())
1370 {
1371 StreamString packet;
1372
Jim Ingham106d0282014-06-25 02:32:56 +00001373 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1374
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001375 if (attach_info.GetWaitForLaunch())
Jim Inghamcd16df92012-07-20 21:37:13 +00001376 {
1377 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1378 {
1379 packet.PutCString ("vAttachWait");
1380 }
1381 else
1382 {
1383 if (attach_info.GetIgnoreExisting())
1384 packet.PutCString("vAttachWait");
1385 else
1386 packet.PutCString ("vAttachOrWait");
1387 }
1388 }
Greg Clayton71337622011-02-24 22:24:29 +00001389 else
1390 packet.PutCString("vAttachName");
1391 packet.PutChar(';');
1392 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1393
1394 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1395
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001396 }
1397 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001398 return error;
1399}
1400
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001401
Greg Claytonfbb76342013-11-20 21:07:01 +00001402bool
1403ProcessGDBRemote::SetExitStatus (int exit_status, const char *cstr)
1404{
1405 m_gdb_comm.Disconnect();
1406 return Process::SetExitStatus (exit_status, cstr);
1407}
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 {
2094 stop_info_sp->SetDescription (description.c_str());
Greg Clayton3418c852011-08-10 02:10:13 +00002095 }
Greg Claytona658fd22011-06-04 01:26:29 +00002096 else
2097 {
Greg Clayton160c9d82013-05-01 21:54:04 +00002098 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00002099 }
2100 }
2101 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002102 }
2103 return eStateStopped;
2104 }
2105 break;
2106
2107 case 'W':
Todd Fialaff6131a2014-05-19 04:57:23 +00002108 case 'X':
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002109 // process exited
2110 return eStateExited;
2111
2112 default:
2113 break;
2114 }
2115 return eStateInvalid;
2116}
2117
2118void
2119ProcessGDBRemote::RefreshStateAfterStop ()
2120{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002121 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00002122 m_thread_ids.clear();
2123 // Set the thread stop info. It might have a "threads" key whose value is
2124 // a list of all thread IDs in the current process, so m_thread_ids might
2125 // get set.
2126 SetThreadStopInfo (m_last_stop_packet);
2127 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2128 if (m_thread_ids.empty())
2129 {
2130 // No, we need to fetch the thread list manually
2131 UpdateThreadIDList();
2132 }
2133
Ewan Crawford78baa192015-05-13 09:18:18 +00002134 // If we have queried for a default thread id
2135 if (m_initial_tid != LLDB_INVALID_THREAD_ID)
2136 {
2137 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2138 m_initial_tid = LLDB_INVALID_THREAD_ID;
2139 }
2140
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002141 // Let all threads recover from stopping and do any clean up based
2142 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002143 m_thread_list_real.RefreshStateAfterStop();
Greg Clayton9e920902012-04-10 02:25:43 +00002144
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002145}
2146
2147Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002148ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002149{
2150 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002151
Greg Clayton6ed95942011-01-22 07:12:45 +00002152 bool timed_out = false;
2153 Mutex::Locker locker;
Greg Clayton513c26c2011-01-29 07:10:55 +00002154
2155 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002156 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002157 // We are being asked to halt during an attach. We need to just close
2158 // our file handle and debugserver will go away, and we can be done...
2159 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00002160 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002161 else
2162 {
Greg Clayton2687cd12012-03-29 01:55:41 +00002163 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton513c26c2011-01-29 07:10:55 +00002164 {
2165 if (timed_out)
2166 error.SetErrorString("timed out sending interrupt packet");
2167 else
2168 error.SetErrorString("unknown error sending interrupt packet");
2169 }
Greg Clayton2687cd12012-03-29 01:55:41 +00002170
2171 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton513c26c2011-01-29 07:10:55 +00002172 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002173 return error;
2174}
2175
2176Error
Jim Inghamacff8952013-05-02 00:27:30 +00002177ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002178{
2179 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002180 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00002181 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00002182 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2183
Jim Inghamacff8952013-05-02 00:27:30 +00002184 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002185 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002186 {
Jim Inghamacff8952013-05-02 00:27:30 +00002187 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002188 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
2189 else
Jim Inghamacff8952013-05-02 00:27:30 +00002190 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00002191 }
Jim Inghamacff8952013-05-02 00:27:30 +00002192
2193 if (!error.Success())
2194 return error;
2195
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002196 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00002197 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002198
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002199 SetPrivateState (eStateDetached);
2200 ResumePrivateStateThread();
2201
2202 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00002203 return error;
2204}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002205
Jim Ingham43c555d2012-07-04 00:35:43 +00002206
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002207Error
2208ProcessGDBRemote::DoDestroy ()
2209{
2210 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002211 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002212 if (log)
2213 log->Printf ("ProcessGDBRemote::DoDestroy()");
2214
Jim Ingham43c555d2012-07-04 00:35:43 +00002215 // There is a bug in older iOS debugservers where they don't shut down the process
2216 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
2217 // this can cause problems with restarting. So we check to see if any of our threads are stopped
2218 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
2219 // destroy it again.
2220 //
2221 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
2222 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
2223 // the debugservers with this bug are equal. There really should be a better way to test this!
2224 //
2225 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
2226 // get called here to destroy again and we're still at a breakpoint or exception, then we should
2227 // just do the straight-forward kill.
2228 //
2229 // And of course, if we weren't able to stop the process by the time we get here, it isn't
2230 // necessary (or helpful) to do any of this.
2231
2232 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
2233 {
2234 PlatformSP platform_sp = GetTarget().GetPlatform();
2235
2236 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2237 if (platform_sp
2238 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00002239 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00002240 {
2241 if (m_destroy_tried_resuming)
2242 {
2243 if (log)
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002244 log->PutCString ("ProcessGDBRemote::DoDestroy() - Tried resuming to destroy once already, not doing it again.");
Jim Ingham43c555d2012-07-04 00:35:43 +00002245 }
2246 else
2247 {
2248 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
2249 // but we really need it to happen here and it doesn't matter if we do it twice.
2250 m_thread_list.DiscardThreadPlans();
2251 DisableAllBreakpointSites();
2252
2253 bool stop_looks_like_crash = false;
2254 ThreadList &threads = GetThreadList();
2255
2256 {
Jim Ingham45350372012-09-11 00:08:52 +00002257 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002258
2259 size_t num_threads = threads.GetSize();
2260 for (size_t i = 0; i < num_threads; i++)
2261 {
2262 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002263 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002264 StopReason reason = eStopReasonInvalid;
2265 if (stop_info_sp)
2266 reason = stop_info_sp->GetStopReason();
2267 if (reason == eStopReasonBreakpoint
2268 || reason == eStopReasonException)
2269 {
2270 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002271 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
2272 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00002273 stop_info_sp->GetDescription());
2274 stop_looks_like_crash = true;
2275 break;
2276 }
2277 }
2278 }
2279
2280 if (stop_looks_like_crash)
2281 {
2282 if (log)
2283 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
2284 m_destroy_tried_resuming = true;
2285
2286 // If we are going to run again before killing, it would be good to suspend all the threads
2287 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
2288 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
2289 // have to run the risk of letting those threads proceed a bit.
2290
2291 {
Jim Ingham45350372012-09-11 00:08:52 +00002292 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002293
2294 size_t num_threads = threads.GetSize();
2295 for (size_t i = 0; i < num_threads; i++)
2296 {
2297 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002298 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002299 StopReason reason = eStopReasonInvalid;
2300 if (stop_info_sp)
2301 reason = stop_info_sp->GetStopReason();
2302 if (reason != eStopReasonBreakpoint
2303 && reason != eStopReasonException)
2304 {
2305 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002306 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
2307 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00002308 thread_sp->SetResumeState(eStateSuspended);
2309 }
2310 }
2311 }
2312 Resume ();
Jason Molendaede31932015-04-17 05:01:58 +00002313 return Destroy(false);
Jim Ingham43c555d2012-07-04 00:35:43 +00002314 }
2315 }
2316 }
2317 }
2318
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002319 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00002320 int exit_status = SIGABRT;
2321 std::string exit_string;
2322
Greg Clayton6ed95942011-01-22 07:12:45 +00002323 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002324 {
Jim Inghamaab78372011-10-28 01:11:35 +00002325 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00002326 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002327 StringExtractorGDBRemote response;
2328 bool send_async = true;
Tamas Berghammer912800c2015-02-24 10:23:39 +00002329 GDBRemoteCommunication::ScopedTimeout (m_gdb_comm, 3);
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002330
Greg Clayton3dedae12013-12-06 21:45:27 +00002331 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton513c26c2011-01-29 07:10:55 +00002332 {
2333 char packet_cmd = response.GetChar(0);
2334
2335 if (packet_cmd == 'W' || packet_cmd == 'X')
2336 {
Jim Inghameac0aa42014-02-21 22:36:11 +00002337#if defined(__APPLE__)
Jim Ingham9d67cc52014-02-21 22:35:29 +00002338 // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off
2339 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill
2340 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns
2341 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap
2342 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of
2343 // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2344 // Anyway, so call waitpid here to finally reap it.
2345 PlatformSP platform_sp(GetTarget().GetPlatform());
2346 if (platform_sp && platform_sp->IsHost())
2347 {
2348 int status;
2349 ::pid_t reap_pid;
2350 reap_pid = waitpid (GetID(), &status, WNOHANG);
2351 if (log)
2352 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2353 }
2354#endif
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002355 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002356 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00002357 exit_status = response.GetHexU8();
2358 }
2359 else
2360 {
2361 if (log)
2362 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2363 exit_string.assign("got unexpected response to k packet: ");
2364 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00002365 }
2366 }
2367 else
2368 {
Jim Inghambabfc382012-06-06 00:32:39 +00002369 if (log)
2370 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2371 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00002372 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002373 }
Jim Inghambabfc382012-06-06 00:32:39 +00002374 else
2375 {
2376 if (log)
Ed Masteb3a53332014-03-17 17:05:22 +00002377 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching");
Jim Inghamcfc09352012-07-27 23:57:19 +00002378 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00002379 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002380 }
Jim Inghambabfc382012-06-06 00:32:39 +00002381 else
2382 {
2383 // If we missed setting the exit status on the way out, do it here.
2384 // NB set exit status can be called multiple times, the first one sets the status.
2385 exit_string.assign("destroying when not connected to debugserver");
2386 }
2387
2388 SetExitStatus(exit_status, exit_string.c_str());
2389
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002390 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002391 KillDebugserverProcess ();
2392 return error;
2393}
2394
Greg Clayton8cda7f02013-05-21 21:55:59 +00002395void
2396ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2397{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00002398 Mutex::Locker locker (m_last_stop_packet_mutex);
Greg Clayton8cda7f02013-05-21 21:55:59 +00002399 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2400 if (did_exec)
2401 {
2402 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2403 if (log)
2404 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2405
2406 m_thread_list_real.Clear();
2407 m_thread_list.Clear();
2408 BuildDynamicRegisterInfo (true);
2409 m_gdb_comm.ResetDiscoverableSettings();
2410 }
2411 m_last_stop_packet = response;
2412}
2413
2414
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002415//------------------------------------------------------------------
2416// Process Queries
2417//------------------------------------------------------------------
2418
2419bool
2420ProcessGDBRemote::IsAlive ()
2421{
Greg Clayton10177aa2010-12-08 05:08:21 +00002422 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002423}
2424
2425addr_t
2426ProcessGDBRemote::GetImageInfoAddress()
2427{
Aidan Doddsc0c83852015-05-08 09:36:31 +00002428 // request the link map address via the $qShlibInfoAddr packet
2429 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2430
2431 // the loaded module list can also provides a link map address
2432 if (addr == LLDB_INVALID_ADDRESS)
2433 {
2434 GDBLoadedModuleInfoList list;
2435 if (GetLoadedModuleList (list).Success())
2436 addr = list.m_link_map;
2437 }
2438
2439 return addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002440}
2441
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002442//------------------------------------------------------------------
2443// Process Memory
2444//------------------------------------------------------------------
2445size_t
2446ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2447{
Jason Molenda6076bf42014-05-06 04:34:52 +00002448 GetMaxMemorySize ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002449 if (size > m_max_memory_size)
2450 {
2451 // Keep memory read sizes down to a sane limit. This function will be
2452 // called multiple times in order to complete the task by
2453 // lldb_private::Process so it is ok to do this.
2454 size = m_max_memory_size;
2455 }
2456
2457 char packet[64];
Jason Molenda6076bf42014-05-06 04:34:52 +00002458 int packet_len;
2459 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2460 if (binary_memory_read)
2461 {
2462 packet_len = ::snprintf (packet, sizeof(packet), "x0x%" PRIx64 ",0x%" PRIx64, (uint64_t)addr, (uint64_t)size);
2463 }
2464 else
2465 {
2466 packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
2467 }
Andy Gibbsa297a972013-06-19 19:04:53 +00002468 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002469 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002470 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002471 {
Greg Clayton576d8832011-03-22 04:00:09 +00002472 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002473 {
2474 error.Clear();
Jason Molenda6076bf42014-05-06 04:34:52 +00002475 if (binary_memory_read)
2476 {
2477 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any
2478 // 0x7d character escaping that was present in the packet
2479
2480 size_t data_received_size = response.GetBytesLeft();
2481 if (data_received_size > size)
2482 {
2483 // Don't write past the end of BUF if the remote debug server gave us too
2484 // much data for some reason.
2485 data_received_size = size;
2486 }
2487 memcpy (buf, response.GetStringRef().data(), data_received_size);
2488 return data_received_size;
2489 }
2490 else
2491 {
2492 return response.GetHexBytes(buf, size, '\xdd');
2493 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002494 }
Greg Clayton576d8832011-03-22 04:00:09 +00002495 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002496 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002497 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002498 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002499 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002500 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002501 }
2502 else
2503 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002504 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002505 }
2506 return 0;
2507}
2508
2509size_t
2510ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2511{
Jason Molenda6076bf42014-05-06 04:34:52 +00002512 GetMaxMemorySize ();
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002513 if (size > m_max_memory_size)
2514 {
2515 // Keep memory read sizes down to a sane limit. This function will be
2516 // called multiple times in order to complete the task by
2517 // lldb_private::Process so it is ok to do this.
2518 size = m_max_memory_size;
2519 }
2520
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002521 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00002522 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Clayton7fb56d02011-02-01 01:31:41 +00002523 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002524 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002525 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002526 {
Greg Clayton576d8832011-03-22 04:00:09 +00002527 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002528 {
2529 error.Clear();
2530 return size;
2531 }
Greg Clayton576d8832011-03-22 04:00:09 +00002532 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002533 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002534 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002535 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002536 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002537 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 +00002538 }
2539 else
2540 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002541 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002542 }
2543 return 0;
2544}
2545
2546lldb::addr_t
2547ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2548{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00002549 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_EXPRESSIONS));
Greg Clayton2a48f522011-05-14 01:50:35 +00002550 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2551
Greg Clayton70b57652011-05-15 01:25:55 +00002552 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton2a48f522011-05-14 01:50:35 +00002553 switch (supported)
2554 {
2555 case eLazyBoolCalculate:
2556 case eLazyBoolYes:
2557 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2558 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2559 return allocated_addr;
2560
2561 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002562 // Call mmap() to create memory in the inferior..
2563 unsigned prot = 0;
2564 if (permissions & lldb::ePermissionsReadable)
2565 prot |= eMmapProtRead;
2566 if (permissions & lldb::ePermissionsWritable)
2567 prot |= eMmapProtWrite;
2568 if (permissions & lldb::ePermissionsExecutable)
2569 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00002570
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002571 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2572 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2573 m_addr_to_mmap_size[allocated_addr] = size;
2574 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002575 {
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002576 allocated_addr = LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00002577 if (log)
2578 log->Printf ("ProcessGDBRemote::%s no direct stub support for memory allocation, and InferiorCallMmap also failed - is stub missing register context save/restore capability?", __FUNCTION__);
2579 }
Greg Clayton2a48f522011-05-14 01:50:35 +00002580 break;
2581 }
2582
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002583 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00002584 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002585 else
2586 error.Clear();
2587 return allocated_addr;
2588}
2589
2590Error
Greg Clayton46fb5582011-11-18 07:03:08 +00002591ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2592 MemoryRegionInfo &region_info)
2593{
2594
2595 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2596 return error;
2597}
2598
2599Error
Johnny Chen64637202012-05-23 21:09:52 +00002600ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2601{
2602
2603 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2604 return error;
2605}
2606
2607Error
Enrico Granataf04a2192012-07-13 23:18:48 +00002608ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2609{
2610 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2611 return error;
2612}
2613
2614Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002615ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2616{
2617 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00002618 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2619
2620 switch (supported)
2621 {
2622 case eLazyBoolCalculate:
2623 // We should never be deallocating memory without allocating memory
2624 // first so we should never get eLazyBoolCalculate
2625 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2626 break;
2627
2628 case eLazyBoolYes:
2629 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00002630 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002631 break;
2632
2633 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002634 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00002635 {
2636 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002637 if (pos != m_addr_to_mmap_size.end() &&
2638 InferiorCallMunmap(this, addr, pos->second))
2639 m_addr_to_mmap_size.erase (pos);
2640 else
Daniel Malead01b2952012-11-29 21:49:15 +00002641 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002642 }
2643 break;
2644 }
2645
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002646 return error;
2647}
2648
2649
2650//------------------------------------------------------------------
2651// Process STDIO
2652//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002653size_t
2654ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2655{
2656 if (m_stdio_communication.IsConnected())
2657 {
2658 ConnectionStatus status;
2659 m_stdio_communication.Write(src, src_len, status, NULL);
2660 }
Vince Harrondf3f00f2015-02-10 21:09:04 +00002661 else if (m_stdin_forward)
Vince Harrone0be4252015-02-06 18:32:57 +00002662 {
2663 m_gdb_comm.SendStdinNotification(src, src_len);
2664 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002665 return 0;
2666}
2667
2668Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002669ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002670{
2671 Error error;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002672 assert(bp_site != NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002673
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002674 // Get logging info
2675 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002676 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002677
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002678 // Get the breakpoint address
2679 const addr_t addr = bp_site->GetLoadAddress();
2680
2681 // Log that a breakpoint was requested
2682 if (log)
2683 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
2684
2685 // Breakpoint already exists and is enabled
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002686 if (bp_site->IsEnabled())
2687 {
2688 if (log)
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002689 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 +00002690 return error;
2691 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002692
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002693 // Get the software breakpoint trap opcode size
2694 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2695
2696 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
2697 // is supported by the remote stub. These are set to true by default, and later set to false
2698 // only after we receive an unimplemented response when sending a breakpoint packet. This means
2699 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
2700 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
2701 // indicates if the user specifically asked for hardware breakpoints. If true then we will
2702 // skip over software breakpoints.
2703 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
2704 {
2705 // Try to send off a software breakpoint packet ($Z0)
2706 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002707 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002708 // The breakpoint was placed successfully
2709 bp_site->SetEnabled(true);
2710 bp_site->SetType(BreakpointSite::eExternal);
Greg Claytoneb023e72013-10-11 19:48:25 +00002711 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002712 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002713
2714 // SendGDBStoppointTypePacket() will return an error if it was unable to set this
2715 // breakpoint. We need to differentiate between a error specific to placing this breakpoint
2716 // or if we have learned that this breakpoint type is unsupported. To do this, we
2717 // must test the support boolean for this breakpoint type to see if it now indicates that
2718 // this breakpoint type is unsupported. If they are still supported then we should return
2719 // with the error code. If they are now unsupported, then we would like to fall through
2720 // and try another form of breakpoint.
2721 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
2722 return error;
2723
2724 // We reach here when software breakpoints have been found to be unsupported. For future
2725 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
2726 // known not to be supported.
2727 if (log)
2728 log->Printf("Software breakpoints are unsupported");
2729
2730 // So we will fall through and try a hardware breakpoint
2731 }
2732
2733 // The process of setting a hardware breakpoint is much the same as above. We check the
2734 // supported boolean for this breakpoint type, and if it is thought to be supported then we
2735 // will try to set this breakpoint with a hardware breakpoint.
2736 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
2737 {
2738 // Try to send off a hardware breakpoint packet ($Z1)
2739 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002740 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002741 // The breakpoint was placed successfully
2742 bp_site->SetEnabled(true);
2743 bp_site->SetType(BreakpointSite::eHardware);
2744 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002745 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002746
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002747 // Check if the error was something other then an unsupported breakpoint type
2748 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
2749 {
2750 // Unable to set this hardware breakpoint
2751 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
2752 return error;
2753 }
2754
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002755 // We will reach here when the stub gives an unsupported response to a hardware breakpoint
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002756 if (log)
2757 log->Printf("Hardware breakpoints are unsupported");
2758
2759 // Finally we will falling through to a #trap style breakpoint
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002760 }
2761
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002762 // Don't fall through when hardware breakpoints were specifically requested
2763 if (bp_site->HardwareRequired())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002764 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002765 error.SetErrorString("hardware breakpoints are not supported");
2766 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002767 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002768
2769 // As a last resort we want to place a manual breakpoint. An instruction
2770 // is placed into the process memory using memory write packets.
2771 return EnableSoftwareBreakpoint(bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002772}
2773
2774Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002775ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002776{
2777 Error error;
2778 assert (bp_site != NULL);
2779 addr_t addr = bp_site->GetLoadAddress();
2780 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00002781 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002782 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002783 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002784
2785 if (bp_site->IsEnabled())
2786 {
2787 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2788
Greg Clayton8b82f082011-04-12 05:54:46 +00002789 BreakpointSite::Type bp_type = bp_site->GetType();
2790 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002791 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002792 case BreakpointSite::eSoftware:
2793 error = DisableSoftwareBreakpoint (bp_site);
2794 break;
2795
2796 case BreakpointSite::eHardware:
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002797 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00002798 error.SetErrorToGenericError();
2799 break;
2800
2801 case BreakpointSite::eExternal:
Jim Inghama04ef752014-03-07 11:18:02 +00002802 {
2803 GDBStoppointType stoppoint_type;
2804 if (bp_site->IsHardware())
2805 stoppoint_type = eBreakpointHardware;
2806 else
2807 stoppoint_type = eBreakpointSoftware;
2808
2809 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00002810 error.SetErrorToGenericError();
Jim Inghama04ef752014-03-07 11:18:02 +00002811 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002812 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002813 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002814 if (error.Success())
2815 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002816 }
2817 else
2818 {
2819 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002820 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 +00002821 return error;
2822 }
2823
2824 if (error.Success())
2825 error.SetErrorToGenericError();
2826 return error;
2827}
2828
Johnny Chen11309a32011-09-06 22:38:36 +00002829// Pre-requisite: wp != NULL.
2830static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00002831GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00002832{
2833 assert(wp);
2834 bool watch_read = wp->WatchpointRead();
2835 bool watch_write = wp->WatchpointWrite();
2836
2837 // watch_read and watch_write cannot both be false.
2838 assert(watch_read || watch_write);
2839 if (watch_read && watch_write)
2840 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00002841 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00002842 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00002843 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00002844 return eWatchpointWrite;
2845}
2846
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002847Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002848ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002849{
2850 Error error;
2851 if (wp)
2852 {
2853 user_id_t watchID = wp->GetID();
2854 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00002855 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002856 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002857 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002858 if (wp->IsEnabled())
2859 {
2860 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002861 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 +00002862 return error;
2863 }
Johnny Chen11309a32011-09-06 22:38:36 +00002864
2865 GDBStoppointType type = GetGDBStoppointType(wp);
2866 // Pass down an appropriate z/Z packet...
2867 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002868 {
Johnny Chen11309a32011-09-06 22:38:36 +00002869 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2870 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002871 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002872 return error;
2873 }
2874 else
2875 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002876 }
Johnny Chen11309a32011-09-06 22:38:36 +00002877 else
2878 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002879 }
2880 else
2881 {
Johnny Chen01a67862011-10-14 00:42:25 +00002882 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002883 }
2884 if (error.Success())
2885 error.SetErrorToGenericError();
2886 return error;
2887}
2888
2889Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002890ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002891{
2892 Error error;
2893 if (wp)
2894 {
2895 user_id_t watchID = wp->GetID();
2896
Greg Clayton5160ce52013-03-27 23:08:40 +00002897 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002898
2899 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00002900
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002901 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002902 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002903
Johnny Chen11309a32011-09-06 22:38:36 +00002904 if (!wp->IsEnabled())
2905 {
2906 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002907 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 +00002908 // See also 'class WatchpointSentry' within StopInfo.cpp.
2909 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2910 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00002911 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002912 return error;
2913 }
2914
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002915 if (wp->IsHardware())
2916 {
Johnny Chen11309a32011-09-06 22:38:36 +00002917 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002918 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00002919 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2920 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002921 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002922 return error;
2923 }
2924 else
2925 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002926 }
2927 // TODO: clear software watchpoints if we implement them
2928 }
2929 else
2930 {
Johnny Chen01a67862011-10-14 00:42:25 +00002931 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002932 }
2933 if (error.Success())
2934 error.SetErrorToGenericError();
2935 return error;
2936}
2937
2938void
2939ProcessGDBRemote::Clear()
2940{
2941 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002942 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002943 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002944}
2945
2946Error
2947ProcessGDBRemote::DoSignal (int signo)
2948{
2949 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002950 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002951 if (log)
2952 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2953
2954 if (!m_gdb_comm.SendAsyncSignal (signo))
2955 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2956 return error;
2957}
2958
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002959Error
Greg Clayton91a9b2472013-12-04 19:19:12 +00002960ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002961{
2962 Error error;
2963 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2964 {
2965 // If we locate debugserver, keep that located version around
2966 static FileSpec g_debugserver_file_spec;
2967
Han Ming Ong84647042012-02-25 01:07:38 +00002968 ProcessLaunchInfo debugserver_launch_info;
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00002969 // Make debugserver run in its own session so signals generated by
2970 // special terminal key sequences (^C) don't affect debugserver.
2971 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
2972
Greg Clayton91a9b2472013-12-04 19:19:12 +00002973 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2974 debugserver_launch_info.SetUserID(process_info.GetUserID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002975
Todd Fiala013434e2014-07-09 01:29:05 +00002976#if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__) || defined (__aarch64__))
Greg Claytonfda4fab2014-01-10 22:24:11 +00002977 // On iOS, still do a local connection using a random port
Greg Clayton16810922014-02-27 19:38:18 +00002978 const char *hostname = "127.0.0.1";
Greg Claytonfda4fab2014-01-10 22:24:11 +00002979 uint16_t port = get_random_port ();
2980#else
2981 // Set hostname being NULL to do the reverse connect where debugserver
2982 // will bind to port zero and it will communicate back to us the port
2983 // that we will connect to
2984 const char *hostname = NULL;
2985 uint16_t port = 0;
2986#endif
2987
2988 error = m_gdb_comm.StartDebugserverProcess (hostname,
2989 port,
Greg Clayton00fe87b2013-12-05 22:58:22 +00002990 debugserver_launch_info,
2991 port);
Greg Clayton91a9b2472013-12-04 19:19:12 +00002992
2993 if (error.Success ())
2994 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002995 else
Greg Clayton91a9b2472013-12-04 19:19:12 +00002996 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002997
2998 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2999 StartAsyncThread ();
Greg Clayton91a9b2472013-12-04 19:19:12 +00003000
3001 if (error.Fail())
3002 {
3003 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
3004
3005 if (log)
3006 log->Printf("failed to start debugserver process: %s", error.AsCString());
3007 return error;
3008 }
3009
Greg Clayton00fe87b2013-12-05 22:58:22 +00003010 if (m_gdb_comm.IsConnected())
3011 {
3012 // Finish the connection process by doing the handshake without connecting (send NULL URL)
3013 ConnectToDebugserver (NULL);
3014 }
3015 else
3016 {
Greg Claytonfda4fab2014-01-10 22:24:11 +00003017 StreamString connect_url;
3018 connect_url.Printf("connect://%s:%u", hostname, port);
3019 error = ConnectToDebugserver (connect_url.GetString().c_str());
Greg Clayton00fe87b2013-12-05 22:58:22 +00003020 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00003021
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003022 }
3023 return error;
3024}
3025
3026bool
3027ProcessGDBRemote::MonitorDebugserverProcess
3028(
3029 void *callback_baton,
3030 lldb::pid_t debugserver_pid,
Greg Claytone4e45922011-11-16 05:37:56 +00003031 bool exited, // True if the process did exit
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003032 int signo, // Zero for no signal
3033 int exit_status // Exit value of process if signal is zero
3034)
3035{
Greg Claytone4e45922011-11-16 05:37:56 +00003036 // The baton is a "ProcessGDBRemote *". Now this class might be gone
3037 // and might not exist anymore, so we need to carefully try to get the
3038 // target for this process first since we have a race condition when
3039 // we are done running between getting the notice that the inferior
3040 // process has died and the debugserver that was debugging this process.
3041 // In our test suite, we are also continually running process after
3042 // process, so we must be very careful to make sure:
3043 // 1 - process object hasn't been deleted already
3044 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003045
3046 // "debugserver_pid" argument passed in is the process ID for
3047 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00003048 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003049
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003050 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton6779606a2011-01-22 23:43:18 +00003051
Greg Claytone4e45922011-11-16 05:37:56 +00003052 // Get a shared pointer to the target that has a matching process pointer.
3053 // This target could be gone, or the target could already have a new process
3054 // object inside of it
3055 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
3056
Greg Clayton6779606a2011-01-22 23:43:18 +00003057 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003058 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 +00003059
Greg Claytone4e45922011-11-16 05:37:56 +00003060 if (target_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003061 {
Greg Claytone4e45922011-11-16 05:37:56 +00003062 // We found a process in a target that matches, but another thread
3063 // might be in the process of launching a new process that will
3064 // soon replace it, so get a shared pointer to the process so we
3065 // can keep it alive.
3066 ProcessSP process_sp (target_sp->GetProcessSP());
3067 // Now we have a shared pointer to the process that can't go away on us
3068 // so we now make sure it was the same as the one passed in, and also make
3069 // sure that our previous "process *" didn't get deleted and have a new
3070 // "process *" created in its place with the same pointer. To verify this
3071 // we make sure the process has our debugserver process ID. If we pass all
3072 // of these tests, then we are sure that this process is the one we were
3073 // looking for.
3074 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003075 {
Greg Claytone4e45922011-11-16 05:37:56 +00003076 // Sleep for a half a second to make sure our inferior process has
3077 // time to set its exit status before we set it incorrectly when
3078 // both the debugserver and the inferior process shut down.
3079 usleep (500000);
3080 // If our process hasn't yet exited, debugserver might have died.
3081 // If the process did exit, the we are reaping it.
3082 const StateType state = process->GetState();
3083
3084 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
3085 state != eStateInvalid &&
3086 state != eStateUnloaded &&
3087 state != eStateExited &&
3088 state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003089 {
Greg Claytone4e45922011-11-16 05:37:56 +00003090 char error_str[1024];
3091 if (signo)
3092 {
3093 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
3094 if (signal_cstr)
3095 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3096 else
3097 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
3098 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003099 else
Greg Claytone4e45922011-11-16 05:37:56 +00003100 {
3101 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
3102 }
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003103
Greg Claytone4e45922011-11-16 05:37:56 +00003104 process->SetExitStatus (-1, error_str);
3105 }
3106 // Debugserver has exited we need to let our ProcessGDBRemote
3107 // know that it no longer has a debugserver instance
3108 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003109 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003110 }
3111 return true;
3112}
3113
3114void
3115ProcessGDBRemote::KillDebugserverProcess ()
3116{
Greg Claytonfbb76342013-11-20 21:07:01 +00003117 m_gdb_comm.Disconnect();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003118 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3119 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003120 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003121 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3122 }
3123}
3124
3125void
3126ProcessGDBRemote::Initialize()
3127{
Davide Italianoc8d69822015-04-03 04:24:32 +00003128 static std::once_flag g_once_flag;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003129
Davide Italianoc8d69822015-04-03 04:24:32 +00003130 std::call_once(g_once_flag, []()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003131 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003132 PluginManager::RegisterPlugin (GetPluginNameStatic(),
3133 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00003134 CreateInstance,
3135 DebuggerInitialize);
Davide Italianoc8d69822015-04-03 04:24:32 +00003136 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003137}
3138
Greg Clayton7f982402013-07-15 22:54:20 +00003139void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003140ProcessGDBRemote::DebuggerInitialize (Debugger &debugger)
Greg Clayton7f982402013-07-15 22:54:20 +00003141{
3142 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
3143 {
3144 const bool is_global_setting = true;
3145 PluginManager::CreateSettingForProcessPlugin (debugger,
3146 GetGlobalPluginProperties()->GetValueProperties(),
3147 ConstString ("Properties for the gdb-remote process plug-in."),
3148 is_global_setting);
3149 }
3150}
3151
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003152bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003153ProcessGDBRemote::StartAsyncThread ()
3154{
Greg Clayton5160ce52013-03-27 23:08:40 +00003155 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003156
3157 if (log)
3158 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003159
3160 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003161 if (!m_async_thread.IsJoinable())
Jim Ingham455fa5c2012-11-01 01:15:33 +00003162 {
3163 // Create a thread that watches our internal state and controls which
3164 // events make it to clients (into the DCProcess event queue).
Zachary Turner39de3112014-09-09 20:54:56 +00003165
3166 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003167 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003168 else if (log)
3169 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was already running.", __FUNCTION__);
Zachary Turner39de3112014-09-09 20:54:56 +00003170
Zachary Turneracee96a2014-09-23 18:32:09 +00003171 return m_async_thread.IsJoinable();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003172}
3173
3174void
3175ProcessGDBRemote::StopAsyncThread ()
3176{
Greg Clayton5160ce52013-03-27 23:08:40 +00003177 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003178
3179 if (log)
3180 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
3181
Jim Ingham455fa5c2012-11-01 01:15:33 +00003182 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003183 if (m_async_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003184 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00003185 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
3186
3187 // This will shut down the async thread.
3188 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3189
3190 // Stop the stdio thread
Zachary Turner39de3112014-09-09 20:54:56 +00003191 m_async_thread.Join(nullptr);
Pavel Labatha55a9532015-03-11 09:53:42 +00003192 m_async_thread.Reset();
Jim Ingham455fa5c2012-11-01 01:15:33 +00003193 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003194 else if (log)
3195 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003196}
3197
3198
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003199thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003200ProcessGDBRemote::AsyncThread (void *arg)
3201{
3202 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
3203
Greg Clayton5160ce52013-03-27 23:08:40 +00003204 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003205 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003206 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003207
3208 Listener listener ("ProcessGDBRemote::AsyncThread");
3209 EventSP event_sp;
3210 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
3211 eBroadcastBitAsyncThreadShouldExit;
3212
3213 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
3214 {
Greg Clayton71337622011-02-24 22:24:29 +00003215 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
3216
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003217 bool done = false;
3218 while (!done)
3219 {
3220 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003221 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003222 if (listener.WaitForEvent (NULL, event_sp))
3223 {
3224 const uint32_t event_type = event_sp->GetType();
Greg Clayton71337622011-02-24 22:24:29 +00003225 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003226 {
Greg Clayton71337622011-02-24 22:24:29 +00003227 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003228 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 +00003229
Greg Clayton71337622011-02-24 22:24:29 +00003230 switch (event_type)
3231 {
3232 case eBroadcastBitAsyncContinue:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003233 {
Greg Clayton71337622011-02-24 22:24:29 +00003234 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003235
Greg Clayton71337622011-02-24 22:24:29 +00003236 if (continue_packet)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003237 {
Greg Clayton71337622011-02-24 22:24:29 +00003238 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
3239 const size_t continue_cstr_len = continue_packet->GetByteSize ();
3240 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003241 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003242
Greg Clayton71337622011-02-24 22:24:29 +00003243 if (::strstr (continue_cstr, "vAttach") == NULL)
3244 process->SetPrivateState(eStateRunning);
3245 StringExtractorGDBRemote response;
3246 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003247
Greg Clayton0772ded2012-05-16 02:48:06 +00003248 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
3249 // The thread ID list might be contained within the "response", or the stop reply packet that
3250 // caused the stop. So clear it now before we give the stop reply packet to the process
3251 // using the process->SetLastStopPacket()...
3252 process->ClearThreadIDList ();
3253
Greg Clayton71337622011-02-24 22:24:29 +00003254 switch (stop_state)
3255 {
3256 case eStateStopped:
3257 case eStateCrashed:
3258 case eStateSuspended:
Greg Clayton09c3e3d2011-12-06 04:51:14 +00003259 process->SetLastStopPacket (response);
Greg Clayton71337622011-02-24 22:24:29 +00003260 process->SetPrivateState (stop_state);
3261 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003262
Greg Clayton71337622011-02-24 22:24:29 +00003263 case eStateExited:
Jason Molendaa3329782014-03-29 18:54:20 +00003264 {
Greg Clayton09c3e3d2011-12-06 04:51:14 +00003265 process->SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00003266 process->ClearThreadIDList();
Greg Clayton71337622011-02-24 22:24:29 +00003267 response.SetFilePos(1);
Jason Molendaa3329782014-03-29 18:54:20 +00003268
3269 int exit_status = response.GetHexU8();
3270 const char *desc_cstr = NULL;
3271 StringExtractor extractor;
3272 std::string desc_string;
3273 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';')
3274 {
3275 std::string desc_token;
3276 while (response.GetNameColonValue (desc_token, desc_string))
3277 {
3278 if (desc_token == "description")
3279 {
3280 extractor.GetStringRef().swap(desc_string);
3281 extractor.SetFilePos(0);
3282 extractor.GetHexByteString (desc_string);
3283 desc_cstr = desc_string.c_str();
3284 }
3285 }
3286 }
3287 process->SetExitStatus(exit_status, desc_cstr);
Greg Clayton71337622011-02-24 22:24:29 +00003288 done = true;
3289 break;
Jason Molendaa3329782014-03-29 18:54:20 +00003290 }
Greg Clayton71337622011-02-24 22:24:29 +00003291 case eStateInvalid:
3292 process->SetExitStatus(-1, "lost connection");
3293 break;
3294
3295 default:
3296 process->SetPrivateState (stop_state);
3297 break;
3298 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003299 }
3300 }
Greg Clayton71337622011-02-24 22:24:29 +00003301 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003302
Greg Clayton71337622011-02-24 22:24:29 +00003303 case eBroadcastBitAsyncThreadShouldExit:
3304 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003305 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Clayton71337622011-02-24 22:24:29 +00003306 done = true;
3307 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003308
Greg Clayton71337622011-02-24 22:24:29 +00003309 default:
3310 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003311 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 +00003312 done = true;
3313 break;
3314 }
3315 }
3316 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
3317 {
3318 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
3319 {
3320 process->SetExitStatus (-1, "lost connection");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003321 done = true;
Greg Clayton71337622011-02-24 22:24:29 +00003322 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003323 }
3324 }
3325 else
3326 {
3327 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003328 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 +00003329 done = true;
3330 }
3331 }
3332 }
3333
3334 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003335 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003336
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003337 return NULL;
3338}
3339
Greg Claytone996fd32011-03-08 22:40:15 +00003340//uint32_t
3341//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3342//{
3343// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
3344// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
3345// if (m_local_debugserver)
3346// {
3347// return Host::ListProcessesMatchingName (name, matches, pids);
3348// }
3349// else
3350// {
3351// // FIXME: Implement talking to the remote debugserver.
3352// return 0;
3353// }
3354//
3355//}
3356//
Jim Ingham1c823b42011-01-22 01:33:44 +00003357bool
3358ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003359 StoppointCallbackContext *context,
Jim Ingham1c823b42011-01-22 01:33:44 +00003360 lldb::user_id_t break_id,
3361 lldb::user_id_t break_loc_id)
3362{
3363 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3364 // run so I can stop it if that's what I want to do.
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003365 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00003366 if (log)
3367 log->Printf("Hit New Thread Notification breakpoint.");
3368 return false;
3369}
3370
3371
3372bool
3373ProcessGDBRemote::StartNoticingNewThreads()
3374{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003375 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00003376 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003377 {
Greg Clayton4116e932012-05-15 02:33:01 +00003378 if (log && log->GetVerbose())
3379 log->Printf("Enabled noticing new thread breakpoint.");
3380 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003381 }
Greg Clayton4116e932012-05-15 02:33:01 +00003382 else
Jim Ingham1c823b42011-01-22 01:33:44 +00003383 {
Greg Clayton4116e932012-05-15 02:33:01 +00003384 PlatformSP platform_sp (m_target.GetPlatform());
3385 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003386 {
Greg Clayton4116e932012-05-15 02:33:01 +00003387 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3388 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003389 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00003390 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00003391 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3392 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003393 }
3394 else
3395 {
3396 if (log)
3397 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00003398 }
3399 }
3400 }
Greg Clayton4116e932012-05-15 02:33:01 +00003401 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00003402}
3403
3404bool
3405ProcessGDBRemote::StopNoticingNewThreads()
3406{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003407 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00003408 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00003409 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00003410
3411 if (m_thread_create_bp_sp)
3412 m_thread_create_bp_sp->SetEnabled(false);
3413
Jim Ingham1c823b42011-01-22 01:33:44 +00003414 return true;
3415}
3416
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003417DynamicLoader *
Jason Molenda5e8534e2012-10-03 01:29:34 +00003418ProcessGDBRemote::GetDynamicLoader ()
3419{
3420 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00003421 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00003422 return m_dyld_ap.get();
3423}
Jim Ingham1c823b42011-01-22 01:33:44 +00003424
Jason Molendaa3329782014-03-29 18:54:20 +00003425Error
3426ProcessGDBRemote::SendEventData(const char *data)
3427{
3428 int return_value;
3429 bool was_supported;
3430
3431 Error error;
3432
3433 return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported);
3434 if (return_value != 0)
3435 {
3436 if (!was_supported)
3437 error.SetErrorString("Sending events is not supported for this process.");
3438 else
3439 error.SetErrorStringWithFormat("Error sending event data: %d.", return_value);
3440 }
3441 return error;
3442}
3443
Steve Pucci03904ac2014-03-04 23:18:46 +00003444const DataBufferSP
3445ProcessGDBRemote::GetAuxvData()
3446{
3447 DataBufferSP buf;
3448 if (m_gdb_comm.GetQXferAuxvReadSupported())
3449 {
3450 std::string response_string;
3451 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success)
3452 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length()));
3453 }
3454 return buf;
3455}
3456
Jason Molenda705b1802014-06-13 02:37:02 +00003457StructuredData::ObjectSP
3458ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid)
3459{
3460 StructuredData::ObjectSP object_sp;
3461
3462 if (m_gdb_comm.GetThreadExtendedInfoSupported())
3463 {
3464 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3465 SystemRuntime *runtime = GetSystemRuntime();
3466 if (runtime)
3467 {
3468 runtime->AddThreadExtendedInfoPacketHints (args_dict);
3469 }
3470 args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid);
3471
3472 StreamString packet;
3473 packet << "jThreadExtendedInfo:";
3474 args_dict->Dump (packet);
3475
3476 // FIXME the final character of a JSON dictionary, '}', is the escape
3477 // character in gdb-remote binary mode. lldb currently doesn't escape
3478 // these characters in its packet output -- so we add the quoted version
3479 // of the } character here manually in case we talk to a debugserver which
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003480 // un-escapes the characters at packet read time.
Jason Molenda705b1802014-06-13 02:37:02 +00003481 packet << (char) (0x7d ^ 0x20);
3482
3483 StringExtractorGDBRemote response;
3484 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
3485 {
3486 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
3487 if (response_type == StringExtractorGDBRemote::eResponse)
3488 {
3489 if (!response.Empty())
3490 {
3491 // The packet has already had the 0x7d xor quoting stripped out at the
3492 // GDBRemoteCommunication packet receive level.
3493 object_sp = StructuredData::ParseJSON (response.GetStringRef());
3494 }
3495 }
3496 }
3497 }
3498 return object_sp;
3499}
3500
Jason Molenda6076bf42014-05-06 04:34:52 +00003501// Establish the largest memory read/write payloads we should use.
3502// If the remote stub has a max packet size, stay under that size.
3503//
3504// If the remote stub's max packet size is crazy large, use a
3505// reasonable largeish default.
3506//
3507// If the remote stub doesn't advertise a max packet size, use a
3508// conservative default.
3509
3510void
3511ProcessGDBRemote::GetMaxMemorySize()
3512{
3513 const uint64_t reasonable_largeish_default = 128 * 1024;
3514 const uint64_t conservative_default = 512;
3515
3516 if (m_max_memory_size == 0)
3517 {
3518 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
3519 if (stub_max_size != UINT64_MAX && stub_max_size != 0)
3520 {
3521 // Save the stub's claimed maximum packet size
3522 m_remote_stub_max_memory_size = stub_max_size;
3523
3524 // Even if the stub says it can support ginormous packets,
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003525 // don't exceed our reasonable largeish default packet size.
Jason Molenda6076bf42014-05-06 04:34:52 +00003526 if (stub_max_size > reasonable_largeish_default)
3527 {
3528 stub_max_size = reasonable_largeish_default;
3529 }
3530
3531 m_max_memory_size = stub_max_size;
3532 }
3533 else
3534 {
3535 m_max_memory_size = conservative_default;
3536 }
3537 }
3538}
3539
3540void
3541ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max)
3542{
3543 if (user_specified_max != 0)
3544 {
3545 GetMaxMemorySize ();
3546
3547 if (m_remote_stub_max_memory_size != 0)
3548 {
3549 if (m_remote_stub_max_memory_size < user_specified_max)
3550 {
3551 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a packet size too big, go as big
3552 // as the remote stub says we can go.
3553 }
3554 else
3555 {
3556 m_max_memory_size = user_specified_max; // user's packet size is good
3557 }
3558 }
3559 else
3560 {
3561 m_max_memory_size = user_specified_max; // user's packet size is probably fine
3562 }
3563 }
3564}
3565
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003566bool
3567ProcessGDBRemote::GetModuleSpec(const FileSpec& module_file_spec,
3568 const ArchSpec& arch,
3569 ModuleSpec &module_spec)
3570{
3571 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PLATFORM);
3572
3573 if (!m_gdb_comm.GetModuleInfo (module_file_spec, arch, module_spec))
3574 {
3575 if (log)
3576 log->Printf ("ProcessGDBRemote::%s - failed to get module info for %s:%s",
3577 __FUNCTION__, module_file_spec.GetPath ().c_str (),
3578 arch.GetTriple ().getTriple ().c_str ());
3579 return false;
3580 }
3581
3582 if (log)
3583 {
3584 StreamString stream;
3585 module_spec.Dump (stream);
3586 log->Printf ("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
3587 __FUNCTION__, module_file_spec.GetPath ().c_str (),
3588 arch.GetTriple ().getTriple ().c_str (), stream.GetString ().c_str ());
3589 }
3590
3591 return true;
3592}
3593
Colin Rileyc3c95b22015-04-16 15:51:33 +00003594#if defined( LIBXML2_DEFINED )
3595namespace {
3596
3597typedef std::vector<std::string> stringVec;
3598typedef std::vector<xmlNodePtr> xmlNodePtrVec;
3599
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003600struct GdbServerRegisterInfo
3601{
Colin Rileyc3c95b22015-04-16 15:51:33 +00003602
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003603 struct
3604 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003605 bool m_has_name : 1;
3606 bool m_has_bitSize : 1;
3607 bool m_has_type : 1;
3608 bool m_has_group : 1;
3609 bool m_has_regNum : 1;
3610 }
3611 m_flags;
3612
3613 std::string m_name;
3614 std::string m_group;
3615 uint32_t m_bitSize;
3616 uint32_t m_regNum;
3617
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003618 enum RegType
3619 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003620 eUnknown ,
3621 eCodePtr ,
3622 eDataPtr ,
3623 eInt32 ,
3624 eI387Ext ,
3625 }
3626 m_type;
3627
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003628 void clear()
3629 {
3630 memset(&m_flags, 0, sizeof(m_flags));
Colin Rileyc3c95b22015-04-16 15:51:33 +00003631 }
3632};
3633
3634typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
3635
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003636struct GdbServerTargetInfo
3637{
Colin Rileyc3c95b22015-04-16 15:51:33 +00003638 std::string m_arch;
3639 std::string m_osabi;
3640};
3641
3642// conversion table between gdb register type and enum
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003643struct
3644{
Colin Rileyc3c95b22015-04-16 15:51:33 +00003645 const char * m_name;
3646 GdbServerRegisterInfo::RegType m_type;
3647}
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003648RegTypeTable[] =
3649{
Colin Rileyc3c95b22015-04-16 15:51:33 +00003650 { "int32" , GdbServerRegisterInfo::eInt32 },
3651 { "int" , GdbServerRegisterInfo::eInt32 },
3652 { "data_ptr", GdbServerRegisterInfo::eDataPtr },
3653 { "code_ptr", GdbServerRegisterInfo::eCodePtr },
3654 { "i387_ext", GdbServerRegisterInfo::eI387Ext }, // 80bit fpu
Greg Claytone68c0082015-04-16 23:13:26 +00003655 { nullptr , GdbServerRegisterInfo::eUnknown } // sentinel
Colin Rileyc3c95b22015-04-16 15:51:33 +00003656};
3657
3658// find the first sibling with a matching name
3659xmlNodePtr
3660xmlExFindSibling (xmlNodePtr node,
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003661 const std::string & name)
3662{
Colin Rileyc3c95b22015-04-16 15:51:33 +00003663
3664 if ( !node ) return nullptr;
3665 // iterate through all siblings
3666 for ( xmlNodePtr temp = node; temp; temp=temp->next ) {
3667 // we are looking for elements
3668 if ( temp->type != XML_ELEMENT_NODE )
3669 continue;
3670 // check element name matches
3671 if ( !temp->name ) continue;
3672 if ( std::strcmp((const char*)temp->name, name.c_str() ) == 0 )
3673 return temp;
3674 }
3675 // no sibling found
3676 return nullptr;
3677}
3678
3679// find an element from a given element path
3680xmlNodePtr
3681xmlExFindElement (xmlNodePtr node,
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003682 const stringVec & path)
3683{
Colin Rileyc3c95b22015-04-16 15:51:33 +00003684
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003685 if (!node)
3686 return nullptr;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003687 xmlNodePtr temp = node;
3688 // iterate all elements in path
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003689 for (uint32_t i = 0; i < path.size(); i++)
3690 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003691
3692 // search for a sibling with this name
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003693 temp = xmlExFindSibling(temp, path[i]);
3694 if (!temp)
Colin Rileyc3c95b22015-04-16 15:51:33 +00003695 return nullptr;
3696 // enter this node if we still need to search
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003697 if ((i + 1) < path.size())
Colin Rileyc3c95b22015-04-16 15:51:33 +00003698 // enter the node we have found
3699 temp = temp->children;
3700 }
3701 // note: node may still be nullptr at this step
3702 return temp;
3703}
3704
3705// locate a specific attribute in an element
3706xmlAttr *
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003707xmlExFindAttribute (xmlNodePtr node,
3708 const std::string & name)
3709{
Colin Rileyc3c95b22015-04-16 15:51:33 +00003710
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003711 if (!node)
Colin Rileyc3c95b22015-04-16 15:51:33 +00003712 return nullptr;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003713 if (node->type != XML_ELEMENT_NODE)
Colin Rileyc3c95b22015-04-16 15:51:33 +00003714 return nullptr;
3715 // iterate over all attributes
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003716 for (xmlAttrPtr attr = node->properties; attr != nullptr; attr=attr->next)
3717 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003718 // check if name matches
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003719 if (!attr->name)
3720 continue;
3721 if (std::strcmp((const char*) attr->name, name.c_str()) == 0)
Colin Rileyc3c95b22015-04-16 15:51:33 +00003722 return attr;
3723 }
3724 return nullptr;
3725}
3726
3727// find all child elements with given name and add them to a vector
3728//
3729// input: node = xml element to search
3730// name = name used when matching child elements
3731// output: out = list of matches
3732// return: number of children added to 'out'
3733int
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003734xmlExFindChildren (xmlNodePtr node,
3735 const std::string & name,
3736 xmlNodePtrVec & out)
3737{
Colin Rileyc3c95b22015-04-16 15:51:33 +00003738
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003739 if (!node)
3740 return 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003741 int count = 0;
3742 // iterate over all children
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003743 for (xmlNodePtr child = node->children; child; child = child->next)
3744 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003745 // if name matches
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003746 if (!child->name)
3747 continue;
3748 if (std::strcmp((const char*) child->name, name.c_str()) == 0)
3749 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003750 // add to output list
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003751 out.push_back(child);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003752 ++count;
3753 }
3754 }
3755 return count;
3756}
3757
3758// get the text content from an attribute
3759std::string
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003760xmlExGetTextContent (xmlAttrPtr attr)
3761{
3762 if (!attr)
3763 return std::string();
3764 if (attr->type != XML_ATTRIBUTE_NODE)
3765 return std::string();
Colin Rileyc3c95b22015-04-16 15:51:33 +00003766 // check child is a text node
3767 xmlNodePtr child = attr->children;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003768 if (child->type != XML_TEXT_NODE)
3769 return std::string();
Colin Rileyc3c95b22015-04-16 15:51:33 +00003770 // access the content
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003771 assert(child->content != nullptr);
3772 return std::string((const char*) child->content);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003773}
3774
3775// get the text content from an node
3776std::string
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003777xmlExGetTextContent (xmlNodePtr node)
3778{
3779 if (!node)
3780 return std::string();
3781 if (node->type != XML_ELEMENT_NODE)
3782 return std::string();
Colin Rileyc3c95b22015-04-16 15:51:33 +00003783 // check child is a text node
3784 xmlNodePtr child = node->children;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003785 if (child->type != XML_TEXT_NODE)
3786 return std::string();
Colin Rileyc3c95b22015-04-16 15:51:33 +00003787 // access the content
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003788 assert(child->content != nullptr);
3789 return std::string((const char*) child->content);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003790}
3791
3792// compile a list of xml includes from the target file
3793// input: doc = target.xml
3794// output: includes = list of .xml names specified in target.xml
3795// return: number of .xml files specified in target.xml and added to includes
3796int
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003797parseTargetIncludes (xmlDocPtr doc, stringVec & includes)
3798{
3799 if (!doc)
3800 return 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003801 int count = 0;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003802 xmlNodePtr elm = xmlExFindElement(doc->children, {"target"});
3803 if (!elm)
3804 return 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003805 xmlNodePtrVec nodes;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003806 xmlExFindChildren(elm, "xi:include", nodes);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003807 // iterate over all includes
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003808 for (uint32_t i = 0; i < nodes.size(); i++)
3809 {
3810 xmlAttrPtr attr = xmlExFindAttribute(nodes[i], "href");
3811 if (attr != nullptr)
3812 {
3813 std::string text = xmlExGetTextContent(attr);
3814 includes.push_back(text);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003815 ++count;
3816 }
3817 }
3818 return count;
3819}
3820
3821// extract target arch information from the target.xml file
3822// input: doc = target.xml document
3823// output: out = remote target information
3824// return: 'true' on success
3825// 'false' on failure
3826bool
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003827parseTargetInfo (xmlDocPtr doc, GdbServerTargetInfo & out)
3828{
3829 if (!doc)
3830 return false;
3831 xmlNodePtr e1 = xmlExFindElement (doc->children, {"target", "architecture"});
3832 if (!e1)
3833 return false;
3834 out.m_arch = xmlExGetTextContent (e1);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003835
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003836 xmlNodePtr e2 = xmlExFindElement (doc->children, {"target", "osabi"});
3837 if (!e2)
3838 return false;
3839 out.m_osabi = xmlExGetTextContent (e2);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003840
3841 return true;
3842}
3843
3844// extract register information from one of the xml files specified in target.xml
3845// input: doc = xml document
3846// output: regList = list of extracted register info
3847// return: 'true' on success
3848// 'false' on failure
3849bool
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003850parseRegisters (xmlDocPtr doc, GDBServerRegisterVec & regList)
3851{
Colin Rileyc3c95b22015-04-16 15:51:33 +00003852
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003853 if (!doc)
3854 return false;
3855 xmlNodePtr elm = xmlExFindElement (doc->children, {"feature"});
3856 if (!elm)
3857 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003858
3859 xmlAttrPtr attr = nullptr;
3860
3861 xmlNodePtrVec regs;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003862 xmlExFindChildren (elm, "reg", regs);
3863 for (unsigned long i = 0; i < regs.size(); i++)
3864 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003865
3866 GdbServerRegisterInfo reg;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003867 reg.clear();
Colin Rileyc3c95b22015-04-16 15:51:33 +00003868
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003869 if ((attr = xmlExFindAttribute(regs[i], "name")))
3870 {
3871 reg.m_name = xmlExGetTextContent(attr).c_str();
Colin Rileyc3c95b22015-04-16 15:51:33 +00003872 reg.m_flags.m_has_name = true;
3873 }
3874
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003875 if ((attr = xmlExFindAttribute( regs[i], "bitsize")))
3876 {
3877 const std::string v = xmlExGetTextContent(attr);
3878 reg.m_bitSize = atoi(v.c_str());
Colin Rileyc3c95b22015-04-16 15:51:33 +00003879 reg.m_flags.m_has_bitSize = true;
3880 }
3881
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003882 if ((attr = xmlExFindAttribute(regs[i], "type")))
3883 {
3884 const std::string v = xmlExGetTextContent(attr);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003885 reg.m_type = GdbServerRegisterInfo::eUnknown;
3886
3887 // search the type table for a match
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003888 for (int j = 0; RegTypeTable[j].m_name !=nullptr; ++j)
3889 {
3890 if (RegTypeTable[j].m_name == v)
3891 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003892 reg.m_type = RegTypeTable[j].m_type;
3893 break;
3894 }
3895 }
3896
3897 reg.m_flags.m_has_type = (reg.m_type != GdbServerRegisterInfo::eUnknown);
3898 }
3899
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003900 if ((attr = xmlExFindAttribute( regs[i], "group")))
3901 {
3902 reg.m_group = xmlExGetTextContent(attr);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003903 reg.m_flags.m_has_group = true;
3904 }
3905
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003906 if ((attr = xmlExFindAttribute(regs[i], "regnum")))
3907 {
3908 const std::string v = xmlExGetTextContent(attr);
3909 reg.m_regNum = atoi(v.c_str());
Colin Rileyc3c95b22015-04-16 15:51:33 +00003910 reg.m_flags.m_has_regNum = true;
3911 }
3912
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003913 regList.push_back(reg);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003914 }
3915
3916 //TODO: there is also a "vector" element to parse
3917 //TODO: there is also eflags to parse
3918
3919 return true;
3920}
3921
3922// build lldb gdb-remote's dynamic register info from a vector of gdb provided registers
3923// input: regList = register information provided by gdbserver
3924// output: regInfo = dynamic register information required by gdb-remote
3925void
3926BuildRegisters (const GDBServerRegisterVec & regList,
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003927 GDBRemoteDynamicRegisterInfo & regInfo)
3928{
Colin Rileyc3c95b22015-04-16 15:51:33 +00003929
3930 using namespace lldb_private;
3931
3932 const uint32_t defSize = 32;
3933 uint32_t regNum = 0;
3934 uint32_t byteOffset = 0;
3935
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003936 for (uint32_t i = 0; i < regList.size(); ++i)
3937 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003938
3939 const GdbServerRegisterInfo & gdbReg = regList[i];
3940
3941 std::string name = gdbReg.m_flags.m_has_name ? gdbReg.m_name : "unknown";
3942 std::string group = gdbReg.m_flags.m_has_group ? gdbReg.m_group : "general";
3943 uint32_t byteSize = gdbReg.m_flags.m_has_bitSize ? (gdbReg.m_bitSize/8) : defSize;
3944
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003945 if (gdbReg.m_flags.m_has_regNum)
Colin Rileyc3c95b22015-04-16 15:51:33 +00003946 regNum = gdbReg.m_regNum;
3947
3948 uint32_t regNumGcc = LLDB_INVALID_REGNUM;
3949 uint32_t regNumDwarf = LLDB_INVALID_REGNUM;
3950 uint32_t regNumGeneric = LLDB_INVALID_REGNUM;
3951 uint32_t regNumGdb = regNum;
3952 uint32_t regNumNative = regNum;
3953
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003954 if (name == "eip" || name == "pc")
3955 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003956 regNumGeneric = LLDB_REGNUM_GENERIC_PC;
3957 }
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003958 if (name == "esp" || name == "sp")
3959 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003960 regNumGeneric = LLDB_REGNUM_GENERIC_SP;
3961 }
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003962 if (name == "ebp")
3963 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003964 regNumGeneric = LLDB_REGNUM_GENERIC_FP;
3965 }
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003966 if (name == "lr")
3967 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003968 regNumGeneric = LLDB_REGNUM_GENERIC_RA;
3969 }
3970
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003971 RegisterInfo info =
3972 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003973 name.c_str(),
3974 nullptr ,
3975 byteSize ,
3976 byteOffset ,
3977 lldb::Encoding::eEncodingUint,
3978 lldb::Format::eFormatDefault,
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003979 { regNumGcc ,
3980 regNumDwarf ,
Colin Rileyc3c95b22015-04-16 15:51:33 +00003981 regNumGeneric,
3982 regNumGdb ,
3983 regNumNative },
3984 nullptr,
3985 nullptr
3986 };
3987
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003988 ConstString regName = ConstString(gdbReg.m_name);
3989 ConstString regAltName = ConstString();
3990 ConstString regGroup = ConstString(group);
3991 regInfo.AddRegister(info, regName, regAltName, regGroup);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003992
3993 // advance register info
3994 byteOffset += byteSize;
3995 regNum += 1;
3996 }
3997
3998 regInfo.Finalize ();
3999}
4000
4001} // namespace {}
4002
4003void XMLCDECL
4004libxml2NullErrorFunc (void *ctx, const char *msg, ...)
4005{
4006 // do nothing currently
4007}
4008
4009// query the target of gdb-remote for extended target information
4010// return: 'true' on success
4011// 'false' on failure
4012bool
Aidan Doddsc0c83852015-05-08 09:36:31 +00004013ProcessGDBRemote::GetGDBServerRegisterInfo ()
Colin Rileyc3c95b22015-04-16 15:51:33 +00004014{
4015
4016 // redirect libxml2's error handler since the default prints to stdout
4017 xmlGenericErrorFunc func = libxml2NullErrorFunc;
4018 initGenericErrorDefaultFunc( &func );
4019
4020 GDBRemoteCommunicationClient & comm = m_gdb_comm;
4021 GDBRemoteDynamicRegisterInfo & regInfo = m_register_info;
4022
4023 // check that we have extended feature read support
4024 if ( !comm.GetQXferFeaturesReadSupported( ) )
4025 return false;
4026
4027 // request the target xml file
4028 std::string raw;
4029 lldb_private::Error lldberr;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004030 if (!comm.ReadExtFeature(ConstString("features"),
4031 ConstString("target.xml"),
4032 raw,
4033 lldberr))
4034 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00004035 return false;
4036 }
4037
4038 // parse the xml file in memory
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004039 xmlDocPtr doc = xmlReadMemory(raw.c_str(), raw.size(), "noname.xml", nullptr, 0);
4040 if (doc == nullptr)
Colin Rileyc3c95b22015-04-16 15:51:33 +00004041 return false;
4042
4043 // extract target info from target.xml
4044 GdbServerTargetInfo gdbInfo;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004045 if (parseTargetInfo(doc, gdbInfo))
4046 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00004047 // NOTE: We could deduce triple from gdbInfo if lldb doesn't already have one set
4048 }
4049
4050 // collect registers from all of the includes
4051 GDBServerRegisterVec regList;
4052 stringVec includes;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004053 if (parseTargetIncludes(doc, includes) > 0)
4054 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00004055
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004056 for (uint32_t i = 0; i < includes.size(); ++i)
4057 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00004058
4059 // request register file
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004060 if (!comm.ReadExtFeature(ConstString("features"),
4061 ConstString(includes[i]),
4062 raw,
4063 lldberr))
Colin Rileyc3c95b22015-04-16 15:51:33 +00004064 continue;
4065
4066 // parse register file
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004067 xmlDocPtr regXml = xmlReadMemory(raw.c_str(),
4068 raw.size( ),
4069 includes[i].c_str(),
4070 nullptr,
4071 0);
4072 if (!regXml)
Colin Rileyc3c95b22015-04-16 15:51:33 +00004073 continue;
4074
4075 // pass registers to lldb
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004076 parseRegisters(regXml, regList);
Colin Rileyc3c95b22015-04-16 15:51:33 +00004077 }
4078 }
4079
4080 // pass all of these registers to lldb
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004081 BuildRegisters(regList, regInfo);
Colin Rileyc3c95b22015-04-16 15:51:33 +00004082
4083 return true;
4084}
4085
Aidan Doddsc0c83852015-05-08 09:36:31 +00004086Error
4087ProcessGDBRemote::GetLoadedModuleList (GDBLoadedModuleInfoList & list)
4088{
4089 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS);
4090 if (log)
4091 log->Printf ("ProcessGDBRemote::%s", __FUNCTION__);
4092
4093 // redirect libxml2's error handler since the default prints to stdout
4094 xmlGenericErrorFunc func = libxml2NullErrorFunc;
4095 initGenericErrorDefaultFunc (&func);
4096
4097 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004098
4099 // check that we have extended feature read support
4100 if (!comm.GetQXferLibrariesSVR4ReadSupported ())
4101 return Error (0, ErrorType::eErrorTypeGeneric);
4102
4103 list.clear ();
4104
4105 // request the loaded library list
4106 std::string raw;
4107 lldb_private::Error lldberr;
4108 if (!comm.ReadExtFeature (ConstString ("libraries-svr4"), ConstString (""), raw, lldberr))
4109 return Error (0, ErrorType::eErrorTypeGeneric);
4110
4111 // parse the xml file in memory
4112 if (log)
4113 log->Printf ("parsing: %s", raw.c_str());
4114 xmlDocPtr doc = xmlReadMemory (raw.c_str(), raw.size(), "noname.xml", nullptr, 0);
4115 if (doc == nullptr)
4116 return Error (0, ErrorType::eErrorTypeGeneric);
4117
4118 xmlNodePtr elm = xmlExFindElement (doc->children, {"library-list-svr4"});
4119 if (!elm)
4120 return Error();
4121
4122 // main link map structure
4123 xmlAttr * attr = xmlExFindAttribute (elm, "main-lm");
4124 if (attr)
4125 {
4126 std::string val = xmlExGetTextContent (attr);
4127 if (val.length() > 2)
4128 {
4129 uint32_t process_lm = std::stoul (val.c_str()+2, 0, 16);
4130 list.m_link_map = process_lm;
4131 }
4132 }
4133
4134 // parse individual library entries
4135 for (xmlNode * child = elm->children; child; child=child->next)
4136 {
4137 if (!child->name)
4138 continue;
4139
Vince Harrond7e6a4f2015-05-13 00:25:54 +00004140 if (strcmp ((const char*)child->name, "library") != 0)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004141 continue;
4142
4143 GDBLoadedModuleInfoList::LoadedModuleInfo module;
4144
4145 for (xmlAttrPtr prop = child->properties; prop; prop=prop->next)
4146 {
Vince Harrond7e6a4f2015-05-13 00:25:54 +00004147 if (strcmp ((const char*)prop->name, "name") == 0)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004148 module.set_name (xmlExGetTextContent (prop));
4149
4150 // the address of the link_map struct.
Vince Harrond7e6a4f2015-05-13 00:25:54 +00004151 if (strcmp ((const char*)prop->name, "lm") == 0)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004152 {
4153 std::string val = xmlExGetTextContent (prop);
4154 if (val.length() > 2)
4155 {
4156 uint32_t module_lm = std::stoul (val.c_str()+2, 0, 16);
4157 module.set_link_map (module_lm);
4158 }
4159 }
4160
4161 // the displacement as read from the field 'l_addr' of the link_map struct.
Vince Harrond7e6a4f2015-05-13 00:25:54 +00004162 if (strcmp ((const char*)prop->name, "l_addr") == 0)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004163 {
4164 std::string val = xmlExGetTextContent (prop);
4165 if (val.length() > 2)
4166 {
4167 uint32_t module_base = std::stoul (val.c_str()+2, 0, 16);
4168 module.set_base (module_base);
4169 }
4170 }
4171
4172 // the memory address of the libraries PT_DYAMIC section.
Vince Harrond7e6a4f2015-05-13 00:25:54 +00004173 if (strcmp ((const char*)prop->name, "l_ld") == 0)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004174 {
4175 std::string val = xmlExGetTextContent (prop);
4176 if (val.length() > 2)
4177 {
4178 uint32_t module_dyn = std::stoul (val.c_str()+2, 0, 16);
4179 module.set_dynamic (module_dyn);
4180 }
4181 }
4182 }
4183
4184 if (log)
4185 {
4186 std::string name ("");
4187 lldb::addr_t lm=0, base=0, ld=0;
4188
4189 module.get_name (name);
4190 module.get_link_map (lm);
4191 module.get_base (base);
4192 module.get_dynamic (ld);
4193
4194 log->Printf ("found (link_map:0x08%" PRIx64 ", base:0x08%" PRIx64 ", ld:0x08%" PRIx64 ", name:'%s')", lm, base, ld, name.c_str());
4195 }
4196
4197 list.add (module);
4198 }
4199
4200 if (log)
4201 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4202
4203 return Error();
4204}
4205
Colin Rileyc3c95b22015-04-16 15:51:33 +00004206#else // if defined( LIBXML2_DEFINED )
4207
Aidan Doddsc0c83852015-05-08 09:36:31 +00004208Error
4209ProcessGDBRemote::GetLoadedModuleList (GDBLoadedModuleInfoList &)
4210{
4211 // stub (libxml2 not present)
4212 Error err;
4213 err.SetError (0, ErrorType::eErrorTypeGeneric);
4214 return err;
4215}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004216
4217bool
Aidan Doddsc0c83852015-05-08 09:36:31 +00004218ProcessGDBRemote::GetGDBServerRegisterInfo ()
Colin Rileyc3c95b22015-04-16 15:51:33 +00004219{
4220 // stub (libxml2 not present)
4221 return false;
4222}
4223
4224#endif // if defined( LIBXML2_DEFINED )
4225
Aidan Doddsc0c83852015-05-08 09:36:31 +00004226lldb::ModuleSP
4227ProcessGDBRemote::LoadModuleAtAddress (const FileSpec &file, lldb::addr_t base_addr)
4228{
4229 Target &target = m_process->GetTarget();
4230 ModuleList &modules = target.GetImages();
4231 ModuleSP module_sp;
4232
4233 bool changed = false;
4234
4235 ModuleSpec module_spec (file, target.GetArchitecture());
4236 if ((module_sp = modules.FindFirstModule (module_spec)))
4237 {
4238 module_sp->SetLoadAddress (target, base_addr, true, changed);
4239 }
4240 else if ((module_sp = target.GetSharedModule (module_spec)))
4241 {
4242 module_sp->SetLoadAddress (target, base_addr, true, changed);
4243 }
4244
4245 return module_sp;
4246}
4247
4248size_t
4249ProcessGDBRemote::LoadModules ()
4250{
4251 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4252
4253 // request a list of loaded libraries from GDBServer
4254 GDBLoadedModuleInfoList module_list;
4255 if (GetLoadedModuleList (module_list).Fail())
4256 return 0;
4257
4258 // get a list of all the modules
4259 ModuleList new_modules;
4260
4261 for (GDBLoadedModuleInfoList::LoadedModuleInfo & modInfo : module_list.m_list)
4262 {
4263 std::string mod_name;
4264 lldb::addr_t mod_base;
4265
4266 bool valid = true;
4267 valid &= modInfo.get_name (mod_name);
4268 valid &= modInfo.get_base (mod_base);
4269 if (!valid)
4270 continue;
4271
4272 // hack (cleaner way to get file name only?) (win/unix compat?)
Vince Harron4cc8d202015-05-10 08:33:58 +00004273 size_t marker = mod_name.rfind ('/');
Aidan Doddsc0c83852015-05-08 09:36:31 +00004274 if (marker == std::string::npos)
4275 marker = 0;
4276 else
4277 marker += 1;
4278
4279 FileSpec file (mod_name.c_str()+marker, true);
4280 lldb::ModuleSP module_sp = LoadModuleAtAddress (file, mod_base);
4281
4282 if (module_sp.get())
4283 new_modules.Append (module_sp);
4284 }
4285
4286 if (new_modules.GetSize() > 0)
4287 {
4288 Target & target = m_target;
4289
4290 new_modules.ForEach ([&target](const lldb::ModuleSP module_sp) -> bool
4291 {
4292 lldb_private::ObjectFile * obj = module_sp->GetObjectFile ();
4293 if (!obj)
4294 return true;
4295
4296 if (obj->GetType () != ObjectFile::Type::eTypeExecutable)
4297 return true;
4298
4299 lldb::ModuleSP module_copy_sp = module_sp;
4300 target.SetExecutableModule (module_copy_sp, false);
4301 return false;
4302 });
4303
4304 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4305 loaded_modules.AppendIfNeeded (new_modules);
4306 m_process->GetTarget().ModulesDidLoad (new_modules);
4307 }
4308
4309 return new_modules.GetSize();
4310}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004311
Greg Clayton02686b82012-10-15 22:42:16 +00004312class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00004313{
4314private:
4315
4316public:
Greg Clayton02686b82012-10-15 22:42:16 +00004317 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00004318 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00004319 "process plugin packet history",
4320 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00004321 NULL)
4322 {
4323 }
4324
Greg Clayton02686b82012-10-15 22:42:16 +00004325 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton998255b2012-10-13 02:07:45 +00004326 {
4327 }
4328
4329 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004330 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton998255b2012-10-13 02:07:45 +00004331 {
Greg Clayton02686b82012-10-15 22:42:16 +00004332 const size_t argc = command.GetArgumentCount();
4333 if (argc == 0)
4334 {
4335 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4336 if (process)
4337 {
4338 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
4339 result.SetStatus (eReturnStatusSuccessFinishResult);
4340 return true;
4341 }
4342 }
4343 else
4344 {
4345 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
4346 }
4347 result.SetStatus (eReturnStatusFailed);
4348 return false;
4349 }
4350};
4351
Jason Molenda6076bf42014-05-06 04:34:52 +00004352class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed
4353{
4354private:
4355
4356public:
4357 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) :
4358 CommandObjectParsed (interpreter,
4359 "process plugin packet xfer-size",
4360 "Maximum size that lldb will try to read/write one one chunk.",
4361 NULL)
4362 {
4363 }
4364
4365 ~CommandObjectProcessGDBRemotePacketXferSize ()
4366 {
4367 }
4368
4369 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004370 DoExecute (Args& command, CommandReturnObject &result) override
Jason Molenda6076bf42014-05-06 04:34:52 +00004371 {
4372 const size_t argc = command.GetArgumentCount();
4373 if (argc == 0)
4374 {
4375 result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str());
4376 result.SetStatus (eReturnStatusFailed);
4377 return false;
4378 }
4379
4380 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4381 if (process)
4382 {
4383 const char *packet_size = command.GetArgumentAtIndex(0);
4384 errno = 0;
4385 uint64_t user_specified_max = strtoul (packet_size, NULL, 10);
4386 if (errno == 0 && user_specified_max != 0)
4387 {
4388 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max);
4389 result.SetStatus (eReturnStatusSuccessFinishResult);
4390 return true;
4391 }
4392 }
4393 result.SetStatus (eReturnStatusFailed);
4394 return false;
4395 }
4396};
4397
4398
Greg Clayton02686b82012-10-15 22:42:16 +00004399class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
4400{
4401private:
4402
4403public:
4404 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
4405 CommandObjectParsed (interpreter,
4406 "process plugin packet send",
4407 "Send a custom packet through the GDB remote protocol and print the answer. "
4408 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
4409 NULL)
4410 {
4411 }
4412
4413 ~CommandObjectProcessGDBRemotePacketSend ()
4414 {
4415 }
4416
4417 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004418 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton02686b82012-10-15 22:42:16 +00004419 {
4420 const size_t argc = command.GetArgumentCount();
4421 if (argc == 0)
4422 {
4423 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
4424 result.SetStatus (eReturnStatusFailed);
4425 return false;
4426 }
4427
4428 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4429 if (process)
4430 {
Han Ming Ong84145852012-11-26 20:42:03 +00004431 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00004432 {
Han Ming Ong84145852012-11-26 20:42:03 +00004433 const char *packet_cstr = command.GetArgumentAtIndex(0);
4434 bool send_async = true;
4435 StringExtractorGDBRemote response;
4436 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
4437 result.SetStatus (eReturnStatusSuccessFinishResult);
4438 Stream &output_strm = result.GetOutputStream();
4439 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00004440 std::string &response_str = response.GetStringRef();
4441
Han Ming Ong399289e2013-06-21 19:56:59 +00004442 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00004443 {
4444 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
4445 }
4446
Han Ming Ong84145852012-11-26 20:42:03 +00004447 if (response_str.empty())
4448 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
4449 else
4450 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00004451 }
Greg Clayton02686b82012-10-15 22:42:16 +00004452 }
Greg Clayton998255b2012-10-13 02:07:45 +00004453 return true;
4454 }
4455};
4456
Greg Claytonba4a0a52013-02-01 23:03:47 +00004457class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
4458{
4459private:
4460
4461public:
4462 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
4463 CommandObjectRaw (interpreter,
4464 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00004465 "Send a qRcmd packet through the GDB remote protocol and print the response."
4466 "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 +00004467 NULL)
4468 {
4469 }
4470
4471 ~CommandObjectProcessGDBRemotePacketMonitor ()
4472 {
4473 }
4474
4475 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004476 DoExecute (const char *command, CommandReturnObject &result) override
Greg Claytonba4a0a52013-02-01 23:03:47 +00004477 {
4478 if (command == NULL || command[0] == '\0')
4479 {
4480 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
4481 result.SetStatus (eReturnStatusFailed);
4482 return false;
4483 }
4484
4485 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4486 if (process)
4487 {
4488 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00004489 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00004490 packet.PutBytesAsRawHex8(command, strlen(command));
4491 const char *packet_cstr = packet.GetString().c_str();
4492
4493 bool send_async = true;
4494 StringExtractorGDBRemote response;
4495 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
4496 result.SetStatus (eReturnStatusSuccessFinishResult);
4497 Stream &output_strm = result.GetOutputStream();
4498 output_strm.Printf (" packet: %s\n", packet_cstr);
4499 const std::string &response_str = response.GetStringRef();
4500
4501 if (response_str.empty())
4502 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
4503 else
4504 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
4505 }
4506 return true;
4507 }
4508};
4509
Greg Clayton02686b82012-10-15 22:42:16 +00004510class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
4511{
4512private:
4513
4514public:
4515 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
4516 CommandObjectMultiword (interpreter,
4517 "process plugin packet",
4518 "Commands that deal with GDB remote packets.",
4519 NULL)
4520 {
4521 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
4522 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00004523 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Jason Molenda6076bf42014-05-06 04:34:52 +00004524 LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00004525 }
4526
4527 ~CommandObjectProcessGDBRemotePacket ()
4528 {
4529 }
4530};
Greg Clayton998255b2012-10-13 02:07:45 +00004531
4532class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
4533{
4534public:
4535 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
4536 CommandObjectMultiword (interpreter,
4537 "process plugin",
4538 "A set of commands for operating on a ProcessGDBRemote process.",
4539 "process plugin <subcommand> [<subcommand-options>]")
4540 {
4541 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
4542 }
4543
4544 ~CommandObjectMultiwordProcessGDBRemote ()
4545 {
4546 }
4547};
4548
Greg Clayton998255b2012-10-13 02:07:45 +00004549CommandObject *
4550ProcessGDBRemote::GetPluginCommandObject()
4551{
4552 if (!m_command_sp)
4553 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
4554 return m_command_sp.get();
4555}