blob: a2e903f47c4029cdb3ffccc4c5e86c032ec642e5 [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())
826 SetUnixSignals(std::make_shared<GDBRemoteSignals>(GetTarget().GetPlatform()->GetUnixSignals()));
Todd Fialaaf245d12014-06-30 21:05:18 +0000827
Greg Claytonb766a732011-02-04 01:58:07 +0000828 return error;
829}
830
831Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000832ProcessGDBRemote::WillLaunchOrAttach ()
833{
834 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000835 m_stdio_communication.Clear ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000836 return error;
837}
838
839//----------------------------------------------------------------------
840// Process Control
841//----------------------------------------------------------------------
842Error
Jean-Daniel Dupas7782de92013-12-09 22:52:50 +0000843ProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000844{
Todd Fiala75f47c32014-10-11 21:42:09 +0000845 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton4957bf62010-09-30 21:49:03 +0000846 Error error;
Greg Clayton982c9762011-11-03 21:22:33 +0000847
Todd Fiala75f47c32014-10-11 21:42:09 +0000848 if (log)
849 log->Printf ("ProcessGDBRemote::%s() entered", __FUNCTION__);
850
Greg Clayton982c9762011-11-03 21:22:33 +0000851 uint32_t launch_flags = launch_info.GetFlags().Get();
Chaoren Lind3173f32015-05-29 19:52:29 +0000852 FileSpec stdin_file_spec{};
853 FileSpec stdout_file_spec{};
854 FileSpec stderr_file_spec{};
855 FileSpec working_dir = launch_info.GetWorkingDirectory();
Greg Clayton982c9762011-11-03 21:22:33 +0000856
Zachary Turner696b5282014-08-14 16:01:25 +0000857 const FileAction *file_action;
Greg Clayton982c9762011-11-03 21:22:33 +0000858 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
859 if (file_action)
860 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000861 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000862 stdin_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000863 }
864 file_action = launch_info.GetFileActionForFD (STDOUT_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 stdout_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000869 }
870 file_action = launch_info.GetFileActionForFD (STDERR_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 stderr_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000875 }
876
Todd Fiala75f47c32014-10-11 21:42:09 +0000877 if (log)
878 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000879 if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
Vince Harron4a8abd32015-02-13 19:15:24 +0000880 log->Printf ("ProcessGDBRemote::%s provided with STDIO paths via launch_info: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000881 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000882 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
883 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
884 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Todd Fiala75f47c32014-10-11 21:42:09 +0000885 else
886 log->Printf ("ProcessGDBRemote::%s no STDIO paths given via launch_info", __FUNCTION__);
887 }
888
Vince Harrondf3f00f2015-02-10 21:09:04 +0000889 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Chaoren Lind3173f32015-05-29 19:52:29 +0000890 if (stdin_file_spec || disable_stdio)
Vince Harrondf3f00f2015-02-10 21:09:04 +0000891 {
892 // the inferior will be reading stdin from the specified file
893 // or stdio is completely disabled
894 m_stdin_forward = false;
895 }
896 else
897 {
898 m_stdin_forward = true;
899 }
900
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000901 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
902 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
903 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000904
Greg Clayton982c9762011-11-03 21:22:33 +0000905 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000906 if (object_file)
907 {
Greg Clayton71337622011-02-24 22:24:29 +0000908 // Make sure we aren't already connected?
909 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000910 {
Greg Clayton91a9b2472013-12-04 19:19:12 +0000911 error = LaunchAndConnectToDebugserver (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000912 }
913
914 if (error.Success())
915 {
916 lldb_utility::PseudoTerminal pty;
917 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000918
Greg Claytonf58c2692011-06-24 22:32:10 +0000919 PlatformSP platform_sp (m_target.GetPlatform());
Vince Harrondf3f00f2015-02-10 21:09:04 +0000920 if (disable_stdio)
Greg Clayton71337622011-02-24 22:24:29 +0000921 {
Vince Harrondf3f00f2015-02-10 21:09:04 +0000922 // set to /dev/null unless redirected to a file above
Chaoren Lind3173f32015-05-29 19:52:29 +0000923 if (!stdin_file_spec)
924 stdin_file_spec.SetFile("/dev/null", false);
925 if (!stdout_file_spec)
926 stdout_file_spec.SetFile("/dev/null", false);
927 if (!stderr_file_spec)
928 stderr_file_spec.SetFile("/dev/null", false);
Vince Harrondf3f00f2015-02-10 21:09:04 +0000929 }
930 else if (platform_sp && platform_sp->IsHost())
931 {
932 // If the debugserver is local and we aren't disabling STDIO, lets use
933 // a pseudo terminal to instead of relying on the 'O' packets for stdio
934 // since 'O' packets can really slow down debugging if the inferior
935 // does a lot of output.
Chaoren Lind3173f32015-05-29 19:52:29 +0000936 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
937 pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000938 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000939 FileSpec slave_name{pty.GetSlaveName(NULL, 0), false};
940
941 if (!stdin_file_spec)
942 stdin_file_spec = slave_name;
943
944 if (!stdout_file_spec)
945 stdout_file_spec = slave_name;
946
947 if (!stderr_file_spec)
948 stderr_file_spec = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000949 }
Todd Fiala75f47c32014-10-11 21:42:09 +0000950 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +0000951 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 +0000952 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000953 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
954 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
955 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Greg Clayton71337622011-02-24 22:24:29 +0000956 }
957
Todd Fiala75f47c32014-10-11 21:42:09 +0000958 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +0000959 log->Printf ("ProcessGDBRemote::%s final STDIO paths after all adjustments: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000960 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000961 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
962 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
963 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Todd Fiala75f47c32014-10-11 21:42:09 +0000964
Chaoren Lind3173f32015-05-29 19:52:29 +0000965 if (stdin_file_spec)
966 m_gdb_comm.SetSTDIN(stdin_file_spec);
967 if (stdout_file_spec)
968 m_gdb_comm.SetSTDOUT(stdout_file_spec);
969 if (stderr_file_spec)
970 m_gdb_comm.SetSTDERR(stderr_file_spec);
Greg Clayton71337622011-02-24 22:24:29 +0000971
972 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
Jim Ingham106d0282014-06-25 02:32:56 +0000973 m_gdb_comm.SetDetachOnError (launch_flags & eLaunchFlagDetachOnError);
Greg Clayton71337622011-02-24 22:24:29 +0000974
Greg Claytonc4103b32011-05-08 04:53:50 +0000975 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Clayton71337622011-02-24 22:24:29 +0000976
Jason Molendaa3329782014-03-29 18:54:20 +0000977 const char * launch_event_data = launch_info.GetLaunchEventData();
978 if (launch_event_data != NULL && *launch_event_data != '\0')
979 m_gdb_comm.SendLaunchEventDataPacket (launch_event_data);
980
Chaoren Lind3173f32015-05-29 19:52:29 +0000981 if (working_dir)
Greg Clayton71337622011-02-24 22:24:29 +0000982 {
983 m_gdb_comm.SetWorkingDir (working_dir);
984 }
985
986 // Send the environment and the program + arguments after we connect
Greg Clayton982c9762011-11-03 21:22:33 +0000987 const Args &environment = launch_info.GetEnvironmentEntries();
988 if (environment.GetArgumentCount())
Greg Clayton71337622011-02-24 22:24:29 +0000989 {
Greg Clayton982c9762011-11-03 21:22:33 +0000990 size_t num_environment_entries = environment.GetArgumentCount();
991 for (size_t i=0; i<num_environment_entries; ++i)
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000992 {
Greg Clayton982c9762011-11-03 21:22:33 +0000993 const char *env_entry = environment.GetArgumentAtIndex(i);
994 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Clayton71337622011-02-24 22:24:29 +0000995 break;
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000996 }
Greg Clayton71337622011-02-24 22:24:29 +0000997 }
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000998
Greg Clayton71337622011-02-24 22:24:29 +0000999 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001000 // Scope for the scoped timeout object
1001 GDBRemoteCommunication::ScopedTimeout timeout (m_gdb_comm, 10);
1002
1003 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
1004 if (arg_packet_err == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001005 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001006 std::string error_str;
1007 if (m_gdb_comm.GetLaunchSuccess (error_str))
1008 {
1009 SetID (m_gdb_comm.GetCurrentProcessID ());
1010 }
1011 else
1012 {
1013 error.SetErrorString (error_str.c_str());
1014 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001015 }
1016 else
1017 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001018 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001019 }
Greg Clayton71337622011-02-24 22:24:29 +00001020 }
Tamas Berghammer912800c2015-02-24 10:23:39 +00001021
Greg Clayton71337622011-02-24 22:24:29 +00001022 if (GetID() == LLDB_INVALID_PROCESS_ID)
1023 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001024 if (log)
1025 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton71337622011-02-24 22:24:29 +00001026 KillDebugserverProcess ();
1027 return error;
1028 }
1029
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001030 StringExtractorGDBRemote response;
1031 if (m_gdb_comm.GetStopReply(response))
Greg Clayton71337622011-02-24 22:24:29 +00001032 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001033 SetLastStopPacket(response);
Ewan Crawford78baa192015-05-13 09:18:18 +00001034 // '?' Packets must be handled differently in non-stop mode
1035 if (GetTarget().GetNonStopModeEnabled())
1036 HandleStopReplySequence();
1037
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001038 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
1039
1040 if (process_arch.IsValid())
Jason Molendac62bd7b2013-12-21 05:20:36 +00001041 {
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001042 m_target.MergeArchitecture(process_arch);
1043 }
1044 else
1045 {
1046 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
1047 if (host_arch.IsValid())
1048 m_target.MergeArchitecture(host_arch);
Carlo Kok74389122013-10-14 07:09:13 +00001049 }
1050
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001051 SetPrivateState (SetThreadStopInfo (response));
Greg Clayton71337622011-02-24 22:24:29 +00001052
1053 if (!disable_stdio)
1054 {
1055 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Claytonee95ed52011-11-17 22:14:31 +00001056 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Clayton71337622011-02-24 22:24:29 +00001057 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001058 }
1059 }
Greg Claytonc235ac72011-08-09 05:20:29 +00001060 else
1061 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001062 if (log)
1063 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytonc235ac72011-08-09 05:20:29 +00001064 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001065 }
1066 else
1067 {
1068 // Set our user ID to an invalid process ID.
1069 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton982c9762011-11-03 21:22:33 +00001070 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
1071 exe_module->GetFileSpec().GetFilename().AsCString(),
1072 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001073 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001074 return error;
Greg Clayton4957bf62010-09-30 21:49:03 +00001075
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001076}
1077
1078
1079Error
Greg Claytonb766a732011-02-04 01:58:07 +00001080ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001081{
1082 Error error;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001083 // Only connect if we have a valid connect URL
Vince Harron1b5a74e2015-01-21 22:42:49 +00001084 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton00fe87b2013-12-05 22:58:22 +00001085
1086 if (connect_url && connect_url[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001087 {
Vince Harron1b5a74e2015-01-21 22:42:49 +00001088 if (log)
1089 log->Printf("ProcessGDBRemote::%s Connecting to %s", __FUNCTION__, connect_url);
Greg Clayton00fe87b2013-12-05 22:58:22 +00001090 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
1091 if (conn_ap.get())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001092 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001093 const uint32_t max_retry_count = 50;
1094 uint32_t retry_count = 0;
1095 while (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001096 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001097 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
1098 {
1099 m_gdb_comm.SetConnection (conn_ap.release());
1100 break;
1101 }
1102 else if (error.WasInterrupted())
1103 {
1104 // If we were interrupted, don't keep retrying.
1105 break;
1106 }
1107
1108 retry_count++;
1109
1110 if (retry_count >= max_retry_count)
1111 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001112
Greg Clayton00fe87b2013-12-05 22:58:22 +00001113 usleep (100000);
1114 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001115 }
1116 }
1117
1118 if (!m_gdb_comm.IsConnected())
1119 {
1120 if (error.Success())
1121 error.SetErrorString("not connected to remote gdb server");
1122 return error;
1123 }
1124
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001125
1126 // Start the communications read thread so all incoming data can be
1127 // parsed into packets and queued as they arrive.
1128 if (GetTarget().GetNonStopModeEnabled())
1129 m_gdb_comm.StartReadThread();
1130
Greg Clayton32e0a752011-03-30 18:16:51 +00001131 // We always seem to be able to open a connection to a local port
1132 // so we need to make sure we can then send data to it. If we can't
1133 // then we aren't actually connected to anything, so try and do the
1134 // handshake with the remote GDB server and make sure that goes
1135 // alright.
Greg Claytonfb909312013-11-23 01:58:15 +00001136 if (!m_gdb_comm.HandshakeWithServer (&error))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001137 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001138 m_gdb_comm.Disconnect();
1139 if (error.Success())
1140 error.SetErrorString("not connected to remote gdb server");
1141 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001142 }
Ewan Crawford78baa192015-05-13 09:18:18 +00001143
1144 // Send $QNonStop:1 packet on startup if required
1145 if (GetTarget().GetNonStopModeEnabled())
Ewan Crawfordaa7eda72015-06-24 15:14:26 +00001146 GetTarget().SetNonStopModeEnabled (m_gdb_comm.SetNonStopMode(true));
Ewan Crawford78baa192015-05-13 09:18:18 +00001147
Greg Claytonb30c50c2015-05-29 00:01:55 +00001148 m_gdb_comm.GetEchoSupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001149 m_gdb_comm.GetThreadSuffixSupported ();
Greg Clayton44633992012-04-10 03:22:03 +00001150 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001151 m_gdb_comm.GetHostInfo ();
1152 m_gdb_comm.GetVContSupported ('c');
Jim Inghamcd16df92012-07-20 21:37:13 +00001153 m_gdb_comm.GetVAttachOrWaitSupported();
Ewan Crawford78baa192015-05-13 09:18:18 +00001154
1155 // Ask the remote server for the default thread id
1156 if (GetTarget().GetNonStopModeEnabled())
1157 m_gdb_comm.GetDefaultThreadId(m_initial_tid);
1158
1159
Jim Ingham03afad82012-07-02 05:40:07 +00001160 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1161 for (size_t idx = 0; idx < num_cmds; idx++)
1162 {
1163 StringExtractorGDBRemote response;
Jim Ingham03afad82012-07-02 05:40:07 +00001164 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1165 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001166 return error;
1167}
1168
1169void
Jim Inghambb006ce2014-08-02 00:33:35 +00001170ProcessGDBRemote::DidLaunchOrAttach (ArchSpec& process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001171{
Greg Clayton5160ce52013-03-27 23:08:40 +00001172 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001173 if (log)
1174 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton93d3c8332011-02-16 04:46:07 +00001175 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001176 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001177 BuildDynamicRegisterInfo (false);
Greg Clayton3af9ea52010-11-18 05:57:03 +00001178
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001179 // See if the GDB server supports the qHostInfo information
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001180
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001181
1182 // See if the GDB server supports the qProcessInfo packet, if so
1183 // prefer that over the Host information as it will be more specific
1184 // to our process.
1185
Todd Fiala75f47c32014-10-11 21:42:09 +00001186 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1187 if (remote_process_arch.IsValid())
1188 {
1189 process_arch = remote_process_arch;
1190 if (log)
1191 log->Printf ("ProcessGDBRemote::%s gdb-remote had process architecture, using %s %s",
1192 __FUNCTION__,
1193 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1194 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1195 }
Jim Inghambb006ce2014-08-02 00:33:35 +00001196 else
Todd Fiala75f47c32014-10-11 21:42:09 +00001197 {
Jim Inghambb006ce2014-08-02 00:33:35 +00001198 process_arch = m_gdb_comm.GetHostArchitecture();
Todd Fiala75f47c32014-10-11 21:42:09 +00001199 if (log)
1200 log->Printf ("ProcessGDBRemote::%s gdb-remote did not have process architecture, using gdb-remote host architecture %s %s",
1201 __FUNCTION__,
1202 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1203 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1204 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001205
Jim Inghambb006ce2014-08-02 00:33:35 +00001206 if (process_arch.IsValid())
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001207 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001208 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Greg Claytond314e812011-03-23 00:09:55 +00001209 if (target_arch.IsValid())
1210 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001211 if (log)
1212 log->Printf ("ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1213 __FUNCTION__,
1214 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1215 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
1216
1217 // If the remote host is ARM and we have apple as the vendor, then
Greg Claytond314e812011-03-23 00:09:55 +00001218 // ARM executables and shared libraries can have mixed ARM architectures.
1219 // You can have an armv6 executable, and if the host is armv7, then the
1220 // system will load the best possible architecture for all shared libraries
1221 // it has, so we really need to take the remote host architecture as our
1222 // defacto architecture in this case.
1223
Jim Inghambb006ce2014-08-02 00:33:35 +00001224 if (process_arch.GetMachine() == llvm::Triple::arm &&
1225 process_arch.GetTriple().getVendor() == llvm::Triple::Apple)
Greg Claytond314e812011-03-23 00:09:55 +00001226 {
Jason Molenda921c01b2014-08-03 21:42:52 +00001227 GetTarget().SetArchitecture (process_arch);
Todd Fiala75f47c32014-10-11 21:42:09 +00001228 if (log)
1229 log->Printf ("ProcessGDBRemote::%s remote process is ARM/Apple, setting target arch to %s %s",
1230 __FUNCTION__,
1231 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1232 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001233 }
1234 else
1235 {
1236 // Fill in what is missing in the triple
Jim Inghambb006ce2014-08-02 00:33:35 +00001237 const llvm::Triple &remote_triple = process_arch.GetTriple();
Tamas Berghammere724af12015-03-13 10:32:37 +00001238 llvm::Triple new_target_triple = target_arch.GetTriple();
1239 if (new_target_triple.getVendorName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001240 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001241 new_target_triple.setVendor (remote_triple.getVendor());
Greg Claytond314e812011-03-23 00:09:55 +00001242
Tamas Berghammere724af12015-03-13 10:32:37 +00001243 if (new_target_triple.getOSName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001244 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001245 new_target_triple.setOS (remote_triple.getOS());
Greg Claytond314e812011-03-23 00:09:55 +00001246
Tamas Berghammere724af12015-03-13 10:32:37 +00001247 if (new_target_triple.getEnvironmentName().size() == 0)
1248 new_target_triple.setEnvironment (remote_triple.getEnvironment());
Greg Clayton70b57652011-05-15 01:25:55 +00001249 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001250
Tamas Berghammere724af12015-03-13 10:32:37 +00001251 ArchSpec new_target_arch = target_arch;
1252 new_target_arch.SetTriple(new_target_triple);
1253 GetTarget().SetArchitecture(new_target_arch);
1254 }
Greg Claytond314e812011-03-23 00:09:55 +00001255 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001256
1257 if (log)
1258 log->Printf ("ProcessGDBRemote::%s final target arch after adjustments for remote architecture: %s %s",
1259 __FUNCTION__,
1260 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1261 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001262 }
1263 else
1264 {
1265 // The target doesn't have a valid architecture yet, set it from
1266 // the architecture we got from the remote GDB server
Jason Molenda921c01b2014-08-03 21:42:52 +00001267 GetTarget().SetArchitecture (process_arch);
Greg Claytond314e812011-03-23 00:09:55 +00001268 }
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001269 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001270 }
1271}
1272
1273void
1274ProcessGDBRemote::DidLaunch ()
1275{
Jim Inghambb006ce2014-08-02 00:33:35 +00001276 ArchSpec process_arch;
1277 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001278}
1279
1280Error
Han Ming Ong84647042012-02-25 01:07:38 +00001281ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1282{
Todd Fiala75f47c32014-10-11 21:42:09 +00001283 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001284 Error error;
Todd Fiala75f47c32014-10-11 21:42:09 +00001285
1286 if (log)
1287 log->Printf ("ProcessGDBRemote::%s()", __FUNCTION__);
1288
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001289 // Clear out and clean up from any current state
1290 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001291 if (attach_pid != LLDB_INVALID_PROCESS_ID)
1292 {
Greg Clayton71337622011-02-24 22:24:29 +00001293 // Make sure we aren't already connected?
1294 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001295 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001296 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001297
1298 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001299 {
Greg Clayton71337622011-02-24 22:24:29 +00001300 const char *error_string = error.AsCString();
1301 if (error_string == NULL)
1302 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1303
1304 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001305 }
Greg Clayton71337622011-02-24 22:24:29 +00001306 }
1307
1308 if (error.Success())
1309 {
Jim Ingham106d0282014-06-25 02:32:56 +00001310 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
Todd Fiala75f47c32014-10-11 21:42:09 +00001311
Greg Clayton71337622011-02-24 22:24:29 +00001312 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001313 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Greg Clayton3b608422011-11-19 02:11:30 +00001314 SetID (attach_pid);
Greg Clayton71337622011-02-24 22:24:29 +00001315 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001316 }
1317 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001318
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001319 return error;
1320}
1321
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001322Error
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001323ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001324{
1325 Error error;
1326 // Clear out and clean up from any current state
1327 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001328
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001329 if (process_name && process_name[0])
1330 {
Greg Clayton71337622011-02-24 22:24:29 +00001331 // Make sure we aren't already connected?
1332 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001333 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001334 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001335
Greg Clayton71337622011-02-24 22:24:29 +00001336 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001337 {
Greg Clayton71337622011-02-24 22:24:29 +00001338 const char *error_string = error.AsCString();
1339 if (error_string == NULL)
1340 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001341
Greg Clayton71337622011-02-24 22:24:29 +00001342 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001343 }
Greg Clayton71337622011-02-24 22:24:29 +00001344 }
1345
1346 if (error.Success())
1347 {
1348 StreamString packet;
1349
Jim Ingham106d0282014-06-25 02:32:56 +00001350 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1351
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001352 if (attach_info.GetWaitForLaunch())
Jim Inghamcd16df92012-07-20 21:37:13 +00001353 {
1354 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1355 {
1356 packet.PutCString ("vAttachWait");
1357 }
1358 else
1359 {
1360 if (attach_info.GetIgnoreExisting())
1361 packet.PutCString("vAttachWait");
1362 else
1363 packet.PutCString ("vAttachOrWait");
1364 }
1365 }
Greg Clayton71337622011-02-24 22:24:29 +00001366 else
1367 packet.PutCString("vAttachName");
1368 packet.PutChar(';');
1369 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1370
1371 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1372
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001373 }
1374 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001375 return error;
1376}
1377
Greg Clayton5df78fa2015-05-23 03:54:53 +00001378void
1379ProcessGDBRemote::DidExit ()
Greg Claytonfbb76342013-11-20 21:07:01 +00001380{
Greg Clayton5df78fa2015-05-23 03:54:53 +00001381 // When we exit, disconnect from the GDB server communications
Greg Claytonfbb76342013-11-20 21:07:01 +00001382 m_gdb_comm.Disconnect();
Greg Claytonfbb76342013-11-20 21:07:01 +00001383}
1384
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001385void
Jim Inghambb006ce2014-08-02 00:33:35 +00001386ProcessGDBRemote::DidAttach (ArchSpec &process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001387{
Jim Inghambb006ce2014-08-02 00:33:35 +00001388 // If you can figure out what the architecture is, fill it in here.
1389 process_arch.Clear();
1390 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001391}
1392
Greg Clayton90ba8112012-12-05 00:16:59 +00001393
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001394Error
1395ProcessGDBRemote::WillResume ()
1396{
Greg Clayton71fc2a32011-02-12 06:28:37 +00001397 m_continue_c_tids.clear();
1398 m_continue_C_tids.clear();
1399 m_continue_s_tids.clear();
1400 m_continue_S_tids.clear();
Greg Clayton2e309072015-07-17 23:42:28 +00001401 m_jstopinfo_sp.reset();
1402 m_jthreadsinfo_sp.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001403 return Error();
1404}
1405
1406Error
1407ProcessGDBRemote::DoResume ()
1408{
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001409 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001410 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001411 if (log)
1412 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytone5219662010-12-03 06:02:24 +00001413
1414 Listener listener ("gdb-remote.resume-packet-sent");
1415 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1416 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00001417 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1418
Greg Claytond1d06e42013-04-20 00:27:58 +00001419 const size_t num_threads = GetThreadList().GetSize();
1420
Greg Clayton71fc2a32011-02-12 06:28:37 +00001421 StreamString continue_packet;
1422 bool continue_packet_error = false;
1423 if (m_gdb_comm.HasAnyVContSupport ())
1424 {
Ewan Crawford78baa192015-05-13 09:18:18 +00001425 if (!GetTarget().GetNonStopModeEnabled() &&
1426 (m_continue_c_tids.size() == num_threads ||
Greg Claytone98008c2014-02-13 23:34:38 +00001427 (m_continue_c_tids.empty() &&
1428 m_continue_C_tids.empty() &&
1429 m_continue_s_tids.empty() &&
Ewan Crawford78baa192015-05-13 09:18:18 +00001430 m_continue_S_tids.empty())))
Greg Clayton71fc2a32011-02-12 06:28:37 +00001431 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001432 // All threads are continuing, just send a "c" packet
1433 continue_packet.PutCString ("c");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001434 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001435 else
1436 {
1437 continue_packet.PutCString ("vCont");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001438
Greg Claytond1d06e42013-04-20 00:27:58 +00001439 if (!m_continue_c_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001440 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001441 if (m_gdb_comm.GetVContSupported ('c'))
1442 {
1443 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)
1444 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1445 }
1446 else
1447 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001448 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001449
1450 if (!continue_packet_error && !m_continue_C_tids.empty())
1451 {
1452 if (m_gdb_comm.GetVContSupported ('C'))
1453 {
1454 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)
1455 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1456 }
1457 else
1458 continue_packet_error = true;
1459 }
Greg Claytone5219662010-12-03 06:02:24 +00001460
Greg Claytond1d06e42013-04-20 00:27:58 +00001461 if (!continue_packet_error && !m_continue_s_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001462 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001463 if (m_gdb_comm.GetVContSupported ('s'))
1464 {
1465 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)
1466 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1467 }
1468 else
1469 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001470 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001471
1472 if (!continue_packet_error && !m_continue_S_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001473 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001474 if (m_gdb_comm.GetVContSupported ('S'))
1475 {
1476 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)
1477 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1478 }
1479 else
1480 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001481 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001482
1483 if (continue_packet_error)
1484 continue_packet.GetString().clear();
Greg Clayton71fc2a32011-02-12 06:28:37 +00001485 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001486 }
1487 else
1488 continue_packet_error = true;
1489
1490 if (continue_packet_error)
1491 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001492 // Either no vCont support, or we tried to use part of the vCont
1493 // packet that wasn't supported by the remote GDB server.
1494 // We need to try and make a simple packet that can do our continue
Greg Clayton71fc2a32011-02-12 06:28:37 +00001495 const size_t num_continue_c_tids = m_continue_c_tids.size();
1496 const size_t num_continue_C_tids = m_continue_C_tids.size();
1497 const size_t num_continue_s_tids = m_continue_s_tids.size();
1498 const size_t num_continue_S_tids = m_continue_S_tids.size();
1499 if (num_continue_c_tids > 0)
1500 {
1501 if (num_continue_c_tids == num_threads)
1502 {
1503 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001504 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001505 continue_packet.PutChar ('c');
1506 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001507 }
1508 else if (num_continue_c_tids == 1 &&
1509 num_continue_C_tids == 0 &&
1510 num_continue_s_tids == 0 &&
1511 num_continue_S_tids == 0 )
1512 {
1513 // Only one thread is continuing
Greg Clayton8b82f082011-04-12 05:54:46 +00001514 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001515 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001516 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001517 }
1518 }
1519
Greg Clayton0c74e782011-06-24 03:21:43 +00001520 if (continue_packet_error && num_continue_C_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001521 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001522 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1523 num_continue_C_tids > 0 &&
1524 num_continue_s_tids == 0 &&
1525 num_continue_S_tids == 0 )
Greg Clayton71fc2a32011-02-12 06:28:37 +00001526 {
1527 const int continue_signo = m_continue_C_tids.front().second;
Greg Clayton0c74e782011-06-24 03:21:43 +00001528 // Only one thread is continuing
Greg Clayton71fc2a32011-02-12 06:28:37 +00001529 if (num_continue_C_tids > 1)
1530 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001531 // More that one thread with a signal, yet we don't have
1532 // vCont support and we are being asked to resume each
1533 // thread with a signal, we need to make sure they are
1534 // all the same signal, or we can't issue the continue
1535 // accurately with the current support...
1536 if (num_continue_C_tids > 1)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001537 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001538 continue_packet_error = false;
1539 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1540 {
1541 if (m_continue_C_tids[i].second != continue_signo)
1542 continue_packet_error = true;
1543 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001544 }
Greg Clayton0c74e782011-06-24 03:21:43 +00001545 if (!continue_packet_error)
1546 m_gdb_comm.SetCurrentThreadForRun (-1);
1547 }
1548 else
1549 {
1550 // Set the continue thread ID
1551 continue_packet_error = false;
1552 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001553 }
1554 if (!continue_packet_error)
1555 {
1556 // Add threads continuing with the same signo...
Greg Clayton71fc2a32011-02-12 06:28:37 +00001557 continue_packet.Printf("C%2.2x", continue_signo);
1558 }
1559 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001560 }
1561
Greg Clayton0c74e782011-06-24 03:21:43 +00001562 if (continue_packet_error && num_continue_s_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001563 {
1564 if (num_continue_s_tids == num_threads)
1565 {
1566 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001567 m_gdb_comm.SetCurrentThreadForRun (-1);
Ewan Crawford76df2882015-06-23 12:32:06 +00001568
1569 // If in Non-Stop-Mode use vCont when stepping
1570 if (GetTarget().GetNonStopModeEnabled())
1571 {
1572 if (m_gdb_comm.GetVContSupported('s'))
1573 continue_packet.PutCString("vCont;s");
1574 else
1575 continue_packet.PutChar('s');
1576 }
1577 else
1578 continue_packet.PutChar('s');
1579
Greg Clayton0c74e782011-06-24 03:21:43 +00001580 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001581 }
1582 else if (num_continue_c_tids == 0 &&
1583 num_continue_C_tids == 0 &&
1584 num_continue_s_tids == 1 &&
1585 num_continue_S_tids == 0 )
1586 {
1587 // Only one thread is stepping
Greg Clayton8b82f082011-04-12 05:54:46 +00001588 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001589 continue_packet.PutChar ('s');
Greg Clayton0c74e782011-06-24 03:21:43 +00001590 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001591 }
1592 }
1593
1594 if (!continue_packet_error && num_continue_S_tids > 0)
1595 {
1596 if (num_continue_S_tids == num_threads)
1597 {
1598 const int step_signo = m_continue_S_tids.front().second;
1599 // Are all threads trying to step with the same signal?
Greg Clayton0c74e782011-06-24 03:21:43 +00001600 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001601 if (num_continue_S_tids > 1)
1602 {
1603 for (size_t i=1; i<num_threads; ++i)
1604 {
1605 if (m_continue_S_tids[i].second != step_signo)
1606 continue_packet_error = true;
1607 }
1608 }
1609 if (!continue_packet_error)
1610 {
1611 // Add threads stepping with the same signo...
Greg Clayton8b82f082011-04-12 05:54:46 +00001612 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001613 continue_packet.Printf("S%2.2x", step_signo);
1614 }
1615 }
1616 else if (num_continue_c_tids == 0 &&
1617 num_continue_C_tids == 0 &&
1618 num_continue_s_tids == 0 &&
1619 num_continue_S_tids == 1 )
1620 {
1621 // Only one thread is stepping with signal
Greg Clayton8b82f082011-04-12 05:54:46 +00001622 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001623 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Clayton0c74e782011-06-24 03:21:43 +00001624 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001625 }
1626 }
1627 }
1628
1629 if (continue_packet_error)
1630 {
1631 error.SetErrorString ("can't make continue packet for this resume");
1632 }
1633 else
1634 {
1635 EventSP event_sp;
1636 TimeValue timeout;
1637 timeout = TimeValue::Now();
1638 timeout.OffsetWithSeconds (5);
Zachary Turneracee96a2014-09-23 18:32:09 +00001639 if (!m_async_thread.IsJoinable())
Jim Inghamb1e2e842012-04-12 18:49:31 +00001640 {
1641 error.SetErrorString ("Trying to resume but the async thread is dead.");
1642 if (log)
1643 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1644 return error;
1645 }
1646
Greg Clayton71fc2a32011-02-12 06:28:37 +00001647 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1648
1649 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Inghamb1e2e842012-04-12 18:49:31 +00001650 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001651 error.SetErrorString("Resume timed out.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00001652 if (log)
1653 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1654 }
1655 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1656 {
1657 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1658 if (log)
1659 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1660 return error;
1661 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001662 }
Greg Claytone5219662010-12-03 06:02:24 +00001663 }
1664
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001665 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001666}
1667
Greg Clayton9e920902012-04-10 02:25:43 +00001668void
Ewan Crawford78baa192015-05-13 09:18:18 +00001669ProcessGDBRemote::HandleStopReplySequence ()
1670{
1671 while(true)
1672 {
1673 // Send vStopped
1674 StringExtractorGDBRemote response;
1675 m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false);
1676
1677 // OK represents end of signal list
1678 if (response.IsOKResponse())
1679 break;
1680
1681 // If not OK or a normal packet we have a problem
1682 if (!response.IsNormalResponse())
1683 break;
1684
1685 SetLastStopPacket(response);
1686 }
1687}
1688
1689void
Greg Clayton9e920902012-04-10 02:25:43 +00001690ProcessGDBRemote::ClearThreadIDList ()
1691{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001692 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001693 m_thread_ids.clear();
1694}
1695
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001696size_t
1697ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue (std::string &value)
1698{
1699 m_thread_ids.clear();
1700 size_t comma_pos;
1701 lldb::tid_t tid;
1702 while ((comma_pos = value.find(',')) != std::string::npos)
1703 {
1704 value[comma_pos] = '\0';
1705 // thread in big endian hex
1706 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1707 if (tid != LLDB_INVALID_THREAD_ID)
1708 m_thread_ids.push_back (tid);
1709 value.erase(0, comma_pos + 1);
1710 }
1711 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1712 if (tid != LLDB_INVALID_THREAD_ID)
1713 m_thread_ids.push_back (tid);
1714 return m_thread_ids.size();
1715}
1716
Greg Clayton9e920902012-04-10 02:25:43 +00001717bool
1718ProcessGDBRemote::UpdateThreadIDList ()
1719{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001720 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001721
Greg Clayton2e309072015-07-17 23:42:28 +00001722 if (m_jthreadsinfo_sp)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001723 {
1724 // If we have the JSON threads info, we can get the thread list from that
Greg Clayton2e309072015-07-17 23:42:28 +00001725 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001726 if (thread_infos && thread_infos->GetSize() > 0)
1727 {
1728 m_thread_ids.clear();
1729 thread_infos->ForEach([this](StructuredData::Object* object) -> bool {
1730 StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1731 if (thread_dict)
1732 {
1733 // Set the thread stop info from the JSON dictionary
1734 SetThreadStopInfo (thread_dict);
1735 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1736 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1737 m_thread_ids.push_back(tid);
1738 }
1739 return true; // Keep iterating through all thread_info objects
1740 });
1741 }
1742 if (!m_thread_ids.empty())
1743 return true;
1744 }
1745 else
1746 {
1747 // See if we can get the thread IDs from the current stop reply packets
1748 // that might contain a "threads" key/value pair
1749
1750 // Lock the thread stack while we access it
1751 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
1752 // Get the number of stop packets on the stack
1753 int nItems = m_stop_packet_stack.size();
1754 // Iterate over them
1755 for (int i = 0; i < nItems; i++)
1756 {
1757 // Get the thread stop info
1758 StringExtractorGDBRemote &stop_info = m_stop_packet_stack[i];
1759 const std::string &stop_info_str = stop_info.GetStringRef();
1760 const size_t threads_pos = stop_info_str.find(";threads:");
1761 if (threads_pos != std::string::npos)
1762 {
1763 const size_t start = threads_pos + strlen(";threads:");
1764 const size_t end = stop_info_str.find(';', start);
1765 if (end != std::string::npos)
1766 {
1767 std::string value = stop_info_str.substr(start, end - start);
1768 if (UpdateThreadIDsFromStopReplyThreadsValue(value))
1769 return true;
1770 }
1771 }
1772 }
1773 }
1774
Greg Clayton9e920902012-04-10 02:25:43 +00001775 bool sequence_mutex_unavailable = false;
1776 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1777 if (sequence_mutex_unavailable)
1778 {
Greg Clayton9e920902012-04-10 02:25:43 +00001779 return false; // We just didn't get the list
1780 }
1781 return true;
1782}
1783
Greg Clayton9fc13552012-04-10 00:18:59 +00001784bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001785ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001786{
1787 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +00001788 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Clayton73b472d2010-10-27 03:32:59 +00001789 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +00001790 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton9e920902012-04-10 02:25:43 +00001791
1792 size_t num_thread_ids = m_thread_ids.size();
1793 // The "m_thread_ids" thread ID list should always be updated after each stop
1794 // reply packet, but in case it isn't, update it here.
1795 if (num_thread_ids == 0)
1796 {
1797 if (!UpdateThreadIDList ())
1798 return false;
1799 num_thread_ids = m_thread_ids.size();
1800 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001801
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001802 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001803 if (num_thread_ids > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001804 {
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001805 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001806 {
Greg Clayton9e920902012-04-10 02:25:43 +00001807 tid_t tid = m_thread_ids[i];
Greg Clayton160c9d82013-05-01 21:54:04 +00001808 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001809 if (!thread_sp)
Jim Inghamdee1bc92013-06-22 00:27:45 +00001810 {
Jim Ingham4f465cf2012-10-10 18:32:14 +00001811 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001812 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1813 log->Printf(
1814 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001815 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001816 thread_sp->GetID());
1817 }
1818 else
1819 {
1820 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1821 log->Printf(
1822 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001823 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001824 thread_sp->GetID());
1825 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001826 new_thread_list.AddThread(thread_sp);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001827 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001828 }
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001829
1830 // Whatever that is left in old_thread_list_copy are not
1831 // present in new_thread_list. Remove non-existent threads from internal id table.
1832 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1833 for (size_t i=0; i<old_num_thread_ids; i++)
1834 {
1835 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1836 if (old_thread_sp)
1837 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001838 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001839 m_thread_id_to_index_id_map.erase(old_thread_id);
1840 }
1841 }
1842
Greg Clayton9fc13552012-04-10 00:18:59 +00001843 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001844}
1845
Greg Clayton2e309072015-07-17 23:42:28 +00001846
Greg Clayton358cf1e2015-06-25 21:46:34 +00001847bool
Greg Clayton2e309072015-07-17 23:42:28 +00001848ProcessGDBRemote::GetThreadStopInfoFromJSON (ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001849{
1850 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet
Greg Clayton2e309072015-07-17 23:42:28 +00001851 if (thread_infos_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001852 {
Greg Clayton2e309072015-07-17 23:42:28 +00001853 StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
Greg Clayton358cf1e2015-06-25 21:46:34 +00001854 if (thread_infos)
1855 {
1856 lldb::tid_t tid;
1857 const size_t n = thread_infos->GetSize();
1858 for (size_t i=0; i<n; ++i)
1859 {
1860 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1861 if (thread_dict)
1862 {
1863 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid, LLDB_INVALID_THREAD_ID))
1864 {
1865 if (tid == thread->GetID())
Greg Clayton2e309072015-07-17 23:42:28 +00001866 return (bool)SetThreadStopInfo(thread_dict);
Greg Clayton358cf1e2015-06-25 21:46:34 +00001867 }
1868 }
1869 }
1870 }
1871 }
Greg Clayton2e309072015-07-17 23:42:28 +00001872 return false;
1873}
1874
1875bool
1876ProcessGDBRemote::CalculateThreadStopInfo (ThreadGDBRemote *thread)
1877{
1878 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet
1879 if (GetThreadStopInfoFromJSON (thread, m_jthreadsinfo_sp))
1880 return true;
1881
1882 // See if we got thread stop info for any threads valid stop info reasons threads
1883 // via the "jstopinfo" packet stop reply packet key/value pair?
1884 if (m_jstopinfo_sp)
1885 {
1886 // If we have "jstopinfo" then we have stop descriptions for all threads
1887 // that have stop reasons, and if there is no entry for a thread, then
1888 // it has no stop reason.
1889 thread->GetRegisterContext()->InvalidateIfNeeded(true);
1890 if (!GetThreadStopInfoFromJSON (thread, m_jstopinfo_sp))
1891 {
1892 thread->SetStopInfo (StopInfoSP());
1893 }
1894 return true;
1895 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00001896
1897 // Fall back to using the qThreadStopInfo packet
1898 StringExtractorGDBRemote stop_packet;
1899 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1900 return SetThreadStopInfo (stop_packet) == eStateStopped;
1901 return false;
1902}
1903
1904
1905ThreadSP
1906ProcessGDBRemote::SetThreadStopInfo (lldb::tid_t tid,
1907 ExpeditedRegisterMap &expedited_register_map,
1908 uint8_t signo,
1909 const std::string &thread_name,
1910 const std::string &reason,
1911 const std::string &description,
1912 uint32_t exc_type,
1913 const std::vector<addr_t> &exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001914 addr_t thread_dispatch_qaddr,
1915 bool queue_vars_valid, // Set to true if queue_name, queue_kind and queue_serial are valid
1916 std::string &queue_name,
1917 QueueKind queue_kind,
1918 uint64_t queue_serial)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001919{
1920 ThreadSP thread_sp;
1921 if (tid != LLDB_INVALID_THREAD_ID)
1922 {
1923 // Scope for "locker" below
1924 {
1925 // m_thread_list_real does have its own mutex, but we need to
1926 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1927 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1928 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1929 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1930
1931 if (!thread_sp)
1932 {
1933 // Create the thread if we need to
1934 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1935 m_thread_list_real.AddThread(thread_sp);
1936 }
1937 }
1938
1939 if (thread_sp)
1940 {
1941 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1942 gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001943
Greg Clayton358cf1e2015-06-25 21:46:34 +00001944 for (const auto &pair : expedited_register_map)
1945 {
1946 StringExtractor reg_value_extractor;
1947 reg_value_extractor.GetStringRef() = pair.second;
1948 gdb_thread->PrivateSetRegisterValue (pair.first, reg_value_extractor);
1949 }
1950
Greg Clayton358cf1e2015-06-25 21:46:34 +00001951 thread_sp->SetName (thread_name.empty() ? NULL : thread_name.c_str());
1952
1953 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001954 // Check if the GDB server was able to provide the queue name, kind and serial number
1955 if (queue_vars_valid)
1956 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind, queue_serial);
1957 else
1958 gdb_thread->ClearQueueInfo();
1959
Greg Clayton2e309072015-07-17 23:42:28 +00001960 // Make sure we update our thread stop reason just once
1961 if (!thread_sp->StopInfoIsUpToDate())
Greg Clayton358cf1e2015-06-25 21:46:34 +00001962 {
Greg Clayton2e309072015-07-17 23:42:28 +00001963 thread_sp->SetStopInfo (StopInfoSP());
Greg Clayton358cf1e2015-06-25 21:46:34 +00001964
Greg Clayton2e309072015-07-17 23:42:28 +00001965 if (exc_type != 0)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001966 {
Greg Clayton2e309072015-07-17 23:42:28 +00001967 const size_t exc_data_size = exc_data.size();
1968
1969 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1970 exc_type,
1971 exc_data_size,
1972 exc_data_size >= 1 ? exc_data[0] : 0,
1973 exc_data_size >= 2 ? exc_data[1] : 0,
1974 exc_data_size >= 3 ? exc_data[2] : 0));
Greg Clayton358cf1e2015-06-25 21:46:34 +00001975 }
Greg Clayton2e309072015-07-17 23:42:28 +00001976 else
Greg Clayton358cf1e2015-06-25 21:46:34 +00001977 {
Greg Clayton2e309072015-07-17 23:42:28 +00001978 bool handled = false;
1979 bool did_exec = false;
1980 if (!reason.empty())
Greg Clayton358cf1e2015-06-25 21:46:34 +00001981 {
Greg Clayton2e309072015-07-17 23:42:28 +00001982 if (reason.compare("trace") == 0)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001983 {
Greg Clayton2e309072015-07-17 23:42:28 +00001984 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1985 handled = true;
1986 }
1987 else if (reason.compare("breakpoint") == 0)
1988 {
1989 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1990 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
1991 if (bp_site_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001992 {
Greg Clayton2e309072015-07-17 23:42:28 +00001993 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1994 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1995 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1996 handled = true;
1997 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
1998 {
1999 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2000 }
2001 else
2002 {
2003 StopInfoSP invalid_stop_info_sp;
2004 thread_sp->SetStopInfo (invalid_stop_info_sp);
2005 }
2006 }
2007 }
2008 else if (reason.compare("trap") == 0)
2009 {
2010 // Let the trap just use the standard signal stop reason below...
2011 }
2012 else if (reason.compare("watchpoint") == 0)
2013 {
2014 StringExtractor desc_extractor(description.c_str());
2015 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
2016 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
2017 watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
2018 if (wp_addr != LLDB_INVALID_ADDRESS)
2019 {
2020 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2021 if (wp_sp)
2022 {
2023 wp_sp->SetHardwareIndex(wp_index);
2024 watch_id = wp_sp->GetID();
2025 }
2026 }
2027 if (watch_id == LLDB_INVALID_WATCH_ID)
2028 {
2029 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_WATCHPOINTS));
2030 if (log) log->Printf ("failed to find watchpoint");
2031 }
2032 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
2033 handled = true;
2034 }
2035 else if (reason.compare("exception") == 0)
2036 {
2037 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
2038 handled = true;
2039 }
2040 else if (reason.compare("exec") == 0)
2041 {
2042 did_exec = true;
2043 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
2044 handled = true;
2045 }
2046 }
2047
2048 if (!handled && signo && did_exec == false)
2049 {
2050 if (signo == SIGTRAP)
2051 {
2052 // Currently we are going to assume SIGTRAP means we are either
2053 // hitting a breakpoint or hardware single stepping.
2054 handled = true;
2055 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
2056 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2057
2058 if (bp_site_sp)
2059 {
2060 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2061 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2062 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2063 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2064 {
2065 if(m_breakpoint_pc_offset != 0)
2066 thread_sp->GetRegisterContext()->SetPC(pc);
2067 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2068 }
2069 else
2070 {
2071 StopInfoSP invalid_stop_info_sp;
2072 thread_sp->SetStopInfo (invalid_stop_info_sp);
2073 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002074 }
2075 else
2076 {
Greg Clayton2e309072015-07-17 23:42:28 +00002077 // If we were stepping then assume the stop was the result of the trace. If we were
2078 // not stepping then report the SIGTRAP.
2079 // FIXME: We are still missing the case where we single step over a trap instruction.
2080 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
2081 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
2082 else
2083 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo, description.c_str()));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002084 }
2085 }
Greg Clayton2e309072015-07-17 23:42:28 +00002086 if (!handled)
2087 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo, description.c_str()));
2088 }
2089
2090 if (!description.empty())
2091 {
2092 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
2093 if (stop_info_sp)
2094 {
2095 const char *stop_info_desc = stop_info_sp->GetDescription();
2096 if (!stop_info_desc || !stop_info_desc[0])
2097 stop_info_sp->SetDescription (description.c_str());
2098 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002099 else
2100 {
Greg Clayton2e309072015-07-17 23:42:28 +00002101 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002102 }
2103 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002104 }
2105 }
2106 }
2107 }
2108 return thread_sp;
2109}
2110
Greg Clayton2e309072015-07-17 23:42:28 +00002111lldb::ThreadSP
Greg Clayton358cf1e2015-06-25 21:46:34 +00002112ProcessGDBRemote::SetThreadStopInfo (StructuredData::Dictionary *thread_dict)
2113{
2114 static ConstString g_key_tid("tid");
2115 static ConstString g_key_name("name");
2116 static ConstString g_key_reason("reason");
2117 static ConstString g_key_metype("metype");
2118 static ConstString g_key_medata("medata");
2119 static ConstString g_key_qaddr("qaddr");
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002120 static ConstString g_key_queue_name("qname");
2121 static ConstString g_key_queue_kind("qkind");
2122 static ConstString g_key_queue_serial("qserial");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002123 static ConstString g_key_registers("registers");
2124 static ConstString g_key_memory("memory");
2125 static ConstString g_key_address("address");
2126 static ConstString g_key_bytes("bytes");
2127 static ConstString g_key_description("description");
Pavel Labath4a4bb122015-07-16 14:14:35 +00002128 static ConstString g_key_signal("signal");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002129
2130 // Stop with signal and thread info
2131 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2132 uint8_t signo = 0;
2133 std::string value;
2134 std::string thread_name;
2135 std::string reason;
2136 std::string description;
2137 uint32_t exc_type = 0;
2138 std::vector<addr_t> exc_data;
2139 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2140 ExpeditedRegisterMap expedited_register_map;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002141 bool queue_vars_valid = false;
2142 std::string queue_name;
2143 QueueKind queue_kind = eQueueKindUnknown;
2144 uint64_t queue_serial = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002145 // Iterate through all of the thread dictionary key/value pairs from the structured data dictionary
2146
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002147 thread_dict->ForEach([this,
2148 &tid,
2149 &expedited_register_map,
2150 &thread_name,
2151 &signo,
2152 &reason,
2153 &description,
2154 &exc_type,
2155 &exc_data,
2156 &thread_dispatch_qaddr,
2157 &queue_vars_valid,
2158 &queue_name,
2159 &queue_kind,
2160 &queue_serial]
2161 (ConstString key, StructuredData::Object* object) -> bool
Greg Clayton358cf1e2015-06-25 21:46:34 +00002162 {
2163 if (key == g_key_tid)
2164 {
2165 // thread in big endian hex
2166 tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
2167 }
2168 else if (key == g_key_metype)
2169 {
2170 // exception type in big endian hex
2171 exc_type = object->GetIntegerValue(0);
2172 }
2173 else if (key == g_key_medata)
2174 {
2175 // exception data in big endian hex
2176 StructuredData::Array *array = object->GetAsArray();
2177 if (array)
2178 {
2179 array->ForEach([&exc_data](StructuredData::Object* object) -> bool {
2180 exc_data.push_back(object->GetIntegerValue());
2181 return true; // Keep iterating through all array items
2182 });
2183 }
2184 }
2185 else if (key == g_key_name)
2186 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002187 thread_name = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002188 }
2189 else if (key == g_key_qaddr)
2190 {
2191 thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
2192 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002193 else if (key == g_key_queue_name)
2194 {
2195 queue_vars_valid = true;
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002196 queue_name = object->GetStringValue();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002197 }
2198 else if (key == g_key_queue_kind)
2199 {
2200 std::string queue_kind_str = object->GetStringValue();
2201 if (queue_kind_str == "serial")
2202 {
2203 queue_vars_valid = true;
2204 queue_kind = eQueueKindSerial;
2205 }
2206 else if (queue_kind_str == "concurrent")
2207 {
2208 queue_vars_valid = true;
2209 queue_kind = eQueueKindConcurrent;
2210 }
2211 }
2212 else if (key == g_key_queue_serial)
2213 {
2214 queue_serial = object->GetIntegerValue(0);
2215 if (queue_serial != 0)
2216 queue_vars_valid = true;
2217 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002218 else if (key == g_key_reason)
2219 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002220 reason = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002221 }
2222 else if (key == g_key_description)
2223 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002224 description = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002225 }
2226 else if (key == g_key_registers)
2227 {
2228 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2229
2230 if (registers_dict)
2231 {
2232 registers_dict->ForEach([&expedited_register_map](ConstString key, StructuredData::Object* object) -> bool {
2233 const uint32_t reg = StringConvert::ToUInt32 (key.GetCString(), UINT32_MAX, 10);
2234 if (reg != UINT32_MAX)
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002235 expedited_register_map[reg] = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002236 return true; // Keep iterating through all array items
2237 });
2238 }
2239 }
2240 else if (key == g_key_memory)
2241 {
2242 StructuredData::Array *array = object->GetAsArray();
2243 if (array)
2244 {
2245 array->ForEach([this](StructuredData::Object* object) -> bool {
2246 StructuredData::Dictionary *mem_cache_dict = object->GetAsDictionary();
2247 if (mem_cache_dict)
2248 {
2249 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2250 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>("address", mem_cache_addr))
2251 {
2252 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
2253 {
2254 StringExtractor bytes;
2255 if (mem_cache_dict->GetValueForKeyAsString("bytes", bytes.GetStringRef()))
2256 {
2257 bytes.SetFilePos(0);
2258
2259 const size_t byte_size = bytes.GetStringRef().size()/2;
2260 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2261 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2262 if (bytes_copied == byte_size)
2263 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2264 }
2265 }
2266 }
2267 }
2268 return true; // Keep iterating through all array items
2269 });
2270 }
2271
2272 }
Pavel Labath4a4bb122015-07-16 14:14:35 +00002273 else if (key == g_key_signal)
2274 signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002275 return true; // Keep iterating through all dictionary key/value pairs
2276 });
2277
Greg Clayton2e309072015-07-17 23:42:28 +00002278 return SetThreadStopInfo (tid,
2279 expedited_register_map,
2280 signo,
2281 thread_name,
2282 reason,
2283 description,
2284 exc_type,
2285 exc_data,
2286 thread_dispatch_qaddr,
2287 queue_vars_valid,
2288 queue_name,
2289 queue_kind,
2290 queue_serial);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002291}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002292
2293StateType
2294ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
2295{
Greg Claytondd0e5a52011-06-02 22:22:38 +00002296 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002297 const char stop_type = stop_packet.GetChar();
2298 switch (stop_type)
2299 {
2300 case 'T':
2301 case 'S':
2302 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00002303 // This is a bit of a hack, but is is required. If we did exec, we
2304 // need to clear our thread lists and also know to rebuild our dynamic
2305 // register info before we lookup and threads and populate the expedited
2306 // register values so we need to know this right away so we can cleanup
2307 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00002308 const uint32_t stop_id = GetStopID();
2309 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00002310 {
2311 // Our first stop, make sure we have a process ID, and also make
2312 // sure we know about our registers
2313 if (GetID() == LLDB_INVALID_PROCESS_ID)
2314 {
Greg Claytonc574ede2011-03-10 02:26:48 +00002315 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00002316 if (pid != LLDB_INVALID_PROCESS_ID)
2317 SetID (pid);
2318 }
2319 BuildDynamicRegisterInfo (true);
2320 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002321 // Stop with signal and thread info
Greg Clayton358cf1e2015-06-25 21:46:34 +00002322 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002323 const uint8_t signo = stop_packet.GetHexU8();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002324 std::string key;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002325 std::string value;
2326 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00002327 std::string reason;
2328 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002329 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00002330 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002331 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton0b90be12015-06-23 21:27:50 +00002332 bool queue_vars_valid = false; // says if locals below that start with "queue_" are valid
2333 std::string queue_name;
2334 QueueKind queue_kind = eQueueKindUnknown;
2335 uint64_t queue_serial = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002336 ExpeditedRegisterMap expedited_register_map;
2337 while (stop_packet.GetNameColonValue(key, value))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002338 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002339 if (key.compare("metype") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002340 {
2341 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002342 exc_type = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002343 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002344 else if (key.compare("medata") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002345 {
2346 // exception data in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002347 exc_data.push_back(StringConvert::ToUInt64 (value.c_str(), 0, 16));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002348 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002349 else if (key.compare("thread") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002350 {
2351 // thread in big endian hex
Greg Clayton358cf1e2015-06-25 21:46:34 +00002352 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002353 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002354 else if (key.compare("threads") == 0)
Greg Clayton9e920902012-04-10 02:25:43 +00002355 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002356 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00002357 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00002358 // A comma separated list of all threads in the current
2359 // process that includes the thread for this stop reply
2360 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00002361 size_t comma_pos;
2362 lldb::tid_t tid;
2363 while ((comma_pos = value.find(',')) != std::string::npos)
2364 {
2365 value[comma_pos] = '\0';
2366 // thread in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002367 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00002368 if (tid != LLDB_INVALID_THREAD_ID)
2369 m_thread_ids.push_back (tid);
2370 value.erase(0, comma_pos + 1);
Greg Clayton9e920902012-04-10 02:25:43 +00002371 }
Vince Harron5275aaa2015-01-15 20:08:35 +00002372 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00002373 if (tid != LLDB_INVALID_THREAD_ID)
2374 m_thread_ids.push_back (tid);
2375 }
Greg Clayton2e309072015-07-17 23:42:28 +00002376 else if (key.compare("jstopinfo") == 0)
Greg Claytona5801ad2015-07-15 22:59:03 +00002377 {
2378 StringExtractor json_extractor;
2379 // Swap "value" over into "name_extractor"
2380 json_extractor.GetStringRef().swap(value);
2381 // Now convert the HEX bytes into a string value
2382 json_extractor.GetHexByteString (value);
2383
2384 // This JSON contains thread IDs and thread stop info for all threads.
2385 // It doesn't contain expedited registers, memory or queue info.
Greg Clayton2e309072015-07-17 23:42:28 +00002386 m_jstopinfo_sp = StructuredData::ParseJSON (value);
Greg Claytona5801ad2015-07-15 22:59:03 +00002387 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002388 else if (key.compare("hexname") == 0)
Greg Claytonde9d0492011-01-08 03:17:57 +00002389 {
2390 StringExtractor name_extractor;
2391 // Swap "value" over into "name_extractor"
2392 name_extractor.GetStringRef().swap(value);
2393 // Now convert the HEX bytes into a string value
2394 name_extractor.GetHexByteString (value);
2395 thread_name.swap (value);
2396 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002397 else if (key.compare("name") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002398 {
2399 thread_name.swap (value);
2400 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002401 else if (key.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002402 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002403 thread_dispatch_qaddr = StringConvert::ToUInt64 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002404 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002405 else if (key.compare("qname") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002406 {
2407 queue_vars_valid = true;
2408 StringExtractor name_extractor;
2409 // Swap "value" over into "name_extractor"
2410 name_extractor.GetStringRef().swap(value);
2411 // Now convert the HEX bytes into a string value
2412 name_extractor.GetHexByteString (value);
2413 queue_name.swap (value);
2414 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002415 else if (key.compare("qkind") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002416 {
Greg Clayton0b90be12015-06-23 21:27:50 +00002417 if (value == "serial")
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002418 {
2419 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002420 queue_kind = eQueueKindSerial;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002421 }
Greg Clayton0b90be12015-06-23 21:27:50 +00002422 else if (value == "concurrent")
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002423 {
2424 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002425 queue_kind = eQueueKindConcurrent;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002426 }
Greg Clayton0b90be12015-06-23 21:27:50 +00002427 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002428 else if (key.compare("qserial") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002429 {
Greg Clayton0b90be12015-06-23 21:27:50 +00002430 queue_serial = StringConvert::ToUInt64 (value.c_str(), 0, 0);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002431 if (queue_serial != 0)
2432 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002433 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002434 else if (key.compare("reason") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002435 {
2436 reason.swap(value);
2437 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002438 else if (key.compare("description") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002439 {
2440 StringExtractor desc_extractor;
2441 // Swap "value" over into "name_extractor"
2442 desc_extractor.GetStringRef().swap(value);
2443 // Now convert the HEX bytes into a string value
Chaoren Lin28e57422015-02-03 01:51:25 +00002444 desc_extractor.GetHexByteString (value);
2445 description.swap(value);
Greg Claytona658fd22011-06-04 01:26:29 +00002446 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002447 else if (key.compare("memory") == 0)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002448 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002449 // Expedited memory. GDB servers can choose to send back expedited memory
2450 // that can populate the L1 memory cache in the process so that things like
2451 // the frame pointer backchain can be expedited. This will help stack
2452 // backtracing be more efficient by not having to send as many memory read
2453 // requests down the remote GDB server.
Chaoren Lin7a306082015-06-23 03:17:01 +00002454
Greg Clayton358cf1e2015-06-25 21:46:34 +00002455 // Key/value pair format: memory:<addr>=<bytes>;
2456 // <addr> is a number whose base will be interpreted by the prefix:
2457 // "0x[0-9a-fA-F]+" for hex
2458 // "0[0-7]+" for octal
2459 // "[1-9]+" for decimal
2460 // <bytes> is native endian ASCII hex bytes just like the register values
2461 llvm::StringRef value_ref(value);
2462 std::pair<llvm::StringRef, llvm::StringRef> pair;
2463 pair = value_ref.split('=');
2464 if (!pair.first.empty() && !pair.second.empty())
2465 {
2466 std::string addr_str(pair.first.str());
2467 const lldb::addr_t mem_cache_addr = StringConvert::ToUInt64(addr_str.c_str(), LLDB_INVALID_ADDRESS, 0);
2468 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002469 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002470 StringExtractor bytes;
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002471 bytes.GetStringRef() = pair.second.str();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002472 const size_t byte_size = bytes.GetStringRef().size()/2;
2473 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2474 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2475 if (bytes_copied == byte_size)
2476 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
Greg Clayton3e06bd92011-01-09 21:07:35 +00002477 }
2478 }
2479 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002480 else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1]))
2481 {
2482 uint32_t reg = StringConvert::ToUInt32 (key.c_str(), UINT32_MAX, 16);
2483 if (reg != UINT32_MAX)
2484 expedited_register_map[reg] = std::move(value);
2485 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002486 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002487
Bhushan D. Attarde1e271df2015-07-24 04:06:20 +00002488 if (tid == LLDB_INVALID_THREAD_ID)
2489 {
2490 // A thread id may be invalid if the response is old style 'S' packet which does not provide the
2491 // thread information. So update the thread list and choose the first one.
2492 UpdateThreadIDList ();
2493
2494 if (!m_thread_ids.empty ())
2495 {
2496 tid = m_thread_ids.front ();
2497 }
2498 }
2499
Greg Clayton358cf1e2015-06-25 21:46:34 +00002500 ThreadSP thread_sp = SetThreadStopInfo (tid,
2501 expedited_register_map,
2502 signo,
2503 thread_name,
2504 reason,
2505 description,
2506 exc_type,
2507 exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002508 thread_dispatch_qaddr,
2509 queue_vars_valid,
2510 queue_name,
2511 queue_kind,
2512 queue_serial);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002513
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002514 return eStateStopped;
2515 }
2516 break;
2517
2518 case 'W':
Todd Fialaff6131a2014-05-19 04:57:23 +00002519 case 'X':
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002520 // process exited
2521 return eStateExited;
2522
2523 default:
2524 break;
2525 }
2526 return eStateInvalid;
2527}
2528
2529void
2530ProcessGDBRemote::RefreshStateAfterStop ()
2531{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002532 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00002533 m_thread_ids.clear();
2534 // Set the thread stop info. It might have a "threads" key whose value is
2535 // a list of all thread IDs in the current process, so m_thread_ids might
2536 // get set.
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002537
2538 // Scope for the lock
2539 {
2540 // Lock the thread stack while we access it
2541 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
2542 // Get the number of stop packets on the stack
2543 int nItems = m_stop_packet_stack.size();
2544 // Iterate over them
2545 for (int i = 0; i < nItems; i++)
2546 {
2547 // Get the thread stop info
2548 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2549 // Process thread stop info
2550 SetThreadStopInfo(stop_info);
2551 }
2552 // Clear the thread stop stack
2553 m_stop_packet_stack.clear();
2554 }
2555
Greg Clayton9e920902012-04-10 02:25:43 +00002556 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2557 if (m_thread_ids.empty())
2558 {
2559 // No, we need to fetch the thread list manually
2560 UpdateThreadIDList();
2561 }
2562
Ewan Crawford78baa192015-05-13 09:18:18 +00002563 // If we have queried for a default thread id
2564 if (m_initial_tid != LLDB_INVALID_THREAD_ID)
2565 {
2566 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2567 m_initial_tid = LLDB_INVALID_THREAD_ID;
2568 }
2569
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002570 // Let all threads recover from stopping and do any clean up based
2571 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002572 m_thread_list_real.RefreshStateAfterStop();
Greg Clayton9e920902012-04-10 02:25:43 +00002573
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002574}
2575
2576Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002577ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002578{
2579 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002580
Greg Clayton6ed95942011-01-22 07:12:45 +00002581 bool timed_out = false;
2582 Mutex::Locker locker;
Greg Clayton513c26c2011-01-29 07:10:55 +00002583
2584 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002585 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002586 // We are being asked to halt during an attach. We need to just close
2587 // our file handle and debugserver will go away, and we can be done...
2588 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00002589 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002590 else
2591 {
Greg Clayton2687cd12012-03-29 01:55:41 +00002592 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton513c26c2011-01-29 07:10:55 +00002593 {
2594 if (timed_out)
2595 error.SetErrorString("timed out sending interrupt packet");
2596 else
2597 error.SetErrorString("unknown error sending interrupt packet");
2598 }
Greg Clayton2687cd12012-03-29 01:55:41 +00002599
2600 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton513c26c2011-01-29 07:10:55 +00002601 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002602 return error;
2603}
2604
2605Error
Jim Inghamacff8952013-05-02 00:27:30 +00002606ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002607{
2608 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002609 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00002610 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00002611 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2612
Jim Inghamacff8952013-05-02 00:27:30 +00002613 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002614 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002615 {
Jim Inghamacff8952013-05-02 00:27:30 +00002616 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002617 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
2618 else
Jim Inghamacff8952013-05-02 00:27:30 +00002619 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00002620 }
Jim Inghamacff8952013-05-02 00:27:30 +00002621
2622 if (!error.Success())
2623 return error;
2624
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002625 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00002626 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002627
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002628 SetPrivateState (eStateDetached);
2629 ResumePrivateStateThread();
2630
2631 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00002632 return error;
2633}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002634
Jim Ingham43c555d2012-07-04 00:35:43 +00002635
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002636Error
2637ProcessGDBRemote::DoDestroy ()
2638{
2639 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002640 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002641 if (log)
2642 log->Printf ("ProcessGDBRemote::DoDestroy()");
2643
Jim Ingham43c555d2012-07-04 00:35:43 +00002644 // There is a bug in older iOS debugservers where they don't shut down the process
2645 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
2646 // this can cause problems with restarting. So we check to see if any of our threads are stopped
2647 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
2648 // destroy it again.
2649 //
2650 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
2651 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
2652 // the debugservers with this bug are equal. There really should be a better way to test this!
2653 //
2654 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
2655 // get called here to destroy again and we're still at a breakpoint or exception, then we should
2656 // just do the straight-forward kill.
2657 //
2658 // And of course, if we weren't able to stop the process by the time we get here, it isn't
2659 // necessary (or helpful) to do any of this.
2660
2661 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
2662 {
2663 PlatformSP platform_sp = GetTarget().GetPlatform();
2664
2665 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2666 if (platform_sp
2667 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00002668 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00002669 {
2670 if (m_destroy_tried_resuming)
2671 {
2672 if (log)
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002673 log->PutCString ("ProcessGDBRemote::DoDestroy() - Tried resuming to destroy once already, not doing it again.");
Jim Ingham43c555d2012-07-04 00:35:43 +00002674 }
2675 else
2676 {
2677 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
2678 // but we really need it to happen here and it doesn't matter if we do it twice.
2679 m_thread_list.DiscardThreadPlans();
2680 DisableAllBreakpointSites();
2681
2682 bool stop_looks_like_crash = false;
2683 ThreadList &threads = GetThreadList();
2684
2685 {
Jim Ingham45350372012-09-11 00:08:52 +00002686 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002687
2688 size_t num_threads = threads.GetSize();
2689 for (size_t i = 0; i < num_threads; i++)
2690 {
2691 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002692 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002693 StopReason reason = eStopReasonInvalid;
2694 if (stop_info_sp)
2695 reason = stop_info_sp->GetStopReason();
2696 if (reason == eStopReasonBreakpoint
2697 || reason == eStopReasonException)
2698 {
2699 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002700 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
2701 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00002702 stop_info_sp->GetDescription());
2703 stop_looks_like_crash = true;
2704 break;
2705 }
2706 }
2707 }
2708
2709 if (stop_looks_like_crash)
2710 {
2711 if (log)
2712 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
2713 m_destroy_tried_resuming = true;
2714
2715 // If we are going to run again before killing, it would be good to suspend all the threads
2716 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
2717 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
2718 // have to run the risk of letting those threads proceed a bit.
2719
2720 {
Jim Ingham45350372012-09-11 00:08:52 +00002721 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002722
2723 size_t num_threads = threads.GetSize();
2724 for (size_t i = 0; i < num_threads; i++)
2725 {
2726 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002727 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002728 StopReason reason = eStopReasonInvalid;
2729 if (stop_info_sp)
2730 reason = stop_info_sp->GetStopReason();
2731 if (reason != eStopReasonBreakpoint
2732 && reason != eStopReasonException)
2733 {
2734 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002735 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
2736 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00002737 thread_sp->SetResumeState(eStateSuspended);
2738 }
2739 }
2740 }
2741 Resume ();
Jason Molendaede31932015-04-17 05:01:58 +00002742 return Destroy(false);
Jim Ingham43c555d2012-07-04 00:35:43 +00002743 }
2744 }
2745 }
2746 }
2747
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002748 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00002749 int exit_status = SIGABRT;
2750 std::string exit_string;
2751
Greg Clayton6ed95942011-01-22 07:12:45 +00002752 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002753 {
Jim Inghamaab78372011-10-28 01:11:35 +00002754 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00002755 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002756 StringExtractorGDBRemote response;
2757 bool send_async = true;
Tamas Berghammer912800c2015-02-24 10:23:39 +00002758 GDBRemoteCommunication::ScopedTimeout (m_gdb_comm, 3);
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002759
Greg Clayton3dedae12013-12-06 21:45:27 +00002760 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton513c26c2011-01-29 07:10:55 +00002761 {
2762 char packet_cmd = response.GetChar(0);
2763
2764 if (packet_cmd == 'W' || packet_cmd == 'X')
2765 {
Jim Inghameac0aa42014-02-21 22:36:11 +00002766#if defined(__APPLE__)
Jim Ingham9d67cc52014-02-21 22:35:29 +00002767 // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off
2768 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill
2769 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns
2770 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap
2771 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of
2772 // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2773 // Anyway, so call waitpid here to finally reap it.
2774 PlatformSP platform_sp(GetTarget().GetPlatform());
2775 if (platform_sp && platform_sp->IsHost())
2776 {
2777 int status;
2778 ::pid_t reap_pid;
2779 reap_pid = waitpid (GetID(), &status, WNOHANG);
2780 if (log)
2781 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2782 }
2783#endif
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002784 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002785 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00002786 exit_status = response.GetHexU8();
2787 }
2788 else
2789 {
2790 if (log)
2791 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2792 exit_string.assign("got unexpected response to k packet: ");
2793 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00002794 }
2795 }
2796 else
2797 {
Jim Inghambabfc382012-06-06 00:32:39 +00002798 if (log)
2799 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2800 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00002801 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002802 }
Jim Inghambabfc382012-06-06 00:32:39 +00002803 else
2804 {
2805 if (log)
Ed Masteb3a53332014-03-17 17:05:22 +00002806 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching");
Jim Inghamcfc09352012-07-27 23:57:19 +00002807 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00002808 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002809 }
Jim Inghambabfc382012-06-06 00:32:39 +00002810 else
2811 {
2812 // If we missed setting the exit status on the way out, do it here.
2813 // NB set exit status can be called multiple times, the first one sets the status.
2814 exit_string.assign("destroying when not connected to debugserver");
2815 }
2816
2817 SetExitStatus(exit_status, exit_string.c_str());
2818
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002819 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002820 KillDebugserverProcess ();
2821 return error;
2822}
2823
Greg Clayton8cda7f02013-05-21 21:55:59 +00002824void
2825ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2826{
Greg Clayton8cda7f02013-05-21 21:55:59 +00002827 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2828 if (did_exec)
2829 {
2830 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2831 if (log)
2832 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2833
2834 m_thread_list_real.Clear();
2835 m_thread_list.Clear();
2836 BuildDynamicRegisterInfo (true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002837 m_gdb_comm.ResetDiscoverableSettings (did_exec);
Greg Clayton8cda7f02013-05-21 21:55:59 +00002838 }
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002839
2840 // Scope the lock
2841 {
2842 // Lock the thread stack while we access it
2843 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
Greg Clayton2e309072015-07-17 23:42:28 +00002844
2845 // We are are not using non-stop mode, there can only be one last stop
2846 // reply packet, so clear the list.
2847 if (GetTarget().GetNonStopModeEnabled() == false)
2848 m_stop_packet_stack.clear();
2849
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002850 // Add this stop packet to the stop packet stack
2851 // This stack will get popped and examined when we switch to the
2852 // Stopped state
2853 m_stop_packet_stack.push_back(response);
2854 }
Greg Clayton8cda7f02013-05-21 21:55:59 +00002855}
2856
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002857//------------------------------------------------------------------
2858// Process Queries
2859//------------------------------------------------------------------
2860
2861bool
2862ProcessGDBRemote::IsAlive ()
2863{
Greg Clayton10177aa2010-12-08 05:08:21 +00002864 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002865}
2866
2867addr_t
2868ProcessGDBRemote::GetImageInfoAddress()
2869{
Aidan Doddsc0c83852015-05-08 09:36:31 +00002870 // request the link map address via the $qShlibInfoAddr packet
2871 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2872
2873 // the loaded module list can also provides a link map address
2874 if (addr == LLDB_INVALID_ADDRESS)
2875 {
2876 GDBLoadedModuleInfoList list;
2877 if (GetLoadedModuleList (list).Success())
2878 addr = list.m_link_map;
2879 }
2880
2881 return addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002882}
2883
Greg Clayton2e309072015-07-17 23:42:28 +00002884void
2885ProcessGDBRemote::WillPublicStop ()
2886{
2887 // See if the GDB remote client supports the JSON threads info.
2888 // If so, we gather stop info for all threads, expedited registers,
2889 // expedited memory, runtime queue information (iOS and MacOSX only),
2890 // and more. Expediting memory will help stack backtracing be much
2891 // faster. Expediting registers will make sure we don't have to read
2892 // the thread registers for GPRs.
2893 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
2894
2895 if (m_jthreadsinfo_sp)
2896 {
2897 // Now set the stop info for each thread and also expedite any registers
2898 // and memory that was in the jThreadsInfo response.
2899 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
2900 if (thread_infos)
2901 {
2902 const size_t n = thread_infos->GetSize();
2903 for (size_t i=0; i<n; ++i)
2904 {
2905 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
2906 if (thread_dict)
2907 SetThreadStopInfo(thread_dict);
2908 }
2909 }
2910 }
2911}
2912
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002913//------------------------------------------------------------------
2914// Process Memory
2915//------------------------------------------------------------------
2916size_t
2917ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2918{
Jason Molenda6076bf42014-05-06 04:34:52 +00002919 GetMaxMemorySize ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002920 if (size > m_max_memory_size)
2921 {
2922 // Keep memory read sizes down to a sane limit. This function will be
2923 // called multiple times in order to complete the task by
2924 // lldb_private::Process so it is ok to do this.
2925 size = m_max_memory_size;
2926 }
2927
2928 char packet[64];
Jason Molenda6076bf42014-05-06 04:34:52 +00002929 int packet_len;
2930 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2931 if (binary_memory_read)
2932 {
2933 packet_len = ::snprintf (packet, sizeof(packet), "x0x%" PRIx64 ",0x%" PRIx64, (uint64_t)addr, (uint64_t)size);
2934 }
2935 else
2936 {
2937 packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
2938 }
Andy Gibbsa297a972013-06-19 19:04:53 +00002939 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002940 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002941 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002942 {
Greg Clayton576d8832011-03-22 04:00:09 +00002943 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002944 {
2945 error.Clear();
Jason Molenda6076bf42014-05-06 04:34:52 +00002946 if (binary_memory_read)
2947 {
2948 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any
2949 // 0x7d character escaping that was present in the packet
2950
2951 size_t data_received_size = response.GetBytesLeft();
2952 if (data_received_size > size)
2953 {
2954 // Don't write past the end of BUF if the remote debug server gave us too
2955 // much data for some reason.
2956 data_received_size = size;
2957 }
2958 memcpy (buf, response.GetStringRef().data(), data_received_size);
2959 return data_received_size;
2960 }
2961 else
2962 {
2963 return response.GetHexBytes(buf, size, '\xdd');
2964 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002965 }
Greg Clayton576d8832011-03-22 04:00:09 +00002966 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002967 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002968 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002969 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002970 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002971 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002972 }
2973 else
2974 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002975 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002976 }
2977 return 0;
2978}
2979
2980size_t
2981ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2982{
Jason Molenda6076bf42014-05-06 04:34:52 +00002983 GetMaxMemorySize ();
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002984 if (size > m_max_memory_size)
2985 {
2986 // Keep memory read sizes down to a sane limit. This function will be
2987 // called multiple times in order to complete the task by
2988 // lldb_private::Process so it is ok to do this.
2989 size = m_max_memory_size;
2990 }
2991
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002992 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00002993 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Clayton7fb56d02011-02-01 01:31:41 +00002994 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002995 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002996 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002997 {
Greg Clayton576d8832011-03-22 04:00:09 +00002998 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002999 {
3000 error.Clear();
3001 return size;
3002 }
Greg Clayton576d8832011-03-22 04:00:09 +00003003 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00003004 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00003005 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00003006 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003007 else
Greg Clayton9944cd72012-09-19 01:46:31 +00003008 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 +00003009 }
3010 else
3011 {
Jim Ingham35579dd2013-06-03 19:34:01 +00003012 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003013 }
3014 return 0;
3015}
3016
3017lldb::addr_t
3018ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
3019{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003020 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_EXPRESSIONS));
Greg Clayton2a48f522011-05-14 01:50:35 +00003021 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
3022
Greg Clayton70b57652011-05-15 01:25:55 +00003023 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton2a48f522011-05-14 01:50:35 +00003024 switch (supported)
3025 {
3026 case eLazyBoolCalculate:
3027 case eLazyBoolYes:
3028 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
3029 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
3030 return allocated_addr;
3031
3032 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003033 // Call mmap() to create memory in the inferior..
3034 unsigned prot = 0;
3035 if (permissions & lldb::ePermissionsReadable)
3036 prot |= eMmapProtRead;
3037 if (permissions & lldb::ePermissionsWritable)
3038 prot |= eMmapProtWrite;
3039 if (permissions & lldb::ePermissionsExecutable)
3040 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00003041
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003042 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
3043 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
3044 m_addr_to_mmap_size[allocated_addr] = size;
3045 else
Todd Fialaaf245d12014-06-30 21:05:18 +00003046 {
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003047 allocated_addr = LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00003048 if (log)
3049 log->Printf ("ProcessGDBRemote::%s no direct stub support for memory allocation, and InferiorCallMmap also failed - is stub missing register context save/restore capability?", __FUNCTION__);
3050 }
Greg Clayton2a48f522011-05-14 01:50:35 +00003051 break;
3052 }
3053
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003054 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00003055 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003056 else
3057 error.Clear();
3058 return allocated_addr;
3059}
3060
3061Error
Greg Clayton46fb5582011-11-18 07:03:08 +00003062ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
3063 MemoryRegionInfo &region_info)
3064{
3065
3066 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
3067 return error;
3068}
3069
3070Error
Johnny Chen64637202012-05-23 21:09:52 +00003071ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
3072{
3073
3074 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
3075 return error;
3076}
3077
3078Error
Enrico Granataf04a2192012-07-13 23:18:48 +00003079ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
3080{
3081 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
3082 return error;
3083}
3084
3085Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003086ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
3087{
3088 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00003089 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
3090
3091 switch (supported)
3092 {
3093 case eLazyBoolCalculate:
3094 // We should never be deallocating memory without allocating memory
3095 // first so we should never get eLazyBoolCalculate
3096 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
3097 break;
3098
3099 case eLazyBoolYes:
3100 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00003101 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003102 break;
3103
3104 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003105 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00003106 {
3107 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003108 if (pos != m_addr_to_mmap_size.end() &&
3109 InferiorCallMunmap(this, addr, pos->second))
3110 m_addr_to_mmap_size.erase (pos);
3111 else
Daniel Malead01b2952012-11-29 21:49:15 +00003112 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003113 }
3114 break;
3115 }
3116
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003117 return error;
3118}
3119
3120
3121//------------------------------------------------------------------
3122// Process STDIO
3123//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003124size_t
3125ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
3126{
3127 if (m_stdio_communication.IsConnected())
3128 {
3129 ConnectionStatus status;
3130 m_stdio_communication.Write(src, src_len, status, NULL);
3131 }
Vince Harrondf3f00f2015-02-10 21:09:04 +00003132 else if (m_stdin_forward)
Vince Harrone0be4252015-02-06 18:32:57 +00003133 {
3134 m_gdb_comm.SendStdinNotification(src, src_len);
3135 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003136 return 0;
3137}
3138
3139Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003140ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003141{
3142 Error error;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003143 assert(bp_site != NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003144
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003145 // Get logging info
3146 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003147 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003148
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003149 // Get the breakpoint address
3150 const addr_t addr = bp_site->GetLoadAddress();
3151
3152 // Log that a breakpoint was requested
3153 if (log)
3154 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
3155
3156 // Breakpoint already exists and is enabled
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003157 if (bp_site->IsEnabled())
3158 {
3159 if (log)
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003160 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 +00003161 return error;
3162 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003163
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003164 // Get the software breakpoint trap opcode size
3165 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3166
3167 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
3168 // is supported by the remote stub. These are set to true by default, and later set to false
3169 // only after we receive an unimplemented response when sending a breakpoint packet. This means
3170 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
3171 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
3172 // indicates if the user specifically asked for hardware breakpoints. If true then we will
3173 // skip over software breakpoints.
3174 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
3175 {
3176 // Try to send off a software breakpoint packet ($Z0)
3177 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003178 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003179 // The breakpoint was placed successfully
3180 bp_site->SetEnabled(true);
3181 bp_site->SetType(BreakpointSite::eExternal);
Greg Claytoneb023e72013-10-11 19:48:25 +00003182 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003183 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003184
3185 // SendGDBStoppointTypePacket() will return an error if it was unable to set this
3186 // breakpoint. We need to differentiate between a error specific to placing this breakpoint
3187 // or if we have learned that this breakpoint type is unsupported. To do this, we
3188 // must test the support boolean for this breakpoint type to see if it now indicates that
3189 // this breakpoint type is unsupported. If they are still supported then we should return
3190 // with the error code. If they are now unsupported, then we would like to fall through
3191 // and try another form of breakpoint.
3192 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
3193 return error;
3194
3195 // We reach here when software breakpoints have been found to be unsupported. For future
3196 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
3197 // known not to be supported.
3198 if (log)
3199 log->Printf("Software breakpoints are unsupported");
3200
3201 // So we will fall through and try a hardware breakpoint
3202 }
3203
3204 // The process of setting a hardware breakpoint is much the same as above. We check the
3205 // supported boolean for this breakpoint type, and if it is thought to be supported then we
3206 // will try to set this breakpoint with a hardware breakpoint.
3207 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3208 {
3209 // Try to send off a hardware breakpoint packet ($Z1)
3210 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003211 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003212 // The breakpoint was placed successfully
3213 bp_site->SetEnabled(true);
3214 bp_site->SetType(BreakpointSite::eHardware);
3215 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003216 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003217
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003218 // Check if the error was something other then an unsupported breakpoint type
3219 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3220 {
3221 // Unable to set this hardware breakpoint
3222 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
3223 return error;
3224 }
3225
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003226 // We will reach here when the stub gives an unsupported response to a hardware breakpoint
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003227 if (log)
3228 log->Printf("Hardware breakpoints are unsupported");
3229
3230 // Finally we will falling through to a #trap style breakpoint
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003231 }
3232
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003233 // Don't fall through when hardware breakpoints were specifically requested
3234 if (bp_site->HardwareRequired())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003235 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003236 error.SetErrorString("hardware breakpoints are not supported");
3237 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003238 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003239
3240 // As a last resort we want to place a manual breakpoint. An instruction
3241 // is placed into the process memory using memory write packets.
3242 return EnableSoftwareBreakpoint(bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003243}
3244
3245Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003246ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003247{
3248 Error error;
3249 assert (bp_site != NULL);
3250 addr_t addr = bp_site->GetLoadAddress();
3251 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00003252 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003253 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003254 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003255
3256 if (bp_site->IsEnabled())
3257 {
3258 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
3259
Greg Clayton8b82f082011-04-12 05:54:46 +00003260 BreakpointSite::Type bp_type = bp_site->GetType();
3261 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003262 {
Greg Clayton8b82f082011-04-12 05:54:46 +00003263 case BreakpointSite::eSoftware:
3264 error = DisableSoftwareBreakpoint (bp_site);
3265 break;
3266
3267 case BreakpointSite::eHardware:
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003268 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003269 error.SetErrorToGenericError();
3270 break;
3271
3272 case BreakpointSite::eExternal:
Jim Inghama04ef752014-03-07 11:18:02 +00003273 {
3274 GDBStoppointType stoppoint_type;
3275 if (bp_site->IsHardware())
3276 stoppoint_type = eBreakpointHardware;
3277 else
3278 stoppoint_type = eBreakpointSoftware;
3279
3280 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003281 error.SetErrorToGenericError();
Jim Inghama04ef752014-03-07 11:18:02 +00003282 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003283 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003284 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003285 if (error.Success())
3286 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003287 }
3288 else
3289 {
3290 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003291 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 +00003292 return error;
3293 }
3294
3295 if (error.Success())
3296 error.SetErrorToGenericError();
3297 return error;
3298}
3299
Johnny Chen11309a32011-09-06 22:38:36 +00003300// Pre-requisite: wp != NULL.
3301static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00003302GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00003303{
3304 assert(wp);
3305 bool watch_read = wp->WatchpointRead();
3306 bool watch_write = wp->WatchpointWrite();
3307
3308 // watch_read and watch_write cannot both be false.
3309 assert(watch_read || watch_write);
3310 if (watch_read && watch_write)
3311 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00003312 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00003313 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00003314 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00003315 return eWatchpointWrite;
3316}
3317
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003318Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003319ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003320{
3321 Error error;
3322 if (wp)
3323 {
3324 user_id_t watchID = wp->GetID();
3325 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00003326 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003327 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003328 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003329 if (wp->IsEnabled())
3330 {
3331 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003332 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 +00003333 return error;
3334 }
Johnny Chen11309a32011-09-06 22:38:36 +00003335
3336 GDBStoppointType type = GetGDBStoppointType(wp);
3337 // Pass down an appropriate z/Z packet...
3338 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003339 {
Johnny Chen11309a32011-09-06 22:38:36 +00003340 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
3341 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003342 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003343 return error;
3344 }
3345 else
3346 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003347 }
Johnny Chen11309a32011-09-06 22:38:36 +00003348 else
3349 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003350 }
3351 else
3352 {
Johnny Chen01a67862011-10-14 00:42:25 +00003353 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003354 }
3355 if (error.Success())
3356 error.SetErrorToGenericError();
3357 return error;
3358}
3359
3360Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003361ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003362{
3363 Error error;
3364 if (wp)
3365 {
3366 user_id_t watchID = wp->GetID();
3367
Greg Clayton5160ce52013-03-27 23:08:40 +00003368 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003369
3370 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00003371
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003372 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003373 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003374
Johnny Chen11309a32011-09-06 22:38:36 +00003375 if (!wp->IsEnabled())
3376 {
3377 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003378 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 +00003379 // See also 'class WatchpointSentry' within StopInfo.cpp.
3380 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
3381 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00003382 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003383 return error;
3384 }
3385
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003386 if (wp->IsHardware())
3387 {
Johnny Chen11309a32011-09-06 22:38:36 +00003388 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003389 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00003390 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
3391 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003392 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003393 return error;
3394 }
3395 else
3396 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003397 }
3398 // TODO: clear software watchpoints if we implement them
3399 }
3400 else
3401 {
Johnny Chen01a67862011-10-14 00:42:25 +00003402 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003403 }
3404 if (error.Success())
3405 error.SetErrorToGenericError();
3406 return error;
3407}
3408
3409void
3410ProcessGDBRemote::Clear()
3411{
3412 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00003413 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003414 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003415}
3416
3417Error
3418ProcessGDBRemote::DoSignal (int signo)
3419{
3420 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00003421 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003422 if (log)
3423 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
3424
3425 if (!m_gdb_comm.SendAsyncSignal (signo))
3426 error.SetErrorStringWithFormat("failed to send signal %i", signo);
3427 return error;
3428}
3429
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003430Error
Greg Clayton91a9b2472013-12-04 19:19:12 +00003431ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003432{
3433 Error error;
3434 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
3435 {
3436 // If we locate debugserver, keep that located version around
3437 static FileSpec g_debugserver_file_spec;
3438
Han Ming Ong84647042012-02-25 01:07:38 +00003439 ProcessLaunchInfo debugserver_launch_info;
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00003440 // Make debugserver run in its own session so signals generated by
3441 // special terminal key sequences (^C) don't affect debugserver.
3442 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3443
Greg Clayton91a9b2472013-12-04 19:19:12 +00003444 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
3445 debugserver_launch_info.SetUserID(process_info.GetUserID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003446
Todd Fiala013434e2014-07-09 01:29:05 +00003447#if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__) || defined (__aarch64__))
Greg Claytonfda4fab2014-01-10 22:24:11 +00003448 // On iOS, still do a local connection using a random port
Greg Clayton16810922014-02-27 19:38:18 +00003449 const char *hostname = "127.0.0.1";
Greg Claytonfda4fab2014-01-10 22:24:11 +00003450 uint16_t port = get_random_port ();
3451#else
3452 // Set hostname being NULL to do the reverse connect where debugserver
3453 // will bind to port zero and it will communicate back to us the port
3454 // that we will connect to
3455 const char *hostname = NULL;
3456 uint16_t port = 0;
3457#endif
3458
3459 error = m_gdb_comm.StartDebugserverProcess (hostname,
3460 port,
Greg Clayton00fe87b2013-12-05 22:58:22 +00003461 debugserver_launch_info,
3462 port);
Greg Clayton91a9b2472013-12-04 19:19:12 +00003463
3464 if (error.Success ())
3465 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003466 else
Greg Clayton91a9b2472013-12-04 19:19:12 +00003467 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003468
3469 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3470 StartAsyncThread ();
Greg Clayton91a9b2472013-12-04 19:19:12 +00003471
3472 if (error.Fail())
3473 {
3474 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
3475
3476 if (log)
3477 log->Printf("failed to start debugserver process: %s", error.AsCString());
3478 return error;
3479 }
3480
Greg Clayton00fe87b2013-12-05 22:58:22 +00003481 if (m_gdb_comm.IsConnected())
3482 {
3483 // Finish the connection process by doing the handshake without connecting (send NULL URL)
3484 ConnectToDebugserver (NULL);
3485 }
3486 else
3487 {
Greg Claytonfda4fab2014-01-10 22:24:11 +00003488 StreamString connect_url;
3489 connect_url.Printf("connect://%s:%u", hostname, port);
3490 error = ConnectToDebugserver (connect_url.GetString().c_str());
Greg Clayton00fe87b2013-12-05 22:58:22 +00003491 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00003492
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003493 }
3494 return error;
3495}
3496
3497bool
3498ProcessGDBRemote::MonitorDebugserverProcess
3499(
3500 void *callback_baton,
3501 lldb::pid_t debugserver_pid,
Greg Claytone4e45922011-11-16 05:37:56 +00003502 bool exited, // True if the process did exit
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003503 int signo, // Zero for no signal
3504 int exit_status // Exit value of process if signal is zero
3505)
3506{
Greg Claytone4e45922011-11-16 05:37:56 +00003507 // The baton is a "ProcessGDBRemote *". Now this class might be gone
3508 // and might not exist anymore, so we need to carefully try to get the
3509 // target for this process first since we have a race condition when
3510 // we are done running between getting the notice that the inferior
3511 // process has died and the debugserver that was debugging this process.
3512 // In our test suite, we are also continually running process after
3513 // process, so we must be very careful to make sure:
3514 // 1 - process object hasn't been deleted already
3515 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003516
3517 // "debugserver_pid" argument passed in is the process ID for
3518 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00003519 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003520
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003521 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton6779606a2011-01-22 23:43:18 +00003522
Greg Claytone4e45922011-11-16 05:37:56 +00003523 // Get a shared pointer to the target that has a matching process pointer.
3524 // This target could be gone, or the target could already have a new process
3525 // object inside of it
3526 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
3527
Greg Clayton6779606a2011-01-22 23:43:18 +00003528 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003529 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 +00003530
Greg Claytone4e45922011-11-16 05:37:56 +00003531 if (target_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003532 {
Greg Claytone4e45922011-11-16 05:37:56 +00003533 // We found a process in a target that matches, but another thread
3534 // might be in the process of launching a new process that will
3535 // soon replace it, so get a shared pointer to the process so we
3536 // can keep it alive.
3537 ProcessSP process_sp (target_sp->GetProcessSP());
3538 // Now we have a shared pointer to the process that can't go away on us
3539 // so we now make sure it was the same as the one passed in, and also make
3540 // sure that our previous "process *" didn't get deleted and have a new
3541 // "process *" created in its place with the same pointer. To verify this
3542 // we make sure the process has our debugserver process ID. If we pass all
3543 // of these tests, then we are sure that this process is the one we were
3544 // looking for.
3545 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003546 {
Greg Claytone4e45922011-11-16 05:37:56 +00003547 // Sleep for a half a second to make sure our inferior process has
3548 // time to set its exit status before we set it incorrectly when
3549 // both the debugserver and the inferior process shut down.
3550 usleep (500000);
3551 // If our process hasn't yet exited, debugserver might have died.
3552 // If the process did exit, the we are reaping it.
3553 const StateType state = process->GetState();
3554
3555 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
3556 state != eStateInvalid &&
3557 state != eStateUnloaded &&
3558 state != eStateExited &&
3559 state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003560 {
Greg Claytone4e45922011-11-16 05:37:56 +00003561 char error_str[1024];
3562 if (signo)
3563 {
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00003564 const char *signal_cstr = process->GetUnixSignals()->GetSignalAsCString(signo);
Greg Claytone4e45922011-11-16 05:37:56 +00003565 if (signal_cstr)
3566 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3567 else
3568 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
3569 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003570 else
Greg Claytone4e45922011-11-16 05:37:56 +00003571 {
3572 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
3573 }
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003574
Greg Claytone4e45922011-11-16 05:37:56 +00003575 process->SetExitStatus (-1, error_str);
3576 }
3577 // Debugserver has exited we need to let our ProcessGDBRemote
3578 // know that it no longer has a debugserver instance
3579 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003580 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003581 }
3582 return true;
3583}
3584
3585void
3586ProcessGDBRemote::KillDebugserverProcess ()
3587{
Greg Claytonfbb76342013-11-20 21:07:01 +00003588 m_gdb_comm.Disconnect();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003589 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3590 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003591 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003592 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3593 }
3594}
3595
3596void
3597ProcessGDBRemote::Initialize()
3598{
Davide Italianoc8d69822015-04-03 04:24:32 +00003599 static std::once_flag g_once_flag;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003600
Davide Italianoc8d69822015-04-03 04:24:32 +00003601 std::call_once(g_once_flag, []()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003602 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003603 PluginManager::RegisterPlugin (GetPluginNameStatic(),
3604 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00003605 CreateInstance,
3606 DebuggerInitialize);
Davide Italianoc8d69822015-04-03 04:24:32 +00003607 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003608}
3609
Greg Clayton7f982402013-07-15 22:54:20 +00003610void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003611ProcessGDBRemote::DebuggerInitialize (Debugger &debugger)
Greg Clayton7f982402013-07-15 22:54:20 +00003612{
3613 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
3614 {
3615 const bool is_global_setting = true;
3616 PluginManager::CreateSettingForProcessPlugin (debugger,
3617 GetGlobalPluginProperties()->GetValueProperties(),
3618 ConstString ("Properties for the gdb-remote process plug-in."),
3619 is_global_setting);
3620 }
3621}
3622
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003623bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003624ProcessGDBRemote::StartAsyncThread ()
3625{
Greg Clayton5160ce52013-03-27 23:08:40 +00003626 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003627
3628 if (log)
3629 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003630
3631 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003632 if (!m_async_thread.IsJoinable())
Jim Ingham455fa5c2012-11-01 01:15:33 +00003633 {
3634 // Create a thread that watches our internal state and controls which
3635 // events make it to clients (into the DCProcess event queue).
Zachary Turner39de3112014-09-09 20:54:56 +00003636
3637 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003638 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003639 else if (log)
3640 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was already running.", __FUNCTION__);
Zachary Turner39de3112014-09-09 20:54:56 +00003641
Zachary Turneracee96a2014-09-23 18:32:09 +00003642 return m_async_thread.IsJoinable();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003643}
3644
3645void
3646ProcessGDBRemote::StopAsyncThread ()
3647{
Greg Clayton5160ce52013-03-27 23:08:40 +00003648 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003649
3650 if (log)
3651 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
3652
Jim Ingham455fa5c2012-11-01 01:15:33 +00003653 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003654 if (m_async_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003655 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00003656 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
3657
3658 // This will shut down the async thread.
3659 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3660
3661 // Stop the stdio thread
Zachary Turner39de3112014-09-09 20:54:56 +00003662 m_async_thread.Join(nullptr);
Pavel Labatha55a9532015-03-11 09:53:42 +00003663 m_async_thread.Reset();
Jim Ingham455fa5c2012-11-01 01:15:33 +00003664 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003665 else if (log)
3666 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003667}
3668
Ewan Crawford76df2882015-06-23 12:32:06 +00003669bool
3670ProcessGDBRemote::HandleNotifyPacket (StringExtractorGDBRemote &packet)
3671{
3672 // get the packet at a string
3673 const std::string &pkt = packet.GetStringRef();
3674 // skip %stop:
3675 StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
3676
3677 // pass as a thread stop info packet
3678 SetLastStopPacket(stop_info);
3679
3680 // check for more stop reasons
3681 HandleStopReplySequence();
3682
3683 // if the process is stopped then we need to fake a resume
3684 // so that we can stop properly with the new break. This
3685 // is possible due to SetPrivateState() broadcasting the
3686 // state change as a side effect.
3687 if (GetPrivateState() == lldb::StateType::eStateStopped)
3688 {
3689 SetPrivateState(lldb::StateType::eStateRunning);
3690 }
3691
3692 // since we have some stopped packets we can halt the process
3693 SetPrivateState(lldb::StateType::eStateStopped);
3694
3695 return true;
3696}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003697
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003698thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003699ProcessGDBRemote::AsyncThread (void *arg)
3700{
3701 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
3702
Greg Clayton5160ce52013-03-27 23:08:40 +00003703 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003704 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003705 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003706
3707 Listener listener ("ProcessGDBRemote::AsyncThread");
3708 EventSP event_sp;
3709 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
3710 eBroadcastBitAsyncThreadShouldExit;
3711
3712 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
3713 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003714 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit |
3715 GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify);
3716
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003717 bool done = false;
3718 while (!done)
3719 {
3720 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003721 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003722 if (listener.WaitForEvent (NULL, event_sp))
3723 {
3724 const uint32_t event_type = event_sp->GetType();
Greg Clayton71337622011-02-24 22:24:29 +00003725 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003726 {
Greg Clayton71337622011-02-24 22:24:29 +00003727 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003728 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 +00003729
Greg Clayton71337622011-02-24 22:24:29 +00003730 switch (event_type)
3731 {
3732 case eBroadcastBitAsyncContinue:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003733 {
Greg Clayton71337622011-02-24 22:24:29 +00003734 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003735
Greg Clayton71337622011-02-24 22:24:29 +00003736 if (continue_packet)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003737 {
Greg Clayton71337622011-02-24 22:24:29 +00003738 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
3739 const size_t continue_cstr_len = continue_packet->GetByteSize ();
3740 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003741 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003742
Greg Clayton71337622011-02-24 22:24:29 +00003743 if (::strstr (continue_cstr, "vAttach") == NULL)
3744 process->SetPrivateState(eStateRunning);
3745 StringExtractorGDBRemote response;
Ewan Crawford76df2882015-06-23 12:32:06 +00003746
3747 // If in Non-Stop-Mode
3748 if (process->GetTarget().GetNonStopModeEnabled())
Greg Clayton71337622011-02-24 22:24:29 +00003749 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003750 // send the vCont packet
3751 if (!process->GetGDBRemote().SendvContPacket(process, continue_cstr, continue_cstr_len, response))
Jason Molendaa3329782014-03-29 18:54:20 +00003752 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003753 // Something went wrong
3754 done = true;
3755 break;
3756 }
3757 }
3758 // If in All-Stop-Mode
3759 else
3760 {
3761 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
3762
3763 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
3764 // The thread ID list might be contained within the "response", or the stop reply packet that
3765 // caused the stop. So clear it now before we give the stop reply packet to the process
3766 // using the process->SetLastStopPacket()...
3767 process->ClearThreadIDList ();
3768
3769 switch (stop_state)
3770 {
3771 case eStateStopped:
3772 case eStateCrashed:
3773 case eStateSuspended:
3774 process->SetLastStopPacket (response);
3775 process->SetPrivateState (stop_state);
3776 break;
3777
3778 case eStateExited:
3779 {
3780 process->SetLastStopPacket (response);
3781 process->ClearThreadIDList();
3782 response.SetFilePos(1);
3783
3784 int exit_status = response.GetHexU8();
3785 const char *desc_cstr = NULL;
3786 StringExtractor extractor;
3787 std::string desc_string;
3788 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';')
Jason Molendaa3329782014-03-29 18:54:20 +00003789 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003790 std::string desc_token;
3791 while (response.GetNameColonValue (desc_token, desc_string))
Jason Molendaa3329782014-03-29 18:54:20 +00003792 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003793 if (desc_token == "description")
3794 {
3795 extractor.GetStringRef().swap(desc_string);
3796 extractor.SetFilePos(0);
3797 extractor.GetHexByteString (desc_string);
3798 desc_cstr = desc_string.c_str();
3799 }
Jason Molendaa3329782014-03-29 18:54:20 +00003800 }
3801 }
Ewan Crawford76df2882015-06-23 12:32:06 +00003802 process->SetExitStatus(exit_status, desc_cstr);
3803 done = true;
3804 break;
Jason Molendaa3329782014-03-29 18:54:20 +00003805 }
Ewan Crawford76df2882015-06-23 12:32:06 +00003806 case eStateInvalid:
3807 process->SetExitStatus(-1, "lost connection");
3808 break;
Greg Clayton71337622011-02-24 22:24:29 +00003809
Ewan Crawford76df2882015-06-23 12:32:06 +00003810 default:
3811 process->SetPrivateState (stop_state);
3812 break;
3813 } // switch(stop_state)
3814 } // else // if in All-stop-mode
3815 } // if (continue_packet)
3816 } // case eBroadcastBitAysncContinue
Greg Clayton71337622011-02-24 22:24:29 +00003817 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003818
Greg Clayton71337622011-02-24 22:24:29 +00003819 case eBroadcastBitAsyncThreadShouldExit:
3820 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003821 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Clayton71337622011-02-24 22:24:29 +00003822 done = true;
3823 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003824
Greg Clayton71337622011-02-24 22:24:29 +00003825 default:
3826 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003827 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 +00003828 done = true;
3829 break;
3830 }
3831 }
3832 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
3833 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003834 switch (event_type)
Greg Clayton71337622011-02-24 22:24:29 +00003835 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003836 case Communication::eBroadcastBitReadThreadDidExit:
3837 process->SetExitStatus (-1, "lost connection");
3838 done = true;
3839 break;
3840
3841 case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify:
3842 {
3843 lldb_private::Event *event = event_sp.get();
3844 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event);
3845 StringExtractorGDBRemote notify((const char*)continue_packet->GetBytes());
3846 // Hand this over to the process to handle
3847 process->HandleNotifyPacket(notify);
3848 break;
3849 }
3850
3851 default:
3852 if (log)
3853 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
3854 done = true;
3855 break;
Greg Clayton71337622011-02-24 22:24:29 +00003856 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003857 }
3858 }
3859 else
3860 {
3861 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003862 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 +00003863 done = true;
3864 }
3865 }
3866 }
3867
3868 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003869 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003870
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003871 return NULL;
3872}
3873
Greg Claytone996fd32011-03-08 22:40:15 +00003874//uint32_t
3875//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3876//{
3877// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
3878// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
3879// if (m_local_debugserver)
3880// {
3881// return Host::ListProcessesMatchingName (name, matches, pids);
3882// }
3883// else
3884// {
3885// // FIXME: Implement talking to the remote debugserver.
3886// return 0;
3887// }
3888//
3889//}
3890//
Jim Ingham1c823b42011-01-22 01:33:44 +00003891bool
3892ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003893 StoppointCallbackContext *context,
Jim Ingham1c823b42011-01-22 01:33:44 +00003894 lldb::user_id_t break_id,
3895 lldb::user_id_t break_loc_id)
3896{
3897 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3898 // run so I can stop it if that's what I want to do.
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003899 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00003900 if (log)
3901 log->Printf("Hit New Thread Notification breakpoint.");
3902 return false;
3903}
3904
3905
3906bool
3907ProcessGDBRemote::StartNoticingNewThreads()
3908{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003909 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00003910 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003911 {
Greg Clayton4116e932012-05-15 02:33:01 +00003912 if (log && log->GetVerbose())
3913 log->Printf("Enabled noticing new thread breakpoint.");
3914 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003915 }
Greg Clayton4116e932012-05-15 02:33:01 +00003916 else
Jim Ingham1c823b42011-01-22 01:33:44 +00003917 {
Greg Clayton4116e932012-05-15 02:33:01 +00003918 PlatformSP platform_sp (m_target.GetPlatform());
3919 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003920 {
Greg Clayton4116e932012-05-15 02:33:01 +00003921 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3922 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003923 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00003924 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00003925 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3926 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003927 }
3928 else
3929 {
3930 if (log)
3931 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00003932 }
3933 }
3934 }
Greg Clayton4116e932012-05-15 02:33:01 +00003935 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00003936}
3937
3938bool
3939ProcessGDBRemote::StopNoticingNewThreads()
3940{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003941 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00003942 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00003943 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00003944
3945 if (m_thread_create_bp_sp)
3946 m_thread_create_bp_sp->SetEnabled(false);
3947
Jim Ingham1c823b42011-01-22 01:33:44 +00003948 return true;
3949}
3950
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003951DynamicLoader *
Jason Molenda5e8534e2012-10-03 01:29:34 +00003952ProcessGDBRemote::GetDynamicLoader ()
3953{
3954 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00003955 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00003956 return m_dyld_ap.get();
3957}
Jim Ingham1c823b42011-01-22 01:33:44 +00003958
Jason Molendaa3329782014-03-29 18:54:20 +00003959Error
3960ProcessGDBRemote::SendEventData(const char *data)
3961{
3962 int return_value;
3963 bool was_supported;
3964
3965 Error error;
3966
3967 return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported);
3968 if (return_value != 0)
3969 {
3970 if (!was_supported)
3971 error.SetErrorString("Sending events is not supported for this process.");
3972 else
3973 error.SetErrorStringWithFormat("Error sending event data: %d.", return_value);
3974 }
3975 return error;
3976}
3977
Steve Pucci03904ac2014-03-04 23:18:46 +00003978const DataBufferSP
3979ProcessGDBRemote::GetAuxvData()
3980{
3981 DataBufferSP buf;
3982 if (m_gdb_comm.GetQXferAuxvReadSupported())
3983 {
3984 std::string response_string;
3985 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success)
3986 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length()));
3987 }
3988 return buf;
3989}
3990
Jason Molenda705b1802014-06-13 02:37:02 +00003991StructuredData::ObjectSP
3992ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid)
3993{
3994 StructuredData::ObjectSP object_sp;
3995
3996 if (m_gdb_comm.GetThreadExtendedInfoSupported())
3997 {
3998 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3999 SystemRuntime *runtime = GetSystemRuntime();
4000 if (runtime)
4001 {
4002 runtime->AddThreadExtendedInfoPacketHints (args_dict);
4003 }
4004 args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid);
4005
4006 StreamString packet;
4007 packet << "jThreadExtendedInfo:";
4008 args_dict->Dump (packet);
4009
4010 // FIXME the final character of a JSON dictionary, '}', is the escape
4011 // character in gdb-remote binary mode. lldb currently doesn't escape
4012 // these characters in its packet output -- so we add the quoted version
4013 // of the } character here manually in case we talk to a debugserver which
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004014 // un-escapes the characters at packet read time.
Jason Molenda705b1802014-06-13 02:37:02 +00004015 packet << (char) (0x7d ^ 0x20);
4016
4017 StringExtractorGDBRemote response;
4018 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4019 {
4020 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4021 if (response_type == StringExtractorGDBRemote::eResponse)
4022 {
4023 if (!response.Empty())
4024 {
Jason Molenda20ee21b2015-07-10 23:15:22 +00004025 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4026 }
4027 }
4028 }
4029 }
4030 return object_sp;
4031}
4032
4033StructuredData::ObjectSP
4034ProcessGDBRemote::GetLoadedDynamicLibrariesInfos (lldb::addr_t image_list_address, lldb::addr_t image_count)
4035{
4036 StructuredData::ObjectSP object_sp;
4037
4038 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported())
4039 {
4040 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4041 args_dict->GetAsDictionary()->AddIntegerItem ("image_list_address", image_list_address);
4042 args_dict->GetAsDictionary()->AddIntegerItem ("image_count", image_count);
4043
4044 StreamString packet;
4045 packet << "jGetLoadedDynamicLibrariesInfos:";
4046 args_dict->Dump (packet);
4047
4048 // FIXME the final character of a JSON dictionary, '}', is the escape
4049 // character in gdb-remote binary mode. lldb currently doesn't escape
4050 // these characters in its packet output -- so we add the quoted version
4051 // of the } character here manually in case we talk to a debugserver which
4052 // un-escapes the characters at packet read time.
4053 packet << (char) (0x7d ^ 0x20);
4054
4055 StringExtractorGDBRemote response;
4056 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4057 {
4058 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4059 if (response_type == StringExtractorGDBRemote::eResponse)
4060 {
4061 if (!response.Empty())
4062 {
Jason Molenda705b1802014-06-13 02:37:02 +00004063 // The packet has already had the 0x7d xor quoting stripped out at the
4064 // GDBRemoteCommunication packet receive level.
4065 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4066 }
4067 }
4068 }
4069 }
4070 return object_sp;
4071}
4072
Jason Molenda20ee21b2015-07-10 23:15:22 +00004073
Jason Molenda6076bf42014-05-06 04:34:52 +00004074// Establish the largest memory read/write payloads we should use.
4075// If the remote stub has a max packet size, stay under that size.
4076//
4077// If the remote stub's max packet size is crazy large, use a
4078// reasonable largeish default.
4079//
4080// If the remote stub doesn't advertise a max packet size, use a
4081// conservative default.
4082
4083void
4084ProcessGDBRemote::GetMaxMemorySize()
4085{
4086 const uint64_t reasonable_largeish_default = 128 * 1024;
4087 const uint64_t conservative_default = 512;
4088
4089 if (m_max_memory_size == 0)
4090 {
4091 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4092 if (stub_max_size != UINT64_MAX && stub_max_size != 0)
4093 {
4094 // Save the stub's claimed maximum packet size
4095 m_remote_stub_max_memory_size = stub_max_size;
4096
4097 // Even if the stub says it can support ginormous packets,
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004098 // don't exceed our reasonable largeish default packet size.
Jason Molenda6076bf42014-05-06 04:34:52 +00004099 if (stub_max_size > reasonable_largeish_default)
4100 {
4101 stub_max_size = reasonable_largeish_default;
4102 }
4103
4104 m_max_memory_size = stub_max_size;
4105 }
4106 else
4107 {
4108 m_max_memory_size = conservative_default;
4109 }
4110 }
4111}
4112
4113void
4114ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max)
4115{
4116 if (user_specified_max != 0)
4117 {
4118 GetMaxMemorySize ();
4119
4120 if (m_remote_stub_max_memory_size != 0)
4121 {
4122 if (m_remote_stub_max_memory_size < user_specified_max)
4123 {
4124 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a packet size too big, go as big
4125 // as the remote stub says we can go.
4126 }
4127 else
4128 {
4129 m_max_memory_size = user_specified_max; // user's packet size is good
4130 }
4131 }
4132 else
4133 {
4134 m_max_memory_size = user_specified_max; // user's packet size is probably fine
4135 }
4136 }
4137}
4138
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004139bool
4140ProcessGDBRemote::GetModuleSpec(const FileSpec& module_file_spec,
4141 const ArchSpec& arch,
4142 ModuleSpec &module_spec)
4143{
4144 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PLATFORM);
4145
4146 if (!m_gdb_comm.GetModuleInfo (module_file_spec, arch, module_spec))
4147 {
4148 if (log)
4149 log->Printf ("ProcessGDBRemote::%s - failed to get module info for %s:%s",
4150 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4151 arch.GetTriple ().getTriple ().c_str ());
4152 return false;
4153 }
4154
4155 if (log)
4156 {
4157 StreamString stream;
4158 module_spec.Dump (stream);
4159 log->Printf ("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4160 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4161 arch.GetTriple ().getTriple ().c_str (), stream.GetString ().c_str ());
4162 }
4163
4164 return true;
4165}
4166
Colin Rileyc3c95b22015-04-16 15:51:33 +00004167namespace {
4168
4169typedef std::vector<std::string> stringVec;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004170
4171typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004172struct RegisterSetInfo
4173{
4174 ConstString name;
4175};
Colin Rileyc3c95b22015-04-16 15:51:33 +00004176
Greg Claytond04f0ed2015-05-26 18:00:51 +00004177typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4178
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004179struct GdbServerTargetInfo
4180{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004181 std::string arch;
4182 std::string osabi;
4183 stringVec includes;
4184 RegisterSetMap reg_set_map;
4185 XMLNode feature_node;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004186};
Greg Claytond04f0ed2015-05-26 18:00:51 +00004187
Colin Rileyc3c95b22015-04-16 15:51:33 +00004188bool
Greg Claytond04f0ed2015-05-26 18:00:51 +00004189ParseRegisters (XMLNode feature_node, GdbServerTargetInfo &target_info, GDBRemoteDynamicRegisterInfo &dyn_reg_info)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004190{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004191 if (!feature_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004192 return false;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004193
4194 uint32_t prev_reg_num = 0;
4195 uint32_t reg_offset = 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004196
Greg Claytond04f0ed2015-05-26 18:00:51 +00004197 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 +00004198 std::string gdb_group;
4199 std::string gdb_type;
4200 ConstString reg_name;
4201 ConstString alt_name;
4202 ConstString set_name;
4203 std::vector<uint32_t> value_regs;
4204 std::vector<uint32_t> invalidate_regs;
4205 bool encoding_set = false;
4206 bool format_set = false;
4207 RegisterInfo reg_info = { NULL, // Name
4208 NULL, // Alt name
4209 0, // byte size
4210 reg_offset, // offset
4211 eEncodingUint, // encoding
4212 eFormatHex, // formate
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004213 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004214 LLDB_INVALID_REGNUM, // GCC reg num
4215 LLDB_INVALID_REGNUM, // DWARF reg num
4216 LLDB_INVALID_REGNUM, // generic reg num
4217 prev_reg_num, // GDB reg num
4218 prev_reg_num // native register number
4219 },
4220 NULL,
4221 NULL
4222 };
4223
Ewan Crawford682e8422015-06-26 09:38:27 +00004224 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 +00004225 if (name == "name")
4226 {
4227 reg_name.SetString(value);
4228 }
4229 else if (name == "bitsize")
4230 {
4231 reg_info.byte_size = StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
4232 }
4233 else if (name == "type")
4234 {
4235 gdb_type = value.str();
4236 }
4237 else if (name == "group")
4238 {
4239 gdb_group = value.str();
4240 }
4241 else if (name == "regnum")
4242 {
4243 const uint32_t regnum = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4244 if (regnum != LLDB_INVALID_REGNUM)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004245 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004246 reg_info.kinds[eRegisterKindGDB] = regnum;
4247 reg_info.kinds[eRegisterKindLLDB] = regnum;
4248 prev_reg_num = regnum;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004249 }
4250 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004251 else if (name == "offset")
4252 {
4253 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4254 }
4255 else if (name == "altname")
4256 {
4257 alt_name.SetString(value);
4258 }
4259 else if (name == "encoding")
4260 {
4261 encoding_set = true;
4262 reg_info.encoding = Args::StringToEncoding (value.data(), eEncodingUint);
4263 }
4264 else if (name == "format")
4265 {
4266 format_set = true;
4267 Format format = eFormatInvalid;
4268 if (Args::StringToFormat (value.data(), format, NULL).Success())
4269 reg_info.format = format;
4270 else if (value == "vector-sint8")
4271 reg_info.format = eFormatVectorOfSInt8;
4272 else if (value == "vector-uint8")
4273 reg_info.format = eFormatVectorOfUInt8;
4274 else if (value == "vector-sint16")
4275 reg_info.format = eFormatVectorOfSInt16;
4276 else if (value == "vector-uint16")
4277 reg_info.format = eFormatVectorOfUInt16;
4278 else if (value == "vector-sint32")
4279 reg_info.format = eFormatVectorOfSInt32;
4280 else if (value == "vector-uint32")
4281 reg_info.format = eFormatVectorOfUInt32;
4282 else if (value == "vector-float32")
4283 reg_info.format = eFormatVectorOfFloat32;
4284 else if (value == "vector-uint128")
4285 reg_info.format = eFormatVectorOfUInt128;
4286 }
4287 else if (name == "group_id")
4288 {
4289 const uint32_t set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4290 RegisterSetMap::const_iterator pos = target_info.reg_set_map.find(set_id);
4291 if (pos != target_info.reg_set_map.end())
4292 set_name = pos->second.name;
4293 }
4294 else if (name == "gcc_regnum")
4295 {
4296 reg_info.kinds[eRegisterKindGCC] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4297 }
4298 else if (name == "dwarf_regnum")
4299 {
4300 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4301 }
4302 else if (name == "generic")
4303 {
4304 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister(value.data());
4305 }
4306 else if (name == "value_regnums")
4307 {
4308 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
4309 }
4310 else if (name == "invalidate_regnums")
4311 {
4312 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
4313 }
4314 else
4315 {
4316 printf("unhandled attribute %s = %s\n", name.data(), value.data());
4317 }
4318 return true; // Keep iterating through all attributes
4319 });
4320
4321 if (!gdb_type.empty() && !(encoding_set || format_set))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004322 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004323 if (gdb_type.find("int") == 0)
4324 {
4325 reg_info.format = eFormatHex;
4326 reg_info.encoding = eEncodingUint;
4327 }
4328 else if (gdb_type == "data_ptr" || gdb_type == "code_ptr")
4329 {
4330 reg_info.format = eFormatAddressInfo;
4331 reg_info.encoding = eEncodingUint;
4332 }
4333 else if (gdb_type == "i387_ext" || gdb_type == "float")
4334 {
4335 reg_info.format = eFormatFloat;
4336 reg_info.encoding = eEncodingIEEE754;
4337 }
Colin Rileyc3c95b22015-04-16 15:51:33 +00004338 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004339
4340 // Only update the register set name if we didn't get a "reg_set" attribute.
4341 // "set_name" will be empty if we didn't have a "reg_set" attribute.
4342 if (!set_name && !gdb_group.empty())
4343 set_name.SetCString(gdb_group.c_str());
4344
4345 reg_info.byte_offset = reg_offset;
4346 assert (reg_info.byte_size != 0);
4347 reg_offset += reg_info.byte_size;
4348 if (!value_regs.empty())
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004349 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004350 value_regs.push_back(LLDB_INVALID_REGNUM);
4351 reg_info.value_regs = value_regs.data();
Colin Rileyc3c95b22015-04-16 15:51:33 +00004352 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004353 if (!invalidate_regs.empty())
4354 {
4355 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
4356 reg_info.invalidate_regs = invalidate_regs.data();
4357 }
4358
Ewan Crawford682e8422015-06-26 09:38:27 +00004359 ++prev_reg_num;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004360 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
4361
4362 return true; // Keep iterating through all "reg" elements
4363 });
Colin Rileyc3c95b22015-04-16 15:51:33 +00004364 return true;
4365}
Greg Claytond04f0ed2015-05-26 18:00:51 +00004366
Colin Rileyc3c95b22015-04-16 15:51:33 +00004367} // namespace {}
4368
Colin Rileyc3c95b22015-04-16 15:51:33 +00004369
4370// query the target of gdb-remote for extended target information
4371// return: 'true' on success
4372// 'false' on failure
4373bool
Aidan Doddsc0c83852015-05-08 09:36:31 +00004374ProcessGDBRemote::GetGDBServerRegisterInfo ()
Colin Rileyc3c95b22015-04-16 15:51:33 +00004375{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004376 // Make sure LLDB has an XML parser it can use first
4377 if (!XMLDocument::XMLEnabled())
4378 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004379
4380 // redirect libxml2's error handler since the default prints to stdout
Colin Rileyc3c95b22015-04-16 15:51:33 +00004381
4382 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004383
4384 // check that we have extended feature read support
4385 if ( !comm.GetQXferFeaturesReadSupported( ) )
4386 return false;
4387
4388 // request the target xml file
4389 std::string raw;
4390 lldb_private::Error lldberr;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004391 if (!comm.ReadExtFeature(ConstString("features"),
4392 ConstString("target.xml"),
4393 raw,
4394 lldberr))
4395 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00004396 return false;
4397 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004398
Colin Rileyc3c95b22015-04-16 15:51:33 +00004399
Greg Claytond04f0ed2015-05-26 18:00:51 +00004400 XMLDocument xml_document;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004401
Greg Claytond04f0ed2015-05-26 18:00:51 +00004402 if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml"))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004403 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004404 GdbServerTargetInfo target_info;
4405
4406 XMLNode target_node = xml_document.GetRootElement("target");
4407 if (target_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004408 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004409 XMLNode feature_node;
4410 target_node.ForEachChildElement([&target_info, this, &feature_node](const XMLNode &node) -> bool
4411 {
4412 llvm::StringRef name = node.GetName();
4413 if (name == "architecture")
4414 {
4415 node.GetElementText(target_info.arch);
4416 }
4417 else if (name == "osabi")
4418 {
4419 node.GetElementText(target_info.osabi);
4420 }
Ewan Crawford682e8422015-06-26 09:38:27 +00004421 else if (name == "xi:include" || name == "include")
Greg Claytond04f0ed2015-05-26 18:00:51 +00004422 {
4423 llvm::StringRef href = node.GetAttributeValue("href");
4424 if (!href.empty())
4425 target_info.includes.push_back(href.str());
4426 }
4427 else if (name == "feature")
4428 {
4429 feature_node = node;
4430 }
4431 else if (name == "groups")
4432 {
4433 node.ForEachChildElementWithName("group", [&target_info](const XMLNode &node) -> bool {
4434 uint32_t set_id = UINT32_MAX;
4435 RegisterSetInfo set_info;
4436
4437 node.ForEachAttribute([&set_id, &set_info](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
4438 if (name == "id")
4439 set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4440 if (name == "name")
4441 set_info.name = ConstString(value);
4442 return true; // Keep iterating through all attributes
4443 });
4444
4445 if (set_id != UINT32_MAX)
4446 target_info.reg_set_map[set_id] = set_info;
4447 return true; // Keep iterating through all "group" elements
4448 });
4449 }
4450 return true; // Keep iterating through all children of the target_node
4451 });
4452
4453 if (feature_node)
4454 {
4455 ParseRegisters(feature_node, target_info, this->m_register_info);
4456 }
4457
4458 for (const auto &include : target_info.includes)
4459 {
4460 // request register file
4461 std::string xml_data;
4462 if (!comm.ReadExtFeature(ConstString("features"),
4463 ConstString(include),
4464 xml_data,
4465 lldberr))
4466 continue;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004467
Greg Claytond04f0ed2015-05-26 18:00:51 +00004468 XMLDocument include_xml_document;
4469 include_xml_document.ParseMemory(xml_data.data(), xml_data.size(), include.c_str());
4470 XMLNode include_feature_node = include_xml_document.GetRootElement("feature");
4471 if (include_feature_node)
4472 {
4473 ParseRegisters(include_feature_node, target_info, this->m_register_info);
4474 }
4475 }
4476 this->m_register_info.Finalize(GetTarget().GetArchitecture());
Colin Rileyc3c95b22015-04-16 15:51:33 +00004477 }
4478 }
4479
Greg Claytond04f0ed2015-05-26 18:00:51 +00004480 return m_register_info.GetNumRegisters() > 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004481}
4482
Aidan Doddsc0c83852015-05-08 09:36:31 +00004483Error
4484ProcessGDBRemote::GetLoadedModuleList (GDBLoadedModuleInfoList & list)
4485{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004486 // Make sure LLDB has an XML parser it can use first
4487 if (!XMLDocument::XMLEnabled())
4488 return Error (0, ErrorType::eErrorTypeGeneric);
4489
Aidan Doddsc0c83852015-05-08 09:36:31 +00004490 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS);
4491 if (log)
4492 log->Printf ("ProcessGDBRemote::%s", __FUNCTION__);
4493
Aidan Doddsc0c83852015-05-08 09:36:31 +00004494 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004495
4496 // check that we have extended feature read support
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004497 if (comm.GetQXferLibrariesSVR4ReadSupported ()) {
4498 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004499
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004500 // request the loaded library list
4501 std::string raw;
4502 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004503
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004504 if (!comm.ReadExtFeature (ConstString ("libraries-svr4"), ConstString (""), raw, lldberr))
4505 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004506
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004507 // parse the xml file in memory
4508 if (log)
4509 log->Printf ("parsing: %s", raw.c_str());
4510 XMLDocument doc;
4511
4512 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4513 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004514
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004515 XMLNode root_element = doc.GetRootElement("library-list-svr4");
4516 if (!root_element)
4517 return Error();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004518
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004519 // main link map structure
4520 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4521 if (!main_lm.empty())
4522 {
4523 list.m_link_map = StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
4524 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004525
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004526 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
Aidan Doddsc0c83852015-05-08 09:36:31 +00004527
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004528 GDBLoadedModuleInfoList::LoadedModuleInfo module;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004529
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004530 library.ForEachAttribute([log, &module](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004531
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004532 if (name == "name")
4533 module.set_name (value.str());
4534 else if (name == "lm")
4535 {
4536 // the address of the link_map struct.
4537 module.set_link_map(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4538 }
4539 else if (name == "l_addr")
4540 {
4541 // the displacement as read from the field 'l_addr' of the link_map struct.
4542 module.set_base(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4543
4544 }
4545 else if (name == "l_ld")
4546 {
4547 // the memory address of the libraries PT_DYAMIC section.
4548 module.set_dynamic(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4549 }
4550
4551 return true; // Keep iterating over all properties of "library"
4552 });
4553
4554 if (log)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004555 {
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004556 std::string name;
4557 lldb::addr_t lm=0, base=0, ld=0;
4558
4559 module.get_name (name);
4560 module.get_link_map (lm);
4561 module.get_base (base);
4562 module.get_dynamic (ld);
4563
4564 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 +00004565 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004566
4567 list.add (module);
4568 return true; // Keep iterating over all "library" elements in the root node
Greg Claytond04f0ed2015-05-26 18:00:51 +00004569 });
Aidan Doddsc0c83852015-05-08 09:36:31 +00004570
4571 if (log)
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004572 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4573 } else if (comm.GetQXferLibrariesReadSupported ()) {
4574 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004575
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004576 // request the loaded library list
4577 std::string raw;
4578 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004579
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004580 if (!comm.ReadExtFeature (ConstString ("libraries"), ConstString (""), raw, lldberr))
4581 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004582
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004583 if (log)
4584 log->Printf ("parsing: %s", raw.c_str());
4585 XMLDocument doc;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004586
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004587 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4588 return Error (0, ErrorType::eErrorTypeGeneric);
4589
4590 XMLNode root_element = doc.GetRootElement("library-list");
4591 if (!root_element)
4592 return Error();
4593
4594 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
4595 GDBLoadedModuleInfoList::LoadedModuleInfo module;
4596
4597 llvm::StringRef name = library.GetAttributeValue("name");
4598 module.set_name(name.str());
4599
4600 // The base address of a given library will be the address of its
4601 // first section. Most remotes send only one section for Windows
4602 // targets for example.
4603 const XMLNode &section = library.FindFirstChildElementWithName("section");
4604 llvm::StringRef address = section.GetAttributeValue("address");
4605 module.set_base(StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0));
4606
4607 if (log)
4608 {
4609 std::string name;
4610 lldb::addr_t base = 0;
4611 module.get_name (name);
4612 module.get_base (base);
4613
4614 log->Printf ("found (base:0x%" PRIx64 ", name:'%s')", base, name.c_str());
4615 }
4616
4617 list.add (module);
4618 return true; // Keep iterating over all "library" elements in the root node
4619 });
4620
4621 if (log)
4622 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4623 } else {
4624 return Error (0, ErrorType::eErrorTypeGeneric);
4625 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004626
4627 return Error();
4628}
4629
Aidan Doddsc0c83852015-05-08 09:36:31 +00004630lldb::ModuleSP
4631ProcessGDBRemote::LoadModuleAtAddress (const FileSpec &file, lldb::addr_t base_addr)
4632{
4633 Target &target = m_process->GetTarget();
4634 ModuleList &modules = target.GetImages();
4635 ModuleSP module_sp;
4636
4637 bool changed = false;
4638
4639 ModuleSpec module_spec (file, target.GetArchitecture());
4640 if ((module_sp = modules.FindFirstModule (module_spec)))
4641 {
4642 module_sp->SetLoadAddress (target, base_addr, true, changed);
4643 }
4644 else if ((module_sp = target.GetSharedModule (module_spec)))
4645 {
4646 module_sp->SetLoadAddress (target, base_addr, true, changed);
4647 }
4648
4649 return module_sp;
4650}
4651
4652size_t
4653ProcessGDBRemote::LoadModules ()
4654{
4655 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4656
4657 // request a list of loaded libraries from GDBServer
4658 GDBLoadedModuleInfoList module_list;
4659 if (GetLoadedModuleList (module_list).Fail())
4660 return 0;
4661
4662 // get a list of all the modules
4663 ModuleList new_modules;
4664
4665 for (GDBLoadedModuleInfoList::LoadedModuleInfo & modInfo : module_list.m_list)
4666 {
4667 std::string mod_name;
4668 lldb::addr_t mod_base;
4669
4670 bool valid = true;
4671 valid &= modInfo.get_name (mod_name);
4672 valid &= modInfo.get_base (mod_base);
4673 if (!valid)
4674 continue;
4675
4676 // hack (cleaner way to get file name only?) (win/unix compat?)
Vince Harron4cc8d202015-05-10 08:33:58 +00004677 size_t marker = mod_name.rfind ('/');
Aidan Doddsc0c83852015-05-08 09:36:31 +00004678 if (marker == std::string::npos)
4679 marker = 0;
4680 else
4681 marker += 1;
4682
4683 FileSpec file (mod_name.c_str()+marker, true);
4684 lldb::ModuleSP module_sp = LoadModuleAtAddress (file, mod_base);
4685
4686 if (module_sp.get())
4687 new_modules.Append (module_sp);
4688 }
4689
4690 if (new_modules.GetSize() > 0)
4691 {
4692 Target & target = m_target;
4693
4694 new_modules.ForEach ([&target](const lldb::ModuleSP module_sp) -> bool
4695 {
4696 lldb_private::ObjectFile * obj = module_sp->GetObjectFile ();
4697 if (!obj)
4698 return true;
4699
4700 if (obj->GetType () != ObjectFile::Type::eTypeExecutable)
4701 return true;
4702
4703 lldb::ModuleSP module_copy_sp = module_sp;
4704 target.SetExecutableModule (module_copy_sp, false);
4705 return false;
4706 });
4707
4708 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4709 loaded_modules.AppendIfNeeded (new_modules);
4710 m_process->GetTarget().ModulesDidLoad (new_modules);
4711 }
4712
4713 return new_modules.GetSize();
4714}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004715
Tamas Berghammer783bfc82015-06-18 20:43:56 +00004716Error
4717ProcessGDBRemote::GetFileLoadAddress(const FileSpec& file, bool& is_loaded, lldb::addr_t& load_addr)
4718{
4719 is_loaded = false;
4720 load_addr = LLDB_INVALID_ADDRESS;
4721
4722 std::string file_path = file.GetPath(false);
4723 if (file_path.empty ())
4724 return Error("Empty file name specified");
4725
4726 StreamString packet;
4727 packet.PutCString("qFileLoadAddress:");
4728 packet.PutCStringAsRawHex8(file_path.c_str());
4729
4730 StringExtractorGDBRemote response;
4731 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString().c_str(), response, false) != GDBRemoteCommunication::PacketResult::Success)
4732 return Error("Sending qFileLoadAddress packet failed");
4733
4734 if (response.IsErrorResponse())
4735 {
4736 if (response.GetError() == 1)
4737 {
4738 // The file is not loaded into the inferior
4739 is_loaded = false;
4740 load_addr = LLDB_INVALID_ADDRESS;
4741 return Error();
4742 }
4743
4744 return Error("Fetching file load address from remote server returned an error");
4745 }
4746
4747 if (response.IsNormalResponse())
4748 {
4749 is_loaded = true;
4750 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
4751 return Error();
4752 }
4753
4754 return Error("Unknown error happened during sending the load address packet");
4755}
4756
Greg Clayton0b90be12015-06-23 21:27:50 +00004757
4758void
4759ProcessGDBRemote::ModulesDidLoad (ModuleList &module_list)
4760{
4761 // We must call the lldb_private::Process::ModulesDidLoad () first before we do anything
4762 Process::ModulesDidLoad (module_list);
4763
4764 // After loading shared libraries, we can ask our remote GDB server if
4765 // it needs any symbols.
4766 m_gdb_comm.ServeSymbolLookups(this);
4767}
4768
4769
Greg Claytone034a042015-05-21 20:52:06 +00004770class CommandObjectProcessGDBRemoteSpeedTest: public CommandObjectParsed
4771{
4772public:
4773 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter) :
4774 CommandObjectParsed (interpreter,
4775 "process plugin packet speed-test",
4776 "Tests packet speeds of various sizes to determine the performance characteristics of the GDB remote connection. ",
4777 NULL),
4778 m_option_group (interpreter),
4779 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),
4780 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),
4781 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),
4782 m_json (LLDB_OPT_SET_1, false, "json", 'j', "Print the output as JSON data for easy parsing.", false, true)
4783 {
4784 m_option_group.Append (&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4785 m_option_group.Append (&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4786 m_option_group.Append (&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4787 m_option_group.Append (&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4788 m_option_group.Finalize();
4789 }
4790
4791 ~CommandObjectProcessGDBRemoteSpeedTest ()
4792 {
4793 }
4794
4795
4796 Options *
4797 GetOptions () override
4798 {
4799 return &m_option_group;
4800 }
4801
4802 bool
4803 DoExecute (Args& command, CommandReturnObject &result) override
4804 {
4805 const size_t argc = command.GetArgumentCount();
4806 if (argc == 0)
4807 {
4808 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4809 if (process)
4810 {
4811 StreamSP output_stream_sp (m_interpreter.GetDebugger().GetAsyncOutputStream());
4812 result.SetImmediateOutputStream (output_stream_sp);
4813
4814 const uint32_t num_packets = (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
4815 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
4816 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
4817 const bool json = m_json.GetOptionValue().GetCurrentValue();
4818 if (output_stream_sp)
4819 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, *output_stream_sp);
4820 else
4821 {
4822 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, result.GetOutputStream());
4823 }
4824 result.SetStatus (eReturnStatusSuccessFinishResult);
4825 return true;
4826 }
4827 }
4828 else
4829 {
4830 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
4831 }
4832 result.SetStatus (eReturnStatusFailed);
4833 return false;
4834 }
4835protected:
4836 OptionGroupOptions m_option_group;
4837 OptionGroupUInt64 m_num_packets;
4838 OptionGroupUInt64 m_max_send;
4839 OptionGroupUInt64 m_max_recv;
4840 OptionGroupBoolean m_json;
4841
4842};
4843
Greg Clayton02686b82012-10-15 22:42:16 +00004844class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00004845{
4846private:
4847
4848public:
Greg Clayton02686b82012-10-15 22:42:16 +00004849 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00004850 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00004851 "process plugin packet history",
4852 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00004853 NULL)
4854 {
4855 }
4856
Greg Clayton02686b82012-10-15 22:42:16 +00004857 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton998255b2012-10-13 02:07:45 +00004858 {
4859 }
4860
4861 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004862 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton998255b2012-10-13 02:07:45 +00004863 {
Greg Clayton02686b82012-10-15 22:42:16 +00004864 const size_t argc = command.GetArgumentCount();
4865 if (argc == 0)
4866 {
4867 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4868 if (process)
4869 {
4870 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
4871 result.SetStatus (eReturnStatusSuccessFinishResult);
4872 return true;
4873 }
4874 }
4875 else
4876 {
4877 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
4878 }
4879 result.SetStatus (eReturnStatusFailed);
4880 return false;
4881 }
4882};
4883
Jason Molenda6076bf42014-05-06 04:34:52 +00004884class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed
4885{
4886private:
4887
4888public:
4889 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) :
4890 CommandObjectParsed (interpreter,
4891 "process plugin packet xfer-size",
4892 "Maximum size that lldb will try to read/write one one chunk.",
4893 NULL)
4894 {
4895 }
4896
4897 ~CommandObjectProcessGDBRemotePacketXferSize ()
4898 {
4899 }
4900
4901 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004902 DoExecute (Args& command, CommandReturnObject &result) override
Jason Molenda6076bf42014-05-06 04:34:52 +00004903 {
4904 const size_t argc = command.GetArgumentCount();
4905 if (argc == 0)
4906 {
4907 result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str());
4908 result.SetStatus (eReturnStatusFailed);
4909 return false;
4910 }
4911
4912 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4913 if (process)
4914 {
4915 const char *packet_size = command.GetArgumentAtIndex(0);
4916 errno = 0;
4917 uint64_t user_specified_max = strtoul (packet_size, NULL, 10);
4918 if (errno == 0 && user_specified_max != 0)
4919 {
4920 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max);
4921 result.SetStatus (eReturnStatusSuccessFinishResult);
4922 return true;
4923 }
4924 }
4925 result.SetStatus (eReturnStatusFailed);
4926 return false;
4927 }
4928};
4929
4930
Greg Clayton02686b82012-10-15 22:42:16 +00004931class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
4932{
4933private:
4934
4935public:
4936 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
4937 CommandObjectParsed (interpreter,
4938 "process plugin packet send",
4939 "Send a custom packet through the GDB remote protocol and print the answer. "
4940 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
4941 NULL)
4942 {
4943 }
4944
4945 ~CommandObjectProcessGDBRemotePacketSend ()
4946 {
4947 }
4948
4949 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004950 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton02686b82012-10-15 22:42:16 +00004951 {
4952 const size_t argc = command.GetArgumentCount();
4953 if (argc == 0)
4954 {
4955 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
4956 result.SetStatus (eReturnStatusFailed);
4957 return false;
4958 }
4959
4960 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4961 if (process)
4962 {
Han Ming Ong84145852012-11-26 20:42:03 +00004963 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00004964 {
Han Ming Ong84145852012-11-26 20:42:03 +00004965 const char *packet_cstr = command.GetArgumentAtIndex(0);
4966 bool send_async = true;
4967 StringExtractorGDBRemote response;
4968 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
4969 result.SetStatus (eReturnStatusSuccessFinishResult);
4970 Stream &output_strm = result.GetOutputStream();
4971 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00004972 std::string &response_str = response.GetStringRef();
4973
Han Ming Ong399289e2013-06-21 19:56:59 +00004974 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00004975 {
4976 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
4977 }
4978
Han Ming Ong84145852012-11-26 20:42:03 +00004979 if (response_str.empty())
4980 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
4981 else
4982 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00004983 }
Greg Clayton02686b82012-10-15 22:42:16 +00004984 }
Greg Clayton998255b2012-10-13 02:07:45 +00004985 return true;
4986 }
4987};
4988
Greg Claytonba4a0a52013-02-01 23:03:47 +00004989class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
4990{
4991private:
4992
4993public:
4994 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
4995 CommandObjectRaw (interpreter,
4996 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00004997 "Send a qRcmd packet through the GDB remote protocol and print the response."
4998 "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 +00004999 NULL)
5000 {
5001 }
5002
5003 ~CommandObjectProcessGDBRemotePacketMonitor ()
5004 {
5005 }
5006
5007 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005008 DoExecute (const char *command, CommandReturnObject &result) override
Greg Claytonba4a0a52013-02-01 23:03:47 +00005009 {
5010 if (command == NULL || command[0] == '\0')
5011 {
5012 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
5013 result.SetStatus (eReturnStatusFailed);
5014 return false;
5015 }
5016
5017 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5018 if (process)
5019 {
5020 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00005021 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00005022 packet.PutBytesAsRawHex8(command, strlen(command));
5023 const char *packet_cstr = packet.GetString().c_str();
5024
5025 bool send_async = true;
5026 StringExtractorGDBRemote response;
5027 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
5028 result.SetStatus (eReturnStatusSuccessFinishResult);
5029 Stream &output_strm = result.GetOutputStream();
5030 output_strm.Printf (" packet: %s\n", packet_cstr);
5031 const std::string &response_str = response.GetStringRef();
5032
5033 if (response_str.empty())
5034 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
5035 else
5036 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
5037 }
5038 return true;
5039 }
5040};
5041
Greg Clayton02686b82012-10-15 22:42:16 +00005042class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
5043{
5044private:
5045
5046public:
5047 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
5048 CommandObjectMultiword (interpreter,
5049 "process plugin packet",
5050 "Commands that deal with GDB remote packets.",
5051 NULL)
5052 {
5053 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
5054 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00005055 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Jason Molenda6076bf42014-05-06 04:34:52 +00005056 LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter)));
Greg Claytone034a042015-05-21 20:52:06 +00005057 LoadSubCommand ("speed-test", CommandObjectSP (new CommandObjectProcessGDBRemoteSpeedTest (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00005058 }
5059
5060 ~CommandObjectProcessGDBRemotePacket ()
5061 {
5062 }
5063};
Greg Clayton998255b2012-10-13 02:07:45 +00005064
5065class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
5066{
5067public:
5068 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
5069 CommandObjectMultiword (interpreter,
5070 "process plugin",
5071 "A set of commands for operating on a ProcessGDBRemote process.",
5072 "process plugin <subcommand> [<subcommand-options>]")
5073 {
5074 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
5075 }
5076
5077 ~CommandObjectMultiwordProcessGDBRemote ()
5078 {
5079 }
5080};
5081
Greg Clayton998255b2012-10-13 02:07:45 +00005082CommandObject *
5083ProcessGDBRemote::GetPluginCommandObject()
5084{
5085 if (!m_command_sp)
5086 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
5087 return m_command_sp.get();
5088}