blob: ed6602383752bc5f96fea6eba5ed557476176263 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- ProcessGDBRemote.cpp ------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Virgile Bellob2f1fb22013-08-23 12:44:05 +000010#include "lldb/Host/Config.h"
Daniel Malea93a64302012-12-05 00:20:57 +000011
Chris Lattner30fdc8d2010-06-08 16:52:24 +000012// C Includes
13#include <errno.h>
Stephen Wilsona78867b2011-03-25 18:16:28 +000014#include <stdlib.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000015#ifndef LLDB_DISABLE_POSIX
Sean Callanan224f6f52012-07-19 18:07:36 +000016#include <netinet/in.h>
Greg Clayton2a48f522011-05-14 01:50:35 +000017#include <sys/mman.h> // for mmap
Virgile Bellob2f1fb22013-08-23 12:44:05 +000018#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000019#include <sys/stat.h>
Greg Clayton2a48f522011-05-14 01:50:35 +000020#include <sys/types.h>
Stephen Wilsondc916862011-03-30 00:12:40 +000021#include <time.h>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000022
23// C++ Includes
24#include <algorithm>
25#include <map>
Benjamin Kramer3f69fa62015-04-03 10:55:00 +000026#include <mutex>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000027
Johnny Chen01a67862011-10-14 00:42:25 +000028#include "lldb/Breakpoint/Watchpoint.h"
Jim Ingham40af72e2010-06-15 19:49:27 +000029#include "lldb/Interpreter/Args.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000030#include "lldb/Core/ArchSpec.h"
31#include "lldb/Core/Debugger.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000032#include "lldb/Host/ConnectionFileDescriptor.h"
Greg Clayton53239f02011-02-08 05:05:52 +000033#include "lldb/Host/FileSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000034#include "lldb/Core/Module.h"
Greg Clayton1f746072012-08-29 21:13:06 +000035#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000036#include "lldb/Core/PluginManager.h"
37#include "lldb/Core/State.h"
Greg Claytond451c1a2012-04-13 21:24:18 +000038#include "lldb/Core/StreamFile.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000039#include "lldb/Core/StreamString.h"
40#include "lldb/Core/Timer.h"
Greg Clayton70b57652011-05-15 01:25:55 +000041#include "lldb/Core/Value.h"
Greg Claytond04f0ed2015-05-26 18:00:51 +000042#include "lldb/DataFormatters/FormatManager.h"
Zachary Turner39de3112014-09-09 20:54:56 +000043#include "lldb/Host/HostThread.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000044#include "lldb/Host/StringConvert.h"
Jason Molendad1fae142012-09-29 08:03:33 +000045#include "lldb/Host/Symbols.h"
Zachary Turner39de3112014-09-09 20:54:56 +000046#include "lldb/Host/ThreadLauncher.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000047#include "lldb/Host/TimeValue.h"
Greg Claytond04f0ed2015-05-26 18:00:51 +000048#include "lldb/Host/XML.h"
Greg Clayton02686b82012-10-15 22:42:16 +000049#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton1d19a2f2012-10-19 22:22:57 +000050#include "lldb/Interpreter/CommandObject.h"
51#include "lldb/Interpreter/CommandObjectMultiword.h"
Greg Clayton02686b82012-10-15 22:42:16 +000052#include "lldb/Interpreter/CommandReturnObject.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000053#include "lldb/Interpreter/OptionValueProperties.h"
Greg Claytone034a042015-05-21 20:52:06 +000054#include "lldb/Interpreter/Options.h"
55#include "lldb/Interpreter/OptionGroupBoolean.h"
56#include "lldb/Interpreter/OptionGroupUInt64.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000057#include "lldb/Interpreter/Property.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000058#include "lldb/Symbol/ObjectFile.h"
59#include "lldb/Target/DynamicLoader.h"
60#include "lldb/Target/Target.h"
61#include "lldb/Target/TargetList.h"
Greg Clayton2a48f522011-05-14 01:50:35 +000062#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molenda705b1802014-06-13 02:37:02 +000063#include "lldb/Target/SystemRuntime.h"
Jason Molendaa34a0c62010-06-09 21:28:42 +000064#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000065
66// Project includes
67#include "lldb/Host/Host.h"
Chaoren Lin98d0a4b2015-07-14 01:09:28 +000068#include "Plugins/Process/Utility/GDBRemoteSignals.h"
Peter Collingbourne99f9aa02011-06-03 20:40:38 +000069#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Jason Molendac42d2432012-07-25 03:40:06 +000070#include "Plugins/Process/Utility/StopInfoMachException.h"
Jim Ingham43c555d2012-07-04 00:35:43 +000071#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
Greg Claytonc982c762010-07-09 20:39:50 +000072#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000073#include "GDBRemoteRegisterContext.h"
74#include "ProcessGDBRemote.h"
75#include "ProcessGDBRemoteLog.h"
76#include "ThreadGDBRemote.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000077
Tamas Berghammerdb264a62015-03-31 09:52:22 +000078#define DEBUGSERVER_BASENAME "debugserver"
79using namespace lldb;
80using namespace lldb_private;
81using namespace lldb_private::process_gdb_remote;
Jason Molenda5e8534e2012-10-03 01:29:34 +000082
Greg Claytonc1422c12012-04-09 22:46:21 +000083namespace lldb
84{
85 // Provide a function that can easily dump the packet history if we know a
86 // ProcessGDBRemote * value (which we can get from logs or from debugging).
87 // We need the function in the lldb namespace so it makes it into the final
88 // executable since the LLDB shared library only exports stuff in the lldb
89 // namespace. This allows you to attach with a debugger and call this
90 // function and get the packet history dumped to a file.
91 void
92 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
93 {
Tamas Berghammerdb264a62015-03-31 09:52:22 +000094 StreamFile strm;
95 Error error (strm.GetFile().Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate));
Greg Claytond451c1a2012-04-13 21:24:18 +000096 if (error.Success())
97 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
Greg Claytonc1422c12012-04-09 22:46:21 +000098 }
Filipe Cabecinhasc34f7762012-05-23 16:27:09 +000099}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000100
Greg Clayton7f982402013-07-15 22:54:20 +0000101namespace {
Steve Pucci5ec012d2014-01-16 22:18:14 +0000102
Greg Clayton7f982402013-07-15 22:54:20 +0000103 static PropertyDefinition
104 g_properties[] =
105 {
106 { "packet-timeout" , OptionValue::eTypeUInt64 , true , 1, NULL, NULL, "Specify the default packet timeout in seconds." },
Greg Claytonef8180a2013-10-15 00:14:28 +0000107 { "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 +0000108 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
109 };
110
111 enum
112 {
Greg Claytonef8180a2013-10-15 00:14:28 +0000113 ePropertyPacketTimeout,
114 ePropertyTargetDefinitionFile
Greg Clayton7f982402013-07-15 22:54:20 +0000115 };
116
117 class PluginProperties : public Properties
118 {
119 public:
120
121 static ConstString
122 GetSettingName ()
123 {
124 return ProcessGDBRemote::GetPluginNameStatic();
125 }
126
127 PluginProperties() :
128 Properties ()
129 {
130 m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
131 m_collection_sp->Initialize(g_properties);
132 }
133
134 virtual
135 ~PluginProperties()
136 {
137 }
138
139 uint64_t
140 GetPacketTimeout()
141 {
142 const uint32_t idx = ePropertyPacketTimeout;
143 return m_collection_sp->GetPropertyAtIndexAsUInt64(NULL, idx, g_properties[idx].default_uint_value);
144 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000145
146 bool
147 SetPacketTimeout(uint64_t timeout)
148 {
149 const uint32_t idx = ePropertyPacketTimeout;
150 return m_collection_sp->SetPropertyAtIndexAsUInt64(NULL, idx, timeout);
151 }
152
Greg Claytonef8180a2013-10-15 00:14:28 +0000153 FileSpec
154 GetTargetDefinitionFile () const
155 {
156 const uint32_t idx = ePropertyTargetDefinitionFile;
157 return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
158 }
Greg Clayton7f982402013-07-15 22:54:20 +0000159 };
160
161 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
162
163 static const ProcessKDPPropertiesSP &
164 GetGlobalPluginProperties()
165 {
166 static ProcessKDPPropertiesSP g_settings_sp;
167 if (!g_settings_sp)
168 g_settings_sp.reset (new PluginProperties ());
169 return g_settings_sp;
170 }
171
172} // anonymous namespace end
173
Aidan Doddsc0c83852015-05-08 09:36:31 +0000174class ProcessGDBRemote::GDBLoadedModuleInfoList
175{
176public:
177
178 class LoadedModuleInfo
179 {
180 public:
181
182 enum e_data_point
183 {
184 e_has_name = 0,
185 e_has_base ,
186 e_has_dynamic ,
187 e_has_link_map ,
188 e_num
189 };
190
191 LoadedModuleInfo ()
192 {
193 for (uint32_t i = 0; i < e_num; ++i)
194 m_has[i] = false;
Pavel Labathcb213b32015-07-22 08:12:01 +0000195 }
Aidan Doddsc0c83852015-05-08 09:36:31 +0000196
197 void set_name (const std::string & name)
198 {
199 m_name = name;
200 m_has[e_has_name] = true;
201 }
202 bool get_name (std::string & out) const
203 {
204 out = m_name;
205 return m_has[e_has_name];
206 }
207
208 void set_base (const lldb::addr_t base)
209 {
210 m_base = base;
211 m_has[e_has_base] = true;
212 }
213 bool get_base (lldb::addr_t & out) const
214 {
215 out = m_base;
216 return m_has[e_has_base];
217 }
218
219 void set_link_map (const lldb::addr_t addr)
220 {
221 m_link_map = addr;
222 m_has[e_has_link_map] = true;
223 }
224 bool get_link_map (lldb::addr_t & out) const
225 {
226 out = m_link_map;
227 return m_has[e_has_link_map];
228 }
229
230 void set_dynamic (const lldb::addr_t addr)
231 {
232 m_dynamic = addr;
233 m_has[e_has_dynamic] = true;
234 }
235 bool get_dynamic (lldb::addr_t & out) const
236 {
237 out = m_dynamic;
238 return m_has[e_has_dynamic];
239 }
240
241 bool has_info (e_data_point datum)
242 {
243 assert (datum < e_num);
244 return m_has[datum];
245 }
246
247 protected:
248
249 bool m_has[e_num];
250 std::string m_name;
251 lldb::addr_t m_link_map;
252 lldb::addr_t m_base;
253 lldb::addr_t m_dynamic;
254 };
255
256 GDBLoadedModuleInfoList ()
257 : m_list ()
258 , m_link_map (LLDB_INVALID_ADDRESS)
259 {}
260
261 void add (const LoadedModuleInfo & mod)
262 {
263 m_list.push_back (mod);
264 }
265
266 void clear ()
267 {
268 m_list.clear ();
269 }
270
271 std::vector<LoadedModuleInfo> m_list;
272 lldb::addr_t m_link_map;
273};
274
Greg Claytonfda4fab2014-01-10 22:24:11 +0000275// TODO Randomly assigning a port is unsafe. We should get an unused
276// ephemeral port from the kernel and make sure we reserve it before passing
277// it to debugserver.
278
279#if defined (__APPLE__)
280#define LOW_PORT (IPPORT_RESERVED)
281#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
282#else
283#define LOW_PORT (1024u)
284#define HIGH_PORT (49151u)
285#endif
286
Todd Fiala013434e2014-07-09 01:29:05 +0000287#if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000288static bool rand_initialized = false;
289
Greg Claytonfda4fab2014-01-10 22:24:11 +0000290static inline uint16_t
291get_random_port ()
292{
293 if (!rand_initialized)
294 {
295 time_t seed = time(NULL);
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000296
Greg Claytonfda4fab2014-01-10 22:24:11 +0000297 rand_initialized = true;
298 srand(seed);
299 }
300 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
301}
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000302#endif
Greg Claytonfda4fab2014-01-10 22:24:11 +0000303
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000304ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000305ProcessGDBRemote::GetPluginNameStatic()
306{
Greg Clayton57abc5d2013-05-10 21:47:16 +0000307 static ConstString g_name("gdb-remote");
308 return g_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000309}
310
311const char *
312ProcessGDBRemote::GetPluginDescriptionStatic()
313{
314 return "GDB Remote protocol based debugging plug-in.";
315}
316
317void
318ProcessGDBRemote::Terminate()
319{
320 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
321}
322
323
Greg Claytonc3776bf2012-02-09 06:16:32 +0000324lldb::ProcessSP
325ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000326{
Greg Claytonc3776bf2012-02-09 06:16:32 +0000327 lldb::ProcessSP process_sp;
328 if (crash_file_path == NULL)
329 process_sp.reset (new ProcessGDBRemote (target, listener));
330 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000331}
332
333bool
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000334ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000335{
Greg Clayton596ed242011-10-21 21:41:45 +0000336 if (plugin_specified_by_name)
337 return true;
338
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000339 // For now we are just making sure the file exists for a given module
Greg Claytonaa149cb2011-08-11 02:48:45 +0000340 Module *exe_module = target.GetExecutableModulePointer();
341 if (exe_module)
Greg Claytonc3776bf2012-02-09 06:16:32 +0000342 {
343 ObjectFile *exe_objfile = exe_module->GetObjectFile();
344 // We can't debug core files...
345 switch (exe_objfile->GetType())
346 {
347 case ObjectFile::eTypeInvalid:
348 case ObjectFile::eTypeCoreFile:
349 case ObjectFile::eTypeDebugInfo:
350 case ObjectFile::eTypeObjectFile:
351 case ObjectFile::eTypeSharedLibrary:
352 case ObjectFile::eTypeStubLibrary:
Greg Clayton23f8c952014-03-24 23:10:19 +0000353 case ObjectFile::eTypeJIT:
Greg Claytonc3776bf2012-02-09 06:16:32 +0000354 return false;
355 case ObjectFile::eTypeExecutable:
356 case ObjectFile::eTypeDynamicLinker:
357 case ObjectFile::eTypeUnknown:
358 break;
359 }
Greg Claytonaa149cb2011-08-11 02:48:45 +0000360 return exe_module->GetFileSpec().Exists();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000361 }
Jim Ingham5aee1622010-08-09 23:31:02 +0000362 // However, if there is no executable module, we return true since we might be preparing to attach.
363 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000364}
365
366//----------------------------------------------------------------------
367// ProcessGDBRemote constructor
368//----------------------------------------------------------------------
369ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
370 Process (target, listener),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000371 m_flags (0),
Tamas Berghammere13c2732015-02-11 10:29:30 +0000372 m_gdb_comm (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000373 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Bhushan D. Attarde1e271df2015-07-24 04:06:20 +0000374 m_last_stop_packet_mutex (Mutex::eMutexTypeRecursive),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000375 m_register_info (),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000376 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
Jim Ingham455fa5c2012-11-01 01:15:33 +0000377 m_async_thread_state_mutex(Mutex::eMutexTypeRecursive),
Greg Clayton9e920902012-04-10 02:25:43 +0000378 m_thread_ids (),
Greg Clayton2e309072015-07-17 23:42:28 +0000379 m_jstopinfo_sp (),
380 m_jthreadsinfo_sp (),
Greg Clayton71fc2a32011-02-12 06:28:37 +0000381 m_continue_c_tids (),
382 m_continue_C_tids (),
383 m_continue_s_tids (),
384 m_continue_S_tids (),
Jason Molenda6076bf42014-05-06 04:34:52 +0000385 m_max_memory_size (0),
386 m_remote_stub_max_memory_size (0),
Greg Clayton4116e932012-05-15 02:33:01 +0000387 m_addr_to_mmap_size (),
388 m_thread_create_bp_sp (),
Jim Ingham43c555d2012-07-04 00:35:43 +0000389 m_waiting_for_attach (false),
Jason Molenda5e8534e2012-10-03 01:29:34 +0000390 m_destroy_tried_resuming (false),
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000391 m_command_sp (),
Ewan Crawford78baa192015-05-13 09:18:18 +0000392 m_breakpoint_pc_offset (0),
393 m_initial_tid (LLDB_INVALID_THREAD_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000394{
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000395 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
396 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Inghamb1e2e842012-04-12 18:49:31 +0000397 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Greg Clayton7f982402013-07-15 22:54:20 +0000398 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
399 if (timeout_seconds > 0)
400 m_gdb_comm.SetPacketTimeout(timeout_seconds);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000401}
402
403//----------------------------------------------------------------------
404// Destructor
405//----------------------------------------------------------------------
406ProcessGDBRemote::~ProcessGDBRemote()
407{
408 // m_mach_process.UnregisterNotificationCallbacks (this);
409 Clear();
Greg Clayton1ed54f52011-10-01 00:45:15 +0000410 // We need to call finalize on the process before destroying ourselves
411 // to make sure all of the broadcaster cleanup goes as planned. If we
412 // destruct this class, then Process::~Process() might have problems
413 // trying to fully destroy the broadcaster.
414 Finalize();
Jim Ingham455fa5c2012-11-01 01:15:33 +0000415
416 // The general Finalize is going to try to destroy the process and that SHOULD
417 // shut down the async thread. However, if we don't kill it it will get stranded and
418 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
419 StopAsyncThread();
420 KillDebugserverProcess();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000421}
422
423//----------------------------------------------------------------------
424// PluginInterface
425//----------------------------------------------------------------------
Greg Clayton57abc5d2013-05-10 21:47:16 +0000426ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000427ProcessGDBRemote::GetPluginName()
428{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000429 return GetPluginNameStatic();
430}
431
432uint32_t
433ProcessGDBRemote::GetPluginVersion()
434{
435 return 1;
436}
437
Greg Claytonef8180a2013-10-15 00:14:28 +0000438bool
439ProcessGDBRemote::ParsePythonTargetDefinition(const FileSpec &target_definition_fspec)
440{
441 ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
442 Error error;
Zachary Turner0641ca12015-03-17 20:04:04 +0000443 StructuredData::ObjectSP module_object_sp(interpreter->LoadPluginModule(target_definition_fspec, error));
Greg Claytonef8180a2013-10-15 00:14:28 +0000444 if (module_object_sp)
445 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000446 StructuredData::DictionarySP target_definition_sp(
447 interpreter->GetDynamicSettings(module_object_sp, &GetTarget(), "gdb-server-target-definition", error));
Greg Claytonef8180a2013-10-15 00:14:28 +0000448
Zachary Turner0641ca12015-03-17 20:04:04 +0000449 if (target_definition_sp)
Greg Claytonef8180a2013-10-15 00:14:28 +0000450 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000451 StructuredData::ObjectSP target_object(target_definition_sp->GetValueForKey("host-info"));
452 if (target_object)
Greg Clayton312bcbe2013-10-17 01:10:23 +0000453 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000454 if (auto host_info_dict = target_object->GetAsDictionary())
Greg Clayton312bcbe2013-10-17 01:10:23 +0000455 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000456 StructuredData::ObjectSP triple_value = host_info_dict->GetValueForKey("triple");
457 if (auto triple_string_value = triple_value->GetAsString())
458 {
459 std::string triple_string = triple_string_value->GetValue();
460 ArchSpec host_arch(triple_string.c_str());
461 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture()))
462 {
463 GetTarget().SetArchitecture(host_arch);
464 }
465 }
Greg Clayton312bcbe2013-10-17 01:10:23 +0000466 }
Greg Clayton312bcbe2013-10-17 01:10:23 +0000467 }
Zachary Turner0641ca12015-03-17 20:04:04 +0000468 m_breakpoint_pc_offset = 0;
469 StructuredData::ObjectSP breakpoint_pc_offset_value = target_definition_sp->GetValueForKey("breakpoint-pc-offset");
470 if (breakpoint_pc_offset_value)
471 {
472 if (auto breakpoint_pc_int_value = breakpoint_pc_offset_value->GetAsInteger())
473 m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
474 }
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000475
Greg Claytond04f0ed2015-05-26 18:00:51 +0000476 if (m_register_info.SetRegisterInfo(*target_definition_sp, GetTarget().GetArchitecture()) > 0)
Greg Claytonef8180a2013-10-15 00:14:28 +0000477 {
478 return true;
479 }
480 }
481 }
482 return false;
483}
484
Greg Claytond04f0ed2015-05-26 18:00:51 +0000485static size_t
486SplitCommaSeparatedRegisterNumberString(const llvm::StringRef &comma_separated_regiter_numbers, std::vector<uint32_t> &regnums, int base)
487{
488 regnums.clear();
489 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
490 value_pair.second = comma_separated_regiter_numbers;
491 do
492 {
493 value_pair = value_pair.second.split(',');
494 if (!value_pair.first.empty())
495 {
496 uint32_t reg = StringConvert::ToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, base);
497 if (reg != LLDB_INVALID_REGNUM)
498 regnums.push_back (reg);
499 }
500 } while (!value_pair.second.empty());
501 return regnums.size();
502}
503
Greg Claytonef8180a2013-10-15 00:14:28 +0000504
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000505void
Greg Clayton513c26c2011-01-29 07:10:55 +0000506ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000507{
Greg Clayton513c26c2011-01-29 07:10:55 +0000508 if (!force && m_register_info.GetNumRegisters() > 0)
509 return;
510
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000511 m_register_info.Clear();
Greg Claytond04f0ed2015-05-26 18:00:51 +0000512
513 // Check if qHostInfo specified a specific packet timeout for this connection.
514 // If so then lets update our setting so the user knows what the timeout is
515 // and can see it.
516 const uint32_t host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
517 if (host_packet_timeout)
518 {
519 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout);
520 }
521
Ewan Crawford0c996a92015-06-30 13:08:44 +0000522 // Register info search order:
523 // 1 - Use the target definition python file if one is specified.
524 // 2 - If the target definition doesn't have any of the info from the target.xml (registers) then proceed to read the target.xml.
525 // 3 - Fall back on the qRegisterInfo packets.
526
527 FileSpec target_definition_fspec = GetGlobalPluginProperties()->GetTargetDefinitionFile ();
528 if (target_definition_fspec)
529 {
530 // See if we can get register definitions from a python file
531 if (ParsePythonTargetDefinition (target_definition_fspec))
Jason Molenda5543abb2015-08-20 03:05:09 +0000532 {
Ewan Crawford0c996a92015-06-30 13:08:44 +0000533 return;
Jason Molenda5543abb2015-08-20 03:05:09 +0000534 }
535 else
536 {
537 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
538 stream_sp->Printf ("ERROR: target description file %s failed to parse.\n", target_definition_fspec.GetPath().c_str());
539 }
Ewan Crawford0c996a92015-06-30 13:08:44 +0000540 }
541
Greg Claytond04f0ed2015-05-26 18:00:51 +0000542 if (GetGDBServerRegisterInfo ())
543 return;
544
545 char packet[128];
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000546 uint32_t reg_offset = 0;
547 uint32_t reg_num = 0;
Greg Clayton23f59502012-07-17 03:23:13 +0000548 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Greg Clayton576d8832011-03-22 04:00:09 +0000549 response_type == StringExtractorGDBRemote::eResponse;
550 ++reg_num)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000551 {
Greg Clayton513c26c2011-01-29 07:10:55 +0000552 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
Andy Gibbsa297a972013-06-19 19:04:53 +0000553 assert (packet_len < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000554 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000555 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000556 {
Greg Clayton576d8832011-03-22 04:00:09 +0000557 response_type = response.GetResponseType();
558 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000559 {
560 std::string name;
561 std::string value;
562 ConstString reg_name;
563 ConstString alt_name;
564 ConstString set_name;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000565 std::vector<uint32_t> value_regs;
566 std::vector<uint32_t> invalidate_regs;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000567 RegisterInfo reg_info = { NULL, // Name
568 NULL, // Alt name
569 0, // byte size
570 reg_offset, // offset
571 eEncodingUint, // encoding
572 eFormatHex, // formate
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000573 {
574 LLDB_INVALID_REGNUM, // GCC reg num
575 LLDB_INVALID_REGNUM, // DWARF reg num
576 LLDB_INVALID_REGNUM, // generic reg num
Jason Molendafbcb7f22010-09-10 07:49:16 +0000577 reg_num, // GDB reg num
578 reg_num // native register number
Greg Clayton435d85a2012-02-29 19:27:27 +0000579 },
580 NULL,
581 NULL
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000582 };
583
584 while (response.GetNameColonValue(name, value))
585 {
586 if (name.compare("name") == 0)
587 {
588 reg_name.SetCString(value.c_str());
589 }
590 else if (name.compare("alt-name") == 0)
591 {
592 alt_name.SetCString(value.c_str());
593 }
594 else if (name.compare("bitsize") == 0)
595 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000596 reg_info.byte_size = StringConvert::ToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000597 }
598 else if (name.compare("offset") == 0)
599 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000600 uint32_t offset = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda743e86a2010-06-11 23:44:18 +0000601 if (reg_offset != offset)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000602 {
603 reg_offset = offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000604 }
605 }
606 else if (name.compare("encoding") == 0)
607 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000608 const Encoding encoding = Args::StringToEncoding (value.c_str());
609 if (encoding != eEncodingInvalid)
610 reg_info.encoding = encoding;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000611 }
612 else if (name.compare("format") == 0)
613 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000614 Format format = eFormatInvalid;
615 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
616 reg_info.format = format;
617 else if (value.compare("binary") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000618 reg_info.format = eFormatBinary;
619 else if (value.compare("decimal") == 0)
620 reg_info.format = eFormatDecimal;
621 else if (value.compare("hex") == 0)
622 reg_info.format = eFormatHex;
623 else if (value.compare("float") == 0)
624 reg_info.format = eFormatFloat;
625 else if (value.compare("vector-sint8") == 0)
626 reg_info.format = eFormatVectorOfSInt8;
627 else if (value.compare("vector-uint8") == 0)
628 reg_info.format = eFormatVectorOfUInt8;
629 else if (value.compare("vector-sint16") == 0)
630 reg_info.format = eFormatVectorOfSInt16;
631 else if (value.compare("vector-uint16") == 0)
632 reg_info.format = eFormatVectorOfUInt16;
633 else if (value.compare("vector-sint32") == 0)
634 reg_info.format = eFormatVectorOfSInt32;
635 else if (value.compare("vector-uint32") == 0)
636 reg_info.format = eFormatVectorOfUInt32;
637 else if (value.compare("vector-float32") == 0)
638 reg_info.format = eFormatVectorOfFloat32;
639 else if (value.compare("vector-uint128") == 0)
640 reg_info.format = eFormatVectorOfUInt128;
641 }
642 else if (name.compare("set") == 0)
643 {
644 set_name.SetCString(value.c_str());
645 }
Jason Molendaa18f7072015-08-15 01:21:01 +0000646 else if (name.compare("gcc") == 0 || name.compare("ehframe") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000647 {
Jason Molendaa18f7072015-08-15 01:21:01 +0000648 reg_info.kinds[eRegisterKindEHFrame] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000649 }
650 else if (name.compare("dwarf") == 0)
651 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000652 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000653 }
654 else if (name.compare("generic") == 0)
655 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000656 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000657 }
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000658 else if (name.compare("container-regs") == 0)
659 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000660 SplitCommaSeparatedRegisterNumberString(value, value_regs, 16);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000661 }
662 else if (name.compare("invalidate-regs") == 0)
663 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000664 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 16);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000665 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000666 }
667
Jason Molenda743e86a2010-06-11 23:44:18 +0000668 reg_info.byte_offset = reg_offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000669 assert (reg_info.byte_size != 0);
670 reg_offset += reg_info.byte_size;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000671 if (!value_regs.empty())
672 {
673 value_regs.push_back(LLDB_INVALID_REGNUM);
674 reg_info.value_regs = value_regs.data();
675 }
676 if (!invalidate_regs.empty())
677 {
678 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
679 reg_info.invalidate_regs = invalidate_regs.data();
680 }
681
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000682 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
683 }
Todd Fiala1a634402014-01-08 07:52:40 +0000684 else
685 {
686 break; // ensure exit before reg_num is incremented
687 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000688 }
689 else
690 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000691 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000692 }
693 }
694
Greg Claytond04f0ed2015-05-26 18:00:51 +0000695 if (m_register_info.GetNumRegisters() > 0)
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000696 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000697 m_register_info.Finalize(GetTarget().GetArchitecture());
698 return;
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000699 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000700
Johnny Chen2fa9de12012-05-14 18:44:23 +0000701 // We didn't get anything if the accumulated reg_num is zero. See if we are
702 // debugging ARM and fill with a hard coded register set until we can get an
703 // updated debugserver down on the devices.
704 // On the other hand, if the accumulated reg_num is positive, see if we can
705 // add composite registers to the existing primordial ones.
Greg Claytond04f0ed2015-05-26 18:00:51 +0000706 bool from_scratch = (m_register_info.GetNumRegisters() == 0);
Johnny Chen2fa9de12012-05-14 18:44:23 +0000707
708 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000709 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
710 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
711
712 // Use the process' architecture instead of the host arch, if available
713 ArchSpec remote_arch;
714 if (remote_process_arch.IsValid ())
715 remote_arch = remote_process_arch;
716 else
717 remote_arch = remote_host_arch;
718
Johnny Chen2fa9de12012-05-14 18:44:23 +0000719 if (!target_arch.IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000720 {
Johnny Chen2fa9de12012-05-14 18:44:23 +0000721 if (remote_arch.IsValid()
722 && remote_arch.GetMachine() == llvm::Triple::arm
723 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
724 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000725 }
Johnny Chen2fa9de12012-05-14 18:44:23 +0000726 else if (target_arch.GetMachine() == llvm::Triple::arm)
727 {
728 m_register_info.HardcodeARMRegisters(from_scratch);
729 }
730
731 // At this point, we can finalize our register info.
Greg Claytond04f0ed2015-05-26 18:00:51 +0000732 m_register_info.Finalize (GetTarget().GetArchitecture());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000733}
734
735Error
736ProcessGDBRemote::WillLaunch (Module* module)
737{
738 return WillLaunchOrAttach ();
739}
740
741Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000742ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000743{
744 return WillLaunchOrAttach ();
745}
746
747Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000748ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000749{
750 return WillLaunchOrAttach ();
751}
752
753Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000754ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +0000755{
Todd Fialaaf245d12014-06-30 21:05:18 +0000756 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Claytonb766a732011-02-04 01:58:07 +0000757 Error error (WillLaunchOrAttach ());
758
759 if (error.Fail())
760 return error;
761
Greg Clayton2289fa42011-04-30 01:09:13 +0000762 error = ConnectToDebugserver (remote_url);
Greg Claytonb766a732011-02-04 01:58:07 +0000763
764 if (error.Fail())
765 return error;
766 StartAsyncThread ();
767
Greg Claytonc574ede2011-03-10 02:26:48 +0000768 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonb766a732011-02-04 01:58:07 +0000769 if (pid == LLDB_INVALID_PROCESS_ID)
770 {
771 // We don't have a valid process ID, so note that we are connected
772 // and could now request to launch or attach, or get remote process
773 // listings...
774 SetPrivateState (eStateConnected);
775 }
776 else
777 {
778 // We have a valid process
779 SetID (pid);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000780 GetThreadList();
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000781 StringExtractorGDBRemote response;
782 if (m_gdb_comm.GetStopReply(response))
Greg Claytonb766a732011-02-04 01:58:07 +0000783 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000784 SetLastStopPacket(response);
Ewan Crawford78baa192015-05-13 09:18:18 +0000785
786 // '?' Packets must be handled differently in non-stop mode
787 if (GetTarget().GetNonStopModeEnabled())
788 HandleStopReplySequence();
789
Jason Molendac62bd7b2013-12-21 05:20:36 +0000790 if (!m_target.GetArchitecture().IsValid())
791 {
792 if (m_gdb_comm.GetProcessArchitecture().IsValid())
793 {
794 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
795 }
796 else
797 {
798 m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
799 }
Carlo Kok74389122013-10-14 07:09:13 +0000800 }
801
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000802 const StateType state = SetThreadStopInfo (response);
Greg Clayton2e309072015-07-17 23:42:28 +0000803 if (state != eStateInvalid)
Greg Claytonb766a732011-02-04 01:58:07 +0000804 {
805 SetPrivateState (state);
806 }
807 else
Daniel Malead01b2952012-11-29 21:49:15 +0000808 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 +0000809 }
810 else
Daniel Malead01b2952012-11-29 21:49:15 +0000811 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 +0000812 }
Jason Molenda16d127c2012-05-03 22:37:30 +0000813
Todd Fialaaf245d12014-06-30 21:05:18 +0000814 if (log)
815 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");
816
817
818 if (error.Success()
Jason Molenda16d127c2012-05-03 22:37:30 +0000819 && !GetTarget().GetArchitecture().IsValid()
820 && m_gdb_comm.GetHostArchitecture().IsValid())
821 {
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000822 // Prefer the *process'* architecture over that of the *host*, if available.
823 if (m_gdb_comm.GetProcessArchitecture().IsValid())
824 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
825 else
826 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molenda16d127c2012-05-03 22:37:30 +0000827 }
828
Todd Fialaaf245d12014-06-30 21:05:18 +0000829 if (log)
830 log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": normalized target architecture triple: %s", __FUNCTION__, GetID (), GetTarget ().GetArchitecture ().GetTriple ().getTriple ().c_str ());
831
Chaoren Lin98d0a4b2015-07-14 01:09:28 +0000832 if (error.Success())
Jaydeep Patil6fc590d2015-07-30 05:06:51 +0000833 {
834 PlatformSP platform_sp = GetTarget().GetPlatform();
835 if (platform_sp && platform_sp->IsConnected())
836 SetUnixSignals(platform_sp->GetUnixSignals());
837 else
838 SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
839 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000840
Greg Claytonb766a732011-02-04 01:58:07 +0000841 return error;
842}
843
844Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000845ProcessGDBRemote::WillLaunchOrAttach ()
846{
847 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000848 m_stdio_communication.Clear ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000849 return error;
850}
851
852//----------------------------------------------------------------------
853// Process Control
854//----------------------------------------------------------------------
855Error
Jean-Daniel Dupas7782de92013-12-09 22:52:50 +0000856ProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000857{
Todd Fiala75f47c32014-10-11 21:42:09 +0000858 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton4957bf62010-09-30 21:49:03 +0000859 Error error;
Greg Clayton982c9762011-11-03 21:22:33 +0000860
Todd Fiala75f47c32014-10-11 21:42:09 +0000861 if (log)
862 log->Printf ("ProcessGDBRemote::%s() entered", __FUNCTION__);
863
Greg Clayton982c9762011-11-03 21:22:33 +0000864 uint32_t launch_flags = launch_info.GetFlags().Get();
Chaoren Lind3173f32015-05-29 19:52:29 +0000865 FileSpec stdin_file_spec{};
866 FileSpec stdout_file_spec{};
867 FileSpec stderr_file_spec{};
868 FileSpec working_dir = launch_info.GetWorkingDirectory();
Greg Clayton982c9762011-11-03 21:22:33 +0000869
Zachary Turner696b5282014-08-14 16:01:25 +0000870 const FileAction *file_action;
Greg Clayton982c9762011-11-03 21:22:33 +0000871 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
872 if (file_action)
873 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000874 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000875 stdin_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000876 }
877 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
878 if (file_action)
879 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000880 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000881 stdout_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000882 }
883 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
884 if (file_action)
885 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000886 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000887 stderr_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000888 }
889
Todd Fiala75f47c32014-10-11 21:42:09 +0000890 if (log)
891 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000892 if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
Vince Harron4a8abd32015-02-13 19:15:24 +0000893 log->Printf ("ProcessGDBRemote::%s provided with STDIO paths via launch_info: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000894 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000895 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
896 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
897 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Todd Fiala75f47c32014-10-11 21:42:09 +0000898 else
899 log->Printf ("ProcessGDBRemote::%s no STDIO paths given via launch_info", __FUNCTION__);
900 }
901
Vince Harrondf3f00f2015-02-10 21:09:04 +0000902 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Chaoren Lind3173f32015-05-29 19:52:29 +0000903 if (stdin_file_spec || disable_stdio)
Vince Harrondf3f00f2015-02-10 21:09:04 +0000904 {
905 // the inferior will be reading stdin from the specified file
906 // or stdio is completely disabled
907 m_stdin_forward = false;
908 }
909 else
910 {
911 m_stdin_forward = true;
912 }
913
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000914 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
915 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
916 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000917
Greg Clayton982c9762011-11-03 21:22:33 +0000918 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000919 if (object_file)
920 {
Greg Clayton71337622011-02-24 22:24:29 +0000921 // Make sure we aren't already connected?
922 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000923 {
Greg Clayton91a9b2472013-12-04 19:19:12 +0000924 error = LaunchAndConnectToDebugserver (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000925 }
926
927 if (error.Success())
928 {
929 lldb_utility::PseudoTerminal pty;
930 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000931
Greg Claytonf58c2692011-06-24 22:32:10 +0000932 PlatformSP platform_sp (m_target.GetPlatform());
Vince Harrondf3f00f2015-02-10 21:09:04 +0000933 if (disable_stdio)
Greg Clayton71337622011-02-24 22:24:29 +0000934 {
Vince Harrondf3f00f2015-02-10 21:09:04 +0000935 // set to /dev/null unless redirected to a file above
Chaoren Lind3173f32015-05-29 19:52:29 +0000936 if (!stdin_file_spec)
937 stdin_file_spec.SetFile("/dev/null", false);
938 if (!stdout_file_spec)
939 stdout_file_spec.SetFile("/dev/null", false);
940 if (!stderr_file_spec)
941 stderr_file_spec.SetFile("/dev/null", false);
Vince Harrondf3f00f2015-02-10 21:09:04 +0000942 }
943 else if (platform_sp && platform_sp->IsHost())
944 {
945 // If the debugserver is local and we aren't disabling STDIO, lets use
946 // a pseudo terminal to instead of relying on the 'O' packets for stdio
947 // since 'O' packets can really slow down debugging if the inferior
948 // does a lot of output.
Chaoren Lind3173f32015-05-29 19:52:29 +0000949 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
950 pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000951 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000952 FileSpec slave_name{pty.GetSlaveName(NULL, 0), false};
953
954 if (!stdin_file_spec)
955 stdin_file_spec = slave_name;
956
957 if (!stdout_file_spec)
958 stdout_file_spec = slave_name;
959
960 if (!stderr_file_spec)
961 stderr_file_spec = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000962 }
Todd Fiala75f47c32014-10-11 21:42:09 +0000963 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +0000964 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 +0000965 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000966 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
967 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
968 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Greg Clayton71337622011-02-24 22:24:29 +0000969 }
970
Todd Fiala75f47c32014-10-11 21:42:09 +0000971 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +0000972 log->Printf ("ProcessGDBRemote::%s final STDIO paths after all adjustments: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000973 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000974 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
975 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
976 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Todd Fiala75f47c32014-10-11 21:42:09 +0000977
Chaoren Lind3173f32015-05-29 19:52:29 +0000978 if (stdin_file_spec)
979 m_gdb_comm.SetSTDIN(stdin_file_spec);
980 if (stdout_file_spec)
981 m_gdb_comm.SetSTDOUT(stdout_file_spec);
982 if (stderr_file_spec)
983 m_gdb_comm.SetSTDERR(stderr_file_spec);
Greg Clayton71337622011-02-24 22:24:29 +0000984
985 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
Jim Ingham106d0282014-06-25 02:32:56 +0000986 m_gdb_comm.SetDetachOnError (launch_flags & eLaunchFlagDetachOnError);
Greg Clayton71337622011-02-24 22:24:29 +0000987
Greg Claytonc4103b32011-05-08 04:53:50 +0000988 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Clayton71337622011-02-24 22:24:29 +0000989
Jason Molendaa3329782014-03-29 18:54:20 +0000990 const char * launch_event_data = launch_info.GetLaunchEventData();
991 if (launch_event_data != NULL && *launch_event_data != '\0')
992 m_gdb_comm.SendLaunchEventDataPacket (launch_event_data);
993
Chaoren Lind3173f32015-05-29 19:52:29 +0000994 if (working_dir)
Greg Clayton71337622011-02-24 22:24:29 +0000995 {
996 m_gdb_comm.SetWorkingDir (working_dir);
997 }
998
999 // Send the environment and the program + arguments after we connect
Greg Clayton982c9762011-11-03 21:22:33 +00001000 const Args &environment = launch_info.GetEnvironmentEntries();
1001 if (environment.GetArgumentCount())
Greg Clayton71337622011-02-24 22:24:29 +00001002 {
Greg Clayton982c9762011-11-03 21:22:33 +00001003 size_t num_environment_entries = environment.GetArgumentCount();
1004 for (size_t i=0; i<num_environment_entries; ++i)
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001005 {
Greg Clayton982c9762011-11-03 21:22:33 +00001006 const char *env_entry = environment.GetArgumentAtIndex(i);
1007 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Clayton71337622011-02-24 22:24:29 +00001008 break;
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001009 }
Greg Clayton71337622011-02-24 22:24:29 +00001010 }
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001011
Greg Clayton71337622011-02-24 22:24:29 +00001012 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001013 // Scope for the scoped timeout object
1014 GDBRemoteCommunication::ScopedTimeout timeout (m_gdb_comm, 10);
1015
1016 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
1017 if (arg_packet_err == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001018 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001019 std::string error_str;
1020 if (m_gdb_comm.GetLaunchSuccess (error_str))
1021 {
1022 SetID (m_gdb_comm.GetCurrentProcessID ());
1023 }
1024 else
1025 {
1026 error.SetErrorString (error_str.c_str());
1027 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001028 }
1029 else
1030 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001031 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001032 }
Greg Clayton71337622011-02-24 22:24:29 +00001033 }
Tamas Berghammer912800c2015-02-24 10:23:39 +00001034
Greg Clayton71337622011-02-24 22:24:29 +00001035 if (GetID() == LLDB_INVALID_PROCESS_ID)
1036 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001037 if (log)
1038 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton71337622011-02-24 22:24:29 +00001039 KillDebugserverProcess ();
1040 return error;
1041 }
1042
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001043 StringExtractorGDBRemote response;
1044 if (m_gdb_comm.GetStopReply(response))
Greg Clayton71337622011-02-24 22:24:29 +00001045 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001046 SetLastStopPacket(response);
Ewan Crawford78baa192015-05-13 09:18:18 +00001047 // '?' Packets must be handled differently in non-stop mode
1048 if (GetTarget().GetNonStopModeEnabled())
1049 HandleStopReplySequence();
1050
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001051 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
1052
1053 if (process_arch.IsValid())
Jason Molendac62bd7b2013-12-21 05:20:36 +00001054 {
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001055 m_target.MergeArchitecture(process_arch);
1056 }
1057 else
1058 {
1059 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
1060 if (host_arch.IsValid())
1061 m_target.MergeArchitecture(host_arch);
Carlo Kok74389122013-10-14 07:09:13 +00001062 }
1063
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001064 SetPrivateState (SetThreadStopInfo (response));
Greg Clayton71337622011-02-24 22:24:29 +00001065
1066 if (!disable_stdio)
1067 {
1068 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Claytonee95ed52011-11-17 22:14:31 +00001069 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Clayton71337622011-02-24 22:24:29 +00001070 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001071 }
1072 }
Greg Claytonc235ac72011-08-09 05:20:29 +00001073 else
1074 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001075 if (log)
1076 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytonc235ac72011-08-09 05:20:29 +00001077 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001078 }
1079 else
1080 {
1081 // Set our user ID to an invalid process ID.
1082 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton982c9762011-11-03 21:22:33 +00001083 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
1084 exe_module->GetFileSpec().GetFilename().AsCString(),
1085 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001086 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001087 return error;
Greg Clayton4957bf62010-09-30 21:49:03 +00001088
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001089}
1090
1091
1092Error
Greg Claytonb766a732011-02-04 01:58:07 +00001093ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001094{
1095 Error error;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001096 // Only connect if we have a valid connect URL
Vince Harron1b5a74e2015-01-21 22:42:49 +00001097 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton00fe87b2013-12-05 22:58:22 +00001098
1099 if (connect_url && connect_url[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001100 {
Vince Harron1b5a74e2015-01-21 22:42:49 +00001101 if (log)
1102 log->Printf("ProcessGDBRemote::%s Connecting to %s", __FUNCTION__, connect_url);
Greg Clayton00fe87b2013-12-05 22:58:22 +00001103 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
1104 if (conn_ap.get())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001105 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001106 const uint32_t max_retry_count = 50;
1107 uint32_t retry_count = 0;
1108 while (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001109 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001110 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
1111 {
1112 m_gdb_comm.SetConnection (conn_ap.release());
1113 break;
1114 }
1115 else if (error.WasInterrupted())
1116 {
1117 // If we were interrupted, don't keep retrying.
1118 break;
1119 }
1120
1121 retry_count++;
1122
1123 if (retry_count >= max_retry_count)
1124 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001125
Greg Clayton00fe87b2013-12-05 22:58:22 +00001126 usleep (100000);
1127 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001128 }
1129 }
1130
1131 if (!m_gdb_comm.IsConnected())
1132 {
1133 if (error.Success())
1134 error.SetErrorString("not connected to remote gdb server");
1135 return error;
1136 }
1137
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001138
1139 // Start the communications read thread so all incoming data can be
1140 // parsed into packets and queued as they arrive.
1141 if (GetTarget().GetNonStopModeEnabled())
1142 m_gdb_comm.StartReadThread();
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 }
Ewan Crawford78baa192015-05-13 09:18:18 +00001156
1157 // Send $QNonStop:1 packet on startup if required
1158 if (GetTarget().GetNonStopModeEnabled())
Ewan Crawfordaa7eda72015-06-24 15:14:26 +00001159 GetTarget().SetNonStopModeEnabled (m_gdb_comm.SetNonStopMode(true));
Ewan Crawford78baa192015-05-13 09:18:18 +00001160
Greg Claytonb30c50c2015-05-29 00:01:55 +00001161 m_gdb_comm.GetEchoSupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001162 m_gdb_comm.GetThreadSuffixSupported ();
Greg Clayton44633992012-04-10 03:22:03 +00001163 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001164 m_gdb_comm.GetHostInfo ();
1165 m_gdb_comm.GetVContSupported ('c');
Jim Inghamcd16df92012-07-20 21:37:13 +00001166 m_gdb_comm.GetVAttachOrWaitSupported();
Ewan Crawford78baa192015-05-13 09:18:18 +00001167
1168 // Ask the remote server for the default thread id
1169 if (GetTarget().GetNonStopModeEnabled())
1170 m_gdb_comm.GetDefaultThreadId(m_initial_tid);
1171
1172
Jim Ingham03afad82012-07-02 05:40:07 +00001173 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1174 for (size_t idx = 0; idx < num_cmds; idx++)
1175 {
1176 StringExtractorGDBRemote response;
Jim Ingham03afad82012-07-02 05:40:07 +00001177 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1178 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001179 return error;
1180}
1181
1182void
Jim Inghambb006ce2014-08-02 00:33:35 +00001183ProcessGDBRemote::DidLaunchOrAttach (ArchSpec& process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001184{
Greg Clayton5160ce52013-03-27 23:08:40 +00001185 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001186 if (log)
1187 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton93d3c8332011-02-16 04:46:07 +00001188 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001189 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001190 BuildDynamicRegisterInfo (false);
Greg Clayton3af9ea52010-11-18 05:57:03 +00001191
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001192 // See if the GDB server supports the qHostInfo information
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001193
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001194
1195 // See if the GDB server supports the qProcessInfo packet, if so
1196 // prefer that over the Host information as it will be more specific
1197 // to our process.
1198
Todd Fiala75f47c32014-10-11 21:42:09 +00001199 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1200 if (remote_process_arch.IsValid())
1201 {
1202 process_arch = remote_process_arch;
1203 if (log)
1204 log->Printf ("ProcessGDBRemote::%s gdb-remote had process architecture, using %s %s",
1205 __FUNCTION__,
1206 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1207 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1208 }
Jim Inghambb006ce2014-08-02 00:33:35 +00001209 else
Todd Fiala75f47c32014-10-11 21:42:09 +00001210 {
Jim Inghambb006ce2014-08-02 00:33:35 +00001211 process_arch = m_gdb_comm.GetHostArchitecture();
Todd Fiala75f47c32014-10-11 21:42:09 +00001212 if (log)
1213 log->Printf ("ProcessGDBRemote::%s gdb-remote did not have process architecture, using gdb-remote host architecture %s %s",
1214 __FUNCTION__,
1215 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1216 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1217 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001218
Jim Inghambb006ce2014-08-02 00:33:35 +00001219 if (process_arch.IsValid())
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001220 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001221 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Greg Claytond314e812011-03-23 00:09:55 +00001222 if (target_arch.IsValid())
1223 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001224 if (log)
1225 log->Printf ("ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1226 __FUNCTION__,
1227 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1228 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
1229
1230 // If the remote host is ARM and we have apple as the vendor, then
Greg Claytond314e812011-03-23 00:09:55 +00001231 // ARM executables and shared libraries can have mixed ARM architectures.
1232 // You can have an armv6 executable, and if the host is armv7, then the
1233 // system will load the best possible architecture for all shared libraries
1234 // it has, so we really need to take the remote host architecture as our
1235 // defacto architecture in this case.
1236
Jim Inghambb006ce2014-08-02 00:33:35 +00001237 if (process_arch.GetMachine() == llvm::Triple::arm &&
1238 process_arch.GetTriple().getVendor() == llvm::Triple::Apple)
Greg Claytond314e812011-03-23 00:09:55 +00001239 {
Jason Molenda921c01b2014-08-03 21:42:52 +00001240 GetTarget().SetArchitecture (process_arch);
Todd Fiala75f47c32014-10-11 21:42:09 +00001241 if (log)
1242 log->Printf ("ProcessGDBRemote::%s remote process is ARM/Apple, setting target arch to %s %s",
1243 __FUNCTION__,
1244 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1245 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001246 }
1247 else
1248 {
1249 // Fill in what is missing in the triple
Jim Inghambb006ce2014-08-02 00:33:35 +00001250 const llvm::Triple &remote_triple = process_arch.GetTriple();
Tamas Berghammere724af12015-03-13 10:32:37 +00001251 llvm::Triple new_target_triple = target_arch.GetTriple();
1252 if (new_target_triple.getVendorName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001253 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001254 new_target_triple.setVendor (remote_triple.getVendor());
Greg Claytond314e812011-03-23 00:09:55 +00001255
Tamas Berghammere724af12015-03-13 10:32:37 +00001256 if (new_target_triple.getOSName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001257 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001258 new_target_triple.setOS (remote_triple.getOS());
Greg Claytond314e812011-03-23 00:09:55 +00001259
Tamas Berghammere724af12015-03-13 10:32:37 +00001260 if (new_target_triple.getEnvironmentName().size() == 0)
1261 new_target_triple.setEnvironment (remote_triple.getEnvironment());
Greg Clayton70b57652011-05-15 01:25:55 +00001262 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001263
Tamas Berghammere724af12015-03-13 10:32:37 +00001264 ArchSpec new_target_arch = target_arch;
1265 new_target_arch.SetTriple(new_target_triple);
1266 GetTarget().SetArchitecture(new_target_arch);
1267 }
Greg Claytond314e812011-03-23 00:09:55 +00001268 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001269
1270 if (log)
1271 log->Printf ("ProcessGDBRemote::%s final target arch after adjustments for remote architecture: %s %s",
1272 __FUNCTION__,
1273 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1274 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001275 }
1276 else
1277 {
1278 // The target doesn't have a valid architecture yet, set it from
1279 // the architecture we got from the remote GDB server
Jason Molenda921c01b2014-08-03 21:42:52 +00001280 GetTarget().SetArchitecture (process_arch);
Greg Claytond314e812011-03-23 00:09:55 +00001281 }
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001282 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001283 }
1284}
1285
1286void
1287ProcessGDBRemote::DidLaunch ()
1288{
Jim Inghambb006ce2014-08-02 00:33:35 +00001289 ArchSpec process_arch;
1290 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001291}
1292
1293Error
Han Ming Ong84647042012-02-25 01:07:38 +00001294ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1295{
Todd Fiala75f47c32014-10-11 21:42:09 +00001296 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001297 Error error;
Todd Fiala75f47c32014-10-11 21:42:09 +00001298
1299 if (log)
1300 log->Printf ("ProcessGDBRemote::%s()", __FUNCTION__);
1301
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001302 // Clear out and clean up from any current state
1303 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001304 if (attach_pid != LLDB_INVALID_PROCESS_ID)
1305 {
Greg Clayton71337622011-02-24 22:24:29 +00001306 // Make sure we aren't already connected?
1307 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001308 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001309 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001310
1311 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001312 {
Greg Clayton71337622011-02-24 22:24:29 +00001313 const char *error_string = error.AsCString();
1314 if (error_string == NULL)
1315 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1316
1317 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001318 }
Greg Clayton71337622011-02-24 22:24:29 +00001319 }
1320
1321 if (error.Success())
1322 {
Jim Ingham106d0282014-06-25 02:32:56 +00001323 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
Todd Fiala75f47c32014-10-11 21:42:09 +00001324
Greg Clayton71337622011-02-24 22:24:29 +00001325 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001326 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Greg Clayton3b608422011-11-19 02:11:30 +00001327 SetID (attach_pid);
Greg Clayton71337622011-02-24 22:24:29 +00001328 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001329 }
1330 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001331
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001332 return error;
1333}
1334
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001335Error
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001336ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001337{
1338 Error error;
1339 // Clear out and clean up from any current state
1340 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001341
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001342 if (process_name && process_name[0])
1343 {
Greg Clayton71337622011-02-24 22:24:29 +00001344 // Make sure we aren't already connected?
1345 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001346 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001347 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001348
Greg Clayton71337622011-02-24 22:24:29 +00001349 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001350 {
Greg Clayton71337622011-02-24 22:24:29 +00001351 const char *error_string = error.AsCString();
1352 if (error_string == NULL)
1353 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001354
Greg Clayton71337622011-02-24 22:24:29 +00001355 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001356 }
Greg Clayton71337622011-02-24 22:24:29 +00001357 }
1358
1359 if (error.Success())
1360 {
1361 StreamString packet;
1362
Jim Ingham106d0282014-06-25 02:32:56 +00001363 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1364
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001365 if (attach_info.GetWaitForLaunch())
Jim Inghamcd16df92012-07-20 21:37:13 +00001366 {
1367 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1368 {
1369 packet.PutCString ("vAttachWait");
1370 }
1371 else
1372 {
1373 if (attach_info.GetIgnoreExisting())
1374 packet.PutCString("vAttachWait");
1375 else
1376 packet.PutCString ("vAttachOrWait");
1377 }
1378 }
Greg Clayton71337622011-02-24 22:24:29 +00001379 else
1380 packet.PutCString("vAttachName");
1381 packet.PutChar(';');
1382 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1383
1384 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1385
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001386 }
1387 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001388 return error;
1389}
1390
Greg Clayton5df78fa2015-05-23 03:54:53 +00001391void
1392ProcessGDBRemote::DidExit ()
Greg Claytonfbb76342013-11-20 21:07:01 +00001393{
Greg Clayton5df78fa2015-05-23 03:54:53 +00001394 // When we exit, disconnect from the GDB server communications
Greg Claytonfbb76342013-11-20 21:07:01 +00001395 m_gdb_comm.Disconnect();
Greg Claytonfbb76342013-11-20 21:07:01 +00001396}
1397
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001398void
Jim Inghambb006ce2014-08-02 00:33:35 +00001399ProcessGDBRemote::DidAttach (ArchSpec &process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001400{
Jim Inghambb006ce2014-08-02 00:33:35 +00001401 // If you can figure out what the architecture is, fill it in here.
1402 process_arch.Clear();
1403 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001404}
1405
Greg Clayton90ba8112012-12-05 00:16:59 +00001406
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001407Error
1408ProcessGDBRemote::WillResume ()
1409{
Greg Clayton71fc2a32011-02-12 06:28:37 +00001410 m_continue_c_tids.clear();
1411 m_continue_C_tids.clear();
1412 m_continue_s_tids.clear();
1413 m_continue_S_tids.clear();
Greg Clayton2e309072015-07-17 23:42:28 +00001414 m_jstopinfo_sp.reset();
1415 m_jthreadsinfo_sp.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001416 return Error();
1417}
1418
1419Error
1420ProcessGDBRemote::DoResume ()
1421{
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001422 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001423 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001424 if (log)
1425 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytone5219662010-12-03 06:02:24 +00001426
1427 Listener listener ("gdb-remote.resume-packet-sent");
1428 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1429 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00001430 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1431
Greg Claytond1d06e42013-04-20 00:27:58 +00001432 const size_t num_threads = GetThreadList().GetSize();
1433
Greg Clayton71fc2a32011-02-12 06:28:37 +00001434 StreamString continue_packet;
1435 bool continue_packet_error = false;
1436 if (m_gdb_comm.HasAnyVContSupport ())
1437 {
Ewan Crawford78baa192015-05-13 09:18:18 +00001438 if (!GetTarget().GetNonStopModeEnabled() &&
1439 (m_continue_c_tids.size() == num_threads ||
Greg Claytone98008c2014-02-13 23:34:38 +00001440 (m_continue_c_tids.empty() &&
1441 m_continue_C_tids.empty() &&
1442 m_continue_s_tids.empty() &&
Ewan Crawford78baa192015-05-13 09:18:18 +00001443 m_continue_S_tids.empty())))
Greg Clayton71fc2a32011-02-12 06:28:37 +00001444 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001445 // All threads are continuing, just send a "c" packet
1446 continue_packet.PutCString ("c");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001447 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001448 else
1449 {
1450 continue_packet.PutCString ("vCont");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001451
Greg Claytond1d06e42013-04-20 00:27:58 +00001452 if (!m_continue_c_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001453 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001454 if (m_gdb_comm.GetVContSupported ('c'))
1455 {
1456 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)
1457 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1458 }
1459 else
1460 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001461 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001462
1463 if (!continue_packet_error && !m_continue_C_tids.empty())
1464 {
1465 if (m_gdb_comm.GetVContSupported ('C'))
1466 {
1467 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)
1468 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1469 }
1470 else
1471 continue_packet_error = true;
1472 }
Greg Claytone5219662010-12-03 06:02:24 +00001473
Greg Claytond1d06e42013-04-20 00:27:58 +00001474 if (!continue_packet_error && !m_continue_s_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001475 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001476 if (m_gdb_comm.GetVContSupported ('s'))
1477 {
1478 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)
1479 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1480 }
1481 else
1482 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001483 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001484
1485 if (!continue_packet_error && !m_continue_S_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001486 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001487 if (m_gdb_comm.GetVContSupported ('S'))
1488 {
1489 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)
1490 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1491 }
1492 else
1493 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001494 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001495
1496 if (continue_packet_error)
1497 continue_packet.GetString().clear();
Greg Clayton71fc2a32011-02-12 06:28:37 +00001498 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001499 }
1500 else
1501 continue_packet_error = true;
1502
1503 if (continue_packet_error)
1504 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001505 // Either no vCont support, or we tried to use part of the vCont
1506 // packet that wasn't supported by the remote GDB server.
1507 // We need to try and make a simple packet that can do our continue
Greg Clayton71fc2a32011-02-12 06:28:37 +00001508 const size_t num_continue_c_tids = m_continue_c_tids.size();
1509 const size_t num_continue_C_tids = m_continue_C_tids.size();
1510 const size_t num_continue_s_tids = m_continue_s_tids.size();
1511 const size_t num_continue_S_tids = m_continue_S_tids.size();
1512 if (num_continue_c_tids > 0)
1513 {
1514 if (num_continue_c_tids == num_threads)
1515 {
1516 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001517 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001518 continue_packet.PutChar ('c');
1519 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001520 }
1521 else if (num_continue_c_tids == 1 &&
1522 num_continue_C_tids == 0 &&
1523 num_continue_s_tids == 0 &&
1524 num_continue_S_tids == 0 )
1525 {
1526 // Only one thread is continuing
Greg Clayton8b82f082011-04-12 05:54:46 +00001527 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001528 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001529 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001530 }
1531 }
1532
Greg Clayton0c74e782011-06-24 03:21:43 +00001533 if (continue_packet_error && num_continue_C_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001534 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001535 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1536 num_continue_C_tids > 0 &&
1537 num_continue_s_tids == 0 &&
1538 num_continue_S_tids == 0 )
Greg Clayton71fc2a32011-02-12 06:28:37 +00001539 {
1540 const int continue_signo = m_continue_C_tids.front().second;
Greg Clayton0c74e782011-06-24 03:21:43 +00001541 // Only one thread is continuing
Greg Clayton71fc2a32011-02-12 06:28:37 +00001542 if (num_continue_C_tids > 1)
1543 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001544 // More that one thread with a signal, yet we don't have
1545 // vCont support and we are being asked to resume each
1546 // thread with a signal, we need to make sure they are
1547 // all the same signal, or we can't issue the continue
1548 // accurately with the current support...
1549 if (num_continue_C_tids > 1)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001550 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001551 continue_packet_error = false;
1552 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1553 {
1554 if (m_continue_C_tids[i].second != continue_signo)
1555 continue_packet_error = true;
1556 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001557 }
Greg Clayton0c74e782011-06-24 03:21:43 +00001558 if (!continue_packet_error)
1559 m_gdb_comm.SetCurrentThreadForRun (-1);
1560 }
1561 else
1562 {
1563 // Set the continue thread ID
1564 continue_packet_error = false;
1565 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001566 }
1567 if (!continue_packet_error)
1568 {
1569 // Add threads continuing with the same signo...
Greg Clayton71fc2a32011-02-12 06:28:37 +00001570 continue_packet.Printf("C%2.2x", continue_signo);
1571 }
1572 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001573 }
1574
Greg Clayton0c74e782011-06-24 03:21:43 +00001575 if (continue_packet_error && num_continue_s_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001576 {
1577 if (num_continue_s_tids == num_threads)
1578 {
1579 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001580 m_gdb_comm.SetCurrentThreadForRun (-1);
Ewan Crawford76df2882015-06-23 12:32:06 +00001581
1582 // If in Non-Stop-Mode use vCont when stepping
1583 if (GetTarget().GetNonStopModeEnabled())
1584 {
1585 if (m_gdb_comm.GetVContSupported('s'))
1586 continue_packet.PutCString("vCont;s");
1587 else
1588 continue_packet.PutChar('s');
1589 }
1590 else
1591 continue_packet.PutChar('s');
1592
Greg Clayton0c74e782011-06-24 03:21:43 +00001593 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001594 }
1595 else if (num_continue_c_tids == 0 &&
1596 num_continue_C_tids == 0 &&
1597 num_continue_s_tids == 1 &&
1598 num_continue_S_tids == 0 )
1599 {
1600 // Only one thread is stepping
Greg Clayton8b82f082011-04-12 05:54:46 +00001601 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001602 continue_packet.PutChar ('s');
Greg Clayton0c74e782011-06-24 03:21:43 +00001603 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001604 }
1605 }
1606
1607 if (!continue_packet_error && num_continue_S_tids > 0)
1608 {
1609 if (num_continue_S_tids == num_threads)
1610 {
1611 const int step_signo = m_continue_S_tids.front().second;
1612 // Are all threads trying to step with the same signal?
Greg Clayton0c74e782011-06-24 03:21:43 +00001613 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001614 if (num_continue_S_tids > 1)
1615 {
1616 for (size_t i=1; i<num_threads; ++i)
1617 {
1618 if (m_continue_S_tids[i].second != step_signo)
1619 continue_packet_error = true;
1620 }
1621 }
1622 if (!continue_packet_error)
1623 {
1624 // Add threads stepping with the same signo...
Greg Clayton8b82f082011-04-12 05:54:46 +00001625 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001626 continue_packet.Printf("S%2.2x", step_signo);
1627 }
1628 }
1629 else if (num_continue_c_tids == 0 &&
1630 num_continue_C_tids == 0 &&
1631 num_continue_s_tids == 0 &&
1632 num_continue_S_tids == 1 )
1633 {
1634 // Only one thread is stepping with signal
Greg Clayton8b82f082011-04-12 05:54:46 +00001635 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001636 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Clayton0c74e782011-06-24 03:21:43 +00001637 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001638 }
1639 }
1640 }
1641
1642 if (continue_packet_error)
1643 {
1644 error.SetErrorString ("can't make continue packet for this resume");
1645 }
1646 else
1647 {
1648 EventSP event_sp;
1649 TimeValue timeout;
1650 timeout = TimeValue::Now();
1651 timeout.OffsetWithSeconds (5);
Zachary Turneracee96a2014-09-23 18:32:09 +00001652 if (!m_async_thread.IsJoinable())
Jim Inghamb1e2e842012-04-12 18:49:31 +00001653 {
1654 error.SetErrorString ("Trying to resume but the async thread is dead.");
1655 if (log)
1656 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1657 return error;
1658 }
1659
Greg Clayton71fc2a32011-02-12 06:28:37 +00001660 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1661
1662 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Inghamb1e2e842012-04-12 18:49:31 +00001663 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001664 error.SetErrorString("Resume timed out.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00001665 if (log)
1666 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1667 }
1668 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1669 {
1670 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1671 if (log)
1672 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1673 return error;
1674 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001675 }
Greg Claytone5219662010-12-03 06:02:24 +00001676 }
1677
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001678 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001679}
1680
Greg Clayton9e920902012-04-10 02:25:43 +00001681void
Ewan Crawford78baa192015-05-13 09:18:18 +00001682ProcessGDBRemote::HandleStopReplySequence ()
1683{
1684 while(true)
1685 {
1686 // Send vStopped
1687 StringExtractorGDBRemote response;
1688 m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false);
1689
1690 // OK represents end of signal list
1691 if (response.IsOKResponse())
1692 break;
1693
1694 // If not OK or a normal packet we have a problem
1695 if (!response.IsNormalResponse())
1696 break;
1697
1698 SetLastStopPacket(response);
1699 }
1700}
1701
1702void
Greg Clayton9e920902012-04-10 02:25:43 +00001703ProcessGDBRemote::ClearThreadIDList ()
1704{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001705 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001706 m_thread_ids.clear();
1707}
1708
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001709size_t
1710ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue (std::string &value)
1711{
1712 m_thread_ids.clear();
1713 size_t comma_pos;
1714 lldb::tid_t tid;
1715 while ((comma_pos = value.find(',')) != std::string::npos)
1716 {
1717 value[comma_pos] = '\0';
1718 // thread in big endian hex
1719 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1720 if (tid != LLDB_INVALID_THREAD_ID)
1721 m_thread_ids.push_back (tid);
1722 value.erase(0, comma_pos + 1);
1723 }
1724 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1725 if (tid != LLDB_INVALID_THREAD_ID)
1726 m_thread_ids.push_back (tid);
1727 return m_thread_ids.size();
1728}
1729
Greg Clayton9e920902012-04-10 02:25:43 +00001730bool
1731ProcessGDBRemote::UpdateThreadIDList ()
1732{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001733 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001734
Greg Clayton2e309072015-07-17 23:42:28 +00001735 if (m_jthreadsinfo_sp)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001736 {
1737 // If we have the JSON threads info, we can get the thread list from that
Greg Clayton2e309072015-07-17 23:42:28 +00001738 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001739 if (thread_infos && thread_infos->GetSize() > 0)
1740 {
1741 m_thread_ids.clear();
1742 thread_infos->ForEach([this](StructuredData::Object* object) -> bool {
1743 StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1744 if (thread_dict)
1745 {
1746 // Set the thread stop info from the JSON dictionary
1747 SetThreadStopInfo (thread_dict);
1748 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1749 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1750 m_thread_ids.push_back(tid);
1751 }
1752 return true; // Keep iterating through all thread_info objects
1753 });
1754 }
1755 if (!m_thread_ids.empty())
1756 return true;
1757 }
1758 else
1759 {
1760 // See if we can get the thread IDs from the current stop reply packets
1761 // that might contain a "threads" key/value pair
1762
1763 // Lock the thread stack while we access it
1764 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
1765 // Get the number of stop packets on the stack
1766 int nItems = m_stop_packet_stack.size();
1767 // Iterate over them
1768 for (int i = 0; i < nItems; i++)
1769 {
1770 // Get the thread stop info
1771 StringExtractorGDBRemote &stop_info = m_stop_packet_stack[i];
1772 const std::string &stop_info_str = stop_info.GetStringRef();
1773 const size_t threads_pos = stop_info_str.find(";threads:");
1774 if (threads_pos != std::string::npos)
1775 {
1776 const size_t start = threads_pos + strlen(";threads:");
1777 const size_t end = stop_info_str.find(';', start);
1778 if (end != std::string::npos)
1779 {
1780 std::string value = stop_info_str.substr(start, end - start);
1781 if (UpdateThreadIDsFromStopReplyThreadsValue(value))
1782 return true;
1783 }
1784 }
1785 }
1786 }
1787
Greg Clayton9e920902012-04-10 02:25:43 +00001788 bool sequence_mutex_unavailable = false;
1789 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1790 if (sequence_mutex_unavailable)
1791 {
Greg Clayton9e920902012-04-10 02:25:43 +00001792 return false; // We just didn't get the list
1793 }
1794 return true;
1795}
1796
Greg Clayton9fc13552012-04-10 00:18:59 +00001797bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001798ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001799{
1800 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +00001801 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Clayton73b472d2010-10-27 03:32:59 +00001802 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +00001803 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton9e920902012-04-10 02:25:43 +00001804
1805 size_t num_thread_ids = m_thread_ids.size();
1806 // The "m_thread_ids" thread ID list should always be updated after each stop
1807 // reply packet, but in case it isn't, update it here.
1808 if (num_thread_ids == 0)
1809 {
1810 if (!UpdateThreadIDList ())
1811 return false;
1812 num_thread_ids = m_thread_ids.size();
1813 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001814
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001815 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001816 if (num_thread_ids > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001817 {
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001818 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001819 {
Greg Clayton9e920902012-04-10 02:25:43 +00001820 tid_t tid = m_thread_ids[i];
Greg Clayton160c9d82013-05-01 21:54:04 +00001821 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001822 if (!thread_sp)
Jim Inghamdee1bc92013-06-22 00:27:45 +00001823 {
Jim Ingham4f465cf2012-10-10 18:32:14 +00001824 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001825 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1826 log->Printf(
1827 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001828 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001829 thread_sp->GetID());
1830 }
1831 else
1832 {
1833 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1834 log->Printf(
1835 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001836 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001837 thread_sp->GetID());
1838 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001839 new_thread_list.AddThread(thread_sp);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001840 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001841 }
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001842
1843 // Whatever that is left in old_thread_list_copy are not
1844 // present in new_thread_list. Remove non-existent threads from internal id table.
1845 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1846 for (size_t i=0; i<old_num_thread_ids; i++)
1847 {
1848 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1849 if (old_thread_sp)
1850 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001851 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001852 m_thread_id_to_index_id_map.erase(old_thread_id);
1853 }
1854 }
1855
Greg Clayton9fc13552012-04-10 00:18:59 +00001856 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001857}
1858
Greg Clayton2e309072015-07-17 23:42:28 +00001859
Greg Clayton358cf1e2015-06-25 21:46:34 +00001860bool
Greg Clayton2e309072015-07-17 23:42:28 +00001861ProcessGDBRemote::GetThreadStopInfoFromJSON (ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001862{
1863 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet
Greg Clayton2e309072015-07-17 23:42:28 +00001864 if (thread_infos_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001865 {
Greg Clayton2e309072015-07-17 23:42:28 +00001866 StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
Greg Clayton358cf1e2015-06-25 21:46:34 +00001867 if (thread_infos)
1868 {
1869 lldb::tid_t tid;
1870 const size_t n = thread_infos->GetSize();
1871 for (size_t i=0; i<n; ++i)
1872 {
1873 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1874 if (thread_dict)
1875 {
1876 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid, LLDB_INVALID_THREAD_ID))
1877 {
1878 if (tid == thread->GetID())
Greg Clayton2e309072015-07-17 23:42:28 +00001879 return (bool)SetThreadStopInfo(thread_dict);
Greg Clayton358cf1e2015-06-25 21:46:34 +00001880 }
1881 }
1882 }
1883 }
1884 }
Greg Clayton2e309072015-07-17 23:42:28 +00001885 return false;
1886}
1887
1888bool
1889ProcessGDBRemote::CalculateThreadStopInfo (ThreadGDBRemote *thread)
1890{
1891 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet
1892 if (GetThreadStopInfoFromJSON (thread, m_jthreadsinfo_sp))
1893 return true;
1894
1895 // See if we got thread stop info for any threads valid stop info reasons threads
1896 // via the "jstopinfo" packet stop reply packet key/value pair?
1897 if (m_jstopinfo_sp)
1898 {
1899 // If we have "jstopinfo" then we have stop descriptions for all threads
1900 // that have stop reasons, and if there is no entry for a thread, then
1901 // it has no stop reason.
1902 thread->GetRegisterContext()->InvalidateIfNeeded(true);
1903 if (!GetThreadStopInfoFromJSON (thread, m_jstopinfo_sp))
1904 {
1905 thread->SetStopInfo (StopInfoSP());
1906 }
1907 return true;
1908 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00001909
1910 // Fall back to using the qThreadStopInfo packet
1911 StringExtractorGDBRemote stop_packet;
1912 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1913 return SetThreadStopInfo (stop_packet) == eStateStopped;
1914 return false;
1915}
1916
1917
1918ThreadSP
1919ProcessGDBRemote::SetThreadStopInfo (lldb::tid_t tid,
1920 ExpeditedRegisterMap &expedited_register_map,
1921 uint8_t signo,
1922 const std::string &thread_name,
1923 const std::string &reason,
1924 const std::string &description,
1925 uint32_t exc_type,
1926 const std::vector<addr_t> &exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001927 addr_t thread_dispatch_qaddr,
1928 bool queue_vars_valid, // Set to true if queue_name, queue_kind and queue_serial are valid
1929 std::string &queue_name,
1930 QueueKind queue_kind,
1931 uint64_t queue_serial)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001932{
1933 ThreadSP thread_sp;
1934 if (tid != LLDB_INVALID_THREAD_ID)
1935 {
1936 // Scope for "locker" below
1937 {
1938 // m_thread_list_real does have its own mutex, but we need to
1939 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1940 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1941 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1942 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1943
1944 if (!thread_sp)
1945 {
1946 // Create the thread if we need to
1947 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1948 m_thread_list_real.AddThread(thread_sp);
1949 }
1950 }
1951
1952 if (thread_sp)
1953 {
1954 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1955 gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001956
Greg Clayton358cf1e2015-06-25 21:46:34 +00001957 for (const auto &pair : expedited_register_map)
1958 {
1959 StringExtractor reg_value_extractor;
1960 reg_value_extractor.GetStringRef() = pair.second;
1961 gdb_thread->PrivateSetRegisterValue (pair.first, reg_value_extractor);
1962 }
1963
Greg Clayton358cf1e2015-06-25 21:46:34 +00001964 thread_sp->SetName (thread_name.empty() ? NULL : thread_name.c_str());
1965
1966 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001967 // Check if the GDB server was able to provide the queue name, kind and serial number
1968 if (queue_vars_valid)
1969 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind, queue_serial);
1970 else
1971 gdb_thread->ClearQueueInfo();
1972
Greg Clayton2e309072015-07-17 23:42:28 +00001973 // Make sure we update our thread stop reason just once
1974 if (!thread_sp->StopInfoIsUpToDate())
Greg Clayton358cf1e2015-06-25 21:46:34 +00001975 {
Greg Clayton2e309072015-07-17 23:42:28 +00001976 thread_sp->SetStopInfo (StopInfoSP());
Greg Clayton358cf1e2015-06-25 21:46:34 +00001977
Greg Clayton2e309072015-07-17 23:42:28 +00001978 if (exc_type != 0)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001979 {
Greg Clayton2e309072015-07-17 23:42:28 +00001980 const size_t exc_data_size = exc_data.size();
1981
1982 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1983 exc_type,
1984 exc_data_size,
1985 exc_data_size >= 1 ? exc_data[0] : 0,
1986 exc_data_size >= 2 ? exc_data[1] : 0,
1987 exc_data_size >= 3 ? exc_data[2] : 0));
Greg Clayton358cf1e2015-06-25 21:46:34 +00001988 }
Greg Clayton2e309072015-07-17 23:42:28 +00001989 else
Greg Clayton358cf1e2015-06-25 21:46:34 +00001990 {
Greg Clayton2e309072015-07-17 23:42:28 +00001991 bool handled = false;
1992 bool did_exec = false;
1993 if (!reason.empty())
Greg Clayton358cf1e2015-06-25 21:46:34 +00001994 {
Greg Clayton2e309072015-07-17 23:42:28 +00001995 if (reason.compare("trace") == 0)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001996 {
Greg Clayton2e309072015-07-17 23:42:28 +00001997 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1998 handled = true;
1999 }
2000 else if (reason.compare("breakpoint") == 0)
2001 {
2002 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
2003 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2004 if (bp_site_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00002005 {
Greg Clayton2e309072015-07-17 23:42:28 +00002006 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2007 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2008 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2009 handled = true;
2010 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2011 {
2012 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2013 }
2014 else
2015 {
2016 StopInfoSP invalid_stop_info_sp;
2017 thread_sp->SetStopInfo (invalid_stop_info_sp);
2018 }
2019 }
2020 }
2021 else if (reason.compare("trap") == 0)
2022 {
2023 // Let the trap just use the standard signal stop reason below...
2024 }
2025 else if (reason.compare("watchpoint") == 0)
2026 {
2027 StringExtractor desc_extractor(description.c_str());
2028 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
2029 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
Jaydeep Patil83143502015-08-13 03:44:09 +00002030 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
Greg Clayton2e309072015-07-17 23:42:28 +00002031 watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
2032 if (wp_addr != LLDB_INVALID_ADDRESS)
2033 {
2034 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2035 if (wp_sp)
2036 {
2037 wp_sp->SetHardwareIndex(wp_index);
2038 watch_id = wp_sp->GetID();
2039 }
2040 }
2041 if (watch_id == LLDB_INVALID_WATCH_ID)
2042 {
2043 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_WATCHPOINTS));
2044 if (log) log->Printf ("failed to find watchpoint");
2045 }
Jaydeep Patil83143502015-08-13 03:44:09 +00002046 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id, wp_hit_addr));
Greg Clayton2e309072015-07-17 23:42:28 +00002047 handled = true;
2048 }
2049 else if (reason.compare("exception") == 0)
2050 {
2051 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
2052 handled = true;
2053 }
2054 else if (reason.compare("exec") == 0)
2055 {
2056 did_exec = true;
2057 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
2058 handled = true;
2059 }
2060 }
2061
2062 if (!handled && signo && did_exec == false)
2063 {
2064 if (signo == SIGTRAP)
2065 {
2066 // Currently we are going to assume SIGTRAP means we are either
2067 // hitting a breakpoint or hardware single stepping.
2068 handled = true;
2069 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
2070 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2071
2072 if (bp_site_sp)
2073 {
2074 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2075 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2076 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2077 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2078 {
2079 if(m_breakpoint_pc_offset != 0)
2080 thread_sp->GetRegisterContext()->SetPC(pc);
2081 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2082 }
2083 else
2084 {
2085 StopInfoSP invalid_stop_info_sp;
2086 thread_sp->SetStopInfo (invalid_stop_info_sp);
2087 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002088 }
2089 else
2090 {
Greg Clayton2e309072015-07-17 23:42:28 +00002091 // If we were stepping then assume the stop was the result of the trace. If we were
2092 // not stepping then report the SIGTRAP.
2093 // FIXME: We are still missing the case where we single step over a trap instruction.
2094 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
2095 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
2096 else
2097 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo, description.c_str()));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002098 }
2099 }
Greg Clayton2e309072015-07-17 23:42:28 +00002100 if (!handled)
2101 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo, description.c_str()));
2102 }
2103
2104 if (!description.empty())
2105 {
2106 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
2107 if (stop_info_sp)
2108 {
2109 const char *stop_info_desc = stop_info_sp->GetDescription();
2110 if (!stop_info_desc || !stop_info_desc[0])
2111 stop_info_sp->SetDescription (description.c_str());
2112 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002113 else
2114 {
Greg Clayton2e309072015-07-17 23:42:28 +00002115 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002116 }
2117 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002118 }
2119 }
2120 }
2121 }
2122 return thread_sp;
2123}
2124
Greg Clayton2e309072015-07-17 23:42:28 +00002125lldb::ThreadSP
Greg Clayton358cf1e2015-06-25 21:46:34 +00002126ProcessGDBRemote::SetThreadStopInfo (StructuredData::Dictionary *thread_dict)
2127{
2128 static ConstString g_key_tid("tid");
2129 static ConstString g_key_name("name");
2130 static ConstString g_key_reason("reason");
2131 static ConstString g_key_metype("metype");
2132 static ConstString g_key_medata("medata");
2133 static ConstString g_key_qaddr("qaddr");
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002134 static ConstString g_key_queue_name("qname");
2135 static ConstString g_key_queue_kind("qkind");
2136 static ConstString g_key_queue_serial("qserial");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002137 static ConstString g_key_registers("registers");
2138 static ConstString g_key_memory("memory");
2139 static ConstString g_key_address("address");
2140 static ConstString g_key_bytes("bytes");
2141 static ConstString g_key_description("description");
Pavel Labath4a4bb122015-07-16 14:14:35 +00002142 static ConstString g_key_signal("signal");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002143
2144 // Stop with signal and thread info
2145 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2146 uint8_t signo = 0;
2147 std::string value;
2148 std::string thread_name;
2149 std::string reason;
2150 std::string description;
2151 uint32_t exc_type = 0;
2152 std::vector<addr_t> exc_data;
2153 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2154 ExpeditedRegisterMap expedited_register_map;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002155 bool queue_vars_valid = false;
2156 std::string queue_name;
2157 QueueKind queue_kind = eQueueKindUnknown;
2158 uint64_t queue_serial = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002159 // Iterate through all of the thread dictionary key/value pairs from the structured data dictionary
2160
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002161 thread_dict->ForEach([this,
2162 &tid,
2163 &expedited_register_map,
2164 &thread_name,
2165 &signo,
2166 &reason,
2167 &description,
2168 &exc_type,
2169 &exc_data,
2170 &thread_dispatch_qaddr,
2171 &queue_vars_valid,
2172 &queue_name,
2173 &queue_kind,
2174 &queue_serial]
2175 (ConstString key, StructuredData::Object* object) -> bool
Greg Clayton358cf1e2015-06-25 21:46:34 +00002176 {
2177 if (key == g_key_tid)
2178 {
2179 // thread in big endian hex
2180 tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
2181 }
2182 else if (key == g_key_metype)
2183 {
2184 // exception type in big endian hex
2185 exc_type = object->GetIntegerValue(0);
2186 }
2187 else if (key == g_key_medata)
2188 {
2189 // exception data in big endian hex
2190 StructuredData::Array *array = object->GetAsArray();
2191 if (array)
2192 {
2193 array->ForEach([&exc_data](StructuredData::Object* object) -> bool {
2194 exc_data.push_back(object->GetIntegerValue());
2195 return true; // Keep iterating through all array items
2196 });
2197 }
2198 }
2199 else if (key == g_key_name)
2200 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002201 thread_name = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002202 }
2203 else if (key == g_key_qaddr)
2204 {
2205 thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
2206 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002207 else if (key == g_key_queue_name)
2208 {
2209 queue_vars_valid = true;
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002210 queue_name = object->GetStringValue();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002211 }
2212 else if (key == g_key_queue_kind)
2213 {
2214 std::string queue_kind_str = object->GetStringValue();
2215 if (queue_kind_str == "serial")
2216 {
2217 queue_vars_valid = true;
2218 queue_kind = eQueueKindSerial;
2219 }
2220 else if (queue_kind_str == "concurrent")
2221 {
2222 queue_vars_valid = true;
2223 queue_kind = eQueueKindConcurrent;
2224 }
2225 }
2226 else if (key == g_key_queue_serial)
2227 {
2228 queue_serial = object->GetIntegerValue(0);
2229 if (queue_serial != 0)
2230 queue_vars_valid = true;
2231 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002232 else if (key == g_key_reason)
2233 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002234 reason = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002235 }
2236 else if (key == g_key_description)
2237 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002238 description = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002239 }
2240 else if (key == g_key_registers)
2241 {
2242 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2243
2244 if (registers_dict)
2245 {
2246 registers_dict->ForEach([&expedited_register_map](ConstString key, StructuredData::Object* object) -> bool {
2247 const uint32_t reg = StringConvert::ToUInt32 (key.GetCString(), UINT32_MAX, 10);
2248 if (reg != UINT32_MAX)
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002249 expedited_register_map[reg] = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002250 return true; // Keep iterating through all array items
2251 });
2252 }
2253 }
2254 else if (key == g_key_memory)
2255 {
2256 StructuredData::Array *array = object->GetAsArray();
2257 if (array)
2258 {
2259 array->ForEach([this](StructuredData::Object* object) -> bool {
2260 StructuredData::Dictionary *mem_cache_dict = object->GetAsDictionary();
2261 if (mem_cache_dict)
2262 {
2263 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2264 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>("address", mem_cache_addr))
2265 {
2266 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
2267 {
2268 StringExtractor bytes;
2269 if (mem_cache_dict->GetValueForKeyAsString("bytes", bytes.GetStringRef()))
2270 {
2271 bytes.SetFilePos(0);
2272
2273 const size_t byte_size = bytes.GetStringRef().size()/2;
2274 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2275 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2276 if (bytes_copied == byte_size)
2277 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2278 }
2279 }
2280 }
2281 }
2282 return true; // Keep iterating through all array items
2283 });
2284 }
2285
2286 }
Pavel Labath4a4bb122015-07-16 14:14:35 +00002287 else if (key == g_key_signal)
2288 signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002289 return true; // Keep iterating through all dictionary key/value pairs
2290 });
2291
Greg Clayton2e309072015-07-17 23:42:28 +00002292 return SetThreadStopInfo (tid,
2293 expedited_register_map,
2294 signo,
2295 thread_name,
2296 reason,
2297 description,
2298 exc_type,
2299 exc_data,
2300 thread_dispatch_qaddr,
2301 queue_vars_valid,
2302 queue_name,
2303 queue_kind,
2304 queue_serial);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002305}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002306
2307StateType
2308ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
2309{
Greg Claytondd0e5a52011-06-02 22:22:38 +00002310 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002311 const char stop_type = stop_packet.GetChar();
2312 switch (stop_type)
2313 {
2314 case 'T':
2315 case 'S':
2316 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00002317 // This is a bit of a hack, but is is required. If we did exec, we
2318 // need to clear our thread lists and also know to rebuild our dynamic
2319 // register info before we lookup and threads and populate the expedited
2320 // register values so we need to know this right away so we can cleanup
2321 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00002322 const uint32_t stop_id = GetStopID();
2323 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00002324 {
2325 // Our first stop, make sure we have a process ID, and also make
2326 // sure we know about our registers
2327 if (GetID() == LLDB_INVALID_PROCESS_ID)
2328 {
Greg Claytonc574ede2011-03-10 02:26:48 +00002329 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00002330 if (pid != LLDB_INVALID_PROCESS_ID)
2331 SetID (pid);
2332 }
2333 BuildDynamicRegisterInfo (true);
2334 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002335 // Stop with signal and thread info
Greg Clayton358cf1e2015-06-25 21:46:34 +00002336 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002337 const uint8_t signo = stop_packet.GetHexU8();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002338 std::string key;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002339 std::string value;
2340 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00002341 std::string reason;
2342 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002343 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00002344 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002345 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton0b90be12015-06-23 21:27:50 +00002346 bool queue_vars_valid = false; // says if locals below that start with "queue_" are valid
2347 std::string queue_name;
2348 QueueKind queue_kind = eQueueKindUnknown;
2349 uint64_t queue_serial = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002350 ExpeditedRegisterMap expedited_register_map;
2351 while (stop_packet.GetNameColonValue(key, value))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002352 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002353 if (key.compare("metype") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002354 {
2355 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002356 exc_type = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002357 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002358 else if (key.compare("medata") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002359 {
2360 // exception data in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002361 exc_data.push_back(StringConvert::ToUInt64 (value.c_str(), 0, 16));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002362 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002363 else if (key.compare("thread") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002364 {
2365 // thread in big endian hex
Greg Clayton358cf1e2015-06-25 21:46:34 +00002366 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002367 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002368 else if (key.compare("threads") == 0)
Greg Clayton9e920902012-04-10 02:25:43 +00002369 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002370 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00002371 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00002372 // A comma separated list of all threads in the current
2373 // process that includes the thread for this stop reply
2374 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00002375 size_t comma_pos;
2376 lldb::tid_t tid;
2377 while ((comma_pos = value.find(',')) != std::string::npos)
2378 {
2379 value[comma_pos] = '\0';
2380 // thread in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002381 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00002382 if (tid != LLDB_INVALID_THREAD_ID)
2383 m_thread_ids.push_back (tid);
2384 value.erase(0, comma_pos + 1);
Greg Clayton9e920902012-04-10 02:25:43 +00002385 }
Vince Harron5275aaa2015-01-15 20:08:35 +00002386 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00002387 if (tid != LLDB_INVALID_THREAD_ID)
2388 m_thread_ids.push_back (tid);
2389 }
Greg Clayton2e309072015-07-17 23:42:28 +00002390 else if (key.compare("jstopinfo") == 0)
Greg Claytona5801ad2015-07-15 22:59:03 +00002391 {
2392 StringExtractor json_extractor;
2393 // Swap "value" over into "name_extractor"
2394 json_extractor.GetStringRef().swap(value);
2395 // Now convert the HEX bytes into a string value
2396 json_extractor.GetHexByteString (value);
2397
2398 // This JSON contains thread IDs and thread stop info for all threads.
2399 // It doesn't contain expedited registers, memory or queue info.
Greg Clayton2e309072015-07-17 23:42:28 +00002400 m_jstopinfo_sp = StructuredData::ParseJSON (value);
Greg Claytona5801ad2015-07-15 22:59:03 +00002401 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002402 else if (key.compare("hexname") == 0)
Greg Claytonde9d0492011-01-08 03:17:57 +00002403 {
2404 StringExtractor name_extractor;
2405 // Swap "value" over into "name_extractor"
2406 name_extractor.GetStringRef().swap(value);
2407 // Now convert the HEX bytes into a string value
2408 name_extractor.GetHexByteString (value);
2409 thread_name.swap (value);
2410 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002411 else if (key.compare("name") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002412 {
2413 thread_name.swap (value);
2414 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002415 else if (key.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002416 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002417 thread_dispatch_qaddr = StringConvert::ToUInt64 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002418 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002419 else if (key.compare("qname") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002420 {
2421 queue_vars_valid = true;
2422 StringExtractor name_extractor;
2423 // Swap "value" over into "name_extractor"
2424 name_extractor.GetStringRef().swap(value);
2425 // Now convert the HEX bytes into a string value
2426 name_extractor.GetHexByteString (value);
2427 queue_name.swap (value);
2428 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002429 else if (key.compare("qkind") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002430 {
Greg Clayton0b90be12015-06-23 21:27:50 +00002431 if (value == "serial")
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002432 {
2433 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002434 queue_kind = eQueueKindSerial;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002435 }
Greg Clayton0b90be12015-06-23 21:27:50 +00002436 else if (value == "concurrent")
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002437 {
2438 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002439 queue_kind = eQueueKindConcurrent;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002440 }
Greg Clayton0b90be12015-06-23 21:27:50 +00002441 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002442 else if (key.compare("qserial") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002443 {
Greg Clayton0b90be12015-06-23 21:27:50 +00002444 queue_serial = StringConvert::ToUInt64 (value.c_str(), 0, 0);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002445 if (queue_serial != 0)
2446 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002447 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002448 else if (key.compare("reason") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002449 {
2450 reason.swap(value);
2451 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002452 else if (key.compare("description") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002453 {
2454 StringExtractor desc_extractor;
2455 // Swap "value" over into "name_extractor"
2456 desc_extractor.GetStringRef().swap(value);
2457 // Now convert the HEX bytes into a string value
Chaoren Lin28e57422015-02-03 01:51:25 +00002458 desc_extractor.GetHexByteString (value);
2459 description.swap(value);
Greg Claytona658fd22011-06-04 01:26:29 +00002460 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002461 else if (key.compare("memory") == 0)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002462 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002463 // Expedited memory. GDB servers can choose to send back expedited memory
2464 // that can populate the L1 memory cache in the process so that things like
2465 // the frame pointer backchain can be expedited. This will help stack
2466 // backtracing be more efficient by not having to send as many memory read
2467 // requests down the remote GDB server.
Chaoren Lin7a306082015-06-23 03:17:01 +00002468
Greg Clayton358cf1e2015-06-25 21:46:34 +00002469 // Key/value pair format: memory:<addr>=<bytes>;
2470 // <addr> is a number whose base will be interpreted by the prefix:
2471 // "0x[0-9a-fA-F]+" for hex
2472 // "0[0-7]+" for octal
2473 // "[1-9]+" for decimal
2474 // <bytes> is native endian ASCII hex bytes just like the register values
2475 llvm::StringRef value_ref(value);
2476 std::pair<llvm::StringRef, llvm::StringRef> pair;
2477 pair = value_ref.split('=');
2478 if (!pair.first.empty() && !pair.second.empty())
2479 {
2480 std::string addr_str(pair.first.str());
2481 const lldb::addr_t mem_cache_addr = StringConvert::ToUInt64(addr_str.c_str(), LLDB_INVALID_ADDRESS, 0);
2482 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002483 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002484 StringExtractor bytes;
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002485 bytes.GetStringRef() = pair.second.str();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002486 const size_t byte_size = bytes.GetStringRef().size()/2;
2487 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2488 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2489 if (bytes_copied == byte_size)
2490 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
Greg Clayton3e06bd92011-01-09 21:07:35 +00002491 }
2492 }
2493 }
Jaydeep Patil725666c2015-08-13 03:46:01 +00002494 else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 || key.compare("awatch") == 0)
2495 {
2496 // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2497 lldb::addr_t wp_addr = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
2498 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2499 uint32_t wp_index = LLDB_INVALID_INDEX32;
2500
2501 if (wp_sp)
2502 wp_index = wp_sp->GetHardwareIndex();
2503
2504 reason = "watchpoint";
2505 StreamString ostr;
2506 ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
2507 description = ostr.GetString().c_str();
2508 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002509 else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1]))
2510 {
2511 uint32_t reg = StringConvert::ToUInt32 (key.c_str(), UINT32_MAX, 16);
2512 if (reg != UINT32_MAX)
2513 expedited_register_map[reg] = std::move(value);
2514 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002515 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002516
Bhushan D. Attarde1e271df2015-07-24 04:06:20 +00002517 if (tid == LLDB_INVALID_THREAD_ID)
2518 {
2519 // A thread id may be invalid if the response is old style 'S' packet which does not provide the
2520 // thread information. So update the thread list and choose the first one.
2521 UpdateThreadIDList ();
2522
2523 if (!m_thread_ids.empty ())
2524 {
2525 tid = m_thread_ids.front ();
2526 }
2527 }
2528
Greg Clayton358cf1e2015-06-25 21:46:34 +00002529 ThreadSP thread_sp = SetThreadStopInfo (tid,
2530 expedited_register_map,
2531 signo,
2532 thread_name,
2533 reason,
2534 description,
2535 exc_type,
2536 exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002537 thread_dispatch_qaddr,
2538 queue_vars_valid,
2539 queue_name,
2540 queue_kind,
2541 queue_serial);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002542
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002543 return eStateStopped;
2544 }
2545 break;
2546
2547 case 'W':
Todd Fialaff6131a2014-05-19 04:57:23 +00002548 case 'X':
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002549 // process exited
2550 return eStateExited;
2551
2552 default:
2553 break;
2554 }
2555 return eStateInvalid;
2556}
2557
2558void
2559ProcessGDBRemote::RefreshStateAfterStop ()
2560{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002561 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00002562 m_thread_ids.clear();
2563 // Set the thread stop info. It might have a "threads" key whose value is
2564 // a list of all thread IDs in the current process, so m_thread_ids might
2565 // get set.
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002566
2567 // Scope for the lock
2568 {
2569 // Lock the thread stack while we access it
2570 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
2571 // Get the number of stop packets on the stack
2572 int nItems = m_stop_packet_stack.size();
2573 // Iterate over them
2574 for (int i = 0; i < nItems; i++)
2575 {
2576 // Get the thread stop info
2577 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2578 // Process thread stop info
2579 SetThreadStopInfo(stop_info);
2580 }
2581 // Clear the thread stop stack
2582 m_stop_packet_stack.clear();
2583 }
2584
Greg Clayton9e920902012-04-10 02:25:43 +00002585 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2586 if (m_thread_ids.empty())
2587 {
2588 // No, we need to fetch the thread list manually
2589 UpdateThreadIDList();
2590 }
2591
Ewan Crawford78baa192015-05-13 09:18:18 +00002592 // If we have queried for a default thread id
2593 if (m_initial_tid != LLDB_INVALID_THREAD_ID)
2594 {
2595 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2596 m_initial_tid = LLDB_INVALID_THREAD_ID;
2597 }
2598
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002599 // Let all threads recover from stopping and do any clean up based
2600 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002601 m_thread_list_real.RefreshStateAfterStop();
Greg Clayton9e920902012-04-10 02:25:43 +00002602
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002603}
2604
2605Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002606ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002607{
2608 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002609
Greg Clayton6ed95942011-01-22 07:12:45 +00002610 bool timed_out = false;
2611 Mutex::Locker locker;
Greg Clayton513c26c2011-01-29 07:10:55 +00002612
2613 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002614 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002615 // We are being asked to halt during an attach. We need to just close
2616 // our file handle and debugserver will go away, and we can be done...
2617 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00002618 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002619 else
2620 {
Greg Clayton2687cd12012-03-29 01:55:41 +00002621 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton513c26c2011-01-29 07:10:55 +00002622 {
2623 if (timed_out)
2624 error.SetErrorString("timed out sending interrupt packet");
2625 else
2626 error.SetErrorString("unknown error sending interrupt packet");
2627 }
Greg Clayton2687cd12012-03-29 01:55:41 +00002628
2629 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton513c26c2011-01-29 07:10:55 +00002630 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002631 return error;
2632}
2633
2634Error
Jim Inghamacff8952013-05-02 00:27:30 +00002635ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002636{
2637 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002638 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00002639 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00002640 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2641
Jim Inghamacff8952013-05-02 00:27:30 +00002642 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002643 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002644 {
Jim Inghamacff8952013-05-02 00:27:30 +00002645 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002646 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
2647 else
Jim Inghamacff8952013-05-02 00:27:30 +00002648 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00002649 }
Jim Inghamacff8952013-05-02 00:27:30 +00002650
2651 if (!error.Success())
2652 return error;
2653
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002654 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00002655 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002656
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002657 SetPrivateState (eStateDetached);
2658 ResumePrivateStateThread();
2659
2660 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00002661 return error;
2662}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002663
Jim Ingham43c555d2012-07-04 00:35:43 +00002664
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002665Error
2666ProcessGDBRemote::DoDestroy ()
2667{
2668 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002669 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002670 if (log)
2671 log->Printf ("ProcessGDBRemote::DoDestroy()");
2672
Jim Ingham43c555d2012-07-04 00:35:43 +00002673 // There is a bug in older iOS debugservers where they don't shut down the process
2674 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
2675 // this can cause problems with restarting. So we check to see if any of our threads are stopped
2676 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
2677 // destroy it again.
2678 //
2679 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
2680 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
2681 // the debugservers with this bug are equal. There really should be a better way to test this!
2682 //
2683 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
2684 // get called here to destroy again and we're still at a breakpoint or exception, then we should
2685 // just do the straight-forward kill.
2686 //
2687 // And of course, if we weren't able to stop the process by the time we get here, it isn't
2688 // necessary (or helpful) to do any of this.
2689
2690 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
2691 {
2692 PlatformSP platform_sp = GetTarget().GetPlatform();
2693
2694 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2695 if (platform_sp
2696 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00002697 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00002698 {
2699 if (m_destroy_tried_resuming)
2700 {
2701 if (log)
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002702 log->PutCString ("ProcessGDBRemote::DoDestroy() - Tried resuming to destroy once already, not doing it again.");
Jim Ingham43c555d2012-07-04 00:35:43 +00002703 }
2704 else
2705 {
2706 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
2707 // but we really need it to happen here and it doesn't matter if we do it twice.
2708 m_thread_list.DiscardThreadPlans();
2709 DisableAllBreakpointSites();
2710
2711 bool stop_looks_like_crash = false;
2712 ThreadList &threads = GetThreadList();
2713
2714 {
Jim Ingham45350372012-09-11 00:08:52 +00002715 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002716
2717 size_t num_threads = threads.GetSize();
2718 for (size_t i = 0; i < num_threads; i++)
2719 {
2720 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002721 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002722 StopReason reason = eStopReasonInvalid;
2723 if (stop_info_sp)
2724 reason = stop_info_sp->GetStopReason();
2725 if (reason == eStopReasonBreakpoint
2726 || reason == eStopReasonException)
2727 {
2728 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002729 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
2730 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00002731 stop_info_sp->GetDescription());
2732 stop_looks_like_crash = true;
2733 break;
2734 }
2735 }
2736 }
2737
2738 if (stop_looks_like_crash)
2739 {
2740 if (log)
2741 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
2742 m_destroy_tried_resuming = true;
2743
2744 // If we are going to run again before killing, it would be good to suspend all the threads
2745 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
2746 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
2747 // have to run the risk of letting those threads proceed a bit.
2748
2749 {
Jim Ingham45350372012-09-11 00:08:52 +00002750 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002751
2752 size_t num_threads = threads.GetSize();
2753 for (size_t i = 0; i < num_threads; i++)
2754 {
2755 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002756 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002757 StopReason reason = eStopReasonInvalid;
2758 if (stop_info_sp)
2759 reason = stop_info_sp->GetStopReason();
2760 if (reason != eStopReasonBreakpoint
2761 && reason != eStopReasonException)
2762 {
2763 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002764 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
2765 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00002766 thread_sp->SetResumeState(eStateSuspended);
2767 }
2768 }
2769 }
2770 Resume ();
Jason Molendaede31932015-04-17 05:01:58 +00002771 return Destroy(false);
Jim Ingham43c555d2012-07-04 00:35:43 +00002772 }
2773 }
2774 }
2775 }
2776
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002777 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00002778 int exit_status = SIGABRT;
2779 std::string exit_string;
2780
Greg Clayton6ed95942011-01-22 07:12:45 +00002781 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002782 {
Jim Inghamaab78372011-10-28 01:11:35 +00002783 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00002784 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002785 StringExtractorGDBRemote response;
2786 bool send_async = true;
Tamas Berghammer912800c2015-02-24 10:23:39 +00002787 GDBRemoteCommunication::ScopedTimeout (m_gdb_comm, 3);
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002788
Greg Clayton3dedae12013-12-06 21:45:27 +00002789 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton513c26c2011-01-29 07:10:55 +00002790 {
2791 char packet_cmd = response.GetChar(0);
2792
2793 if (packet_cmd == 'W' || packet_cmd == 'X')
2794 {
Jim Inghameac0aa42014-02-21 22:36:11 +00002795#if defined(__APPLE__)
Jim Ingham9d67cc52014-02-21 22:35:29 +00002796 // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off
2797 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill
2798 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns
2799 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap
2800 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of
2801 // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2802 // Anyway, so call waitpid here to finally reap it.
2803 PlatformSP platform_sp(GetTarget().GetPlatform());
2804 if (platform_sp && platform_sp->IsHost())
2805 {
2806 int status;
2807 ::pid_t reap_pid;
2808 reap_pid = waitpid (GetID(), &status, WNOHANG);
2809 if (log)
2810 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2811 }
2812#endif
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002813 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002814 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00002815 exit_status = response.GetHexU8();
2816 }
2817 else
2818 {
2819 if (log)
2820 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2821 exit_string.assign("got unexpected response to k packet: ");
2822 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00002823 }
2824 }
2825 else
2826 {
Jim Inghambabfc382012-06-06 00:32:39 +00002827 if (log)
2828 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2829 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00002830 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002831 }
Jim Inghambabfc382012-06-06 00:32:39 +00002832 else
2833 {
2834 if (log)
Ed Masteb3a53332014-03-17 17:05:22 +00002835 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching");
Jim Inghamcfc09352012-07-27 23:57:19 +00002836 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00002837 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002838 }
Jim Inghambabfc382012-06-06 00:32:39 +00002839 else
2840 {
2841 // If we missed setting the exit status on the way out, do it here.
2842 // NB set exit status can be called multiple times, the first one sets the status.
2843 exit_string.assign("destroying when not connected to debugserver");
2844 }
2845
2846 SetExitStatus(exit_status, exit_string.c_str());
2847
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002848 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002849 KillDebugserverProcess ();
2850 return error;
2851}
2852
Greg Clayton8cda7f02013-05-21 21:55:59 +00002853void
2854ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2855{
Greg Clayton8cda7f02013-05-21 21:55:59 +00002856 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2857 if (did_exec)
2858 {
2859 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2860 if (log)
2861 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2862
2863 m_thread_list_real.Clear();
2864 m_thread_list.Clear();
2865 BuildDynamicRegisterInfo (true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002866 m_gdb_comm.ResetDiscoverableSettings (did_exec);
Greg Clayton8cda7f02013-05-21 21:55:59 +00002867 }
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002868
2869 // Scope the lock
2870 {
2871 // Lock the thread stack while we access it
2872 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
Greg Clayton2e309072015-07-17 23:42:28 +00002873
2874 // We are are not using non-stop mode, there can only be one last stop
2875 // reply packet, so clear the list.
2876 if (GetTarget().GetNonStopModeEnabled() == false)
2877 m_stop_packet_stack.clear();
2878
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002879 // Add this stop packet to the stop packet stack
2880 // This stack will get popped and examined when we switch to the
2881 // Stopped state
2882 m_stop_packet_stack.push_back(response);
2883 }
Greg Clayton8cda7f02013-05-21 21:55:59 +00002884}
2885
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002886//------------------------------------------------------------------
2887// Process Queries
2888//------------------------------------------------------------------
2889
2890bool
2891ProcessGDBRemote::IsAlive ()
2892{
Greg Clayton10177aa2010-12-08 05:08:21 +00002893 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002894}
2895
2896addr_t
2897ProcessGDBRemote::GetImageInfoAddress()
2898{
Aidan Doddsc0c83852015-05-08 09:36:31 +00002899 // request the link map address via the $qShlibInfoAddr packet
2900 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2901
2902 // the loaded module list can also provides a link map address
2903 if (addr == LLDB_INVALID_ADDRESS)
2904 {
2905 GDBLoadedModuleInfoList list;
2906 if (GetLoadedModuleList (list).Success())
2907 addr = list.m_link_map;
2908 }
2909
2910 return addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002911}
2912
Greg Clayton2e309072015-07-17 23:42:28 +00002913void
2914ProcessGDBRemote::WillPublicStop ()
2915{
2916 // See if the GDB remote client supports the JSON threads info.
2917 // If so, we gather stop info for all threads, expedited registers,
2918 // expedited memory, runtime queue information (iOS and MacOSX only),
2919 // and more. Expediting memory will help stack backtracing be much
2920 // faster. Expediting registers will make sure we don't have to read
2921 // the thread registers for GPRs.
2922 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
2923
2924 if (m_jthreadsinfo_sp)
2925 {
2926 // Now set the stop info for each thread and also expedite any registers
2927 // and memory that was in the jThreadsInfo response.
2928 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
2929 if (thread_infos)
2930 {
2931 const size_t n = thread_infos->GetSize();
2932 for (size_t i=0; i<n; ++i)
2933 {
2934 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
2935 if (thread_dict)
2936 SetThreadStopInfo(thread_dict);
2937 }
2938 }
2939 }
2940}
2941
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002942//------------------------------------------------------------------
2943// Process Memory
2944//------------------------------------------------------------------
2945size_t
2946ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2947{
Jason Molenda6076bf42014-05-06 04:34:52 +00002948 GetMaxMemorySize ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002949 if (size > m_max_memory_size)
2950 {
2951 // Keep memory read sizes down to a sane limit. This function will be
2952 // called multiple times in order to complete the task by
2953 // lldb_private::Process so it is ok to do this.
2954 size = m_max_memory_size;
2955 }
2956
2957 char packet[64];
Jason Molenda6076bf42014-05-06 04:34:52 +00002958 int packet_len;
2959 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2960 if (binary_memory_read)
2961 {
2962 packet_len = ::snprintf (packet, sizeof(packet), "x0x%" PRIx64 ",0x%" PRIx64, (uint64_t)addr, (uint64_t)size);
2963 }
2964 else
2965 {
2966 packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
2967 }
Andy Gibbsa297a972013-06-19 19:04:53 +00002968 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002969 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002970 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002971 {
Greg Clayton576d8832011-03-22 04:00:09 +00002972 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002973 {
2974 error.Clear();
Jason Molenda6076bf42014-05-06 04:34:52 +00002975 if (binary_memory_read)
2976 {
2977 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any
2978 // 0x7d character escaping that was present in the packet
2979
2980 size_t data_received_size = response.GetBytesLeft();
2981 if (data_received_size > size)
2982 {
2983 // Don't write past the end of BUF if the remote debug server gave us too
2984 // much data for some reason.
2985 data_received_size = size;
2986 }
2987 memcpy (buf, response.GetStringRef().data(), data_received_size);
2988 return data_received_size;
2989 }
2990 else
2991 {
2992 return response.GetHexBytes(buf, size, '\xdd');
2993 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002994 }
Greg Clayton576d8832011-03-22 04:00:09 +00002995 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002996 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002997 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002998 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002999 else
Greg Clayton9944cd72012-09-19 01:46:31 +00003000 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003001 }
3002 else
3003 {
Jim Ingham35579dd2013-06-03 19:34:01 +00003004 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003005 }
3006 return 0;
3007}
3008
3009size_t
3010ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
3011{
Jason Molenda6076bf42014-05-06 04:34:52 +00003012 GetMaxMemorySize ();
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00003013 if (size > m_max_memory_size)
3014 {
3015 // Keep memory read sizes down to a sane limit. This function will be
3016 // called multiple times in order to complete the task by
3017 // lldb_private::Process so it is ok to do this.
3018 size = m_max_memory_size;
3019 }
3020
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003021 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00003022 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Clayton7fb56d02011-02-01 01:31:41 +00003023 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003024 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003025 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003026 {
Greg Clayton576d8832011-03-22 04:00:09 +00003027 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003028 {
3029 error.Clear();
3030 return size;
3031 }
Greg Clayton576d8832011-03-22 04:00:09 +00003032 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00003033 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00003034 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00003035 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003036 else
Greg Clayton9944cd72012-09-19 01:46:31 +00003037 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 +00003038 }
3039 else
3040 {
Jim Ingham35579dd2013-06-03 19:34:01 +00003041 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003042 }
3043 return 0;
3044}
3045
3046lldb::addr_t
3047ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
3048{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003049 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_EXPRESSIONS));
Greg Clayton2a48f522011-05-14 01:50:35 +00003050 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
3051
Greg Clayton70b57652011-05-15 01:25:55 +00003052 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton2a48f522011-05-14 01:50:35 +00003053 switch (supported)
3054 {
3055 case eLazyBoolCalculate:
3056 case eLazyBoolYes:
3057 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
3058 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
3059 return allocated_addr;
3060
3061 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003062 // Call mmap() to create memory in the inferior..
3063 unsigned prot = 0;
3064 if (permissions & lldb::ePermissionsReadable)
3065 prot |= eMmapProtRead;
3066 if (permissions & lldb::ePermissionsWritable)
3067 prot |= eMmapProtWrite;
3068 if (permissions & lldb::ePermissionsExecutable)
3069 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00003070
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003071 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
3072 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
3073 m_addr_to_mmap_size[allocated_addr] = size;
3074 else
Todd Fialaaf245d12014-06-30 21:05:18 +00003075 {
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003076 allocated_addr = LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00003077 if (log)
3078 log->Printf ("ProcessGDBRemote::%s no direct stub support for memory allocation, and InferiorCallMmap also failed - is stub missing register context save/restore capability?", __FUNCTION__);
3079 }
Greg Clayton2a48f522011-05-14 01:50:35 +00003080 break;
3081 }
3082
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003083 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00003084 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003085 else
3086 error.Clear();
3087 return allocated_addr;
3088}
3089
3090Error
Greg Clayton46fb5582011-11-18 07:03:08 +00003091ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
3092 MemoryRegionInfo &region_info)
3093{
3094
3095 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
3096 return error;
3097}
3098
3099Error
Johnny Chen64637202012-05-23 21:09:52 +00003100ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
3101{
3102
3103 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
3104 return error;
3105}
3106
3107Error
Enrico Granataf04a2192012-07-13 23:18:48 +00003108ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
3109{
Jaydeep Patil725666c2015-08-13 03:46:01 +00003110 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after, GetTarget().GetArchitecture()));
Enrico Granataf04a2192012-07-13 23:18:48 +00003111 return error;
3112}
3113
3114Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003115ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
3116{
3117 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00003118 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
3119
3120 switch (supported)
3121 {
3122 case eLazyBoolCalculate:
3123 // We should never be deallocating memory without allocating memory
3124 // first so we should never get eLazyBoolCalculate
3125 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
3126 break;
3127
3128 case eLazyBoolYes:
3129 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00003130 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003131 break;
3132
3133 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003134 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00003135 {
3136 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003137 if (pos != m_addr_to_mmap_size.end() &&
3138 InferiorCallMunmap(this, addr, pos->second))
3139 m_addr_to_mmap_size.erase (pos);
3140 else
Daniel Malead01b2952012-11-29 21:49:15 +00003141 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003142 }
3143 break;
3144 }
3145
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003146 return error;
3147}
3148
3149
3150//------------------------------------------------------------------
3151// Process STDIO
3152//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003153size_t
3154ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
3155{
3156 if (m_stdio_communication.IsConnected())
3157 {
3158 ConnectionStatus status;
3159 m_stdio_communication.Write(src, src_len, status, NULL);
3160 }
Vince Harrondf3f00f2015-02-10 21:09:04 +00003161 else if (m_stdin_forward)
Vince Harrone0be4252015-02-06 18:32:57 +00003162 {
3163 m_gdb_comm.SendStdinNotification(src, src_len);
3164 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003165 return 0;
3166}
3167
3168Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003169ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003170{
3171 Error error;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003172 assert(bp_site != NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003173
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003174 // Get logging info
3175 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003176 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003177
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003178 // Get the breakpoint address
3179 const addr_t addr = bp_site->GetLoadAddress();
3180
3181 // Log that a breakpoint was requested
3182 if (log)
3183 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
3184
3185 // Breakpoint already exists and is enabled
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003186 if (bp_site->IsEnabled())
3187 {
3188 if (log)
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003189 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 +00003190 return error;
3191 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003192
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003193 // Get the software breakpoint trap opcode size
3194 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3195
3196 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
3197 // is supported by the remote stub. These are set to true by default, and later set to false
3198 // only after we receive an unimplemented response when sending a breakpoint packet. This means
3199 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
3200 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
3201 // indicates if the user specifically asked for hardware breakpoints. If true then we will
3202 // skip over software breakpoints.
3203 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
3204 {
3205 // Try to send off a software breakpoint packet ($Z0)
3206 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003207 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003208 // The breakpoint was placed successfully
3209 bp_site->SetEnabled(true);
3210 bp_site->SetType(BreakpointSite::eExternal);
Greg Claytoneb023e72013-10-11 19:48:25 +00003211 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003212 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003213
3214 // SendGDBStoppointTypePacket() will return an error if it was unable to set this
3215 // breakpoint. We need to differentiate between a error specific to placing this breakpoint
3216 // or if we have learned that this breakpoint type is unsupported. To do this, we
3217 // must test the support boolean for this breakpoint type to see if it now indicates that
3218 // this breakpoint type is unsupported. If they are still supported then we should return
3219 // with the error code. If they are now unsupported, then we would like to fall through
3220 // and try another form of breakpoint.
3221 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
3222 return error;
3223
3224 // We reach here when software breakpoints have been found to be unsupported. For future
3225 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
3226 // known not to be supported.
3227 if (log)
3228 log->Printf("Software breakpoints are unsupported");
3229
3230 // So we will fall through and try a hardware breakpoint
3231 }
3232
3233 // The process of setting a hardware breakpoint is much the same as above. We check the
3234 // supported boolean for this breakpoint type, and if it is thought to be supported then we
3235 // will try to set this breakpoint with a hardware breakpoint.
3236 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3237 {
3238 // Try to send off a hardware breakpoint packet ($Z1)
3239 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003240 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003241 // The breakpoint was placed successfully
3242 bp_site->SetEnabled(true);
3243 bp_site->SetType(BreakpointSite::eHardware);
3244 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003245 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003246
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003247 // Check if the error was something other then an unsupported breakpoint type
3248 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3249 {
3250 // Unable to set this hardware breakpoint
3251 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
3252 return error;
3253 }
3254
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003255 // We will reach here when the stub gives an unsupported response to a hardware breakpoint
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003256 if (log)
3257 log->Printf("Hardware breakpoints are unsupported");
3258
3259 // Finally we will falling through to a #trap style breakpoint
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003260 }
3261
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003262 // Don't fall through when hardware breakpoints were specifically requested
3263 if (bp_site->HardwareRequired())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003264 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003265 error.SetErrorString("hardware breakpoints are not supported");
3266 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003267 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003268
3269 // As a last resort we want to place a manual breakpoint. An instruction
3270 // is placed into the process memory using memory write packets.
3271 return EnableSoftwareBreakpoint(bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003272}
3273
3274Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003275ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003276{
3277 Error error;
3278 assert (bp_site != NULL);
3279 addr_t addr = bp_site->GetLoadAddress();
3280 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00003281 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003282 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003283 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003284
3285 if (bp_site->IsEnabled())
3286 {
3287 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
3288
Greg Clayton8b82f082011-04-12 05:54:46 +00003289 BreakpointSite::Type bp_type = bp_site->GetType();
3290 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003291 {
Greg Clayton8b82f082011-04-12 05:54:46 +00003292 case BreakpointSite::eSoftware:
3293 error = DisableSoftwareBreakpoint (bp_site);
3294 break;
3295
3296 case BreakpointSite::eHardware:
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003297 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003298 error.SetErrorToGenericError();
3299 break;
3300
3301 case BreakpointSite::eExternal:
Jim Inghama04ef752014-03-07 11:18:02 +00003302 {
3303 GDBStoppointType stoppoint_type;
3304 if (bp_site->IsHardware())
3305 stoppoint_type = eBreakpointHardware;
3306 else
3307 stoppoint_type = eBreakpointSoftware;
3308
3309 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003310 error.SetErrorToGenericError();
Jim Inghama04ef752014-03-07 11:18:02 +00003311 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003312 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003313 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003314 if (error.Success())
3315 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003316 }
3317 else
3318 {
3319 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003320 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 +00003321 return error;
3322 }
3323
3324 if (error.Success())
3325 error.SetErrorToGenericError();
3326 return error;
3327}
3328
Johnny Chen11309a32011-09-06 22:38:36 +00003329// Pre-requisite: wp != NULL.
3330static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00003331GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00003332{
3333 assert(wp);
3334 bool watch_read = wp->WatchpointRead();
3335 bool watch_write = wp->WatchpointWrite();
3336
3337 // watch_read and watch_write cannot both be false.
3338 assert(watch_read || watch_write);
3339 if (watch_read && watch_write)
3340 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00003341 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00003342 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00003343 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00003344 return eWatchpointWrite;
3345}
3346
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003347Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003348ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003349{
3350 Error error;
3351 if (wp)
3352 {
3353 user_id_t watchID = wp->GetID();
3354 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00003355 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003356 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003357 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003358 if (wp->IsEnabled())
3359 {
3360 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003361 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 +00003362 return error;
3363 }
Johnny Chen11309a32011-09-06 22:38:36 +00003364
3365 GDBStoppointType type = GetGDBStoppointType(wp);
3366 // Pass down an appropriate z/Z packet...
3367 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003368 {
Johnny Chen11309a32011-09-06 22:38:36 +00003369 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
3370 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003371 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003372 return error;
3373 }
3374 else
3375 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003376 }
Johnny Chen11309a32011-09-06 22:38:36 +00003377 else
3378 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003379 }
3380 else
3381 {
Johnny Chen01a67862011-10-14 00:42:25 +00003382 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003383 }
3384 if (error.Success())
3385 error.SetErrorToGenericError();
3386 return error;
3387}
3388
3389Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003390ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003391{
3392 Error error;
3393 if (wp)
3394 {
3395 user_id_t watchID = wp->GetID();
3396
Greg Clayton5160ce52013-03-27 23:08:40 +00003397 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003398
3399 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00003400
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003401 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003402 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003403
Johnny Chen11309a32011-09-06 22:38:36 +00003404 if (!wp->IsEnabled())
3405 {
3406 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003407 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 +00003408 // See also 'class WatchpointSentry' within StopInfo.cpp.
3409 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
3410 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00003411 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003412 return error;
3413 }
3414
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003415 if (wp->IsHardware())
3416 {
Johnny Chen11309a32011-09-06 22:38:36 +00003417 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003418 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00003419 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
3420 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003421 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003422 return error;
3423 }
3424 else
3425 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003426 }
3427 // TODO: clear software watchpoints if we implement them
3428 }
3429 else
3430 {
Johnny Chen01a67862011-10-14 00:42:25 +00003431 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003432 }
3433 if (error.Success())
3434 error.SetErrorToGenericError();
3435 return error;
3436}
3437
3438void
3439ProcessGDBRemote::Clear()
3440{
3441 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00003442 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003443 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003444}
3445
3446Error
3447ProcessGDBRemote::DoSignal (int signo)
3448{
3449 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00003450 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003451 if (log)
3452 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
3453
3454 if (!m_gdb_comm.SendAsyncSignal (signo))
3455 error.SetErrorStringWithFormat("failed to send signal %i", signo);
3456 return error;
3457}
3458
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003459Error
Greg Clayton91a9b2472013-12-04 19:19:12 +00003460ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003461{
3462 Error error;
3463 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
3464 {
3465 // If we locate debugserver, keep that located version around
3466 static FileSpec g_debugserver_file_spec;
3467
Han Ming Ong84647042012-02-25 01:07:38 +00003468 ProcessLaunchInfo debugserver_launch_info;
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00003469 // Make debugserver run in its own session so signals generated by
3470 // special terminal key sequences (^C) don't affect debugserver.
3471 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3472
Greg Clayton91a9b2472013-12-04 19:19:12 +00003473 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
3474 debugserver_launch_info.SetUserID(process_info.GetUserID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003475
Todd Fiala013434e2014-07-09 01:29:05 +00003476#if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__) || defined (__aarch64__))
Greg Claytonfda4fab2014-01-10 22:24:11 +00003477 // On iOS, still do a local connection using a random port
Greg Clayton16810922014-02-27 19:38:18 +00003478 const char *hostname = "127.0.0.1";
Greg Claytonfda4fab2014-01-10 22:24:11 +00003479 uint16_t port = get_random_port ();
3480#else
3481 // Set hostname being NULL to do the reverse connect where debugserver
3482 // will bind to port zero and it will communicate back to us the port
3483 // that we will connect to
3484 const char *hostname = NULL;
3485 uint16_t port = 0;
3486#endif
3487
3488 error = m_gdb_comm.StartDebugserverProcess (hostname,
3489 port,
Greg Clayton00fe87b2013-12-05 22:58:22 +00003490 debugserver_launch_info,
3491 port);
Greg Clayton91a9b2472013-12-04 19:19:12 +00003492
3493 if (error.Success ())
3494 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003495 else
Greg Clayton91a9b2472013-12-04 19:19:12 +00003496 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003497
3498 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3499 StartAsyncThread ();
Greg Clayton91a9b2472013-12-04 19:19:12 +00003500
3501 if (error.Fail())
3502 {
3503 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
3504
3505 if (log)
3506 log->Printf("failed to start debugserver process: %s", error.AsCString());
3507 return error;
3508 }
3509
Greg Clayton00fe87b2013-12-05 22:58:22 +00003510 if (m_gdb_comm.IsConnected())
3511 {
3512 // Finish the connection process by doing the handshake without connecting (send NULL URL)
3513 ConnectToDebugserver (NULL);
3514 }
3515 else
3516 {
Greg Claytonfda4fab2014-01-10 22:24:11 +00003517 StreamString connect_url;
3518 connect_url.Printf("connect://%s:%u", hostname, port);
3519 error = ConnectToDebugserver (connect_url.GetString().c_str());
Greg Clayton00fe87b2013-12-05 22:58:22 +00003520 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00003521
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003522 }
3523 return error;
3524}
3525
3526bool
3527ProcessGDBRemote::MonitorDebugserverProcess
3528(
3529 void *callback_baton,
3530 lldb::pid_t debugserver_pid,
Greg Claytone4e45922011-11-16 05:37:56 +00003531 bool exited, // True if the process did exit
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003532 int signo, // Zero for no signal
3533 int exit_status // Exit value of process if signal is zero
3534)
3535{
Greg Claytone4e45922011-11-16 05:37:56 +00003536 // The baton is a "ProcessGDBRemote *". Now this class might be gone
3537 // and might not exist anymore, so we need to carefully try to get the
3538 // target for this process first since we have a race condition when
3539 // we are done running between getting the notice that the inferior
3540 // process has died and the debugserver that was debugging this process.
3541 // In our test suite, we are also continually running process after
3542 // process, so we must be very careful to make sure:
3543 // 1 - process object hasn't been deleted already
3544 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003545
3546 // "debugserver_pid" argument passed in is the process ID for
3547 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00003548 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003549
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003550 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton6779606a2011-01-22 23:43:18 +00003551
Greg Claytone4e45922011-11-16 05:37:56 +00003552 // Get a shared pointer to the target that has a matching process pointer.
3553 // This target could be gone, or the target could already have a new process
3554 // object inside of it
3555 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
3556
Greg Clayton6779606a2011-01-22 23:43:18 +00003557 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003558 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 +00003559
Greg Claytone4e45922011-11-16 05:37:56 +00003560 if (target_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003561 {
Greg Claytone4e45922011-11-16 05:37:56 +00003562 // We found a process in a target that matches, but another thread
3563 // might be in the process of launching a new process that will
3564 // soon replace it, so get a shared pointer to the process so we
3565 // can keep it alive.
3566 ProcessSP process_sp (target_sp->GetProcessSP());
3567 // Now we have a shared pointer to the process that can't go away on us
3568 // so we now make sure it was the same as the one passed in, and also make
3569 // sure that our previous "process *" didn't get deleted and have a new
3570 // "process *" created in its place with the same pointer. To verify this
3571 // we make sure the process has our debugserver process ID. If we pass all
3572 // of these tests, then we are sure that this process is the one we were
3573 // looking for.
3574 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003575 {
Greg Claytone4e45922011-11-16 05:37:56 +00003576 // Sleep for a half a second to make sure our inferior process has
3577 // time to set its exit status before we set it incorrectly when
3578 // both the debugserver and the inferior process shut down.
3579 usleep (500000);
3580 // If our process hasn't yet exited, debugserver might have died.
3581 // If the process did exit, the we are reaping it.
3582 const StateType state = process->GetState();
3583
3584 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
3585 state != eStateInvalid &&
3586 state != eStateUnloaded &&
3587 state != eStateExited &&
3588 state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003589 {
Greg Claytone4e45922011-11-16 05:37:56 +00003590 char error_str[1024];
3591 if (signo)
3592 {
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00003593 const char *signal_cstr = process->GetUnixSignals()->GetSignalAsCString(signo);
Greg Claytone4e45922011-11-16 05:37:56 +00003594 if (signal_cstr)
3595 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3596 else
3597 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
3598 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003599 else
Greg Claytone4e45922011-11-16 05:37:56 +00003600 {
3601 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
3602 }
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003603
Greg Claytone4e45922011-11-16 05:37:56 +00003604 process->SetExitStatus (-1, error_str);
3605 }
3606 // Debugserver has exited we need to let our ProcessGDBRemote
3607 // know that it no longer has a debugserver instance
3608 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003609 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003610 }
3611 return true;
3612}
3613
3614void
3615ProcessGDBRemote::KillDebugserverProcess ()
3616{
Greg Claytonfbb76342013-11-20 21:07:01 +00003617 m_gdb_comm.Disconnect();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003618 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3619 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003620 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003621 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3622 }
3623}
3624
3625void
3626ProcessGDBRemote::Initialize()
3627{
Davide Italianoc8d69822015-04-03 04:24:32 +00003628 static std::once_flag g_once_flag;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003629
Davide Italianoc8d69822015-04-03 04:24:32 +00003630 std::call_once(g_once_flag, []()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003631 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003632 PluginManager::RegisterPlugin (GetPluginNameStatic(),
3633 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00003634 CreateInstance,
3635 DebuggerInitialize);
Davide Italianoc8d69822015-04-03 04:24:32 +00003636 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003637}
3638
Greg Clayton7f982402013-07-15 22:54:20 +00003639void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003640ProcessGDBRemote::DebuggerInitialize (Debugger &debugger)
Greg Clayton7f982402013-07-15 22:54:20 +00003641{
3642 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
3643 {
3644 const bool is_global_setting = true;
3645 PluginManager::CreateSettingForProcessPlugin (debugger,
3646 GetGlobalPluginProperties()->GetValueProperties(),
3647 ConstString ("Properties for the gdb-remote process plug-in."),
3648 is_global_setting);
3649 }
3650}
3651
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003652bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003653ProcessGDBRemote::StartAsyncThread ()
3654{
Greg Clayton5160ce52013-03-27 23:08:40 +00003655 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003656
3657 if (log)
3658 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003659
3660 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003661 if (!m_async_thread.IsJoinable())
Jim Ingham455fa5c2012-11-01 01:15:33 +00003662 {
3663 // Create a thread that watches our internal state and controls which
3664 // events make it to clients (into the DCProcess event queue).
Zachary Turner39de3112014-09-09 20:54:56 +00003665
3666 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003667 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003668 else if (log)
3669 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was already running.", __FUNCTION__);
Zachary Turner39de3112014-09-09 20:54:56 +00003670
Zachary Turneracee96a2014-09-23 18:32:09 +00003671 return m_async_thread.IsJoinable();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003672}
3673
3674void
3675ProcessGDBRemote::StopAsyncThread ()
3676{
Greg Clayton5160ce52013-03-27 23:08:40 +00003677 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003678
3679 if (log)
3680 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
3681
Jim Ingham455fa5c2012-11-01 01:15:33 +00003682 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003683 if (m_async_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003684 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00003685 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
3686
3687 // This will shut down the async thread.
3688 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3689
3690 // Stop the stdio thread
Zachary Turner39de3112014-09-09 20:54:56 +00003691 m_async_thread.Join(nullptr);
Pavel Labatha55a9532015-03-11 09:53:42 +00003692 m_async_thread.Reset();
Jim Ingham455fa5c2012-11-01 01:15:33 +00003693 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003694 else if (log)
3695 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003696}
3697
Ewan Crawford76df2882015-06-23 12:32:06 +00003698bool
3699ProcessGDBRemote::HandleNotifyPacket (StringExtractorGDBRemote &packet)
3700{
3701 // get the packet at a string
3702 const std::string &pkt = packet.GetStringRef();
3703 // skip %stop:
3704 StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
3705
3706 // pass as a thread stop info packet
3707 SetLastStopPacket(stop_info);
3708
3709 // check for more stop reasons
3710 HandleStopReplySequence();
3711
3712 // if the process is stopped then we need to fake a resume
3713 // so that we can stop properly with the new break. This
3714 // is possible due to SetPrivateState() broadcasting the
3715 // state change as a side effect.
3716 if (GetPrivateState() == lldb::StateType::eStateStopped)
3717 {
3718 SetPrivateState(lldb::StateType::eStateRunning);
3719 }
3720
3721 // since we have some stopped packets we can halt the process
3722 SetPrivateState(lldb::StateType::eStateStopped);
3723
3724 return true;
3725}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003726
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003727thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003728ProcessGDBRemote::AsyncThread (void *arg)
3729{
3730 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
3731
Greg Clayton5160ce52013-03-27 23:08:40 +00003732 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003733 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003734 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003735
3736 Listener listener ("ProcessGDBRemote::AsyncThread");
3737 EventSP event_sp;
3738 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
3739 eBroadcastBitAsyncThreadShouldExit;
3740
3741 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
3742 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003743 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit |
3744 GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify);
3745
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003746 bool done = false;
3747 while (!done)
3748 {
3749 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003750 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003751 if (listener.WaitForEvent (NULL, event_sp))
3752 {
3753 const uint32_t event_type = event_sp->GetType();
Greg Clayton71337622011-02-24 22:24:29 +00003754 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003755 {
Greg Clayton71337622011-02-24 22:24:29 +00003756 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003757 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 +00003758
Greg Clayton71337622011-02-24 22:24:29 +00003759 switch (event_type)
3760 {
3761 case eBroadcastBitAsyncContinue:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003762 {
Greg Clayton71337622011-02-24 22:24:29 +00003763 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003764
Greg Clayton71337622011-02-24 22:24:29 +00003765 if (continue_packet)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003766 {
Greg Clayton71337622011-02-24 22:24:29 +00003767 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
3768 const size_t continue_cstr_len = continue_packet->GetByteSize ();
3769 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003770 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003771
Greg Clayton71337622011-02-24 22:24:29 +00003772 if (::strstr (continue_cstr, "vAttach") == NULL)
3773 process->SetPrivateState(eStateRunning);
3774 StringExtractorGDBRemote response;
Ewan Crawford76df2882015-06-23 12:32:06 +00003775
3776 // If in Non-Stop-Mode
3777 if (process->GetTarget().GetNonStopModeEnabled())
Greg Clayton71337622011-02-24 22:24:29 +00003778 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003779 // send the vCont packet
3780 if (!process->GetGDBRemote().SendvContPacket(process, continue_cstr, continue_cstr_len, response))
Jason Molendaa3329782014-03-29 18:54:20 +00003781 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003782 // Something went wrong
3783 done = true;
3784 break;
3785 }
3786 }
3787 // If in All-Stop-Mode
3788 else
3789 {
3790 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
3791
3792 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
3793 // The thread ID list might be contained within the "response", or the stop reply packet that
3794 // caused the stop. So clear it now before we give the stop reply packet to the process
3795 // using the process->SetLastStopPacket()...
3796 process->ClearThreadIDList ();
3797
3798 switch (stop_state)
3799 {
3800 case eStateStopped:
3801 case eStateCrashed:
3802 case eStateSuspended:
3803 process->SetLastStopPacket (response);
3804 process->SetPrivateState (stop_state);
3805 break;
3806
3807 case eStateExited:
3808 {
3809 process->SetLastStopPacket (response);
3810 process->ClearThreadIDList();
3811 response.SetFilePos(1);
3812
3813 int exit_status = response.GetHexU8();
3814 const char *desc_cstr = NULL;
3815 StringExtractor extractor;
3816 std::string desc_string;
3817 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';')
Jason Molendaa3329782014-03-29 18:54:20 +00003818 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003819 std::string desc_token;
3820 while (response.GetNameColonValue (desc_token, desc_string))
Jason Molendaa3329782014-03-29 18:54:20 +00003821 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003822 if (desc_token == "description")
3823 {
3824 extractor.GetStringRef().swap(desc_string);
3825 extractor.SetFilePos(0);
3826 extractor.GetHexByteString (desc_string);
3827 desc_cstr = desc_string.c_str();
3828 }
Jason Molendaa3329782014-03-29 18:54:20 +00003829 }
3830 }
Ewan Crawford76df2882015-06-23 12:32:06 +00003831 process->SetExitStatus(exit_status, desc_cstr);
3832 done = true;
3833 break;
Jason Molendaa3329782014-03-29 18:54:20 +00003834 }
Ewan Crawford76df2882015-06-23 12:32:06 +00003835 case eStateInvalid:
Jason Molenda752e1e82015-07-29 01:42:16 +00003836 {
3837 // Check to see if we were trying to attach and if we got back
3838 // the "E87" error code from debugserver -- this indicates that
3839 // the process is not debuggable. Return a slightly more helpful
3840 // error message about why the attach failed.
3841 if (::strstr (continue_cstr, "vAttach") != NULL
3842 && response.GetError() == 0x87)
3843 {
3844 process->SetExitStatus(-1, "cannot attach to process due to System Integrity Protection");
3845 }
3846 // E01 code from vAttach means that the attach failed
3847 if (::strstr (continue_cstr, "vAttach") != NULL
3848 && response.GetError() == 0x1)
3849 {
3850 process->SetExitStatus(-1, "unable to attach");
3851 }
3852 else
3853 {
3854 process->SetExitStatus(-1, "lost connection");
3855 }
3856 break;
3857 }
Greg Clayton71337622011-02-24 22:24:29 +00003858
Ewan Crawford76df2882015-06-23 12:32:06 +00003859 default:
3860 process->SetPrivateState (stop_state);
3861 break;
3862 } // switch(stop_state)
3863 } // else // if in All-stop-mode
3864 } // if (continue_packet)
3865 } // case eBroadcastBitAysncContinue
Greg Clayton71337622011-02-24 22:24:29 +00003866 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003867
Greg Clayton71337622011-02-24 22:24:29 +00003868 case eBroadcastBitAsyncThreadShouldExit:
3869 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003870 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Clayton71337622011-02-24 22:24:29 +00003871 done = true;
3872 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003873
Greg Clayton71337622011-02-24 22:24:29 +00003874 default:
3875 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003876 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 +00003877 done = true;
3878 break;
3879 }
3880 }
3881 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
3882 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003883 switch (event_type)
Greg Clayton71337622011-02-24 22:24:29 +00003884 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003885 case Communication::eBroadcastBitReadThreadDidExit:
3886 process->SetExitStatus (-1, "lost connection");
3887 done = true;
3888 break;
3889
3890 case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify:
3891 {
3892 lldb_private::Event *event = event_sp.get();
3893 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event);
3894 StringExtractorGDBRemote notify((const char*)continue_packet->GetBytes());
3895 // Hand this over to the process to handle
3896 process->HandleNotifyPacket(notify);
3897 break;
3898 }
3899
3900 default:
3901 if (log)
3902 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
3903 done = true;
3904 break;
Greg Clayton71337622011-02-24 22:24:29 +00003905 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003906 }
3907 }
3908 else
3909 {
3910 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003911 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 +00003912 done = true;
3913 }
3914 }
3915 }
3916
3917 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003918 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003919
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003920 return NULL;
3921}
3922
Greg Claytone996fd32011-03-08 22:40:15 +00003923//uint32_t
3924//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3925//{
3926// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
3927// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
3928// if (m_local_debugserver)
3929// {
3930// return Host::ListProcessesMatchingName (name, matches, pids);
3931// }
3932// else
3933// {
3934// // FIXME: Implement talking to the remote debugserver.
3935// return 0;
3936// }
3937//
3938//}
3939//
Jim Ingham1c823b42011-01-22 01:33:44 +00003940bool
3941ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003942 StoppointCallbackContext *context,
Jim Ingham1c823b42011-01-22 01:33:44 +00003943 lldb::user_id_t break_id,
3944 lldb::user_id_t break_loc_id)
3945{
3946 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3947 // run so I can stop it if that's what I want to do.
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003948 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00003949 if (log)
3950 log->Printf("Hit New Thread Notification breakpoint.");
3951 return false;
3952}
3953
3954
3955bool
3956ProcessGDBRemote::StartNoticingNewThreads()
3957{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003958 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00003959 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003960 {
Greg Clayton4116e932012-05-15 02:33:01 +00003961 if (log && log->GetVerbose())
3962 log->Printf("Enabled noticing new thread breakpoint.");
3963 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003964 }
Greg Clayton4116e932012-05-15 02:33:01 +00003965 else
Jim Ingham1c823b42011-01-22 01:33:44 +00003966 {
Greg Clayton4116e932012-05-15 02:33:01 +00003967 PlatformSP platform_sp (m_target.GetPlatform());
3968 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003969 {
Greg Clayton4116e932012-05-15 02:33:01 +00003970 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3971 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003972 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00003973 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00003974 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3975 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003976 }
3977 else
3978 {
3979 if (log)
3980 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00003981 }
3982 }
3983 }
Greg Clayton4116e932012-05-15 02:33:01 +00003984 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00003985}
3986
3987bool
3988ProcessGDBRemote::StopNoticingNewThreads()
3989{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003990 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00003991 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00003992 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00003993
3994 if (m_thread_create_bp_sp)
3995 m_thread_create_bp_sp->SetEnabled(false);
3996
Jim Ingham1c823b42011-01-22 01:33:44 +00003997 return true;
3998}
3999
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004000DynamicLoader *
Jason Molenda5e8534e2012-10-03 01:29:34 +00004001ProcessGDBRemote::GetDynamicLoader ()
4002{
4003 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00004004 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00004005 return m_dyld_ap.get();
4006}
Jim Ingham1c823b42011-01-22 01:33:44 +00004007
Jason Molendaa3329782014-03-29 18:54:20 +00004008Error
4009ProcessGDBRemote::SendEventData(const char *data)
4010{
4011 int return_value;
4012 bool was_supported;
4013
4014 Error error;
4015
4016 return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported);
4017 if (return_value != 0)
4018 {
4019 if (!was_supported)
4020 error.SetErrorString("Sending events is not supported for this process.");
4021 else
4022 error.SetErrorStringWithFormat("Error sending event data: %d.", return_value);
4023 }
4024 return error;
4025}
4026
Steve Pucci03904ac2014-03-04 23:18:46 +00004027const DataBufferSP
4028ProcessGDBRemote::GetAuxvData()
4029{
4030 DataBufferSP buf;
4031 if (m_gdb_comm.GetQXferAuxvReadSupported())
4032 {
4033 std::string response_string;
4034 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success)
4035 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length()));
4036 }
4037 return buf;
4038}
4039
Jason Molenda705b1802014-06-13 02:37:02 +00004040StructuredData::ObjectSP
4041ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid)
4042{
4043 StructuredData::ObjectSP object_sp;
4044
4045 if (m_gdb_comm.GetThreadExtendedInfoSupported())
4046 {
4047 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4048 SystemRuntime *runtime = GetSystemRuntime();
4049 if (runtime)
4050 {
4051 runtime->AddThreadExtendedInfoPacketHints (args_dict);
4052 }
4053 args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid);
4054
4055 StreamString packet;
4056 packet << "jThreadExtendedInfo:";
4057 args_dict->Dump (packet);
4058
4059 // FIXME the final character of a JSON dictionary, '}', is the escape
4060 // character in gdb-remote binary mode. lldb currently doesn't escape
4061 // these characters in its packet output -- so we add the quoted version
4062 // of the } character here manually in case we talk to a debugserver which
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004063 // un-escapes the characters at packet read time.
Jason Molenda705b1802014-06-13 02:37:02 +00004064 packet << (char) (0x7d ^ 0x20);
4065
4066 StringExtractorGDBRemote response;
4067 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4068 {
4069 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4070 if (response_type == StringExtractorGDBRemote::eResponse)
4071 {
4072 if (!response.Empty())
4073 {
Jason Molenda20ee21b2015-07-10 23:15:22 +00004074 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4075 }
4076 }
4077 }
4078 }
4079 return object_sp;
4080}
4081
4082StructuredData::ObjectSP
4083ProcessGDBRemote::GetLoadedDynamicLibrariesInfos (lldb::addr_t image_list_address, lldb::addr_t image_count)
4084{
4085 StructuredData::ObjectSP object_sp;
4086
4087 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported())
4088 {
4089 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4090 args_dict->GetAsDictionary()->AddIntegerItem ("image_list_address", image_list_address);
4091 args_dict->GetAsDictionary()->AddIntegerItem ("image_count", image_count);
4092
4093 StreamString packet;
4094 packet << "jGetLoadedDynamicLibrariesInfos:";
4095 args_dict->Dump (packet);
4096
4097 // FIXME the final character of a JSON dictionary, '}', is the escape
4098 // character in gdb-remote binary mode. lldb currently doesn't escape
4099 // these characters in its packet output -- so we add the quoted version
4100 // of the } character here manually in case we talk to a debugserver which
4101 // un-escapes the characters at packet read time.
4102 packet << (char) (0x7d ^ 0x20);
4103
4104 StringExtractorGDBRemote response;
4105 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4106 {
4107 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4108 if (response_type == StringExtractorGDBRemote::eResponse)
4109 {
4110 if (!response.Empty())
4111 {
Jason Molenda705b1802014-06-13 02:37:02 +00004112 // The packet has already had the 0x7d xor quoting stripped out at the
4113 // GDBRemoteCommunication packet receive level.
4114 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4115 }
4116 }
4117 }
4118 }
4119 return object_sp;
4120}
4121
Jason Molenda20ee21b2015-07-10 23:15:22 +00004122
Jason Molenda6076bf42014-05-06 04:34:52 +00004123// Establish the largest memory read/write payloads we should use.
4124// If the remote stub has a max packet size, stay under that size.
4125//
4126// If the remote stub's max packet size is crazy large, use a
4127// reasonable largeish default.
4128//
4129// If the remote stub doesn't advertise a max packet size, use a
4130// conservative default.
4131
4132void
4133ProcessGDBRemote::GetMaxMemorySize()
4134{
4135 const uint64_t reasonable_largeish_default = 128 * 1024;
4136 const uint64_t conservative_default = 512;
4137
4138 if (m_max_memory_size == 0)
4139 {
4140 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4141 if (stub_max_size != UINT64_MAX && stub_max_size != 0)
4142 {
4143 // Save the stub's claimed maximum packet size
4144 m_remote_stub_max_memory_size = stub_max_size;
4145
4146 // Even if the stub says it can support ginormous packets,
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004147 // don't exceed our reasonable largeish default packet size.
Jason Molenda6076bf42014-05-06 04:34:52 +00004148 if (stub_max_size > reasonable_largeish_default)
4149 {
4150 stub_max_size = reasonable_largeish_default;
4151 }
4152
4153 m_max_memory_size = stub_max_size;
4154 }
4155 else
4156 {
4157 m_max_memory_size = conservative_default;
4158 }
4159 }
4160}
4161
4162void
4163ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max)
4164{
4165 if (user_specified_max != 0)
4166 {
4167 GetMaxMemorySize ();
4168
4169 if (m_remote_stub_max_memory_size != 0)
4170 {
4171 if (m_remote_stub_max_memory_size < user_specified_max)
4172 {
4173 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a packet size too big, go as big
4174 // as the remote stub says we can go.
4175 }
4176 else
4177 {
4178 m_max_memory_size = user_specified_max; // user's packet size is good
4179 }
4180 }
4181 else
4182 {
4183 m_max_memory_size = user_specified_max; // user's packet size is probably fine
4184 }
4185 }
4186}
4187
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004188bool
4189ProcessGDBRemote::GetModuleSpec(const FileSpec& module_file_spec,
4190 const ArchSpec& arch,
4191 ModuleSpec &module_spec)
4192{
4193 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PLATFORM);
4194
4195 if (!m_gdb_comm.GetModuleInfo (module_file_spec, arch, module_spec))
4196 {
4197 if (log)
4198 log->Printf ("ProcessGDBRemote::%s - failed to get module info for %s:%s",
4199 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4200 arch.GetTriple ().getTriple ().c_str ());
4201 return false;
4202 }
4203
4204 if (log)
4205 {
4206 StreamString stream;
4207 module_spec.Dump (stream);
4208 log->Printf ("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4209 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4210 arch.GetTriple ().getTriple ().c_str (), stream.GetString ().c_str ());
4211 }
4212
4213 return true;
4214}
4215
Colin Rileyc3c95b22015-04-16 15:51:33 +00004216namespace {
4217
4218typedef std::vector<std::string> stringVec;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004219
4220typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004221struct RegisterSetInfo
4222{
4223 ConstString name;
4224};
Colin Rileyc3c95b22015-04-16 15:51:33 +00004225
Greg Claytond04f0ed2015-05-26 18:00:51 +00004226typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4227
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004228struct GdbServerTargetInfo
4229{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004230 std::string arch;
4231 std::string osabi;
4232 stringVec includes;
4233 RegisterSetMap reg_set_map;
4234 XMLNode feature_node;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004235};
Greg Claytond04f0ed2015-05-26 18:00:51 +00004236
Colin Rileyc3c95b22015-04-16 15:51:33 +00004237bool
Greg Claytond04f0ed2015-05-26 18:00:51 +00004238ParseRegisters (XMLNode feature_node, GdbServerTargetInfo &target_info, GDBRemoteDynamicRegisterInfo &dyn_reg_info)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004239{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004240 if (!feature_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004241 return false;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004242
4243 uint32_t prev_reg_num = 0;
4244 uint32_t reg_offset = 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004245
Greg Claytond04f0ed2015-05-26 18:00:51 +00004246 feature_node.ForEachChildElementWithName("reg", [&target_info, &dyn_reg_info, &prev_reg_num, &reg_offset](const XMLNode &reg_node) -> bool {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004247 std::string gdb_group;
4248 std::string gdb_type;
4249 ConstString reg_name;
4250 ConstString alt_name;
4251 ConstString set_name;
4252 std::vector<uint32_t> value_regs;
4253 std::vector<uint32_t> invalidate_regs;
4254 bool encoding_set = false;
4255 bool format_set = false;
4256 RegisterInfo reg_info = { NULL, // Name
4257 NULL, // Alt name
4258 0, // byte size
4259 reg_offset, // offset
4260 eEncodingUint, // encoding
4261 eFormatHex, // formate
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004262 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004263 LLDB_INVALID_REGNUM, // GCC reg num
4264 LLDB_INVALID_REGNUM, // DWARF reg num
4265 LLDB_INVALID_REGNUM, // generic reg num
4266 prev_reg_num, // GDB reg num
4267 prev_reg_num // native register number
4268 },
4269 NULL,
4270 NULL
4271 };
4272
Ewan Crawford682e8422015-06-26 09:38:27 +00004273 reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type, &reg_name, &alt_name, &set_name, &value_regs, &invalidate_regs, &encoding_set, &format_set, &reg_info, &prev_reg_num, &reg_offset](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004274 if (name == "name")
4275 {
4276 reg_name.SetString(value);
4277 }
4278 else if (name == "bitsize")
4279 {
4280 reg_info.byte_size = StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
4281 }
4282 else if (name == "type")
4283 {
4284 gdb_type = value.str();
4285 }
4286 else if (name == "group")
4287 {
4288 gdb_group = value.str();
4289 }
4290 else if (name == "regnum")
4291 {
4292 const uint32_t regnum = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4293 if (regnum != LLDB_INVALID_REGNUM)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004294 {
Jason Molendaa18f7072015-08-15 01:21:01 +00004295 reg_info.kinds[eRegisterKindStabs] = regnum;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004296 reg_info.kinds[eRegisterKindLLDB] = regnum;
4297 prev_reg_num = regnum;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004298 }
4299 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004300 else if (name == "offset")
4301 {
4302 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4303 }
4304 else if (name == "altname")
4305 {
4306 alt_name.SetString(value);
4307 }
4308 else if (name == "encoding")
4309 {
4310 encoding_set = true;
4311 reg_info.encoding = Args::StringToEncoding (value.data(), eEncodingUint);
4312 }
4313 else if (name == "format")
4314 {
4315 format_set = true;
4316 Format format = eFormatInvalid;
4317 if (Args::StringToFormat (value.data(), format, NULL).Success())
4318 reg_info.format = format;
4319 else if (value == "vector-sint8")
4320 reg_info.format = eFormatVectorOfSInt8;
4321 else if (value == "vector-uint8")
4322 reg_info.format = eFormatVectorOfUInt8;
4323 else if (value == "vector-sint16")
4324 reg_info.format = eFormatVectorOfSInt16;
4325 else if (value == "vector-uint16")
4326 reg_info.format = eFormatVectorOfUInt16;
4327 else if (value == "vector-sint32")
4328 reg_info.format = eFormatVectorOfSInt32;
4329 else if (value == "vector-uint32")
4330 reg_info.format = eFormatVectorOfUInt32;
4331 else if (value == "vector-float32")
4332 reg_info.format = eFormatVectorOfFloat32;
4333 else if (value == "vector-uint128")
4334 reg_info.format = eFormatVectorOfUInt128;
4335 }
4336 else if (name == "group_id")
4337 {
4338 const uint32_t set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4339 RegisterSetMap::const_iterator pos = target_info.reg_set_map.find(set_id);
4340 if (pos != target_info.reg_set_map.end())
4341 set_name = pos->second.name;
4342 }
Jason Molendaa18f7072015-08-15 01:21:01 +00004343 else if (name == "gcc_regnum" || name == "ehframe_regnum")
Greg Claytond04f0ed2015-05-26 18:00:51 +00004344 {
Jason Molendaa18f7072015-08-15 01:21:01 +00004345 reg_info.kinds[eRegisterKindEHFrame] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004346 }
4347 else if (name == "dwarf_regnum")
4348 {
4349 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4350 }
4351 else if (name == "generic")
4352 {
4353 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister(value.data());
4354 }
4355 else if (name == "value_regnums")
4356 {
4357 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
4358 }
4359 else if (name == "invalidate_regnums")
4360 {
4361 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
4362 }
4363 else
4364 {
4365 printf("unhandled attribute %s = %s\n", name.data(), value.data());
4366 }
4367 return true; // Keep iterating through all attributes
4368 });
4369
4370 if (!gdb_type.empty() && !(encoding_set || format_set))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004371 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004372 if (gdb_type.find("int") == 0)
4373 {
4374 reg_info.format = eFormatHex;
4375 reg_info.encoding = eEncodingUint;
4376 }
4377 else if (gdb_type == "data_ptr" || gdb_type == "code_ptr")
4378 {
4379 reg_info.format = eFormatAddressInfo;
4380 reg_info.encoding = eEncodingUint;
4381 }
4382 else if (gdb_type == "i387_ext" || gdb_type == "float")
4383 {
4384 reg_info.format = eFormatFloat;
4385 reg_info.encoding = eEncodingIEEE754;
4386 }
Colin Rileyc3c95b22015-04-16 15:51:33 +00004387 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004388
4389 // Only update the register set name if we didn't get a "reg_set" attribute.
4390 // "set_name" will be empty if we didn't have a "reg_set" attribute.
4391 if (!set_name && !gdb_group.empty())
4392 set_name.SetCString(gdb_group.c_str());
4393
4394 reg_info.byte_offset = reg_offset;
4395 assert (reg_info.byte_size != 0);
4396 reg_offset += reg_info.byte_size;
4397 if (!value_regs.empty())
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004398 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004399 value_regs.push_back(LLDB_INVALID_REGNUM);
4400 reg_info.value_regs = value_regs.data();
Colin Rileyc3c95b22015-04-16 15:51:33 +00004401 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004402 if (!invalidate_regs.empty())
4403 {
4404 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
4405 reg_info.invalidate_regs = invalidate_regs.data();
4406 }
4407
Ewan Crawford682e8422015-06-26 09:38:27 +00004408 ++prev_reg_num;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004409 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
4410
4411 return true; // Keep iterating through all "reg" elements
4412 });
Colin Rileyc3c95b22015-04-16 15:51:33 +00004413 return true;
4414}
Greg Claytond04f0ed2015-05-26 18:00:51 +00004415
Colin Rileyc3c95b22015-04-16 15:51:33 +00004416} // namespace {}
4417
Colin Rileyc3c95b22015-04-16 15:51:33 +00004418
4419// query the target of gdb-remote for extended target information
4420// return: 'true' on success
4421// 'false' on failure
4422bool
Aidan Doddsc0c83852015-05-08 09:36:31 +00004423ProcessGDBRemote::GetGDBServerRegisterInfo ()
Colin Rileyc3c95b22015-04-16 15:51:33 +00004424{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004425 // Make sure LLDB has an XML parser it can use first
4426 if (!XMLDocument::XMLEnabled())
4427 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004428
4429 // redirect libxml2's error handler since the default prints to stdout
Colin Rileyc3c95b22015-04-16 15:51:33 +00004430
4431 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004432
4433 // check that we have extended feature read support
4434 if ( !comm.GetQXferFeaturesReadSupported( ) )
4435 return false;
4436
4437 // request the target xml file
4438 std::string raw;
4439 lldb_private::Error lldberr;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004440 if (!comm.ReadExtFeature(ConstString("features"),
4441 ConstString("target.xml"),
4442 raw,
4443 lldberr))
4444 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00004445 return false;
4446 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004447
Colin Rileyc3c95b22015-04-16 15:51:33 +00004448
Greg Claytond04f0ed2015-05-26 18:00:51 +00004449 XMLDocument xml_document;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004450
Greg Claytond04f0ed2015-05-26 18:00:51 +00004451 if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml"))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004452 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004453 GdbServerTargetInfo target_info;
4454
4455 XMLNode target_node = xml_document.GetRootElement("target");
4456 if (target_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004457 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004458 XMLNode feature_node;
4459 target_node.ForEachChildElement([&target_info, this, &feature_node](const XMLNode &node) -> bool
4460 {
4461 llvm::StringRef name = node.GetName();
4462 if (name == "architecture")
4463 {
4464 node.GetElementText(target_info.arch);
4465 }
4466 else if (name == "osabi")
4467 {
4468 node.GetElementText(target_info.osabi);
4469 }
Ewan Crawford682e8422015-06-26 09:38:27 +00004470 else if (name == "xi:include" || name == "include")
Greg Claytond04f0ed2015-05-26 18:00:51 +00004471 {
4472 llvm::StringRef href = node.GetAttributeValue("href");
4473 if (!href.empty())
4474 target_info.includes.push_back(href.str());
4475 }
4476 else if (name == "feature")
4477 {
4478 feature_node = node;
4479 }
4480 else if (name == "groups")
4481 {
4482 node.ForEachChildElementWithName("group", [&target_info](const XMLNode &node) -> bool {
4483 uint32_t set_id = UINT32_MAX;
4484 RegisterSetInfo set_info;
4485
4486 node.ForEachAttribute([&set_id, &set_info](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
4487 if (name == "id")
4488 set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4489 if (name == "name")
4490 set_info.name = ConstString(value);
4491 return true; // Keep iterating through all attributes
4492 });
4493
4494 if (set_id != UINT32_MAX)
4495 target_info.reg_set_map[set_id] = set_info;
4496 return true; // Keep iterating through all "group" elements
4497 });
4498 }
4499 return true; // Keep iterating through all children of the target_node
4500 });
4501
4502 if (feature_node)
4503 {
4504 ParseRegisters(feature_node, target_info, this->m_register_info);
4505 }
4506
4507 for (const auto &include : target_info.includes)
4508 {
4509 // request register file
4510 std::string xml_data;
4511 if (!comm.ReadExtFeature(ConstString("features"),
4512 ConstString(include),
4513 xml_data,
4514 lldberr))
4515 continue;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004516
Greg Claytond04f0ed2015-05-26 18:00:51 +00004517 XMLDocument include_xml_document;
4518 include_xml_document.ParseMemory(xml_data.data(), xml_data.size(), include.c_str());
4519 XMLNode include_feature_node = include_xml_document.GetRootElement("feature");
4520 if (include_feature_node)
4521 {
4522 ParseRegisters(include_feature_node, target_info, this->m_register_info);
4523 }
4524 }
4525 this->m_register_info.Finalize(GetTarget().GetArchitecture());
Colin Rileyc3c95b22015-04-16 15:51:33 +00004526 }
4527 }
4528
Greg Claytond04f0ed2015-05-26 18:00:51 +00004529 return m_register_info.GetNumRegisters() > 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004530}
4531
Aidan Doddsc0c83852015-05-08 09:36:31 +00004532Error
4533ProcessGDBRemote::GetLoadedModuleList (GDBLoadedModuleInfoList & list)
4534{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004535 // Make sure LLDB has an XML parser it can use first
4536 if (!XMLDocument::XMLEnabled())
4537 return Error (0, ErrorType::eErrorTypeGeneric);
4538
Aidan Doddsc0c83852015-05-08 09:36:31 +00004539 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS);
4540 if (log)
4541 log->Printf ("ProcessGDBRemote::%s", __FUNCTION__);
4542
Aidan Doddsc0c83852015-05-08 09:36:31 +00004543 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004544
4545 // check that we have extended feature read support
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004546 if (comm.GetQXferLibrariesSVR4ReadSupported ()) {
4547 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004548
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004549 // request the loaded library list
4550 std::string raw;
4551 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004552
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004553 if (!comm.ReadExtFeature (ConstString ("libraries-svr4"), ConstString (""), raw, lldberr))
4554 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004555
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004556 // parse the xml file in memory
4557 if (log)
4558 log->Printf ("parsing: %s", raw.c_str());
4559 XMLDocument doc;
4560
4561 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4562 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004563
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004564 XMLNode root_element = doc.GetRootElement("library-list-svr4");
4565 if (!root_element)
4566 return Error();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004567
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004568 // main link map structure
4569 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4570 if (!main_lm.empty())
4571 {
4572 list.m_link_map = StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
4573 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004574
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004575 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
Aidan Doddsc0c83852015-05-08 09:36:31 +00004576
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004577 GDBLoadedModuleInfoList::LoadedModuleInfo module;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004578
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004579 library.ForEachAttribute([log, &module](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004580
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004581 if (name == "name")
4582 module.set_name (value.str());
4583 else if (name == "lm")
4584 {
4585 // the address of the link_map struct.
4586 module.set_link_map(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4587 }
4588 else if (name == "l_addr")
4589 {
4590 // the displacement as read from the field 'l_addr' of the link_map struct.
4591 module.set_base(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4592
4593 }
4594 else if (name == "l_ld")
4595 {
4596 // the memory address of the libraries PT_DYAMIC section.
4597 module.set_dynamic(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4598 }
4599
4600 return true; // Keep iterating over all properties of "library"
4601 });
4602
4603 if (log)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004604 {
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004605 std::string name;
4606 lldb::addr_t lm=0, base=0, ld=0;
4607
4608 module.get_name (name);
4609 module.get_link_map (lm);
4610 module.get_base (base);
4611 module.get_dynamic (ld);
4612
4613 log->Printf ("found (link_map:0x08%" PRIx64 ", base:0x08%" PRIx64 ", ld:0x08%" PRIx64 ", name:'%s')", lm, base, ld, name.c_str());
Aidan Doddsc0c83852015-05-08 09:36:31 +00004614 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004615
4616 list.add (module);
4617 return true; // Keep iterating over all "library" elements in the root node
Greg Claytond04f0ed2015-05-26 18:00:51 +00004618 });
Aidan Doddsc0c83852015-05-08 09:36:31 +00004619
4620 if (log)
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004621 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4622 } else if (comm.GetQXferLibrariesReadSupported ()) {
4623 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004624
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004625 // request the loaded library list
4626 std::string raw;
4627 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004628
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004629 if (!comm.ReadExtFeature (ConstString ("libraries"), ConstString (""), raw, lldberr))
4630 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004631
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004632 if (log)
4633 log->Printf ("parsing: %s", raw.c_str());
4634 XMLDocument doc;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004635
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004636 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4637 return Error (0, ErrorType::eErrorTypeGeneric);
4638
4639 XMLNode root_element = doc.GetRootElement("library-list");
4640 if (!root_element)
4641 return Error();
4642
4643 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
4644 GDBLoadedModuleInfoList::LoadedModuleInfo module;
4645
4646 llvm::StringRef name = library.GetAttributeValue("name");
4647 module.set_name(name.str());
4648
4649 // The base address of a given library will be the address of its
4650 // first section. Most remotes send only one section for Windows
4651 // targets for example.
4652 const XMLNode &section = library.FindFirstChildElementWithName("section");
4653 llvm::StringRef address = section.GetAttributeValue("address");
4654 module.set_base(StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0));
4655
4656 if (log)
4657 {
4658 std::string name;
4659 lldb::addr_t base = 0;
4660 module.get_name (name);
4661 module.get_base (base);
4662
4663 log->Printf ("found (base:0x%" PRIx64 ", name:'%s')", base, name.c_str());
4664 }
4665
4666 list.add (module);
4667 return true; // Keep iterating over all "library" elements in the root node
4668 });
4669
4670 if (log)
4671 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4672 } else {
4673 return Error (0, ErrorType::eErrorTypeGeneric);
4674 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004675
4676 return Error();
4677}
4678
Aidan Doddsc0c83852015-05-08 09:36:31 +00004679lldb::ModuleSP
4680ProcessGDBRemote::LoadModuleAtAddress (const FileSpec &file, lldb::addr_t base_addr)
4681{
4682 Target &target = m_process->GetTarget();
4683 ModuleList &modules = target.GetImages();
4684 ModuleSP module_sp;
4685
4686 bool changed = false;
4687
4688 ModuleSpec module_spec (file, target.GetArchitecture());
4689 if ((module_sp = modules.FindFirstModule (module_spec)))
4690 {
4691 module_sp->SetLoadAddress (target, base_addr, true, changed);
4692 }
4693 else if ((module_sp = target.GetSharedModule (module_spec)))
4694 {
4695 module_sp->SetLoadAddress (target, base_addr, true, changed);
4696 }
4697
4698 return module_sp;
4699}
4700
4701size_t
4702ProcessGDBRemote::LoadModules ()
4703{
4704 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4705
4706 // request a list of loaded libraries from GDBServer
4707 GDBLoadedModuleInfoList module_list;
4708 if (GetLoadedModuleList (module_list).Fail())
4709 return 0;
4710
4711 // get a list of all the modules
4712 ModuleList new_modules;
4713
4714 for (GDBLoadedModuleInfoList::LoadedModuleInfo & modInfo : module_list.m_list)
4715 {
4716 std::string mod_name;
4717 lldb::addr_t mod_base;
4718
4719 bool valid = true;
4720 valid &= modInfo.get_name (mod_name);
4721 valid &= modInfo.get_base (mod_base);
4722 if (!valid)
4723 continue;
4724
4725 // hack (cleaner way to get file name only?) (win/unix compat?)
Vince Harron4cc8d202015-05-10 08:33:58 +00004726 size_t marker = mod_name.rfind ('/');
Aidan Doddsc0c83852015-05-08 09:36:31 +00004727 if (marker == std::string::npos)
4728 marker = 0;
4729 else
4730 marker += 1;
4731
4732 FileSpec file (mod_name.c_str()+marker, true);
4733 lldb::ModuleSP module_sp = LoadModuleAtAddress (file, mod_base);
4734
4735 if (module_sp.get())
4736 new_modules.Append (module_sp);
4737 }
4738
4739 if (new_modules.GetSize() > 0)
4740 {
4741 Target & target = m_target;
4742
4743 new_modules.ForEach ([&target](const lldb::ModuleSP module_sp) -> bool
4744 {
4745 lldb_private::ObjectFile * obj = module_sp->GetObjectFile ();
4746 if (!obj)
4747 return true;
4748
4749 if (obj->GetType () != ObjectFile::Type::eTypeExecutable)
4750 return true;
4751
4752 lldb::ModuleSP module_copy_sp = module_sp;
4753 target.SetExecutableModule (module_copy_sp, false);
4754 return false;
4755 });
4756
4757 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4758 loaded_modules.AppendIfNeeded (new_modules);
4759 m_process->GetTarget().ModulesDidLoad (new_modules);
4760 }
4761
4762 return new_modules.GetSize();
4763}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004764
Tamas Berghammer783bfc82015-06-18 20:43:56 +00004765Error
4766ProcessGDBRemote::GetFileLoadAddress(const FileSpec& file, bool& is_loaded, lldb::addr_t& load_addr)
4767{
4768 is_loaded = false;
4769 load_addr = LLDB_INVALID_ADDRESS;
4770
4771 std::string file_path = file.GetPath(false);
4772 if (file_path.empty ())
4773 return Error("Empty file name specified");
4774
4775 StreamString packet;
4776 packet.PutCString("qFileLoadAddress:");
4777 packet.PutCStringAsRawHex8(file_path.c_str());
4778
4779 StringExtractorGDBRemote response;
4780 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString().c_str(), response, false) != GDBRemoteCommunication::PacketResult::Success)
4781 return Error("Sending qFileLoadAddress packet failed");
4782
4783 if (response.IsErrorResponse())
4784 {
4785 if (response.GetError() == 1)
4786 {
4787 // The file is not loaded into the inferior
4788 is_loaded = false;
4789 load_addr = LLDB_INVALID_ADDRESS;
4790 return Error();
4791 }
4792
4793 return Error("Fetching file load address from remote server returned an error");
4794 }
4795
4796 if (response.IsNormalResponse())
4797 {
4798 is_loaded = true;
4799 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
4800 return Error();
4801 }
4802
4803 return Error("Unknown error happened during sending the load address packet");
4804}
4805
Greg Clayton0b90be12015-06-23 21:27:50 +00004806
4807void
4808ProcessGDBRemote::ModulesDidLoad (ModuleList &module_list)
4809{
4810 // We must call the lldb_private::Process::ModulesDidLoad () first before we do anything
4811 Process::ModulesDidLoad (module_list);
4812
4813 // After loading shared libraries, we can ask our remote GDB server if
4814 // it needs any symbols.
4815 m_gdb_comm.ServeSymbolLookups(this);
4816}
4817
4818
Greg Claytone034a042015-05-21 20:52:06 +00004819class CommandObjectProcessGDBRemoteSpeedTest: public CommandObjectParsed
4820{
4821public:
4822 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter) :
4823 CommandObjectParsed (interpreter,
4824 "process plugin packet speed-test",
4825 "Tests packet speeds of various sizes to determine the performance characteristics of the GDB remote connection. ",
4826 NULL),
4827 m_option_group (interpreter),
4828 m_num_packets (LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount, "The number of packets to send of each varying size (default is 1000).", 1000),
4829 m_max_send (LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount, "The maximum number of bytes to send in a packet. Sizes increase in powers of 2 while the size is less than or equal to this option value. (default 1024).", 1024),
4830 m_max_recv (LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount, "The maximum number of bytes to receive in a packet. Sizes increase in powers of 2 while the size is less than or equal to this option value. (default 1024).", 1024),
4831 m_json (LLDB_OPT_SET_1, false, "json", 'j', "Print the output as JSON data for easy parsing.", false, true)
4832 {
4833 m_option_group.Append (&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4834 m_option_group.Append (&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4835 m_option_group.Append (&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4836 m_option_group.Append (&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4837 m_option_group.Finalize();
4838 }
4839
4840 ~CommandObjectProcessGDBRemoteSpeedTest ()
4841 {
4842 }
4843
4844
4845 Options *
4846 GetOptions () override
4847 {
4848 return &m_option_group;
4849 }
4850
4851 bool
4852 DoExecute (Args& command, CommandReturnObject &result) override
4853 {
4854 const size_t argc = command.GetArgumentCount();
4855 if (argc == 0)
4856 {
4857 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4858 if (process)
4859 {
4860 StreamSP output_stream_sp (m_interpreter.GetDebugger().GetAsyncOutputStream());
4861 result.SetImmediateOutputStream (output_stream_sp);
4862
4863 const uint32_t num_packets = (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
4864 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
4865 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
4866 const bool json = m_json.GetOptionValue().GetCurrentValue();
4867 if (output_stream_sp)
4868 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, *output_stream_sp);
4869 else
4870 {
4871 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, result.GetOutputStream());
4872 }
4873 result.SetStatus (eReturnStatusSuccessFinishResult);
4874 return true;
4875 }
4876 }
4877 else
4878 {
4879 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
4880 }
4881 result.SetStatus (eReturnStatusFailed);
4882 return false;
4883 }
4884protected:
4885 OptionGroupOptions m_option_group;
4886 OptionGroupUInt64 m_num_packets;
4887 OptionGroupUInt64 m_max_send;
4888 OptionGroupUInt64 m_max_recv;
4889 OptionGroupBoolean m_json;
4890
4891};
4892
Greg Clayton02686b82012-10-15 22:42:16 +00004893class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00004894{
4895private:
4896
4897public:
Greg Clayton02686b82012-10-15 22:42:16 +00004898 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00004899 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00004900 "process plugin packet history",
4901 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00004902 NULL)
4903 {
4904 }
4905
Greg Clayton02686b82012-10-15 22:42:16 +00004906 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton998255b2012-10-13 02:07:45 +00004907 {
4908 }
4909
4910 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004911 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton998255b2012-10-13 02:07:45 +00004912 {
Greg Clayton02686b82012-10-15 22:42:16 +00004913 const size_t argc = command.GetArgumentCount();
4914 if (argc == 0)
4915 {
4916 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4917 if (process)
4918 {
4919 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
4920 result.SetStatus (eReturnStatusSuccessFinishResult);
4921 return true;
4922 }
4923 }
4924 else
4925 {
4926 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
4927 }
4928 result.SetStatus (eReturnStatusFailed);
4929 return false;
4930 }
4931};
4932
Jason Molenda6076bf42014-05-06 04:34:52 +00004933class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed
4934{
4935private:
4936
4937public:
4938 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) :
4939 CommandObjectParsed (interpreter,
4940 "process plugin packet xfer-size",
4941 "Maximum size that lldb will try to read/write one one chunk.",
4942 NULL)
4943 {
4944 }
4945
4946 ~CommandObjectProcessGDBRemotePacketXferSize ()
4947 {
4948 }
4949
4950 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004951 DoExecute (Args& command, CommandReturnObject &result) override
Jason Molenda6076bf42014-05-06 04:34:52 +00004952 {
4953 const size_t argc = command.GetArgumentCount();
4954 if (argc == 0)
4955 {
4956 result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str());
4957 result.SetStatus (eReturnStatusFailed);
4958 return false;
4959 }
4960
4961 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4962 if (process)
4963 {
4964 const char *packet_size = command.GetArgumentAtIndex(0);
4965 errno = 0;
4966 uint64_t user_specified_max = strtoul (packet_size, NULL, 10);
4967 if (errno == 0 && user_specified_max != 0)
4968 {
4969 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max);
4970 result.SetStatus (eReturnStatusSuccessFinishResult);
4971 return true;
4972 }
4973 }
4974 result.SetStatus (eReturnStatusFailed);
4975 return false;
4976 }
4977};
4978
4979
Greg Clayton02686b82012-10-15 22:42:16 +00004980class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
4981{
4982private:
4983
4984public:
4985 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
4986 CommandObjectParsed (interpreter,
4987 "process plugin packet send",
4988 "Send a custom packet through the GDB remote protocol and print the answer. "
4989 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
4990 NULL)
4991 {
4992 }
4993
4994 ~CommandObjectProcessGDBRemotePacketSend ()
4995 {
4996 }
4997
4998 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004999 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton02686b82012-10-15 22:42:16 +00005000 {
5001 const size_t argc = command.GetArgumentCount();
5002 if (argc == 0)
5003 {
5004 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
5005 result.SetStatus (eReturnStatusFailed);
5006 return false;
5007 }
5008
5009 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5010 if (process)
5011 {
Han Ming Ong84145852012-11-26 20:42:03 +00005012 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00005013 {
Han Ming Ong84145852012-11-26 20:42:03 +00005014 const char *packet_cstr = command.GetArgumentAtIndex(0);
5015 bool send_async = true;
5016 StringExtractorGDBRemote response;
5017 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
5018 result.SetStatus (eReturnStatusSuccessFinishResult);
5019 Stream &output_strm = result.GetOutputStream();
5020 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00005021 std::string &response_str = response.GetStringRef();
5022
Han Ming Ong399289e2013-06-21 19:56:59 +00005023 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00005024 {
5025 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
5026 }
5027
Han Ming Ong84145852012-11-26 20:42:03 +00005028 if (response_str.empty())
5029 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
5030 else
5031 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00005032 }
Greg Clayton02686b82012-10-15 22:42:16 +00005033 }
Greg Clayton998255b2012-10-13 02:07:45 +00005034 return true;
5035 }
5036};
5037
Greg Claytonba4a0a52013-02-01 23:03:47 +00005038class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
5039{
5040private:
5041
5042public:
5043 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
5044 CommandObjectRaw (interpreter,
5045 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00005046 "Send a qRcmd packet through the GDB remote protocol and print the response."
5047 "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 +00005048 NULL)
5049 {
5050 }
5051
5052 ~CommandObjectProcessGDBRemotePacketMonitor ()
5053 {
5054 }
5055
5056 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005057 DoExecute (const char *command, CommandReturnObject &result) override
Greg Claytonba4a0a52013-02-01 23:03:47 +00005058 {
5059 if (command == NULL || command[0] == '\0')
5060 {
5061 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
5062 result.SetStatus (eReturnStatusFailed);
5063 return false;
5064 }
5065
5066 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5067 if (process)
5068 {
5069 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00005070 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00005071 packet.PutBytesAsRawHex8(command, strlen(command));
5072 const char *packet_cstr = packet.GetString().c_str();
5073
5074 bool send_async = true;
5075 StringExtractorGDBRemote response;
5076 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
5077 result.SetStatus (eReturnStatusSuccessFinishResult);
5078 Stream &output_strm = result.GetOutputStream();
5079 output_strm.Printf (" packet: %s\n", packet_cstr);
5080 const std::string &response_str = response.GetStringRef();
5081
5082 if (response_str.empty())
5083 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
5084 else
5085 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
5086 }
5087 return true;
5088 }
5089};
5090
Greg Clayton02686b82012-10-15 22:42:16 +00005091class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
5092{
5093private:
5094
5095public:
5096 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
5097 CommandObjectMultiword (interpreter,
5098 "process plugin packet",
5099 "Commands that deal with GDB remote packets.",
5100 NULL)
5101 {
5102 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
5103 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00005104 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Jason Molenda6076bf42014-05-06 04:34:52 +00005105 LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter)));
Greg Claytone034a042015-05-21 20:52:06 +00005106 LoadSubCommand ("speed-test", CommandObjectSP (new CommandObjectProcessGDBRemoteSpeedTest (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00005107 }
5108
5109 ~CommandObjectProcessGDBRemotePacket ()
5110 {
5111 }
5112};
Greg Clayton998255b2012-10-13 02:07:45 +00005113
5114class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
5115{
5116public:
5117 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
5118 CommandObjectMultiword (interpreter,
5119 "process plugin",
5120 "A set of commands for operating on a ProcessGDBRemote process.",
5121 "process plugin <subcommand> [<subcommand-options>]")
5122 {
5123 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
5124 }
5125
5126 ~CommandObjectMultiwordProcessGDBRemote ()
5127 {
5128 }
5129};
5130
Greg Clayton998255b2012-10-13 02:07:45 +00005131CommandObject *
5132ProcessGDBRemote::GetPluginCommandObject()
5133{
5134 if (!m_command_sp)
5135 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
5136 return m_command_sp.get();
5137}