blob: 6eb4fbd2078ac430d0b1efe64b355fa521eda616 [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 (),
Todd Fiala4ceced32014-08-29 17:35:57 +0000394 m_breakpoint_pc_offset (0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000395{
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000396 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
397 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Inghamb1e2e842012-04-12 18:49:31 +0000398 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Greg Clayton7f982402013-07-15 22:54:20 +0000399 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
400 if (timeout_seconds > 0)
401 m_gdb_comm.SetPacketTimeout(timeout_seconds);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000402}
403
404//----------------------------------------------------------------------
405// Destructor
406//----------------------------------------------------------------------
407ProcessGDBRemote::~ProcessGDBRemote()
408{
409 // m_mach_process.UnregisterNotificationCallbacks (this);
410 Clear();
Greg Clayton1ed54f52011-10-01 00:45:15 +0000411 // We need to call finalize on the process before destroying ourselves
412 // to make sure all of the broadcaster cleanup goes as planned. If we
413 // destruct this class, then Process::~Process() might have problems
414 // trying to fully destroy the broadcaster.
415 Finalize();
Jim Ingham455fa5c2012-11-01 01:15:33 +0000416
417 // The general Finalize is going to try to destroy the process and that SHOULD
418 // shut down the async thread. However, if we don't kill it it will get stranded and
419 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
420 StopAsyncThread();
421 KillDebugserverProcess();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000422}
423
424//----------------------------------------------------------------------
425// PluginInterface
426//----------------------------------------------------------------------
Greg Clayton57abc5d2013-05-10 21:47:16 +0000427ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000428ProcessGDBRemote::GetPluginName()
429{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000430 return GetPluginNameStatic();
431}
432
433uint32_t
434ProcessGDBRemote::GetPluginVersion()
435{
436 return 1;
437}
438
Greg Claytonef8180a2013-10-15 00:14:28 +0000439bool
440ProcessGDBRemote::ParsePythonTargetDefinition(const FileSpec &target_definition_fspec)
441{
442 ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
443 Error error;
Zachary Turner0641ca12015-03-17 20:04:04 +0000444 StructuredData::ObjectSP module_object_sp(interpreter->LoadPluginModule(target_definition_fspec, error));
Greg Claytonef8180a2013-10-15 00:14:28 +0000445 if (module_object_sp)
446 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000447 StructuredData::DictionarySP target_definition_sp(
448 interpreter->GetDynamicSettings(module_object_sp, &GetTarget(), "gdb-server-target-definition", error));
Greg Claytonef8180a2013-10-15 00:14:28 +0000449
Zachary Turner0641ca12015-03-17 20:04:04 +0000450 if (target_definition_sp)
Greg Claytonef8180a2013-10-15 00:14:28 +0000451 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000452 StructuredData::ObjectSP target_object(target_definition_sp->GetValueForKey("host-info"));
453 if (target_object)
Greg Clayton312bcbe2013-10-17 01:10:23 +0000454 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000455 if (auto host_info_dict = target_object->GetAsDictionary())
Greg Clayton312bcbe2013-10-17 01:10:23 +0000456 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000457 StructuredData::ObjectSP triple_value = host_info_dict->GetValueForKey("triple");
458 if (auto triple_string_value = triple_value->GetAsString())
459 {
460 std::string triple_string = triple_string_value->GetValue();
461 ArchSpec host_arch(triple_string.c_str());
462 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture()))
463 {
464 GetTarget().SetArchitecture(host_arch);
465 }
466 }
Greg Clayton312bcbe2013-10-17 01:10:23 +0000467 }
Greg Clayton312bcbe2013-10-17 01:10:23 +0000468 }
Zachary Turner0641ca12015-03-17 20:04:04 +0000469 m_breakpoint_pc_offset = 0;
470 StructuredData::ObjectSP breakpoint_pc_offset_value = target_definition_sp->GetValueForKey("breakpoint-pc-offset");
471 if (breakpoint_pc_offset_value)
472 {
473 if (auto breakpoint_pc_int_value = breakpoint_pc_offset_value->GetAsInteger())
474 m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
475 }
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000476
Zachary Turner0641ca12015-03-17 20:04:04 +0000477 if (m_register_info.SetRegisterInfo(*target_definition_sp, GetTarget().GetArchitecture().GetByteOrder()) > 0)
Greg Claytonef8180a2013-10-15 00:14:28 +0000478 {
479 return true;
480 }
481 }
482 }
483 return false;
484}
485
486
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000487void
Greg Clayton513c26c2011-01-29 07:10:55 +0000488ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000489{
Greg Clayton513c26c2011-01-29 07:10:55 +0000490 if (!force && m_register_info.GetNumRegisters() > 0)
491 return;
492
493 char packet[128];
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000494 m_register_info.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000495 uint32_t reg_offset = 0;
496 uint32_t reg_num = 0;
Greg Clayton23f59502012-07-17 03:23:13 +0000497 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Greg Clayton576d8832011-03-22 04:00:09 +0000498 response_type == StringExtractorGDBRemote::eResponse;
499 ++reg_num)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000500 {
Greg Clayton513c26c2011-01-29 07:10:55 +0000501 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
Andy Gibbsa297a972013-06-19 19:04:53 +0000502 assert (packet_len < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000503 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000504 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000505 {
Greg Clayton576d8832011-03-22 04:00:09 +0000506 response_type = response.GetResponseType();
507 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000508 {
509 std::string name;
510 std::string value;
511 ConstString reg_name;
512 ConstString alt_name;
513 ConstString set_name;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000514 std::vector<uint32_t> value_regs;
515 std::vector<uint32_t> invalidate_regs;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000516 RegisterInfo reg_info = { NULL, // Name
517 NULL, // Alt name
518 0, // byte size
519 reg_offset, // offset
520 eEncodingUint, // encoding
521 eFormatHex, // formate
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000522 {
523 LLDB_INVALID_REGNUM, // GCC reg num
524 LLDB_INVALID_REGNUM, // DWARF reg num
525 LLDB_INVALID_REGNUM, // generic reg num
Jason Molendafbcb7f22010-09-10 07:49:16 +0000526 reg_num, // GDB reg num
527 reg_num // native register number
Greg Clayton435d85a2012-02-29 19:27:27 +0000528 },
529 NULL,
530 NULL
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000531 };
532
533 while (response.GetNameColonValue(name, value))
534 {
535 if (name.compare("name") == 0)
536 {
537 reg_name.SetCString(value.c_str());
538 }
539 else if (name.compare("alt-name") == 0)
540 {
541 alt_name.SetCString(value.c_str());
542 }
543 else if (name.compare("bitsize") == 0)
544 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000545 reg_info.byte_size = StringConvert::ToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000546 }
547 else if (name.compare("offset") == 0)
548 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000549 uint32_t offset = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda743e86a2010-06-11 23:44:18 +0000550 if (reg_offset != offset)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000551 {
552 reg_offset = offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000553 }
554 }
555 else if (name.compare("encoding") == 0)
556 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000557 const Encoding encoding = Args::StringToEncoding (value.c_str());
558 if (encoding != eEncodingInvalid)
559 reg_info.encoding = encoding;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000560 }
561 else if (name.compare("format") == 0)
562 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000563 Format format = eFormatInvalid;
564 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
565 reg_info.format = format;
566 else if (value.compare("binary") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000567 reg_info.format = eFormatBinary;
568 else if (value.compare("decimal") == 0)
569 reg_info.format = eFormatDecimal;
570 else if (value.compare("hex") == 0)
571 reg_info.format = eFormatHex;
572 else if (value.compare("float") == 0)
573 reg_info.format = eFormatFloat;
574 else if (value.compare("vector-sint8") == 0)
575 reg_info.format = eFormatVectorOfSInt8;
576 else if (value.compare("vector-uint8") == 0)
577 reg_info.format = eFormatVectorOfUInt8;
578 else if (value.compare("vector-sint16") == 0)
579 reg_info.format = eFormatVectorOfSInt16;
580 else if (value.compare("vector-uint16") == 0)
581 reg_info.format = eFormatVectorOfUInt16;
582 else if (value.compare("vector-sint32") == 0)
583 reg_info.format = eFormatVectorOfSInt32;
584 else if (value.compare("vector-uint32") == 0)
585 reg_info.format = eFormatVectorOfUInt32;
586 else if (value.compare("vector-float32") == 0)
587 reg_info.format = eFormatVectorOfFloat32;
588 else if (value.compare("vector-uint128") == 0)
589 reg_info.format = eFormatVectorOfUInt128;
590 }
591 else if (name.compare("set") == 0)
592 {
593 set_name.SetCString(value.c_str());
594 }
595 else if (name.compare("gcc") == 0)
596 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000597 reg_info.kinds[eRegisterKindGCC] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000598 }
599 else if (name.compare("dwarf") == 0)
600 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000601 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000602 }
603 else if (name.compare("generic") == 0)
604 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000605 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000606 }
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000607 else if (name.compare("container-regs") == 0)
608 {
609 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
610 value_pair.second = value;
611 do
612 {
613 value_pair = value_pair.second.split(',');
614 if (!value_pair.first.empty())
615 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000616 uint32_t reg = StringConvert::ToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
Greg Clayton0ba20242013-01-21 23:32:42 +0000617 if (reg != LLDB_INVALID_REGNUM)
618 value_regs.push_back (reg);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000619 }
620 } while (!value_pair.second.empty());
621 }
622 else if (name.compare("invalidate-regs") == 0)
623 {
624 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
625 value_pair.second = value;
626 do
627 {
628 value_pair = value_pair.second.split(',');
629 if (!value_pair.first.empty())
630 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000631 uint32_t reg = StringConvert::ToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
Greg Clayton0ba20242013-01-21 23:32:42 +0000632 if (reg != LLDB_INVALID_REGNUM)
633 invalidate_regs.push_back (reg);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000634 }
635 } while (!value_pair.second.empty());
636 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000637 }
638
Jason Molenda743e86a2010-06-11 23:44:18 +0000639 reg_info.byte_offset = reg_offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000640 assert (reg_info.byte_size != 0);
641 reg_offset += reg_info.byte_size;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000642 if (!value_regs.empty())
643 {
644 value_regs.push_back(LLDB_INVALID_REGNUM);
645 reg_info.value_regs = value_regs.data();
646 }
647 if (!invalidate_regs.empty())
648 {
649 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
650 reg_info.invalidate_regs = invalidate_regs.data();
651 }
652
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000653 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
654 }
Todd Fiala1a634402014-01-08 07:52:40 +0000655 else
656 {
657 break; // ensure exit before reg_num is incremented
658 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000659 }
660 else
661 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000662 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000663 }
664 }
665
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000666 // Check if qHostInfo specified a specific packet timeout for this connection.
667 // If so then lets update our setting so the user knows what the timeout is
668 // and can see it.
669 const uint32_t host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
670 if (host_packet_timeout)
671 {
672 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout);
673 }
674
675
Greg Claytonef8180a2013-10-15 00:14:28 +0000676 if (reg_num == 0)
677 {
Colin Rileyc3c95b22015-04-16 15:51:33 +0000678 // try to extract information from servers target.xml
Aidan Doddsc0c83852015-05-08 09:36:31 +0000679 if (GetGDBServerRegisterInfo ())
Colin Rileyc3c95b22015-04-16 15:51:33 +0000680 return;
681
Greg Claytonef8180a2013-10-15 00:14:28 +0000682 FileSpec target_definition_fspec = GetGlobalPluginProperties()->GetTargetDefinitionFile ();
Greg Clayton312bcbe2013-10-17 01:10:23 +0000683
684 if (target_definition_fspec)
Greg Claytonef8180a2013-10-15 00:14:28 +0000685 {
Greg Clayton312bcbe2013-10-17 01:10:23 +0000686 // See if we can get register definitions from a python file
687 if (ParsePythonTargetDefinition (target_definition_fspec))
688 return;
Greg Claytonef8180a2013-10-15 00:14:28 +0000689 }
690 }
691
Johnny Chen2fa9de12012-05-14 18:44:23 +0000692 // We didn't get anything if the accumulated reg_num is zero. See if we are
693 // debugging ARM and fill with a hard coded register set until we can get an
694 // updated debugserver down on the devices.
695 // On the other hand, if the accumulated reg_num is positive, see if we can
696 // add composite registers to the existing primordial ones.
697 bool from_scratch = (reg_num == 0);
698
699 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000700 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
701 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
702
703 // Use the process' architecture instead of the host arch, if available
704 ArchSpec remote_arch;
705 if (remote_process_arch.IsValid ())
706 remote_arch = remote_process_arch;
707 else
708 remote_arch = remote_host_arch;
709
Johnny Chen2fa9de12012-05-14 18:44:23 +0000710 if (!target_arch.IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000711 {
Johnny Chen2fa9de12012-05-14 18:44:23 +0000712 if (remote_arch.IsValid()
713 && remote_arch.GetMachine() == llvm::Triple::arm
714 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
715 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000716 }
Johnny Chen2fa9de12012-05-14 18:44:23 +0000717 else if (target_arch.GetMachine() == llvm::Triple::arm)
718 {
719 m_register_info.HardcodeARMRegisters(from_scratch);
720 }
721
722 // At this point, we can finalize our register info.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000723 m_register_info.Finalize ();
724}
725
726Error
727ProcessGDBRemote::WillLaunch (Module* module)
728{
729 return WillLaunchOrAttach ();
730}
731
732Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000733ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000734{
735 return WillLaunchOrAttach ();
736}
737
738Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000739ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000740{
741 return WillLaunchOrAttach ();
742}
743
744Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000745ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +0000746{
Todd Fialaaf245d12014-06-30 21:05:18 +0000747 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Claytonb766a732011-02-04 01:58:07 +0000748 Error error (WillLaunchOrAttach ());
749
750 if (error.Fail())
751 return error;
752
Greg Clayton2289fa42011-04-30 01:09:13 +0000753 error = ConnectToDebugserver (remote_url);
Greg Claytonb766a732011-02-04 01:58:07 +0000754
755 if (error.Fail())
756 return error;
757 StartAsyncThread ();
758
Greg Claytonc574ede2011-03-10 02:26:48 +0000759 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonb766a732011-02-04 01:58:07 +0000760 if (pid == LLDB_INVALID_PROCESS_ID)
761 {
762 // We don't have a valid process ID, so note that we are connected
763 // and could now request to launch or attach, or get remote process
764 // listings...
765 SetPrivateState (eStateConnected);
766 }
767 else
768 {
769 // We have a valid process
770 SetID (pid);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000771 GetThreadList();
Greg Clayton3dedae12013-12-06 21:45:27 +0000772 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false) == GDBRemoteCommunication::PacketResult::Success)
Greg Claytonb766a732011-02-04 01:58:07 +0000773 {
Jason Molendac62bd7b2013-12-21 05:20:36 +0000774 if (!m_target.GetArchitecture().IsValid())
775 {
776 if (m_gdb_comm.GetProcessArchitecture().IsValid())
777 {
778 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
779 }
780 else
781 {
782 m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
783 }
Carlo Kok74389122013-10-14 07:09:13 +0000784 }
785
Greg Claytondd0e5a52011-06-02 22:22:38 +0000786 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytonb766a732011-02-04 01:58:07 +0000787 if (state == eStateStopped)
788 {
789 SetPrivateState (state);
790 }
791 else
Daniel Malead01b2952012-11-29 21:49:15 +0000792 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 +0000793 }
794 else
Daniel Malead01b2952012-11-29 21:49:15 +0000795 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 +0000796 }
Jason Molenda16d127c2012-05-03 22:37:30 +0000797
Todd Fialaaf245d12014-06-30 21:05:18 +0000798 if (log)
799 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");
800
801
802 if (error.Success()
Jason Molenda16d127c2012-05-03 22:37:30 +0000803 && !GetTarget().GetArchitecture().IsValid()
804 && m_gdb_comm.GetHostArchitecture().IsValid())
805 {
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000806 // Prefer the *process'* architecture over that of the *host*, if available.
807 if (m_gdb_comm.GetProcessArchitecture().IsValid())
808 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
809 else
810 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molenda16d127c2012-05-03 22:37:30 +0000811 }
812
Todd Fialaaf245d12014-06-30 21:05:18 +0000813 if (log)
814 log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": normalized target architecture triple: %s", __FUNCTION__, GetID (), GetTarget ().GetArchitecture ().GetTriple ().getTriple ().c_str ());
815
816 // Set the Unix signals properly for the target.
817 // FIXME Add a gdb-remote packet to discover dynamically.
818 if (error.Success ())
819 {
Tamas Berghammerac839822015-03-04 11:34:10 +0000820 const ArchSpec arch_spec = m_gdb_comm.GetHostArchitecture();
Todd Fialaaf245d12014-06-30 21:05:18 +0000821 if (arch_spec.IsValid ())
822 {
823 if (log)
824 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 ());
825
826 switch (arch_spec.GetTriple ().getOS ())
827 {
828 case llvm::Triple::Linux:
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +0000829 if (arch_spec.GetTriple ().getArch () == llvm::Triple::mips64 || arch_spec.GetTriple ().getArch () == llvm::Triple::mips64el)
830 SetUnixSignals (UnixSignalsSP (new process_linux::MipsLinuxSignals ()));
831 else
832 SetUnixSignals (UnixSignalsSP (new process_linux::LinuxSignals ()));
Todd Fialaaf245d12014-06-30 21:05:18 +0000833 if (log)
834 log->Printf ("ProcessGDBRemote::%s using Linux unix signals type for pid %" PRIu64, __FUNCTION__, GetID ());
835 break;
836 case llvm::Triple::OpenBSD:
837 case llvm::Triple::FreeBSD:
838 case llvm::Triple::NetBSD:
Todd Fiala4ceced32014-08-29 17:35:57 +0000839 SetUnixSignals (UnixSignalsSP (new FreeBSDSignals ()));
Todd Fialaaf245d12014-06-30 21:05:18 +0000840 if (log)
841 log->Printf ("ProcessGDBRemote::%s using *BSD unix signals type for pid %" PRIu64, __FUNCTION__, GetID ());
842 break;
843 default:
Todd Fiala4ceced32014-08-29 17:35:57 +0000844 SetUnixSignals (UnixSignalsSP (new UnixSignals ()));
Todd Fialaaf245d12014-06-30 21:05:18 +0000845 if (log)
846 log->Printf ("ProcessGDBRemote::%s using generic unix signals type for pid %" PRIu64, __FUNCTION__, GetID ());
847 break;
848 }
849 }
850 }
851
Greg Claytonb766a732011-02-04 01:58:07 +0000852 return error;
853}
854
855Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000856ProcessGDBRemote::WillLaunchOrAttach ()
857{
858 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000859 m_stdio_communication.Clear ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000860 return error;
861}
862
863//----------------------------------------------------------------------
864// Process Control
865//----------------------------------------------------------------------
866Error
Jean-Daniel Dupas7782de92013-12-09 22:52:50 +0000867ProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000868{
Todd Fiala75f47c32014-10-11 21:42:09 +0000869 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton4957bf62010-09-30 21:49:03 +0000870 Error error;
Greg Clayton982c9762011-11-03 21:22:33 +0000871
Todd Fiala75f47c32014-10-11 21:42:09 +0000872 if (log)
873 log->Printf ("ProcessGDBRemote::%s() entered", __FUNCTION__);
874
Greg Clayton982c9762011-11-03 21:22:33 +0000875 uint32_t launch_flags = launch_info.GetFlags().Get();
876 const char *stdin_path = NULL;
877 const char *stdout_path = NULL;
878 const char *stderr_path = NULL;
879 const char *working_dir = launch_info.GetWorkingDirectory();
880
Zachary Turner696b5282014-08-14 16:01:25 +0000881 const FileAction *file_action;
Greg Clayton982c9762011-11-03 21:22:33 +0000882 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
883 if (file_action)
884 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000885 if (file_action->GetAction() == FileAction::eFileActionOpen)
Greg Clayton982c9762011-11-03 21:22:33 +0000886 stdin_path = file_action->GetPath();
887 }
888 file_action = launch_info.GetFileActionForFD (STDOUT_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 stdout_path = file_action->GetPath();
893 }
894 file_action = launch_info.GetFileActionForFD (STDERR_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 stderr_path = file_action->GetPath();
899 }
900
Todd Fiala75f47c32014-10-11 21:42:09 +0000901 if (log)
902 {
903 if (stdin_path || stdout_path || stderr_path)
Vince Harron4a8abd32015-02-13 19:15:24 +0000904 log->Printf ("ProcessGDBRemote::%s provided with STDIO paths via launch_info: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000905 __FUNCTION__,
906 stdin_path ? stdin_path : "<null>",
907 stdout_path ? stdout_path : "<null>",
908 stderr_path ? stderr_path : "<null>");
909 else
910 log->Printf ("ProcessGDBRemote::%s no STDIO paths given via launch_info", __FUNCTION__);
911 }
912
Vince Harrondf3f00f2015-02-10 21:09:04 +0000913 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
914 if (stdin_path || disable_stdio)
915 {
916 // the inferior will be reading stdin from the specified file
917 // or stdio is completely disabled
918 m_stdin_forward = false;
919 }
920 else
921 {
922 m_stdin_forward = true;
923 }
924
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000925 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
926 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
927 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000928
Greg Clayton982c9762011-11-03 21:22:33 +0000929 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000930 if (object_file)
931 {
Greg Clayton71337622011-02-24 22:24:29 +0000932 // Make sure we aren't already connected?
933 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000934 {
Greg Clayton91a9b2472013-12-04 19:19:12 +0000935 error = LaunchAndConnectToDebugserver (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000936 }
937
938 if (error.Success())
939 {
940 lldb_utility::PseudoTerminal pty;
941 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000942
Greg Claytonf58c2692011-06-24 22:32:10 +0000943 PlatformSP platform_sp (m_target.GetPlatform());
Vince Harrondf3f00f2015-02-10 21:09:04 +0000944 if (disable_stdio)
Greg Clayton71337622011-02-24 22:24:29 +0000945 {
Vince Harrondf3f00f2015-02-10 21:09:04 +0000946 // set to /dev/null unless redirected to a file above
947 if (!stdin_path)
948 stdin_path = "/dev/null";
949 if (!stdout_path)
950 stdout_path = "/dev/null";
951 if (!stderr_path)
952 stderr_path = "/dev/null";
953 }
954 else if (platform_sp && platform_sp->IsHost())
955 {
956 // If the debugserver is local and we aren't disabling STDIO, lets use
957 // a pseudo terminal to instead of relying on the 'O' packets for stdio
958 // since 'O' packets can really slow down debugging if the inferior
959 // does a lot of output.
Greg Clayton71337622011-02-24 22:24:29 +0000960 const char *slave_name = NULL;
961 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000962 {
Greg Clayton71337622011-02-24 22:24:29 +0000963 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
964 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000965 }
Greg Clayton71337622011-02-24 22:24:29 +0000966 if (stdin_path == NULL)
967 stdin_path = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000968
Greg Clayton71337622011-02-24 22:24:29 +0000969 if (stdout_path == NULL)
970 stdout_path = slave_name;
971
972 if (stderr_path == NULL)
973 stderr_path = slave_name;
Todd Fiala75f47c32014-10-11 21:42:09 +0000974
975 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +0000976 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 +0000977 __FUNCTION__,
978 stdin_path ? stdin_path : "<null>",
979 stdout_path ? stdout_path : "<null>",
980 stderr_path ? stderr_path : "<null>");
Greg Clayton71337622011-02-24 22:24:29 +0000981 }
982
Todd Fiala75f47c32014-10-11 21:42:09 +0000983 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +0000984 log->Printf ("ProcessGDBRemote::%s final STDIO paths after all adjustments: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000985 __FUNCTION__,
986 stdin_path ? stdin_path : "<null>",
987 stdout_path ? stdout_path : "<null>",
988 stderr_path ? stderr_path : "<null>");
989
990 if (stdin_path)
Greg Clayton71337622011-02-24 22:24:29 +0000991 m_gdb_comm.SetSTDIN (stdin_path);
992 if (stdout_path)
993 m_gdb_comm.SetSTDOUT (stdout_path);
994 if (stderr_path)
995 m_gdb_comm.SetSTDERR (stderr_path);
996
997 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
Jim Ingham106d0282014-06-25 02:32:56 +0000998 m_gdb_comm.SetDetachOnError (launch_flags & eLaunchFlagDetachOnError);
Greg Clayton71337622011-02-24 22:24:29 +0000999
Greg Claytonc4103b32011-05-08 04:53:50 +00001000 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Clayton71337622011-02-24 22:24:29 +00001001
Jason Molendaa3329782014-03-29 18:54:20 +00001002 const char * launch_event_data = launch_info.GetLaunchEventData();
1003 if (launch_event_data != NULL && *launch_event_data != '\0')
1004 m_gdb_comm.SendLaunchEventDataPacket (launch_event_data);
1005
Greg Clayton71337622011-02-24 22:24:29 +00001006 if (working_dir && working_dir[0])
1007 {
1008 m_gdb_comm.SetWorkingDir (working_dir);
1009 }
1010
1011 // Send the environment and the program + arguments after we connect
Greg Clayton982c9762011-11-03 21:22:33 +00001012 const Args &environment = launch_info.GetEnvironmentEntries();
1013 if (environment.GetArgumentCount())
Greg Clayton71337622011-02-24 22:24:29 +00001014 {
Greg Clayton982c9762011-11-03 21:22:33 +00001015 size_t num_environment_entries = environment.GetArgumentCount();
1016 for (size_t i=0; i<num_environment_entries; ++i)
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001017 {
Greg Clayton982c9762011-11-03 21:22:33 +00001018 const char *env_entry = environment.GetArgumentAtIndex(i);
1019 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Clayton71337622011-02-24 22:24:29 +00001020 break;
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001021 }
Greg Clayton71337622011-02-24 22:24:29 +00001022 }
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001023
Greg Clayton71337622011-02-24 22:24:29 +00001024 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001025 // Scope for the scoped timeout object
1026 GDBRemoteCommunication::ScopedTimeout timeout (m_gdb_comm, 10);
1027
1028 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
1029 if (arg_packet_err == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001030 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001031 std::string error_str;
1032 if (m_gdb_comm.GetLaunchSuccess (error_str))
1033 {
1034 SetID (m_gdb_comm.GetCurrentProcessID ());
1035 }
1036 else
1037 {
1038 error.SetErrorString (error_str.c_str());
1039 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001040 }
1041 else
1042 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001043 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001044 }
Greg Clayton71337622011-02-24 22:24:29 +00001045 }
Tamas Berghammer912800c2015-02-24 10:23:39 +00001046
Greg Clayton71337622011-02-24 22:24:29 +00001047 if (GetID() == LLDB_INVALID_PROCESS_ID)
1048 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001049 if (log)
1050 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton71337622011-02-24 22:24:29 +00001051 KillDebugserverProcess ();
1052 return error;
1053 }
1054
Greg Clayton3dedae12013-12-06 21:45:27 +00001055 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton71337622011-02-24 22:24:29 +00001056 {
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001057 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
1058
1059 if (process_arch.IsValid())
Jason Molendac62bd7b2013-12-21 05:20:36 +00001060 {
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001061 m_target.MergeArchitecture(process_arch);
1062 }
1063 else
1064 {
1065 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
1066 if (host_arch.IsValid())
1067 m_target.MergeArchitecture(host_arch);
Carlo Kok74389122013-10-14 07:09:13 +00001068 }
1069
Greg Claytondd0e5a52011-06-02 22:22:38 +00001070 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Clayton71337622011-02-24 22:24:29 +00001071
1072 if (!disable_stdio)
1073 {
1074 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Claytonee95ed52011-11-17 22:14:31 +00001075 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Clayton71337622011-02-24 22:24:29 +00001076 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001077 }
1078 }
Greg Claytonc235ac72011-08-09 05:20:29 +00001079 else
1080 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001081 if (log)
1082 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytonc235ac72011-08-09 05:20:29 +00001083 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001084 }
1085 else
1086 {
1087 // Set our user ID to an invalid process ID.
1088 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton982c9762011-11-03 21:22:33 +00001089 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
1090 exe_module->GetFileSpec().GetFilename().AsCString(),
1091 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001092 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001093 return error;
Greg Clayton4957bf62010-09-30 21:49:03 +00001094
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001095}
1096
1097
1098Error
Greg Claytonb766a732011-02-04 01:58:07 +00001099ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001100{
1101 Error error;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001102 // Only connect if we have a valid connect URL
Vince Harron1b5a74e2015-01-21 22:42:49 +00001103 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton00fe87b2013-12-05 22:58:22 +00001104
1105 if (connect_url && connect_url[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001106 {
Vince Harron1b5a74e2015-01-21 22:42:49 +00001107 if (log)
1108 log->Printf("ProcessGDBRemote::%s Connecting to %s", __FUNCTION__, connect_url);
Greg Clayton00fe87b2013-12-05 22:58:22 +00001109 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
1110 if (conn_ap.get())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001111 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001112 const uint32_t max_retry_count = 50;
1113 uint32_t retry_count = 0;
1114 while (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001115 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001116 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
1117 {
1118 m_gdb_comm.SetConnection (conn_ap.release());
1119 break;
1120 }
1121 else if (error.WasInterrupted())
1122 {
1123 // If we were interrupted, don't keep retrying.
1124 break;
1125 }
1126
1127 retry_count++;
1128
1129 if (retry_count >= max_retry_count)
1130 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001131
Greg Clayton00fe87b2013-12-05 22:58:22 +00001132 usleep (100000);
1133 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001134 }
1135 }
1136
1137 if (!m_gdb_comm.IsConnected())
1138 {
1139 if (error.Success())
1140 error.SetErrorString("not connected to remote gdb server");
1141 return error;
1142 }
1143
Greg Clayton32e0a752011-03-30 18:16:51 +00001144 // We always seem to be able to open a connection to a local port
1145 // so we need to make sure we can then send data to it. If we can't
1146 // then we aren't actually connected to anything, so try and do the
1147 // handshake with the remote GDB server and make sure that goes
1148 // alright.
Greg Claytonfb909312013-11-23 01:58:15 +00001149 if (!m_gdb_comm.HandshakeWithServer (&error))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001150 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001151 m_gdb_comm.Disconnect();
1152 if (error.Success())
1153 error.SetErrorString("not connected to remote gdb server");
1154 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001155 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001156 m_gdb_comm.GetThreadSuffixSupported ();
Greg Clayton44633992012-04-10 03:22:03 +00001157 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001158 m_gdb_comm.GetHostInfo ();
1159 m_gdb_comm.GetVContSupported ('c');
Jim Inghamcd16df92012-07-20 21:37:13 +00001160 m_gdb_comm.GetVAttachOrWaitSupported();
Jim Ingham03afad82012-07-02 05:40:07 +00001161
1162 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1163 for (size_t idx = 0; idx < num_cmds; idx++)
1164 {
1165 StringExtractorGDBRemote response;
Jim Ingham03afad82012-07-02 05:40:07 +00001166 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1167 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001168 return error;
1169}
1170
1171void
Jim Inghambb006ce2014-08-02 00:33:35 +00001172ProcessGDBRemote::DidLaunchOrAttach (ArchSpec& process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001173{
Greg Clayton5160ce52013-03-27 23:08:40 +00001174 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001175 if (log)
1176 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton93d3c8332011-02-16 04:46:07 +00001177 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001178 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001179 BuildDynamicRegisterInfo (false);
Greg Clayton3af9ea52010-11-18 05:57:03 +00001180
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001181 // See if the GDB server supports the qHostInfo information
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001182
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001183
1184 // See if the GDB server supports the qProcessInfo packet, if so
1185 // prefer that over the Host information as it will be more specific
1186 // to our process.
1187
Todd Fiala75f47c32014-10-11 21:42:09 +00001188 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1189 if (remote_process_arch.IsValid())
1190 {
1191 process_arch = remote_process_arch;
1192 if (log)
1193 log->Printf ("ProcessGDBRemote::%s gdb-remote had process architecture, using %s %s",
1194 __FUNCTION__,
1195 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1196 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1197 }
Jim Inghambb006ce2014-08-02 00:33:35 +00001198 else
Todd Fiala75f47c32014-10-11 21:42:09 +00001199 {
Jim Inghambb006ce2014-08-02 00:33:35 +00001200 process_arch = m_gdb_comm.GetHostArchitecture();
Todd Fiala75f47c32014-10-11 21:42:09 +00001201 if (log)
1202 log->Printf ("ProcessGDBRemote::%s gdb-remote did not have process architecture, using gdb-remote host architecture %s %s",
1203 __FUNCTION__,
1204 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1205 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1206 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001207
Jim Inghambb006ce2014-08-02 00:33:35 +00001208 if (process_arch.IsValid())
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001209 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001210 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Greg Claytond314e812011-03-23 00:09:55 +00001211 if (target_arch.IsValid())
1212 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001213 if (log)
1214 log->Printf ("ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1215 __FUNCTION__,
1216 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1217 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
1218
1219 // If the remote host is ARM and we have apple as the vendor, then
Greg Claytond314e812011-03-23 00:09:55 +00001220 // ARM executables and shared libraries can have mixed ARM architectures.
1221 // You can have an armv6 executable, and if the host is armv7, then the
1222 // system will load the best possible architecture for all shared libraries
1223 // it has, so we really need to take the remote host architecture as our
1224 // defacto architecture in this case.
1225
Jim Inghambb006ce2014-08-02 00:33:35 +00001226 if (process_arch.GetMachine() == llvm::Triple::arm &&
1227 process_arch.GetTriple().getVendor() == llvm::Triple::Apple)
Greg Claytond314e812011-03-23 00:09:55 +00001228 {
Jason Molenda921c01b2014-08-03 21:42:52 +00001229 GetTarget().SetArchitecture (process_arch);
Todd Fiala75f47c32014-10-11 21:42:09 +00001230 if (log)
1231 log->Printf ("ProcessGDBRemote::%s remote process is ARM/Apple, setting target arch to %s %s",
1232 __FUNCTION__,
1233 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1234 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001235 }
1236 else
1237 {
1238 // Fill in what is missing in the triple
Jim Inghambb006ce2014-08-02 00:33:35 +00001239 const llvm::Triple &remote_triple = process_arch.GetTriple();
Tamas Berghammere724af12015-03-13 10:32:37 +00001240 llvm::Triple new_target_triple = target_arch.GetTriple();
1241 if (new_target_triple.getVendorName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001242 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001243 new_target_triple.setVendor (remote_triple.getVendor());
Greg Claytond314e812011-03-23 00:09:55 +00001244
Tamas Berghammere724af12015-03-13 10:32:37 +00001245 if (new_target_triple.getOSName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001246 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001247 new_target_triple.setOS (remote_triple.getOS());
Greg Claytond314e812011-03-23 00:09:55 +00001248
Tamas Berghammere724af12015-03-13 10:32:37 +00001249 if (new_target_triple.getEnvironmentName().size() == 0)
1250 new_target_triple.setEnvironment (remote_triple.getEnvironment());
Greg Clayton70b57652011-05-15 01:25:55 +00001251 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001252
Tamas Berghammere724af12015-03-13 10:32:37 +00001253 ArchSpec new_target_arch = target_arch;
1254 new_target_arch.SetTriple(new_target_triple);
1255 GetTarget().SetArchitecture(new_target_arch);
1256 }
Greg Claytond314e812011-03-23 00:09:55 +00001257 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001258
1259 if (log)
1260 log->Printf ("ProcessGDBRemote::%s final target arch after adjustments for remote architecture: %s %s",
1261 __FUNCTION__,
1262 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1263 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001264 }
1265 else
1266 {
1267 // The target doesn't have a valid architecture yet, set it from
1268 // the architecture we got from the remote GDB server
Jason Molenda921c01b2014-08-03 21:42:52 +00001269 GetTarget().SetArchitecture (process_arch);
Greg Claytond314e812011-03-23 00:09:55 +00001270 }
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001271 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001272 }
1273}
1274
1275void
1276ProcessGDBRemote::DidLaunch ()
1277{
Jim Inghambb006ce2014-08-02 00:33:35 +00001278 ArchSpec process_arch;
1279 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001280}
1281
1282Error
Greg Claytonc982c762010-07-09 20:39:50 +00001283ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001284{
Han Ming Ong84647042012-02-25 01:07:38 +00001285 ProcessAttachInfo attach_info;
1286 return DoAttachToProcessWithID(attach_pid, attach_info);
1287}
1288
1289Error
1290ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1291{
Todd Fiala75f47c32014-10-11 21:42:09 +00001292 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001293 Error error;
Todd Fiala75f47c32014-10-11 21:42:09 +00001294
1295 if (log)
1296 log->Printf ("ProcessGDBRemote::%s()", __FUNCTION__);
1297
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001298 // Clear out and clean up from any current state
1299 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001300 if (attach_pid != LLDB_INVALID_PROCESS_ID)
1301 {
Greg Clayton71337622011-02-24 22:24:29 +00001302 // Make sure we aren't already connected?
1303 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001304 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001305 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001306
1307 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001308 {
Greg Clayton71337622011-02-24 22:24:29 +00001309 const char *error_string = error.AsCString();
1310 if (error_string == NULL)
1311 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1312
1313 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001314 }
Greg Clayton71337622011-02-24 22:24:29 +00001315 }
1316
1317 if (error.Success())
1318 {
Jim Ingham106d0282014-06-25 02:32:56 +00001319 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
Todd Fiala75f47c32014-10-11 21:42:09 +00001320
Greg Clayton71337622011-02-24 22:24:29 +00001321 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001322 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Greg Clayton3b608422011-11-19 02:11:30 +00001323 SetID (attach_pid);
Greg Clayton71337622011-02-24 22:24:29 +00001324 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001325 }
1326 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001327
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001328 return error;
1329}
1330
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001331Error
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001332ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001333{
1334 Error error;
1335 // Clear out and clean up from any current state
1336 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001337
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001338 if (process_name && process_name[0])
1339 {
Greg Clayton71337622011-02-24 22:24:29 +00001340 // Make sure we aren't already connected?
1341 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001342 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001343 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001344
Greg Clayton71337622011-02-24 22:24:29 +00001345 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001346 {
Greg Clayton71337622011-02-24 22:24:29 +00001347 const char *error_string = error.AsCString();
1348 if (error_string == NULL)
1349 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001350
Greg Clayton71337622011-02-24 22:24:29 +00001351 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001352 }
Greg Clayton71337622011-02-24 22:24:29 +00001353 }
1354
1355 if (error.Success())
1356 {
1357 StreamString packet;
1358
Jim Ingham106d0282014-06-25 02:32:56 +00001359 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1360
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001361 if (attach_info.GetWaitForLaunch())
Jim Inghamcd16df92012-07-20 21:37:13 +00001362 {
1363 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1364 {
1365 packet.PutCString ("vAttachWait");
1366 }
1367 else
1368 {
1369 if (attach_info.GetIgnoreExisting())
1370 packet.PutCString("vAttachWait");
1371 else
1372 packet.PutCString ("vAttachOrWait");
1373 }
1374 }
Greg Clayton71337622011-02-24 22:24:29 +00001375 else
1376 packet.PutCString("vAttachName");
1377 packet.PutChar(';');
1378 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1379
1380 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1381
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001382 }
1383 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001384 return error;
1385}
1386
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001387
Greg Claytonfbb76342013-11-20 21:07:01 +00001388bool
1389ProcessGDBRemote::SetExitStatus (int exit_status, const char *cstr)
1390{
1391 m_gdb_comm.Disconnect();
1392 return Process::SetExitStatus (exit_status, cstr);
1393}
1394
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001395void
Jim Inghambb006ce2014-08-02 00:33:35 +00001396ProcessGDBRemote::DidAttach (ArchSpec &process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001397{
Jim Inghambb006ce2014-08-02 00:33:35 +00001398 // If you can figure out what the architecture is, fill it in here.
1399 process_arch.Clear();
1400 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001401}
1402
Greg Clayton90ba8112012-12-05 00:16:59 +00001403
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001404Error
1405ProcessGDBRemote::WillResume ()
1406{
Greg Clayton71fc2a32011-02-12 06:28:37 +00001407 m_continue_c_tids.clear();
1408 m_continue_C_tids.clear();
1409 m_continue_s_tids.clear();
1410 m_continue_S_tids.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001411 return Error();
1412}
1413
1414Error
1415ProcessGDBRemote::DoResume ()
1416{
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001417 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001418 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001419 if (log)
1420 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytone5219662010-12-03 06:02:24 +00001421
1422 Listener listener ("gdb-remote.resume-packet-sent");
1423 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1424 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00001425 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1426
Greg Claytond1d06e42013-04-20 00:27:58 +00001427 const size_t num_threads = GetThreadList().GetSize();
1428
Greg Clayton71fc2a32011-02-12 06:28:37 +00001429 StreamString continue_packet;
1430 bool continue_packet_error = false;
1431 if (m_gdb_comm.HasAnyVContSupport ())
1432 {
Greg Claytone98008c2014-02-13 23:34:38 +00001433 if (m_continue_c_tids.size() == num_threads ||
1434 (m_continue_c_tids.empty() &&
1435 m_continue_C_tids.empty() &&
1436 m_continue_s_tids.empty() &&
1437 m_continue_S_tids.empty()))
Greg Clayton71fc2a32011-02-12 06:28:37 +00001438 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001439 // All threads are continuing, just send a "c" packet
1440 continue_packet.PutCString ("c");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001441 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001442 else
1443 {
1444 continue_packet.PutCString ("vCont");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001445
Greg Claytond1d06e42013-04-20 00:27:58 +00001446 if (!m_continue_c_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001447 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001448 if (m_gdb_comm.GetVContSupported ('c'))
1449 {
1450 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)
1451 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1452 }
1453 else
1454 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001455 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001456
1457 if (!continue_packet_error && !m_continue_C_tids.empty())
1458 {
1459 if (m_gdb_comm.GetVContSupported ('C'))
1460 {
1461 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)
1462 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1463 }
1464 else
1465 continue_packet_error = true;
1466 }
Greg Claytone5219662010-12-03 06:02:24 +00001467
Greg Claytond1d06e42013-04-20 00:27:58 +00001468 if (!continue_packet_error && !m_continue_s_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001469 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001470 if (m_gdb_comm.GetVContSupported ('s'))
1471 {
1472 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)
1473 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1474 }
1475 else
1476 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001477 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001478
1479 if (!continue_packet_error && !m_continue_S_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001480 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001481 if (m_gdb_comm.GetVContSupported ('S'))
1482 {
1483 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)
1484 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1485 }
1486 else
1487 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001488 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001489
1490 if (continue_packet_error)
1491 continue_packet.GetString().clear();
Greg Clayton71fc2a32011-02-12 06:28:37 +00001492 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001493 }
1494 else
1495 continue_packet_error = true;
1496
1497 if (continue_packet_error)
1498 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001499 // Either no vCont support, or we tried to use part of the vCont
1500 // packet that wasn't supported by the remote GDB server.
1501 // We need to try and make a simple packet that can do our continue
Greg Clayton71fc2a32011-02-12 06:28:37 +00001502 const size_t num_continue_c_tids = m_continue_c_tids.size();
1503 const size_t num_continue_C_tids = m_continue_C_tids.size();
1504 const size_t num_continue_s_tids = m_continue_s_tids.size();
1505 const size_t num_continue_S_tids = m_continue_S_tids.size();
1506 if (num_continue_c_tids > 0)
1507 {
1508 if (num_continue_c_tids == num_threads)
1509 {
1510 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001511 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001512 continue_packet.PutChar ('c');
1513 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001514 }
1515 else if (num_continue_c_tids == 1 &&
1516 num_continue_C_tids == 0 &&
1517 num_continue_s_tids == 0 &&
1518 num_continue_S_tids == 0 )
1519 {
1520 // Only one thread is continuing
Greg Clayton8b82f082011-04-12 05:54:46 +00001521 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001522 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001523 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001524 }
1525 }
1526
Greg Clayton0c74e782011-06-24 03:21:43 +00001527 if (continue_packet_error && num_continue_C_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001528 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001529 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1530 num_continue_C_tids > 0 &&
1531 num_continue_s_tids == 0 &&
1532 num_continue_S_tids == 0 )
Greg Clayton71fc2a32011-02-12 06:28:37 +00001533 {
1534 const int continue_signo = m_continue_C_tids.front().second;
Greg Clayton0c74e782011-06-24 03:21:43 +00001535 // Only one thread is continuing
Greg Clayton71fc2a32011-02-12 06:28:37 +00001536 if (num_continue_C_tids > 1)
1537 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001538 // More that one thread with a signal, yet we don't have
1539 // vCont support and we are being asked to resume each
1540 // thread with a signal, we need to make sure they are
1541 // all the same signal, or we can't issue the continue
1542 // accurately with the current support...
1543 if (num_continue_C_tids > 1)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001544 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001545 continue_packet_error = false;
1546 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1547 {
1548 if (m_continue_C_tids[i].second != continue_signo)
1549 continue_packet_error = true;
1550 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001551 }
Greg Clayton0c74e782011-06-24 03:21:43 +00001552 if (!continue_packet_error)
1553 m_gdb_comm.SetCurrentThreadForRun (-1);
1554 }
1555 else
1556 {
1557 // Set the continue thread ID
1558 continue_packet_error = false;
1559 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001560 }
1561 if (!continue_packet_error)
1562 {
1563 // Add threads continuing with the same signo...
Greg Clayton71fc2a32011-02-12 06:28:37 +00001564 continue_packet.Printf("C%2.2x", continue_signo);
1565 }
1566 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001567 }
1568
Greg Clayton0c74e782011-06-24 03:21:43 +00001569 if (continue_packet_error && num_continue_s_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001570 {
1571 if (num_continue_s_tids == num_threads)
1572 {
1573 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001574 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001575 continue_packet.PutChar ('s');
1576 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001577 }
1578 else if (num_continue_c_tids == 0 &&
1579 num_continue_C_tids == 0 &&
1580 num_continue_s_tids == 1 &&
1581 num_continue_S_tids == 0 )
1582 {
1583 // Only one thread is stepping
Greg Clayton8b82f082011-04-12 05:54:46 +00001584 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001585 continue_packet.PutChar ('s');
Greg Clayton0c74e782011-06-24 03:21:43 +00001586 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001587 }
1588 }
1589
1590 if (!continue_packet_error && num_continue_S_tids > 0)
1591 {
1592 if (num_continue_S_tids == num_threads)
1593 {
1594 const int step_signo = m_continue_S_tids.front().second;
1595 // Are all threads trying to step with the same signal?
Greg Clayton0c74e782011-06-24 03:21:43 +00001596 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001597 if (num_continue_S_tids > 1)
1598 {
1599 for (size_t i=1; i<num_threads; ++i)
1600 {
1601 if (m_continue_S_tids[i].second != step_signo)
1602 continue_packet_error = true;
1603 }
1604 }
1605 if (!continue_packet_error)
1606 {
1607 // Add threads stepping with the same signo...
Greg Clayton8b82f082011-04-12 05:54:46 +00001608 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001609 continue_packet.Printf("S%2.2x", step_signo);
1610 }
1611 }
1612 else if (num_continue_c_tids == 0 &&
1613 num_continue_C_tids == 0 &&
1614 num_continue_s_tids == 0 &&
1615 num_continue_S_tids == 1 )
1616 {
1617 // Only one thread is stepping with signal
Greg Clayton8b82f082011-04-12 05:54:46 +00001618 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001619 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Clayton0c74e782011-06-24 03:21:43 +00001620 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001621 }
1622 }
1623 }
1624
1625 if (continue_packet_error)
1626 {
1627 error.SetErrorString ("can't make continue packet for this resume");
1628 }
1629 else
1630 {
1631 EventSP event_sp;
1632 TimeValue timeout;
1633 timeout = TimeValue::Now();
1634 timeout.OffsetWithSeconds (5);
Zachary Turneracee96a2014-09-23 18:32:09 +00001635 if (!m_async_thread.IsJoinable())
Jim Inghamb1e2e842012-04-12 18:49:31 +00001636 {
1637 error.SetErrorString ("Trying to resume but the async thread is dead.");
1638 if (log)
1639 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1640 return error;
1641 }
1642
Greg Clayton71fc2a32011-02-12 06:28:37 +00001643 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1644
1645 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Inghamb1e2e842012-04-12 18:49:31 +00001646 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001647 error.SetErrorString("Resume timed out.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00001648 if (log)
1649 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1650 }
1651 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1652 {
1653 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1654 if (log)
1655 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1656 return error;
1657 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001658 }
Greg Claytone5219662010-12-03 06:02:24 +00001659 }
1660
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001661 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001662}
1663
Greg Clayton9e920902012-04-10 02:25:43 +00001664void
1665ProcessGDBRemote::ClearThreadIDList ()
1666{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001667 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001668 m_thread_ids.clear();
1669}
1670
1671bool
1672ProcessGDBRemote::UpdateThreadIDList ()
1673{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001674 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001675 bool sequence_mutex_unavailable = false;
1676 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1677 if (sequence_mutex_unavailable)
1678 {
Greg Clayton9e920902012-04-10 02:25:43 +00001679 return false; // We just didn't get the list
1680 }
1681 return true;
1682}
1683
Greg Clayton9fc13552012-04-10 00:18:59 +00001684bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001685ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001686{
1687 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +00001688 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Clayton73b472d2010-10-27 03:32:59 +00001689 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +00001690 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton9e920902012-04-10 02:25:43 +00001691
1692 size_t num_thread_ids = m_thread_ids.size();
1693 // The "m_thread_ids" thread ID list should always be updated after each stop
1694 // reply packet, but in case it isn't, update it here.
1695 if (num_thread_ids == 0)
1696 {
1697 if (!UpdateThreadIDList ())
1698 return false;
1699 num_thread_ids = m_thread_ids.size();
1700 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001701
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001702 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001703 if (num_thread_ids > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001704 {
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001705 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001706 {
Greg Clayton9e920902012-04-10 02:25:43 +00001707 tid_t tid = m_thread_ids[i];
Greg Clayton160c9d82013-05-01 21:54:04 +00001708 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001709 if (!thread_sp)
Jim Inghamdee1bc92013-06-22 00:27:45 +00001710 {
Jim Ingham4f465cf2012-10-10 18:32:14 +00001711 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001712 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1713 log->Printf(
1714 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001715 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001716 thread_sp->GetID());
1717 }
1718 else
1719 {
1720 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1721 log->Printf(
1722 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001723 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001724 thread_sp->GetID());
1725 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001726 new_thread_list.AddThread(thread_sp);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001727 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001728 }
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001729
1730 // Whatever that is left in old_thread_list_copy are not
1731 // present in new_thread_list. Remove non-existent threads from internal id table.
1732 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1733 for (size_t i=0; i<old_num_thread_ids; i++)
1734 {
1735 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1736 if (old_thread_sp)
1737 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001738 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001739 m_thread_id_to_index_id_map.erase(old_thread_id);
1740 }
1741 }
1742
Greg Clayton9fc13552012-04-10 00:18:59 +00001743 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001744}
1745
1746
1747StateType
1748ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1749{
Greg Claytondd0e5a52011-06-02 22:22:38 +00001750 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001751 const char stop_type = stop_packet.GetChar();
1752 switch (stop_type)
1753 {
1754 case 'T':
1755 case 'S':
1756 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00001757 // This is a bit of a hack, but is is required. If we did exec, we
1758 // need to clear our thread lists and also know to rebuild our dynamic
1759 // register info before we lookup and threads and populate the expedited
1760 // register values so we need to know this right away so we can cleanup
1761 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00001762 const uint32_t stop_id = GetStopID();
1763 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00001764 {
1765 // Our first stop, make sure we have a process ID, and also make
1766 // sure we know about our registers
1767 if (GetID() == LLDB_INVALID_PROCESS_ID)
1768 {
Greg Claytonc574ede2011-03-10 02:26:48 +00001769 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00001770 if (pid != LLDB_INVALID_PROCESS_ID)
1771 SetID (pid);
1772 }
1773 BuildDynamicRegisterInfo (true);
1774 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001775 // Stop with signal and thread info
1776 const uint8_t signo = stop_packet.GetHexU8();
1777 std::string name;
1778 std::string value;
1779 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00001780 std::string reason;
1781 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001782 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00001783 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001784 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001785 ThreadSP thread_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001786 ThreadGDBRemote *gdb_thread = NULL;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001787
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001788 while (stop_packet.GetNameColonValue(name, value))
1789 {
1790 if (name.compare("metype") == 0)
1791 {
1792 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001793 exc_type = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001794 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001795 else if (name.compare("medata") == 0)
1796 {
1797 // exception data in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001798 exc_data.push_back(StringConvert::ToUInt64 (value.c_str(), 0, 16));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001799 }
1800 else if (name.compare("thread") == 0)
1801 {
1802 // thread in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001803 lldb::tid_t tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001804 // m_thread_list_real does have its own mutex, but we need to
1805 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1806 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1807 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1808 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
Greg Clayton160c9d82013-05-01 21:54:04 +00001809
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001810 if (!thread_sp)
Greg Claytond1d06e42013-04-20 00:27:58 +00001811 {
Greg Claytone576ab22011-02-15 00:19:15 +00001812 // Create the thread if we need to
Jim Ingham4f465cf2012-10-10 18:32:14 +00001813 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001814 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
1815 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1816 log->Printf ("ProcessGDBRemote::%s Adding new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1817 __FUNCTION__,
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001818 static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001819 thread_sp->GetID());
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001820
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001821 m_thread_list_real.AddThread(thread_sp);
Greg Claytone576ab22011-02-15 00:19:15 +00001822 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001823 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1824
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001825 }
Greg Clayton9e920902012-04-10 02:25:43 +00001826 else if (name.compare("threads") == 0)
1827 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001828 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001829 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00001830 // A comma separated list of all threads in the current
1831 // process that includes the thread for this stop reply
1832 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00001833 size_t comma_pos;
1834 lldb::tid_t tid;
1835 while ((comma_pos = value.find(',')) != std::string::npos)
1836 {
1837 value[comma_pos] = '\0';
1838 // thread in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001839 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00001840 if (tid != LLDB_INVALID_THREAD_ID)
1841 m_thread_ids.push_back (tid);
1842 value.erase(0, comma_pos + 1);
Greg Clayton9e920902012-04-10 02:25:43 +00001843 }
Vince Harron5275aaa2015-01-15 20:08:35 +00001844 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00001845 if (tid != LLDB_INVALID_THREAD_ID)
1846 m_thread_ids.push_back (tid);
1847 }
Greg Claytonde9d0492011-01-08 03:17:57 +00001848 else if (name.compare("hexname") == 0)
1849 {
1850 StringExtractor name_extractor;
1851 // Swap "value" over into "name_extractor"
1852 name_extractor.GetStringRef().swap(value);
1853 // Now convert the HEX bytes into a string value
1854 name_extractor.GetHexByteString (value);
1855 thread_name.swap (value);
1856 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001857 else if (name.compare("name") == 0)
1858 {
1859 thread_name.swap (value);
1860 }
Greg Clayton6f35f5c2010-09-09 06:32:46 +00001861 else if (name.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001862 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001863 thread_dispatch_qaddr = StringConvert::ToUInt64 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001864 }
Greg Claytona658fd22011-06-04 01:26:29 +00001865 else if (name.compare("reason") == 0)
1866 {
1867 reason.swap(value);
1868 }
1869 else if (name.compare("description") == 0)
1870 {
1871 StringExtractor desc_extractor;
1872 // Swap "value" over into "name_extractor"
1873 desc_extractor.GetStringRef().swap(value);
1874 // Now convert the HEX bytes into a string value
Chaoren Lin28e57422015-02-03 01:51:25 +00001875 desc_extractor.GetHexByteString (value);
1876 description.swap(value);
Greg Claytona658fd22011-06-04 01:26:29 +00001877 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001878 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1879 {
1880 // We have a register number that contains an expedited
1881 // register value. Lets supply this register to our thread
1882 // so it won't have to go and read it.
Greg Clayton160c9d82013-05-01 21:54:04 +00001883 if (gdb_thread)
Greg Clayton3e06bd92011-01-09 21:07:35 +00001884 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001885 uint32_t reg = StringConvert::ToUInt32 (name.c_str(), UINT32_MAX, 16);
Greg Clayton3e06bd92011-01-09 21:07:35 +00001886
1887 if (reg != UINT32_MAX)
1888 {
1889 StringExtractor reg_value_extractor;
1890 // Swap "value" over into "reg_value_extractor"
1891 reg_value_extractor.GetStringRef().swap(value);
Greg Clayton160c9d82013-05-01 21:54:04 +00001892 if (!gdb_thread->PrivateSetRegisterValue (reg, reg_value_extractor))
Greg Claytone576ab22011-02-15 00:19:15 +00001893 {
1894 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1895 name.c_str(),
1896 reg,
1897 reg,
1898 reg_value_extractor.GetStringRef().c_str(),
1899 stop_packet.GetStringRef().c_str());
1900 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001901 }
1902 }
1903 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001904 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001905
Hafiz Abid Qadeer673b4a32014-02-20 10:23:20 +00001906 // If the response is old style 'S' packet which does not provide us with thread information
1907 // then update the thread list and choose the first one.
1908 if (!thread_sp)
1909 {
1910 UpdateThreadIDList ();
1911
1912 if (!m_thread_ids.empty ())
1913 {
1914 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1915 thread_sp = m_thread_list_real.FindThreadByProtocolID (m_thread_ids.front (), false);
1916 if (thread_sp)
1917 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get ());
1918 }
1919 }
1920
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001921 if (thread_sp)
1922 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001923 // Clear the stop info just in case we don't set it to anything
1924 thread_sp->SetStopInfo (StopInfoSP());
1925
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001926 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Inghamdd2fe7a2011-01-28 02:23:12 +00001927 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001928 if (exc_type != 0)
1929 {
Greg Clayton1a65ae12011-01-25 23:55:37 +00001930 const size_t exc_data_size = exc_data.size();
Greg Claytonf4b47e12010-08-04 01:40:35 +00001931
Greg Clayton160c9d82013-05-01 21:54:04 +00001932 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1933 exc_type,
1934 exc_data_size,
1935 exc_data_size >= 1 ? exc_data[0] : 0,
1936 exc_data_size >= 2 ? exc_data[1] : 0,
1937 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001938 }
Greg Claytona658fd22011-06-04 01:26:29 +00001939 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001940 {
Greg Claytona658fd22011-06-04 01:26:29 +00001941 bool handled = false;
Greg Clayton8cda7f02013-05-21 21:55:59 +00001942 bool did_exec = false;
Greg Claytona658fd22011-06-04 01:26:29 +00001943 if (!reason.empty())
1944 {
1945 if (reason.compare("trace") == 0)
1946 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001947 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Greg Claytona658fd22011-06-04 01:26:29 +00001948 handled = true;
1949 }
1950 else if (reason.compare("breakpoint") == 0)
1951 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001952 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1953 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Claytona658fd22011-06-04 01:26:29 +00001954 if (bp_site_sp)
1955 {
1956 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1957 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1958 // 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 +00001959 handled = true;
Greg Clayton160c9d82013-05-01 21:54:04 +00001960 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00001961 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001962 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00001963 }
1964 else
1965 {
1966 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001967 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00001968 }
1969 }
Greg Claytona658fd22011-06-04 01:26:29 +00001970 }
1971 else if (reason.compare("trap") == 0)
1972 {
1973 // Let the trap just use the standard signal stop reason below...
1974 }
1975 else if (reason.compare("watchpoint") == 0)
1976 {
Chaoren Lin18fe6402015-02-03 01:51:47 +00001977 StringExtractor desc_extractor(description.c_str());
1978 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1979 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
1980 watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
1981 if (wp_addr != LLDB_INVALID_ADDRESS)
1982 {
1983 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
1984 if (wp_sp)
1985 {
1986 wp_sp->SetHardwareIndex(wp_index);
1987 watch_id = wp_sp->GetID();
1988 }
1989 }
1990 if (watch_id == LLDB_INVALID_WATCH_ID)
1991 {
1992 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_WATCHPOINTS));
1993 if (log) log->Printf ("failed to find watchpoint");
1994 }
Greg Clayton160c9d82013-05-01 21:54:04 +00001995 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
Greg Claytona658fd22011-06-04 01:26:29 +00001996 handled = true;
1997 }
1998 else if (reason.compare("exception") == 0)
1999 {
Greg Clayton160c9d82013-05-01 21:54:04 +00002000 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00002001 handled = true;
2002 }
Greg Clayton15fc2be2013-05-21 01:00:52 +00002003 else if (reason.compare("exec") == 0)
2004 {
Greg Clayton8cda7f02013-05-21 21:55:59 +00002005 did_exec = true;
Greg Clayton15fc2be2013-05-21 01:00:52 +00002006 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
2007 handled = true;
2008 }
Greg Claytona658fd22011-06-04 01:26:29 +00002009 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00002010
Jim Ingham40083a42014-02-24 19:49:46 +00002011 if (!handled && signo && did_exec == false)
Greg Claytona658fd22011-06-04 01:26:29 +00002012 {
2013 if (signo == SIGTRAP)
2014 {
2015 // Currently we are going to assume SIGTRAP means we are either
2016 // hitting a breakpoint or hardware single stepping.
Jim Ingham54cc6e42012-07-11 21:41:19 +00002017 handled = true;
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +00002018 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
Greg Clayton160c9d82013-05-01 21:54:04 +00002019 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00002020
Greg Claytona658fd22011-06-04 01:26:29 +00002021 if (bp_site_sp)
2022 {
2023 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2024 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2025 // 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 +00002026 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00002027 {
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +00002028 if(m_breakpoint_pc_offset != 0)
2029 thread_sp->GetRegisterContext()->SetPC(pc);
Greg Clayton160c9d82013-05-01 21:54:04 +00002030 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00002031 }
2032 else
2033 {
2034 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00002035 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00002036 }
2037 }
Jim Ingham54cc6e42012-07-11 21:41:19 +00002038 else
Greg Claytona658fd22011-06-04 01:26:29 +00002039 {
Jim Ingham4dc613b2012-10-27 02:52:04 +00002040 // If we were stepping then assume the stop was the result of the trace. If we were
2041 // not stepping then report the SIGTRAP.
2042 // FIXME: We are still missing the case where we single step over a trap instruction.
Greg Clayton160c9d82013-05-01 21:54:04 +00002043 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
2044 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Jim Ingham4dc613b2012-10-27 02:52:04 +00002045 else
Greg Clayton160c9d82013-05-01 21:54:04 +00002046 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo));
Greg Claytona658fd22011-06-04 01:26:29 +00002047 }
2048 }
2049 if (!handled)
Greg Clayton160c9d82013-05-01 21:54:04 +00002050 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Jason Molenda8214b012013-04-25 01:33:46 +00002051 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00002052
Greg Claytona658fd22011-06-04 01:26:29 +00002053 if (!description.empty())
2054 {
Greg Clayton160c9d82013-05-01 21:54:04 +00002055 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
Greg Claytona658fd22011-06-04 01:26:29 +00002056 if (stop_info_sp)
2057 {
2058 stop_info_sp->SetDescription (description.c_str());
Greg Clayton3418c852011-08-10 02:10:13 +00002059 }
Greg Claytona658fd22011-06-04 01:26:29 +00002060 else
2061 {
Greg Clayton160c9d82013-05-01 21:54:04 +00002062 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00002063 }
2064 }
2065 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002066 }
2067 return eStateStopped;
2068 }
2069 break;
2070
2071 case 'W':
Todd Fialaff6131a2014-05-19 04:57:23 +00002072 case 'X':
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002073 // process exited
2074 return eStateExited;
2075
2076 default:
2077 break;
2078 }
2079 return eStateInvalid;
2080}
2081
2082void
2083ProcessGDBRemote::RefreshStateAfterStop ()
2084{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002085 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00002086 m_thread_ids.clear();
2087 // Set the thread stop info. It might have a "threads" key whose value is
2088 // a list of all thread IDs in the current process, so m_thread_ids might
2089 // get set.
2090 SetThreadStopInfo (m_last_stop_packet);
2091 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2092 if (m_thread_ids.empty())
2093 {
2094 // No, we need to fetch the thread list manually
2095 UpdateThreadIDList();
2096 }
2097
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002098 // Let all threads recover from stopping and do any clean up based
2099 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002100 m_thread_list_real.RefreshStateAfterStop();
Greg Clayton9e920902012-04-10 02:25:43 +00002101
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002102}
2103
2104Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002105ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002106{
2107 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002108
Greg Clayton6ed95942011-01-22 07:12:45 +00002109 bool timed_out = false;
2110 Mutex::Locker locker;
Greg Clayton513c26c2011-01-29 07:10:55 +00002111
2112 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002113 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002114 // We are being asked to halt during an attach. We need to just close
2115 // our file handle and debugserver will go away, and we can be done...
2116 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00002117 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002118 else
2119 {
Greg Clayton2687cd12012-03-29 01:55:41 +00002120 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton513c26c2011-01-29 07:10:55 +00002121 {
2122 if (timed_out)
2123 error.SetErrorString("timed out sending interrupt packet");
2124 else
2125 error.SetErrorString("unknown error sending interrupt packet");
2126 }
Greg Clayton2687cd12012-03-29 01:55:41 +00002127
2128 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton513c26c2011-01-29 07:10:55 +00002129 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002130 return error;
2131}
2132
2133Error
Jim Inghamacff8952013-05-02 00:27:30 +00002134ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002135{
2136 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002137 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00002138 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00002139 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2140
Jim Inghamacff8952013-05-02 00:27:30 +00002141 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002142 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002143 {
Jim Inghamacff8952013-05-02 00:27:30 +00002144 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002145 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
2146 else
Jim Inghamacff8952013-05-02 00:27:30 +00002147 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00002148 }
Jim Inghamacff8952013-05-02 00:27:30 +00002149
2150 if (!error.Success())
2151 return error;
2152
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002153 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00002154 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002155
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002156 SetPrivateState (eStateDetached);
2157 ResumePrivateStateThread();
2158
2159 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00002160 return error;
2161}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002162
Jim Ingham43c555d2012-07-04 00:35:43 +00002163
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002164Error
2165ProcessGDBRemote::DoDestroy ()
2166{
2167 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002168 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002169 if (log)
2170 log->Printf ("ProcessGDBRemote::DoDestroy()");
2171
Jim Ingham43c555d2012-07-04 00:35:43 +00002172 // There is a bug in older iOS debugservers where they don't shut down the process
2173 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
2174 // this can cause problems with restarting. So we check to see if any of our threads are stopped
2175 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
2176 // destroy it again.
2177 //
2178 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
2179 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
2180 // the debugservers with this bug are equal. There really should be a better way to test this!
2181 //
2182 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
2183 // get called here to destroy again and we're still at a breakpoint or exception, then we should
2184 // just do the straight-forward kill.
2185 //
2186 // And of course, if we weren't able to stop the process by the time we get here, it isn't
2187 // necessary (or helpful) to do any of this.
2188
2189 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
2190 {
2191 PlatformSP platform_sp = GetTarget().GetPlatform();
2192
2193 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2194 if (platform_sp
2195 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00002196 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00002197 {
2198 if (m_destroy_tried_resuming)
2199 {
2200 if (log)
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002201 log->PutCString ("ProcessGDBRemote::DoDestroy() - Tried resuming to destroy once already, not doing it again.");
Jim Ingham43c555d2012-07-04 00:35:43 +00002202 }
2203 else
2204 {
2205 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
2206 // but we really need it to happen here and it doesn't matter if we do it twice.
2207 m_thread_list.DiscardThreadPlans();
2208 DisableAllBreakpointSites();
2209
2210 bool stop_looks_like_crash = false;
2211 ThreadList &threads = GetThreadList();
2212
2213 {
Jim Ingham45350372012-09-11 00:08:52 +00002214 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002215
2216 size_t num_threads = threads.GetSize();
2217 for (size_t i = 0; i < num_threads; i++)
2218 {
2219 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002220 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002221 StopReason reason = eStopReasonInvalid;
2222 if (stop_info_sp)
2223 reason = stop_info_sp->GetStopReason();
2224 if (reason == eStopReasonBreakpoint
2225 || reason == eStopReasonException)
2226 {
2227 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002228 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
2229 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00002230 stop_info_sp->GetDescription());
2231 stop_looks_like_crash = true;
2232 break;
2233 }
2234 }
2235 }
2236
2237 if (stop_looks_like_crash)
2238 {
2239 if (log)
2240 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
2241 m_destroy_tried_resuming = true;
2242
2243 // If we are going to run again before killing, it would be good to suspend all the threads
2244 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
2245 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
2246 // have to run the risk of letting those threads proceed a bit.
2247
2248 {
Jim Ingham45350372012-09-11 00:08:52 +00002249 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002250
2251 size_t num_threads = threads.GetSize();
2252 for (size_t i = 0; i < num_threads; i++)
2253 {
2254 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002255 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002256 StopReason reason = eStopReasonInvalid;
2257 if (stop_info_sp)
2258 reason = stop_info_sp->GetStopReason();
2259 if (reason != eStopReasonBreakpoint
2260 && reason != eStopReasonException)
2261 {
2262 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002263 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
2264 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00002265 thread_sp->SetResumeState(eStateSuspended);
2266 }
2267 }
2268 }
2269 Resume ();
Jason Molendaede31932015-04-17 05:01:58 +00002270 return Destroy(false);
Jim Ingham43c555d2012-07-04 00:35:43 +00002271 }
2272 }
2273 }
2274 }
2275
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002276 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00002277 int exit_status = SIGABRT;
2278 std::string exit_string;
2279
Greg Clayton6ed95942011-01-22 07:12:45 +00002280 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002281 {
Jim Inghamaab78372011-10-28 01:11:35 +00002282 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00002283 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002284 StringExtractorGDBRemote response;
2285 bool send_async = true;
Tamas Berghammer912800c2015-02-24 10:23:39 +00002286 GDBRemoteCommunication::ScopedTimeout (m_gdb_comm, 3);
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002287
Greg Clayton3dedae12013-12-06 21:45:27 +00002288 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton513c26c2011-01-29 07:10:55 +00002289 {
2290 char packet_cmd = response.GetChar(0);
2291
2292 if (packet_cmd == 'W' || packet_cmd == 'X')
2293 {
Jim Inghameac0aa42014-02-21 22:36:11 +00002294#if defined(__APPLE__)
Jim Ingham9d67cc52014-02-21 22:35:29 +00002295 // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off
2296 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill
2297 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns
2298 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap
2299 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of
2300 // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2301 // Anyway, so call waitpid here to finally reap it.
2302 PlatformSP platform_sp(GetTarget().GetPlatform());
2303 if (platform_sp && platform_sp->IsHost())
2304 {
2305 int status;
2306 ::pid_t reap_pid;
2307 reap_pid = waitpid (GetID(), &status, WNOHANG);
2308 if (log)
2309 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2310 }
2311#endif
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002312 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002313 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00002314 exit_status = response.GetHexU8();
2315 }
2316 else
2317 {
2318 if (log)
2319 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2320 exit_string.assign("got unexpected response to k packet: ");
2321 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00002322 }
2323 }
2324 else
2325 {
Jim Inghambabfc382012-06-06 00:32:39 +00002326 if (log)
2327 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2328 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00002329 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002330 }
Jim Inghambabfc382012-06-06 00:32:39 +00002331 else
2332 {
2333 if (log)
Ed Masteb3a53332014-03-17 17:05:22 +00002334 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching");
Jim Inghamcfc09352012-07-27 23:57:19 +00002335 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00002336 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002337 }
Jim Inghambabfc382012-06-06 00:32:39 +00002338 else
2339 {
2340 // If we missed setting the exit status on the way out, do it here.
2341 // NB set exit status can be called multiple times, the first one sets the status.
2342 exit_string.assign("destroying when not connected to debugserver");
2343 }
2344
2345 SetExitStatus(exit_status, exit_string.c_str());
2346
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002347 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002348 KillDebugserverProcess ();
2349 return error;
2350}
2351
Greg Clayton8cda7f02013-05-21 21:55:59 +00002352void
2353ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2354{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00002355 Mutex::Locker locker (m_last_stop_packet_mutex);
Greg Clayton8cda7f02013-05-21 21:55:59 +00002356 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2357 if (did_exec)
2358 {
2359 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2360 if (log)
2361 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2362
2363 m_thread_list_real.Clear();
2364 m_thread_list.Clear();
2365 BuildDynamicRegisterInfo (true);
2366 m_gdb_comm.ResetDiscoverableSettings();
2367 }
2368 m_last_stop_packet = response;
2369}
2370
2371
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002372//------------------------------------------------------------------
2373// Process Queries
2374//------------------------------------------------------------------
2375
2376bool
2377ProcessGDBRemote::IsAlive ()
2378{
Greg Clayton10177aa2010-12-08 05:08:21 +00002379 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002380}
2381
2382addr_t
2383ProcessGDBRemote::GetImageInfoAddress()
2384{
Aidan Doddsc0c83852015-05-08 09:36:31 +00002385 // request the link map address via the $qShlibInfoAddr packet
2386 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2387
2388 // the loaded module list can also provides a link map address
2389 if (addr == LLDB_INVALID_ADDRESS)
2390 {
2391 GDBLoadedModuleInfoList list;
2392 if (GetLoadedModuleList (list).Success())
2393 addr = list.m_link_map;
2394 }
2395
2396 return addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002397}
2398
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002399//------------------------------------------------------------------
2400// Process Memory
2401//------------------------------------------------------------------
2402size_t
2403ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2404{
Jason Molenda6076bf42014-05-06 04:34:52 +00002405 GetMaxMemorySize ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002406 if (size > m_max_memory_size)
2407 {
2408 // Keep memory read sizes down to a sane limit. This function will be
2409 // called multiple times in order to complete the task by
2410 // lldb_private::Process so it is ok to do this.
2411 size = m_max_memory_size;
2412 }
2413
2414 char packet[64];
Jason Molenda6076bf42014-05-06 04:34:52 +00002415 int packet_len;
2416 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2417 if (binary_memory_read)
2418 {
2419 packet_len = ::snprintf (packet, sizeof(packet), "x0x%" PRIx64 ",0x%" PRIx64, (uint64_t)addr, (uint64_t)size);
2420 }
2421 else
2422 {
2423 packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
2424 }
Andy Gibbsa297a972013-06-19 19:04:53 +00002425 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002426 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002427 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002428 {
Greg Clayton576d8832011-03-22 04:00:09 +00002429 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002430 {
2431 error.Clear();
Jason Molenda6076bf42014-05-06 04:34:52 +00002432 if (binary_memory_read)
2433 {
2434 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any
2435 // 0x7d character escaping that was present in the packet
2436
2437 size_t data_received_size = response.GetBytesLeft();
2438 if (data_received_size > size)
2439 {
2440 // Don't write past the end of BUF if the remote debug server gave us too
2441 // much data for some reason.
2442 data_received_size = size;
2443 }
2444 memcpy (buf, response.GetStringRef().data(), data_received_size);
2445 return data_received_size;
2446 }
2447 else
2448 {
2449 return response.GetHexBytes(buf, size, '\xdd');
2450 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002451 }
Greg Clayton576d8832011-03-22 04:00:09 +00002452 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002453 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002454 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002455 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002456 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002457 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002458 }
2459 else
2460 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002461 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002462 }
2463 return 0;
2464}
2465
2466size_t
2467ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2468{
Jason Molenda6076bf42014-05-06 04:34:52 +00002469 GetMaxMemorySize ();
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002470 if (size > m_max_memory_size)
2471 {
2472 // Keep memory read sizes down to a sane limit. This function will be
2473 // called multiple times in order to complete the task by
2474 // lldb_private::Process so it is ok to do this.
2475 size = m_max_memory_size;
2476 }
2477
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002478 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00002479 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Clayton7fb56d02011-02-01 01:31:41 +00002480 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002481 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002482 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002483 {
Greg Clayton576d8832011-03-22 04:00:09 +00002484 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002485 {
2486 error.Clear();
2487 return size;
2488 }
Greg Clayton576d8832011-03-22 04:00:09 +00002489 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002490 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002491 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002492 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002493 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002494 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 +00002495 }
2496 else
2497 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002498 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002499 }
2500 return 0;
2501}
2502
2503lldb::addr_t
2504ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2505{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00002506 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_EXPRESSIONS));
Greg Clayton2a48f522011-05-14 01:50:35 +00002507 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2508
Greg Clayton70b57652011-05-15 01:25:55 +00002509 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton2a48f522011-05-14 01:50:35 +00002510 switch (supported)
2511 {
2512 case eLazyBoolCalculate:
2513 case eLazyBoolYes:
2514 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2515 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2516 return allocated_addr;
2517
2518 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002519 // Call mmap() to create memory in the inferior..
2520 unsigned prot = 0;
2521 if (permissions & lldb::ePermissionsReadable)
2522 prot |= eMmapProtRead;
2523 if (permissions & lldb::ePermissionsWritable)
2524 prot |= eMmapProtWrite;
2525 if (permissions & lldb::ePermissionsExecutable)
2526 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00002527
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002528 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2529 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2530 m_addr_to_mmap_size[allocated_addr] = size;
2531 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002532 {
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002533 allocated_addr = LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00002534 if (log)
2535 log->Printf ("ProcessGDBRemote::%s no direct stub support for memory allocation, and InferiorCallMmap also failed - is stub missing register context save/restore capability?", __FUNCTION__);
2536 }
Greg Clayton2a48f522011-05-14 01:50:35 +00002537 break;
2538 }
2539
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002540 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00002541 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002542 else
2543 error.Clear();
2544 return allocated_addr;
2545}
2546
2547Error
Greg Clayton46fb5582011-11-18 07:03:08 +00002548ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2549 MemoryRegionInfo &region_info)
2550{
2551
2552 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2553 return error;
2554}
2555
2556Error
Johnny Chen64637202012-05-23 21:09:52 +00002557ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2558{
2559
2560 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2561 return error;
2562}
2563
2564Error
Enrico Granataf04a2192012-07-13 23:18:48 +00002565ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2566{
2567 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2568 return error;
2569}
2570
2571Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002572ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2573{
2574 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00002575 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2576
2577 switch (supported)
2578 {
2579 case eLazyBoolCalculate:
2580 // We should never be deallocating memory without allocating memory
2581 // first so we should never get eLazyBoolCalculate
2582 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2583 break;
2584
2585 case eLazyBoolYes:
2586 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00002587 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002588 break;
2589
2590 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002591 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00002592 {
2593 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002594 if (pos != m_addr_to_mmap_size.end() &&
2595 InferiorCallMunmap(this, addr, pos->second))
2596 m_addr_to_mmap_size.erase (pos);
2597 else
Daniel Malead01b2952012-11-29 21:49:15 +00002598 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002599 }
2600 break;
2601 }
2602
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002603 return error;
2604}
2605
2606
2607//------------------------------------------------------------------
2608// Process STDIO
2609//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002610size_t
2611ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2612{
2613 if (m_stdio_communication.IsConnected())
2614 {
2615 ConnectionStatus status;
2616 m_stdio_communication.Write(src, src_len, status, NULL);
2617 }
Vince Harrondf3f00f2015-02-10 21:09:04 +00002618 else if (m_stdin_forward)
Vince Harrone0be4252015-02-06 18:32:57 +00002619 {
2620 m_gdb_comm.SendStdinNotification(src, src_len);
2621 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002622 return 0;
2623}
2624
2625Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002626ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002627{
2628 Error error;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002629 assert(bp_site != NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002630
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002631 // Get logging info
2632 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002633 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002634
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002635 // Get the breakpoint address
2636 const addr_t addr = bp_site->GetLoadAddress();
2637
2638 // Log that a breakpoint was requested
2639 if (log)
2640 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
2641
2642 // Breakpoint already exists and is enabled
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002643 if (bp_site->IsEnabled())
2644 {
2645 if (log)
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002646 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 +00002647 return error;
2648 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002649
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002650 // Get the software breakpoint trap opcode size
2651 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2652
2653 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
2654 // is supported by the remote stub. These are set to true by default, and later set to false
2655 // only after we receive an unimplemented response when sending a breakpoint packet. This means
2656 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
2657 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
2658 // indicates if the user specifically asked for hardware breakpoints. If true then we will
2659 // skip over software breakpoints.
2660 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
2661 {
2662 // Try to send off a software breakpoint packet ($Z0)
2663 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002664 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002665 // The breakpoint was placed successfully
2666 bp_site->SetEnabled(true);
2667 bp_site->SetType(BreakpointSite::eExternal);
Greg Claytoneb023e72013-10-11 19:48:25 +00002668 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002669 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002670
2671 // SendGDBStoppointTypePacket() will return an error if it was unable to set this
2672 // breakpoint. We need to differentiate between a error specific to placing this breakpoint
2673 // or if we have learned that this breakpoint type is unsupported. To do this, we
2674 // must test the support boolean for this breakpoint type to see if it now indicates that
2675 // this breakpoint type is unsupported. If they are still supported then we should return
2676 // with the error code. If they are now unsupported, then we would like to fall through
2677 // and try another form of breakpoint.
2678 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
2679 return error;
2680
2681 // We reach here when software breakpoints have been found to be unsupported. For future
2682 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
2683 // known not to be supported.
2684 if (log)
2685 log->Printf("Software breakpoints are unsupported");
2686
2687 // So we will fall through and try a hardware breakpoint
2688 }
2689
2690 // The process of setting a hardware breakpoint is much the same as above. We check the
2691 // supported boolean for this breakpoint type, and if it is thought to be supported then we
2692 // will try to set this breakpoint with a hardware breakpoint.
2693 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
2694 {
2695 // Try to send off a hardware breakpoint packet ($Z1)
2696 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002697 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002698 // The breakpoint was placed successfully
2699 bp_site->SetEnabled(true);
2700 bp_site->SetType(BreakpointSite::eHardware);
2701 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002702 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002703
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002704 // Check if the error was something other then an unsupported breakpoint type
2705 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
2706 {
2707 // Unable to set this hardware breakpoint
2708 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
2709 return error;
2710 }
2711
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002712 // We will reach here when the stub gives an unsupported response to a hardware breakpoint
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002713 if (log)
2714 log->Printf("Hardware breakpoints are unsupported");
2715
2716 // Finally we will falling through to a #trap style breakpoint
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002717 }
2718
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002719 // Don't fall through when hardware breakpoints were specifically requested
2720 if (bp_site->HardwareRequired())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002721 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002722 error.SetErrorString("hardware breakpoints are not supported");
2723 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002724 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002725
2726 // As a last resort we want to place a manual breakpoint. An instruction
2727 // is placed into the process memory using memory write packets.
2728 return EnableSoftwareBreakpoint(bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002729}
2730
2731Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002732ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002733{
2734 Error error;
2735 assert (bp_site != NULL);
2736 addr_t addr = bp_site->GetLoadAddress();
2737 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00002738 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002739 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002740 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002741
2742 if (bp_site->IsEnabled())
2743 {
2744 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2745
Greg Clayton8b82f082011-04-12 05:54:46 +00002746 BreakpointSite::Type bp_type = bp_site->GetType();
2747 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002748 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002749 case BreakpointSite::eSoftware:
2750 error = DisableSoftwareBreakpoint (bp_site);
2751 break;
2752
2753 case BreakpointSite::eHardware:
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002754 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00002755 error.SetErrorToGenericError();
2756 break;
2757
2758 case BreakpointSite::eExternal:
Jim Inghama04ef752014-03-07 11:18:02 +00002759 {
2760 GDBStoppointType stoppoint_type;
2761 if (bp_site->IsHardware())
2762 stoppoint_type = eBreakpointHardware;
2763 else
2764 stoppoint_type = eBreakpointSoftware;
2765
2766 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00002767 error.SetErrorToGenericError();
Jim Inghama04ef752014-03-07 11:18:02 +00002768 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002769 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002770 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002771 if (error.Success())
2772 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002773 }
2774 else
2775 {
2776 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002777 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 +00002778 return error;
2779 }
2780
2781 if (error.Success())
2782 error.SetErrorToGenericError();
2783 return error;
2784}
2785
Johnny Chen11309a32011-09-06 22:38:36 +00002786// Pre-requisite: wp != NULL.
2787static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00002788GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00002789{
2790 assert(wp);
2791 bool watch_read = wp->WatchpointRead();
2792 bool watch_write = wp->WatchpointWrite();
2793
2794 // watch_read and watch_write cannot both be false.
2795 assert(watch_read || watch_write);
2796 if (watch_read && watch_write)
2797 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00002798 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00002799 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00002800 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00002801 return eWatchpointWrite;
2802}
2803
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002804Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002805ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002806{
2807 Error error;
2808 if (wp)
2809 {
2810 user_id_t watchID = wp->GetID();
2811 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00002812 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002813 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002814 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002815 if (wp->IsEnabled())
2816 {
2817 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002818 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 +00002819 return error;
2820 }
Johnny Chen11309a32011-09-06 22:38:36 +00002821
2822 GDBStoppointType type = GetGDBStoppointType(wp);
2823 // Pass down an appropriate z/Z packet...
2824 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002825 {
Johnny Chen11309a32011-09-06 22:38:36 +00002826 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2827 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002828 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002829 return error;
2830 }
2831 else
2832 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002833 }
Johnny Chen11309a32011-09-06 22:38:36 +00002834 else
2835 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002836 }
2837 else
2838 {
Johnny Chen01a67862011-10-14 00:42:25 +00002839 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002840 }
2841 if (error.Success())
2842 error.SetErrorToGenericError();
2843 return error;
2844}
2845
2846Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002847ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002848{
2849 Error error;
2850 if (wp)
2851 {
2852 user_id_t watchID = wp->GetID();
2853
Greg Clayton5160ce52013-03-27 23:08:40 +00002854 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002855
2856 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00002857
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002858 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002859 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002860
Johnny Chen11309a32011-09-06 22:38:36 +00002861 if (!wp->IsEnabled())
2862 {
2863 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002864 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 +00002865 // See also 'class WatchpointSentry' within StopInfo.cpp.
2866 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2867 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00002868 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002869 return error;
2870 }
2871
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002872 if (wp->IsHardware())
2873 {
Johnny Chen11309a32011-09-06 22:38:36 +00002874 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002875 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00002876 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2877 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002878 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002879 return error;
2880 }
2881 else
2882 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002883 }
2884 // TODO: clear software watchpoints if we implement them
2885 }
2886 else
2887 {
Johnny Chen01a67862011-10-14 00:42:25 +00002888 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002889 }
2890 if (error.Success())
2891 error.SetErrorToGenericError();
2892 return error;
2893}
2894
2895void
2896ProcessGDBRemote::Clear()
2897{
2898 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002899 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002900 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002901}
2902
2903Error
2904ProcessGDBRemote::DoSignal (int signo)
2905{
2906 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002907 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002908 if (log)
2909 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2910
2911 if (!m_gdb_comm.SendAsyncSignal (signo))
2912 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2913 return error;
2914}
2915
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002916Error
Greg Clayton91a9b2472013-12-04 19:19:12 +00002917ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002918{
2919 Error error;
2920 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2921 {
2922 // If we locate debugserver, keep that located version around
2923 static FileSpec g_debugserver_file_spec;
2924
Han Ming Ong84647042012-02-25 01:07:38 +00002925 ProcessLaunchInfo debugserver_launch_info;
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00002926 // Make debugserver run in its own session so signals generated by
2927 // special terminal key sequences (^C) don't affect debugserver.
2928 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
2929
Greg Clayton91a9b2472013-12-04 19:19:12 +00002930 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2931 debugserver_launch_info.SetUserID(process_info.GetUserID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002932
Todd Fiala013434e2014-07-09 01:29:05 +00002933#if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__) || defined (__aarch64__))
Greg Claytonfda4fab2014-01-10 22:24:11 +00002934 // On iOS, still do a local connection using a random port
Greg Clayton16810922014-02-27 19:38:18 +00002935 const char *hostname = "127.0.0.1";
Greg Claytonfda4fab2014-01-10 22:24:11 +00002936 uint16_t port = get_random_port ();
2937#else
2938 // Set hostname being NULL to do the reverse connect where debugserver
2939 // will bind to port zero and it will communicate back to us the port
2940 // that we will connect to
2941 const char *hostname = NULL;
2942 uint16_t port = 0;
2943#endif
2944
2945 error = m_gdb_comm.StartDebugserverProcess (hostname,
2946 port,
Greg Clayton00fe87b2013-12-05 22:58:22 +00002947 debugserver_launch_info,
2948 port);
Greg Clayton91a9b2472013-12-04 19:19:12 +00002949
2950 if (error.Success ())
2951 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002952 else
Greg Clayton91a9b2472013-12-04 19:19:12 +00002953 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002954
2955 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2956 StartAsyncThread ();
Greg Clayton91a9b2472013-12-04 19:19:12 +00002957
2958 if (error.Fail())
2959 {
2960 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
2961
2962 if (log)
2963 log->Printf("failed to start debugserver process: %s", error.AsCString());
2964 return error;
2965 }
2966
Greg Clayton00fe87b2013-12-05 22:58:22 +00002967 if (m_gdb_comm.IsConnected())
2968 {
2969 // Finish the connection process by doing the handshake without connecting (send NULL URL)
2970 ConnectToDebugserver (NULL);
2971 }
2972 else
2973 {
Greg Claytonfda4fab2014-01-10 22:24:11 +00002974 StreamString connect_url;
2975 connect_url.Printf("connect://%s:%u", hostname, port);
2976 error = ConnectToDebugserver (connect_url.GetString().c_str());
Greg Clayton00fe87b2013-12-05 22:58:22 +00002977 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00002978
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002979 }
2980 return error;
2981}
2982
2983bool
2984ProcessGDBRemote::MonitorDebugserverProcess
2985(
2986 void *callback_baton,
2987 lldb::pid_t debugserver_pid,
Greg Claytone4e45922011-11-16 05:37:56 +00002988 bool exited, // True if the process did exit
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002989 int signo, // Zero for no signal
2990 int exit_status // Exit value of process if signal is zero
2991)
2992{
Greg Claytone4e45922011-11-16 05:37:56 +00002993 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2994 // and might not exist anymore, so we need to carefully try to get the
2995 // target for this process first since we have a race condition when
2996 // we are done running between getting the notice that the inferior
2997 // process has died and the debugserver that was debugging this process.
2998 // In our test suite, we are also continually running process after
2999 // process, so we must be very careful to make sure:
3000 // 1 - process object hasn't been deleted already
3001 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003002
3003 // "debugserver_pid" argument passed in is the process ID for
3004 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00003005 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003006
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003007 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton6779606a2011-01-22 23:43:18 +00003008
Greg Claytone4e45922011-11-16 05:37:56 +00003009 // Get a shared pointer to the target that has a matching process pointer.
3010 // This target could be gone, or the target could already have a new process
3011 // object inside of it
3012 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
3013
Greg Clayton6779606a2011-01-22 23:43:18 +00003014 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003015 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 +00003016
Greg Claytone4e45922011-11-16 05:37:56 +00003017 if (target_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003018 {
Greg Claytone4e45922011-11-16 05:37:56 +00003019 // We found a process in a target that matches, but another thread
3020 // might be in the process of launching a new process that will
3021 // soon replace it, so get a shared pointer to the process so we
3022 // can keep it alive.
3023 ProcessSP process_sp (target_sp->GetProcessSP());
3024 // Now we have a shared pointer to the process that can't go away on us
3025 // so we now make sure it was the same as the one passed in, and also make
3026 // sure that our previous "process *" didn't get deleted and have a new
3027 // "process *" created in its place with the same pointer. To verify this
3028 // we make sure the process has our debugserver process ID. If we pass all
3029 // of these tests, then we are sure that this process is the one we were
3030 // looking for.
3031 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003032 {
Greg Claytone4e45922011-11-16 05:37:56 +00003033 // Sleep for a half a second to make sure our inferior process has
3034 // time to set its exit status before we set it incorrectly when
3035 // both the debugserver and the inferior process shut down.
3036 usleep (500000);
3037 // If our process hasn't yet exited, debugserver might have died.
3038 // If the process did exit, the we are reaping it.
3039 const StateType state = process->GetState();
3040
3041 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
3042 state != eStateInvalid &&
3043 state != eStateUnloaded &&
3044 state != eStateExited &&
3045 state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003046 {
Greg Claytone4e45922011-11-16 05:37:56 +00003047 char error_str[1024];
3048 if (signo)
3049 {
3050 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
3051 if (signal_cstr)
3052 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3053 else
3054 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
3055 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003056 else
Greg Claytone4e45922011-11-16 05:37:56 +00003057 {
3058 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
3059 }
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003060
Greg Claytone4e45922011-11-16 05:37:56 +00003061 process->SetExitStatus (-1, error_str);
3062 }
3063 // Debugserver has exited we need to let our ProcessGDBRemote
3064 // know that it no longer has a debugserver instance
3065 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003066 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003067 }
3068 return true;
3069}
3070
3071void
3072ProcessGDBRemote::KillDebugserverProcess ()
3073{
Greg Claytonfbb76342013-11-20 21:07:01 +00003074 m_gdb_comm.Disconnect();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003075 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3076 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003077 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003078 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3079 }
3080}
3081
3082void
3083ProcessGDBRemote::Initialize()
3084{
Davide Italianoc8d69822015-04-03 04:24:32 +00003085 static std::once_flag g_once_flag;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003086
Davide Italianoc8d69822015-04-03 04:24:32 +00003087 std::call_once(g_once_flag, []()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003088 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003089 PluginManager::RegisterPlugin (GetPluginNameStatic(),
3090 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00003091 CreateInstance,
3092 DebuggerInitialize);
Davide Italianoc8d69822015-04-03 04:24:32 +00003093 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003094}
3095
Greg Clayton7f982402013-07-15 22:54:20 +00003096void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003097ProcessGDBRemote::DebuggerInitialize (Debugger &debugger)
Greg Clayton7f982402013-07-15 22:54:20 +00003098{
3099 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
3100 {
3101 const bool is_global_setting = true;
3102 PluginManager::CreateSettingForProcessPlugin (debugger,
3103 GetGlobalPluginProperties()->GetValueProperties(),
3104 ConstString ("Properties for the gdb-remote process plug-in."),
3105 is_global_setting);
3106 }
3107}
3108
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003109bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003110ProcessGDBRemote::StartAsyncThread ()
3111{
Greg Clayton5160ce52013-03-27 23:08:40 +00003112 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003113
3114 if (log)
3115 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003116
3117 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003118 if (!m_async_thread.IsJoinable())
Jim Ingham455fa5c2012-11-01 01:15:33 +00003119 {
3120 // Create a thread that watches our internal state and controls which
3121 // events make it to clients (into the DCProcess event queue).
Zachary Turner39de3112014-09-09 20:54:56 +00003122
3123 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003124 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003125 else if (log)
3126 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was already running.", __FUNCTION__);
Zachary Turner39de3112014-09-09 20:54:56 +00003127
Zachary Turneracee96a2014-09-23 18:32:09 +00003128 return m_async_thread.IsJoinable();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003129}
3130
3131void
3132ProcessGDBRemote::StopAsyncThread ()
3133{
Greg Clayton5160ce52013-03-27 23:08:40 +00003134 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003135
3136 if (log)
3137 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
3138
Jim Ingham455fa5c2012-11-01 01:15:33 +00003139 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003140 if (m_async_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003141 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00003142 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
3143
3144 // This will shut down the async thread.
3145 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3146
3147 // Stop the stdio thread
Zachary Turner39de3112014-09-09 20:54:56 +00003148 m_async_thread.Join(nullptr);
Pavel Labatha55a9532015-03-11 09:53:42 +00003149 m_async_thread.Reset();
Jim Ingham455fa5c2012-11-01 01:15:33 +00003150 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003151 else if (log)
3152 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003153}
3154
3155
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003156thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003157ProcessGDBRemote::AsyncThread (void *arg)
3158{
3159 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
3160
Greg Clayton5160ce52013-03-27 23:08:40 +00003161 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003162 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003163 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003164
3165 Listener listener ("ProcessGDBRemote::AsyncThread");
3166 EventSP event_sp;
3167 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
3168 eBroadcastBitAsyncThreadShouldExit;
3169
3170 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
3171 {
Greg Clayton71337622011-02-24 22:24:29 +00003172 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
3173
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003174 bool done = false;
3175 while (!done)
3176 {
3177 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003178 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003179 if (listener.WaitForEvent (NULL, event_sp))
3180 {
3181 const uint32_t event_type = event_sp->GetType();
Greg Clayton71337622011-02-24 22:24:29 +00003182 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003183 {
Greg Clayton71337622011-02-24 22:24:29 +00003184 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003185 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 +00003186
Greg Clayton71337622011-02-24 22:24:29 +00003187 switch (event_type)
3188 {
3189 case eBroadcastBitAsyncContinue:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003190 {
Greg Clayton71337622011-02-24 22:24:29 +00003191 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003192
Greg Clayton71337622011-02-24 22:24:29 +00003193 if (continue_packet)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003194 {
Greg Clayton71337622011-02-24 22:24:29 +00003195 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
3196 const size_t continue_cstr_len = continue_packet->GetByteSize ();
3197 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003198 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003199
Greg Clayton71337622011-02-24 22:24:29 +00003200 if (::strstr (continue_cstr, "vAttach") == NULL)
3201 process->SetPrivateState(eStateRunning);
3202 StringExtractorGDBRemote response;
3203 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003204
Greg Clayton0772ded2012-05-16 02:48:06 +00003205 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
3206 // The thread ID list might be contained within the "response", or the stop reply packet that
3207 // caused the stop. So clear it now before we give the stop reply packet to the process
3208 // using the process->SetLastStopPacket()...
3209 process->ClearThreadIDList ();
3210
Greg Clayton71337622011-02-24 22:24:29 +00003211 switch (stop_state)
3212 {
3213 case eStateStopped:
3214 case eStateCrashed:
3215 case eStateSuspended:
Greg Clayton09c3e3d2011-12-06 04:51:14 +00003216 process->SetLastStopPacket (response);
Greg Clayton71337622011-02-24 22:24:29 +00003217 process->SetPrivateState (stop_state);
3218 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003219
Greg Clayton71337622011-02-24 22:24:29 +00003220 case eStateExited:
Jason Molendaa3329782014-03-29 18:54:20 +00003221 {
Greg Clayton09c3e3d2011-12-06 04:51:14 +00003222 process->SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00003223 process->ClearThreadIDList();
Greg Clayton71337622011-02-24 22:24:29 +00003224 response.SetFilePos(1);
Jason Molendaa3329782014-03-29 18:54:20 +00003225
3226 int exit_status = response.GetHexU8();
3227 const char *desc_cstr = NULL;
3228 StringExtractor extractor;
3229 std::string desc_string;
3230 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';')
3231 {
3232 std::string desc_token;
3233 while (response.GetNameColonValue (desc_token, desc_string))
3234 {
3235 if (desc_token == "description")
3236 {
3237 extractor.GetStringRef().swap(desc_string);
3238 extractor.SetFilePos(0);
3239 extractor.GetHexByteString (desc_string);
3240 desc_cstr = desc_string.c_str();
3241 }
3242 }
3243 }
3244 process->SetExitStatus(exit_status, desc_cstr);
Greg Clayton71337622011-02-24 22:24:29 +00003245 done = true;
3246 break;
Jason Molendaa3329782014-03-29 18:54:20 +00003247 }
Greg Clayton71337622011-02-24 22:24:29 +00003248 case eStateInvalid:
3249 process->SetExitStatus(-1, "lost connection");
3250 break;
3251
3252 default:
3253 process->SetPrivateState (stop_state);
3254 break;
3255 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003256 }
3257 }
Greg Clayton71337622011-02-24 22:24:29 +00003258 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003259
Greg Clayton71337622011-02-24 22:24:29 +00003260 case eBroadcastBitAsyncThreadShouldExit:
3261 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003262 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Clayton71337622011-02-24 22:24:29 +00003263 done = true;
3264 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003265
Greg Clayton71337622011-02-24 22:24:29 +00003266 default:
3267 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003268 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 +00003269 done = true;
3270 break;
3271 }
3272 }
3273 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
3274 {
3275 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
3276 {
3277 process->SetExitStatus (-1, "lost connection");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003278 done = true;
Greg Clayton71337622011-02-24 22:24:29 +00003279 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003280 }
3281 }
3282 else
3283 {
3284 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003285 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 +00003286 done = true;
3287 }
3288 }
3289 }
3290
3291 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003292 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003293
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003294 return NULL;
3295}
3296
Greg Claytone996fd32011-03-08 22:40:15 +00003297//uint32_t
3298//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3299//{
3300// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
3301// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
3302// if (m_local_debugserver)
3303// {
3304// return Host::ListProcessesMatchingName (name, matches, pids);
3305// }
3306// else
3307// {
3308// // FIXME: Implement talking to the remote debugserver.
3309// return 0;
3310// }
3311//
3312//}
3313//
Jim Ingham1c823b42011-01-22 01:33:44 +00003314bool
3315ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003316 StoppointCallbackContext *context,
Jim Ingham1c823b42011-01-22 01:33:44 +00003317 lldb::user_id_t break_id,
3318 lldb::user_id_t break_loc_id)
3319{
3320 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3321 // run so I can stop it if that's what I want to do.
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003322 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00003323 if (log)
3324 log->Printf("Hit New Thread Notification breakpoint.");
3325 return false;
3326}
3327
3328
3329bool
3330ProcessGDBRemote::StartNoticingNewThreads()
3331{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003332 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00003333 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003334 {
Greg Clayton4116e932012-05-15 02:33:01 +00003335 if (log && log->GetVerbose())
3336 log->Printf("Enabled noticing new thread breakpoint.");
3337 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003338 }
Greg Clayton4116e932012-05-15 02:33:01 +00003339 else
Jim Ingham1c823b42011-01-22 01:33:44 +00003340 {
Greg Clayton4116e932012-05-15 02:33:01 +00003341 PlatformSP platform_sp (m_target.GetPlatform());
3342 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003343 {
Greg Clayton4116e932012-05-15 02:33:01 +00003344 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3345 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003346 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00003347 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00003348 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3349 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003350 }
3351 else
3352 {
3353 if (log)
3354 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00003355 }
3356 }
3357 }
Greg Clayton4116e932012-05-15 02:33:01 +00003358 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00003359}
3360
3361bool
3362ProcessGDBRemote::StopNoticingNewThreads()
3363{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003364 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00003365 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00003366 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00003367
3368 if (m_thread_create_bp_sp)
3369 m_thread_create_bp_sp->SetEnabled(false);
3370
Jim Ingham1c823b42011-01-22 01:33:44 +00003371 return true;
3372}
3373
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003374DynamicLoader *
Jason Molenda5e8534e2012-10-03 01:29:34 +00003375ProcessGDBRemote::GetDynamicLoader ()
3376{
3377 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00003378 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00003379 return m_dyld_ap.get();
3380}
Jim Ingham1c823b42011-01-22 01:33:44 +00003381
Jason Molendaa3329782014-03-29 18:54:20 +00003382Error
3383ProcessGDBRemote::SendEventData(const char *data)
3384{
3385 int return_value;
3386 bool was_supported;
3387
3388 Error error;
3389
3390 return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported);
3391 if (return_value != 0)
3392 {
3393 if (!was_supported)
3394 error.SetErrorString("Sending events is not supported for this process.");
3395 else
3396 error.SetErrorStringWithFormat("Error sending event data: %d.", return_value);
3397 }
3398 return error;
3399}
3400
Steve Pucci03904ac2014-03-04 23:18:46 +00003401const DataBufferSP
3402ProcessGDBRemote::GetAuxvData()
3403{
3404 DataBufferSP buf;
3405 if (m_gdb_comm.GetQXferAuxvReadSupported())
3406 {
3407 std::string response_string;
3408 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success)
3409 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length()));
3410 }
3411 return buf;
3412}
3413
Jason Molenda705b1802014-06-13 02:37:02 +00003414StructuredData::ObjectSP
3415ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid)
3416{
3417 StructuredData::ObjectSP object_sp;
3418
3419 if (m_gdb_comm.GetThreadExtendedInfoSupported())
3420 {
3421 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3422 SystemRuntime *runtime = GetSystemRuntime();
3423 if (runtime)
3424 {
3425 runtime->AddThreadExtendedInfoPacketHints (args_dict);
3426 }
3427 args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid);
3428
3429 StreamString packet;
3430 packet << "jThreadExtendedInfo:";
3431 args_dict->Dump (packet);
3432
3433 // FIXME the final character of a JSON dictionary, '}', is the escape
3434 // character in gdb-remote binary mode. lldb currently doesn't escape
3435 // these characters in its packet output -- so we add the quoted version
3436 // of the } character here manually in case we talk to a debugserver which
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003437 // un-escapes the characters at packet read time.
Jason Molenda705b1802014-06-13 02:37:02 +00003438 packet << (char) (0x7d ^ 0x20);
3439
3440 StringExtractorGDBRemote response;
3441 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
3442 {
3443 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
3444 if (response_type == StringExtractorGDBRemote::eResponse)
3445 {
3446 if (!response.Empty())
3447 {
3448 // The packet has already had the 0x7d xor quoting stripped out at the
3449 // GDBRemoteCommunication packet receive level.
3450 object_sp = StructuredData::ParseJSON (response.GetStringRef());
3451 }
3452 }
3453 }
3454 }
3455 return object_sp;
3456}
3457
Jason Molenda6076bf42014-05-06 04:34:52 +00003458// Establish the largest memory read/write payloads we should use.
3459// If the remote stub has a max packet size, stay under that size.
3460//
3461// If the remote stub's max packet size is crazy large, use a
3462// reasonable largeish default.
3463//
3464// If the remote stub doesn't advertise a max packet size, use a
3465// conservative default.
3466
3467void
3468ProcessGDBRemote::GetMaxMemorySize()
3469{
3470 const uint64_t reasonable_largeish_default = 128 * 1024;
3471 const uint64_t conservative_default = 512;
3472
3473 if (m_max_memory_size == 0)
3474 {
3475 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
3476 if (stub_max_size != UINT64_MAX && stub_max_size != 0)
3477 {
3478 // Save the stub's claimed maximum packet size
3479 m_remote_stub_max_memory_size = stub_max_size;
3480
3481 // Even if the stub says it can support ginormous packets,
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003482 // don't exceed our reasonable largeish default packet size.
Jason Molenda6076bf42014-05-06 04:34:52 +00003483 if (stub_max_size > reasonable_largeish_default)
3484 {
3485 stub_max_size = reasonable_largeish_default;
3486 }
3487
3488 m_max_memory_size = stub_max_size;
3489 }
3490 else
3491 {
3492 m_max_memory_size = conservative_default;
3493 }
3494 }
3495}
3496
3497void
3498ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max)
3499{
3500 if (user_specified_max != 0)
3501 {
3502 GetMaxMemorySize ();
3503
3504 if (m_remote_stub_max_memory_size != 0)
3505 {
3506 if (m_remote_stub_max_memory_size < user_specified_max)
3507 {
3508 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a packet size too big, go as big
3509 // as the remote stub says we can go.
3510 }
3511 else
3512 {
3513 m_max_memory_size = user_specified_max; // user's packet size is good
3514 }
3515 }
3516 else
3517 {
3518 m_max_memory_size = user_specified_max; // user's packet size is probably fine
3519 }
3520 }
3521}
3522
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003523bool
3524ProcessGDBRemote::GetModuleSpec(const FileSpec& module_file_spec,
3525 const ArchSpec& arch,
3526 ModuleSpec &module_spec)
3527{
3528 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PLATFORM);
3529
3530 if (!m_gdb_comm.GetModuleInfo (module_file_spec, arch, module_spec))
3531 {
3532 if (log)
3533 log->Printf ("ProcessGDBRemote::%s - failed to get module info for %s:%s",
3534 __FUNCTION__, module_file_spec.GetPath ().c_str (),
3535 arch.GetTriple ().getTriple ().c_str ());
3536 return false;
3537 }
3538
3539 if (log)
3540 {
3541 StreamString stream;
3542 module_spec.Dump (stream);
3543 log->Printf ("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
3544 __FUNCTION__, module_file_spec.GetPath ().c_str (),
3545 arch.GetTriple ().getTriple ().c_str (), stream.GetString ().c_str ());
3546 }
3547
3548 return true;
3549}
3550
Colin Rileyc3c95b22015-04-16 15:51:33 +00003551#if defined( LIBXML2_DEFINED )
3552namespace {
3553
3554typedef std::vector<std::string> stringVec;
3555typedef std::vector<xmlNodePtr> xmlNodePtrVec;
3556
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003557struct GdbServerRegisterInfo
3558{
Colin Rileyc3c95b22015-04-16 15:51:33 +00003559
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003560 struct
3561 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003562 bool m_has_name : 1;
3563 bool m_has_bitSize : 1;
3564 bool m_has_type : 1;
3565 bool m_has_group : 1;
3566 bool m_has_regNum : 1;
3567 }
3568 m_flags;
3569
3570 std::string m_name;
3571 std::string m_group;
3572 uint32_t m_bitSize;
3573 uint32_t m_regNum;
3574
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003575 enum RegType
3576 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003577 eUnknown ,
3578 eCodePtr ,
3579 eDataPtr ,
3580 eInt32 ,
3581 eI387Ext ,
3582 }
3583 m_type;
3584
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003585 void clear()
3586 {
3587 memset(&m_flags, 0, sizeof(m_flags));
Colin Rileyc3c95b22015-04-16 15:51:33 +00003588 }
3589};
3590
3591typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
3592
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003593struct GdbServerTargetInfo
3594{
Colin Rileyc3c95b22015-04-16 15:51:33 +00003595 std::string m_arch;
3596 std::string m_osabi;
3597};
3598
3599// conversion table between gdb register type and enum
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003600struct
3601{
Colin Rileyc3c95b22015-04-16 15:51:33 +00003602 const char * m_name;
3603 GdbServerRegisterInfo::RegType m_type;
3604}
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003605RegTypeTable[] =
3606{
Colin Rileyc3c95b22015-04-16 15:51:33 +00003607 { "int32" , GdbServerRegisterInfo::eInt32 },
3608 { "int" , GdbServerRegisterInfo::eInt32 },
3609 { "data_ptr", GdbServerRegisterInfo::eDataPtr },
3610 { "code_ptr", GdbServerRegisterInfo::eCodePtr },
3611 { "i387_ext", GdbServerRegisterInfo::eI387Ext }, // 80bit fpu
Greg Claytone68c0082015-04-16 23:13:26 +00003612 { nullptr , GdbServerRegisterInfo::eUnknown } // sentinel
Colin Rileyc3c95b22015-04-16 15:51:33 +00003613};
3614
3615// find the first sibling with a matching name
3616xmlNodePtr
3617xmlExFindSibling (xmlNodePtr node,
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003618 const std::string & name)
3619{
Colin Rileyc3c95b22015-04-16 15:51:33 +00003620
3621 if ( !node ) return nullptr;
3622 // iterate through all siblings
3623 for ( xmlNodePtr temp = node; temp; temp=temp->next ) {
3624 // we are looking for elements
3625 if ( temp->type != XML_ELEMENT_NODE )
3626 continue;
3627 // check element name matches
3628 if ( !temp->name ) continue;
3629 if ( std::strcmp((const char*)temp->name, name.c_str() ) == 0 )
3630 return temp;
3631 }
3632 // no sibling found
3633 return nullptr;
3634}
3635
3636// find an element from a given element path
3637xmlNodePtr
3638xmlExFindElement (xmlNodePtr node,
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003639 const stringVec & path)
3640{
Colin Rileyc3c95b22015-04-16 15:51:33 +00003641
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003642 if (!node)
3643 return nullptr;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003644 xmlNodePtr temp = node;
3645 // iterate all elements in path
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003646 for (uint32_t i = 0; i < path.size(); i++)
3647 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003648
3649 // search for a sibling with this name
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003650 temp = xmlExFindSibling(temp, path[i]);
3651 if (!temp)
Colin Rileyc3c95b22015-04-16 15:51:33 +00003652 return nullptr;
3653 // enter this node if we still need to search
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003654 if ((i + 1) < path.size())
Colin Rileyc3c95b22015-04-16 15:51:33 +00003655 // enter the node we have found
3656 temp = temp->children;
3657 }
3658 // note: node may still be nullptr at this step
3659 return temp;
3660}
3661
3662// locate a specific attribute in an element
3663xmlAttr *
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003664xmlExFindAttribute (xmlNodePtr node,
3665 const std::string & name)
3666{
Colin Rileyc3c95b22015-04-16 15:51:33 +00003667
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003668 if (!node)
Colin Rileyc3c95b22015-04-16 15:51:33 +00003669 return nullptr;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003670 if (node->type != XML_ELEMENT_NODE)
Colin Rileyc3c95b22015-04-16 15:51:33 +00003671 return nullptr;
3672 // iterate over all attributes
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003673 for (xmlAttrPtr attr = node->properties; attr != nullptr; attr=attr->next)
3674 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003675 // check if name matches
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003676 if (!attr->name)
3677 continue;
3678 if (std::strcmp((const char*) attr->name, name.c_str()) == 0)
Colin Rileyc3c95b22015-04-16 15:51:33 +00003679 return attr;
3680 }
3681 return nullptr;
3682}
3683
3684// find all child elements with given name and add them to a vector
3685//
3686// input: node = xml element to search
3687// name = name used when matching child elements
3688// output: out = list of matches
3689// return: number of children added to 'out'
3690int
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003691xmlExFindChildren (xmlNodePtr node,
3692 const std::string & name,
3693 xmlNodePtrVec & out)
3694{
Colin Rileyc3c95b22015-04-16 15:51:33 +00003695
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003696 if (!node)
3697 return 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003698 int count = 0;
3699 // iterate over all children
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003700 for (xmlNodePtr child = node->children; child; child = child->next)
3701 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003702 // if name matches
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003703 if (!child->name)
3704 continue;
3705 if (std::strcmp((const char*) child->name, name.c_str()) == 0)
3706 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003707 // add to output list
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003708 out.push_back(child);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003709 ++count;
3710 }
3711 }
3712 return count;
3713}
3714
3715// get the text content from an attribute
3716std::string
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003717xmlExGetTextContent (xmlAttrPtr attr)
3718{
3719 if (!attr)
3720 return std::string();
3721 if (attr->type != XML_ATTRIBUTE_NODE)
3722 return std::string();
Colin Rileyc3c95b22015-04-16 15:51:33 +00003723 // check child is a text node
3724 xmlNodePtr child = attr->children;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003725 if (child->type != XML_TEXT_NODE)
3726 return std::string();
Colin Rileyc3c95b22015-04-16 15:51:33 +00003727 // access the content
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003728 assert(child->content != nullptr);
3729 return std::string((const char*) child->content);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003730}
3731
3732// get the text content from an node
3733std::string
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003734xmlExGetTextContent (xmlNodePtr node)
3735{
3736 if (!node)
3737 return std::string();
3738 if (node->type != XML_ELEMENT_NODE)
3739 return std::string();
Colin Rileyc3c95b22015-04-16 15:51:33 +00003740 // check child is a text node
3741 xmlNodePtr child = node->children;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003742 if (child->type != XML_TEXT_NODE)
3743 return std::string();
Colin Rileyc3c95b22015-04-16 15:51:33 +00003744 // access the content
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003745 assert(child->content != nullptr);
3746 return std::string((const char*) child->content);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003747}
3748
3749// compile a list of xml includes from the target file
3750// input: doc = target.xml
3751// output: includes = list of .xml names specified in target.xml
3752// return: number of .xml files specified in target.xml and added to includes
3753int
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003754parseTargetIncludes (xmlDocPtr doc, stringVec & includes)
3755{
3756 if (!doc)
3757 return 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003758 int count = 0;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003759 xmlNodePtr elm = xmlExFindElement(doc->children, {"target"});
3760 if (!elm)
3761 return 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003762 xmlNodePtrVec nodes;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003763 xmlExFindChildren(elm, "xi:include", nodes);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003764 // iterate over all includes
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003765 for (uint32_t i = 0; i < nodes.size(); i++)
3766 {
3767 xmlAttrPtr attr = xmlExFindAttribute(nodes[i], "href");
3768 if (attr != nullptr)
3769 {
3770 std::string text = xmlExGetTextContent(attr);
3771 includes.push_back(text);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003772 ++count;
3773 }
3774 }
3775 return count;
3776}
3777
3778// extract target arch information from the target.xml file
3779// input: doc = target.xml document
3780// output: out = remote target information
3781// return: 'true' on success
3782// 'false' on failure
3783bool
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003784parseTargetInfo (xmlDocPtr doc, GdbServerTargetInfo & out)
3785{
3786 if (!doc)
3787 return false;
3788 xmlNodePtr e1 = xmlExFindElement (doc->children, {"target", "architecture"});
3789 if (!e1)
3790 return false;
3791 out.m_arch = xmlExGetTextContent (e1);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003792
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003793 xmlNodePtr e2 = xmlExFindElement (doc->children, {"target", "osabi"});
3794 if (!e2)
3795 return false;
3796 out.m_osabi = xmlExGetTextContent (e2);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003797
3798 return true;
3799}
3800
3801// extract register information from one of the xml files specified in target.xml
3802// input: doc = xml document
3803// output: regList = list of extracted register info
3804// return: 'true' on success
3805// 'false' on failure
3806bool
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003807parseRegisters (xmlDocPtr doc, GDBServerRegisterVec & regList)
3808{
Colin Rileyc3c95b22015-04-16 15:51:33 +00003809
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003810 if (!doc)
3811 return false;
3812 xmlNodePtr elm = xmlExFindElement (doc->children, {"feature"});
3813 if (!elm)
3814 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003815
3816 xmlAttrPtr attr = nullptr;
3817
3818 xmlNodePtrVec regs;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003819 xmlExFindChildren (elm, "reg", regs);
3820 for (unsigned long i = 0; i < regs.size(); i++)
3821 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003822
3823 GdbServerRegisterInfo reg;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003824 reg.clear();
Colin Rileyc3c95b22015-04-16 15:51:33 +00003825
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003826 if ((attr = xmlExFindAttribute(regs[i], "name")))
3827 {
3828 reg.m_name = xmlExGetTextContent(attr).c_str();
Colin Rileyc3c95b22015-04-16 15:51:33 +00003829 reg.m_flags.m_has_name = true;
3830 }
3831
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003832 if ((attr = xmlExFindAttribute( regs[i], "bitsize")))
3833 {
3834 const std::string v = xmlExGetTextContent(attr);
3835 reg.m_bitSize = atoi(v.c_str());
Colin Rileyc3c95b22015-04-16 15:51:33 +00003836 reg.m_flags.m_has_bitSize = true;
3837 }
3838
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003839 if ((attr = xmlExFindAttribute(regs[i], "type")))
3840 {
3841 const std::string v = xmlExGetTextContent(attr);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003842 reg.m_type = GdbServerRegisterInfo::eUnknown;
3843
3844 // search the type table for a match
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003845 for (int j = 0; RegTypeTable[j].m_name !=nullptr; ++j)
3846 {
3847 if (RegTypeTable[j].m_name == v)
3848 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003849 reg.m_type = RegTypeTable[j].m_type;
3850 break;
3851 }
3852 }
3853
3854 reg.m_flags.m_has_type = (reg.m_type != GdbServerRegisterInfo::eUnknown);
3855 }
3856
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003857 if ((attr = xmlExFindAttribute( regs[i], "group")))
3858 {
3859 reg.m_group = xmlExGetTextContent(attr);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003860 reg.m_flags.m_has_group = true;
3861 }
3862
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003863 if ((attr = xmlExFindAttribute(regs[i], "regnum")))
3864 {
3865 const std::string v = xmlExGetTextContent(attr);
3866 reg.m_regNum = atoi(v.c_str());
Colin Rileyc3c95b22015-04-16 15:51:33 +00003867 reg.m_flags.m_has_regNum = true;
3868 }
3869
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003870 regList.push_back(reg);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003871 }
3872
3873 //TODO: there is also a "vector" element to parse
3874 //TODO: there is also eflags to parse
3875
3876 return true;
3877}
3878
3879// build lldb gdb-remote's dynamic register info from a vector of gdb provided registers
3880// input: regList = register information provided by gdbserver
3881// output: regInfo = dynamic register information required by gdb-remote
3882void
3883BuildRegisters (const GDBServerRegisterVec & regList,
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003884 GDBRemoteDynamicRegisterInfo & regInfo)
3885{
Colin Rileyc3c95b22015-04-16 15:51:33 +00003886
3887 using namespace lldb_private;
3888
3889 const uint32_t defSize = 32;
3890 uint32_t regNum = 0;
3891 uint32_t byteOffset = 0;
3892
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003893 for (uint32_t i = 0; i < regList.size(); ++i)
3894 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003895
3896 const GdbServerRegisterInfo & gdbReg = regList[i];
3897
3898 std::string name = gdbReg.m_flags.m_has_name ? gdbReg.m_name : "unknown";
3899 std::string group = gdbReg.m_flags.m_has_group ? gdbReg.m_group : "general";
3900 uint32_t byteSize = gdbReg.m_flags.m_has_bitSize ? (gdbReg.m_bitSize/8) : defSize;
3901
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003902 if (gdbReg.m_flags.m_has_regNum)
Colin Rileyc3c95b22015-04-16 15:51:33 +00003903 regNum = gdbReg.m_regNum;
3904
3905 uint32_t regNumGcc = LLDB_INVALID_REGNUM;
3906 uint32_t regNumDwarf = LLDB_INVALID_REGNUM;
3907 uint32_t regNumGeneric = LLDB_INVALID_REGNUM;
3908 uint32_t regNumGdb = regNum;
3909 uint32_t regNumNative = regNum;
3910
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003911 if (name == "eip" || name == "pc")
3912 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003913 regNumGeneric = LLDB_REGNUM_GENERIC_PC;
3914 }
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003915 if (name == "esp" || name == "sp")
3916 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003917 regNumGeneric = LLDB_REGNUM_GENERIC_SP;
3918 }
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003919 if (name == "ebp")
3920 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003921 regNumGeneric = LLDB_REGNUM_GENERIC_FP;
3922 }
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003923 if (name == "lr")
3924 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003925 regNumGeneric = LLDB_REGNUM_GENERIC_RA;
3926 }
3927
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003928 RegisterInfo info =
3929 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003930 name.c_str(),
3931 nullptr ,
3932 byteSize ,
3933 byteOffset ,
3934 lldb::Encoding::eEncodingUint,
3935 lldb::Format::eFormatDefault,
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003936 { regNumGcc ,
3937 regNumDwarf ,
Colin Rileyc3c95b22015-04-16 15:51:33 +00003938 regNumGeneric,
3939 regNumGdb ,
3940 regNumNative },
3941 nullptr,
3942 nullptr
3943 };
3944
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003945 ConstString regName = ConstString(gdbReg.m_name);
3946 ConstString regAltName = ConstString();
3947 ConstString regGroup = ConstString(group);
3948 regInfo.AddRegister(info, regName, regAltName, regGroup);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003949
3950 // advance register info
3951 byteOffset += byteSize;
3952 regNum += 1;
3953 }
3954
3955 regInfo.Finalize ();
3956}
3957
3958} // namespace {}
3959
3960void XMLCDECL
3961libxml2NullErrorFunc (void *ctx, const char *msg, ...)
3962{
3963 // do nothing currently
3964}
3965
3966// query the target of gdb-remote for extended target information
3967// return: 'true' on success
3968// 'false' on failure
3969bool
Aidan Doddsc0c83852015-05-08 09:36:31 +00003970ProcessGDBRemote::GetGDBServerRegisterInfo ()
Colin Rileyc3c95b22015-04-16 15:51:33 +00003971{
3972
3973 // redirect libxml2's error handler since the default prints to stdout
3974 xmlGenericErrorFunc func = libxml2NullErrorFunc;
3975 initGenericErrorDefaultFunc( &func );
3976
3977 GDBRemoteCommunicationClient & comm = m_gdb_comm;
3978 GDBRemoteDynamicRegisterInfo & regInfo = m_register_info;
3979
3980 // check that we have extended feature read support
3981 if ( !comm.GetQXferFeaturesReadSupported( ) )
3982 return false;
3983
3984 // request the target xml file
3985 std::string raw;
3986 lldb_private::Error lldberr;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003987 if (!comm.ReadExtFeature(ConstString("features"),
3988 ConstString("target.xml"),
3989 raw,
3990 lldberr))
3991 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003992 return false;
3993 }
3994
3995 // parse the xml file in memory
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003996 xmlDocPtr doc = xmlReadMemory(raw.c_str(), raw.size(), "noname.xml", nullptr, 0);
3997 if (doc == nullptr)
Colin Rileyc3c95b22015-04-16 15:51:33 +00003998 return false;
3999
4000 // extract target info from target.xml
4001 GdbServerTargetInfo gdbInfo;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004002 if (parseTargetInfo(doc, gdbInfo))
4003 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00004004 // NOTE: We could deduce triple from gdbInfo if lldb doesn't already have one set
4005 }
4006
4007 // collect registers from all of the includes
4008 GDBServerRegisterVec regList;
4009 stringVec includes;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004010 if (parseTargetIncludes(doc, includes) > 0)
4011 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00004012
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004013 for (uint32_t i = 0; i < includes.size(); ++i)
4014 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00004015
4016 // request register file
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004017 if (!comm.ReadExtFeature(ConstString("features"),
4018 ConstString(includes[i]),
4019 raw,
4020 lldberr))
Colin Rileyc3c95b22015-04-16 15:51:33 +00004021 continue;
4022
4023 // parse register file
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004024 xmlDocPtr regXml = xmlReadMemory(raw.c_str(),
4025 raw.size( ),
4026 includes[i].c_str(),
4027 nullptr,
4028 0);
4029 if (!regXml)
Colin Rileyc3c95b22015-04-16 15:51:33 +00004030 continue;
4031
4032 // pass registers to lldb
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004033 parseRegisters(regXml, regList);
Colin Rileyc3c95b22015-04-16 15:51:33 +00004034 }
4035 }
4036
4037 // pass all of these registers to lldb
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004038 BuildRegisters(regList, regInfo);
Colin Rileyc3c95b22015-04-16 15:51:33 +00004039
4040 return true;
4041}
4042
Aidan Doddsc0c83852015-05-08 09:36:31 +00004043Error
4044ProcessGDBRemote::GetLoadedModuleList (GDBLoadedModuleInfoList & list)
4045{
4046 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS);
4047 if (log)
4048 log->Printf ("ProcessGDBRemote::%s", __FUNCTION__);
4049
4050 // redirect libxml2's error handler since the default prints to stdout
4051 xmlGenericErrorFunc func = libxml2NullErrorFunc;
4052 initGenericErrorDefaultFunc (&func);
4053
4054 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004055
4056 // check that we have extended feature read support
4057 if (!comm.GetQXferLibrariesSVR4ReadSupported ())
4058 return Error (0, ErrorType::eErrorTypeGeneric);
4059
4060 list.clear ();
4061
4062 // request the loaded library list
4063 std::string raw;
4064 lldb_private::Error lldberr;
4065 if (!comm.ReadExtFeature (ConstString ("libraries-svr4"), ConstString (""), raw, lldberr))
4066 return Error (0, ErrorType::eErrorTypeGeneric);
4067
4068 // parse the xml file in memory
4069 if (log)
4070 log->Printf ("parsing: %s", raw.c_str());
4071 xmlDocPtr doc = xmlReadMemory (raw.c_str(), raw.size(), "noname.xml", nullptr, 0);
4072 if (doc == nullptr)
4073 return Error (0, ErrorType::eErrorTypeGeneric);
4074
4075 xmlNodePtr elm = xmlExFindElement (doc->children, {"library-list-svr4"});
4076 if (!elm)
4077 return Error();
4078
4079 // main link map structure
4080 xmlAttr * attr = xmlExFindAttribute (elm, "main-lm");
4081 if (attr)
4082 {
4083 std::string val = xmlExGetTextContent (attr);
4084 if (val.length() > 2)
4085 {
4086 uint32_t process_lm = std::stoul (val.c_str()+2, 0, 16);
4087 list.m_link_map = process_lm;
4088 }
4089 }
4090
4091 // parse individual library entries
4092 for (xmlNode * child = elm->children; child; child=child->next)
4093 {
4094 if (!child->name)
4095 continue;
4096
4097 if (strcmp ((char*)child->name, "library") != 0)
4098 continue;
4099
4100 GDBLoadedModuleInfoList::LoadedModuleInfo module;
4101
4102 for (xmlAttrPtr prop = child->properties; prop; prop=prop->next)
4103 {
4104 if (strcmp ((char*)prop->name, "name") == 0)
4105 module.set_name (xmlExGetTextContent (prop));
4106
4107 // the address of the link_map struct.
4108 if (strcmp ((char*)prop->name, "lm") == 0)
4109 {
4110 std::string val = xmlExGetTextContent (prop);
4111 if (val.length() > 2)
4112 {
4113 uint32_t module_lm = std::stoul (val.c_str()+2, 0, 16);
4114 module.set_link_map (module_lm);
4115 }
4116 }
4117
4118 // the displacement as read from the field 'l_addr' of the link_map struct.
4119 if (strcmp ((char*)prop->name, "l_addr") == 0)
4120 {
4121 std::string val = xmlExGetTextContent (prop);
4122 if (val.length() > 2)
4123 {
4124 uint32_t module_base = std::stoul (val.c_str()+2, 0, 16);
4125 module.set_base (module_base);
4126 }
4127 }
4128
4129 // the memory address of the libraries PT_DYAMIC section.
4130 if (strcmp ((char*)prop->name, "l_ld") == 0)
4131 {
4132 std::string val = xmlExGetTextContent (prop);
4133 if (val.length() > 2)
4134 {
4135 uint32_t module_dyn = std::stoul (val.c_str()+2, 0, 16);
4136 module.set_dynamic (module_dyn);
4137 }
4138 }
4139 }
4140
4141 if (log)
4142 {
4143 std::string name ("");
4144 lldb::addr_t lm=0, base=0, ld=0;
4145
4146 module.get_name (name);
4147 module.get_link_map (lm);
4148 module.get_base (base);
4149 module.get_dynamic (ld);
4150
4151 log->Printf ("found (link_map:0x08%" PRIx64 ", base:0x08%" PRIx64 ", ld:0x08%" PRIx64 ", name:'%s')", lm, base, ld, name.c_str());
4152 }
4153
4154 list.add (module);
4155 }
4156
4157 if (log)
4158 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4159
4160 return Error();
4161}
4162
Colin Rileyc3c95b22015-04-16 15:51:33 +00004163#else // if defined( LIBXML2_DEFINED )
4164
Aidan Doddsc0c83852015-05-08 09:36:31 +00004165Error
4166ProcessGDBRemote::GetLoadedModuleList (GDBLoadedModuleInfoList &)
4167{
4168 // stub (libxml2 not present)
4169 Error err;
4170 err.SetError (0, ErrorType::eErrorTypeGeneric);
4171 return err;
4172}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004173
4174bool
Aidan Doddsc0c83852015-05-08 09:36:31 +00004175ProcessGDBRemote::GetGDBServerRegisterInfo ()
Colin Rileyc3c95b22015-04-16 15:51:33 +00004176{
4177 // stub (libxml2 not present)
4178 return false;
4179}
4180
4181#endif // if defined( LIBXML2_DEFINED )
4182
Aidan Doddsc0c83852015-05-08 09:36:31 +00004183lldb::ModuleSP
4184ProcessGDBRemote::LoadModuleAtAddress (const FileSpec &file, lldb::addr_t base_addr)
4185{
4186 Target &target = m_process->GetTarget();
4187 ModuleList &modules = target.GetImages();
4188 ModuleSP module_sp;
4189
4190 bool changed = false;
4191
4192 ModuleSpec module_spec (file, target.GetArchitecture());
4193 if ((module_sp = modules.FindFirstModule (module_spec)))
4194 {
4195 module_sp->SetLoadAddress (target, base_addr, true, changed);
4196 }
4197 else if ((module_sp = target.GetSharedModule (module_spec)))
4198 {
4199 module_sp->SetLoadAddress (target, base_addr, true, changed);
4200 }
4201
4202 return module_sp;
4203}
4204
4205size_t
4206ProcessGDBRemote::LoadModules ()
4207{
4208 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4209
4210 // request a list of loaded libraries from GDBServer
4211 GDBLoadedModuleInfoList module_list;
4212 if (GetLoadedModuleList (module_list).Fail())
4213 return 0;
4214
4215 // get a list of all the modules
4216 ModuleList new_modules;
4217
4218 for (GDBLoadedModuleInfoList::LoadedModuleInfo & modInfo : module_list.m_list)
4219 {
4220 std::string mod_name;
4221 lldb::addr_t mod_base;
4222
4223 bool valid = true;
4224 valid &= modInfo.get_name (mod_name);
4225 valid &= modInfo.get_base (mod_base);
4226 if (!valid)
4227 continue;
4228
4229 // hack (cleaner way to get file name only?) (win/unix compat?)
Vince Harron4cc8d202015-05-10 08:33:58 +00004230 size_t marker = mod_name.rfind ('/');
Aidan Doddsc0c83852015-05-08 09:36:31 +00004231 if (marker == std::string::npos)
4232 marker = 0;
4233 else
4234 marker += 1;
4235
4236 FileSpec file (mod_name.c_str()+marker, true);
4237 lldb::ModuleSP module_sp = LoadModuleAtAddress (file, mod_base);
4238
4239 if (module_sp.get())
4240 new_modules.Append (module_sp);
4241 }
4242
4243 if (new_modules.GetSize() > 0)
4244 {
4245 Target & target = m_target;
4246
4247 new_modules.ForEach ([&target](const lldb::ModuleSP module_sp) -> bool
4248 {
4249 lldb_private::ObjectFile * obj = module_sp->GetObjectFile ();
4250 if (!obj)
4251 return true;
4252
4253 if (obj->GetType () != ObjectFile::Type::eTypeExecutable)
4254 return true;
4255
4256 lldb::ModuleSP module_copy_sp = module_sp;
4257 target.SetExecutableModule (module_copy_sp, false);
4258 return false;
4259 });
4260
4261 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4262 loaded_modules.AppendIfNeeded (new_modules);
4263 m_process->GetTarget().ModulesDidLoad (new_modules);
4264 }
4265
4266 return new_modules.GetSize();
4267}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004268
Greg Clayton02686b82012-10-15 22:42:16 +00004269class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00004270{
4271private:
4272
4273public:
Greg Clayton02686b82012-10-15 22:42:16 +00004274 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00004275 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00004276 "process plugin packet history",
4277 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00004278 NULL)
4279 {
4280 }
4281
Greg Clayton02686b82012-10-15 22:42:16 +00004282 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton998255b2012-10-13 02:07:45 +00004283 {
4284 }
4285
4286 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004287 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton998255b2012-10-13 02:07:45 +00004288 {
Greg Clayton02686b82012-10-15 22:42:16 +00004289 const size_t argc = command.GetArgumentCount();
4290 if (argc == 0)
4291 {
4292 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4293 if (process)
4294 {
4295 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
4296 result.SetStatus (eReturnStatusSuccessFinishResult);
4297 return true;
4298 }
4299 }
4300 else
4301 {
4302 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
4303 }
4304 result.SetStatus (eReturnStatusFailed);
4305 return false;
4306 }
4307};
4308
Jason Molenda6076bf42014-05-06 04:34:52 +00004309class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed
4310{
4311private:
4312
4313public:
4314 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) :
4315 CommandObjectParsed (interpreter,
4316 "process plugin packet xfer-size",
4317 "Maximum size that lldb will try to read/write one one chunk.",
4318 NULL)
4319 {
4320 }
4321
4322 ~CommandObjectProcessGDBRemotePacketXferSize ()
4323 {
4324 }
4325
4326 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004327 DoExecute (Args& command, CommandReturnObject &result) override
Jason Molenda6076bf42014-05-06 04:34:52 +00004328 {
4329 const size_t argc = command.GetArgumentCount();
4330 if (argc == 0)
4331 {
4332 result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str());
4333 result.SetStatus (eReturnStatusFailed);
4334 return false;
4335 }
4336
4337 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4338 if (process)
4339 {
4340 const char *packet_size = command.GetArgumentAtIndex(0);
4341 errno = 0;
4342 uint64_t user_specified_max = strtoul (packet_size, NULL, 10);
4343 if (errno == 0 && user_specified_max != 0)
4344 {
4345 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max);
4346 result.SetStatus (eReturnStatusSuccessFinishResult);
4347 return true;
4348 }
4349 }
4350 result.SetStatus (eReturnStatusFailed);
4351 return false;
4352 }
4353};
4354
4355
Greg Clayton02686b82012-10-15 22:42:16 +00004356class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
4357{
4358private:
4359
4360public:
4361 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
4362 CommandObjectParsed (interpreter,
4363 "process plugin packet send",
4364 "Send a custom packet through the GDB remote protocol and print the answer. "
4365 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
4366 NULL)
4367 {
4368 }
4369
4370 ~CommandObjectProcessGDBRemotePacketSend ()
4371 {
4372 }
4373
4374 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004375 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton02686b82012-10-15 22:42:16 +00004376 {
4377 const size_t argc = command.GetArgumentCount();
4378 if (argc == 0)
4379 {
4380 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
4381 result.SetStatus (eReturnStatusFailed);
4382 return false;
4383 }
4384
4385 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4386 if (process)
4387 {
Han Ming Ong84145852012-11-26 20:42:03 +00004388 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00004389 {
Han Ming Ong84145852012-11-26 20:42:03 +00004390 const char *packet_cstr = command.GetArgumentAtIndex(0);
4391 bool send_async = true;
4392 StringExtractorGDBRemote response;
4393 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
4394 result.SetStatus (eReturnStatusSuccessFinishResult);
4395 Stream &output_strm = result.GetOutputStream();
4396 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00004397 std::string &response_str = response.GetStringRef();
4398
Han Ming Ong399289e2013-06-21 19:56:59 +00004399 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00004400 {
4401 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
4402 }
4403
Han Ming Ong84145852012-11-26 20:42:03 +00004404 if (response_str.empty())
4405 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
4406 else
4407 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00004408 }
Greg Clayton02686b82012-10-15 22:42:16 +00004409 }
Greg Clayton998255b2012-10-13 02:07:45 +00004410 return true;
4411 }
4412};
4413
Greg Claytonba4a0a52013-02-01 23:03:47 +00004414class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
4415{
4416private:
4417
4418public:
4419 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
4420 CommandObjectRaw (interpreter,
4421 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00004422 "Send a qRcmd packet through the GDB remote protocol and print the response."
4423 "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 +00004424 NULL)
4425 {
4426 }
4427
4428 ~CommandObjectProcessGDBRemotePacketMonitor ()
4429 {
4430 }
4431
4432 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004433 DoExecute (const char *command, CommandReturnObject &result) override
Greg Claytonba4a0a52013-02-01 23:03:47 +00004434 {
4435 if (command == NULL || command[0] == '\0')
4436 {
4437 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
4438 result.SetStatus (eReturnStatusFailed);
4439 return false;
4440 }
4441
4442 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4443 if (process)
4444 {
4445 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00004446 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00004447 packet.PutBytesAsRawHex8(command, strlen(command));
4448 const char *packet_cstr = packet.GetString().c_str();
4449
4450 bool send_async = true;
4451 StringExtractorGDBRemote response;
4452 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
4453 result.SetStatus (eReturnStatusSuccessFinishResult);
4454 Stream &output_strm = result.GetOutputStream();
4455 output_strm.Printf (" packet: %s\n", packet_cstr);
4456 const std::string &response_str = response.GetStringRef();
4457
4458 if (response_str.empty())
4459 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
4460 else
4461 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
4462 }
4463 return true;
4464 }
4465};
4466
Greg Clayton02686b82012-10-15 22:42:16 +00004467class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
4468{
4469private:
4470
4471public:
4472 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
4473 CommandObjectMultiword (interpreter,
4474 "process plugin packet",
4475 "Commands that deal with GDB remote packets.",
4476 NULL)
4477 {
4478 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
4479 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00004480 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Jason Molenda6076bf42014-05-06 04:34:52 +00004481 LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00004482 }
4483
4484 ~CommandObjectProcessGDBRemotePacket ()
4485 {
4486 }
4487};
Greg Clayton998255b2012-10-13 02:07:45 +00004488
4489class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
4490{
4491public:
4492 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
4493 CommandObjectMultiword (interpreter,
4494 "process plugin",
4495 "A set of commands for operating on a ProcessGDBRemote process.",
4496 "process plugin <subcommand> [<subcommand-options>]")
4497 {
4498 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
4499 }
4500
4501 ~CommandObjectMultiwordProcessGDBRemote ()
4502 {
4503 }
4504};
4505
Greg Clayton998255b2012-10-13 02:07:45 +00004506CommandObject *
4507ProcessGDBRemote::GetPluginCommandObject()
4508{
4509 if (!m_command_sp)
4510 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
4511 return m_command_sp.get();
4512}