blob: 9b8ccd21f729c908c99e79f6314d812c14fc99c7 [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 {
Pavel Labath48fca3b2015-05-15 10:14:51 +00002094 const char *stop_info_desc = stop_info_sp->GetDescription();
2095 if (!stop_info_desc || !stop_info_desc[0])
2096 stop_info_sp->SetDescription (description.c_str());
Greg Clayton3418c852011-08-10 02:10:13 +00002097 }
Greg Claytona658fd22011-06-04 01:26:29 +00002098 else
2099 {
Greg Clayton160c9d82013-05-01 21:54:04 +00002100 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00002101 }
2102 }
2103 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002104 }
2105 return eStateStopped;
2106 }
2107 break;
2108
2109 case 'W':
Todd Fialaff6131a2014-05-19 04:57:23 +00002110 case 'X':
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002111 // process exited
2112 return eStateExited;
2113
2114 default:
2115 break;
2116 }
2117 return eStateInvalid;
2118}
2119
2120void
2121ProcessGDBRemote::RefreshStateAfterStop ()
2122{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002123 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00002124 m_thread_ids.clear();
2125 // Set the thread stop info. It might have a "threads" key whose value is
2126 // a list of all thread IDs in the current process, so m_thread_ids might
2127 // get set.
2128 SetThreadStopInfo (m_last_stop_packet);
2129 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2130 if (m_thread_ids.empty())
2131 {
2132 // No, we need to fetch the thread list manually
2133 UpdateThreadIDList();
2134 }
2135
Ewan Crawford78baa192015-05-13 09:18:18 +00002136 // If we have queried for a default thread id
2137 if (m_initial_tid != LLDB_INVALID_THREAD_ID)
2138 {
2139 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2140 m_initial_tid = LLDB_INVALID_THREAD_ID;
2141 }
2142
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002143 // Let all threads recover from stopping and do any clean up based
2144 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002145 m_thread_list_real.RefreshStateAfterStop();
Greg Clayton9e920902012-04-10 02:25:43 +00002146
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002147}
2148
2149Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002150ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002151{
2152 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002153
Greg Clayton6ed95942011-01-22 07:12:45 +00002154 bool timed_out = false;
2155 Mutex::Locker locker;
Greg Clayton513c26c2011-01-29 07:10:55 +00002156
2157 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002158 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002159 // We are being asked to halt during an attach. We need to just close
2160 // our file handle and debugserver will go away, and we can be done...
2161 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00002162 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002163 else
2164 {
Greg Clayton2687cd12012-03-29 01:55:41 +00002165 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton513c26c2011-01-29 07:10:55 +00002166 {
2167 if (timed_out)
2168 error.SetErrorString("timed out sending interrupt packet");
2169 else
2170 error.SetErrorString("unknown error sending interrupt packet");
2171 }
Greg Clayton2687cd12012-03-29 01:55:41 +00002172
2173 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton513c26c2011-01-29 07:10:55 +00002174 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002175 return error;
2176}
2177
2178Error
Jim Inghamacff8952013-05-02 00:27:30 +00002179ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002180{
2181 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002182 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00002183 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00002184 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2185
Jim Inghamacff8952013-05-02 00:27:30 +00002186 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002187 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002188 {
Jim Inghamacff8952013-05-02 00:27:30 +00002189 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002190 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
2191 else
Jim Inghamacff8952013-05-02 00:27:30 +00002192 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00002193 }
Jim Inghamacff8952013-05-02 00:27:30 +00002194
2195 if (!error.Success())
2196 return error;
2197
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002198 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00002199 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002200
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002201 SetPrivateState (eStateDetached);
2202 ResumePrivateStateThread();
2203
2204 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00002205 return error;
2206}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002207
Jim Ingham43c555d2012-07-04 00:35:43 +00002208
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002209Error
2210ProcessGDBRemote::DoDestroy ()
2211{
2212 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002213 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002214 if (log)
2215 log->Printf ("ProcessGDBRemote::DoDestroy()");
2216
Jim Ingham43c555d2012-07-04 00:35:43 +00002217 // There is a bug in older iOS debugservers where they don't shut down the process
2218 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
2219 // this can cause problems with restarting. So we check to see if any of our threads are stopped
2220 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
2221 // destroy it again.
2222 //
2223 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
2224 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
2225 // the debugservers with this bug are equal. There really should be a better way to test this!
2226 //
2227 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
2228 // get called here to destroy again and we're still at a breakpoint or exception, then we should
2229 // just do the straight-forward kill.
2230 //
2231 // And of course, if we weren't able to stop the process by the time we get here, it isn't
2232 // necessary (or helpful) to do any of this.
2233
2234 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
2235 {
2236 PlatformSP platform_sp = GetTarget().GetPlatform();
2237
2238 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2239 if (platform_sp
2240 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00002241 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00002242 {
2243 if (m_destroy_tried_resuming)
2244 {
2245 if (log)
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002246 log->PutCString ("ProcessGDBRemote::DoDestroy() - Tried resuming to destroy once already, not doing it again.");
Jim Ingham43c555d2012-07-04 00:35:43 +00002247 }
2248 else
2249 {
2250 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
2251 // but we really need it to happen here and it doesn't matter if we do it twice.
2252 m_thread_list.DiscardThreadPlans();
2253 DisableAllBreakpointSites();
2254
2255 bool stop_looks_like_crash = false;
2256 ThreadList &threads = GetThreadList();
2257
2258 {
Jim Ingham45350372012-09-11 00:08:52 +00002259 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002260
2261 size_t num_threads = threads.GetSize();
2262 for (size_t i = 0; i < num_threads; i++)
2263 {
2264 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002265 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002266 StopReason reason = eStopReasonInvalid;
2267 if (stop_info_sp)
2268 reason = stop_info_sp->GetStopReason();
2269 if (reason == eStopReasonBreakpoint
2270 || reason == eStopReasonException)
2271 {
2272 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002273 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
2274 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00002275 stop_info_sp->GetDescription());
2276 stop_looks_like_crash = true;
2277 break;
2278 }
2279 }
2280 }
2281
2282 if (stop_looks_like_crash)
2283 {
2284 if (log)
2285 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
2286 m_destroy_tried_resuming = true;
2287
2288 // If we are going to run again before killing, it would be good to suspend all the threads
2289 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
2290 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
2291 // have to run the risk of letting those threads proceed a bit.
2292
2293 {
Jim Ingham45350372012-09-11 00:08:52 +00002294 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002295
2296 size_t num_threads = threads.GetSize();
2297 for (size_t i = 0; i < num_threads; i++)
2298 {
2299 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002300 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002301 StopReason reason = eStopReasonInvalid;
2302 if (stop_info_sp)
2303 reason = stop_info_sp->GetStopReason();
2304 if (reason != eStopReasonBreakpoint
2305 && reason != eStopReasonException)
2306 {
2307 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002308 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
2309 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00002310 thread_sp->SetResumeState(eStateSuspended);
2311 }
2312 }
2313 }
2314 Resume ();
Jason Molendaede31932015-04-17 05:01:58 +00002315 return Destroy(false);
Jim Ingham43c555d2012-07-04 00:35:43 +00002316 }
2317 }
2318 }
2319 }
2320
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002321 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00002322 int exit_status = SIGABRT;
2323 std::string exit_string;
2324
Greg Clayton6ed95942011-01-22 07:12:45 +00002325 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002326 {
Jim Inghamaab78372011-10-28 01:11:35 +00002327 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00002328 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002329 StringExtractorGDBRemote response;
2330 bool send_async = true;
Tamas Berghammer912800c2015-02-24 10:23:39 +00002331 GDBRemoteCommunication::ScopedTimeout (m_gdb_comm, 3);
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002332
Greg Clayton3dedae12013-12-06 21:45:27 +00002333 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton513c26c2011-01-29 07:10:55 +00002334 {
2335 char packet_cmd = response.GetChar(0);
2336
2337 if (packet_cmd == 'W' || packet_cmd == 'X')
2338 {
Jim Inghameac0aa42014-02-21 22:36:11 +00002339#if defined(__APPLE__)
Jim Ingham9d67cc52014-02-21 22:35:29 +00002340 // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off
2341 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill
2342 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns
2343 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap
2344 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of
2345 // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2346 // Anyway, so call waitpid here to finally reap it.
2347 PlatformSP platform_sp(GetTarget().GetPlatform());
2348 if (platform_sp && platform_sp->IsHost())
2349 {
2350 int status;
2351 ::pid_t reap_pid;
2352 reap_pid = waitpid (GetID(), &status, WNOHANG);
2353 if (log)
2354 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2355 }
2356#endif
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002357 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002358 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00002359 exit_status = response.GetHexU8();
2360 }
2361 else
2362 {
2363 if (log)
2364 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2365 exit_string.assign("got unexpected response to k packet: ");
2366 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00002367 }
2368 }
2369 else
2370 {
Jim Inghambabfc382012-06-06 00:32:39 +00002371 if (log)
2372 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2373 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00002374 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002375 }
Jim Inghambabfc382012-06-06 00:32:39 +00002376 else
2377 {
2378 if (log)
Ed Masteb3a53332014-03-17 17:05:22 +00002379 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching");
Jim Inghamcfc09352012-07-27 23:57:19 +00002380 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00002381 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002382 }
Jim Inghambabfc382012-06-06 00:32:39 +00002383 else
2384 {
2385 // If we missed setting the exit status on the way out, do it here.
2386 // NB set exit status can be called multiple times, the first one sets the status.
2387 exit_string.assign("destroying when not connected to debugserver");
2388 }
2389
2390 SetExitStatus(exit_status, exit_string.c_str());
2391
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002392 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002393 KillDebugserverProcess ();
2394 return error;
2395}
2396
Greg Clayton8cda7f02013-05-21 21:55:59 +00002397void
2398ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2399{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00002400 Mutex::Locker locker (m_last_stop_packet_mutex);
Greg Clayton8cda7f02013-05-21 21:55:59 +00002401 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2402 if (did_exec)
2403 {
2404 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2405 if (log)
2406 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2407
2408 m_thread_list_real.Clear();
2409 m_thread_list.Clear();
2410 BuildDynamicRegisterInfo (true);
2411 m_gdb_comm.ResetDiscoverableSettings();
2412 }
2413 m_last_stop_packet = response;
2414}
2415
2416
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002417//------------------------------------------------------------------
2418// Process Queries
2419//------------------------------------------------------------------
2420
2421bool
2422ProcessGDBRemote::IsAlive ()
2423{
Greg Clayton10177aa2010-12-08 05:08:21 +00002424 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002425}
2426
2427addr_t
2428ProcessGDBRemote::GetImageInfoAddress()
2429{
Aidan Doddsc0c83852015-05-08 09:36:31 +00002430 // request the link map address via the $qShlibInfoAddr packet
2431 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2432
2433 // the loaded module list can also provides a link map address
2434 if (addr == LLDB_INVALID_ADDRESS)
2435 {
2436 GDBLoadedModuleInfoList list;
2437 if (GetLoadedModuleList (list).Success())
2438 addr = list.m_link_map;
2439 }
2440
2441 return addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002442}
2443
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002444//------------------------------------------------------------------
2445// Process Memory
2446//------------------------------------------------------------------
2447size_t
2448ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2449{
Jason Molenda6076bf42014-05-06 04:34:52 +00002450 GetMaxMemorySize ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002451 if (size > m_max_memory_size)
2452 {
2453 // Keep memory read sizes down to a sane limit. This function will be
2454 // called multiple times in order to complete the task by
2455 // lldb_private::Process so it is ok to do this.
2456 size = m_max_memory_size;
2457 }
2458
2459 char packet[64];
Jason Molenda6076bf42014-05-06 04:34:52 +00002460 int packet_len;
2461 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2462 if (binary_memory_read)
2463 {
2464 packet_len = ::snprintf (packet, sizeof(packet), "x0x%" PRIx64 ",0x%" PRIx64, (uint64_t)addr, (uint64_t)size);
2465 }
2466 else
2467 {
2468 packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
2469 }
Andy Gibbsa297a972013-06-19 19:04:53 +00002470 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002471 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002472 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002473 {
Greg Clayton576d8832011-03-22 04:00:09 +00002474 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002475 {
2476 error.Clear();
Jason Molenda6076bf42014-05-06 04:34:52 +00002477 if (binary_memory_read)
2478 {
2479 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any
2480 // 0x7d character escaping that was present in the packet
2481
2482 size_t data_received_size = response.GetBytesLeft();
2483 if (data_received_size > size)
2484 {
2485 // Don't write past the end of BUF if the remote debug server gave us too
2486 // much data for some reason.
2487 data_received_size = size;
2488 }
2489 memcpy (buf, response.GetStringRef().data(), data_received_size);
2490 return data_received_size;
2491 }
2492 else
2493 {
2494 return response.GetHexBytes(buf, size, '\xdd');
2495 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002496 }
Greg Clayton576d8832011-03-22 04:00:09 +00002497 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002498 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002499 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002500 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002501 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002502 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002503 }
2504 else
2505 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002506 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002507 }
2508 return 0;
2509}
2510
2511size_t
2512ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2513{
Jason Molenda6076bf42014-05-06 04:34:52 +00002514 GetMaxMemorySize ();
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002515 if (size > m_max_memory_size)
2516 {
2517 // Keep memory read sizes down to a sane limit. This function will be
2518 // called multiple times in order to complete the task by
2519 // lldb_private::Process so it is ok to do this.
2520 size = m_max_memory_size;
2521 }
2522
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002523 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00002524 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Clayton7fb56d02011-02-01 01:31:41 +00002525 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002526 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002527 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002528 {
Greg Clayton576d8832011-03-22 04:00:09 +00002529 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002530 {
2531 error.Clear();
2532 return size;
2533 }
Greg Clayton576d8832011-03-22 04:00:09 +00002534 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002535 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002536 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002537 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002538 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002539 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 +00002540 }
2541 else
2542 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002543 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002544 }
2545 return 0;
2546}
2547
2548lldb::addr_t
2549ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2550{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00002551 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_EXPRESSIONS));
Greg Clayton2a48f522011-05-14 01:50:35 +00002552 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2553
Greg Clayton70b57652011-05-15 01:25:55 +00002554 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton2a48f522011-05-14 01:50:35 +00002555 switch (supported)
2556 {
2557 case eLazyBoolCalculate:
2558 case eLazyBoolYes:
2559 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2560 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2561 return allocated_addr;
2562
2563 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002564 // Call mmap() to create memory in the inferior..
2565 unsigned prot = 0;
2566 if (permissions & lldb::ePermissionsReadable)
2567 prot |= eMmapProtRead;
2568 if (permissions & lldb::ePermissionsWritable)
2569 prot |= eMmapProtWrite;
2570 if (permissions & lldb::ePermissionsExecutable)
2571 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00002572
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002573 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2574 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2575 m_addr_to_mmap_size[allocated_addr] = size;
2576 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002577 {
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002578 allocated_addr = LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00002579 if (log)
2580 log->Printf ("ProcessGDBRemote::%s no direct stub support for memory allocation, and InferiorCallMmap also failed - is stub missing register context save/restore capability?", __FUNCTION__);
2581 }
Greg Clayton2a48f522011-05-14 01:50:35 +00002582 break;
2583 }
2584
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002585 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00002586 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002587 else
2588 error.Clear();
2589 return allocated_addr;
2590}
2591
2592Error
Greg Clayton46fb5582011-11-18 07:03:08 +00002593ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2594 MemoryRegionInfo &region_info)
2595{
2596
2597 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2598 return error;
2599}
2600
2601Error
Johnny Chen64637202012-05-23 21:09:52 +00002602ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2603{
2604
2605 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2606 return error;
2607}
2608
2609Error
Enrico Granataf04a2192012-07-13 23:18:48 +00002610ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2611{
2612 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2613 return error;
2614}
2615
2616Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002617ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2618{
2619 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00002620 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2621
2622 switch (supported)
2623 {
2624 case eLazyBoolCalculate:
2625 // We should never be deallocating memory without allocating memory
2626 // first so we should never get eLazyBoolCalculate
2627 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2628 break;
2629
2630 case eLazyBoolYes:
2631 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00002632 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002633 break;
2634
2635 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002636 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00002637 {
2638 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002639 if (pos != m_addr_to_mmap_size.end() &&
2640 InferiorCallMunmap(this, addr, pos->second))
2641 m_addr_to_mmap_size.erase (pos);
2642 else
Daniel Malead01b2952012-11-29 21:49:15 +00002643 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002644 }
2645 break;
2646 }
2647
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002648 return error;
2649}
2650
2651
2652//------------------------------------------------------------------
2653// Process STDIO
2654//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002655size_t
2656ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2657{
2658 if (m_stdio_communication.IsConnected())
2659 {
2660 ConnectionStatus status;
2661 m_stdio_communication.Write(src, src_len, status, NULL);
2662 }
Vince Harrondf3f00f2015-02-10 21:09:04 +00002663 else if (m_stdin_forward)
Vince Harrone0be4252015-02-06 18:32:57 +00002664 {
2665 m_gdb_comm.SendStdinNotification(src, src_len);
2666 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002667 return 0;
2668}
2669
2670Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002671ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002672{
2673 Error error;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002674 assert(bp_site != NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002675
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002676 // Get logging info
2677 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002678 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002679
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002680 // Get the breakpoint address
2681 const addr_t addr = bp_site->GetLoadAddress();
2682
2683 // Log that a breakpoint was requested
2684 if (log)
2685 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
2686
2687 // Breakpoint already exists and is enabled
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002688 if (bp_site->IsEnabled())
2689 {
2690 if (log)
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002691 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 +00002692 return error;
2693 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002694
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002695 // Get the software breakpoint trap opcode size
2696 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2697
2698 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
2699 // is supported by the remote stub. These are set to true by default, and later set to false
2700 // only after we receive an unimplemented response when sending a breakpoint packet. This means
2701 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
2702 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
2703 // indicates if the user specifically asked for hardware breakpoints. If true then we will
2704 // skip over software breakpoints.
2705 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
2706 {
2707 // Try to send off a software breakpoint packet ($Z0)
2708 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002709 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002710 // The breakpoint was placed successfully
2711 bp_site->SetEnabled(true);
2712 bp_site->SetType(BreakpointSite::eExternal);
Greg Claytoneb023e72013-10-11 19:48:25 +00002713 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002714 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002715
2716 // SendGDBStoppointTypePacket() will return an error if it was unable to set this
2717 // breakpoint. We need to differentiate between a error specific to placing this breakpoint
2718 // or if we have learned that this breakpoint type is unsupported. To do this, we
2719 // must test the support boolean for this breakpoint type to see if it now indicates that
2720 // this breakpoint type is unsupported. If they are still supported then we should return
2721 // with the error code. If they are now unsupported, then we would like to fall through
2722 // and try another form of breakpoint.
2723 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
2724 return error;
2725
2726 // We reach here when software breakpoints have been found to be unsupported. For future
2727 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
2728 // known not to be supported.
2729 if (log)
2730 log->Printf("Software breakpoints are unsupported");
2731
2732 // So we will fall through and try a hardware breakpoint
2733 }
2734
2735 // The process of setting a hardware breakpoint is much the same as above. We check the
2736 // supported boolean for this breakpoint type, and if it is thought to be supported then we
2737 // will try to set this breakpoint with a hardware breakpoint.
2738 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
2739 {
2740 // Try to send off a hardware breakpoint packet ($Z1)
2741 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002742 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002743 // The breakpoint was placed successfully
2744 bp_site->SetEnabled(true);
2745 bp_site->SetType(BreakpointSite::eHardware);
2746 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002747 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002748
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002749 // Check if the error was something other then an unsupported breakpoint type
2750 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
2751 {
2752 // Unable to set this hardware breakpoint
2753 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
2754 return error;
2755 }
2756
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002757 // We will reach here when the stub gives an unsupported response to a hardware breakpoint
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002758 if (log)
2759 log->Printf("Hardware breakpoints are unsupported");
2760
2761 // Finally we will falling through to a #trap style breakpoint
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002762 }
2763
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002764 // Don't fall through when hardware breakpoints were specifically requested
2765 if (bp_site->HardwareRequired())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002766 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002767 error.SetErrorString("hardware breakpoints are not supported");
2768 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002769 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002770
2771 // As a last resort we want to place a manual breakpoint. An instruction
2772 // is placed into the process memory using memory write packets.
2773 return EnableSoftwareBreakpoint(bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002774}
2775
2776Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002777ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002778{
2779 Error error;
2780 assert (bp_site != NULL);
2781 addr_t addr = bp_site->GetLoadAddress();
2782 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00002783 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002784 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002785 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002786
2787 if (bp_site->IsEnabled())
2788 {
2789 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2790
Greg Clayton8b82f082011-04-12 05:54:46 +00002791 BreakpointSite::Type bp_type = bp_site->GetType();
2792 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002793 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002794 case BreakpointSite::eSoftware:
2795 error = DisableSoftwareBreakpoint (bp_site);
2796 break;
2797
2798 case BreakpointSite::eHardware:
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002799 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00002800 error.SetErrorToGenericError();
2801 break;
2802
2803 case BreakpointSite::eExternal:
Jim Inghama04ef752014-03-07 11:18:02 +00002804 {
2805 GDBStoppointType stoppoint_type;
2806 if (bp_site->IsHardware())
2807 stoppoint_type = eBreakpointHardware;
2808 else
2809 stoppoint_type = eBreakpointSoftware;
2810
2811 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00002812 error.SetErrorToGenericError();
Jim Inghama04ef752014-03-07 11:18:02 +00002813 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002814 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002815 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002816 if (error.Success())
2817 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002818 }
2819 else
2820 {
2821 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002822 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 +00002823 return error;
2824 }
2825
2826 if (error.Success())
2827 error.SetErrorToGenericError();
2828 return error;
2829}
2830
Johnny Chen11309a32011-09-06 22:38:36 +00002831// Pre-requisite: wp != NULL.
2832static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00002833GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00002834{
2835 assert(wp);
2836 bool watch_read = wp->WatchpointRead();
2837 bool watch_write = wp->WatchpointWrite();
2838
2839 // watch_read and watch_write cannot both be false.
2840 assert(watch_read || watch_write);
2841 if (watch_read && watch_write)
2842 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00002843 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00002844 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00002845 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00002846 return eWatchpointWrite;
2847}
2848
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002849Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002850ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002851{
2852 Error error;
2853 if (wp)
2854 {
2855 user_id_t watchID = wp->GetID();
2856 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00002857 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002858 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002859 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002860 if (wp->IsEnabled())
2861 {
2862 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002863 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 +00002864 return error;
2865 }
Johnny Chen11309a32011-09-06 22:38:36 +00002866
2867 GDBStoppointType type = GetGDBStoppointType(wp);
2868 // Pass down an appropriate z/Z packet...
2869 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002870 {
Johnny Chen11309a32011-09-06 22:38:36 +00002871 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2872 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002873 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002874 return error;
2875 }
2876 else
2877 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002878 }
Johnny Chen11309a32011-09-06 22:38:36 +00002879 else
2880 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002881 }
2882 else
2883 {
Johnny Chen01a67862011-10-14 00:42:25 +00002884 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002885 }
2886 if (error.Success())
2887 error.SetErrorToGenericError();
2888 return error;
2889}
2890
2891Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002892ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002893{
2894 Error error;
2895 if (wp)
2896 {
2897 user_id_t watchID = wp->GetID();
2898
Greg Clayton5160ce52013-03-27 23:08:40 +00002899 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002900
2901 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00002902
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002903 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002904 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002905
Johnny Chen11309a32011-09-06 22:38:36 +00002906 if (!wp->IsEnabled())
2907 {
2908 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002909 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 +00002910 // See also 'class WatchpointSentry' within StopInfo.cpp.
2911 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2912 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00002913 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002914 return error;
2915 }
2916
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002917 if (wp->IsHardware())
2918 {
Johnny Chen11309a32011-09-06 22:38:36 +00002919 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002920 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00002921 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2922 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002923 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002924 return error;
2925 }
2926 else
2927 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002928 }
2929 // TODO: clear software watchpoints if we implement them
2930 }
2931 else
2932 {
Johnny Chen01a67862011-10-14 00:42:25 +00002933 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002934 }
2935 if (error.Success())
2936 error.SetErrorToGenericError();
2937 return error;
2938}
2939
2940void
2941ProcessGDBRemote::Clear()
2942{
2943 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002944 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002945 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002946}
2947
2948Error
2949ProcessGDBRemote::DoSignal (int signo)
2950{
2951 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002952 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002953 if (log)
2954 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2955
2956 if (!m_gdb_comm.SendAsyncSignal (signo))
2957 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2958 return error;
2959}
2960
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002961Error
Greg Clayton91a9b2472013-12-04 19:19:12 +00002962ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002963{
2964 Error error;
2965 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2966 {
2967 // If we locate debugserver, keep that located version around
2968 static FileSpec g_debugserver_file_spec;
2969
Han Ming Ong84647042012-02-25 01:07:38 +00002970 ProcessLaunchInfo debugserver_launch_info;
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00002971 // Make debugserver run in its own session so signals generated by
2972 // special terminal key sequences (^C) don't affect debugserver.
2973 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
2974
Greg Clayton91a9b2472013-12-04 19:19:12 +00002975 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2976 debugserver_launch_info.SetUserID(process_info.GetUserID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002977
Todd Fiala013434e2014-07-09 01:29:05 +00002978#if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__) || defined (__aarch64__))
Greg Claytonfda4fab2014-01-10 22:24:11 +00002979 // On iOS, still do a local connection using a random port
Greg Clayton16810922014-02-27 19:38:18 +00002980 const char *hostname = "127.0.0.1";
Greg Claytonfda4fab2014-01-10 22:24:11 +00002981 uint16_t port = get_random_port ();
2982#else
2983 // Set hostname being NULL to do the reverse connect where debugserver
2984 // will bind to port zero and it will communicate back to us the port
2985 // that we will connect to
2986 const char *hostname = NULL;
2987 uint16_t port = 0;
2988#endif
2989
2990 error = m_gdb_comm.StartDebugserverProcess (hostname,
2991 port,
Greg Clayton00fe87b2013-12-05 22:58:22 +00002992 debugserver_launch_info,
2993 port);
Greg Clayton91a9b2472013-12-04 19:19:12 +00002994
2995 if (error.Success ())
2996 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002997 else
Greg Clayton91a9b2472013-12-04 19:19:12 +00002998 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002999
3000 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3001 StartAsyncThread ();
Greg Clayton91a9b2472013-12-04 19:19:12 +00003002
3003 if (error.Fail())
3004 {
3005 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
3006
3007 if (log)
3008 log->Printf("failed to start debugserver process: %s", error.AsCString());
3009 return error;
3010 }
3011
Greg Clayton00fe87b2013-12-05 22:58:22 +00003012 if (m_gdb_comm.IsConnected())
3013 {
3014 // Finish the connection process by doing the handshake without connecting (send NULL URL)
3015 ConnectToDebugserver (NULL);
3016 }
3017 else
3018 {
Greg Claytonfda4fab2014-01-10 22:24:11 +00003019 StreamString connect_url;
3020 connect_url.Printf("connect://%s:%u", hostname, port);
3021 error = ConnectToDebugserver (connect_url.GetString().c_str());
Greg Clayton00fe87b2013-12-05 22:58:22 +00003022 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00003023
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003024 }
3025 return error;
3026}
3027
3028bool
3029ProcessGDBRemote::MonitorDebugserverProcess
3030(
3031 void *callback_baton,
3032 lldb::pid_t debugserver_pid,
Greg Claytone4e45922011-11-16 05:37:56 +00003033 bool exited, // True if the process did exit
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003034 int signo, // Zero for no signal
3035 int exit_status // Exit value of process if signal is zero
3036)
3037{
Greg Claytone4e45922011-11-16 05:37:56 +00003038 // The baton is a "ProcessGDBRemote *". Now this class might be gone
3039 // and might not exist anymore, so we need to carefully try to get the
3040 // target for this process first since we have a race condition when
3041 // we are done running between getting the notice that the inferior
3042 // process has died and the debugserver that was debugging this process.
3043 // In our test suite, we are also continually running process after
3044 // process, so we must be very careful to make sure:
3045 // 1 - process object hasn't been deleted already
3046 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003047
3048 // "debugserver_pid" argument passed in is the process ID for
3049 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00003050 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003051
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003052 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton6779606a2011-01-22 23:43:18 +00003053
Greg Claytone4e45922011-11-16 05:37:56 +00003054 // Get a shared pointer to the target that has a matching process pointer.
3055 // This target could be gone, or the target could already have a new process
3056 // object inside of it
3057 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
3058
Greg Clayton6779606a2011-01-22 23:43:18 +00003059 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003060 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 +00003061
Greg Claytone4e45922011-11-16 05:37:56 +00003062 if (target_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003063 {
Greg Claytone4e45922011-11-16 05:37:56 +00003064 // We found a process in a target that matches, but another thread
3065 // might be in the process of launching a new process that will
3066 // soon replace it, so get a shared pointer to the process so we
3067 // can keep it alive.
3068 ProcessSP process_sp (target_sp->GetProcessSP());
3069 // Now we have a shared pointer to the process that can't go away on us
3070 // so we now make sure it was the same as the one passed in, and also make
3071 // sure that our previous "process *" didn't get deleted and have a new
3072 // "process *" created in its place with the same pointer. To verify this
3073 // we make sure the process has our debugserver process ID. If we pass all
3074 // of these tests, then we are sure that this process is the one we were
3075 // looking for.
3076 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003077 {
Greg Claytone4e45922011-11-16 05:37:56 +00003078 // Sleep for a half a second to make sure our inferior process has
3079 // time to set its exit status before we set it incorrectly when
3080 // both the debugserver and the inferior process shut down.
3081 usleep (500000);
3082 // If our process hasn't yet exited, debugserver might have died.
3083 // If the process did exit, the we are reaping it.
3084 const StateType state = process->GetState();
3085
3086 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
3087 state != eStateInvalid &&
3088 state != eStateUnloaded &&
3089 state != eStateExited &&
3090 state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003091 {
Greg Claytone4e45922011-11-16 05:37:56 +00003092 char error_str[1024];
3093 if (signo)
3094 {
3095 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
3096 if (signal_cstr)
3097 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3098 else
3099 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
3100 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003101 else
Greg Claytone4e45922011-11-16 05:37:56 +00003102 {
3103 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
3104 }
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003105
Greg Claytone4e45922011-11-16 05:37:56 +00003106 process->SetExitStatus (-1, error_str);
3107 }
3108 // Debugserver has exited we need to let our ProcessGDBRemote
3109 // know that it no longer has a debugserver instance
3110 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003111 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003112 }
3113 return true;
3114}
3115
3116void
3117ProcessGDBRemote::KillDebugserverProcess ()
3118{
Greg Claytonfbb76342013-11-20 21:07:01 +00003119 m_gdb_comm.Disconnect();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003120 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3121 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003122 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003123 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3124 }
3125}
3126
3127void
3128ProcessGDBRemote::Initialize()
3129{
Davide Italianoc8d69822015-04-03 04:24:32 +00003130 static std::once_flag g_once_flag;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003131
Davide Italianoc8d69822015-04-03 04:24:32 +00003132 std::call_once(g_once_flag, []()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003133 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003134 PluginManager::RegisterPlugin (GetPluginNameStatic(),
3135 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00003136 CreateInstance,
3137 DebuggerInitialize);
Davide Italianoc8d69822015-04-03 04:24:32 +00003138 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003139}
3140
Greg Clayton7f982402013-07-15 22:54:20 +00003141void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003142ProcessGDBRemote::DebuggerInitialize (Debugger &debugger)
Greg Clayton7f982402013-07-15 22:54:20 +00003143{
3144 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
3145 {
3146 const bool is_global_setting = true;
3147 PluginManager::CreateSettingForProcessPlugin (debugger,
3148 GetGlobalPluginProperties()->GetValueProperties(),
3149 ConstString ("Properties for the gdb-remote process plug-in."),
3150 is_global_setting);
3151 }
3152}
3153
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003154bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003155ProcessGDBRemote::StartAsyncThread ()
3156{
Greg Clayton5160ce52013-03-27 23:08:40 +00003157 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003158
3159 if (log)
3160 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003161
3162 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003163 if (!m_async_thread.IsJoinable())
Jim Ingham455fa5c2012-11-01 01:15:33 +00003164 {
3165 // Create a thread that watches our internal state and controls which
3166 // events make it to clients (into the DCProcess event queue).
Zachary Turner39de3112014-09-09 20:54:56 +00003167
3168 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003169 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003170 else if (log)
3171 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was already running.", __FUNCTION__);
Zachary Turner39de3112014-09-09 20:54:56 +00003172
Zachary Turneracee96a2014-09-23 18:32:09 +00003173 return m_async_thread.IsJoinable();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003174}
3175
3176void
3177ProcessGDBRemote::StopAsyncThread ()
3178{
Greg Clayton5160ce52013-03-27 23:08:40 +00003179 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003180
3181 if (log)
3182 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
3183
Jim Ingham455fa5c2012-11-01 01:15:33 +00003184 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003185 if (m_async_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003186 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00003187 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
3188
3189 // This will shut down the async thread.
3190 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3191
3192 // Stop the stdio thread
Zachary Turner39de3112014-09-09 20:54:56 +00003193 m_async_thread.Join(nullptr);
Pavel Labatha55a9532015-03-11 09:53:42 +00003194 m_async_thread.Reset();
Jim Ingham455fa5c2012-11-01 01:15:33 +00003195 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003196 else if (log)
3197 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003198}
3199
3200
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003201thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003202ProcessGDBRemote::AsyncThread (void *arg)
3203{
3204 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
3205
Greg Clayton5160ce52013-03-27 23:08:40 +00003206 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003207 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003208 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003209
3210 Listener listener ("ProcessGDBRemote::AsyncThread");
3211 EventSP event_sp;
3212 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
3213 eBroadcastBitAsyncThreadShouldExit;
3214
3215 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
3216 {
Greg Clayton71337622011-02-24 22:24:29 +00003217 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
3218
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003219 bool done = false;
3220 while (!done)
3221 {
3222 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003223 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003224 if (listener.WaitForEvent (NULL, event_sp))
3225 {
3226 const uint32_t event_type = event_sp->GetType();
Greg Clayton71337622011-02-24 22:24:29 +00003227 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003228 {
Greg Clayton71337622011-02-24 22:24:29 +00003229 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003230 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 +00003231
Greg Clayton71337622011-02-24 22:24:29 +00003232 switch (event_type)
3233 {
3234 case eBroadcastBitAsyncContinue:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003235 {
Greg Clayton71337622011-02-24 22:24:29 +00003236 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003237
Greg Clayton71337622011-02-24 22:24:29 +00003238 if (continue_packet)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003239 {
Greg Clayton71337622011-02-24 22:24:29 +00003240 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
3241 const size_t continue_cstr_len = continue_packet->GetByteSize ();
3242 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003243 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003244
Greg Clayton71337622011-02-24 22:24:29 +00003245 if (::strstr (continue_cstr, "vAttach") == NULL)
3246 process->SetPrivateState(eStateRunning);
3247 StringExtractorGDBRemote response;
3248 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003249
Greg Clayton0772ded2012-05-16 02:48:06 +00003250 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
3251 // The thread ID list might be contained within the "response", or the stop reply packet that
3252 // caused the stop. So clear it now before we give the stop reply packet to the process
3253 // using the process->SetLastStopPacket()...
3254 process->ClearThreadIDList ();
3255
Greg Clayton71337622011-02-24 22:24:29 +00003256 switch (stop_state)
3257 {
3258 case eStateStopped:
3259 case eStateCrashed:
3260 case eStateSuspended:
Greg Clayton09c3e3d2011-12-06 04:51:14 +00003261 process->SetLastStopPacket (response);
Greg Clayton71337622011-02-24 22:24:29 +00003262 process->SetPrivateState (stop_state);
3263 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003264
Greg Clayton71337622011-02-24 22:24:29 +00003265 case eStateExited:
Jason Molendaa3329782014-03-29 18:54:20 +00003266 {
Greg Clayton09c3e3d2011-12-06 04:51:14 +00003267 process->SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00003268 process->ClearThreadIDList();
Greg Clayton71337622011-02-24 22:24:29 +00003269 response.SetFilePos(1);
Jason Molendaa3329782014-03-29 18:54:20 +00003270
3271 int exit_status = response.GetHexU8();
3272 const char *desc_cstr = NULL;
3273 StringExtractor extractor;
3274 std::string desc_string;
3275 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';')
3276 {
3277 std::string desc_token;
3278 while (response.GetNameColonValue (desc_token, desc_string))
3279 {
3280 if (desc_token == "description")
3281 {
3282 extractor.GetStringRef().swap(desc_string);
3283 extractor.SetFilePos(0);
3284 extractor.GetHexByteString (desc_string);
3285 desc_cstr = desc_string.c_str();
3286 }
3287 }
3288 }
3289 process->SetExitStatus(exit_status, desc_cstr);
Greg Clayton71337622011-02-24 22:24:29 +00003290 done = true;
3291 break;
Jason Molendaa3329782014-03-29 18:54:20 +00003292 }
Greg Clayton71337622011-02-24 22:24:29 +00003293 case eStateInvalid:
3294 process->SetExitStatus(-1, "lost connection");
3295 break;
3296
3297 default:
3298 process->SetPrivateState (stop_state);
3299 break;
3300 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003301 }
3302 }
Greg Clayton71337622011-02-24 22:24:29 +00003303 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003304
Greg Clayton71337622011-02-24 22:24:29 +00003305 case eBroadcastBitAsyncThreadShouldExit:
3306 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003307 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Clayton71337622011-02-24 22:24:29 +00003308 done = true;
3309 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003310
Greg Clayton71337622011-02-24 22:24:29 +00003311 default:
3312 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003313 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 +00003314 done = true;
3315 break;
3316 }
3317 }
3318 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
3319 {
3320 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
3321 {
3322 process->SetExitStatus (-1, "lost connection");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003323 done = true;
Greg Clayton71337622011-02-24 22:24:29 +00003324 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003325 }
3326 }
3327 else
3328 {
3329 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003330 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 +00003331 done = true;
3332 }
3333 }
3334 }
3335
3336 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003337 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003338
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003339 return NULL;
3340}
3341
Greg Claytone996fd32011-03-08 22:40:15 +00003342//uint32_t
3343//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3344//{
3345// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
3346// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
3347// if (m_local_debugserver)
3348// {
3349// return Host::ListProcessesMatchingName (name, matches, pids);
3350// }
3351// else
3352// {
3353// // FIXME: Implement talking to the remote debugserver.
3354// return 0;
3355// }
3356//
3357//}
3358//
Jim Ingham1c823b42011-01-22 01:33:44 +00003359bool
3360ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003361 StoppointCallbackContext *context,
Jim Ingham1c823b42011-01-22 01:33:44 +00003362 lldb::user_id_t break_id,
3363 lldb::user_id_t break_loc_id)
3364{
3365 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3366 // run so I can stop it if that's what I want to do.
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003367 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00003368 if (log)
3369 log->Printf("Hit New Thread Notification breakpoint.");
3370 return false;
3371}
3372
3373
3374bool
3375ProcessGDBRemote::StartNoticingNewThreads()
3376{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003377 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00003378 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003379 {
Greg Clayton4116e932012-05-15 02:33:01 +00003380 if (log && log->GetVerbose())
3381 log->Printf("Enabled noticing new thread breakpoint.");
3382 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003383 }
Greg Clayton4116e932012-05-15 02:33:01 +00003384 else
Jim Ingham1c823b42011-01-22 01:33:44 +00003385 {
Greg Clayton4116e932012-05-15 02:33:01 +00003386 PlatformSP platform_sp (m_target.GetPlatform());
3387 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003388 {
Greg Clayton4116e932012-05-15 02:33:01 +00003389 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3390 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003391 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00003392 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00003393 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3394 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003395 }
3396 else
3397 {
3398 if (log)
3399 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00003400 }
3401 }
3402 }
Greg Clayton4116e932012-05-15 02:33:01 +00003403 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00003404}
3405
3406bool
3407ProcessGDBRemote::StopNoticingNewThreads()
3408{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003409 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00003410 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00003411 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00003412
3413 if (m_thread_create_bp_sp)
3414 m_thread_create_bp_sp->SetEnabled(false);
3415
Jim Ingham1c823b42011-01-22 01:33:44 +00003416 return true;
3417}
3418
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003419DynamicLoader *
Jason Molenda5e8534e2012-10-03 01:29:34 +00003420ProcessGDBRemote::GetDynamicLoader ()
3421{
3422 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00003423 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00003424 return m_dyld_ap.get();
3425}
Jim Ingham1c823b42011-01-22 01:33:44 +00003426
Jason Molendaa3329782014-03-29 18:54:20 +00003427Error
3428ProcessGDBRemote::SendEventData(const char *data)
3429{
3430 int return_value;
3431 bool was_supported;
3432
3433 Error error;
3434
3435 return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported);
3436 if (return_value != 0)
3437 {
3438 if (!was_supported)
3439 error.SetErrorString("Sending events is not supported for this process.");
3440 else
3441 error.SetErrorStringWithFormat("Error sending event data: %d.", return_value);
3442 }
3443 return error;
3444}
3445
Steve Pucci03904ac2014-03-04 23:18:46 +00003446const DataBufferSP
3447ProcessGDBRemote::GetAuxvData()
3448{
3449 DataBufferSP buf;
3450 if (m_gdb_comm.GetQXferAuxvReadSupported())
3451 {
3452 std::string response_string;
3453 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success)
3454 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length()));
3455 }
3456 return buf;
3457}
3458
Jason Molenda705b1802014-06-13 02:37:02 +00003459StructuredData::ObjectSP
3460ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid)
3461{
3462 StructuredData::ObjectSP object_sp;
3463
3464 if (m_gdb_comm.GetThreadExtendedInfoSupported())
3465 {
3466 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3467 SystemRuntime *runtime = GetSystemRuntime();
3468 if (runtime)
3469 {
3470 runtime->AddThreadExtendedInfoPacketHints (args_dict);
3471 }
3472 args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid);
3473
3474 StreamString packet;
3475 packet << "jThreadExtendedInfo:";
3476 args_dict->Dump (packet);
3477
3478 // FIXME the final character of a JSON dictionary, '}', is the escape
3479 // character in gdb-remote binary mode. lldb currently doesn't escape
3480 // these characters in its packet output -- so we add the quoted version
3481 // of the } character here manually in case we talk to a debugserver which
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003482 // un-escapes the characters at packet read time.
Jason Molenda705b1802014-06-13 02:37:02 +00003483 packet << (char) (0x7d ^ 0x20);
3484
3485 StringExtractorGDBRemote response;
3486 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
3487 {
3488 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
3489 if (response_type == StringExtractorGDBRemote::eResponse)
3490 {
3491 if (!response.Empty())
3492 {
3493 // The packet has already had the 0x7d xor quoting stripped out at the
3494 // GDBRemoteCommunication packet receive level.
3495 object_sp = StructuredData::ParseJSON (response.GetStringRef());
3496 }
3497 }
3498 }
3499 }
3500 return object_sp;
3501}
3502
Jason Molenda6076bf42014-05-06 04:34:52 +00003503// Establish the largest memory read/write payloads we should use.
3504// If the remote stub has a max packet size, stay under that size.
3505//
3506// If the remote stub's max packet size is crazy large, use a
3507// reasonable largeish default.
3508//
3509// If the remote stub doesn't advertise a max packet size, use a
3510// conservative default.
3511
3512void
3513ProcessGDBRemote::GetMaxMemorySize()
3514{
3515 const uint64_t reasonable_largeish_default = 128 * 1024;
3516 const uint64_t conservative_default = 512;
3517
3518 if (m_max_memory_size == 0)
3519 {
3520 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
3521 if (stub_max_size != UINT64_MAX && stub_max_size != 0)
3522 {
3523 // Save the stub's claimed maximum packet size
3524 m_remote_stub_max_memory_size = stub_max_size;
3525
3526 // Even if the stub says it can support ginormous packets,
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003527 // don't exceed our reasonable largeish default packet size.
Jason Molenda6076bf42014-05-06 04:34:52 +00003528 if (stub_max_size > reasonable_largeish_default)
3529 {
3530 stub_max_size = reasonable_largeish_default;
3531 }
3532
3533 m_max_memory_size = stub_max_size;
3534 }
3535 else
3536 {
3537 m_max_memory_size = conservative_default;
3538 }
3539 }
3540}
3541
3542void
3543ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max)
3544{
3545 if (user_specified_max != 0)
3546 {
3547 GetMaxMemorySize ();
3548
3549 if (m_remote_stub_max_memory_size != 0)
3550 {
3551 if (m_remote_stub_max_memory_size < user_specified_max)
3552 {
3553 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a packet size too big, go as big
3554 // as the remote stub says we can go.
3555 }
3556 else
3557 {
3558 m_max_memory_size = user_specified_max; // user's packet size is good
3559 }
3560 }
3561 else
3562 {
3563 m_max_memory_size = user_specified_max; // user's packet size is probably fine
3564 }
3565 }
3566}
3567
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003568bool
3569ProcessGDBRemote::GetModuleSpec(const FileSpec& module_file_spec,
3570 const ArchSpec& arch,
3571 ModuleSpec &module_spec)
3572{
3573 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PLATFORM);
3574
3575 if (!m_gdb_comm.GetModuleInfo (module_file_spec, arch, module_spec))
3576 {
3577 if (log)
3578 log->Printf ("ProcessGDBRemote::%s - failed to get module info for %s:%s",
3579 __FUNCTION__, module_file_spec.GetPath ().c_str (),
3580 arch.GetTriple ().getTriple ().c_str ());
3581 return false;
3582 }
3583
3584 if (log)
3585 {
3586 StreamString stream;
3587 module_spec.Dump (stream);
3588 log->Printf ("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
3589 __FUNCTION__, module_file_spec.GetPath ().c_str (),
3590 arch.GetTriple ().getTriple ().c_str (), stream.GetString ().c_str ());
3591 }
3592
3593 return true;
3594}
3595
Colin Rileyc3c95b22015-04-16 15:51:33 +00003596#if defined( LIBXML2_DEFINED )
3597namespace {
3598
3599typedef std::vector<std::string> stringVec;
3600typedef std::vector<xmlNodePtr> xmlNodePtrVec;
3601
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003602struct GdbServerRegisterInfo
3603{
Colin Rileyc3c95b22015-04-16 15:51:33 +00003604
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003605 struct
3606 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003607 bool m_has_name : 1;
3608 bool m_has_bitSize : 1;
3609 bool m_has_type : 1;
3610 bool m_has_group : 1;
3611 bool m_has_regNum : 1;
3612 }
3613 m_flags;
3614
3615 std::string m_name;
3616 std::string m_group;
3617 uint32_t m_bitSize;
3618 uint32_t m_regNum;
3619
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003620 enum RegType
3621 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003622 eUnknown ,
3623 eCodePtr ,
3624 eDataPtr ,
3625 eInt32 ,
3626 eI387Ext ,
3627 }
3628 m_type;
3629
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003630 void clear()
3631 {
3632 memset(&m_flags, 0, sizeof(m_flags));
Colin Rileyc3c95b22015-04-16 15:51:33 +00003633 }
3634};
3635
3636typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
3637
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003638struct GdbServerTargetInfo
3639{
Colin Rileyc3c95b22015-04-16 15:51:33 +00003640 std::string m_arch;
3641 std::string m_osabi;
3642};
3643
3644// conversion table between gdb register type and enum
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003645struct
3646{
Colin Rileyc3c95b22015-04-16 15:51:33 +00003647 const char * m_name;
3648 GdbServerRegisterInfo::RegType m_type;
3649}
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003650RegTypeTable[] =
3651{
Colin Rileyc3c95b22015-04-16 15:51:33 +00003652 { "int32" , GdbServerRegisterInfo::eInt32 },
3653 { "int" , GdbServerRegisterInfo::eInt32 },
3654 { "data_ptr", GdbServerRegisterInfo::eDataPtr },
3655 { "code_ptr", GdbServerRegisterInfo::eCodePtr },
3656 { "i387_ext", GdbServerRegisterInfo::eI387Ext }, // 80bit fpu
Greg Claytone68c0082015-04-16 23:13:26 +00003657 { nullptr , GdbServerRegisterInfo::eUnknown } // sentinel
Colin Rileyc3c95b22015-04-16 15:51:33 +00003658};
3659
3660// find the first sibling with a matching name
3661xmlNodePtr
3662xmlExFindSibling (xmlNodePtr node,
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003663 const std::string & name)
3664{
Colin Rileyc3c95b22015-04-16 15:51:33 +00003665
3666 if ( !node ) return nullptr;
3667 // iterate through all siblings
3668 for ( xmlNodePtr temp = node; temp; temp=temp->next ) {
3669 // we are looking for elements
3670 if ( temp->type != XML_ELEMENT_NODE )
3671 continue;
3672 // check element name matches
3673 if ( !temp->name ) continue;
3674 if ( std::strcmp((const char*)temp->name, name.c_str() ) == 0 )
3675 return temp;
3676 }
3677 // no sibling found
3678 return nullptr;
3679}
3680
3681// find an element from a given element path
3682xmlNodePtr
3683xmlExFindElement (xmlNodePtr node,
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003684 const stringVec & path)
3685{
Colin Rileyc3c95b22015-04-16 15:51:33 +00003686
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003687 if (!node)
3688 return nullptr;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003689 xmlNodePtr temp = node;
3690 // iterate all elements in path
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003691 for (uint32_t i = 0; i < path.size(); i++)
3692 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003693
3694 // search for a sibling with this name
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003695 temp = xmlExFindSibling(temp, path[i]);
3696 if (!temp)
Colin Rileyc3c95b22015-04-16 15:51:33 +00003697 return nullptr;
3698 // enter this node if we still need to search
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003699 if ((i + 1) < path.size())
Colin Rileyc3c95b22015-04-16 15:51:33 +00003700 // enter the node we have found
3701 temp = temp->children;
3702 }
3703 // note: node may still be nullptr at this step
3704 return temp;
3705}
3706
3707// locate a specific attribute in an element
3708xmlAttr *
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003709xmlExFindAttribute (xmlNodePtr node,
3710 const std::string & name)
3711{
Colin Rileyc3c95b22015-04-16 15:51:33 +00003712
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003713 if (!node)
Colin Rileyc3c95b22015-04-16 15:51:33 +00003714 return nullptr;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003715 if (node->type != XML_ELEMENT_NODE)
Colin Rileyc3c95b22015-04-16 15:51:33 +00003716 return nullptr;
3717 // iterate over all attributes
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003718 for (xmlAttrPtr attr = node->properties; attr != nullptr; attr=attr->next)
3719 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003720 // check if name matches
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003721 if (!attr->name)
3722 continue;
3723 if (std::strcmp((const char*) attr->name, name.c_str()) == 0)
Colin Rileyc3c95b22015-04-16 15:51:33 +00003724 return attr;
3725 }
3726 return nullptr;
3727}
3728
3729// find all child elements with given name and add them to a vector
3730//
3731// input: node = xml element to search
3732// name = name used when matching child elements
3733// output: out = list of matches
3734// return: number of children added to 'out'
3735int
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003736xmlExFindChildren (xmlNodePtr node,
3737 const std::string & name,
3738 xmlNodePtrVec & out)
3739{
Colin Rileyc3c95b22015-04-16 15:51:33 +00003740
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003741 if (!node)
3742 return 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003743 int count = 0;
3744 // iterate over all children
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003745 for (xmlNodePtr child = node->children; child; child = child->next)
3746 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003747 // if name matches
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003748 if (!child->name)
3749 continue;
3750 if (std::strcmp((const char*) child->name, name.c_str()) == 0)
3751 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003752 // add to output list
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003753 out.push_back(child);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003754 ++count;
3755 }
3756 }
3757 return count;
3758}
3759
3760// get the text content from an attribute
3761std::string
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003762xmlExGetTextContent (xmlAttrPtr attr)
3763{
3764 if (!attr)
3765 return std::string();
3766 if (attr->type != XML_ATTRIBUTE_NODE)
3767 return std::string();
Colin Rileyc3c95b22015-04-16 15:51:33 +00003768 // check child is a text node
3769 xmlNodePtr child = attr->children;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003770 if (child->type != XML_TEXT_NODE)
3771 return std::string();
Colin Rileyc3c95b22015-04-16 15:51:33 +00003772 // access the content
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003773 assert(child->content != nullptr);
3774 return std::string((const char*) child->content);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003775}
3776
3777// get the text content from an node
3778std::string
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003779xmlExGetTextContent (xmlNodePtr node)
3780{
3781 if (!node)
3782 return std::string();
3783 if (node->type != XML_ELEMENT_NODE)
3784 return std::string();
Colin Rileyc3c95b22015-04-16 15:51:33 +00003785 // check child is a text node
3786 xmlNodePtr child = node->children;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003787 if (child->type != XML_TEXT_NODE)
3788 return std::string();
Colin Rileyc3c95b22015-04-16 15:51:33 +00003789 // access the content
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003790 assert(child->content != nullptr);
3791 return std::string((const char*) child->content);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003792}
3793
3794// compile a list of xml includes from the target file
3795// input: doc = target.xml
3796// output: includes = list of .xml names specified in target.xml
3797// return: number of .xml files specified in target.xml and added to includes
3798int
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003799parseTargetIncludes (xmlDocPtr doc, stringVec & includes)
3800{
3801 if (!doc)
3802 return 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003803 int count = 0;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003804 xmlNodePtr elm = xmlExFindElement(doc->children, {"target"});
3805 if (!elm)
3806 return 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003807 xmlNodePtrVec nodes;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003808 xmlExFindChildren(elm, "xi:include", nodes);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003809 // iterate over all includes
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003810 for (uint32_t i = 0; i < nodes.size(); i++)
3811 {
3812 xmlAttrPtr attr = xmlExFindAttribute(nodes[i], "href");
3813 if (attr != nullptr)
3814 {
3815 std::string text = xmlExGetTextContent(attr);
3816 includes.push_back(text);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003817 ++count;
3818 }
3819 }
3820 return count;
3821}
3822
3823// extract target arch information from the target.xml file
3824// input: doc = target.xml document
3825// output: out = remote target information
3826// return: 'true' on success
3827// 'false' on failure
3828bool
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003829parseTargetInfo (xmlDocPtr doc, GdbServerTargetInfo & out)
3830{
3831 if (!doc)
3832 return false;
3833 xmlNodePtr e1 = xmlExFindElement (doc->children, {"target", "architecture"});
3834 if (!e1)
3835 return false;
3836 out.m_arch = xmlExGetTextContent (e1);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003837
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003838 xmlNodePtr e2 = xmlExFindElement (doc->children, {"target", "osabi"});
3839 if (!e2)
3840 return false;
3841 out.m_osabi = xmlExGetTextContent (e2);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003842
3843 return true;
3844}
3845
3846// extract register information from one of the xml files specified in target.xml
3847// input: doc = xml document
3848// output: regList = list of extracted register info
3849// return: 'true' on success
3850// 'false' on failure
3851bool
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003852parseRegisters (xmlDocPtr doc, GDBServerRegisterVec & regList)
3853{
Colin Rileyc3c95b22015-04-16 15:51:33 +00003854
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003855 if (!doc)
3856 return false;
3857 xmlNodePtr elm = xmlExFindElement (doc->children, {"feature"});
3858 if (!elm)
3859 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003860
3861 xmlAttrPtr attr = nullptr;
3862
3863 xmlNodePtrVec regs;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003864 xmlExFindChildren (elm, "reg", regs);
3865 for (unsigned long i = 0; i < regs.size(); i++)
3866 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003867
3868 GdbServerRegisterInfo reg;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003869 reg.clear();
Colin Rileyc3c95b22015-04-16 15:51:33 +00003870
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003871 if ((attr = xmlExFindAttribute(regs[i], "name")))
3872 {
3873 reg.m_name = xmlExGetTextContent(attr).c_str();
Colin Rileyc3c95b22015-04-16 15:51:33 +00003874 reg.m_flags.m_has_name = true;
3875 }
3876
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003877 if ((attr = xmlExFindAttribute( regs[i], "bitsize")))
3878 {
3879 const std::string v = xmlExGetTextContent(attr);
3880 reg.m_bitSize = atoi(v.c_str());
Colin Rileyc3c95b22015-04-16 15:51:33 +00003881 reg.m_flags.m_has_bitSize = true;
3882 }
3883
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003884 if ((attr = xmlExFindAttribute(regs[i], "type")))
3885 {
3886 const std::string v = xmlExGetTextContent(attr);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003887 reg.m_type = GdbServerRegisterInfo::eUnknown;
3888
3889 // search the type table for a match
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003890 for (int j = 0; RegTypeTable[j].m_name !=nullptr; ++j)
3891 {
3892 if (RegTypeTable[j].m_name == v)
3893 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003894 reg.m_type = RegTypeTable[j].m_type;
3895 break;
3896 }
3897 }
3898
3899 reg.m_flags.m_has_type = (reg.m_type != GdbServerRegisterInfo::eUnknown);
3900 }
3901
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003902 if ((attr = xmlExFindAttribute( regs[i], "group")))
3903 {
3904 reg.m_group = xmlExGetTextContent(attr);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003905 reg.m_flags.m_has_group = true;
3906 }
3907
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003908 if ((attr = xmlExFindAttribute(regs[i], "regnum")))
3909 {
3910 const std::string v = xmlExGetTextContent(attr);
3911 reg.m_regNum = atoi(v.c_str());
Colin Rileyc3c95b22015-04-16 15:51:33 +00003912 reg.m_flags.m_has_regNum = true;
3913 }
3914
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003915 regList.push_back(reg);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003916 }
3917
3918 //TODO: there is also a "vector" element to parse
3919 //TODO: there is also eflags to parse
3920
3921 return true;
3922}
3923
3924// build lldb gdb-remote's dynamic register info from a vector of gdb provided registers
3925// input: regList = register information provided by gdbserver
3926// output: regInfo = dynamic register information required by gdb-remote
3927void
3928BuildRegisters (const GDBServerRegisterVec & regList,
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003929 GDBRemoteDynamicRegisterInfo & regInfo)
3930{
Colin Rileyc3c95b22015-04-16 15:51:33 +00003931
3932 using namespace lldb_private;
3933
3934 const uint32_t defSize = 32;
3935 uint32_t regNum = 0;
3936 uint32_t byteOffset = 0;
3937
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003938 for (uint32_t i = 0; i < regList.size(); ++i)
3939 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003940
3941 const GdbServerRegisterInfo & gdbReg = regList[i];
3942
3943 std::string name = gdbReg.m_flags.m_has_name ? gdbReg.m_name : "unknown";
3944 std::string group = gdbReg.m_flags.m_has_group ? gdbReg.m_group : "general";
3945 uint32_t byteSize = gdbReg.m_flags.m_has_bitSize ? (gdbReg.m_bitSize/8) : defSize;
3946
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003947 if (gdbReg.m_flags.m_has_regNum)
Colin Rileyc3c95b22015-04-16 15:51:33 +00003948 regNum = gdbReg.m_regNum;
3949
3950 uint32_t regNumGcc = LLDB_INVALID_REGNUM;
3951 uint32_t regNumDwarf = LLDB_INVALID_REGNUM;
3952 uint32_t regNumGeneric = LLDB_INVALID_REGNUM;
3953 uint32_t regNumGdb = regNum;
3954 uint32_t regNumNative = regNum;
3955
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003956 if (name == "eip" || name == "pc")
3957 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003958 regNumGeneric = LLDB_REGNUM_GENERIC_PC;
3959 }
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003960 if (name == "esp" || name == "sp")
3961 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003962 regNumGeneric = LLDB_REGNUM_GENERIC_SP;
3963 }
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003964 if (name == "ebp")
3965 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003966 regNumGeneric = LLDB_REGNUM_GENERIC_FP;
3967 }
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003968 if (name == "lr")
3969 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003970 regNumGeneric = LLDB_REGNUM_GENERIC_RA;
3971 }
3972
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003973 RegisterInfo info =
3974 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003975 name.c_str(),
3976 nullptr ,
3977 byteSize ,
3978 byteOffset ,
3979 lldb::Encoding::eEncodingUint,
3980 lldb::Format::eFormatDefault,
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003981 { regNumGcc ,
3982 regNumDwarf ,
Colin Rileyc3c95b22015-04-16 15:51:33 +00003983 regNumGeneric,
3984 regNumGdb ,
3985 regNumNative },
3986 nullptr,
3987 nullptr
3988 };
3989
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003990 ConstString regName = ConstString(gdbReg.m_name);
3991 ConstString regAltName = ConstString();
3992 ConstString regGroup = ConstString(group);
3993 regInfo.AddRegister(info, regName, regAltName, regGroup);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003994
3995 // advance register info
3996 byteOffset += byteSize;
3997 regNum += 1;
3998 }
3999
4000 regInfo.Finalize ();
4001}
4002
4003} // namespace {}
4004
4005void XMLCDECL
4006libxml2NullErrorFunc (void *ctx, const char *msg, ...)
4007{
4008 // do nothing currently
4009}
4010
4011// query the target of gdb-remote for extended target information
4012// return: 'true' on success
4013// 'false' on failure
4014bool
Aidan Doddsc0c83852015-05-08 09:36:31 +00004015ProcessGDBRemote::GetGDBServerRegisterInfo ()
Colin Rileyc3c95b22015-04-16 15:51:33 +00004016{
4017
4018 // redirect libxml2's error handler since the default prints to stdout
4019 xmlGenericErrorFunc func = libxml2NullErrorFunc;
4020 initGenericErrorDefaultFunc( &func );
4021
4022 GDBRemoteCommunicationClient & comm = m_gdb_comm;
4023 GDBRemoteDynamicRegisterInfo & regInfo = m_register_info;
4024
4025 // check that we have extended feature read support
4026 if ( !comm.GetQXferFeaturesReadSupported( ) )
4027 return false;
4028
4029 // request the target xml file
4030 std::string raw;
4031 lldb_private::Error lldberr;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004032 if (!comm.ReadExtFeature(ConstString("features"),
4033 ConstString("target.xml"),
4034 raw,
4035 lldberr))
4036 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00004037 return false;
4038 }
4039
4040 // parse the xml file in memory
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004041 xmlDocPtr doc = xmlReadMemory(raw.c_str(), raw.size(), "noname.xml", nullptr, 0);
4042 if (doc == nullptr)
Colin Rileyc3c95b22015-04-16 15:51:33 +00004043 return false;
4044
4045 // extract target info from target.xml
4046 GdbServerTargetInfo gdbInfo;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004047 if (parseTargetInfo(doc, gdbInfo))
4048 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00004049 // NOTE: We could deduce triple from gdbInfo if lldb doesn't already have one set
4050 }
4051
4052 // collect registers from all of the includes
4053 GDBServerRegisterVec regList;
4054 stringVec includes;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004055 if (parseTargetIncludes(doc, includes) > 0)
4056 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00004057
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004058 for (uint32_t i = 0; i < includes.size(); ++i)
4059 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00004060
4061 // request register file
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004062 if (!comm.ReadExtFeature(ConstString("features"),
4063 ConstString(includes[i]),
4064 raw,
4065 lldberr))
Colin Rileyc3c95b22015-04-16 15:51:33 +00004066 continue;
4067
4068 // parse register file
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004069 xmlDocPtr regXml = xmlReadMemory(raw.c_str(),
4070 raw.size( ),
4071 includes[i].c_str(),
4072 nullptr,
4073 0);
4074 if (!regXml)
Colin Rileyc3c95b22015-04-16 15:51:33 +00004075 continue;
4076
4077 // pass registers to lldb
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004078 parseRegisters(regXml, regList);
Colin Rileyc3c95b22015-04-16 15:51:33 +00004079 }
4080 }
4081
4082 // pass all of these registers to lldb
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004083 BuildRegisters(regList, regInfo);
Colin Rileyc3c95b22015-04-16 15:51:33 +00004084
4085 return true;
4086}
4087
Aidan Doddsc0c83852015-05-08 09:36:31 +00004088Error
4089ProcessGDBRemote::GetLoadedModuleList (GDBLoadedModuleInfoList & list)
4090{
4091 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS);
4092 if (log)
4093 log->Printf ("ProcessGDBRemote::%s", __FUNCTION__);
4094
4095 // redirect libxml2's error handler since the default prints to stdout
4096 xmlGenericErrorFunc func = libxml2NullErrorFunc;
4097 initGenericErrorDefaultFunc (&func);
4098
4099 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004100
4101 // check that we have extended feature read support
4102 if (!comm.GetQXferLibrariesSVR4ReadSupported ())
4103 return Error (0, ErrorType::eErrorTypeGeneric);
4104
4105 list.clear ();
4106
4107 // request the loaded library list
4108 std::string raw;
4109 lldb_private::Error lldberr;
4110 if (!comm.ReadExtFeature (ConstString ("libraries-svr4"), ConstString (""), raw, lldberr))
4111 return Error (0, ErrorType::eErrorTypeGeneric);
4112
4113 // parse the xml file in memory
4114 if (log)
4115 log->Printf ("parsing: %s", raw.c_str());
4116 xmlDocPtr doc = xmlReadMemory (raw.c_str(), raw.size(), "noname.xml", nullptr, 0);
4117 if (doc == nullptr)
4118 return Error (0, ErrorType::eErrorTypeGeneric);
4119
4120 xmlNodePtr elm = xmlExFindElement (doc->children, {"library-list-svr4"});
4121 if (!elm)
4122 return Error();
4123
4124 // main link map structure
4125 xmlAttr * attr = xmlExFindAttribute (elm, "main-lm");
4126 if (attr)
4127 {
4128 std::string val = xmlExGetTextContent (attr);
4129 if (val.length() > 2)
4130 {
4131 uint32_t process_lm = std::stoul (val.c_str()+2, 0, 16);
4132 list.m_link_map = process_lm;
4133 }
4134 }
4135
4136 // parse individual library entries
4137 for (xmlNode * child = elm->children; child; child=child->next)
4138 {
4139 if (!child->name)
4140 continue;
4141
Vince Harrond7e6a4f2015-05-13 00:25:54 +00004142 if (strcmp ((const char*)child->name, "library") != 0)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004143 continue;
4144
4145 GDBLoadedModuleInfoList::LoadedModuleInfo module;
4146
4147 for (xmlAttrPtr prop = child->properties; prop; prop=prop->next)
4148 {
Vince Harrond7e6a4f2015-05-13 00:25:54 +00004149 if (strcmp ((const char*)prop->name, "name") == 0)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004150 module.set_name (xmlExGetTextContent (prop));
4151
4152 // the address of the link_map struct.
Vince Harrond7e6a4f2015-05-13 00:25:54 +00004153 if (strcmp ((const char*)prop->name, "lm") == 0)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004154 {
4155 std::string val = xmlExGetTextContent (prop);
4156 if (val.length() > 2)
4157 {
4158 uint32_t module_lm = std::stoul (val.c_str()+2, 0, 16);
4159 module.set_link_map (module_lm);
4160 }
4161 }
4162
4163 // the displacement as read from the field 'l_addr' of the link_map struct.
Vince Harrond7e6a4f2015-05-13 00:25:54 +00004164 if (strcmp ((const char*)prop->name, "l_addr") == 0)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004165 {
4166 std::string val = xmlExGetTextContent (prop);
4167 if (val.length() > 2)
4168 {
4169 uint32_t module_base = std::stoul (val.c_str()+2, 0, 16);
4170 module.set_base (module_base);
4171 }
4172 }
4173
4174 // the memory address of the libraries PT_DYAMIC section.
Vince Harrond7e6a4f2015-05-13 00:25:54 +00004175 if (strcmp ((const char*)prop->name, "l_ld") == 0)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004176 {
4177 std::string val = xmlExGetTextContent (prop);
4178 if (val.length() > 2)
4179 {
4180 uint32_t module_dyn = std::stoul (val.c_str()+2, 0, 16);
4181 module.set_dynamic (module_dyn);
4182 }
4183 }
4184 }
4185
4186 if (log)
4187 {
4188 std::string name ("");
4189 lldb::addr_t lm=0, base=0, ld=0;
4190
4191 module.get_name (name);
4192 module.get_link_map (lm);
4193 module.get_base (base);
4194 module.get_dynamic (ld);
4195
4196 log->Printf ("found (link_map:0x08%" PRIx64 ", base:0x08%" PRIx64 ", ld:0x08%" PRIx64 ", name:'%s')", lm, base, ld, name.c_str());
4197 }
4198
4199 list.add (module);
4200 }
4201
4202 if (log)
4203 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4204
4205 return Error();
4206}
4207
Colin Rileyc3c95b22015-04-16 15:51:33 +00004208#else // if defined( LIBXML2_DEFINED )
4209
Aidan Doddsc0c83852015-05-08 09:36:31 +00004210Error
4211ProcessGDBRemote::GetLoadedModuleList (GDBLoadedModuleInfoList &)
4212{
4213 // stub (libxml2 not present)
4214 Error err;
4215 err.SetError (0, ErrorType::eErrorTypeGeneric);
4216 return err;
4217}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004218
4219bool
Aidan Doddsc0c83852015-05-08 09:36:31 +00004220ProcessGDBRemote::GetGDBServerRegisterInfo ()
Colin Rileyc3c95b22015-04-16 15:51:33 +00004221{
4222 // stub (libxml2 not present)
4223 return false;
4224}
4225
4226#endif // if defined( LIBXML2_DEFINED )
4227
Aidan Doddsc0c83852015-05-08 09:36:31 +00004228lldb::ModuleSP
4229ProcessGDBRemote::LoadModuleAtAddress (const FileSpec &file, lldb::addr_t base_addr)
4230{
4231 Target &target = m_process->GetTarget();
4232 ModuleList &modules = target.GetImages();
4233 ModuleSP module_sp;
4234
4235 bool changed = false;
4236
4237 ModuleSpec module_spec (file, target.GetArchitecture());
4238 if ((module_sp = modules.FindFirstModule (module_spec)))
4239 {
4240 module_sp->SetLoadAddress (target, base_addr, true, changed);
4241 }
4242 else if ((module_sp = target.GetSharedModule (module_spec)))
4243 {
4244 module_sp->SetLoadAddress (target, base_addr, true, changed);
4245 }
4246
4247 return module_sp;
4248}
4249
4250size_t
4251ProcessGDBRemote::LoadModules ()
4252{
4253 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4254
4255 // request a list of loaded libraries from GDBServer
4256 GDBLoadedModuleInfoList module_list;
4257 if (GetLoadedModuleList (module_list).Fail())
4258 return 0;
4259
4260 // get a list of all the modules
4261 ModuleList new_modules;
4262
4263 for (GDBLoadedModuleInfoList::LoadedModuleInfo & modInfo : module_list.m_list)
4264 {
4265 std::string mod_name;
4266 lldb::addr_t mod_base;
4267
4268 bool valid = true;
4269 valid &= modInfo.get_name (mod_name);
4270 valid &= modInfo.get_base (mod_base);
4271 if (!valid)
4272 continue;
4273
4274 // hack (cleaner way to get file name only?) (win/unix compat?)
Vince Harron4cc8d202015-05-10 08:33:58 +00004275 size_t marker = mod_name.rfind ('/');
Aidan Doddsc0c83852015-05-08 09:36:31 +00004276 if (marker == std::string::npos)
4277 marker = 0;
4278 else
4279 marker += 1;
4280
4281 FileSpec file (mod_name.c_str()+marker, true);
4282 lldb::ModuleSP module_sp = LoadModuleAtAddress (file, mod_base);
4283
4284 if (module_sp.get())
4285 new_modules.Append (module_sp);
4286 }
4287
4288 if (new_modules.GetSize() > 0)
4289 {
4290 Target & target = m_target;
4291
4292 new_modules.ForEach ([&target](const lldb::ModuleSP module_sp) -> bool
4293 {
4294 lldb_private::ObjectFile * obj = module_sp->GetObjectFile ();
4295 if (!obj)
4296 return true;
4297
4298 if (obj->GetType () != ObjectFile::Type::eTypeExecutable)
4299 return true;
4300
4301 lldb::ModuleSP module_copy_sp = module_sp;
4302 target.SetExecutableModule (module_copy_sp, false);
4303 return false;
4304 });
4305
4306 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4307 loaded_modules.AppendIfNeeded (new_modules);
4308 m_process->GetTarget().ModulesDidLoad (new_modules);
4309 }
4310
4311 return new_modules.GetSize();
4312}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004313
Greg Clayton02686b82012-10-15 22:42:16 +00004314class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00004315{
4316private:
4317
4318public:
Greg Clayton02686b82012-10-15 22:42:16 +00004319 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00004320 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00004321 "process plugin packet history",
4322 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00004323 NULL)
4324 {
4325 }
4326
Greg Clayton02686b82012-10-15 22:42:16 +00004327 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton998255b2012-10-13 02:07:45 +00004328 {
4329 }
4330
4331 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004332 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton998255b2012-10-13 02:07:45 +00004333 {
Greg Clayton02686b82012-10-15 22:42:16 +00004334 const size_t argc = command.GetArgumentCount();
4335 if (argc == 0)
4336 {
4337 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4338 if (process)
4339 {
4340 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
4341 result.SetStatus (eReturnStatusSuccessFinishResult);
4342 return true;
4343 }
4344 }
4345 else
4346 {
4347 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
4348 }
4349 result.SetStatus (eReturnStatusFailed);
4350 return false;
4351 }
4352};
4353
Jason Molenda6076bf42014-05-06 04:34:52 +00004354class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed
4355{
4356private:
4357
4358public:
4359 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) :
4360 CommandObjectParsed (interpreter,
4361 "process plugin packet xfer-size",
4362 "Maximum size that lldb will try to read/write one one chunk.",
4363 NULL)
4364 {
4365 }
4366
4367 ~CommandObjectProcessGDBRemotePacketXferSize ()
4368 {
4369 }
4370
4371 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004372 DoExecute (Args& command, CommandReturnObject &result) override
Jason Molenda6076bf42014-05-06 04:34:52 +00004373 {
4374 const size_t argc = command.GetArgumentCount();
4375 if (argc == 0)
4376 {
4377 result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str());
4378 result.SetStatus (eReturnStatusFailed);
4379 return false;
4380 }
4381
4382 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4383 if (process)
4384 {
4385 const char *packet_size = command.GetArgumentAtIndex(0);
4386 errno = 0;
4387 uint64_t user_specified_max = strtoul (packet_size, NULL, 10);
4388 if (errno == 0 && user_specified_max != 0)
4389 {
4390 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max);
4391 result.SetStatus (eReturnStatusSuccessFinishResult);
4392 return true;
4393 }
4394 }
4395 result.SetStatus (eReturnStatusFailed);
4396 return false;
4397 }
4398};
4399
4400
Greg Clayton02686b82012-10-15 22:42:16 +00004401class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
4402{
4403private:
4404
4405public:
4406 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
4407 CommandObjectParsed (interpreter,
4408 "process plugin packet send",
4409 "Send a custom packet through the GDB remote protocol and print the answer. "
4410 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
4411 NULL)
4412 {
4413 }
4414
4415 ~CommandObjectProcessGDBRemotePacketSend ()
4416 {
4417 }
4418
4419 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004420 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton02686b82012-10-15 22:42:16 +00004421 {
4422 const size_t argc = command.GetArgumentCount();
4423 if (argc == 0)
4424 {
4425 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
4426 result.SetStatus (eReturnStatusFailed);
4427 return false;
4428 }
4429
4430 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4431 if (process)
4432 {
Han Ming Ong84145852012-11-26 20:42:03 +00004433 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00004434 {
Han Ming Ong84145852012-11-26 20:42:03 +00004435 const char *packet_cstr = command.GetArgumentAtIndex(0);
4436 bool send_async = true;
4437 StringExtractorGDBRemote response;
4438 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
4439 result.SetStatus (eReturnStatusSuccessFinishResult);
4440 Stream &output_strm = result.GetOutputStream();
4441 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00004442 std::string &response_str = response.GetStringRef();
4443
Han Ming Ong399289e2013-06-21 19:56:59 +00004444 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00004445 {
4446 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
4447 }
4448
Han Ming Ong84145852012-11-26 20:42:03 +00004449 if (response_str.empty())
4450 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
4451 else
4452 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00004453 }
Greg Clayton02686b82012-10-15 22:42:16 +00004454 }
Greg Clayton998255b2012-10-13 02:07:45 +00004455 return true;
4456 }
4457};
4458
Greg Claytonba4a0a52013-02-01 23:03:47 +00004459class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
4460{
4461private:
4462
4463public:
4464 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
4465 CommandObjectRaw (interpreter,
4466 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00004467 "Send a qRcmd packet through the GDB remote protocol and print the response."
4468 "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 +00004469 NULL)
4470 {
4471 }
4472
4473 ~CommandObjectProcessGDBRemotePacketMonitor ()
4474 {
4475 }
4476
4477 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004478 DoExecute (const char *command, CommandReturnObject &result) override
Greg Claytonba4a0a52013-02-01 23:03:47 +00004479 {
4480 if (command == NULL || command[0] == '\0')
4481 {
4482 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
4483 result.SetStatus (eReturnStatusFailed);
4484 return false;
4485 }
4486
4487 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4488 if (process)
4489 {
4490 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00004491 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00004492 packet.PutBytesAsRawHex8(command, strlen(command));
4493 const char *packet_cstr = packet.GetString().c_str();
4494
4495 bool send_async = true;
4496 StringExtractorGDBRemote response;
4497 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
4498 result.SetStatus (eReturnStatusSuccessFinishResult);
4499 Stream &output_strm = result.GetOutputStream();
4500 output_strm.Printf (" packet: %s\n", packet_cstr);
4501 const std::string &response_str = response.GetStringRef();
4502
4503 if (response_str.empty())
4504 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
4505 else
4506 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
4507 }
4508 return true;
4509 }
4510};
4511
Greg Clayton02686b82012-10-15 22:42:16 +00004512class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
4513{
4514private:
4515
4516public:
4517 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
4518 CommandObjectMultiword (interpreter,
4519 "process plugin packet",
4520 "Commands that deal with GDB remote packets.",
4521 NULL)
4522 {
4523 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
4524 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00004525 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Jason Molenda6076bf42014-05-06 04:34:52 +00004526 LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00004527 }
4528
4529 ~CommandObjectProcessGDBRemotePacket ()
4530 {
4531 }
4532};
Greg Clayton998255b2012-10-13 02:07:45 +00004533
4534class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
4535{
4536public:
4537 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
4538 CommandObjectMultiword (interpreter,
4539 "process plugin",
4540 "A set of commands for operating on a ProcessGDBRemote process.",
4541 "process plugin <subcommand> [<subcommand-options>]")
4542 {
4543 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
4544 }
4545
4546 ~CommandObjectMultiwordProcessGDBRemote ()
4547 {
4548 }
4549};
4550
Greg Clayton998255b2012-10-13 02:07:45 +00004551CommandObject *
4552ProcessGDBRemote::GetPluginCommandObject()
4553{
4554 if (!m_command_sp)
4555 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
4556 return m_command_sp.get();
4557}