blob: f6236f03b8a95bc2cdd4a0281fe78d7b0fe50b5e [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))
532 return;
533 }
534
Greg Claytond04f0ed2015-05-26 18:00:51 +0000535 if (GetGDBServerRegisterInfo ())
536 return;
537
538 char packet[128];
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000539 uint32_t reg_offset = 0;
540 uint32_t reg_num = 0;
Greg Clayton23f59502012-07-17 03:23:13 +0000541 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Greg Clayton576d8832011-03-22 04:00:09 +0000542 response_type == StringExtractorGDBRemote::eResponse;
543 ++reg_num)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000544 {
Greg Clayton513c26c2011-01-29 07:10:55 +0000545 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
Andy Gibbsa297a972013-06-19 19:04:53 +0000546 assert (packet_len < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000547 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000548 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000549 {
Greg Clayton576d8832011-03-22 04:00:09 +0000550 response_type = response.GetResponseType();
551 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000552 {
553 std::string name;
554 std::string value;
555 ConstString reg_name;
556 ConstString alt_name;
557 ConstString set_name;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000558 std::vector<uint32_t> value_regs;
559 std::vector<uint32_t> invalidate_regs;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000560 RegisterInfo reg_info = { NULL, // Name
561 NULL, // Alt name
562 0, // byte size
563 reg_offset, // offset
564 eEncodingUint, // encoding
565 eFormatHex, // formate
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000566 {
567 LLDB_INVALID_REGNUM, // GCC reg num
568 LLDB_INVALID_REGNUM, // DWARF reg num
569 LLDB_INVALID_REGNUM, // generic reg num
Jason Molendafbcb7f22010-09-10 07:49:16 +0000570 reg_num, // GDB reg num
571 reg_num // native register number
Greg Clayton435d85a2012-02-29 19:27:27 +0000572 },
573 NULL,
574 NULL
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000575 };
576
577 while (response.GetNameColonValue(name, value))
578 {
579 if (name.compare("name") == 0)
580 {
581 reg_name.SetCString(value.c_str());
582 }
583 else if (name.compare("alt-name") == 0)
584 {
585 alt_name.SetCString(value.c_str());
586 }
587 else if (name.compare("bitsize") == 0)
588 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000589 reg_info.byte_size = StringConvert::ToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000590 }
591 else if (name.compare("offset") == 0)
592 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000593 uint32_t offset = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda743e86a2010-06-11 23:44:18 +0000594 if (reg_offset != offset)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000595 {
596 reg_offset = offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000597 }
598 }
599 else if (name.compare("encoding") == 0)
600 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000601 const Encoding encoding = Args::StringToEncoding (value.c_str());
602 if (encoding != eEncodingInvalid)
603 reg_info.encoding = encoding;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000604 }
605 else if (name.compare("format") == 0)
606 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000607 Format format = eFormatInvalid;
608 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
609 reg_info.format = format;
610 else if (value.compare("binary") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000611 reg_info.format = eFormatBinary;
612 else if (value.compare("decimal") == 0)
613 reg_info.format = eFormatDecimal;
614 else if (value.compare("hex") == 0)
615 reg_info.format = eFormatHex;
616 else if (value.compare("float") == 0)
617 reg_info.format = eFormatFloat;
618 else if (value.compare("vector-sint8") == 0)
619 reg_info.format = eFormatVectorOfSInt8;
620 else if (value.compare("vector-uint8") == 0)
621 reg_info.format = eFormatVectorOfUInt8;
622 else if (value.compare("vector-sint16") == 0)
623 reg_info.format = eFormatVectorOfSInt16;
624 else if (value.compare("vector-uint16") == 0)
625 reg_info.format = eFormatVectorOfUInt16;
626 else if (value.compare("vector-sint32") == 0)
627 reg_info.format = eFormatVectorOfSInt32;
628 else if (value.compare("vector-uint32") == 0)
629 reg_info.format = eFormatVectorOfUInt32;
630 else if (value.compare("vector-float32") == 0)
631 reg_info.format = eFormatVectorOfFloat32;
632 else if (value.compare("vector-uint128") == 0)
633 reg_info.format = eFormatVectorOfUInt128;
634 }
635 else if (name.compare("set") == 0)
636 {
637 set_name.SetCString(value.c_str());
638 }
639 else if (name.compare("gcc") == 0)
640 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000641 reg_info.kinds[eRegisterKindGCC] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000642 }
643 else if (name.compare("dwarf") == 0)
644 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000645 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000646 }
647 else if (name.compare("generic") == 0)
648 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000649 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000650 }
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000651 else if (name.compare("container-regs") == 0)
652 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000653 SplitCommaSeparatedRegisterNumberString(value, value_regs, 16);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000654 }
655 else if (name.compare("invalidate-regs") == 0)
656 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000657 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 16);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000658 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000659 }
660
Jason Molenda743e86a2010-06-11 23:44:18 +0000661 reg_info.byte_offset = reg_offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000662 assert (reg_info.byte_size != 0);
663 reg_offset += reg_info.byte_size;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000664 if (!value_regs.empty())
665 {
666 value_regs.push_back(LLDB_INVALID_REGNUM);
667 reg_info.value_regs = value_regs.data();
668 }
669 if (!invalidate_regs.empty())
670 {
671 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
672 reg_info.invalidate_regs = invalidate_regs.data();
673 }
674
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000675 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
676 }
Todd Fiala1a634402014-01-08 07:52:40 +0000677 else
678 {
679 break; // ensure exit before reg_num is incremented
680 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000681 }
682 else
683 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000684 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000685 }
686 }
687
Greg Claytond04f0ed2015-05-26 18:00:51 +0000688 if (m_register_info.GetNumRegisters() > 0)
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000689 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000690 m_register_info.Finalize(GetTarget().GetArchitecture());
691 return;
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000692 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000693
Johnny Chen2fa9de12012-05-14 18:44:23 +0000694 // We didn't get anything if the accumulated reg_num is zero. See if we are
695 // debugging ARM and fill with a hard coded register set until we can get an
696 // updated debugserver down on the devices.
697 // On the other hand, if the accumulated reg_num is positive, see if we can
698 // add composite registers to the existing primordial ones.
Greg Claytond04f0ed2015-05-26 18:00:51 +0000699 bool from_scratch = (m_register_info.GetNumRegisters() == 0);
Johnny Chen2fa9de12012-05-14 18:44:23 +0000700
701 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000702 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
703 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
704
705 // Use the process' architecture instead of the host arch, if available
706 ArchSpec remote_arch;
707 if (remote_process_arch.IsValid ())
708 remote_arch = remote_process_arch;
709 else
710 remote_arch = remote_host_arch;
711
Johnny Chen2fa9de12012-05-14 18:44:23 +0000712 if (!target_arch.IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000713 {
Johnny Chen2fa9de12012-05-14 18:44:23 +0000714 if (remote_arch.IsValid()
715 && remote_arch.GetMachine() == llvm::Triple::arm
716 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
717 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000718 }
Johnny Chen2fa9de12012-05-14 18:44:23 +0000719 else if (target_arch.GetMachine() == llvm::Triple::arm)
720 {
721 m_register_info.HardcodeARMRegisters(from_scratch);
722 }
723
724 // At this point, we can finalize our register info.
Greg Claytond04f0ed2015-05-26 18:00:51 +0000725 m_register_info.Finalize (GetTarget().GetArchitecture());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000726}
727
728Error
729ProcessGDBRemote::WillLaunch (Module* module)
730{
731 return WillLaunchOrAttach ();
732}
733
734Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000735ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000736{
737 return WillLaunchOrAttach ();
738}
739
740Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000741ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000742{
743 return WillLaunchOrAttach ();
744}
745
746Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000747ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +0000748{
Todd Fialaaf245d12014-06-30 21:05:18 +0000749 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Claytonb766a732011-02-04 01:58:07 +0000750 Error error (WillLaunchOrAttach ());
751
752 if (error.Fail())
753 return error;
754
Greg Clayton2289fa42011-04-30 01:09:13 +0000755 error = ConnectToDebugserver (remote_url);
Greg Claytonb766a732011-02-04 01:58:07 +0000756
757 if (error.Fail())
758 return error;
759 StartAsyncThread ();
760
Greg Claytonc574ede2011-03-10 02:26:48 +0000761 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonb766a732011-02-04 01:58:07 +0000762 if (pid == LLDB_INVALID_PROCESS_ID)
763 {
764 // We don't have a valid process ID, so note that we are connected
765 // and could now request to launch or attach, or get remote process
766 // listings...
767 SetPrivateState (eStateConnected);
768 }
769 else
770 {
771 // We have a valid process
772 SetID (pid);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000773 GetThreadList();
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000774 StringExtractorGDBRemote response;
775 if (m_gdb_comm.GetStopReply(response))
Greg Claytonb766a732011-02-04 01:58:07 +0000776 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000777 SetLastStopPacket(response);
Ewan Crawford78baa192015-05-13 09:18:18 +0000778
779 // '?' Packets must be handled differently in non-stop mode
780 if (GetTarget().GetNonStopModeEnabled())
781 HandleStopReplySequence();
782
Jason Molendac62bd7b2013-12-21 05:20:36 +0000783 if (!m_target.GetArchitecture().IsValid())
784 {
785 if (m_gdb_comm.GetProcessArchitecture().IsValid())
786 {
787 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
788 }
789 else
790 {
791 m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
792 }
Carlo Kok74389122013-10-14 07:09:13 +0000793 }
794
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000795 const StateType state = SetThreadStopInfo (response);
Greg Clayton2e309072015-07-17 23:42:28 +0000796 if (state != eStateInvalid)
Greg Claytonb766a732011-02-04 01:58:07 +0000797 {
798 SetPrivateState (state);
799 }
800 else
Daniel Malead01b2952012-11-29 21:49:15 +0000801 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 +0000802 }
803 else
Daniel Malead01b2952012-11-29 21:49:15 +0000804 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 +0000805 }
Jason Molenda16d127c2012-05-03 22:37:30 +0000806
Todd Fialaaf245d12014-06-30 21:05:18 +0000807 if (log)
808 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");
809
810
811 if (error.Success()
Jason Molenda16d127c2012-05-03 22:37:30 +0000812 && !GetTarget().GetArchitecture().IsValid()
813 && m_gdb_comm.GetHostArchitecture().IsValid())
814 {
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000815 // Prefer the *process'* architecture over that of the *host*, if available.
816 if (m_gdb_comm.GetProcessArchitecture().IsValid())
817 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
818 else
819 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molenda16d127c2012-05-03 22:37:30 +0000820 }
821
Todd Fialaaf245d12014-06-30 21:05:18 +0000822 if (log)
823 log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": normalized target architecture triple: %s", __FUNCTION__, GetID (), GetTarget ().GetArchitecture ().GetTriple ().getTriple ().c_str ());
824
Chaoren Lin98d0a4b2015-07-14 01:09:28 +0000825 if (error.Success())
Jaydeep Patil6fc590d2015-07-30 05:06:51 +0000826 {
827 PlatformSP platform_sp = GetTarget().GetPlatform();
828 if (platform_sp && platform_sp->IsConnected())
829 SetUnixSignals(platform_sp->GetUnixSignals());
830 else
831 SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
832 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000833
Greg Claytonb766a732011-02-04 01:58:07 +0000834 return error;
835}
836
837Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000838ProcessGDBRemote::WillLaunchOrAttach ()
839{
840 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000841 m_stdio_communication.Clear ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000842 return error;
843}
844
845//----------------------------------------------------------------------
846// Process Control
847//----------------------------------------------------------------------
848Error
Jean-Daniel Dupas7782de92013-12-09 22:52:50 +0000849ProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000850{
Todd Fiala75f47c32014-10-11 21:42:09 +0000851 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton4957bf62010-09-30 21:49:03 +0000852 Error error;
Greg Clayton982c9762011-11-03 21:22:33 +0000853
Todd Fiala75f47c32014-10-11 21:42:09 +0000854 if (log)
855 log->Printf ("ProcessGDBRemote::%s() entered", __FUNCTION__);
856
Greg Clayton982c9762011-11-03 21:22:33 +0000857 uint32_t launch_flags = launch_info.GetFlags().Get();
Chaoren Lind3173f32015-05-29 19:52:29 +0000858 FileSpec stdin_file_spec{};
859 FileSpec stdout_file_spec{};
860 FileSpec stderr_file_spec{};
861 FileSpec working_dir = launch_info.GetWorkingDirectory();
Greg Clayton982c9762011-11-03 21:22:33 +0000862
Zachary Turner696b5282014-08-14 16:01:25 +0000863 const FileAction *file_action;
Greg Clayton982c9762011-11-03 21:22:33 +0000864 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
865 if (file_action)
866 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000867 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000868 stdin_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000869 }
870 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
871 if (file_action)
872 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000873 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000874 stdout_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000875 }
876 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
877 if (file_action)
878 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000879 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000880 stderr_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000881 }
882
Todd Fiala75f47c32014-10-11 21:42:09 +0000883 if (log)
884 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000885 if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
Vince Harron4a8abd32015-02-13 19:15:24 +0000886 log->Printf ("ProcessGDBRemote::%s provided with STDIO paths via launch_info: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000887 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000888 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
889 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
890 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Todd Fiala75f47c32014-10-11 21:42:09 +0000891 else
892 log->Printf ("ProcessGDBRemote::%s no STDIO paths given via launch_info", __FUNCTION__);
893 }
894
Vince Harrondf3f00f2015-02-10 21:09:04 +0000895 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Chaoren Lind3173f32015-05-29 19:52:29 +0000896 if (stdin_file_spec || disable_stdio)
Vince Harrondf3f00f2015-02-10 21:09:04 +0000897 {
898 // the inferior will be reading stdin from the specified file
899 // or stdio is completely disabled
900 m_stdin_forward = false;
901 }
902 else
903 {
904 m_stdin_forward = true;
905 }
906
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000907 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
908 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
909 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000910
Greg Clayton982c9762011-11-03 21:22:33 +0000911 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000912 if (object_file)
913 {
Greg Clayton71337622011-02-24 22:24:29 +0000914 // Make sure we aren't already connected?
915 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000916 {
Greg Clayton91a9b2472013-12-04 19:19:12 +0000917 error = LaunchAndConnectToDebugserver (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000918 }
919
920 if (error.Success())
921 {
922 lldb_utility::PseudoTerminal pty;
923 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000924
Greg Claytonf58c2692011-06-24 22:32:10 +0000925 PlatformSP platform_sp (m_target.GetPlatform());
Vince Harrondf3f00f2015-02-10 21:09:04 +0000926 if (disable_stdio)
Greg Clayton71337622011-02-24 22:24:29 +0000927 {
Vince Harrondf3f00f2015-02-10 21:09:04 +0000928 // set to /dev/null unless redirected to a file above
Chaoren Lind3173f32015-05-29 19:52:29 +0000929 if (!stdin_file_spec)
930 stdin_file_spec.SetFile("/dev/null", false);
931 if (!stdout_file_spec)
932 stdout_file_spec.SetFile("/dev/null", false);
933 if (!stderr_file_spec)
934 stderr_file_spec.SetFile("/dev/null", false);
Vince Harrondf3f00f2015-02-10 21:09:04 +0000935 }
936 else if (platform_sp && platform_sp->IsHost())
937 {
938 // If the debugserver is local and we aren't disabling STDIO, lets use
939 // a pseudo terminal to instead of relying on the 'O' packets for stdio
940 // since 'O' packets can really slow down debugging if the inferior
941 // does a lot of output.
Chaoren Lind3173f32015-05-29 19:52:29 +0000942 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
943 pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000944 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000945 FileSpec slave_name{pty.GetSlaveName(NULL, 0), false};
946
947 if (!stdin_file_spec)
948 stdin_file_spec = slave_name;
949
950 if (!stdout_file_spec)
951 stdout_file_spec = slave_name;
952
953 if (!stderr_file_spec)
954 stderr_file_spec = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000955 }
Todd Fiala75f47c32014-10-11 21:42:09 +0000956 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +0000957 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 +0000958 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000959 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
960 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
961 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Greg Clayton71337622011-02-24 22:24:29 +0000962 }
963
Todd Fiala75f47c32014-10-11 21:42:09 +0000964 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +0000965 log->Printf ("ProcessGDBRemote::%s final STDIO paths after all adjustments: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000966 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000967 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
968 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
969 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Todd Fiala75f47c32014-10-11 21:42:09 +0000970
Chaoren Lind3173f32015-05-29 19:52:29 +0000971 if (stdin_file_spec)
972 m_gdb_comm.SetSTDIN(stdin_file_spec);
973 if (stdout_file_spec)
974 m_gdb_comm.SetSTDOUT(stdout_file_spec);
975 if (stderr_file_spec)
976 m_gdb_comm.SetSTDERR(stderr_file_spec);
Greg Clayton71337622011-02-24 22:24:29 +0000977
978 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
Jim Ingham106d0282014-06-25 02:32:56 +0000979 m_gdb_comm.SetDetachOnError (launch_flags & eLaunchFlagDetachOnError);
Greg Clayton71337622011-02-24 22:24:29 +0000980
Greg Claytonc4103b32011-05-08 04:53:50 +0000981 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Clayton71337622011-02-24 22:24:29 +0000982
Jason Molendaa3329782014-03-29 18:54:20 +0000983 const char * launch_event_data = launch_info.GetLaunchEventData();
984 if (launch_event_data != NULL && *launch_event_data != '\0')
985 m_gdb_comm.SendLaunchEventDataPacket (launch_event_data);
986
Chaoren Lind3173f32015-05-29 19:52:29 +0000987 if (working_dir)
Greg Clayton71337622011-02-24 22:24:29 +0000988 {
989 m_gdb_comm.SetWorkingDir (working_dir);
990 }
991
992 // Send the environment and the program + arguments after we connect
Greg Clayton982c9762011-11-03 21:22:33 +0000993 const Args &environment = launch_info.GetEnvironmentEntries();
994 if (environment.GetArgumentCount())
Greg Clayton71337622011-02-24 22:24:29 +0000995 {
Greg Clayton982c9762011-11-03 21:22:33 +0000996 size_t num_environment_entries = environment.GetArgumentCount();
997 for (size_t i=0; i<num_environment_entries; ++i)
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000998 {
Greg Clayton982c9762011-11-03 21:22:33 +0000999 const char *env_entry = environment.GetArgumentAtIndex(i);
1000 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Clayton71337622011-02-24 22:24:29 +00001001 break;
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001002 }
Greg Clayton71337622011-02-24 22:24:29 +00001003 }
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001004
Greg Clayton71337622011-02-24 22:24:29 +00001005 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001006 // Scope for the scoped timeout object
1007 GDBRemoteCommunication::ScopedTimeout timeout (m_gdb_comm, 10);
1008
1009 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
1010 if (arg_packet_err == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001011 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001012 std::string error_str;
1013 if (m_gdb_comm.GetLaunchSuccess (error_str))
1014 {
1015 SetID (m_gdb_comm.GetCurrentProcessID ());
1016 }
1017 else
1018 {
1019 error.SetErrorString (error_str.c_str());
1020 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001021 }
1022 else
1023 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001024 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001025 }
Greg Clayton71337622011-02-24 22:24:29 +00001026 }
Tamas Berghammer912800c2015-02-24 10:23:39 +00001027
Greg Clayton71337622011-02-24 22:24:29 +00001028 if (GetID() == LLDB_INVALID_PROCESS_ID)
1029 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001030 if (log)
1031 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton71337622011-02-24 22:24:29 +00001032 KillDebugserverProcess ();
1033 return error;
1034 }
1035
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001036 StringExtractorGDBRemote response;
1037 if (m_gdb_comm.GetStopReply(response))
Greg Clayton71337622011-02-24 22:24:29 +00001038 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001039 SetLastStopPacket(response);
Ewan Crawford78baa192015-05-13 09:18:18 +00001040 // '?' Packets must be handled differently in non-stop mode
1041 if (GetTarget().GetNonStopModeEnabled())
1042 HandleStopReplySequence();
1043
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001044 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
1045
1046 if (process_arch.IsValid())
Jason Molendac62bd7b2013-12-21 05:20:36 +00001047 {
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001048 m_target.MergeArchitecture(process_arch);
1049 }
1050 else
1051 {
1052 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
1053 if (host_arch.IsValid())
1054 m_target.MergeArchitecture(host_arch);
Carlo Kok74389122013-10-14 07:09:13 +00001055 }
1056
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001057 SetPrivateState (SetThreadStopInfo (response));
Greg Clayton71337622011-02-24 22:24:29 +00001058
1059 if (!disable_stdio)
1060 {
1061 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Claytonee95ed52011-11-17 22:14:31 +00001062 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Clayton71337622011-02-24 22:24:29 +00001063 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001064 }
1065 }
Greg Claytonc235ac72011-08-09 05:20:29 +00001066 else
1067 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001068 if (log)
1069 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytonc235ac72011-08-09 05:20:29 +00001070 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001071 }
1072 else
1073 {
1074 // Set our user ID to an invalid process ID.
1075 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton982c9762011-11-03 21:22:33 +00001076 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
1077 exe_module->GetFileSpec().GetFilename().AsCString(),
1078 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001079 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001080 return error;
Greg Clayton4957bf62010-09-30 21:49:03 +00001081
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001082}
1083
1084
1085Error
Greg Claytonb766a732011-02-04 01:58:07 +00001086ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001087{
1088 Error error;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001089 // Only connect if we have a valid connect URL
Vince Harron1b5a74e2015-01-21 22:42:49 +00001090 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton00fe87b2013-12-05 22:58:22 +00001091
1092 if (connect_url && connect_url[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001093 {
Vince Harron1b5a74e2015-01-21 22:42:49 +00001094 if (log)
1095 log->Printf("ProcessGDBRemote::%s Connecting to %s", __FUNCTION__, connect_url);
Greg Clayton00fe87b2013-12-05 22:58:22 +00001096 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
1097 if (conn_ap.get())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001098 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001099 const uint32_t max_retry_count = 50;
1100 uint32_t retry_count = 0;
1101 while (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001102 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001103 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
1104 {
1105 m_gdb_comm.SetConnection (conn_ap.release());
1106 break;
1107 }
1108 else if (error.WasInterrupted())
1109 {
1110 // If we were interrupted, don't keep retrying.
1111 break;
1112 }
1113
1114 retry_count++;
1115
1116 if (retry_count >= max_retry_count)
1117 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001118
Greg Clayton00fe87b2013-12-05 22:58:22 +00001119 usleep (100000);
1120 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001121 }
1122 }
1123
1124 if (!m_gdb_comm.IsConnected())
1125 {
1126 if (error.Success())
1127 error.SetErrorString("not connected to remote gdb server");
1128 return error;
1129 }
1130
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001131
1132 // Start the communications read thread so all incoming data can be
1133 // parsed into packets and queued as they arrive.
1134 if (GetTarget().GetNonStopModeEnabled())
1135 m_gdb_comm.StartReadThread();
1136
Greg Clayton32e0a752011-03-30 18:16:51 +00001137 // We always seem to be able to open a connection to a local port
1138 // so we need to make sure we can then send data to it. If we can't
1139 // then we aren't actually connected to anything, so try and do the
1140 // handshake with the remote GDB server and make sure that goes
1141 // alright.
Greg Claytonfb909312013-11-23 01:58:15 +00001142 if (!m_gdb_comm.HandshakeWithServer (&error))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001143 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001144 m_gdb_comm.Disconnect();
1145 if (error.Success())
1146 error.SetErrorString("not connected to remote gdb server");
1147 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001148 }
Ewan Crawford78baa192015-05-13 09:18:18 +00001149
1150 // Send $QNonStop:1 packet on startup if required
1151 if (GetTarget().GetNonStopModeEnabled())
Ewan Crawfordaa7eda72015-06-24 15:14:26 +00001152 GetTarget().SetNonStopModeEnabled (m_gdb_comm.SetNonStopMode(true));
Ewan Crawford78baa192015-05-13 09:18:18 +00001153
Greg Claytonb30c50c2015-05-29 00:01:55 +00001154 m_gdb_comm.GetEchoSupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001155 m_gdb_comm.GetThreadSuffixSupported ();
Greg Clayton44633992012-04-10 03:22:03 +00001156 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001157 m_gdb_comm.GetHostInfo ();
1158 m_gdb_comm.GetVContSupported ('c');
Jim Inghamcd16df92012-07-20 21:37:13 +00001159 m_gdb_comm.GetVAttachOrWaitSupported();
Ewan Crawford78baa192015-05-13 09:18:18 +00001160
1161 // Ask the remote server for the default thread id
1162 if (GetTarget().GetNonStopModeEnabled())
1163 m_gdb_comm.GetDefaultThreadId(m_initial_tid);
1164
1165
Jim Ingham03afad82012-07-02 05:40:07 +00001166 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1167 for (size_t idx = 0; idx < num_cmds; idx++)
1168 {
1169 StringExtractorGDBRemote response;
Jim Ingham03afad82012-07-02 05:40:07 +00001170 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1171 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001172 return error;
1173}
1174
1175void
Jim Inghambb006ce2014-08-02 00:33:35 +00001176ProcessGDBRemote::DidLaunchOrAttach (ArchSpec& process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001177{
Greg Clayton5160ce52013-03-27 23:08:40 +00001178 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001179 if (log)
1180 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton93d3c8332011-02-16 04:46:07 +00001181 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001182 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001183 BuildDynamicRegisterInfo (false);
Greg Clayton3af9ea52010-11-18 05:57:03 +00001184
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001185 // See if the GDB server supports the qHostInfo information
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001186
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001187
1188 // See if the GDB server supports the qProcessInfo packet, if so
1189 // prefer that over the Host information as it will be more specific
1190 // to our process.
1191
Todd Fiala75f47c32014-10-11 21:42:09 +00001192 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1193 if (remote_process_arch.IsValid())
1194 {
1195 process_arch = remote_process_arch;
1196 if (log)
1197 log->Printf ("ProcessGDBRemote::%s gdb-remote had process architecture, using %s %s",
1198 __FUNCTION__,
1199 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1200 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1201 }
Jim Inghambb006ce2014-08-02 00:33:35 +00001202 else
Todd Fiala75f47c32014-10-11 21:42:09 +00001203 {
Jim Inghambb006ce2014-08-02 00:33:35 +00001204 process_arch = m_gdb_comm.GetHostArchitecture();
Todd Fiala75f47c32014-10-11 21:42:09 +00001205 if (log)
1206 log->Printf ("ProcessGDBRemote::%s gdb-remote did not have process architecture, using gdb-remote host architecture %s %s",
1207 __FUNCTION__,
1208 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1209 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1210 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001211
Jim Inghambb006ce2014-08-02 00:33:35 +00001212 if (process_arch.IsValid())
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001213 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001214 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Greg Claytond314e812011-03-23 00:09:55 +00001215 if (target_arch.IsValid())
1216 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001217 if (log)
1218 log->Printf ("ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1219 __FUNCTION__,
1220 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1221 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
1222
1223 // If the remote host is ARM and we have apple as the vendor, then
Greg Claytond314e812011-03-23 00:09:55 +00001224 // ARM executables and shared libraries can have mixed ARM architectures.
1225 // You can have an armv6 executable, and if the host is armv7, then the
1226 // system will load the best possible architecture for all shared libraries
1227 // it has, so we really need to take the remote host architecture as our
1228 // defacto architecture in this case.
1229
Jim Inghambb006ce2014-08-02 00:33:35 +00001230 if (process_arch.GetMachine() == llvm::Triple::arm &&
1231 process_arch.GetTriple().getVendor() == llvm::Triple::Apple)
Greg Claytond314e812011-03-23 00:09:55 +00001232 {
Jason Molenda921c01b2014-08-03 21:42:52 +00001233 GetTarget().SetArchitecture (process_arch);
Todd Fiala75f47c32014-10-11 21:42:09 +00001234 if (log)
1235 log->Printf ("ProcessGDBRemote::%s remote process is ARM/Apple, setting target arch to %s %s",
1236 __FUNCTION__,
1237 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1238 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001239 }
1240 else
1241 {
1242 // Fill in what is missing in the triple
Jim Inghambb006ce2014-08-02 00:33:35 +00001243 const llvm::Triple &remote_triple = process_arch.GetTriple();
Tamas Berghammere724af12015-03-13 10:32:37 +00001244 llvm::Triple new_target_triple = target_arch.GetTriple();
1245 if (new_target_triple.getVendorName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001246 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001247 new_target_triple.setVendor (remote_triple.getVendor());
Greg Claytond314e812011-03-23 00:09:55 +00001248
Tamas Berghammere724af12015-03-13 10:32:37 +00001249 if (new_target_triple.getOSName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001250 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001251 new_target_triple.setOS (remote_triple.getOS());
Greg Claytond314e812011-03-23 00:09:55 +00001252
Tamas Berghammere724af12015-03-13 10:32:37 +00001253 if (new_target_triple.getEnvironmentName().size() == 0)
1254 new_target_triple.setEnvironment (remote_triple.getEnvironment());
Greg Clayton70b57652011-05-15 01:25:55 +00001255 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001256
Tamas Berghammere724af12015-03-13 10:32:37 +00001257 ArchSpec new_target_arch = target_arch;
1258 new_target_arch.SetTriple(new_target_triple);
1259 GetTarget().SetArchitecture(new_target_arch);
1260 }
Greg Claytond314e812011-03-23 00:09:55 +00001261 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001262
1263 if (log)
1264 log->Printf ("ProcessGDBRemote::%s final target arch after adjustments for remote architecture: %s %s",
1265 __FUNCTION__,
1266 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1267 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001268 }
1269 else
1270 {
1271 // The target doesn't have a valid architecture yet, set it from
1272 // the architecture we got from the remote GDB server
Jason Molenda921c01b2014-08-03 21:42:52 +00001273 GetTarget().SetArchitecture (process_arch);
Greg Claytond314e812011-03-23 00:09:55 +00001274 }
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001275 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001276 }
1277}
1278
1279void
1280ProcessGDBRemote::DidLaunch ()
1281{
Jim Inghambb006ce2014-08-02 00:33:35 +00001282 ArchSpec process_arch;
1283 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001284}
1285
1286Error
Han Ming Ong84647042012-02-25 01:07:38 +00001287ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1288{
Todd Fiala75f47c32014-10-11 21:42:09 +00001289 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001290 Error error;
Todd Fiala75f47c32014-10-11 21:42:09 +00001291
1292 if (log)
1293 log->Printf ("ProcessGDBRemote::%s()", __FUNCTION__);
1294
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001295 // Clear out and clean up from any current state
1296 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001297 if (attach_pid != LLDB_INVALID_PROCESS_ID)
1298 {
Greg Clayton71337622011-02-24 22:24:29 +00001299 // Make sure we aren't already connected?
1300 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001301 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001302 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001303
1304 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001305 {
Greg Clayton71337622011-02-24 22:24:29 +00001306 const char *error_string = error.AsCString();
1307 if (error_string == NULL)
1308 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1309
1310 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001311 }
Greg Clayton71337622011-02-24 22:24:29 +00001312 }
1313
1314 if (error.Success())
1315 {
Jim Ingham106d0282014-06-25 02:32:56 +00001316 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
Todd Fiala75f47c32014-10-11 21:42:09 +00001317
Greg Clayton71337622011-02-24 22:24:29 +00001318 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001319 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Greg Clayton3b608422011-11-19 02:11:30 +00001320 SetID (attach_pid);
Greg Clayton71337622011-02-24 22:24:29 +00001321 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001322 }
1323 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001324
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001325 return error;
1326}
1327
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001328Error
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001329ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001330{
1331 Error error;
1332 // Clear out and clean up from any current state
1333 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001334
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001335 if (process_name && process_name[0])
1336 {
Greg Clayton71337622011-02-24 22:24:29 +00001337 // Make sure we aren't already connected?
1338 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001339 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001340 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001341
Greg Clayton71337622011-02-24 22:24:29 +00001342 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001343 {
Greg Clayton71337622011-02-24 22:24:29 +00001344 const char *error_string = error.AsCString();
1345 if (error_string == NULL)
1346 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001347
Greg Clayton71337622011-02-24 22:24:29 +00001348 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001349 }
Greg Clayton71337622011-02-24 22:24:29 +00001350 }
1351
1352 if (error.Success())
1353 {
1354 StreamString packet;
1355
Jim Ingham106d0282014-06-25 02:32:56 +00001356 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1357
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001358 if (attach_info.GetWaitForLaunch())
Jim Inghamcd16df92012-07-20 21:37:13 +00001359 {
1360 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1361 {
1362 packet.PutCString ("vAttachWait");
1363 }
1364 else
1365 {
1366 if (attach_info.GetIgnoreExisting())
1367 packet.PutCString("vAttachWait");
1368 else
1369 packet.PutCString ("vAttachOrWait");
1370 }
1371 }
Greg Clayton71337622011-02-24 22:24:29 +00001372 else
1373 packet.PutCString("vAttachName");
1374 packet.PutChar(';');
1375 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1376
1377 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1378
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001379 }
1380 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001381 return error;
1382}
1383
Greg Clayton5df78fa2015-05-23 03:54:53 +00001384void
1385ProcessGDBRemote::DidExit ()
Greg Claytonfbb76342013-11-20 21:07:01 +00001386{
Greg Clayton5df78fa2015-05-23 03:54:53 +00001387 // When we exit, disconnect from the GDB server communications
Greg Claytonfbb76342013-11-20 21:07:01 +00001388 m_gdb_comm.Disconnect();
Greg Claytonfbb76342013-11-20 21:07:01 +00001389}
1390
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001391void
Jim Inghambb006ce2014-08-02 00:33:35 +00001392ProcessGDBRemote::DidAttach (ArchSpec &process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001393{
Jim Inghambb006ce2014-08-02 00:33:35 +00001394 // If you can figure out what the architecture is, fill it in here.
1395 process_arch.Clear();
1396 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001397}
1398
Greg Clayton90ba8112012-12-05 00:16:59 +00001399
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001400Error
1401ProcessGDBRemote::WillResume ()
1402{
Greg Clayton71fc2a32011-02-12 06:28:37 +00001403 m_continue_c_tids.clear();
1404 m_continue_C_tids.clear();
1405 m_continue_s_tids.clear();
1406 m_continue_S_tids.clear();
Greg Clayton2e309072015-07-17 23:42:28 +00001407 m_jstopinfo_sp.reset();
1408 m_jthreadsinfo_sp.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001409 return Error();
1410}
1411
1412Error
1413ProcessGDBRemote::DoResume ()
1414{
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001415 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001416 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001417 if (log)
1418 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytone5219662010-12-03 06:02:24 +00001419
1420 Listener listener ("gdb-remote.resume-packet-sent");
1421 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1422 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00001423 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1424
Greg Claytond1d06e42013-04-20 00:27:58 +00001425 const size_t num_threads = GetThreadList().GetSize();
1426
Greg Clayton71fc2a32011-02-12 06:28:37 +00001427 StreamString continue_packet;
1428 bool continue_packet_error = false;
1429 if (m_gdb_comm.HasAnyVContSupport ())
1430 {
Ewan Crawford78baa192015-05-13 09:18:18 +00001431 if (!GetTarget().GetNonStopModeEnabled() &&
1432 (m_continue_c_tids.size() == num_threads ||
Greg Claytone98008c2014-02-13 23:34:38 +00001433 (m_continue_c_tids.empty() &&
1434 m_continue_C_tids.empty() &&
1435 m_continue_s_tids.empty() &&
Ewan Crawford78baa192015-05-13 09:18:18 +00001436 m_continue_S_tids.empty())))
Greg Clayton71fc2a32011-02-12 06:28:37 +00001437 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001438 // All threads are continuing, just send a "c" packet
1439 continue_packet.PutCString ("c");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001440 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001441 else
1442 {
1443 continue_packet.PutCString ("vCont");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001444
Greg Claytond1d06e42013-04-20 00:27:58 +00001445 if (!m_continue_c_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001446 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001447 if (m_gdb_comm.GetVContSupported ('c'))
1448 {
1449 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)
1450 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1451 }
1452 else
1453 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001454 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001455
1456 if (!continue_packet_error && !m_continue_C_tids.empty())
1457 {
1458 if (m_gdb_comm.GetVContSupported ('C'))
1459 {
1460 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)
1461 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1462 }
1463 else
1464 continue_packet_error = true;
1465 }
Greg Claytone5219662010-12-03 06:02:24 +00001466
Greg Claytond1d06e42013-04-20 00:27:58 +00001467 if (!continue_packet_error && !m_continue_s_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001468 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001469 if (m_gdb_comm.GetVContSupported ('s'))
1470 {
1471 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)
1472 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1473 }
1474 else
1475 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001476 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001477
1478 if (!continue_packet_error && !m_continue_S_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001479 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001480 if (m_gdb_comm.GetVContSupported ('S'))
1481 {
1482 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)
1483 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1484 }
1485 else
1486 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001487 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001488
1489 if (continue_packet_error)
1490 continue_packet.GetString().clear();
Greg Clayton71fc2a32011-02-12 06:28:37 +00001491 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001492 }
1493 else
1494 continue_packet_error = true;
1495
1496 if (continue_packet_error)
1497 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001498 // Either no vCont support, or we tried to use part of the vCont
1499 // packet that wasn't supported by the remote GDB server.
1500 // We need to try and make a simple packet that can do our continue
Greg Clayton71fc2a32011-02-12 06:28:37 +00001501 const size_t num_continue_c_tids = m_continue_c_tids.size();
1502 const size_t num_continue_C_tids = m_continue_C_tids.size();
1503 const size_t num_continue_s_tids = m_continue_s_tids.size();
1504 const size_t num_continue_S_tids = m_continue_S_tids.size();
1505 if (num_continue_c_tids > 0)
1506 {
1507 if (num_continue_c_tids == num_threads)
1508 {
1509 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001510 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001511 continue_packet.PutChar ('c');
1512 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001513 }
1514 else if (num_continue_c_tids == 1 &&
1515 num_continue_C_tids == 0 &&
1516 num_continue_s_tids == 0 &&
1517 num_continue_S_tids == 0 )
1518 {
1519 // Only one thread is continuing
Greg Clayton8b82f082011-04-12 05:54:46 +00001520 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001521 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001522 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001523 }
1524 }
1525
Greg Clayton0c74e782011-06-24 03:21:43 +00001526 if (continue_packet_error && num_continue_C_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001527 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001528 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1529 num_continue_C_tids > 0 &&
1530 num_continue_s_tids == 0 &&
1531 num_continue_S_tids == 0 )
Greg Clayton71fc2a32011-02-12 06:28:37 +00001532 {
1533 const int continue_signo = m_continue_C_tids.front().second;
Greg Clayton0c74e782011-06-24 03:21:43 +00001534 // Only one thread is continuing
Greg Clayton71fc2a32011-02-12 06:28:37 +00001535 if (num_continue_C_tids > 1)
1536 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001537 // More that one thread with a signal, yet we don't have
1538 // vCont support and we are being asked to resume each
1539 // thread with a signal, we need to make sure they are
1540 // all the same signal, or we can't issue the continue
1541 // accurately with the current support...
1542 if (num_continue_C_tids > 1)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001543 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001544 continue_packet_error = false;
1545 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1546 {
1547 if (m_continue_C_tids[i].second != continue_signo)
1548 continue_packet_error = true;
1549 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001550 }
Greg Clayton0c74e782011-06-24 03:21:43 +00001551 if (!continue_packet_error)
1552 m_gdb_comm.SetCurrentThreadForRun (-1);
1553 }
1554 else
1555 {
1556 // Set the continue thread ID
1557 continue_packet_error = false;
1558 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001559 }
1560 if (!continue_packet_error)
1561 {
1562 // Add threads continuing with the same signo...
Greg Clayton71fc2a32011-02-12 06:28:37 +00001563 continue_packet.Printf("C%2.2x", continue_signo);
1564 }
1565 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001566 }
1567
Greg Clayton0c74e782011-06-24 03:21:43 +00001568 if (continue_packet_error && num_continue_s_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001569 {
1570 if (num_continue_s_tids == num_threads)
1571 {
1572 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001573 m_gdb_comm.SetCurrentThreadForRun (-1);
Ewan Crawford76df2882015-06-23 12:32:06 +00001574
1575 // If in Non-Stop-Mode use vCont when stepping
1576 if (GetTarget().GetNonStopModeEnabled())
1577 {
1578 if (m_gdb_comm.GetVContSupported('s'))
1579 continue_packet.PutCString("vCont;s");
1580 else
1581 continue_packet.PutChar('s');
1582 }
1583 else
1584 continue_packet.PutChar('s');
1585
Greg Clayton0c74e782011-06-24 03:21:43 +00001586 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001587 }
1588 else if (num_continue_c_tids == 0 &&
1589 num_continue_C_tids == 0 &&
1590 num_continue_s_tids == 1 &&
1591 num_continue_S_tids == 0 )
1592 {
1593 // Only one thread is stepping
Greg Clayton8b82f082011-04-12 05:54:46 +00001594 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001595 continue_packet.PutChar ('s');
Greg Clayton0c74e782011-06-24 03:21:43 +00001596 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001597 }
1598 }
1599
1600 if (!continue_packet_error && num_continue_S_tids > 0)
1601 {
1602 if (num_continue_S_tids == num_threads)
1603 {
1604 const int step_signo = m_continue_S_tids.front().second;
1605 // Are all threads trying to step with the same signal?
Greg Clayton0c74e782011-06-24 03:21:43 +00001606 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001607 if (num_continue_S_tids > 1)
1608 {
1609 for (size_t i=1; i<num_threads; ++i)
1610 {
1611 if (m_continue_S_tids[i].second != step_signo)
1612 continue_packet_error = true;
1613 }
1614 }
1615 if (!continue_packet_error)
1616 {
1617 // Add threads stepping with the same signo...
Greg Clayton8b82f082011-04-12 05:54:46 +00001618 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001619 continue_packet.Printf("S%2.2x", step_signo);
1620 }
1621 }
1622 else if (num_continue_c_tids == 0 &&
1623 num_continue_C_tids == 0 &&
1624 num_continue_s_tids == 0 &&
1625 num_continue_S_tids == 1 )
1626 {
1627 // Only one thread is stepping with signal
Greg Clayton8b82f082011-04-12 05:54:46 +00001628 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001629 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Clayton0c74e782011-06-24 03:21:43 +00001630 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001631 }
1632 }
1633 }
1634
1635 if (continue_packet_error)
1636 {
1637 error.SetErrorString ("can't make continue packet for this resume");
1638 }
1639 else
1640 {
1641 EventSP event_sp;
1642 TimeValue timeout;
1643 timeout = TimeValue::Now();
1644 timeout.OffsetWithSeconds (5);
Zachary Turneracee96a2014-09-23 18:32:09 +00001645 if (!m_async_thread.IsJoinable())
Jim Inghamb1e2e842012-04-12 18:49:31 +00001646 {
1647 error.SetErrorString ("Trying to resume but the async thread is dead.");
1648 if (log)
1649 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1650 return error;
1651 }
1652
Greg Clayton71fc2a32011-02-12 06:28:37 +00001653 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1654
1655 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Inghamb1e2e842012-04-12 18:49:31 +00001656 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001657 error.SetErrorString("Resume timed out.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00001658 if (log)
1659 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1660 }
1661 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1662 {
1663 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1664 if (log)
1665 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1666 return error;
1667 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001668 }
Greg Claytone5219662010-12-03 06:02:24 +00001669 }
1670
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001671 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001672}
1673
Greg Clayton9e920902012-04-10 02:25:43 +00001674void
Ewan Crawford78baa192015-05-13 09:18:18 +00001675ProcessGDBRemote::HandleStopReplySequence ()
1676{
1677 while(true)
1678 {
1679 // Send vStopped
1680 StringExtractorGDBRemote response;
1681 m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false);
1682
1683 // OK represents end of signal list
1684 if (response.IsOKResponse())
1685 break;
1686
1687 // If not OK or a normal packet we have a problem
1688 if (!response.IsNormalResponse())
1689 break;
1690
1691 SetLastStopPacket(response);
1692 }
1693}
1694
1695void
Greg Clayton9e920902012-04-10 02:25:43 +00001696ProcessGDBRemote::ClearThreadIDList ()
1697{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001698 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001699 m_thread_ids.clear();
1700}
1701
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001702size_t
1703ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue (std::string &value)
1704{
1705 m_thread_ids.clear();
1706 size_t comma_pos;
1707 lldb::tid_t tid;
1708 while ((comma_pos = value.find(',')) != std::string::npos)
1709 {
1710 value[comma_pos] = '\0';
1711 // thread in big endian hex
1712 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1713 if (tid != LLDB_INVALID_THREAD_ID)
1714 m_thread_ids.push_back (tid);
1715 value.erase(0, comma_pos + 1);
1716 }
1717 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1718 if (tid != LLDB_INVALID_THREAD_ID)
1719 m_thread_ids.push_back (tid);
1720 return m_thread_ids.size();
1721}
1722
Greg Clayton9e920902012-04-10 02:25:43 +00001723bool
1724ProcessGDBRemote::UpdateThreadIDList ()
1725{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001726 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001727
Greg Clayton2e309072015-07-17 23:42:28 +00001728 if (m_jthreadsinfo_sp)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001729 {
1730 // If we have the JSON threads info, we can get the thread list from that
Greg Clayton2e309072015-07-17 23:42:28 +00001731 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001732 if (thread_infos && thread_infos->GetSize() > 0)
1733 {
1734 m_thread_ids.clear();
1735 thread_infos->ForEach([this](StructuredData::Object* object) -> bool {
1736 StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1737 if (thread_dict)
1738 {
1739 // Set the thread stop info from the JSON dictionary
1740 SetThreadStopInfo (thread_dict);
1741 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1742 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1743 m_thread_ids.push_back(tid);
1744 }
1745 return true; // Keep iterating through all thread_info objects
1746 });
1747 }
1748 if (!m_thread_ids.empty())
1749 return true;
1750 }
1751 else
1752 {
1753 // See if we can get the thread IDs from the current stop reply packets
1754 // that might contain a "threads" key/value pair
1755
1756 // Lock the thread stack while we access it
1757 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
1758 // Get the number of stop packets on the stack
1759 int nItems = m_stop_packet_stack.size();
1760 // Iterate over them
1761 for (int i = 0; i < nItems; i++)
1762 {
1763 // Get the thread stop info
1764 StringExtractorGDBRemote &stop_info = m_stop_packet_stack[i];
1765 const std::string &stop_info_str = stop_info.GetStringRef();
1766 const size_t threads_pos = stop_info_str.find(";threads:");
1767 if (threads_pos != std::string::npos)
1768 {
1769 const size_t start = threads_pos + strlen(";threads:");
1770 const size_t end = stop_info_str.find(';', start);
1771 if (end != std::string::npos)
1772 {
1773 std::string value = stop_info_str.substr(start, end - start);
1774 if (UpdateThreadIDsFromStopReplyThreadsValue(value))
1775 return true;
1776 }
1777 }
1778 }
1779 }
1780
Greg Clayton9e920902012-04-10 02:25:43 +00001781 bool sequence_mutex_unavailable = false;
1782 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1783 if (sequence_mutex_unavailable)
1784 {
Greg Clayton9e920902012-04-10 02:25:43 +00001785 return false; // We just didn't get the list
1786 }
1787 return true;
1788}
1789
Greg Clayton9fc13552012-04-10 00:18:59 +00001790bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001791ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001792{
1793 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +00001794 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Clayton73b472d2010-10-27 03:32:59 +00001795 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +00001796 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton9e920902012-04-10 02:25:43 +00001797
1798 size_t num_thread_ids = m_thread_ids.size();
1799 // The "m_thread_ids" thread ID list should always be updated after each stop
1800 // reply packet, but in case it isn't, update it here.
1801 if (num_thread_ids == 0)
1802 {
1803 if (!UpdateThreadIDList ())
1804 return false;
1805 num_thread_ids = m_thread_ids.size();
1806 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001807
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001808 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001809 if (num_thread_ids > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001810 {
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001811 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001812 {
Greg Clayton9e920902012-04-10 02:25:43 +00001813 tid_t tid = m_thread_ids[i];
Greg Clayton160c9d82013-05-01 21:54:04 +00001814 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001815 if (!thread_sp)
Jim Inghamdee1bc92013-06-22 00:27:45 +00001816 {
Jim Ingham4f465cf2012-10-10 18:32:14 +00001817 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001818 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1819 log->Printf(
1820 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001821 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001822 thread_sp->GetID());
1823 }
1824 else
1825 {
1826 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1827 log->Printf(
1828 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001829 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001830 thread_sp->GetID());
1831 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001832 new_thread_list.AddThread(thread_sp);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001833 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001834 }
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001835
1836 // Whatever that is left in old_thread_list_copy are not
1837 // present in new_thread_list. Remove non-existent threads from internal id table.
1838 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1839 for (size_t i=0; i<old_num_thread_ids; i++)
1840 {
1841 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1842 if (old_thread_sp)
1843 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001844 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001845 m_thread_id_to_index_id_map.erase(old_thread_id);
1846 }
1847 }
1848
Greg Clayton9fc13552012-04-10 00:18:59 +00001849 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001850}
1851
Greg Clayton2e309072015-07-17 23:42:28 +00001852
Greg Clayton358cf1e2015-06-25 21:46:34 +00001853bool
Greg Clayton2e309072015-07-17 23:42:28 +00001854ProcessGDBRemote::GetThreadStopInfoFromJSON (ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001855{
1856 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet
Greg Clayton2e309072015-07-17 23:42:28 +00001857 if (thread_infos_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001858 {
Greg Clayton2e309072015-07-17 23:42:28 +00001859 StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
Greg Clayton358cf1e2015-06-25 21:46:34 +00001860 if (thread_infos)
1861 {
1862 lldb::tid_t tid;
1863 const size_t n = thread_infos->GetSize();
1864 for (size_t i=0; i<n; ++i)
1865 {
1866 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1867 if (thread_dict)
1868 {
1869 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid, LLDB_INVALID_THREAD_ID))
1870 {
1871 if (tid == thread->GetID())
Greg Clayton2e309072015-07-17 23:42:28 +00001872 return (bool)SetThreadStopInfo(thread_dict);
Greg Clayton358cf1e2015-06-25 21:46:34 +00001873 }
1874 }
1875 }
1876 }
1877 }
Greg Clayton2e309072015-07-17 23:42:28 +00001878 return false;
1879}
1880
1881bool
1882ProcessGDBRemote::CalculateThreadStopInfo (ThreadGDBRemote *thread)
1883{
1884 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet
1885 if (GetThreadStopInfoFromJSON (thread, m_jthreadsinfo_sp))
1886 return true;
1887
1888 // See if we got thread stop info for any threads valid stop info reasons threads
1889 // via the "jstopinfo" packet stop reply packet key/value pair?
1890 if (m_jstopinfo_sp)
1891 {
1892 // If we have "jstopinfo" then we have stop descriptions for all threads
1893 // that have stop reasons, and if there is no entry for a thread, then
1894 // it has no stop reason.
1895 thread->GetRegisterContext()->InvalidateIfNeeded(true);
1896 if (!GetThreadStopInfoFromJSON (thread, m_jstopinfo_sp))
1897 {
1898 thread->SetStopInfo (StopInfoSP());
1899 }
1900 return true;
1901 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00001902
1903 // Fall back to using the qThreadStopInfo packet
1904 StringExtractorGDBRemote stop_packet;
1905 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1906 return SetThreadStopInfo (stop_packet) == eStateStopped;
1907 return false;
1908}
1909
1910
1911ThreadSP
1912ProcessGDBRemote::SetThreadStopInfo (lldb::tid_t tid,
1913 ExpeditedRegisterMap &expedited_register_map,
1914 uint8_t signo,
1915 const std::string &thread_name,
1916 const std::string &reason,
1917 const std::string &description,
1918 uint32_t exc_type,
1919 const std::vector<addr_t> &exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001920 addr_t thread_dispatch_qaddr,
1921 bool queue_vars_valid, // Set to true if queue_name, queue_kind and queue_serial are valid
1922 std::string &queue_name,
1923 QueueKind queue_kind,
1924 uint64_t queue_serial)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001925{
1926 ThreadSP thread_sp;
1927 if (tid != LLDB_INVALID_THREAD_ID)
1928 {
1929 // Scope for "locker" below
1930 {
1931 // m_thread_list_real does have its own mutex, but we need to
1932 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1933 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1934 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1935 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1936
1937 if (!thread_sp)
1938 {
1939 // Create the thread if we need to
1940 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1941 m_thread_list_real.AddThread(thread_sp);
1942 }
1943 }
1944
1945 if (thread_sp)
1946 {
1947 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1948 gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001949
Greg Clayton358cf1e2015-06-25 21:46:34 +00001950 for (const auto &pair : expedited_register_map)
1951 {
1952 StringExtractor reg_value_extractor;
1953 reg_value_extractor.GetStringRef() = pair.second;
1954 gdb_thread->PrivateSetRegisterValue (pair.first, reg_value_extractor);
1955 }
1956
Greg Clayton358cf1e2015-06-25 21:46:34 +00001957 thread_sp->SetName (thread_name.empty() ? NULL : thread_name.c_str());
1958
1959 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001960 // Check if the GDB server was able to provide the queue name, kind and serial number
1961 if (queue_vars_valid)
1962 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind, queue_serial);
1963 else
1964 gdb_thread->ClearQueueInfo();
1965
Greg Clayton2e309072015-07-17 23:42:28 +00001966 // Make sure we update our thread stop reason just once
1967 if (!thread_sp->StopInfoIsUpToDate())
Greg Clayton358cf1e2015-06-25 21:46:34 +00001968 {
Greg Clayton2e309072015-07-17 23:42:28 +00001969 thread_sp->SetStopInfo (StopInfoSP());
Greg Clayton358cf1e2015-06-25 21:46:34 +00001970
Greg Clayton2e309072015-07-17 23:42:28 +00001971 if (exc_type != 0)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001972 {
Greg Clayton2e309072015-07-17 23:42:28 +00001973 const size_t exc_data_size = exc_data.size();
1974
1975 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1976 exc_type,
1977 exc_data_size,
1978 exc_data_size >= 1 ? exc_data[0] : 0,
1979 exc_data_size >= 2 ? exc_data[1] : 0,
1980 exc_data_size >= 3 ? exc_data[2] : 0));
Greg Clayton358cf1e2015-06-25 21:46:34 +00001981 }
Greg Clayton2e309072015-07-17 23:42:28 +00001982 else
Greg Clayton358cf1e2015-06-25 21:46:34 +00001983 {
Greg Clayton2e309072015-07-17 23:42:28 +00001984 bool handled = false;
1985 bool did_exec = false;
1986 if (!reason.empty())
Greg Clayton358cf1e2015-06-25 21:46:34 +00001987 {
Greg Clayton2e309072015-07-17 23:42:28 +00001988 if (reason.compare("trace") == 0)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001989 {
Greg Clayton2e309072015-07-17 23:42:28 +00001990 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1991 handled = true;
1992 }
1993 else if (reason.compare("breakpoint") == 0)
1994 {
1995 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1996 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
1997 if (bp_site_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001998 {
Greg Clayton2e309072015-07-17 23:42:28 +00001999 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2000 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2001 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2002 handled = true;
2003 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2004 {
2005 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2006 }
2007 else
2008 {
2009 StopInfoSP invalid_stop_info_sp;
2010 thread_sp->SetStopInfo (invalid_stop_info_sp);
2011 }
2012 }
2013 }
2014 else if (reason.compare("trap") == 0)
2015 {
2016 // Let the trap just use the standard signal stop reason below...
2017 }
2018 else if (reason.compare("watchpoint") == 0)
2019 {
2020 StringExtractor desc_extractor(description.c_str());
2021 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
2022 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
2023 watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
2024 if (wp_addr != LLDB_INVALID_ADDRESS)
2025 {
2026 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2027 if (wp_sp)
2028 {
2029 wp_sp->SetHardwareIndex(wp_index);
2030 watch_id = wp_sp->GetID();
2031 }
2032 }
2033 if (watch_id == LLDB_INVALID_WATCH_ID)
2034 {
2035 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_WATCHPOINTS));
2036 if (log) log->Printf ("failed to find watchpoint");
2037 }
2038 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
2039 handled = true;
2040 }
2041 else if (reason.compare("exception") == 0)
2042 {
2043 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
2044 handled = true;
2045 }
2046 else if (reason.compare("exec") == 0)
2047 {
2048 did_exec = true;
2049 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
2050 handled = true;
2051 }
2052 }
2053
2054 if (!handled && signo && did_exec == false)
2055 {
2056 if (signo == SIGTRAP)
2057 {
2058 // Currently we are going to assume SIGTRAP means we are either
2059 // hitting a breakpoint or hardware single stepping.
2060 handled = true;
2061 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
2062 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2063
2064 if (bp_site_sp)
2065 {
2066 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2067 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2068 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2069 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2070 {
2071 if(m_breakpoint_pc_offset != 0)
2072 thread_sp->GetRegisterContext()->SetPC(pc);
2073 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2074 }
2075 else
2076 {
2077 StopInfoSP invalid_stop_info_sp;
2078 thread_sp->SetStopInfo (invalid_stop_info_sp);
2079 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002080 }
2081 else
2082 {
Greg Clayton2e309072015-07-17 23:42:28 +00002083 // If we were stepping then assume the stop was the result of the trace. If we were
2084 // not stepping then report the SIGTRAP.
2085 // FIXME: We are still missing the case where we single step over a trap instruction.
2086 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
2087 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
2088 else
2089 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo, description.c_str()));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002090 }
2091 }
Greg Clayton2e309072015-07-17 23:42:28 +00002092 if (!handled)
2093 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo, description.c_str()));
2094 }
2095
2096 if (!description.empty())
2097 {
2098 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
2099 if (stop_info_sp)
2100 {
2101 const char *stop_info_desc = stop_info_sp->GetDescription();
2102 if (!stop_info_desc || !stop_info_desc[0])
2103 stop_info_sp->SetDescription (description.c_str());
2104 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002105 else
2106 {
Greg Clayton2e309072015-07-17 23:42:28 +00002107 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002108 }
2109 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002110 }
2111 }
2112 }
2113 }
2114 return thread_sp;
2115}
2116
Greg Clayton2e309072015-07-17 23:42:28 +00002117lldb::ThreadSP
Greg Clayton358cf1e2015-06-25 21:46:34 +00002118ProcessGDBRemote::SetThreadStopInfo (StructuredData::Dictionary *thread_dict)
2119{
2120 static ConstString g_key_tid("tid");
2121 static ConstString g_key_name("name");
2122 static ConstString g_key_reason("reason");
2123 static ConstString g_key_metype("metype");
2124 static ConstString g_key_medata("medata");
2125 static ConstString g_key_qaddr("qaddr");
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002126 static ConstString g_key_queue_name("qname");
2127 static ConstString g_key_queue_kind("qkind");
2128 static ConstString g_key_queue_serial("qserial");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002129 static ConstString g_key_registers("registers");
2130 static ConstString g_key_memory("memory");
2131 static ConstString g_key_address("address");
2132 static ConstString g_key_bytes("bytes");
2133 static ConstString g_key_description("description");
Pavel Labath4a4bb122015-07-16 14:14:35 +00002134 static ConstString g_key_signal("signal");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002135
2136 // Stop with signal and thread info
2137 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2138 uint8_t signo = 0;
2139 std::string value;
2140 std::string thread_name;
2141 std::string reason;
2142 std::string description;
2143 uint32_t exc_type = 0;
2144 std::vector<addr_t> exc_data;
2145 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2146 ExpeditedRegisterMap expedited_register_map;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002147 bool queue_vars_valid = false;
2148 std::string queue_name;
2149 QueueKind queue_kind = eQueueKindUnknown;
2150 uint64_t queue_serial = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002151 // Iterate through all of the thread dictionary key/value pairs from the structured data dictionary
2152
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002153 thread_dict->ForEach([this,
2154 &tid,
2155 &expedited_register_map,
2156 &thread_name,
2157 &signo,
2158 &reason,
2159 &description,
2160 &exc_type,
2161 &exc_data,
2162 &thread_dispatch_qaddr,
2163 &queue_vars_valid,
2164 &queue_name,
2165 &queue_kind,
2166 &queue_serial]
2167 (ConstString key, StructuredData::Object* object) -> bool
Greg Clayton358cf1e2015-06-25 21:46:34 +00002168 {
2169 if (key == g_key_tid)
2170 {
2171 // thread in big endian hex
2172 tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
2173 }
2174 else if (key == g_key_metype)
2175 {
2176 // exception type in big endian hex
2177 exc_type = object->GetIntegerValue(0);
2178 }
2179 else if (key == g_key_medata)
2180 {
2181 // exception data in big endian hex
2182 StructuredData::Array *array = object->GetAsArray();
2183 if (array)
2184 {
2185 array->ForEach([&exc_data](StructuredData::Object* object) -> bool {
2186 exc_data.push_back(object->GetIntegerValue());
2187 return true; // Keep iterating through all array items
2188 });
2189 }
2190 }
2191 else if (key == g_key_name)
2192 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002193 thread_name = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002194 }
2195 else if (key == g_key_qaddr)
2196 {
2197 thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
2198 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002199 else if (key == g_key_queue_name)
2200 {
2201 queue_vars_valid = true;
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002202 queue_name = object->GetStringValue();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002203 }
2204 else if (key == g_key_queue_kind)
2205 {
2206 std::string queue_kind_str = object->GetStringValue();
2207 if (queue_kind_str == "serial")
2208 {
2209 queue_vars_valid = true;
2210 queue_kind = eQueueKindSerial;
2211 }
2212 else if (queue_kind_str == "concurrent")
2213 {
2214 queue_vars_valid = true;
2215 queue_kind = eQueueKindConcurrent;
2216 }
2217 }
2218 else if (key == g_key_queue_serial)
2219 {
2220 queue_serial = object->GetIntegerValue(0);
2221 if (queue_serial != 0)
2222 queue_vars_valid = true;
2223 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002224 else if (key == g_key_reason)
2225 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002226 reason = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002227 }
2228 else if (key == g_key_description)
2229 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002230 description = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002231 }
2232 else if (key == g_key_registers)
2233 {
2234 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2235
2236 if (registers_dict)
2237 {
2238 registers_dict->ForEach([&expedited_register_map](ConstString key, StructuredData::Object* object) -> bool {
2239 const uint32_t reg = StringConvert::ToUInt32 (key.GetCString(), UINT32_MAX, 10);
2240 if (reg != UINT32_MAX)
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002241 expedited_register_map[reg] = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002242 return true; // Keep iterating through all array items
2243 });
2244 }
2245 }
2246 else if (key == g_key_memory)
2247 {
2248 StructuredData::Array *array = object->GetAsArray();
2249 if (array)
2250 {
2251 array->ForEach([this](StructuredData::Object* object) -> bool {
2252 StructuredData::Dictionary *mem_cache_dict = object->GetAsDictionary();
2253 if (mem_cache_dict)
2254 {
2255 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2256 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>("address", mem_cache_addr))
2257 {
2258 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
2259 {
2260 StringExtractor bytes;
2261 if (mem_cache_dict->GetValueForKeyAsString("bytes", bytes.GetStringRef()))
2262 {
2263 bytes.SetFilePos(0);
2264
2265 const size_t byte_size = bytes.GetStringRef().size()/2;
2266 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2267 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2268 if (bytes_copied == byte_size)
2269 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2270 }
2271 }
2272 }
2273 }
2274 return true; // Keep iterating through all array items
2275 });
2276 }
2277
2278 }
Pavel Labath4a4bb122015-07-16 14:14:35 +00002279 else if (key == g_key_signal)
2280 signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002281 return true; // Keep iterating through all dictionary key/value pairs
2282 });
2283
Greg Clayton2e309072015-07-17 23:42:28 +00002284 return SetThreadStopInfo (tid,
2285 expedited_register_map,
2286 signo,
2287 thread_name,
2288 reason,
2289 description,
2290 exc_type,
2291 exc_data,
2292 thread_dispatch_qaddr,
2293 queue_vars_valid,
2294 queue_name,
2295 queue_kind,
2296 queue_serial);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002297}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002298
2299StateType
2300ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
2301{
Greg Claytondd0e5a52011-06-02 22:22:38 +00002302 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002303 const char stop_type = stop_packet.GetChar();
2304 switch (stop_type)
2305 {
2306 case 'T':
2307 case 'S':
2308 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00002309 // This is a bit of a hack, but is is required. If we did exec, we
2310 // need to clear our thread lists and also know to rebuild our dynamic
2311 // register info before we lookup and threads and populate the expedited
2312 // register values so we need to know this right away so we can cleanup
2313 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00002314 const uint32_t stop_id = GetStopID();
2315 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00002316 {
2317 // Our first stop, make sure we have a process ID, and also make
2318 // sure we know about our registers
2319 if (GetID() == LLDB_INVALID_PROCESS_ID)
2320 {
Greg Claytonc574ede2011-03-10 02:26:48 +00002321 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00002322 if (pid != LLDB_INVALID_PROCESS_ID)
2323 SetID (pid);
2324 }
2325 BuildDynamicRegisterInfo (true);
2326 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002327 // Stop with signal and thread info
Greg Clayton358cf1e2015-06-25 21:46:34 +00002328 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002329 const uint8_t signo = stop_packet.GetHexU8();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002330 std::string key;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002331 std::string value;
2332 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00002333 std::string reason;
2334 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002335 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00002336 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002337 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton0b90be12015-06-23 21:27:50 +00002338 bool queue_vars_valid = false; // says if locals below that start with "queue_" are valid
2339 std::string queue_name;
2340 QueueKind queue_kind = eQueueKindUnknown;
2341 uint64_t queue_serial = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002342 ExpeditedRegisterMap expedited_register_map;
2343 while (stop_packet.GetNameColonValue(key, value))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002344 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002345 if (key.compare("metype") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002346 {
2347 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002348 exc_type = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002349 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002350 else if (key.compare("medata") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002351 {
2352 // exception data in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002353 exc_data.push_back(StringConvert::ToUInt64 (value.c_str(), 0, 16));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002354 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002355 else if (key.compare("thread") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002356 {
2357 // thread in big endian hex
Greg Clayton358cf1e2015-06-25 21:46:34 +00002358 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002359 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002360 else if (key.compare("threads") == 0)
Greg Clayton9e920902012-04-10 02:25:43 +00002361 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002362 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00002363 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00002364 // A comma separated list of all threads in the current
2365 // process that includes the thread for this stop reply
2366 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00002367 size_t comma_pos;
2368 lldb::tid_t tid;
2369 while ((comma_pos = value.find(',')) != std::string::npos)
2370 {
2371 value[comma_pos] = '\0';
2372 // thread in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002373 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00002374 if (tid != LLDB_INVALID_THREAD_ID)
2375 m_thread_ids.push_back (tid);
2376 value.erase(0, comma_pos + 1);
Greg Clayton9e920902012-04-10 02:25:43 +00002377 }
Vince Harron5275aaa2015-01-15 20:08:35 +00002378 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00002379 if (tid != LLDB_INVALID_THREAD_ID)
2380 m_thread_ids.push_back (tid);
2381 }
Greg Clayton2e309072015-07-17 23:42:28 +00002382 else if (key.compare("jstopinfo") == 0)
Greg Claytona5801ad2015-07-15 22:59:03 +00002383 {
2384 StringExtractor json_extractor;
2385 // Swap "value" over into "name_extractor"
2386 json_extractor.GetStringRef().swap(value);
2387 // Now convert the HEX bytes into a string value
2388 json_extractor.GetHexByteString (value);
2389
2390 // This JSON contains thread IDs and thread stop info for all threads.
2391 // It doesn't contain expedited registers, memory or queue info.
Greg Clayton2e309072015-07-17 23:42:28 +00002392 m_jstopinfo_sp = StructuredData::ParseJSON (value);
Greg Claytona5801ad2015-07-15 22:59:03 +00002393 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002394 else if (key.compare("hexname") == 0)
Greg Claytonde9d0492011-01-08 03:17:57 +00002395 {
2396 StringExtractor name_extractor;
2397 // Swap "value" over into "name_extractor"
2398 name_extractor.GetStringRef().swap(value);
2399 // Now convert the HEX bytes into a string value
2400 name_extractor.GetHexByteString (value);
2401 thread_name.swap (value);
2402 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002403 else if (key.compare("name") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002404 {
2405 thread_name.swap (value);
2406 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002407 else if (key.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002408 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002409 thread_dispatch_qaddr = StringConvert::ToUInt64 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002410 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002411 else if (key.compare("qname") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002412 {
2413 queue_vars_valid = true;
2414 StringExtractor name_extractor;
2415 // Swap "value" over into "name_extractor"
2416 name_extractor.GetStringRef().swap(value);
2417 // Now convert the HEX bytes into a string value
2418 name_extractor.GetHexByteString (value);
2419 queue_name.swap (value);
2420 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002421 else if (key.compare("qkind") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002422 {
Greg Clayton0b90be12015-06-23 21:27:50 +00002423 if (value == "serial")
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002424 {
2425 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002426 queue_kind = eQueueKindSerial;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002427 }
Greg Clayton0b90be12015-06-23 21:27:50 +00002428 else if (value == "concurrent")
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002429 {
2430 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002431 queue_kind = eQueueKindConcurrent;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002432 }
Greg Clayton0b90be12015-06-23 21:27:50 +00002433 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002434 else if (key.compare("qserial") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002435 {
Greg Clayton0b90be12015-06-23 21:27:50 +00002436 queue_serial = StringConvert::ToUInt64 (value.c_str(), 0, 0);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002437 if (queue_serial != 0)
2438 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002439 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002440 else if (key.compare("reason") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002441 {
2442 reason.swap(value);
2443 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002444 else if (key.compare("description") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002445 {
2446 StringExtractor desc_extractor;
2447 // Swap "value" over into "name_extractor"
2448 desc_extractor.GetStringRef().swap(value);
2449 // Now convert the HEX bytes into a string value
Chaoren Lin28e57422015-02-03 01:51:25 +00002450 desc_extractor.GetHexByteString (value);
2451 description.swap(value);
Greg Claytona658fd22011-06-04 01:26:29 +00002452 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002453 else if (key.compare("memory") == 0)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002454 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002455 // Expedited memory. GDB servers can choose to send back expedited memory
2456 // that can populate the L1 memory cache in the process so that things like
2457 // the frame pointer backchain can be expedited. This will help stack
2458 // backtracing be more efficient by not having to send as many memory read
2459 // requests down the remote GDB server.
Chaoren Lin7a306082015-06-23 03:17:01 +00002460
Greg Clayton358cf1e2015-06-25 21:46:34 +00002461 // Key/value pair format: memory:<addr>=<bytes>;
2462 // <addr> is a number whose base will be interpreted by the prefix:
2463 // "0x[0-9a-fA-F]+" for hex
2464 // "0[0-7]+" for octal
2465 // "[1-9]+" for decimal
2466 // <bytes> is native endian ASCII hex bytes just like the register values
2467 llvm::StringRef value_ref(value);
2468 std::pair<llvm::StringRef, llvm::StringRef> pair;
2469 pair = value_ref.split('=');
2470 if (!pair.first.empty() && !pair.second.empty())
2471 {
2472 std::string addr_str(pair.first.str());
2473 const lldb::addr_t mem_cache_addr = StringConvert::ToUInt64(addr_str.c_str(), LLDB_INVALID_ADDRESS, 0);
2474 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002475 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002476 StringExtractor bytes;
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002477 bytes.GetStringRef() = pair.second.str();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002478 const size_t byte_size = bytes.GetStringRef().size()/2;
2479 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2480 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2481 if (bytes_copied == byte_size)
2482 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
Greg Clayton3e06bd92011-01-09 21:07:35 +00002483 }
2484 }
2485 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002486 else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1]))
2487 {
2488 uint32_t reg = StringConvert::ToUInt32 (key.c_str(), UINT32_MAX, 16);
2489 if (reg != UINT32_MAX)
2490 expedited_register_map[reg] = std::move(value);
2491 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002492 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002493
Bhushan D. Attarde1e271df2015-07-24 04:06:20 +00002494 if (tid == LLDB_INVALID_THREAD_ID)
2495 {
2496 // A thread id may be invalid if the response is old style 'S' packet which does not provide the
2497 // thread information. So update the thread list and choose the first one.
2498 UpdateThreadIDList ();
2499
2500 if (!m_thread_ids.empty ())
2501 {
2502 tid = m_thread_ids.front ();
2503 }
2504 }
2505
Greg Clayton358cf1e2015-06-25 21:46:34 +00002506 ThreadSP thread_sp = SetThreadStopInfo (tid,
2507 expedited_register_map,
2508 signo,
2509 thread_name,
2510 reason,
2511 description,
2512 exc_type,
2513 exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002514 thread_dispatch_qaddr,
2515 queue_vars_valid,
2516 queue_name,
2517 queue_kind,
2518 queue_serial);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002519
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002520 return eStateStopped;
2521 }
2522 break;
2523
2524 case 'W':
Todd Fialaff6131a2014-05-19 04:57:23 +00002525 case 'X':
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002526 // process exited
2527 return eStateExited;
2528
2529 default:
2530 break;
2531 }
2532 return eStateInvalid;
2533}
2534
2535void
2536ProcessGDBRemote::RefreshStateAfterStop ()
2537{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002538 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00002539 m_thread_ids.clear();
2540 // Set the thread stop info. It might have a "threads" key whose value is
2541 // a list of all thread IDs in the current process, so m_thread_ids might
2542 // get set.
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002543
2544 // Scope for the lock
2545 {
2546 // Lock the thread stack while we access it
2547 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
2548 // Get the number of stop packets on the stack
2549 int nItems = m_stop_packet_stack.size();
2550 // Iterate over them
2551 for (int i = 0; i < nItems; i++)
2552 {
2553 // Get the thread stop info
2554 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2555 // Process thread stop info
2556 SetThreadStopInfo(stop_info);
2557 }
2558 // Clear the thread stop stack
2559 m_stop_packet_stack.clear();
2560 }
2561
Greg Clayton9e920902012-04-10 02:25:43 +00002562 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2563 if (m_thread_ids.empty())
2564 {
2565 // No, we need to fetch the thread list manually
2566 UpdateThreadIDList();
2567 }
2568
Ewan Crawford78baa192015-05-13 09:18:18 +00002569 // If we have queried for a default thread id
2570 if (m_initial_tid != LLDB_INVALID_THREAD_ID)
2571 {
2572 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2573 m_initial_tid = LLDB_INVALID_THREAD_ID;
2574 }
2575
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002576 // Let all threads recover from stopping and do any clean up based
2577 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002578 m_thread_list_real.RefreshStateAfterStop();
Greg Clayton9e920902012-04-10 02:25:43 +00002579
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002580}
2581
2582Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002583ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002584{
2585 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002586
Greg Clayton6ed95942011-01-22 07:12:45 +00002587 bool timed_out = false;
2588 Mutex::Locker locker;
Greg Clayton513c26c2011-01-29 07:10:55 +00002589
2590 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002591 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002592 // We are being asked to halt during an attach. We need to just close
2593 // our file handle and debugserver will go away, and we can be done...
2594 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00002595 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002596 else
2597 {
Greg Clayton2687cd12012-03-29 01:55:41 +00002598 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton513c26c2011-01-29 07:10:55 +00002599 {
2600 if (timed_out)
2601 error.SetErrorString("timed out sending interrupt packet");
2602 else
2603 error.SetErrorString("unknown error sending interrupt packet");
2604 }
Greg Clayton2687cd12012-03-29 01:55:41 +00002605
2606 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton513c26c2011-01-29 07:10:55 +00002607 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002608 return error;
2609}
2610
2611Error
Jim Inghamacff8952013-05-02 00:27:30 +00002612ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002613{
2614 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002615 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00002616 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00002617 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2618
Jim Inghamacff8952013-05-02 00:27:30 +00002619 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002620 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002621 {
Jim Inghamacff8952013-05-02 00:27:30 +00002622 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002623 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
2624 else
Jim Inghamacff8952013-05-02 00:27:30 +00002625 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00002626 }
Jim Inghamacff8952013-05-02 00:27:30 +00002627
2628 if (!error.Success())
2629 return error;
2630
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002631 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00002632 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002633
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002634 SetPrivateState (eStateDetached);
2635 ResumePrivateStateThread();
2636
2637 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00002638 return error;
2639}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002640
Jim Ingham43c555d2012-07-04 00:35:43 +00002641
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002642Error
2643ProcessGDBRemote::DoDestroy ()
2644{
2645 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002646 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002647 if (log)
2648 log->Printf ("ProcessGDBRemote::DoDestroy()");
2649
Jim Ingham43c555d2012-07-04 00:35:43 +00002650 // There is a bug in older iOS debugservers where they don't shut down the process
2651 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
2652 // this can cause problems with restarting. So we check to see if any of our threads are stopped
2653 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
2654 // destroy it again.
2655 //
2656 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
2657 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
2658 // the debugservers with this bug are equal. There really should be a better way to test this!
2659 //
2660 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
2661 // get called here to destroy again and we're still at a breakpoint or exception, then we should
2662 // just do the straight-forward kill.
2663 //
2664 // And of course, if we weren't able to stop the process by the time we get here, it isn't
2665 // necessary (or helpful) to do any of this.
2666
2667 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
2668 {
2669 PlatformSP platform_sp = GetTarget().GetPlatform();
2670
2671 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2672 if (platform_sp
2673 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00002674 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00002675 {
2676 if (m_destroy_tried_resuming)
2677 {
2678 if (log)
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002679 log->PutCString ("ProcessGDBRemote::DoDestroy() - Tried resuming to destroy once already, not doing it again.");
Jim Ingham43c555d2012-07-04 00:35:43 +00002680 }
2681 else
2682 {
2683 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
2684 // but we really need it to happen here and it doesn't matter if we do it twice.
2685 m_thread_list.DiscardThreadPlans();
2686 DisableAllBreakpointSites();
2687
2688 bool stop_looks_like_crash = false;
2689 ThreadList &threads = GetThreadList();
2690
2691 {
Jim Ingham45350372012-09-11 00:08:52 +00002692 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002693
2694 size_t num_threads = threads.GetSize();
2695 for (size_t i = 0; i < num_threads; i++)
2696 {
2697 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002698 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002699 StopReason reason = eStopReasonInvalid;
2700 if (stop_info_sp)
2701 reason = stop_info_sp->GetStopReason();
2702 if (reason == eStopReasonBreakpoint
2703 || reason == eStopReasonException)
2704 {
2705 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002706 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
2707 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00002708 stop_info_sp->GetDescription());
2709 stop_looks_like_crash = true;
2710 break;
2711 }
2712 }
2713 }
2714
2715 if (stop_looks_like_crash)
2716 {
2717 if (log)
2718 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
2719 m_destroy_tried_resuming = true;
2720
2721 // If we are going to run again before killing, it would be good to suspend all the threads
2722 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
2723 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
2724 // have to run the risk of letting those threads proceed a bit.
2725
2726 {
Jim Ingham45350372012-09-11 00:08:52 +00002727 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002728
2729 size_t num_threads = threads.GetSize();
2730 for (size_t i = 0; i < num_threads; i++)
2731 {
2732 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002733 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002734 StopReason reason = eStopReasonInvalid;
2735 if (stop_info_sp)
2736 reason = stop_info_sp->GetStopReason();
2737 if (reason != eStopReasonBreakpoint
2738 && reason != eStopReasonException)
2739 {
2740 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002741 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
2742 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00002743 thread_sp->SetResumeState(eStateSuspended);
2744 }
2745 }
2746 }
2747 Resume ();
Jason Molendaede31932015-04-17 05:01:58 +00002748 return Destroy(false);
Jim Ingham43c555d2012-07-04 00:35:43 +00002749 }
2750 }
2751 }
2752 }
2753
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002754 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00002755 int exit_status = SIGABRT;
2756 std::string exit_string;
2757
Greg Clayton6ed95942011-01-22 07:12:45 +00002758 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002759 {
Jim Inghamaab78372011-10-28 01:11:35 +00002760 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00002761 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002762 StringExtractorGDBRemote response;
2763 bool send_async = true;
Tamas Berghammer912800c2015-02-24 10:23:39 +00002764 GDBRemoteCommunication::ScopedTimeout (m_gdb_comm, 3);
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002765
Greg Clayton3dedae12013-12-06 21:45:27 +00002766 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton513c26c2011-01-29 07:10:55 +00002767 {
2768 char packet_cmd = response.GetChar(0);
2769
2770 if (packet_cmd == 'W' || packet_cmd == 'X')
2771 {
Jim Inghameac0aa42014-02-21 22:36:11 +00002772#if defined(__APPLE__)
Jim Ingham9d67cc52014-02-21 22:35:29 +00002773 // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off
2774 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill
2775 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns
2776 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap
2777 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of
2778 // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2779 // Anyway, so call waitpid here to finally reap it.
2780 PlatformSP platform_sp(GetTarget().GetPlatform());
2781 if (platform_sp && platform_sp->IsHost())
2782 {
2783 int status;
2784 ::pid_t reap_pid;
2785 reap_pid = waitpid (GetID(), &status, WNOHANG);
2786 if (log)
2787 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2788 }
2789#endif
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002790 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002791 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00002792 exit_status = response.GetHexU8();
2793 }
2794 else
2795 {
2796 if (log)
2797 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2798 exit_string.assign("got unexpected response to k packet: ");
2799 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00002800 }
2801 }
2802 else
2803 {
Jim Inghambabfc382012-06-06 00:32:39 +00002804 if (log)
2805 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2806 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00002807 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002808 }
Jim Inghambabfc382012-06-06 00:32:39 +00002809 else
2810 {
2811 if (log)
Ed Masteb3a53332014-03-17 17:05:22 +00002812 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching");
Jim Inghamcfc09352012-07-27 23:57:19 +00002813 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00002814 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002815 }
Jim Inghambabfc382012-06-06 00:32:39 +00002816 else
2817 {
2818 // If we missed setting the exit status on the way out, do it here.
2819 // NB set exit status can be called multiple times, the first one sets the status.
2820 exit_string.assign("destroying when not connected to debugserver");
2821 }
2822
2823 SetExitStatus(exit_status, exit_string.c_str());
2824
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002825 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002826 KillDebugserverProcess ();
2827 return error;
2828}
2829
Greg Clayton8cda7f02013-05-21 21:55:59 +00002830void
2831ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2832{
Greg Clayton8cda7f02013-05-21 21:55:59 +00002833 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2834 if (did_exec)
2835 {
2836 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2837 if (log)
2838 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2839
2840 m_thread_list_real.Clear();
2841 m_thread_list.Clear();
2842 BuildDynamicRegisterInfo (true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002843 m_gdb_comm.ResetDiscoverableSettings (did_exec);
Greg Clayton8cda7f02013-05-21 21:55:59 +00002844 }
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002845
2846 // Scope the lock
2847 {
2848 // Lock the thread stack while we access it
2849 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
Greg Clayton2e309072015-07-17 23:42:28 +00002850
2851 // We are are not using non-stop mode, there can only be one last stop
2852 // reply packet, so clear the list.
2853 if (GetTarget().GetNonStopModeEnabled() == false)
2854 m_stop_packet_stack.clear();
2855
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002856 // Add this stop packet to the stop packet stack
2857 // This stack will get popped and examined when we switch to the
2858 // Stopped state
2859 m_stop_packet_stack.push_back(response);
2860 }
Greg Clayton8cda7f02013-05-21 21:55:59 +00002861}
2862
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002863//------------------------------------------------------------------
2864// Process Queries
2865//------------------------------------------------------------------
2866
2867bool
2868ProcessGDBRemote::IsAlive ()
2869{
Greg Clayton10177aa2010-12-08 05:08:21 +00002870 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002871}
2872
2873addr_t
2874ProcessGDBRemote::GetImageInfoAddress()
2875{
Aidan Doddsc0c83852015-05-08 09:36:31 +00002876 // request the link map address via the $qShlibInfoAddr packet
2877 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2878
2879 // the loaded module list can also provides a link map address
2880 if (addr == LLDB_INVALID_ADDRESS)
2881 {
2882 GDBLoadedModuleInfoList list;
2883 if (GetLoadedModuleList (list).Success())
2884 addr = list.m_link_map;
2885 }
2886
2887 return addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002888}
2889
Greg Clayton2e309072015-07-17 23:42:28 +00002890void
2891ProcessGDBRemote::WillPublicStop ()
2892{
2893 // See if the GDB remote client supports the JSON threads info.
2894 // If so, we gather stop info for all threads, expedited registers,
2895 // expedited memory, runtime queue information (iOS and MacOSX only),
2896 // and more. Expediting memory will help stack backtracing be much
2897 // faster. Expediting registers will make sure we don't have to read
2898 // the thread registers for GPRs.
2899 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
2900
2901 if (m_jthreadsinfo_sp)
2902 {
2903 // Now set the stop info for each thread and also expedite any registers
2904 // and memory that was in the jThreadsInfo response.
2905 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
2906 if (thread_infos)
2907 {
2908 const size_t n = thread_infos->GetSize();
2909 for (size_t i=0; i<n; ++i)
2910 {
2911 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
2912 if (thread_dict)
2913 SetThreadStopInfo(thread_dict);
2914 }
2915 }
2916 }
2917}
2918
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002919//------------------------------------------------------------------
2920// Process Memory
2921//------------------------------------------------------------------
2922size_t
2923ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2924{
Jason Molenda6076bf42014-05-06 04:34:52 +00002925 GetMaxMemorySize ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002926 if (size > m_max_memory_size)
2927 {
2928 // Keep memory read sizes down to a sane limit. This function will be
2929 // called multiple times in order to complete the task by
2930 // lldb_private::Process so it is ok to do this.
2931 size = m_max_memory_size;
2932 }
2933
2934 char packet[64];
Jason Molenda6076bf42014-05-06 04:34:52 +00002935 int packet_len;
2936 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2937 if (binary_memory_read)
2938 {
2939 packet_len = ::snprintf (packet, sizeof(packet), "x0x%" PRIx64 ",0x%" PRIx64, (uint64_t)addr, (uint64_t)size);
2940 }
2941 else
2942 {
2943 packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
2944 }
Andy Gibbsa297a972013-06-19 19:04:53 +00002945 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002946 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002947 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002948 {
Greg Clayton576d8832011-03-22 04:00:09 +00002949 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002950 {
2951 error.Clear();
Jason Molenda6076bf42014-05-06 04:34:52 +00002952 if (binary_memory_read)
2953 {
2954 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any
2955 // 0x7d character escaping that was present in the packet
2956
2957 size_t data_received_size = response.GetBytesLeft();
2958 if (data_received_size > size)
2959 {
2960 // Don't write past the end of BUF if the remote debug server gave us too
2961 // much data for some reason.
2962 data_received_size = size;
2963 }
2964 memcpy (buf, response.GetStringRef().data(), data_received_size);
2965 return data_received_size;
2966 }
2967 else
2968 {
2969 return response.GetHexBytes(buf, size, '\xdd');
2970 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002971 }
Greg Clayton576d8832011-03-22 04:00:09 +00002972 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002973 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002974 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002975 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002976 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002977 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002978 }
2979 else
2980 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002981 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002982 }
2983 return 0;
2984}
2985
2986size_t
2987ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2988{
Jason Molenda6076bf42014-05-06 04:34:52 +00002989 GetMaxMemorySize ();
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002990 if (size > m_max_memory_size)
2991 {
2992 // Keep memory read sizes down to a sane limit. This function will be
2993 // called multiple times in order to complete the task by
2994 // lldb_private::Process so it is ok to do this.
2995 size = m_max_memory_size;
2996 }
2997
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002998 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00002999 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Clayton7fb56d02011-02-01 01:31:41 +00003000 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003001 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003002 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003003 {
Greg Clayton576d8832011-03-22 04:00:09 +00003004 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003005 {
3006 error.Clear();
3007 return size;
3008 }
Greg Clayton576d8832011-03-22 04:00:09 +00003009 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00003010 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00003011 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00003012 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003013 else
Greg Clayton9944cd72012-09-19 01:46:31 +00003014 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 +00003015 }
3016 else
3017 {
Jim Ingham35579dd2013-06-03 19:34:01 +00003018 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003019 }
3020 return 0;
3021}
3022
3023lldb::addr_t
3024ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
3025{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003026 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_EXPRESSIONS));
Greg Clayton2a48f522011-05-14 01:50:35 +00003027 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
3028
Greg Clayton70b57652011-05-15 01:25:55 +00003029 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton2a48f522011-05-14 01:50:35 +00003030 switch (supported)
3031 {
3032 case eLazyBoolCalculate:
3033 case eLazyBoolYes:
3034 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
3035 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
3036 return allocated_addr;
3037
3038 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003039 // Call mmap() to create memory in the inferior..
3040 unsigned prot = 0;
3041 if (permissions & lldb::ePermissionsReadable)
3042 prot |= eMmapProtRead;
3043 if (permissions & lldb::ePermissionsWritable)
3044 prot |= eMmapProtWrite;
3045 if (permissions & lldb::ePermissionsExecutable)
3046 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00003047
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003048 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
3049 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
3050 m_addr_to_mmap_size[allocated_addr] = size;
3051 else
Todd Fialaaf245d12014-06-30 21:05:18 +00003052 {
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003053 allocated_addr = LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00003054 if (log)
3055 log->Printf ("ProcessGDBRemote::%s no direct stub support for memory allocation, and InferiorCallMmap also failed - is stub missing register context save/restore capability?", __FUNCTION__);
3056 }
Greg Clayton2a48f522011-05-14 01:50:35 +00003057 break;
3058 }
3059
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003060 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00003061 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003062 else
3063 error.Clear();
3064 return allocated_addr;
3065}
3066
3067Error
Greg Clayton46fb5582011-11-18 07:03:08 +00003068ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
3069 MemoryRegionInfo &region_info)
3070{
3071
3072 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
3073 return error;
3074}
3075
3076Error
Johnny Chen64637202012-05-23 21:09:52 +00003077ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
3078{
3079
3080 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
3081 return error;
3082}
3083
3084Error
Enrico Granataf04a2192012-07-13 23:18:48 +00003085ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
3086{
3087 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
3088 return error;
3089}
3090
3091Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003092ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
3093{
3094 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00003095 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
3096
3097 switch (supported)
3098 {
3099 case eLazyBoolCalculate:
3100 // We should never be deallocating memory without allocating memory
3101 // first so we should never get eLazyBoolCalculate
3102 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
3103 break;
3104
3105 case eLazyBoolYes:
3106 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00003107 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003108 break;
3109
3110 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003111 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00003112 {
3113 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003114 if (pos != m_addr_to_mmap_size.end() &&
3115 InferiorCallMunmap(this, addr, pos->second))
3116 m_addr_to_mmap_size.erase (pos);
3117 else
Daniel Malead01b2952012-11-29 21:49:15 +00003118 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003119 }
3120 break;
3121 }
3122
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003123 return error;
3124}
3125
3126
3127//------------------------------------------------------------------
3128// Process STDIO
3129//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003130size_t
3131ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
3132{
3133 if (m_stdio_communication.IsConnected())
3134 {
3135 ConnectionStatus status;
3136 m_stdio_communication.Write(src, src_len, status, NULL);
3137 }
Vince Harrondf3f00f2015-02-10 21:09:04 +00003138 else if (m_stdin_forward)
Vince Harrone0be4252015-02-06 18:32:57 +00003139 {
3140 m_gdb_comm.SendStdinNotification(src, src_len);
3141 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003142 return 0;
3143}
3144
3145Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003146ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003147{
3148 Error error;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003149 assert(bp_site != NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003150
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003151 // Get logging info
3152 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003153 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003154
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003155 // Get the breakpoint address
3156 const addr_t addr = bp_site->GetLoadAddress();
3157
3158 // Log that a breakpoint was requested
3159 if (log)
3160 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
3161
3162 // Breakpoint already exists and is enabled
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003163 if (bp_site->IsEnabled())
3164 {
3165 if (log)
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003166 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 +00003167 return error;
3168 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003169
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003170 // Get the software breakpoint trap opcode size
3171 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3172
3173 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
3174 // is supported by the remote stub. These are set to true by default, and later set to false
3175 // only after we receive an unimplemented response when sending a breakpoint packet. This means
3176 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
3177 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
3178 // indicates if the user specifically asked for hardware breakpoints. If true then we will
3179 // skip over software breakpoints.
3180 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
3181 {
3182 // Try to send off a software breakpoint packet ($Z0)
3183 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003184 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003185 // The breakpoint was placed successfully
3186 bp_site->SetEnabled(true);
3187 bp_site->SetType(BreakpointSite::eExternal);
Greg Claytoneb023e72013-10-11 19:48:25 +00003188 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003189 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003190
3191 // SendGDBStoppointTypePacket() will return an error if it was unable to set this
3192 // breakpoint. We need to differentiate between a error specific to placing this breakpoint
3193 // or if we have learned that this breakpoint type is unsupported. To do this, we
3194 // must test the support boolean for this breakpoint type to see if it now indicates that
3195 // this breakpoint type is unsupported. If they are still supported then we should return
3196 // with the error code. If they are now unsupported, then we would like to fall through
3197 // and try another form of breakpoint.
3198 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
3199 return error;
3200
3201 // We reach here when software breakpoints have been found to be unsupported. For future
3202 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
3203 // known not to be supported.
3204 if (log)
3205 log->Printf("Software breakpoints are unsupported");
3206
3207 // So we will fall through and try a hardware breakpoint
3208 }
3209
3210 // The process of setting a hardware breakpoint is much the same as above. We check the
3211 // supported boolean for this breakpoint type, and if it is thought to be supported then we
3212 // will try to set this breakpoint with a hardware breakpoint.
3213 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3214 {
3215 // Try to send off a hardware breakpoint packet ($Z1)
3216 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003217 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003218 // The breakpoint was placed successfully
3219 bp_site->SetEnabled(true);
3220 bp_site->SetType(BreakpointSite::eHardware);
3221 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003222 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003223
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003224 // Check if the error was something other then an unsupported breakpoint type
3225 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3226 {
3227 // Unable to set this hardware breakpoint
3228 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
3229 return error;
3230 }
3231
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003232 // We will reach here when the stub gives an unsupported response to a hardware breakpoint
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003233 if (log)
3234 log->Printf("Hardware breakpoints are unsupported");
3235
3236 // Finally we will falling through to a #trap style breakpoint
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003237 }
3238
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003239 // Don't fall through when hardware breakpoints were specifically requested
3240 if (bp_site->HardwareRequired())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003241 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003242 error.SetErrorString("hardware breakpoints are not supported");
3243 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003244 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003245
3246 // As a last resort we want to place a manual breakpoint. An instruction
3247 // is placed into the process memory using memory write packets.
3248 return EnableSoftwareBreakpoint(bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003249}
3250
3251Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003252ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003253{
3254 Error error;
3255 assert (bp_site != NULL);
3256 addr_t addr = bp_site->GetLoadAddress();
3257 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00003258 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003259 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003260 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003261
3262 if (bp_site->IsEnabled())
3263 {
3264 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
3265
Greg Clayton8b82f082011-04-12 05:54:46 +00003266 BreakpointSite::Type bp_type = bp_site->GetType();
3267 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003268 {
Greg Clayton8b82f082011-04-12 05:54:46 +00003269 case BreakpointSite::eSoftware:
3270 error = DisableSoftwareBreakpoint (bp_site);
3271 break;
3272
3273 case BreakpointSite::eHardware:
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003274 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003275 error.SetErrorToGenericError();
3276 break;
3277
3278 case BreakpointSite::eExternal:
Jim Inghama04ef752014-03-07 11:18:02 +00003279 {
3280 GDBStoppointType stoppoint_type;
3281 if (bp_site->IsHardware())
3282 stoppoint_type = eBreakpointHardware;
3283 else
3284 stoppoint_type = eBreakpointSoftware;
3285
3286 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003287 error.SetErrorToGenericError();
Jim Inghama04ef752014-03-07 11:18:02 +00003288 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003289 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003290 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003291 if (error.Success())
3292 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003293 }
3294 else
3295 {
3296 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003297 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 +00003298 return error;
3299 }
3300
3301 if (error.Success())
3302 error.SetErrorToGenericError();
3303 return error;
3304}
3305
Johnny Chen11309a32011-09-06 22:38:36 +00003306// Pre-requisite: wp != NULL.
3307static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00003308GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00003309{
3310 assert(wp);
3311 bool watch_read = wp->WatchpointRead();
3312 bool watch_write = wp->WatchpointWrite();
3313
3314 // watch_read and watch_write cannot both be false.
3315 assert(watch_read || watch_write);
3316 if (watch_read && watch_write)
3317 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00003318 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00003319 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00003320 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00003321 return eWatchpointWrite;
3322}
3323
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003324Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003325ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003326{
3327 Error error;
3328 if (wp)
3329 {
3330 user_id_t watchID = wp->GetID();
3331 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00003332 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003333 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003334 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003335 if (wp->IsEnabled())
3336 {
3337 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003338 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 +00003339 return error;
3340 }
Johnny Chen11309a32011-09-06 22:38:36 +00003341
3342 GDBStoppointType type = GetGDBStoppointType(wp);
3343 // Pass down an appropriate z/Z packet...
3344 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003345 {
Johnny Chen11309a32011-09-06 22:38:36 +00003346 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
3347 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003348 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003349 return error;
3350 }
3351 else
3352 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003353 }
Johnny Chen11309a32011-09-06 22:38:36 +00003354 else
3355 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003356 }
3357 else
3358 {
Johnny Chen01a67862011-10-14 00:42:25 +00003359 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003360 }
3361 if (error.Success())
3362 error.SetErrorToGenericError();
3363 return error;
3364}
3365
3366Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003367ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003368{
3369 Error error;
3370 if (wp)
3371 {
3372 user_id_t watchID = wp->GetID();
3373
Greg Clayton5160ce52013-03-27 23:08:40 +00003374 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003375
3376 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00003377
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003378 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003379 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003380
Johnny Chen11309a32011-09-06 22:38:36 +00003381 if (!wp->IsEnabled())
3382 {
3383 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003384 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 +00003385 // See also 'class WatchpointSentry' within StopInfo.cpp.
3386 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
3387 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00003388 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003389 return error;
3390 }
3391
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003392 if (wp->IsHardware())
3393 {
Johnny Chen11309a32011-09-06 22:38:36 +00003394 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003395 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00003396 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
3397 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003398 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003399 return error;
3400 }
3401 else
3402 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003403 }
3404 // TODO: clear software watchpoints if we implement them
3405 }
3406 else
3407 {
Johnny Chen01a67862011-10-14 00:42:25 +00003408 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003409 }
3410 if (error.Success())
3411 error.SetErrorToGenericError();
3412 return error;
3413}
3414
3415void
3416ProcessGDBRemote::Clear()
3417{
3418 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00003419 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003420 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003421}
3422
3423Error
3424ProcessGDBRemote::DoSignal (int signo)
3425{
3426 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00003427 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003428 if (log)
3429 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
3430
3431 if (!m_gdb_comm.SendAsyncSignal (signo))
3432 error.SetErrorStringWithFormat("failed to send signal %i", signo);
3433 return error;
3434}
3435
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003436Error
Greg Clayton91a9b2472013-12-04 19:19:12 +00003437ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003438{
3439 Error error;
3440 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
3441 {
3442 // If we locate debugserver, keep that located version around
3443 static FileSpec g_debugserver_file_spec;
3444
Han Ming Ong84647042012-02-25 01:07:38 +00003445 ProcessLaunchInfo debugserver_launch_info;
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00003446 // Make debugserver run in its own session so signals generated by
3447 // special terminal key sequences (^C) don't affect debugserver.
3448 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3449
Greg Clayton91a9b2472013-12-04 19:19:12 +00003450 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
3451 debugserver_launch_info.SetUserID(process_info.GetUserID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003452
Todd Fiala013434e2014-07-09 01:29:05 +00003453#if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__) || defined (__aarch64__))
Greg Claytonfda4fab2014-01-10 22:24:11 +00003454 // On iOS, still do a local connection using a random port
Greg Clayton16810922014-02-27 19:38:18 +00003455 const char *hostname = "127.0.0.1";
Greg Claytonfda4fab2014-01-10 22:24:11 +00003456 uint16_t port = get_random_port ();
3457#else
3458 // Set hostname being NULL to do the reverse connect where debugserver
3459 // will bind to port zero and it will communicate back to us the port
3460 // that we will connect to
3461 const char *hostname = NULL;
3462 uint16_t port = 0;
3463#endif
3464
3465 error = m_gdb_comm.StartDebugserverProcess (hostname,
3466 port,
Greg Clayton00fe87b2013-12-05 22:58:22 +00003467 debugserver_launch_info,
3468 port);
Greg Clayton91a9b2472013-12-04 19:19:12 +00003469
3470 if (error.Success ())
3471 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003472 else
Greg Clayton91a9b2472013-12-04 19:19:12 +00003473 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003474
3475 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3476 StartAsyncThread ();
Greg Clayton91a9b2472013-12-04 19:19:12 +00003477
3478 if (error.Fail())
3479 {
3480 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
3481
3482 if (log)
3483 log->Printf("failed to start debugserver process: %s", error.AsCString());
3484 return error;
3485 }
3486
Greg Clayton00fe87b2013-12-05 22:58:22 +00003487 if (m_gdb_comm.IsConnected())
3488 {
3489 // Finish the connection process by doing the handshake without connecting (send NULL URL)
3490 ConnectToDebugserver (NULL);
3491 }
3492 else
3493 {
Greg Claytonfda4fab2014-01-10 22:24:11 +00003494 StreamString connect_url;
3495 connect_url.Printf("connect://%s:%u", hostname, port);
3496 error = ConnectToDebugserver (connect_url.GetString().c_str());
Greg Clayton00fe87b2013-12-05 22:58:22 +00003497 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00003498
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003499 }
3500 return error;
3501}
3502
3503bool
3504ProcessGDBRemote::MonitorDebugserverProcess
3505(
3506 void *callback_baton,
3507 lldb::pid_t debugserver_pid,
Greg Claytone4e45922011-11-16 05:37:56 +00003508 bool exited, // True if the process did exit
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003509 int signo, // Zero for no signal
3510 int exit_status // Exit value of process if signal is zero
3511)
3512{
Greg Claytone4e45922011-11-16 05:37:56 +00003513 // The baton is a "ProcessGDBRemote *". Now this class might be gone
3514 // and might not exist anymore, so we need to carefully try to get the
3515 // target for this process first since we have a race condition when
3516 // we are done running between getting the notice that the inferior
3517 // process has died and the debugserver that was debugging this process.
3518 // In our test suite, we are also continually running process after
3519 // process, so we must be very careful to make sure:
3520 // 1 - process object hasn't been deleted already
3521 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003522
3523 // "debugserver_pid" argument passed in is the process ID for
3524 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00003525 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003526
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003527 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton6779606a2011-01-22 23:43:18 +00003528
Greg Claytone4e45922011-11-16 05:37:56 +00003529 // Get a shared pointer to the target that has a matching process pointer.
3530 // This target could be gone, or the target could already have a new process
3531 // object inside of it
3532 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
3533
Greg Clayton6779606a2011-01-22 23:43:18 +00003534 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003535 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 +00003536
Greg Claytone4e45922011-11-16 05:37:56 +00003537 if (target_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003538 {
Greg Claytone4e45922011-11-16 05:37:56 +00003539 // We found a process in a target that matches, but another thread
3540 // might be in the process of launching a new process that will
3541 // soon replace it, so get a shared pointer to the process so we
3542 // can keep it alive.
3543 ProcessSP process_sp (target_sp->GetProcessSP());
3544 // Now we have a shared pointer to the process that can't go away on us
3545 // so we now make sure it was the same as the one passed in, and also make
3546 // sure that our previous "process *" didn't get deleted and have a new
3547 // "process *" created in its place with the same pointer. To verify this
3548 // we make sure the process has our debugserver process ID. If we pass all
3549 // of these tests, then we are sure that this process is the one we were
3550 // looking for.
3551 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003552 {
Greg Claytone4e45922011-11-16 05:37:56 +00003553 // Sleep for a half a second to make sure our inferior process has
3554 // time to set its exit status before we set it incorrectly when
3555 // both the debugserver and the inferior process shut down.
3556 usleep (500000);
3557 // If our process hasn't yet exited, debugserver might have died.
3558 // If the process did exit, the we are reaping it.
3559 const StateType state = process->GetState();
3560
3561 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
3562 state != eStateInvalid &&
3563 state != eStateUnloaded &&
3564 state != eStateExited &&
3565 state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003566 {
Greg Claytone4e45922011-11-16 05:37:56 +00003567 char error_str[1024];
3568 if (signo)
3569 {
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00003570 const char *signal_cstr = process->GetUnixSignals()->GetSignalAsCString(signo);
Greg Claytone4e45922011-11-16 05:37:56 +00003571 if (signal_cstr)
3572 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3573 else
3574 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
3575 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003576 else
Greg Claytone4e45922011-11-16 05:37:56 +00003577 {
3578 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
3579 }
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003580
Greg Claytone4e45922011-11-16 05:37:56 +00003581 process->SetExitStatus (-1, error_str);
3582 }
3583 // Debugserver has exited we need to let our ProcessGDBRemote
3584 // know that it no longer has a debugserver instance
3585 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003586 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003587 }
3588 return true;
3589}
3590
3591void
3592ProcessGDBRemote::KillDebugserverProcess ()
3593{
Greg Claytonfbb76342013-11-20 21:07:01 +00003594 m_gdb_comm.Disconnect();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003595 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3596 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003597 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003598 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3599 }
3600}
3601
3602void
3603ProcessGDBRemote::Initialize()
3604{
Davide Italianoc8d69822015-04-03 04:24:32 +00003605 static std::once_flag g_once_flag;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003606
Davide Italianoc8d69822015-04-03 04:24:32 +00003607 std::call_once(g_once_flag, []()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003608 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003609 PluginManager::RegisterPlugin (GetPluginNameStatic(),
3610 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00003611 CreateInstance,
3612 DebuggerInitialize);
Davide Italianoc8d69822015-04-03 04:24:32 +00003613 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003614}
3615
Greg Clayton7f982402013-07-15 22:54:20 +00003616void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003617ProcessGDBRemote::DebuggerInitialize (Debugger &debugger)
Greg Clayton7f982402013-07-15 22:54:20 +00003618{
3619 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
3620 {
3621 const bool is_global_setting = true;
3622 PluginManager::CreateSettingForProcessPlugin (debugger,
3623 GetGlobalPluginProperties()->GetValueProperties(),
3624 ConstString ("Properties for the gdb-remote process plug-in."),
3625 is_global_setting);
3626 }
3627}
3628
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003629bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003630ProcessGDBRemote::StartAsyncThread ()
3631{
Greg Clayton5160ce52013-03-27 23:08:40 +00003632 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003633
3634 if (log)
3635 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003636
3637 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003638 if (!m_async_thread.IsJoinable())
Jim Ingham455fa5c2012-11-01 01:15:33 +00003639 {
3640 // Create a thread that watches our internal state and controls which
3641 // events make it to clients (into the DCProcess event queue).
Zachary Turner39de3112014-09-09 20:54:56 +00003642
3643 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003644 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003645 else if (log)
3646 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was already running.", __FUNCTION__);
Zachary Turner39de3112014-09-09 20:54:56 +00003647
Zachary Turneracee96a2014-09-23 18:32:09 +00003648 return m_async_thread.IsJoinable();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003649}
3650
3651void
3652ProcessGDBRemote::StopAsyncThread ()
3653{
Greg Clayton5160ce52013-03-27 23:08:40 +00003654 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003655
3656 if (log)
3657 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
3658
Jim Ingham455fa5c2012-11-01 01:15:33 +00003659 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003660 if (m_async_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003661 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00003662 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
3663
3664 // This will shut down the async thread.
3665 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3666
3667 // Stop the stdio thread
Zachary Turner39de3112014-09-09 20:54:56 +00003668 m_async_thread.Join(nullptr);
Pavel Labatha55a9532015-03-11 09:53:42 +00003669 m_async_thread.Reset();
Jim Ingham455fa5c2012-11-01 01:15:33 +00003670 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003671 else if (log)
3672 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003673}
3674
Ewan Crawford76df2882015-06-23 12:32:06 +00003675bool
3676ProcessGDBRemote::HandleNotifyPacket (StringExtractorGDBRemote &packet)
3677{
3678 // get the packet at a string
3679 const std::string &pkt = packet.GetStringRef();
3680 // skip %stop:
3681 StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
3682
3683 // pass as a thread stop info packet
3684 SetLastStopPacket(stop_info);
3685
3686 // check for more stop reasons
3687 HandleStopReplySequence();
3688
3689 // if the process is stopped then we need to fake a resume
3690 // so that we can stop properly with the new break. This
3691 // is possible due to SetPrivateState() broadcasting the
3692 // state change as a side effect.
3693 if (GetPrivateState() == lldb::StateType::eStateStopped)
3694 {
3695 SetPrivateState(lldb::StateType::eStateRunning);
3696 }
3697
3698 // since we have some stopped packets we can halt the process
3699 SetPrivateState(lldb::StateType::eStateStopped);
3700
3701 return true;
3702}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003703
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003704thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003705ProcessGDBRemote::AsyncThread (void *arg)
3706{
3707 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
3708
Greg Clayton5160ce52013-03-27 23:08:40 +00003709 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003710 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003711 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003712
3713 Listener listener ("ProcessGDBRemote::AsyncThread");
3714 EventSP event_sp;
3715 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
3716 eBroadcastBitAsyncThreadShouldExit;
3717
3718 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
3719 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003720 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit |
3721 GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify);
3722
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003723 bool done = false;
3724 while (!done)
3725 {
3726 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003727 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003728 if (listener.WaitForEvent (NULL, event_sp))
3729 {
3730 const uint32_t event_type = event_sp->GetType();
Greg Clayton71337622011-02-24 22:24:29 +00003731 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003732 {
Greg Clayton71337622011-02-24 22:24:29 +00003733 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003734 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 +00003735
Greg Clayton71337622011-02-24 22:24:29 +00003736 switch (event_type)
3737 {
3738 case eBroadcastBitAsyncContinue:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003739 {
Greg Clayton71337622011-02-24 22:24:29 +00003740 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003741
Greg Clayton71337622011-02-24 22:24:29 +00003742 if (continue_packet)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003743 {
Greg Clayton71337622011-02-24 22:24:29 +00003744 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
3745 const size_t continue_cstr_len = continue_packet->GetByteSize ();
3746 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003747 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003748
Greg Clayton71337622011-02-24 22:24:29 +00003749 if (::strstr (continue_cstr, "vAttach") == NULL)
3750 process->SetPrivateState(eStateRunning);
3751 StringExtractorGDBRemote response;
Ewan Crawford76df2882015-06-23 12:32:06 +00003752
3753 // If in Non-Stop-Mode
3754 if (process->GetTarget().GetNonStopModeEnabled())
Greg Clayton71337622011-02-24 22:24:29 +00003755 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003756 // send the vCont packet
3757 if (!process->GetGDBRemote().SendvContPacket(process, continue_cstr, continue_cstr_len, response))
Jason Molendaa3329782014-03-29 18:54:20 +00003758 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003759 // Something went wrong
3760 done = true;
3761 break;
3762 }
3763 }
3764 // If in All-Stop-Mode
3765 else
3766 {
3767 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
3768
3769 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
3770 // The thread ID list might be contained within the "response", or the stop reply packet that
3771 // caused the stop. So clear it now before we give the stop reply packet to the process
3772 // using the process->SetLastStopPacket()...
3773 process->ClearThreadIDList ();
3774
3775 switch (stop_state)
3776 {
3777 case eStateStopped:
3778 case eStateCrashed:
3779 case eStateSuspended:
3780 process->SetLastStopPacket (response);
3781 process->SetPrivateState (stop_state);
3782 break;
3783
3784 case eStateExited:
3785 {
3786 process->SetLastStopPacket (response);
3787 process->ClearThreadIDList();
3788 response.SetFilePos(1);
3789
3790 int exit_status = response.GetHexU8();
3791 const char *desc_cstr = NULL;
3792 StringExtractor extractor;
3793 std::string desc_string;
3794 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';')
Jason Molendaa3329782014-03-29 18:54:20 +00003795 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003796 std::string desc_token;
3797 while (response.GetNameColonValue (desc_token, desc_string))
Jason Molendaa3329782014-03-29 18:54:20 +00003798 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003799 if (desc_token == "description")
3800 {
3801 extractor.GetStringRef().swap(desc_string);
3802 extractor.SetFilePos(0);
3803 extractor.GetHexByteString (desc_string);
3804 desc_cstr = desc_string.c_str();
3805 }
Jason Molendaa3329782014-03-29 18:54:20 +00003806 }
3807 }
Ewan Crawford76df2882015-06-23 12:32:06 +00003808 process->SetExitStatus(exit_status, desc_cstr);
3809 done = true;
3810 break;
Jason Molendaa3329782014-03-29 18:54:20 +00003811 }
Ewan Crawford76df2882015-06-23 12:32:06 +00003812 case eStateInvalid:
Jason Molenda752e1e82015-07-29 01:42:16 +00003813 {
3814 // Check to see if we were trying to attach and if we got back
3815 // the "E87" error code from debugserver -- this indicates that
3816 // the process is not debuggable. Return a slightly more helpful
3817 // error message about why the attach failed.
3818 if (::strstr (continue_cstr, "vAttach") != NULL
3819 && response.GetError() == 0x87)
3820 {
3821 process->SetExitStatus(-1, "cannot attach to process due to System Integrity Protection");
3822 }
3823 // E01 code from vAttach means that the attach failed
3824 if (::strstr (continue_cstr, "vAttach") != NULL
3825 && response.GetError() == 0x1)
3826 {
3827 process->SetExitStatus(-1, "unable to attach");
3828 }
3829 else
3830 {
3831 process->SetExitStatus(-1, "lost connection");
3832 }
3833 break;
3834 }
Greg Clayton71337622011-02-24 22:24:29 +00003835
Ewan Crawford76df2882015-06-23 12:32:06 +00003836 default:
3837 process->SetPrivateState (stop_state);
3838 break;
3839 } // switch(stop_state)
3840 } // else // if in All-stop-mode
3841 } // if (continue_packet)
3842 } // case eBroadcastBitAysncContinue
Greg Clayton71337622011-02-24 22:24:29 +00003843 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003844
Greg Clayton71337622011-02-24 22:24:29 +00003845 case eBroadcastBitAsyncThreadShouldExit:
3846 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003847 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Clayton71337622011-02-24 22:24:29 +00003848 done = true;
3849 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003850
Greg Clayton71337622011-02-24 22:24:29 +00003851 default:
3852 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003853 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 +00003854 done = true;
3855 break;
3856 }
3857 }
3858 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
3859 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003860 switch (event_type)
Greg Clayton71337622011-02-24 22:24:29 +00003861 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003862 case Communication::eBroadcastBitReadThreadDidExit:
3863 process->SetExitStatus (-1, "lost connection");
3864 done = true;
3865 break;
3866
3867 case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify:
3868 {
3869 lldb_private::Event *event = event_sp.get();
3870 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event);
3871 StringExtractorGDBRemote notify((const char*)continue_packet->GetBytes());
3872 // Hand this over to the process to handle
3873 process->HandleNotifyPacket(notify);
3874 break;
3875 }
3876
3877 default:
3878 if (log)
3879 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
3880 done = true;
3881 break;
Greg Clayton71337622011-02-24 22:24:29 +00003882 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003883 }
3884 }
3885 else
3886 {
3887 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003888 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 +00003889 done = true;
3890 }
3891 }
3892 }
3893
3894 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003895 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003896
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003897 return NULL;
3898}
3899
Greg Claytone996fd32011-03-08 22:40:15 +00003900//uint32_t
3901//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3902//{
3903// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
3904// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
3905// if (m_local_debugserver)
3906// {
3907// return Host::ListProcessesMatchingName (name, matches, pids);
3908// }
3909// else
3910// {
3911// // FIXME: Implement talking to the remote debugserver.
3912// return 0;
3913// }
3914//
3915//}
3916//
Jim Ingham1c823b42011-01-22 01:33:44 +00003917bool
3918ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003919 StoppointCallbackContext *context,
Jim Ingham1c823b42011-01-22 01:33:44 +00003920 lldb::user_id_t break_id,
3921 lldb::user_id_t break_loc_id)
3922{
3923 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3924 // run so I can stop it if that's what I want to do.
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003925 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00003926 if (log)
3927 log->Printf("Hit New Thread Notification breakpoint.");
3928 return false;
3929}
3930
3931
3932bool
3933ProcessGDBRemote::StartNoticingNewThreads()
3934{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003935 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00003936 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003937 {
Greg Clayton4116e932012-05-15 02:33:01 +00003938 if (log && log->GetVerbose())
3939 log->Printf("Enabled noticing new thread breakpoint.");
3940 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003941 }
Greg Clayton4116e932012-05-15 02:33:01 +00003942 else
Jim Ingham1c823b42011-01-22 01:33:44 +00003943 {
Greg Clayton4116e932012-05-15 02:33:01 +00003944 PlatformSP platform_sp (m_target.GetPlatform());
3945 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003946 {
Greg Clayton4116e932012-05-15 02:33:01 +00003947 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3948 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003949 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00003950 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00003951 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3952 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003953 }
3954 else
3955 {
3956 if (log)
3957 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00003958 }
3959 }
3960 }
Greg Clayton4116e932012-05-15 02:33:01 +00003961 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00003962}
3963
3964bool
3965ProcessGDBRemote::StopNoticingNewThreads()
3966{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003967 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00003968 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00003969 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00003970
3971 if (m_thread_create_bp_sp)
3972 m_thread_create_bp_sp->SetEnabled(false);
3973
Jim Ingham1c823b42011-01-22 01:33:44 +00003974 return true;
3975}
3976
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003977DynamicLoader *
Jason Molenda5e8534e2012-10-03 01:29:34 +00003978ProcessGDBRemote::GetDynamicLoader ()
3979{
3980 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00003981 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00003982 return m_dyld_ap.get();
3983}
Jim Ingham1c823b42011-01-22 01:33:44 +00003984
Jason Molendaa3329782014-03-29 18:54:20 +00003985Error
3986ProcessGDBRemote::SendEventData(const char *data)
3987{
3988 int return_value;
3989 bool was_supported;
3990
3991 Error error;
3992
3993 return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported);
3994 if (return_value != 0)
3995 {
3996 if (!was_supported)
3997 error.SetErrorString("Sending events is not supported for this process.");
3998 else
3999 error.SetErrorStringWithFormat("Error sending event data: %d.", return_value);
4000 }
4001 return error;
4002}
4003
Steve Pucci03904ac2014-03-04 23:18:46 +00004004const DataBufferSP
4005ProcessGDBRemote::GetAuxvData()
4006{
4007 DataBufferSP buf;
4008 if (m_gdb_comm.GetQXferAuxvReadSupported())
4009 {
4010 std::string response_string;
4011 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success)
4012 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length()));
4013 }
4014 return buf;
4015}
4016
Jason Molenda705b1802014-06-13 02:37:02 +00004017StructuredData::ObjectSP
4018ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid)
4019{
4020 StructuredData::ObjectSP object_sp;
4021
4022 if (m_gdb_comm.GetThreadExtendedInfoSupported())
4023 {
4024 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4025 SystemRuntime *runtime = GetSystemRuntime();
4026 if (runtime)
4027 {
4028 runtime->AddThreadExtendedInfoPacketHints (args_dict);
4029 }
4030 args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid);
4031
4032 StreamString packet;
4033 packet << "jThreadExtendedInfo:";
4034 args_dict->Dump (packet);
4035
4036 // FIXME the final character of a JSON dictionary, '}', is the escape
4037 // character in gdb-remote binary mode. lldb currently doesn't escape
4038 // these characters in its packet output -- so we add the quoted version
4039 // of the } character here manually in case we talk to a debugserver which
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004040 // un-escapes the characters at packet read time.
Jason Molenda705b1802014-06-13 02:37:02 +00004041 packet << (char) (0x7d ^ 0x20);
4042
4043 StringExtractorGDBRemote response;
4044 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4045 {
4046 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4047 if (response_type == StringExtractorGDBRemote::eResponse)
4048 {
4049 if (!response.Empty())
4050 {
Jason Molenda20ee21b2015-07-10 23:15:22 +00004051 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4052 }
4053 }
4054 }
4055 }
4056 return object_sp;
4057}
4058
4059StructuredData::ObjectSP
4060ProcessGDBRemote::GetLoadedDynamicLibrariesInfos (lldb::addr_t image_list_address, lldb::addr_t image_count)
4061{
4062 StructuredData::ObjectSP object_sp;
4063
4064 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported())
4065 {
4066 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4067 args_dict->GetAsDictionary()->AddIntegerItem ("image_list_address", image_list_address);
4068 args_dict->GetAsDictionary()->AddIntegerItem ("image_count", image_count);
4069
4070 StreamString packet;
4071 packet << "jGetLoadedDynamicLibrariesInfos:";
4072 args_dict->Dump (packet);
4073
4074 // FIXME the final character of a JSON dictionary, '}', is the escape
4075 // character in gdb-remote binary mode. lldb currently doesn't escape
4076 // these characters in its packet output -- so we add the quoted version
4077 // of the } character here manually in case we talk to a debugserver which
4078 // un-escapes the characters at packet read time.
4079 packet << (char) (0x7d ^ 0x20);
4080
4081 StringExtractorGDBRemote response;
4082 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4083 {
4084 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4085 if (response_type == StringExtractorGDBRemote::eResponse)
4086 {
4087 if (!response.Empty())
4088 {
Jason Molenda705b1802014-06-13 02:37:02 +00004089 // The packet has already had the 0x7d xor quoting stripped out at the
4090 // GDBRemoteCommunication packet receive level.
4091 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4092 }
4093 }
4094 }
4095 }
4096 return object_sp;
4097}
4098
Jason Molenda20ee21b2015-07-10 23:15:22 +00004099
Jason Molenda6076bf42014-05-06 04:34:52 +00004100// Establish the largest memory read/write payloads we should use.
4101// If the remote stub has a max packet size, stay under that size.
4102//
4103// If the remote stub's max packet size is crazy large, use a
4104// reasonable largeish default.
4105//
4106// If the remote stub doesn't advertise a max packet size, use a
4107// conservative default.
4108
4109void
4110ProcessGDBRemote::GetMaxMemorySize()
4111{
4112 const uint64_t reasonable_largeish_default = 128 * 1024;
4113 const uint64_t conservative_default = 512;
4114
4115 if (m_max_memory_size == 0)
4116 {
4117 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4118 if (stub_max_size != UINT64_MAX && stub_max_size != 0)
4119 {
4120 // Save the stub's claimed maximum packet size
4121 m_remote_stub_max_memory_size = stub_max_size;
4122
4123 // Even if the stub says it can support ginormous packets,
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004124 // don't exceed our reasonable largeish default packet size.
Jason Molenda6076bf42014-05-06 04:34:52 +00004125 if (stub_max_size > reasonable_largeish_default)
4126 {
4127 stub_max_size = reasonable_largeish_default;
4128 }
4129
4130 m_max_memory_size = stub_max_size;
4131 }
4132 else
4133 {
4134 m_max_memory_size = conservative_default;
4135 }
4136 }
4137}
4138
4139void
4140ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max)
4141{
4142 if (user_specified_max != 0)
4143 {
4144 GetMaxMemorySize ();
4145
4146 if (m_remote_stub_max_memory_size != 0)
4147 {
4148 if (m_remote_stub_max_memory_size < user_specified_max)
4149 {
4150 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a packet size too big, go as big
4151 // as the remote stub says we can go.
4152 }
4153 else
4154 {
4155 m_max_memory_size = user_specified_max; // user's packet size is good
4156 }
4157 }
4158 else
4159 {
4160 m_max_memory_size = user_specified_max; // user's packet size is probably fine
4161 }
4162 }
4163}
4164
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004165bool
4166ProcessGDBRemote::GetModuleSpec(const FileSpec& module_file_spec,
4167 const ArchSpec& arch,
4168 ModuleSpec &module_spec)
4169{
4170 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PLATFORM);
4171
4172 if (!m_gdb_comm.GetModuleInfo (module_file_spec, arch, module_spec))
4173 {
4174 if (log)
4175 log->Printf ("ProcessGDBRemote::%s - failed to get module info for %s:%s",
4176 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4177 arch.GetTriple ().getTriple ().c_str ());
4178 return false;
4179 }
4180
4181 if (log)
4182 {
4183 StreamString stream;
4184 module_spec.Dump (stream);
4185 log->Printf ("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4186 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4187 arch.GetTriple ().getTriple ().c_str (), stream.GetString ().c_str ());
4188 }
4189
4190 return true;
4191}
4192
Colin Rileyc3c95b22015-04-16 15:51:33 +00004193namespace {
4194
4195typedef std::vector<std::string> stringVec;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004196
4197typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004198struct RegisterSetInfo
4199{
4200 ConstString name;
4201};
Colin Rileyc3c95b22015-04-16 15:51:33 +00004202
Greg Claytond04f0ed2015-05-26 18:00:51 +00004203typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4204
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004205struct GdbServerTargetInfo
4206{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004207 std::string arch;
4208 std::string osabi;
4209 stringVec includes;
4210 RegisterSetMap reg_set_map;
4211 XMLNode feature_node;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004212};
Greg Claytond04f0ed2015-05-26 18:00:51 +00004213
Colin Rileyc3c95b22015-04-16 15:51:33 +00004214bool
Greg Claytond04f0ed2015-05-26 18:00:51 +00004215ParseRegisters (XMLNode feature_node, GdbServerTargetInfo &target_info, GDBRemoteDynamicRegisterInfo &dyn_reg_info)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004216{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004217 if (!feature_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004218 return false;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004219
4220 uint32_t prev_reg_num = 0;
4221 uint32_t reg_offset = 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004222
Greg Claytond04f0ed2015-05-26 18:00:51 +00004223 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 +00004224 std::string gdb_group;
4225 std::string gdb_type;
4226 ConstString reg_name;
4227 ConstString alt_name;
4228 ConstString set_name;
4229 std::vector<uint32_t> value_regs;
4230 std::vector<uint32_t> invalidate_regs;
4231 bool encoding_set = false;
4232 bool format_set = false;
4233 RegisterInfo reg_info = { NULL, // Name
4234 NULL, // Alt name
4235 0, // byte size
4236 reg_offset, // offset
4237 eEncodingUint, // encoding
4238 eFormatHex, // formate
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004239 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004240 LLDB_INVALID_REGNUM, // GCC reg num
4241 LLDB_INVALID_REGNUM, // DWARF reg num
4242 LLDB_INVALID_REGNUM, // generic reg num
4243 prev_reg_num, // GDB reg num
4244 prev_reg_num // native register number
4245 },
4246 NULL,
4247 NULL
4248 };
4249
Ewan Crawford682e8422015-06-26 09:38:27 +00004250 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 +00004251 if (name == "name")
4252 {
4253 reg_name.SetString(value);
4254 }
4255 else if (name == "bitsize")
4256 {
4257 reg_info.byte_size = StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
4258 }
4259 else if (name == "type")
4260 {
4261 gdb_type = value.str();
4262 }
4263 else if (name == "group")
4264 {
4265 gdb_group = value.str();
4266 }
4267 else if (name == "regnum")
4268 {
4269 const uint32_t regnum = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4270 if (regnum != LLDB_INVALID_REGNUM)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004271 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004272 reg_info.kinds[eRegisterKindGDB] = regnum;
4273 reg_info.kinds[eRegisterKindLLDB] = regnum;
4274 prev_reg_num = regnum;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004275 }
4276 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004277 else if (name == "offset")
4278 {
4279 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4280 }
4281 else if (name == "altname")
4282 {
4283 alt_name.SetString(value);
4284 }
4285 else if (name == "encoding")
4286 {
4287 encoding_set = true;
4288 reg_info.encoding = Args::StringToEncoding (value.data(), eEncodingUint);
4289 }
4290 else if (name == "format")
4291 {
4292 format_set = true;
4293 Format format = eFormatInvalid;
4294 if (Args::StringToFormat (value.data(), format, NULL).Success())
4295 reg_info.format = format;
4296 else if (value == "vector-sint8")
4297 reg_info.format = eFormatVectorOfSInt8;
4298 else if (value == "vector-uint8")
4299 reg_info.format = eFormatVectorOfUInt8;
4300 else if (value == "vector-sint16")
4301 reg_info.format = eFormatVectorOfSInt16;
4302 else if (value == "vector-uint16")
4303 reg_info.format = eFormatVectorOfUInt16;
4304 else if (value == "vector-sint32")
4305 reg_info.format = eFormatVectorOfSInt32;
4306 else if (value == "vector-uint32")
4307 reg_info.format = eFormatVectorOfUInt32;
4308 else if (value == "vector-float32")
4309 reg_info.format = eFormatVectorOfFloat32;
4310 else if (value == "vector-uint128")
4311 reg_info.format = eFormatVectorOfUInt128;
4312 }
4313 else if (name == "group_id")
4314 {
4315 const uint32_t set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4316 RegisterSetMap::const_iterator pos = target_info.reg_set_map.find(set_id);
4317 if (pos != target_info.reg_set_map.end())
4318 set_name = pos->second.name;
4319 }
4320 else if (name == "gcc_regnum")
4321 {
4322 reg_info.kinds[eRegisterKindGCC] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4323 }
4324 else if (name == "dwarf_regnum")
4325 {
4326 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4327 }
4328 else if (name == "generic")
4329 {
4330 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister(value.data());
4331 }
4332 else if (name == "value_regnums")
4333 {
4334 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
4335 }
4336 else if (name == "invalidate_regnums")
4337 {
4338 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
4339 }
4340 else
4341 {
4342 printf("unhandled attribute %s = %s\n", name.data(), value.data());
4343 }
4344 return true; // Keep iterating through all attributes
4345 });
4346
4347 if (!gdb_type.empty() && !(encoding_set || format_set))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004348 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004349 if (gdb_type.find("int") == 0)
4350 {
4351 reg_info.format = eFormatHex;
4352 reg_info.encoding = eEncodingUint;
4353 }
4354 else if (gdb_type == "data_ptr" || gdb_type == "code_ptr")
4355 {
4356 reg_info.format = eFormatAddressInfo;
4357 reg_info.encoding = eEncodingUint;
4358 }
4359 else if (gdb_type == "i387_ext" || gdb_type == "float")
4360 {
4361 reg_info.format = eFormatFloat;
4362 reg_info.encoding = eEncodingIEEE754;
4363 }
Colin Rileyc3c95b22015-04-16 15:51:33 +00004364 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004365
4366 // Only update the register set name if we didn't get a "reg_set" attribute.
4367 // "set_name" will be empty if we didn't have a "reg_set" attribute.
4368 if (!set_name && !gdb_group.empty())
4369 set_name.SetCString(gdb_group.c_str());
4370
4371 reg_info.byte_offset = reg_offset;
4372 assert (reg_info.byte_size != 0);
4373 reg_offset += reg_info.byte_size;
4374 if (!value_regs.empty())
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004375 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004376 value_regs.push_back(LLDB_INVALID_REGNUM);
4377 reg_info.value_regs = value_regs.data();
Colin Rileyc3c95b22015-04-16 15:51:33 +00004378 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004379 if (!invalidate_regs.empty())
4380 {
4381 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
4382 reg_info.invalidate_regs = invalidate_regs.data();
4383 }
4384
Ewan Crawford682e8422015-06-26 09:38:27 +00004385 ++prev_reg_num;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004386 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
4387
4388 return true; // Keep iterating through all "reg" elements
4389 });
Colin Rileyc3c95b22015-04-16 15:51:33 +00004390 return true;
4391}
Greg Claytond04f0ed2015-05-26 18:00:51 +00004392
Colin Rileyc3c95b22015-04-16 15:51:33 +00004393} // namespace {}
4394
Colin Rileyc3c95b22015-04-16 15:51:33 +00004395
4396// query the target of gdb-remote for extended target information
4397// return: 'true' on success
4398// 'false' on failure
4399bool
Aidan Doddsc0c83852015-05-08 09:36:31 +00004400ProcessGDBRemote::GetGDBServerRegisterInfo ()
Colin Rileyc3c95b22015-04-16 15:51:33 +00004401{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004402 // Make sure LLDB has an XML parser it can use first
4403 if (!XMLDocument::XMLEnabled())
4404 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004405
4406 // redirect libxml2's error handler since the default prints to stdout
Colin Rileyc3c95b22015-04-16 15:51:33 +00004407
4408 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004409
4410 // check that we have extended feature read support
4411 if ( !comm.GetQXferFeaturesReadSupported( ) )
4412 return false;
4413
4414 // request the target xml file
4415 std::string raw;
4416 lldb_private::Error lldberr;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004417 if (!comm.ReadExtFeature(ConstString("features"),
4418 ConstString("target.xml"),
4419 raw,
4420 lldberr))
4421 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00004422 return false;
4423 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004424
Colin Rileyc3c95b22015-04-16 15:51:33 +00004425
Greg Claytond04f0ed2015-05-26 18:00:51 +00004426 XMLDocument xml_document;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004427
Greg Claytond04f0ed2015-05-26 18:00:51 +00004428 if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml"))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004429 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004430 GdbServerTargetInfo target_info;
4431
4432 XMLNode target_node = xml_document.GetRootElement("target");
4433 if (target_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004434 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004435 XMLNode feature_node;
4436 target_node.ForEachChildElement([&target_info, this, &feature_node](const XMLNode &node) -> bool
4437 {
4438 llvm::StringRef name = node.GetName();
4439 if (name == "architecture")
4440 {
4441 node.GetElementText(target_info.arch);
4442 }
4443 else if (name == "osabi")
4444 {
4445 node.GetElementText(target_info.osabi);
4446 }
Ewan Crawford682e8422015-06-26 09:38:27 +00004447 else if (name == "xi:include" || name == "include")
Greg Claytond04f0ed2015-05-26 18:00:51 +00004448 {
4449 llvm::StringRef href = node.GetAttributeValue("href");
4450 if (!href.empty())
4451 target_info.includes.push_back(href.str());
4452 }
4453 else if (name == "feature")
4454 {
4455 feature_node = node;
4456 }
4457 else if (name == "groups")
4458 {
4459 node.ForEachChildElementWithName("group", [&target_info](const XMLNode &node) -> bool {
4460 uint32_t set_id = UINT32_MAX;
4461 RegisterSetInfo set_info;
4462
4463 node.ForEachAttribute([&set_id, &set_info](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
4464 if (name == "id")
4465 set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4466 if (name == "name")
4467 set_info.name = ConstString(value);
4468 return true; // Keep iterating through all attributes
4469 });
4470
4471 if (set_id != UINT32_MAX)
4472 target_info.reg_set_map[set_id] = set_info;
4473 return true; // Keep iterating through all "group" elements
4474 });
4475 }
4476 return true; // Keep iterating through all children of the target_node
4477 });
4478
4479 if (feature_node)
4480 {
4481 ParseRegisters(feature_node, target_info, this->m_register_info);
4482 }
4483
4484 for (const auto &include : target_info.includes)
4485 {
4486 // request register file
4487 std::string xml_data;
4488 if (!comm.ReadExtFeature(ConstString("features"),
4489 ConstString(include),
4490 xml_data,
4491 lldberr))
4492 continue;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004493
Greg Claytond04f0ed2015-05-26 18:00:51 +00004494 XMLDocument include_xml_document;
4495 include_xml_document.ParseMemory(xml_data.data(), xml_data.size(), include.c_str());
4496 XMLNode include_feature_node = include_xml_document.GetRootElement("feature");
4497 if (include_feature_node)
4498 {
4499 ParseRegisters(include_feature_node, target_info, this->m_register_info);
4500 }
4501 }
4502 this->m_register_info.Finalize(GetTarget().GetArchitecture());
Colin Rileyc3c95b22015-04-16 15:51:33 +00004503 }
4504 }
4505
Greg Claytond04f0ed2015-05-26 18:00:51 +00004506 return m_register_info.GetNumRegisters() > 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004507}
4508
Aidan Doddsc0c83852015-05-08 09:36:31 +00004509Error
4510ProcessGDBRemote::GetLoadedModuleList (GDBLoadedModuleInfoList & list)
4511{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004512 // Make sure LLDB has an XML parser it can use first
4513 if (!XMLDocument::XMLEnabled())
4514 return Error (0, ErrorType::eErrorTypeGeneric);
4515
Aidan Doddsc0c83852015-05-08 09:36:31 +00004516 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS);
4517 if (log)
4518 log->Printf ("ProcessGDBRemote::%s", __FUNCTION__);
4519
Aidan Doddsc0c83852015-05-08 09:36:31 +00004520 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004521
4522 // check that we have extended feature read support
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004523 if (comm.GetQXferLibrariesSVR4ReadSupported ()) {
4524 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004525
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004526 // request the loaded library list
4527 std::string raw;
4528 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004529
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004530 if (!comm.ReadExtFeature (ConstString ("libraries-svr4"), ConstString (""), raw, lldberr))
4531 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004532
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004533 // parse the xml file in memory
4534 if (log)
4535 log->Printf ("parsing: %s", raw.c_str());
4536 XMLDocument doc;
4537
4538 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4539 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004540
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004541 XMLNode root_element = doc.GetRootElement("library-list-svr4");
4542 if (!root_element)
4543 return Error();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004544
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004545 // main link map structure
4546 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4547 if (!main_lm.empty())
4548 {
4549 list.m_link_map = StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
4550 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004551
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004552 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
Aidan Doddsc0c83852015-05-08 09:36:31 +00004553
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004554 GDBLoadedModuleInfoList::LoadedModuleInfo module;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004555
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004556 library.ForEachAttribute([log, &module](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004557
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004558 if (name == "name")
4559 module.set_name (value.str());
4560 else if (name == "lm")
4561 {
4562 // the address of the link_map struct.
4563 module.set_link_map(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4564 }
4565 else if (name == "l_addr")
4566 {
4567 // the displacement as read from the field 'l_addr' of the link_map struct.
4568 module.set_base(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4569
4570 }
4571 else if (name == "l_ld")
4572 {
4573 // the memory address of the libraries PT_DYAMIC section.
4574 module.set_dynamic(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4575 }
4576
4577 return true; // Keep iterating over all properties of "library"
4578 });
4579
4580 if (log)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004581 {
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004582 std::string name;
4583 lldb::addr_t lm=0, base=0, ld=0;
4584
4585 module.get_name (name);
4586 module.get_link_map (lm);
4587 module.get_base (base);
4588 module.get_dynamic (ld);
4589
4590 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 +00004591 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004592
4593 list.add (module);
4594 return true; // Keep iterating over all "library" elements in the root node
Greg Claytond04f0ed2015-05-26 18:00:51 +00004595 });
Aidan Doddsc0c83852015-05-08 09:36:31 +00004596
4597 if (log)
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004598 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4599 } else if (comm.GetQXferLibrariesReadSupported ()) {
4600 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004601
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004602 // request the loaded library list
4603 std::string raw;
4604 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004605
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004606 if (!comm.ReadExtFeature (ConstString ("libraries"), ConstString (""), raw, lldberr))
4607 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004608
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004609 if (log)
4610 log->Printf ("parsing: %s", raw.c_str());
4611 XMLDocument doc;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004612
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004613 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4614 return Error (0, ErrorType::eErrorTypeGeneric);
4615
4616 XMLNode root_element = doc.GetRootElement("library-list");
4617 if (!root_element)
4618 return Error();
4619
4620 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
4621 GDBLoadedModuleInfoList::LoadedModuleInfo module;
4622
4623 llvm::StringRef name = library.GetAttributeValue("name");
4624 module.set_name(name.str());
4625
4626 // The base address of a given library will be the address of its
4627 // first section. Most remotes send only one section for Windows
4628 // targets for example.
4629 const XMLNode &section = library.FindFirstChildElementWithName("section");
4630 llvm::StringRef address = section.GetAttributeValue("address");
4631 module.set_base(StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0));
4632
4633 if (log)
4634 {
4635 std::string name;
4636 lldb::addr_t base = 0;
4637 module.get_name (name);
4638 module.get_base (base);
4639
4640 log->Printf ("found (base:0x%" PRIx64 ", name:'%s')", base, name.c_str());
4641 }
4642
4643 list.add (module);
4644 return true; // Keep iterating over all "library" elements in the root node
4645 });
4646
4647 if (log)
4648 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4649 } else {
4650 return Error (0, ErrorType::eErrorTypeGeneric);
4651 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004652
4653 return Error();
4654}
4655
Aidan Doddsc0c83852015-05-08 09:36:31 +00004656lldb::ModuleSP
4657ProcessGDBRemote::LoadModuleAtAddress (const FileSpec &file, lldb::addr_t base_addr)
4658{
4659 Target &target = m_process->GetTarget();
4660 ModuleList &modules = target.GetImages();
4661 ModuleSP module_sp;
4662
4663 bool changed = false;
4664
4665 ModuleSpec module_spec (file, target.GetArchitecture());
4666 if ((module_sp = modules.FindFirstModule (module_spec)))
4667 {
4668 module_sp->SetLoadAddress (target, base_addr, true, changed);
4669 }
4670 else if ((module_sp = target.GetSharedModule (module_spec)))
4671 {
4672 module_sp->SetLoadAddress (target, base_addr, true, changed);
4673 }
4674
4675 return module_sp;
4676}
4677
4678size_t
4679ProcessGDBRemote::LoadModules ()
4680{
4681 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4682
4683 // request a list of loaded libraries from GDBServer
4684 GDBLoadedModuleInfoList module_list;
4685 if (GetLoadedModuleList (module_list).Fail())
4686 return 0;
4687
4688 // get a list of all the modules
4689 ModuleList new_modules;
4690
4691 for (GDBLoadedModuleInfoList::LoadedModuleInfo & modInfo : module_list.m_list)
4692 {
4693 std::string mod_name;
4694 lldb::addr_t mod_base;
4695
4696 bool valid = true;
4697 valid &= modInfo.get_name (mod_name);
4698 valid &= modInfo.get_base (mod_base);
4699 if (!valid)
4700 continue;
4701
4702 // hack (cleaner way to get file name only?) (win/unix compat?)
Vince Harron4cc8d202015-05-10 08:33:58 +00004703 size_t marker = mod_name.rfind ('/');
Aidan Doddsc0c83852015-05-08 09:36:31 +00004704 if (marker == std::string::npos)
4705 marker = 0;
4706 else
4707 marker += 1;
4708
4709 FileSpec file (mod_name.c_str()+marker, true);
4710 lldb::ModuleSP module_sp = LoadModuleAtAddress (file, mod_base);
4711
4712 if (module_sp.get())
4713 new_modules.Append (module_sp);
4714 }
4715
4716 if (new_modules.GetSize() > 0)
4717 {
4718 Target & target = m_target;
4719
4720 new_modules.ForEach ([&target](const lldb::ModuleSP module_sp) -> bool
4721 {
4722 lldb_private::ObjectFile * obj = module_sp->GetObjectFile ();
4723 if (!obj)
4724 return true;
4725
4726 if (obj->GetType () != ObjectFile::Type::eTypeExecutable)
4727 return true;
4728
4729 lldb::ModuleSP module_copy_sp = module_sp;
4730 target.SetExecutableModule (module_copy_sp, false);
4731 return false;
4732 });
4733
4734 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4735 loaded_modules.AppendIfNeeded (new_modules);
4736 m_process->GetTarget().ModulesDidLoad (new_modules);
4737 }
4738
4739 return new_modules.GetSize();
4740}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004741
Tamas Berghammer783bfc82015-06-18 20:43:56 +00004742Error
4743ProcessGDBRemote::GetFileLoadAddress(const FileSpec& file, bool& is_loaded, lldb::addr_t& load_addr)
4744{
4745 is_loaded = false;
4746 load_addr = LLDB_INVALID_ADDRESS;
4747
4748 std::string file_path = file.GetPath(false);
4749 if (file_path.empty ())
4750 return Error("Empty file name specified");
4751
4752 StreamString packet;
4753 packet.PutCString("qFileLoadAddress:");
4754 packet.PutCStringAsRawHex8(file_path.c_str());
4755
4756 StringExtractorGDBRemote response;
4757 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString().c_str(), response, false) != GDBRemoteCommunication::PacketResult::Success)
4758 return Error("Sending qFileLoadAddress packet failed");
4759
4760 if (response.IsErrorResponse())
4761 {
4762 if (response.GetError() == 1)
4763 {
4764 // The file is not loaded into the inferior
4765 is_loaded = false;
4766 load_addr = LLDB_INVALID_ADDRESS;
4767 return Error();
4768 }
4769
4770 return Error("Fetching file load address from remote server returned an error");
4771 }
4772
4773 if (response.IsNormalResponse())
4774 {
4775 is_loaded = true;
4776 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
4777 return Error();
4778 }
4779
4780 return Error("Unknown error happened during sending the load address packet");
4781}
4782
Greg Clayton0b90be12015-06-23 21:27:50 +00004783
4784void
4785ProcessGDBRemote::ModulesDidLoad (ModuleList &module_list)
4786{
4787 // We must call the lldb_private::Process::ModulesDidLoad () first before we do anything
4788 Process::ModulesDidLoad (module_list);
4789
4790 // After loading shared libraries, we can ask our remote GDB server if
4791 // it needs any symbols.
4792 m_gdb_comm.ServeSymbolLookups(this);
4793}
4794
4795
Greg Claytone034a042015-05-21 20:52:06 +00004796class CommandObjectProcessGDBRemoteSpeedTest: public CommandObjectParsed
4797{
4798public:
4799 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter) :
4800 CommandObjectParsed (interpreter,
4801 "process plugin packet speed-test",
4802 "Tests packet speeds of various sizes to determine the performance characteristics of the GDB remote connection. ",
4803 NULL),
4804 m_option_group (interpreter),
4805 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),
4806 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),
4807 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),
4808 m_json (LLDB_OPT_SET_1, false, "json", 'j', "Print the output as JSON data for easy parsing.", false, true)
4809 {
4810 m_option_group.Append (&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4811 m_option_group.Append (&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4812 m_option_group.Append (&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4813 m_option_group.Append (&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4814 m_option_group.Finalize();
4815 }
4816
4817 ~CommandObjectProcessGDBRemoteSpeedTest ()
4818 {
4819 }
4820
4821
4822 Options *
4823 GetOptions () override
4824 {
4825 return &m_option_group;
4826 }
4827
4828 bool
4829 DoExecute (Args& command, CommandReturnObject &result) override
4830 {
4831 const size_t argc = command.GetArgumentCount();
4832 if (argc == 0)
4833 {
4834 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4835 if (process)
4836 {
4837 StreamSP output_stream_sp (m_interpreter.GetDebugger().GetAsyncOutputStream());
4838 result.SetImmediateOutputStream (output_stream_sp);
4839
4840 const uint32_t num_packets = (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
4841 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
4842 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
4843 const bool json = m_json.GetOptionValue().GetCurrentValue();
4844 if (output_stream_sp)
4845 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, *output_stream_sp);
4846 else
4847 {
4848 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, result.GetOutputStream());
4849 }
4850 result.SetStatus (eReturnStatusSuccessFinishResult);
4851 return true;
4852 }
4853 }
4854 else
4855 {
4856 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
4857 }
4858 result.SetStatus (eReturnStatusFailed);
4859 return false;
4860 }
4861protected:
4862 OptionGroupOptions m_option_group;
4863 OptionGroupUInt64 m_num_packets;
4864 OptionGroupUInt64 m_max_send;
4865 OptionGroupUInt64 m_max_recv;
4866 OptionGroupBoolean m_json;
4867
4868};
4869
Greg Clayton02686b82012-10-15 22:42:16 +00004870class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00004871{
4872private:
4873
4874public:
Greg Clayton02686b82012-10-15 22:42:16 +00004875 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00004876 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00004877 "process plugin packet history",
4878 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00004879 NULL)
4880 {
4881 }
4882
Greg Clayton02686b82012-10-15 22:42:16 +00004883 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton998255b2012-10-13 02:07:45 +00004884 {
4885 }
4886
4887 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004888 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton998255b2012-10-13 02:07:45 +00004889 {
Greg Clayton02686b82012-10-15 22:42:16 +00004890 const size_t argc = command.GetArgumentCount();
4891 if (argc == 0)
4892 {
4893 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4894 if (process)
4895 {
4896 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
4897 result.SetStatus (eReturnStatusSuccessFinishResult);
4898 return true;
4899 }
4900 }
4901 else
4902 {
4903 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
4904 }
4905 result.SetStatus (eReturnStatusFailed);
4906 return false;
4907 }
4908};
4909
Jason Molenda6076bf42014-05-06 04:34:52 +00004910class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed
4911{
4912private:
4913
4914public:
4915 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) :
4916 CommandObjectParsed (interpreter,
4917 "process plugin packet xfer-size",
4918 "Maximum size that lldb will try to read/write one one chunk.",
4919 NULL)
4920 {
4921 }
4922
4923 ~CommandObjectProcessGDBRemotePacketXferSize ()
4924 {
4925 }
4926
4927 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004928 DoExecute (Args& command, CommandReturnObject &result) override
Jason Molenda6076bf42014-05-06 04:34:52 +00004929 {
4930 const size_t argc = command.GetArgumentCount();
4931 if (argc == 0)
4932 {
4933 result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str());
4934 result.SetStatus (eReturnStatusFailed);
4935 return false;
4936 }
4937
4938 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4939 if (process)
4940 {
4941 const char *packet_size = command.GetArgumentAtIndex(0);
4942 errno = 0;
4943 uint64_t user_specified_max = strtoul (packet_size, NULL, 10);
4944 if (errno == 0 && user_specified_max != 0)
4945 {
4946 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max);
4947 result.SetStatus (eReturnStatusSuccessFinishResult);
4948 return true;
4949 }
4950 }
4951 result.SetStatus (eReturnStatusFailed);
4952 return false;
4953 }
4954};
4955
4956
Greg Clayton02686b82012-10-15 22:42:16 +00004957class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
4958{
4959private:
4960
4961public:
4962 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
4963 CommandObjectParsed (interpreter,
4964 "process plugin packet send",
4965 "Send a custom packet through the GDB remote protocol and print the answer. "
4966 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
4967 NULL)
4968 {
4969 }
4970
4971 ~CommandObjectProcessGDBRemotePacketSend ()
4972 {
4973 }
4974
4975 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004976 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton02686b82012-10-15 22:42:16 +00004977 {
4978 const size_t argc = command.GetArgumentCount();
4979 if (argc == 0)
4980 {
4981 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
4982 result.SetStatus (eReturnStatusFailed);
4983 return false;
4984 }
4985
4986 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4987 if (process)
4988 {
Han Ming Ong84145852012-11-26 20:42:03 +00004989 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00004990 {
Han Ming Ong84145852012-11-26 20:42:03 +00004991 const char *packet_cstr = command.GetArgumentAtIndex(0);
4992 bool send_async = true;
4993 StringExtractorGDBRemote response;
4994 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
4995 result.SetStatus (eReturnStatusSuccessFinishResult);
4996 Stream &output_strm = result.GetOutputStream();
4997 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00004998 std::string &response_str = response.GetStringRef();
4999
Han Ming Ong399289e2013-06-21 19:56:59 +00005000 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00005001 {
5002 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
5003 }
5004
Han Ming Ong84145852012-11-26 20:42:03 +00005005 if (response_str.empty())
5006 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
5007 else
5008 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00005009 }
Greg Clayton02686b82012-10-15 22:42:16 +00005010 }
Greg Clayton998255b2012-10-13 02:07:45 +00005011 return true;
5012 }
5013};
5014
Greg Claytonba4a0a52013-02-01 23:03:47 +00005015class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
5016{
5017private:
5018
5019public:
5020 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
5021 CommandObjectRaw (interpreter,
5022 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00005023 "Send a qRcmd packet through the GDB remote protocol and print the response."
5024 "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 +00005025 NULL)
5026 {
5027 }
5028
5029 ~CommandObjectProcessGDBRemotePacketMonitor ()
5030 {
5031 }
5032
5033 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005034 DoExecute (const char *command, CommandReturnObject &result) override
Greg Claytonba4a0a52013-02-01 23:03:47 +00005035 {
5036 if (command == NULL || command[0] == '\0')
5037 {
5038 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
5039 result.SetStatus (eReturnStatusFailed);
5040 return false;
5041 }
5042
5043 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5044 if (process)
5045 {
5046 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00005047 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00005048 packet.PutBytesAsRawHex8(command, strlen(command));
5049 const char *packet_cstr = packet.GetString().c_str();
5050
5051 bool send_async = true;
5052 StringExtractorGDBRemote response;
5053 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
5054 result.SetStatus (eReturnStatusSuccessFinishResult);
5055 Stream &output_strm = result.GetOutputStream();
5056 output_strm.Printf (" packet: %s\n", packet_cstr);
5057 const std::string &response_str = response.GetStringRef();
5058
5059 if (response_str.empty())
5060 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
5061 else
5062 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
5063 }
5064 return true;
5065 }
5066};
5067
Greg Clayton02686b82012-10-15 22:42:16 +00005068class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
5069{
5070private:
5071
5072public:
5073 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
5074 CommandObjectMultiword (interpreter,
5075 "process plugin packet",
5076 "Commands that deal with GDB remote packets.",
5077 NULL)
5078 {
5079 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
5080 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00005081 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Jason Molenda6076bf42014-05-06 04:34:52 +00005082 LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter)));
Greg Claytone034a042015-05-21 20:52:06 +00005083 LoadSubCommand ("speed-test", CommandObjectSP (new CommandObjectProcessGDBRemoteSpeedTest (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00005084 }
5085
5086 ~CommandObjectProcessGDBRemotePacket ()
5087 {
5088 }
5089};
Greg Clayton998255b2012-10-13 02:07:45 +00005090
5091class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
5092{
5093public:
5094 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
5095 CommandObjectMultiword (interpreter,
5096 "process plugin",
5097 "A set of commands for operating on a ProcessGDBRemote process.",
5098 "process plugin <subcommand> [<subcommand-options>]")
5099 {
5100 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
5101 }
5102
5103 ~CommandObjectMultiwordProcessGDBRemote ()
5104 {
5105 }
5106};
5107
Greg Clayton998255b2012-10-13 02:07:45 +00005108CommandObject *
5109ProcessGDBRemote::GetPluginCommandObject()
5110{
5111 if (!m_command_sp)
5112 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
5113 return m_command_sp.get();
5114}