blob: 16a966dba42cbab012a283996642236453cab660 [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 }
Jason Molendaa18f7072015-08-15 01:21:01 +0000639 else if (name.compare("gcc") == 0 || name.compare("ehframe") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000640 {
Jason Molendaa18f7072015-08-15 01:21:01 +0000641 reg_info.kinds[eRegisterKindEHFrame] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000642 }
643 else if (name.compare("dwarf") == 0)
644 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000645 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000646 }
647 else if (name.compare("generic") == 0)
648 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000649 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000650 }
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000651 else if (name.compare("container-regs") == 0)
652 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000653 SplitCommaSeparatedRegisterNumberString(value, value_regs, 16);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000654 }
655 else if (name.compare("invalidate-regs") == 0)
656 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000657 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 16);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000658 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000659 }
660
Jason Molenda743e86a2010-06-11 23:44:18 +0000661 reg_info.byte_offset = reg_offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000662 assert (reg_info.byte_size != 0);
663 reg_offset += reg_info.byte_size;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000664 if (!value_regs.empty())
665 {
666 value_regs.push_back(LLDB_INVALID_REGNUM);
667 reg_info.value_regs = value_regs.data();
668 }
669 if (!invalidate_regs.empty())
670 {
671 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
672 reg_info.invalidate_regs = invalidate_regs.data();
673 }
674
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000675 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
676 }
Todd Fiala1a634402014-01-08 07:52:40 +0000677 else
678 {
679 break; // ensure exit before reg_num is incremented
680 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000681 }
682 else
683 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000684 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000685 }
686 }
687
Greg Claytond04f0ed2015-05-26 18:00:51 +0000688 if (m_register_info.GetNumRegisters() > 0)
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000689 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000690 m_register_info.Finalize(GetTarget().GetArchitecture());
691 return;
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000692 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000693
Johnny Chen2fa9de12012-05-14 18:44:23 +0000694 // We didn't get anything if the accumulated reg_num is zero. See if we are
695 // debugging ARM and fill with a hard coded register set until we can get an
696 // updated debugserver down on the devices.
697 // On the other hand, if the accumulated reg_num is positive, see if we can
698 // add composite registers to the existing primordial ones.
Greg Claytond04f0ed2015-05-26 18:00:51 +0000699 bool from_scratch = (m_register_info.GetNumRegisters() == 0);
Johnny Chen2fa9de12012-05-14 18:44:23 +0000700
701 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000702 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
703 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
704
705 // Use the process' architecture instead of the host arch, if available
706 ArchSpec remote_arch;
707 if (remote_process_arch.IsValid ())
708 remote_arch = remote_process_arch;
709 else
710 remote_arch = remote_host_arch;
711
Johnny Chen2fa9de12012-05-14 18:44:23 +0000712 if (!target_arch.IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000713 {
Johnny Chen2fa9de12012-05-14 18:44:23 +0000714 if (remote_arch.IsValid()
715 && remote_arch.GetMachine() == llvm::Triple::arm
716 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
717 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000718 }
Johnny Chen2fa9de12012-05-14 18:44:23 +0000719 else if (target_arch.GetMachine() == llvm::Triple::arm)
720 {
721 m_register_info.HardcodeARMRegisters(from_scratch);
722 }
723
724 // At this point, we can finalize our register info.
Greg Claytond04f0ed2015-05-26 18:00:51 +0000725 m_register_info.Finalize (GetTarget().GetArchitecture());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000726}
727
728Error
729ProcessGDBRemote::WillLaunch (Module* module)
730{
731 return WillLaunchOrAttach ();
732}
733
734Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000735ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000736{
737 return WillLaunchOrAttach ();
738}
739
740Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000741ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000742{
743 return WillLaunchOrAttach ();
744}
745
746Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000747ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +0000748{
Todd Fialaaf245d12014-06-30 21:05:18 +0000749 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Claytonb766a732011-02-04 01:58:07 +0000750 Error error (WillLaunchOrAttach ());
751
752 if (error.Fail())
753 return error;
754
Greg Clayton2289fa42011-04-30 01:09:13 +0000755 error = ConnectToDebugserver (remote_url);
Greg Claytonb766a732011-02-04 01:58:07 +0000756
757 if (error.Fail())
758 return error;
759 StartAsyncThread ();
760
Greg Claytonc574ede2011-03-10 02:26:48 +0000761 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonb766a732011-02-04 01:58:07 +0000762 if (pid == LLDB_INVALID_PROCESS_ID)
763 {
764 // We don't have a valid process ID, so note that we are connected
765 // and could now request to launch or attach, or get remote process
766 // listings...
767 SetPrivateState (eStateConnected);
768 }
769 else
770 {
771 // We have a valid process
772 SetID (pid);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000773 GetThreadList();
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000774 StringExtractorGDBRemote response;
775 if (m_gdb_comm.GetStopReply(response))
Greg Claytonb766a732011-02-04 01:58:07 +0000776 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000777 SetLastStopPacket(response);
Ewan Crawford78baa192015-05-13 09:18:18 +0000778
779 // '?' Packets must be handled differently in non-stop mode
780 if (GetTarget().GetNonStopModeEnabled())
781 HandleStopReplySequence();
782
Jason Molendac62bd7b2013-12-21 05:20:36 +0000783 if (!m_target.GetArchitecture().IsValid())
784 {
785 if (m_gdb_comm.GetProcessArchitecture().IsValid())
786 {
787 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
788 }
789 else
790 {
791 m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
792 }
Carlo Kok74389122013-10-14 07:09:13 +0000793 }
794
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000795 const StateType state = SetThreadStopInfo (response);
Greg Clayton2e309072015-07-17 23:42:28 +0000796 if (state != eStateInvalid)
Greg Claytonb766a732011-02-04 01:58:07 +0000797 {
798 SetPrivateState (state);
799 }
800 else
Daniel Malead01b2952012-11-29 21:49:15 +0000801 error.SetErrorStringWithFormat ("Process %" PRIu64 " was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
Greg Claytonb766a732011-02-04 01:58:07 +0000802 }
803 else
Daniel Malead01b2952012-11-29 21:49:15 +0000804 error.SetErrorStringWithFormat ("Process %" PRIu64 " was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
Greg Claytonb766a732011-02-04 01:58:07 +0000805 }
Jason Molenda16d127c2012-05-03 22:37:30 +0000806
Todd Fialaaf245d12014-06-30 21:05:18 +0000807 if (log)
808 log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": normalizing target architecture initial triple: %s (GetTarget().GetArchitecture().IsValid() %s, m_gdb_comm.GetHostArchitecture().IsValid(): %s)", __FUNCTION__, GetID (), GetTarget ().GetArchitecture ().GetTriple ().getTriple ().c_str (), GetTarget ().GetArchitecture ().IsValid () ? "true" : "false", m_gdb_comm.GetHostArchitecture ().IsValid () ? "true" : "false");
809
810
811 if (error.Success()
Jason Molenda16d127c2012-05-03 22:37:30 +0000812 && !GetTarget().GetArchitecture().IsValid()
813 && m_gdb_comm.GetHostArchitecture().IsValid())
814 {
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000815 // Prefer the *process'* architecture over that of the *host*, if available.
816 if (m_gdb_comm.GetProcessArchitecture().IsValid())
817 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
818 else
819 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molenda16d127c2012-05-03 22:37:30 +0000820 }
821
Todd Fialaaf245d12014-06-30 21:05:18 +0000822 if (log)
823 log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": normalized target architecture triple: %s", __FUNCTION__, GetID (), GetTarget ().GetArchitecture ().GetTriple ().getTriple ().c_str ());
824
Chaoren Lin98d0a4b2015-07-14 01:09:28 +0000825 if (error.Success())
Jaydeep Patil6fc590d2015-07-30 05:06:51 +0000826 {
827 PlatformSP platform_sp = GetTarget().GetPlatform();
828 if (platform_sp && platform_sp->IsConnected())
829 SetUnixSignals(platform_sp->GetUnixSignals());
830 else
831 SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
832 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000833
Greg Claytonb766a732011-02-04 01:58:07 +0000834 return error;
835}
836
837Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000838ProcessGDBRemote::WillLaunchOrAttach ()
839{
840 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000841 m_stdio_communication.Clear ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000842 return error;
843}
844
845//----------------------------------------------------------------------
846// Process Control
847//----------------------------------------------------------------------
848Error
Jean-Daniel Dupas7782de92013-12-09 22:52:50 +0000849ProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000850{
Todd Fiala75f47c32014-10-11 21:42:09 +0000851 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton4957bf62010-09-30 21:49:03 +0000852 Error error;
Greg Clayton982c9762011-11-03 21:22:33 +0000853
Todd Fiala75f47c32014-10-11 21:42:09 +0000854 if (log)
855 log->Printf ("ProcessGDBRemote::%s() entered", __FUNCTION__);
856
Greg Clayton982c9762011-11-03 21:22:33 +0000857 uint32_t launch_flags = launch_info.GetFlags().Get();
Chaoren Lind3173f32015-05-29 19:52:29 +0000858 FileSpec stdin_file_spec{};
859 FileSpec stdout_file_spec{};
860 FileSpec stderr_file_spec{};
861 FileSpec working_dir = launch_info.GetWorkingDirectory();
Greg Clayton982c9762011-11-03 21:22:33 +0000862
Zachary Turner696b5282014-08-14 16:01:25 +0000863 const FileAction *file_action;
Greg Clayton982c9762011-11-03 21:22:33 +0000864 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
865 if (file_action)
866 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000867 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000868 stdin_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000869 }
870 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
871 if (file_action)
872 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000873 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000874 stdout_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000875 }
876 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
877 if (file_action)
878 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000879 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000880 stderr_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000881 }
882
Todd Fiala75f47c32014-10-11 21:42:09 +0000883 if (log)
884 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000885 if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
Vince Harron4a8abd32015-02-13 19:15:24 +0000886 log->Printf ("ProcessGDBRemote::%s provided with STDIO paths via launch_info: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000887 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000888 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
889 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
890 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Todd Fiala75f47c32014-10-11 21:42:09 +0000891 else
892 log->Printf ("ProcessGDBRemote::%s no STDIO paths given via launch_info", __FUNCTION__);
893 }
894
Vince Harrondf3f00f2015-02-10 21:09:04 +0000895 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Chaoren Lind3173f32015-05-29 19:52:29 +0000896 if (stdin_file_spec || disable_stdio)
Vince Harrondf3f00f2015-02-10 21:09:04 +0000897 {
898 // the inferior will be reading stdin from the specified file
899 // or stdio is completely disabled
900 m_stdin_forward = false;
901 }
902 else
903 {
904 m_stdin_forward = true;
905 }
906
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000907 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
908 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
909 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000910
Greg Clayton982c9762011-11-03 21:22:33 +0000911 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000912 if (object_file)
913 {
Greg Clayton71337622011-02-24 22:24:29 +0000914 // Make sure we aren't already connected?
915 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000916 {
Greg Clayton91a9b2472013-12-04 19:19:12 +0000917 error = LaunchAndConnectToDebugserver (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000918 }
919
920 if (error.Success())
921 {
922 lldb_utility::PseudoTerminal pty;
923 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000924
Greg Claytonf58c2692011-06-24 22:32:10 +0000925 PlatformSP platform_sp (m_target.GetPlatform());
Vince Harrondf3f00f2015-02-10 21:09:04 +0000926 if (disable_stdio)
Greg Clayton71337622011-02-24 22:24:29 +0000927 {
Vince Harrondf3f00f2015-02-10 21:09:04 +0000928 // set to /dev/null unless redirected to a file above
Chaoren Lind3173f32015-05-29 19:52:29 +0000929 if (!stdin_file_spec)
930 stdin_file_spec.SetFile("/dev/null", false);
931 if (!stdout_file_spec)
932 stdout_file_spec.SetFile("/dev/null", false);
933 if (!stderr_file_spec)
934 stderr_file_spec.SetFile("/dev/null", false);
Vince Harrondf3f00f2015-02-10 21:09:04 +0000935 }
936 else if (platform_sp && platform_sp->IsHost())
937 {
938 // If the debugserver is local and we aren't disabling STDIO, lets use
939 // a pseudo terminal to instead of relying on the 'O' packets for stdio
940 // since 'O' packets can really slow down debugging if the inferior
941 // does a lot of output.
Chaoren Lind3173f32015-05-29 19:52:29 +0000942 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
943 pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000944 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000945 FileSpec slave_name{pty.GetSlaveName(NULL, 0), false};
946
947 if (!stdin_file_spec)
948 stdin_file_spec = slave_name;
949
950 if (!stdout_file_spec)
951 stdout_file_spec = slave_name;
952
953 if (!stderr_file_spec)
954 stderr_file_spec = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000955 }
Todd Fiala75f47c32014-10-11 21:42:09 +0000956 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +0000957 log->Printf ("ProcessGDBRemote::%s adjusted STDIO paths for local platform (IsHost() is true) using slave: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000958 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000959 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
960 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
961 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Greg Clayton71337622011-02-24 22:24:29 +0000962 }
963
Todd Fiala75f47c32014-10-11 21:42:09 +0000964 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +0000965 log->Printf ("ProcessGDBRemote::%s final STDIO paths after all adjustments: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000966 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000967 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
968 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
969 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Todd Fiala75f47c32014-10-11 21:42:09 +0000970
Chaoren Lind3173f32015-05-29 19:52:29 +0000971 if (stdin_file_spec)
972 m_gdb_comm.SetSTDIN(stdin_file_spec);
973 if (stdout_file_spec)
974 m_gdb_comm.SetSTDOUT(stdout_file_spec);
975 if (stderr_file_spec)
976 m_gdb_comm.SetSTDERR(stderr_file_spec);
Greg Clayton71337622011-02-24 22:24:29 +0000977
978 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
Jim Ingham106d0282014-06-25 02:32:56 +0000979 m_gdb_comm.SetDetachOnError (launch_flags & eLaunchFlagDetachOnError);
Greg Clayton71337622011-02-24 22:24:29 +0000980
Greg Claytonc4103b32011-05-08 04:53:50 +0000981 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Clayton71337622011-02-24 22:24:29 +0000982
Jason Molendaa3329782014-03-29 18:54:20 +0000983 const char * launch_event_data = launch_info.GetLaunchEventData();
984 if (launch_event_data != NULL && *launch_event_data != '\0')
985 m_gdb_comm.SendLaunchEventDataPacket (launch_event_data);
986
Chaoren Lind3173f32015-05-29 19:52:29 +0000987 if (working_dir)
Greg Clayton71337622011-02-24 22:24:29 +0000988 {
989 m_gdb_comm.SetWorkingDir (working_dir);
990 }
991
992 // Send the environment and the program + arguments after we connect
Greg Clayton982c9762011-11-03 21:22:33 +0000993 const Args &environment = launch_info.GetEnvironmentEntries();
994 if (environment.GetArgumentCount())
Greg Clayton71337622011-02-24 22:24:29 +0000995 {
Greg Clayton982c9762011-11-03 21:22:33 +0000996 size_t num_environment_entries = environment.GetArgumentCount();
997 for (size_t i=0; i<num_environment_entries; ++i)
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000998 {
Greg Clayton982c9762011-11-03 21:22:33 +0000999 const char *env_entry = environment.GetArgumentAtIndex(i);
1000 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Clayton71337622011-02-24 22:24:29 +00001001 break;
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001002 }
Greg Clayton71337622011-02-24 22:24:29 +00001003 }
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001004
Greg Clayton71337622011-02-24 22:24:29 +00001005 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001006 // Scope for the scoped timeout object
1007 GDBRemoteCommunication::ScopedTimeout timeout (m_gdb_comm, 10);
1008
1009 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
1010 if (arg_packet_err == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001011 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001012 std::string error_str;
1013 if (m_gdb_comm.GetLaunchSuccess (error_str))
1014 {
1015 SetID (m_gdb_comm.GetCurrentProcessID ());
1016 }
1017 else
1018 {
1019 error.SetErrorString (error_str.c_str());
1020 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001021 }
1022 else
1023 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001024 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001025 }
Greg Clayton71337622011-02-24 22:24:29 +00001026 }
Tamas Berghammer912800c2015-02-24 10:23:39 +00001027
Greg Clayton71337622011-02-24 22:24:29 +00001028 if (GetID() == LLDB_INVALID_PROCESS_ID)
1029 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001030 if (log)
1031 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton71337622011-02-24 22:24:29 +00001032 KillDebugserverProcess ();
1033 return error;
1034 }
1035
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001036 StringExtractorGDBRemote response;
1037 if (m_gdb_comm.GetStopReply(response))
Greg Clayton71337622011-02-24 22:24:29 +00001038 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001039 SetLastStopPacket(response);
Ewan Crawford78baa192015-05-13 09:18:18 +00001040 // '?' Packets must be handled differently in non-stop mode
1041 if (GetTarget().GetNonStopModeEnabled())
1042 HandleStopReplySequence();
1043
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001044 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
1045
1046 if (process_arch.IsValid())
Jason Molendac62bd7b2013-12-21 05:20:36 +00001047 {
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001048 m_target.MergeArchitecture(process_arch);
1049 }
1050 else
1051 {
1052 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
1053 if (host_arch.IsValid())
1054 m_target.MergeArchitecture(host_arch);
Carlo Kok74389122013-10-14 07:09:13 +00001055 }
1056
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001057 SetPrivateState (SetThreadStopInfo (response));
Greg Clayton71337622011-02-24 22:24:29 +00001058
1059 if (!disable_stdio)
1060 {
1061 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Claytonee95ed52011-11-17 22:14:31 +00001062 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Clayton71337622011-02-24 22:24:29 +00001063 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001064 }
1065 }
Greg Claytonc235ac72011-08-09 05:20:29 +00001066 else
1067 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001068 if (log)
1069 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytonc235ac72011-08-09 05:20:29 +00001070 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001071 }
1072 else
1073 {
1074 // Set our user ID to an invalid process ID.
1075 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton982c9762011-11-03 21:22:33 +00001076 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
1077 exe_module->GetFileSpec().GetFilename().AsCString(),
1078 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001079 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001080 return error;
Greg Clayton4957bf62010-09-30 21:49:03 +00001081
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001082}
1083
1084
1085Error
Greg Claytonb766a732011-02-04 01:58:07 +00001086ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001087{
1088 Error error;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001089 // Only connect if we have a valid connect URL
Vince Harron1b5a74e2015-01-21 22:42:49 +00001090 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton00fe87b2013-12-05 22:58:22 +00001091
1092 if (connect_url && connect_url[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001093 {
Vince Harron1b5a74e2015-01-21 22:42:49 +00001094 if (log)
1095 log->Printf("ProcessGDBRemote::%s Connecting to %s", __FUNCTION__, connect_url);
Greg Clayton00fe87b2013-12-05 22:58:22 +00001096 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
1097 if (conn_ap.get())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001098 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001099 const uint32_t max_retry_count = 50;
1100 uint32_t retry_count = 0;
1101 while (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001102 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001103 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
1104 {
1105 m_gdb_comm.SetConnection (conn_ap.release());
1106 break;
1107 }
1108 else if (error.WasInterrupted())
1109 {
1110 // If we were interrupted, don't keep retrying.
1111 break;
1112 }
1113
1114 retry_count++;
1115
1116 if (retry_count >= max_retry_count)
1117 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001118
Greg Clayton00fe87b2013-12-05 22:58:22 +00001119 usleep (100000);
1120 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001121 }
1122 }
1123
1124 if (!m_gdb_comm.IsConnected())
1125 {
1126 if (error.Success())
1127 error.SetErrorString("not connected to remote gdb server");
1128 return error;
1129 }
1130
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001131
1132 // Start the communications read thread so all incoming data can be
1133 // parsed into packets and queued as they arrive.
1134 if (GetTarget().GetNonStopModeEnabled())
1135 m_gdb_comm.StartReadThread();
1136
Greg Clayton32e0a752011-03-30 18:16:51 +00001137 // We always seem to be able to open a connection to a local port
1138 // so we need to make sure we can then send data to it. If we can't
1139 // then we aren't actually connected to anything, so try and do the
1140 // handshake with the remote GDB server and make sure that goes
1141 // alright.
Greg Claytonfb909312013-11-23 01:58:15 +00001142 if (!m_gdb_comm.HandshakeWithServer (&error))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001143 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001144 m_gdb_comm.Disconnect();
1145 if (error.Success())
1146 error.SetErrorString("not connected to remote gdb server");
1147 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001148 }
Ewan Crawford78baa192015-05-13 09:18:18 +00001149
1150 // Send $QNonStop:1 packet on startup if required
1151 if (GetTarget().GetNonStopModeEnabled())
Ewan Crawfordaa7eda72015-06-24 15:14:26 +00001152 GetTarget().SetNonStopModeEnabled (m_gdb_comm.SetNonStopMode(true));
Ewan Crawford78baa192015-05-13 09:18:18 +00001153
Greg Claytonb30c50c2015-05-29 00:01:55 +00001154 m_gdb_comm.GetEchoSupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001155 m_gdb_comm.GetThreadSuffixSupported ();
Greg Clayton44633992012-04-10 03:22:03 +00001156 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001157 m_gdb_comm.GetHostInfo ();
1158 m_gdb_comm.GetVContSupported ('c');
Jim Inghamcd16df92012-07-20 21:37:13 +00001159 m_gdb_comm.GetVAttachOrWaitSupported();
Ewan Crawford78baa192015-05-13 09:18:18 +00001160
1161 // Ask the remote server for the default thread id
1162 if (GetTarget().GetNonStopModeEnabled())
1163 m_gdb_comm.GetDefaultThreadId(m_initial_tid);
1164
1165
Jim Ingham03afad82012-07-02 05:40:07 +00001166 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1167 for (size_t idx = 0; idx < num_cmds; idx++)
1168 {
1169 StringExtractorGDBRemote response;
Jim Ingham03afad82012-07-02 05:40:07 +00001170 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1171 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001172 return error;
1173}
1174
1175void
Jim Inghambb006ce2014-08-02 00:33:35 +00001176ProcessGDBRemote::DidLaunchOrAttach (ArchSpec& process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001177{
Greg Clayton5160ce52013-03-27 23:08:40 +00001178 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001179 if (log)
1180 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton93d3c8332011-02-16 04:46:07 +00001181 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001182 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001183 BuildDynamicRegisterInfo (false);
Greg Clayton3af9ea52010-11-18 05:57:03 +00001184
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001185 // See if the GDB server supports the qHostInfo information
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001186
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001187
1188 // See if the GDB server supports the qProcessInfo packet, if so
1189 // prefer that over the Host information as it will be more specific
1190 // to our process.
1191
Todd Fiala75f47c32014-10-11 21:42:09 +00001192 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1193 if (remote_process_arch.IsValid())
1194 {
1195 process_arch = remote_process_arch;
1196 if (log)
1197 log->Printf ("ProcessGDBRemote::%s gdb-remote had process architecture, using %s %s",
1198 __FUNCTION__,
1199 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1200 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1201 }
Jim Inghambb006ce2014-08-02 00:33:35 +00001202 else
Todd Fiala75f47c32014-10-11 21:42:09 +00001203 {
Jim Inghambb006ce2014-08-02 00:33:35 +00001204 process_arch = m_gdb_comm.GetHostArchitecture();
Todd Fiala75f47c32014-10-11 21:42:09 +00001205 if (log)
1206 log->Printf ("ProcessGDBRemote::%s gdb-remote did not have process architecture, using gdb-remote host architecture %s %s",
1207 __FUNCTION__,
1208 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1209 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1210 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001211
Jim Inghambb006ce2014-08-02 00:33:35 +00001212 if (process_arch.IsValid())
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001213 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001214 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Greg Claytond314e812011-03-23 00:09:55 +00001215 if (target_arch.IsValid())
1216 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001217 if (log)
1218 log->Printf ("ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1219 __FUNCTION__,
1220 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1221 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
1222
1223 // If the remote host is ARM and we have apple as the vendor, then
Greg Claytond314e812011-03-23 00:09:55 +00001224 // ARM executables and shared libraries can have mixed ARM architectures.
1225 // You can have an armv6 executable, and if the host is armv7, then the
1226 // system will load the best possible architecture for all shared libraries
1227 // it has, so we really need to take the remote host architecture as our
1228 // defacto architecture in this case.
1229
Jim Inghambb006ce2014-08-02 00:33:35 +00001230 if (process_arch.GetMachine() == llvm::Triple::arm &&
1231 process_arch.GetTriple().getVendor() == llvm::Triple::Apple)
Greg Claytond314e812011-03-23 00:09:55 +00001232 {
Jason Molenda921c01b2014-08-03 21:42:52 +00001233 GetTarget().SetArchitecture (process_arch);
Todd Fiala75f47c32014-10-11 21:42:09 +00001234 if (log)
1235 log->Printf ("ProcessGDBRemote::%s remote process is ARM/Apple, setting target arch to %s %s",
1236 __FUNCTION__,
1237 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1238 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001239 }
1240 else
1241 {
1242 // Fill in what is missing in the triple
Jim Inghambb006ce2014-08-02 00:33:35 +00001243 const llvm::Triple &remote_triple = process_arch.GetTriple();
Tamas Berghammere724af12015-03-13 10:32:37 +00001244 llvm::Triple new_target_triple = target_arch.GetTriple();
1245 if (new_target_triple.getVendorName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001246 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001247 new_target_triple.setVendor (remote_triple.getVendor());
Greg Claytond314e812011-03-23 00:09:55 +00001248
Tamas Berghammere724af12015-03-13 10:32:37 +00001249 if (new_target_triple.getOSName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001250 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001251 new_target_triple.setOS (remote_triple.getOS());
Greg Claytond314e812011-03-23 00:09:55 +00001252
Tamas Berghammere724af12015-03-13 10:32:37 +00001253 if (new_target_triple.getEnvironmentName().size() == 0)
1254 new_target_triple.setEnvironment (remote_triple.getEnvironment());
Greg Clayton70b57652011-05-15 01:25:55 +00001255 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001256
Tamas Berghammere724af12015-03-13 10:32:37 +00001257 ArchSpec new_target_arch = target_arch;
1258 new_target_arch.SetTriple(new_target_triple);
1259 GetTarget().SetArchitecture(new_target_arch);
1260 }
Greg Claytond314e812011-03-23 00:09:55 +00001261 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001262
1263 if (log)
1264 log->Printf ("ProcessGDBRemote::%s final target arch after adjustments for remote architecture: %s %s",
1265 __FUNCTION__,
1266 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1267 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001268 }
1269 else
1270 {
1271 // The target doesn't have a valid architecture yet, set it from
1272 // the architecture we got from the remote GDB server
Jason Molenda921c01b2014-08-03 21:42:52 +00001273 GetTarget().SetArchitecture (process_arch);
Greg Claytond314e812011-03-23 00:09:55 +00001274 }
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001275 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001276 }
1277}
1278
1279void
1280ProcessGDBRemote::DidLaunch ()
1281{
Jim Inghambb006ce2014-08-02 00:33:35 +00001282 ArchSpec process_arch;
1283 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001284}
1285
1286Error
Han Ming Ong84647042012-02-25 01:07:38 +00001287ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1288{
Todd Fiala75f47c32014-10-11 21:42:09 +00001289 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001290 Error error;
Todd Fiala75f47c32014-10-11 21:42:09 +00001291
1292 if (log)
1293 log->Printf ("ProcessGDBRemote::%s()", __FUNCTION__);
1294
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001295 // Clear out and clean up from any current state
1296 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001297 if (attach_pid != LLDB_INVALID_PROCESS_ID)
1298 {
Greg Clayton71337622011-02-24 22:24:29 +00001299 // Make sure we aren't already connected?
1300 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001301 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001302 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001303
1304 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001305 {
Greg Clayton71337622011-02-24 22:24:29 +00001306 const char *error_string = error.AsCString();
1307 if (error_string == NULL)
1308 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1309
1310 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001311 }
Greg Clayton71337622011-02-24 22:24:29 +00001312 }
1313
1314 if (error.Success())
1315 {
Jim Ingham106d0282014-06-25 02:32:56 +00001316 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
Todd Fiala75f47c32014-10-11 21:42:09 +00001317
Greg Clayton71337622011-02-24 22:24:29 +00001318 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001319 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Greg Clayton3b608422011-11-19 02:11:30 +00001320 SetID (attach_pid);
Greg Clayton71337622011-02-24 22:24:29 +00001321 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001322 }
1323 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001324
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001325 return error;
1326}
1327
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001328Error
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001329ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001330{
1331 Error error;
1332 // Clear out and clean up from any current state
1333 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001334
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001335 if (process_name && process_name[0])
1336 {
Greg Clayton71337622011-02-24 22:24:29 +00001337 // Make sure we aren't already connected?
1338 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001339 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001340 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001341
Greg Clayton71337622011-02-24 22:24:29 +00001342 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001343 {
Greg Clayton71337622011-02-24 22:24:29 +00001344 const char *error_string = error.AsCString();
1345 if (error_string == NULL)
1346 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001347
Greg Clayton71337622011-02-24 22:24:29 +00001348 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001349 }
Greg Clayton71337622011-02-24 22:24:29 +00001350 }
1351
1352 if (error.Success())
1353 {
1354 StreamString packet;
1355
Jim Ingham106d0282014-06-25 02:32:56 +00001356 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1357
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001358 if (attach_info.GetWaitForLaunch())
Jim Inghamcd16df92012-07-20 21:37:13 +00001359 {
1360 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1361 {
1362 packet.PutCString ("vAttachWait");
1363 }
1364 else
1365 {
1366 if (attach_info.GetIgnoreExisting())
1367 packet.PutCString("vAttachWait");
1368 else
1369 packet.PutCString ("vAttachOrWait");
1370 }
1371 }
Greg Clayton71337622011-02-24 22:24:29 +00001372 else
1373 packet.PutCString("vAttachName");
1374 packet.PutChar(';');
1375 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1376
1377 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1378
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001379 }
1380 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001381 return error;
1382}
1383
Greg Clayton5df78fa2015-05-23 03:54:53 +00001384void
1385ProcessGDBRemote::DidExit ()
Greg Claytonfbb76342013-11-20 21:07:01 +00001386{
Greg Clayton5df78fa2015-05-23 03:54:53 +00001387 // When we exit, disconnect from the GDB server communications
Greg Claytonfbb76342013-11-20 21:07:01 +00001388 m_gdb_comm.Disconnect();
Greg Claytonfbb76342013-11-20 21:07:01 +00001389}
1390
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001391void
Jim Inghambb006ce2014-08-02 00:33:35 +00001392ProcessGDBRemote::DidAttach (ArchSpec &process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001393{
Jim Inghambb006ce2014-08-02 00:33:35 +00001394 // If you can figure out what the architecture is, fill it in here.
1395 process_arch.Clear();
1396 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001397}
1398
Greg Clayton90ba8112012-12-05 00:16:59 +00001399
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001400Error
1401ProcessGDBRemote::WillResume ()
1402{
Greg Clayton71fc2a32011-02-12 06:28:37 +00001403 m_continue_c_tids.clear();
1404 m_continue_C_tids.clear();
1405 m_continue_s_tids.clear();
1406 m_continue_S_tids.clear();
Greg Clayton2e309072015-07-17 23:42:28 +00001407 m_jstopinfo_sp.reset();
1408 m_jthreadsinfo_sp.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001409 return Error();
1410}
1411
1412Error
1413ProcessGDBRemote::DoResume ()
1414{
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001415 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001416 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001417 if (log)
1418 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytone5219662010-12-03 06:02:24 +00001419
1420 Listener listener ("gdb-remote.resume-packet-sent");
1421 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1422 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00001423 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1424
Greg Claytond1d06e42013-04-20 00:27:58 +00001425 const size_t num_threads = GetThreadList().GetSize();
1426
Greg Clayton71fc2a32011-02-12 06:28:37 +00001427 StreamString continue_packet;
1428 bool continue_packet_error = false;
1429 if (m_gdb_comm.HasAnyVContSupport ())
1430 {
Ewan Crawford78baa192015-05-13 09:18:18 +00001431 if (!GetTarget().GetNonStopModeEnabled() &&
1432 (m_continue_c_tids.size() == num_threads ||
Greg Claytone98008c2014-02-13 23:34:38 +00001433 (m_continue_c_tids.empty() &&
1434 m_continue_C_tids.empty() &&
1435 m_continue_s_tids.empty() &&
Ewan Crawford78baa192015-05-13 09:18:18 +00001436 m_continue_S_tids.empty())))
Greg Clayton71fc2a32011-02-12 06:28:37 +00001437 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001438 // All threads are continuing, just send a "c" packet
1439 continue_packet.PutCString ("c");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001440 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001441 else
1442 {
1443 continue_packet.PutCString ("vCont");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001444
Greg Claytond1d06e42013-04-20 00:27:58 +00001445 if (!m_continue_c_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001446 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001447 if (m_gdb_comm.GetVContSupported ('c'))
1448 {
1449 for (tid_collection::const_iterator t_pos = m_continue_c_tids.begin(), t_end = m_continue_c_tids.end(); t_pos != t_end; ++t_pos)
1450 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1451 }
1452 else
1453 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001454 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001455
1456 if (!continue_packet_error && !m_continue_C_tids.empty())
1457 {
1458 if (m_gdb_comm.GetVContSupported ('C'))
1459 {
1460 for (tid_sig_collection::const_iterator s_pos = m_continue_C_tids.begin(), s_end = m_continue_C_tids.end(); s_pos != s_end; ++s_pos)
1461 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1462 }
1463 else
1464 continue_packet_error = true;
1465 }
Greg Claytone5219662010-12-03 06:02:24 +00001466
Greg Claytond1d06e42013-04-20 00:27:58 +00001467 if (!continue_packet_error && !m_continue_s_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001468 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001469 if (m_gdb_comm.GetVContSupported ('s'))
1470 {
1471 for (tid_collection::const_iterator t_pos = m_continue_s_tids.begin(), t_end = m_continue_s_tids.end(); t_pos != t_end; ++t_pos)
1472 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1473 }
1474 else
1475 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001476 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001477
1478 if (!continue_packet_error && !m_continue_S_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001479 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001480 if (m_gdb_comm.GetVContSupported ('S'))
1481 {
1482 for (tid_sig_collection::const_iterator s_pos = m_continue_S_tids.begin(), s_end = m_continue_S_tids.end(); s_pos != s_end; ++s_pos)
1483 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1484 }
1485 else
1486 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001487 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001488
1489 if (continue_packet_error)
1490 continue_packet.GetString().clear();
Greg Clayton71fc2a32011-02-12 06:28:37 +00001491 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001492 }
1493 else
1494 continue_packet_error = true;
1495
1496 if (continue_packet_error)
1497 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001498 // Either no vCont support, or we tried to use part of the vCont
1499 // packet that wasn't supported by the remote GDB server.
1500 // We need to try and make a simple packet that can do our continue
Greg Clayton71fc2a32011-02-12 06:28:37 +00001501 const size_t num_continue_c_tids = m_continue_c_tids.size();
1502 const size_t num_continue_C_tids = m_continue_C_tids.size();
1503 const size_t num_continue_s_tids = m_continue_s_tids.size();
1504 const size_t num_continue_S_tids = m_continue_S_tids.size();
1505 if (num_continue_c_tids > 0)
1506 {
1507 if (num_continue_c_tids == num_threads)
1508 {
1509 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001510 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001511 continue_packet.PutChar ('c');
1512 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001513 }
1514 else if (num_continue_c_tids == 1 &&
1515 num_continue_C_tids == 0 &&
1516 num_continue_s_tids == 0 &&
1517 num_continue_S_tids == 0 )
1518 {
1519 // Only one thread is continuing
Greg Clayton8b82f082011-04-12 05:54:46 +00001520 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001521 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001522 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001523 }
1524 }
1525
Greg Clayton0c74e782011-06-24 03:21:43 +00001526 if (continue_packet_error && num_continue_C_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001527 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001528 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1529 num_continue_C_tids > 0 &&
1530 num_continue_s_tids == 0 &&
1531 num_continue_S_tids == 0 )
Greg Clayton71fc2a32011-02-12 06:28:37 +00001532 {
1533 const int continue_signo = m_continue_C_tids.front().second;
Greg Clayton0c74e782011-06-24 03:21:43 +00001534 // Only one thread is continuing
Greg Clayton71fc2a32011-02-12 06:28:37 +00001535 if (num_continue_C_tids > 1)
1536 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001537 // More that one thread with a signal, yet we don't have
1538 // vCont support and we are being asked to resume each
1539 // thread with a signal, we need to make sure they are
1540 // all the same signal, or we can't issue the continue
1541 // accurately with the current support...
1542 if (num_continue_C_tids > 1)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001543 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001544 continue_packet_error = false;
1545 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1546 {
1547 if (m_continue_C_tids[i].second != continue_signo)
1548 continue_packet_error = true;
1549 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001550 }
Greg Clayton0c74e782011-06-24 03:21:43 +00001551 if (!continue_packet_error)
1552 m_gdb_comm.SetCurrentThreadForRun (-1);
1553 }
1554 else
1555 {
1556 // Set the continue thread ID
1557 continue_packet_error = false;
1558 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001559 }
1560 if (!continue_packet_error)
1561 {
1562 // Add threads continuing with the same signo...
Greg Clayton71fc2a32011-02-12 06:28:37 +00001563 continue_packet.Printf("C%2.2x", continue_signo);
1564 }
1565 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001566 }
1567
Greg Clayton0c74e782011-06-24 03:21:43 +00001568 if (continue_packet_error && num_continue_s_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001569 {
1570 if (num_continue_s_tids == num_threads)
1571 {
1572 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001573 m_gdb_comm.SetCurrentThreadForRun (-1);
Ewan Crawford76df2882015-06-23 12:32:06 +00001574
1575 // If in Non-Stop-Mode use vCont when stepping
1576 if (GetTarget().GetNonStopModeEnabled())
1577 {
1578 if (m_gdb_comm.GetVContSupported('s'))
1579 continue_packet.PutCString("vCont;s");
1580 else
1581 continue_packet.PutChar('s');
1582 }
1583 else
1584 continue_packet.PutChar('s');
1585
Greg Clayton0c74e782011-06-24 03:21:43 +00001586 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001587 }
1588 else if (num_continue_c_tids == 0 &&
1589 num_continue_C_tids == 0 &&
1590 num_continue_s_tids == 1 &&
1591 num_continue_S_tids == 0 )
1592 {
1593 // Only one thread is stepping
Greg Clayton8b82f082011-04-12 05:54:46 +00001594 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001595 continue_packet.PutChar ('s');
Greg Clayton0c74e782011-06-24 03:21:43 +00001596 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001597 }
1598 }
1599
1600 if (!continue_packet_error && num_continue_S_tids > 0)
1601 {
1602 if (num_continue_S_tids == num_threads)
1603 {
1604 const int step_signo = m_continue_S_tids.front().second;
1605 // Are all threads trying to step with the same signal?
Greg Clayton0c74e782011-06-24 03:21:43 +00001606 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001607 if (num_continue_S_tids > 1)
1608 {
1609 for (size_t i=1; i<num_threads; ++i)
1610 {
1611 if (m_continue_S_tids[i].second != step_signo)
1612 continue_packet_error = true;
1613 }
1614 }
1615 if (!continue_packet_error)
1616 {
1617 // Add threads stepping with the same signo...
Greg Clayton8b82f082011-04-12 05:54:46 +00001618 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001619 continue_packet.Printf("S%2.2x", step_signo);
1620 }
1621 }
1622 else if (num_continue_c_tids == 0 &&
1623 num_continue_C_tids == 0 &&
1624 num_continue_s_tids == 0 &&
1625 num_continue_S_tids == 1 )
1626 {
1627 // Only one thread is stepping with signal
Greg Clayton8b82f082011-04-12 05:54:46 +00001628 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001629 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Clayton0c74e782011-06-24 03:21:43 +00001630 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001631 }
1632 }
1633 }
1634
1635 if (continue_packet_error)
1636 {
1637 error.SetErrorString ("can't make continue packet for this resume");
1638 }
1639 else
1640 {
1641 EventSP event_sp;
1642 TimeValue timeout;
1643 timeout = TimeValue::Now();
1644 timeout.OffsetWithSeconds (5);
Zachary Turneracee96a2014-09-23 18:32:09 +00001645 if (!m_async_thread.IsJoinable())
Jim Inghamb1e2e842012-04-12 18:49:31 +00001646 {
1647 error.SetErrorString ("Trying to resume but the async thread is dead.");
1648 if (log)
1649 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1650 return error;
1651 }
1652
Greg Clayton71fc2a32011-02-12 06:28:37 +00001653 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1654
1655 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Inghamb1e2e842012-04-12 18:49:31 +00001656 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001657 error.SetErrorString("Resume timed out.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00001658 if (log)
1659 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1660 }
1661 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1662 {
1663 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1664 if (log)
1665 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1666 return error;
1667 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001668 }
Greg Claytone5219662010-12-03 06:02:24 +00001669 }
1670
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001671 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001672}
1673
Greg Clayton9e920902012-04-10 02:25:43 +00001674void
Ewan Crawford78baa192015-05-13 09:18:18 +00001675ProcessGDBRemote::HandleStopReplySequence ()
1676{
1677 while(true)
1678 {
1679 // Send vStopped
1680 StringExtractorGDBRemote response;
1681 m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false);
1682
1683 // OK represents end of signal list
1684 if (response.IsOKResponse())
1685 break;
1686
1687 // If not OK or a normal packet we have a problem
1688 if (!response.IsNormalResponse())
1689 break;
1690
1691 SetLastStopPacket(response);
1692 }
1693}
1694
1695void
Greg Clayton9e920902012-04-10 02:25:43 +00001696ProcessGDBRemote::ClearThreadIDList ()
1697{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001698 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001699 m_thread_ids.clear();
1700}
1701
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001702size_t
1703ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue (std::string &value)
1704{
1705 m_thread_ids.clear();
1706 size_t comma_pos;
1707 lldb::tid_t tid;
1708 while ((comma_pos = value.find(',')) != std::string::npos)
1709 {
1710 value[comma_pos] = '\0';
1711 // thread in big endian hex
1712 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1713 if (tid != LLDB_INVALID_THREAD_ID)
1714 m_thread_ids.push_back (tid);
1715 value.erase(0, comma_pos + 1);
1716 }
1717 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1718 if (tid != LLDB_INVALID_THREAD_ID)
1719 m_thread_ids.push_back (tid);
1720 return m_thread_ids.size();
1721}
1722
Greg Clayton9e920902012-04-10 02:25:43 +00001723bool
1724ProcessGDBRemote::UpdateThreadIDList ()
1725{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001726 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001727
Greg Clayton2e309072015-07-17 23:42:28 +00001728 if (m_jthreadsinfo_sp)
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001729 {
1730 // If we have the JSON threads info, we can get the thread list from that
Greg Clayton2e309072015-07-17 23:42:28 +00001731 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001732 if (thread_infos && thread_infos->GetSize() > 0)
1733 {
1734 m_thread_ids.clear();
1735 thread_infos->ForEach([this](StructuredData::Object* object) -> bool {
1736 StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1737 if (thread_dict)
1738 {
1739 // Set the thread stop info from the JSON dictionary
1740 SetThreadStopInfo (thread_dict);
1741 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1742 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1743 m_thread_ids.push_back(tid);
1744 }
1745 return true; // Keep iterating through all thread_info objects
1746 });
1747 }
1748 if (!m_thread_ids.empty())
1749 return true;
1750 }
1751 else
1752 {
1753 // See if we can get the thread IDs from the current stop reply packets
1754 // that might contain a "threads" key/value pair
1755
1756 // Lock the thread stack while we access it
1757 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
1758 // Get the number of stop packets on the stack
1759 int nItems = m_stop_packet_stack.size();
1760 // Iterate over them
1761 for (int i = 0; i < nItems; i++)
1762 {
1763 // Get the thread stop info
1764 StringExtractorGDBRemote &stop_info = m_stop_packet_stack[i];
1765 const std::string &stop_info_str = stop_info.GetStringRef();
1766 const size_t threads_pos = stop_info_str.find(";threads:");
1767 if (threads_pos != std::string::npos)
1768 {
1769 const size_t start = threads_pos + strlen(";threads:");
1770 const size_t end = stop_info_str.find(';', start);
1771 if (end != std::string::npos)
1772 {
1773 std::string value = stop_info_str.substr(start, end - start);
1774 if (UpdateThreadIDsFromStopReplyThreadsValue(value))
1775 return true;
1776 }
1777 }
1778 }
1779 }
1780
Greg Clayton9e920902012-04-10 02:25:43 +00001781 bool sequence_mutex_unavailable = false;
1782 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1783 if (sequence_mutex_unavailable)
1784 {
Greg Clayton9e920902012-04-10 02:25:43 +00001785 return false; // We just didn't get the list
1786 }
1787 return true;
1788}
1789
Greg Clayton9fc13552012-04-10 00:18:59 +00001790bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001791ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001792{
1793 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +00001794 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Clayton73b472d2010-10-27 03:32:59 +00001795 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +00001796 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton9e920902012-04-10 02:25:43 +00001797
1798 size_t num_thread_ids = m_thread_ids.size();
1799 // The "m_thread_ids" thread ID list should always be updated after each stop
1800 // reply packet, but in case it isn't, update it here.
1801 if (num_thread_ids == 0)
1802 {
1803 if (!UpdateThreadIDList ())
1804 return false;
1805 num_thread_ids = m_thread_ids.size();
1806 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001807
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001808 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001809 if (num_thread_ids > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001810 {
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001811 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001812 {
Greg Clayton9e920902012-04-10 02:25:43 +00001813 tid_t tid = m_thread_ids[i];
Greg Clayton160c9d82013-05-01 21:54:04 +00001814 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001815 if (!thread_sp)
Jim Inghamdee1bc92013-06-22 00:27:45 +00001816 {
Jim Ingham4f465cf2012-10-10 18:32:14 +00001817 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001818 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1819 log->Printf(
1820 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001821 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001822 thread_sp->GetID());
1823 }
1824 else
1825 {
1826 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1827 log->Printf(
1828 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001829 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001830 thread_sp->GetID());
1831 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001832 new_thread_list.AddThread(thread_sp);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001833 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001834 }
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001835
1836 // Whatever that is left in old_thread_list_copy are not
1837 // present in new_thread_list. Remove non-existent threads from internal id table.
1838 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1839 for (size_t i=0; i<old_num_thread_ids; i++)
1840 {
1841 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1842 if (old_thread_sp)
1843 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001844 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001845 m_thread_id_to_index_id_map.erase(old_thread_id);
1846 }
1847 }
1848
Greg Clayton9fc13552012-04-10 00:18:59 +00001849 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001850}
1851
Greg Clayton2e309072015-07-17 23:42:28 +00001852
Greg Clayton358cf1e2015-06-25 21:46:34 +00001853bool
Greg Clayton2e309072015-07-17 23:42:28 +00001854ProcessGDBRemote::GetThreadStopInfoFromJSON (ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001855{
1856 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet
Greg Clayton2e309072015-07-17 23:42:28 +00001857 if (thread_infos_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001858 {
Greg Clayton2e309072015-07-17 23:42:28 +00001859 StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
Greg Clayton358cf1e2015-06-25 21:46:34 +00001860 if (thread_infos)
1861 {
1862 lldb::tid_t tid;
1863 const size_t n = thread_infos->GetSize();
1864 for (size_t i=0; i<n; ++i)
1865 {
1866 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1867 if (thread_dict)
1868 {
1869 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid, LLDB_INVALID_THREAD_ID))
1870 {
1871 if (tid == thread->GetID())
Greg Clayton2e309072015-07-17 23:42:28 +00001872 return (bool)SetThreadStopInfo(thread_dict);
Greg Clayton358cf1e2015-06-25 21:46:34 +00001873 }
1874 }
1875 }
1876 }
1877 }
Greg Clayton2e309072015-07-17 23:42:28 +00001878 return false;
1879}
1880
1881bool
1882ProcessGDBRemote::CalculateThreadStopInfo (ThreadGDBRemote *thread)
1883{
1884 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet
1885 if (GetThreadStopInfoFromJSON (thread, m_jthreadsinfo_sp))
1886 return true;
1887
1888 // See if we got thread stop info for any threads valid stop info reasons threads
1889 // via the "jstopinfo" packet stop reply packet key/value pair?
1890 if (m_jstopinfo_sp)
1891 {
1892 // If we have "jstopinfo" then we have stop descriptions for all threads
1893 // that have stop reasons, and if there is no entry for a thread, then
1894 // it has no stop reason.
1895 thread->GetRegisterContext()->InvalidateIfNeeded(true);
1896 if (!GetThreadStopInfoFromJSON (thread, m_jstopinfo_sp))
1897 {
1898 thread->SetStopInfo (StopInfoSP());
1899 }
1900 return true;
1901 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00001902
1903 // Fall back to using the qThreadStopInfo packet
1904 StringExtractorGDBRemote stop_packet;
1905 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1906 return SetThreadStopInfo (stop_packet) == eStateStopped;
1907 return false;
1908}
1909
1910
1911ThreadSP
1912ProcessGDBRemote::SetThreadStopInfo (lldb::tid_t tid,
1913 ExpeditedRegisterMap &expedited_register_map,
1914 uint8_t signo,
1915 const std::string &thread_name,
1916 const std::string &reason,
1917 const std::string &description,
1918 uint32_t exc_type,
1919 const std::vector<addr_t> &exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001920 addr_t thread_dispatch_qaddr,
1921 bool queue_vars_valid, // Set to true if queue_name, queue_kind and queue_serial are valid
1922 std::string &queue_name,
1923 QueueKind queue_kind,
1924 uint64_t queue_serial)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001925{
1926 ThreadSP thread_sp;
1927 if (tid != LLDB_INVALID_THREAD_ID)
1928 {
1929 // Scope for "locker" below
1930 {
1931 // m_thread_list_real does have its own mutex, but we need to
1932 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1933 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1934 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1935 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1936
1937 if (!thread_sp)
1938 {
1939 // Create the thread if we need to
1940 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1941 m_thread_list_real.AddThread(thread_sp);
1942 }
1943 }
1944
1945 if (thread_sp)
1946 {
1947 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1948 gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001949
Greg Clayton358cf1e2015-06-25 21:46:34 +00001950 for (const auto &pair : expedited_register_map)
1951 {
1952 StringExtractor reg_value_extractor;
1953 reg_value_extractor.GetStringRef() = pair.second;
1954 gdb_thread->PrivateSetRegisterValue (pair.first, reg_value_extractor);
1955 }
1956
Greg Clayton358cf1e2015-06-25 21:46:34 +00001957 thread_sp->SetName (thread_name.empty() ? NULL : thread_name.c_str());
1958
1959 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001960 // Check if the GDB server was able to provide the queue name, kind and serial number
1961 if (queue_vars_valid)
1962 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind, queue_serial);
1963 else
1964 gdb_thread->ClearQueueInfo();
1965
Greg Clayton2e309072015-07-17 23:42:28 +00001966 // Make sure we update our thread stop reason just once
1967 if (!thread_sp->StopInfoIsUpToDate())
Greg Clayton358cf1e2015-06-25 21:46:34 +00001968 {
Greg Clayton2e309072015-07-17 23:42:28 +00001969 thread_sp->SetStopInfo (StopInfoSP());
Greg Clayton358cf1e2015-06-25 21:46:34 +00001970
Greg Clayton2e309072015-07-17 23:42:28 +00001971 if (exc_type != 0)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001972 {
Greg Clayton2e309072015-07-17 23:42:28 +00001973 const size_t exc_data_size = exc_data.size();
1974
1975 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1976 exc_type,
1977 exc_data_size,
1978 exc_data_size >= 1 ? exc_data[0] : 0,
1979 exc_data_size >= 2 ? exc_data[1] : 0,
1980 exc_data_size >= 3 ? exc_data[2] : 0));
Greg Clayton358cf1e2015-06-25 21:46:34 +00001981 }
Greg Clayton2e309072015-07-17 23:42:28 +00001982 else
Greg Clayton358cf1e2015-06-25 21:46:34 +00001983 {
Greg Clayton2e309072015-07-17 23:42:28 +00001984 bool handled = false;
1985 bool did_exec = false;
1986 if (!reason.empty())
Greg Clayton358cf1e2015-06-25 21:46:34 +00001987 {
Greg Clayton2e309072015-07-17 23:42:28 +00001988 if (reason.compare("trace") == 0)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001989 {
Greg Clayton2e309072015-07-17 23:42:28 +00001990 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1991 handled = true;
1992 }
1993 else if (reason.compare("breakpoint") == 0)
1994 {
1995 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1996 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
1997 if (bp_site_sp)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001998 {
Greg Clayton2e309072015-07-17 23:42:28 +00001999 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2000 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2001 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2002 handled = true;
2003 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2004 {
2005 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2006 }
2007 else
2008 {
2009 StopInfoSP invalid_stop_info_sp;
2010 thread_sp->SetStopInfo (invalid_stop_info_sp);
2011 }
2012 }
2013 }
2014 else if (reason.compare("trap") == 0)
2015 {
2016 // Let the trap just use the standard signal stop reason below...
2017 }
2018 else if (reason.compare("watchpoint") == 0)
2019 {
2020 StringExtractor desc_extractor(description.c_str());
2021 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
2022 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
Jaydeep Patil83143502015-08-13 03:44:09 +00002023 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
Greg Clayton2e309072015-07-17 23:42:28 +00002024 watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
2025 if (wp_addr != LLDB_INVALID_ADDRESS)
2026 {
2027 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2028 if (wp_sp)
2029 {
2030 wp_sp->SetHardwareIndex(wp_index);
2031 watch_id = wp_sp->GetID();
2032 }
2033 }
2034 if (watch_id == LLDB_INVALID_WATCH_ID)
2035 {
2036 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_WATCHPOINTS));
2037 if (log) log->Printf ("failed to find watchpoint");
2038 }
Jaydeep Patil83143502015-08-13 03:44:09 +00002039 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id, wp_hit_addr));
Greg Clayton2e309072015-07-17 23:42:28 +00002040 handled = true;
2041 }
2042 else if (reason.compare("exception") == 0)
2043 {
2044 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
2045 handled = true;
2046 }
2047 else if (reason.compare("exec") == 0)
2048 {
2049 did_exec = true;
2050 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
2051 handled = true;
2052 }
2053 }
2054
2055 if (!handled && signo && did_exec == false)
2056 {
2057 if (signo == SIGTRAP)
2058 {
2059 // Currently we are going to assume SIGTRAP means we are either
2060 // hitting a breakpoint or hardware single stepping.
2061 handled = true;
2062 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
2063 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2064
2065 if (bp_site_sp)
2066 {
2067 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2068 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2069 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2070 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2071 {
2072 if(m_breakpoint_pc_offset != 0)
2073 thread_sp->GetRegisterContext()->SetPC(pc);
2074 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2075 }
2076 else
2077 {
2078 StopInfoSP invalid_stop_info_sp;
2079 thread_sp->SetStopInfo (invalid_stop_info_sp);
2080 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002081 }
2082 else
2083 {
Greg Clayton2e309072015-07-17 23:42:28 +00002084 // If we were stepping then assume the stop was the result of the trace. If we were
2085 // not stepping then report the SIGTRAP.
2086 // FIXME: We are still missing the case where we single step over a trap instruction.
2087 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
2088 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
2089 else
2090 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo, description.c_str()));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002091 }
2092 }
Greg Clayton2e309072015-07-17 23:42:28 +00002093 if (!handled)
2094 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo, description.c_str()));
2095 }
2096
2097 if (!description.empty())
2098 {
2099 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
2100 if (stop_info_sp)
2101 {
2102 const char *stop_info_desc = stop_info_sp->GetDescription();
2103 if (!stop_info_desc || !stop_info_desc[0])
2104 stop_info_sp->SetDescription (description.c_str());
2105 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002106 else
2107 {
Greg Clayton2e309072015-07-17 23:42:28 +00002108 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Clayton358cf1e2015-06-25 21:46:34 +00002109 }
2110 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002111 }
2112 }
2113 }
2114 }
2115 return thread_sp;
2116}
2117
Greg Clayton2e309072015-07-17 23:42:28 +00002118lldb::ThreadSP
Greg Clayton358cf1e2015-06-25 21:46:34 +00002119ProcessGDBRemote::SetThreadStopInfo (StructuredData::Dictionary *thread_dict)
2120{
2121 static ConstString g_key_tid("tid");
2122 static ConstString g_key_name("name");
2123 static ConstString g_key_reason("reason");
2124 static ConstString g_key_metype("metype");
2125 static ConstString g_key_medata("medata");
2126 static ConstString g_key_qaddr("qaddr");
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002127 static ConstString g_key_queue_name("qname");
2128 static ConstString g_key_queue_kind("qkind");
2129 static ConstString g_key_queue_serial("qserial");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002130 static ConstString g_key_registers("registers");
2131 static ConstString g_key_memory("memory");
2132 static ConstString g_key_address("address");
2133 static ConstString g_key_bytes("bytes");
2134 static ConstString g_key_description("description");
Pavel Labath4a4bb122015-07-16 14:14:35 +00002135 static ConstString g_key_signal("signal");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002136
2137 // Stop with signal and thread info
2138 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2139 uint8_t signo = 0;
2140 std::string value;
2141 std::string thread_name;
2142 std::string reason;
2143 std::string description;
2144 uint32_t exc_type = 0;
2145 std::vector<addr_t> exc_data;
2146 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2147 ExpeditedRegisterMap expedited_register_map;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002148 bool queue_vars_valid = false;
2149 std::string queue_name;
2150 QueueKind queue_kind = eQueueKindUnknown;
2151 uint64_t queue_serial = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002152 // Iterate through all of the thread dictionary key/value pairs from the structured data dictionary
2153
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002154 thread_dict->ForEach([this,
2155 &tid,
2156 &expedited_register_map,
2157 &thread_name,
2158 &signo,
2159 &reason,
2160 &description,
2161 &exc_type,
2162 &exc_data,
2163 &thread_dispatch_qaddr,
2164 &queue_vars_valid,
2165 &queue_name,
2166 &queue_kind,
2167 &queue_serial]
2168 (ConstString key, StructuredData::Object* object) -> bool
Greg Clayton358cf1e2015-06-25 21:46:34 +00002169 {
2170 if (key == g_key_tid)
2171 {
2172 // thread in big endian hex
2173 tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
2174 }
2175 else if (key == g_key_metype)
2176 {
2177 // exception type in big endian hex
2178 exc_type = object->GetIntegerValue(0);
2179 }
2180 else if (key == g_key_medata)
2181 {
2182 // exception data in big endian hex
2183 StructuredData::Array *array = object->GetAsArray();
2184 if (array)
2185 {
2186 array->ForEach([&exc_data](StructuredData::Object* object) -> bool {
2187 exc_data.push_back(object->GetIntegerValue());
2188 return true; // Keep iterating through all array items
2189 });
2190 }
2191 }
2192 else if (key == g_key_name)
2193 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002194 thread_name = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002195 }
2196 else if (key == g_key_qaddr)
2197 {
2198 thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
2199 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002200 else if (key == g_key_queue_name)
2201 {
2202 queue_vars_valid = true;
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002203 queue_name = object->GetStringValue();
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002204 }
2205 else if (key == g_key_queue_kind)
2206 {
2207 std::string queue_kind_str = object->GetStringValue();
2208 if (queue_kind_str == "serial")
2209 {
2210 queue_vars_valid = true;
2211 queue_kind = eQueueKindSerial;
2212 }
2213 else if (queue_kind_str == "concurrent")
2214 {
2215 queue_vars_valid = true;
2216 queue_kind = eQueueKindConcurrent;
2217 }
2218 }
2219 else if (key == g_key_queue_serial)
2220 {
2221 queue_serial = object->GetIntegerValue(0);
2222 if (queue_serial != 0)
2223 queue_vars_valid = true;
2224 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002225 else if (key == g_key_reason)
2226 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002227 reason = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002228 }
2229 else if (key == g_key_description)
2230 {
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002231 description = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002232 }
2233 else if (key == g_key_registers)
2234 {
2235 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2236
2237 if (registers_dict)
2238 {
2239 registers_dict->ForEach([&expedited_register_map](ConstString key, StructuredData::Object* object) -> bool {
2240 const uint32_t reg = StringConvert::ToUInt32 (key.GetCString(), UINT32_MAX, 10);
2241 if (reg != UINT32_MAX)
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002242 expedited_register_map[reg] = object->GetStringValue();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002243 return true; // Keep iterating through all array items
2244 });
2245 }
2246 }
2247 else if (key == g_key_memory)
2248 {
2249 StructuredData::Array *array = object->GetAsArray();
2250 if (array)
2251 {
2252 array->ForEach([this](StructuredData::Object* object) -> bool {
2253 StructuredData::Dictionary *mem_cache_dict = object->GetAsDictionary();
2254 if (mem_cache_dict)
2255 {
2256 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2257 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>("address", mem_cache_addr))
2258 {
2259 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
2260 {
2261 StringExtractor bytes;
2262 if (mem_cache_dict->GetValueForKeyAsString("bytes", bytes.GetStringRef()))
2263 {
2264 bytes.SetFilePos(0);
2265
2266 const size_t byte_size = bytes.GetStringRef().size()/2;
2267 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2268 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2269 if (bytes_copied == byte_size)
2270 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2271 }
2272 }
2273 }
2274 }
2275 return true; // Keep iterating through all array items
2276 });
2277 }
2278
2279 }
Pavel Labath4a4bb122015-07-16 14:14:35 +00002280 else if (key == g_key_signal)
2281 signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002282 return true; // Keep iterating through all dictionary key/value pairs
2283 });
2284
Greg Clayton2e309072015-07-17 23:42:28 +00002285 return SetThreadStopInfo (tid,
2286 expedited_register_map,
2287 signo,
2288 thread_name,
2289 reason,
2290 description,
2291 exc_type,
2292 exc_data,
2293 thread_dispatch_qaddr,
2294 queue_vars_valid,
2295 queue_name,
2296 queue_kind,
2297 queue_serial);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002298}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002299
2300StateType
2301ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
2302{
Greg Claytondd0e5a52011-06-02 22:22:38 +00002303 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002304 const char stop_type = stop_packet.GetChar();
2305 switch (stop_type)
2306 {
2307 case 'T':
2308 case 'S':
2309 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00002310 // This is a bit of a hack, but is is required. If we did exec, we
2311 // need to clear our thread lists and also know to rebuild our dynamic
2312 // register info before we lookup and threads and populate the expedited
2313 // register values so we need to know this right away so we can cleanup
2314 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00002315 const uint32_t stop_id = GetStopID();
2316 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00002317 {
2318 // Our first stop, make sure we have a process ID, and also make
2319 // sure we know about our registers
2320 if (GetID() == LLDB_INVALID_PROCESS_ID)
2321 {
Greg Claytonc574ede2011-03-10 02:26:48 +00002322 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00002323 if (pid != LLDB_INVALID_PROCESS_ID)
2324 SetID (pid);
2325 }
2326 BuildDynamicRegisterInfo (true);
2327 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002328 // Stop with signal and thread info
Greg Clayton358cf1e2015-06-25 21:46:34 +00002329 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002330 const uint8_t signo = stop_packet.GetHexU8();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002331 std::string key;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002332 std::string value;
2333 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00002334 std::string reason;
2335 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002336 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00002337 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002338 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton0b90be12015-06-23 21:27:50 +00002339 bool queue_vars_valid = false; // says if locals below that start with "queue_" are valid
2340 std::string queue_name;
2341 QueueKind queue_kind = eQueueKindUnknown;
2342 uint64_t queue_serial = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002343 ExpeditedRegisterMap expedited_register_map;
2344 while (stop_packet.GetNameColonValue(key, value))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002345 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002346 if (key.compare("metype") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002347 {
2348 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002349 exc_type = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002350 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002351 else if (key.compare("medata") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002352 {
2353 // exception data in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002354 exc_data.push_back(StringConvert::ToUInt64 (value.c_str(), 0, 16));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002355 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002356 else if (key.compare("thread") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002357 {
2358 // thread in big endian hex
Greg Clayton358cf1e2015-06-25 21:46:34 +00002359 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002360 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002361 else if (key.compare("threads") == 0)
Greg Clayton9e920902012-04-10 02:25:43 +00002362 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002363 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00002364 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00002365 // A comma separated list of all threads in the current
2366 // process that includes the thread for this stop reply
2367 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00002368 size_t comma_pos;
2369 lldb::tid_t tid;
2370 while ((comma_pos = value.find(',')) != std::string::npos)
2371 {
2372 value[comma_pos] = '\0';
2373 // thread in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002374 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00002375 if (tid != LLDB_INVALID_THREAD_ID)
2376 m_thread_ids.push_back (tid);
2377 value.erase(0, comma_pos + 1);
Greg Clayton9e920902012-04-10 02:25:43 +00002378 }
Vince Harron5275aaa2015-01-15 20:08:35 +00002379 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00002380 if (tid != LLDB_INVALID_THREAD_ID)
2381 m_thread_ids.push_back (tid);
2382 }
Greg Clayton2e309072015-07-17 23:42:28 +00002383 else if (key.compare("jstopinfo") == 0)
Greg Claytona5801ad2015-07-15 22:59:03 +00002384 {
2385 StringExtractor json_extractor;
2386 // Swap "value" over into "name_extractor"
2387 json_extractor.GetStringRef().swap(value);
2388 // Now convert the HEX bytes into a string value
2389 json_extractor.GetHexByteString (value);
2390
2391 // This JSON contains thread IDs and thread stop info for all threads.
2392 // It doesn't contain expedited registers, memory or queue info.
Greg Clayton2e309072015-07-17 23:42:28 +00002393 m_jstopinfo_sp = StructuredData::ParseJSON (value);
Greg Claytona5801ad2015-07-15 22:59:03 +00002394 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002395 else if (key.compare("hexname") == 0)
Greg Claytonde9d0492011-01-08 03:17:57 +00002396 {
2397 StringExtractor name_extractor;
2398 // Swap "value" over into "name_extractor"
2399 name_extractor.GetStringRef().swap(value);
2400 // Now convert the HEX bytes into a string value
2401 name_extractor.GetHexByteString (value);
2402 thread_name.swap (value);
2403 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002404 else if (key.compare("name") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002405 {
2406 thread_name.swap (value);
2407 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002408 else if (key.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002409 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002410 thread_dispatch_qaddr = StringConvert::ToUInt64 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002411 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002412 else if (key.compare("qname") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002413 {
2414 queue_vars_valid = true;
2415 StringExtractor name_extractor;
2416 // Swap "value" over into "name_extractor"
2417 name_extractor.GetStringRef().swap(value);
2418 // Now convert the HEX bytes into a string value
2419 name_extractor.GetHexByteString (value);
2420 queue_name.swap (value);
2421 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002422 else if (key.compare("qkind") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002423 {
Greg Clayton0b90be12015-06-23 21:27:50 +00002424 if (value == "serial")
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002425 {
2426 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002427 queue_kind = eQueueKindSerial;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002428 }
Greg Clayton0b90be12015-06-23 21:27:50 +00002429 else if (value == "concurrent")
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002430 {
2431 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002432 queue_kind = eQueueKindConcurrent;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002433 }
Greg Clayton0b90be12015-06-23 21:27:50 +00002434 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002435 else if (key.compare("qserial") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002436 {
Greg Clayton0b90be12015-06-23 21:27:50 +00002437 queue_serial = StringConvert::ToUInt64 (value.c_str(), 0, 0);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002438 if (queue_serial != 0)
2439 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002440 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002441 else if (key.compare("reason") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002442 {
2443 reason.swap(value);
2444 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002445 else if (key.compare("description") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002446 {
2447 StringExtractor desc_extractor;
2448 // Swap "value" over into "name_extractor"
2449 desc_extractor.GetStringRef().swap(value);
2450 // Now convert the HEX bytes into a string value
Chaoren Lin28e57422015-02-03 01:51:25 +00002451 desc_extractor.GetHexByteString (value);
2452 description.swap(value);
Greg Claytona658fd22011-06-04 01:26:29 +00002453 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002454 else if (key.compare("memory") == 0)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002455 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002456 // Expedited memory. GDB servers can choose to send back expedited memory
2457 // that can populate the L1 memory cache in the process so that things like
2458 // the frame pointer backchain can be expedited. This will help stack
2459 // backtracing be more efficient by not having to send as many memory read
2460 // requests down the remote GDB server.
Chaoren Lin7a306082015-06-23 03:17:01 +00002461
Greg Clayton358cf1e2015-06-25 21:46:34 +00002462 // Key/value pair format: memory:<addr>=<bytes>;
2463 // <addr> is a number whose base will be interpreted by the prefix:
2464 // "0x[0-9a-fA-F]+" for hex
2465 // "0[0-7]+" for octal
2466 // "[1-9]+" for decimal
2467 // <bytes> is native endian ASCII hex bytes just like the register values
2468 llvm::StringRef value_ref(value);
2469 std::pair<llvm::StringRef, llvm::StringRef> pair;
2470 pair = value_ref.split('=');
2471 if (!pair.first.empty() && !pair.second.empty())
2472 {
2473 std::string addr_str(pair.first.str());
2474 const lldb::addr_t mem_cache_addr = StringConvert::ToUInt64(addr_str.c_str(), LLDB_INVALID_ADDRESS, 0);
2475 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002476 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002477 StringExtractor bytes;
Pavel Labath3a29f8b2015-07-28 09:18:32 +00002478 bytes.GetStringRef() = pair.second.str();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002479 const size_t byte_size = bytes.GetStringRef().size()/2;
2480 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2481 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2482 if (bytes_copied == byte_size)
2483 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
Greg Clayton3e06bd92011-01-09 21:07:35 +00002484 }
2485 }
2486 }
Jaydeep Patil725666c2015-08-13 03:46:01 +00002487 else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 || key.compare("awatch") == 0)
2488 {
2489 // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2490 lldb::addr_t wp_addr = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
2491 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2492 uint32_t wp_index = LLDB_INVALID_INDEX32;
2493
2494 if (wp_sp)
2495 wp_index = wp_sp->GetHardwareIndex();
2496
2497 reason = "watchpoint";
2498 StreamString ostr;
2499 ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
2500 description = ostr.GetString().c_str();
2501 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002502 else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1]))
2503 {
2504 uint32_t reg = StringConvert::ToUInt32 (key.c_str(), UINT32_MAX, 16);
2505 if (reg != UINT32_MAX)
2506 expedited_register_map[reg] = std::move(value);
2507 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002508 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002509
Bhushan D. Attarde1e271df2015-07-24 04:06:20 +00002510 if (tid == LLDB_INVALID_THREAD_ID)
2511 {
2512 // A thread id may be invalid if the response is old style 'S' packet which does not provide the
2513 // thread information. So update the thread list and choose the first one.
2514 UpdateThreadIDList ();
2515
2516 if (!m_thread_ids.empty ())
2517 {
2518 tid = m_thread_ids.front ();
2519 }
2520 }
2521
Greg Clayton358cf1e2015-06-25 21:46:34 +00002522 ThreadSP thread_sp = SetThreadStopInfo (tid,
2523 expedited_register_map,
2524 signo,
2525 thread_name,
2526 reason,
2527 description,
2528 exc_type,
2529 exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002530 thread_dispatch_qaddr,
2531 queue_vars_valid,
2532 queue_name,
2533 queue_kind,
2534 queue_serial);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002535
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002536 return eStateStopped;
2537 }
2538 break;
2539
2540 case 'W':
Todd Fialaff6131a2014-05-19 04:57:23 +00002541 case 'X':
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002542 // process exited
2543 return eStateExited;
2544
2545 default:
2546 break;
2547 }
2548 return eStateInvalid;
2549}
2550
2551void
2552ProcessGDBRemote::RefreshStateAfterStop ()
2553{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002554 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00002555 m_thread_ids.clear();
2556 // Set the thread stop info. It might have a "threads" key whose value is
2557 // a list of all thread IDs in the current process, so m_thread_ids might
2558 // get set.
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002559
2560 // Scope for the lock
2561 {
2562 // Lock the thread stack while we access it
2563 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
2564 // Get the number of stop packets on the stack
2565 int nItems = m_stop_packet_stack.size();
2566 // Iterate over them
2567 for (int i = 0; i < nItems; i++)
2568 {
2569 // Get the thread stop info
2570 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2571 // Process thread stop info
2572 SetThreadStopInfo(stop_info);
2573 }
2574 // Clear the thread stop stack
2575 m_stop_packet_stack.clear();
2576 }
2577
Greg Clayton9e920902012-04-10 02:25:43 +00002578 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2579 if (m_thread_ids.empty())
2580 {
2581 // No, we need to fetch the thread list manually
2582 UpdateThreadIDList();
2583 }
2584
Ewan Crawford78baa192015-05-13 09:18:18 +00002585 // If we have queried for a default thread id
2586 if (m_initial_tid != LLDB_INVALID_THREAD_ID)
2587 {
2588 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2589 m_initial_tid = LLDB_INVALID_THREAD_ID;
2590 }
2591
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002592 // Let all threads recover from stopping and do any clean up based
2593 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002594 m_thread_list_real.RefreshStateAfterStop();
Greg Clayton9e920902012-04-10 02:25:43 +00002595
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002596}
2597
2598Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002599ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002600{
2601 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002602
Greg Clayton6ed95942011-01-22 07:12:45 +00002603 bool timed_out = false;
2604 Mutex::Locker locker;
Greg Clayton513c26c2011-01-29 07:10:55 +00002605
2606 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002607 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002608 // We are being asked to halt during an attach. We need to just close
2609 // our file handle and debugserver will go away, and we can be done...
2610 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00002611 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002612 else
2613 {
Greg Clayton2687cd12012-03-29 01:55:41 +00002614 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton513c26c2011-01-29 07:10:55 +00002615 {
2616 if (timed_out)
2617 error.SetErrorString("timed out sending interrupt packet");
2618 else
2619 error.SetErrorString("unknown error sending interrupt packet");
2620 }
Greg Clayton2687cd12012-03-29 01:55:41 +00002621
2622 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton513c26c2011-01-29 07:10:55 +00002623 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002624 return error;
2625}
2626
2627Error
Jim Inghamacff8952013-05-02 00:27:30 +00002628ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002629{
2630 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002631 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00002632 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00002633 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2634
Jim Inghamacff8952013-05-02 00:27:30 +00002635 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002636 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002637 {
Jim Inghamacff8952013-05-02 00:27:30 +00002638 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002639 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
2640 else
Jim Inghamacff8952013-05-02 00:27:30 +00002641 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00002642 }
Jim Inghamacff8952013-05-02 00:27:30 +00002643
2644 if (!error.Success())
2645 return error;
2646
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002647 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00002648 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002649
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002650 SetPrivateState (eStateDetached);
2651 ResumePrivateStateThread();
2652
2653 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00002654 return error;
2655}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002656
Jim Ingham43c555d2012-07-04 00:35:43 +00002657
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002658Error
2659ProcessGDBRemote::DoDestroy ()
2660{
2661 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002662 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002663 if (log)
2664 log->Printf ("ProcessGDBRemote::DoDestroy()");
2665
Jim Ingham43c555d2012-07-04 00:35:43 +00002666 // There is a bug in older iOS debugservers where they don't shut down the process
2667 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
2668 // this can cause problems with restarting. So we check to see if any of our threads are stopped
2669 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
2670 // destroy it again.
2671 //
2672 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
2673 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
2674 // the debugservers with this bug are equal. There really should be a better way to test this!
2675 //
2676 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
2677 // get called here to destroy again and we're still at a breakpoint or exception, then we should
2678 // just do the straight-forward kill.
2679 //
2680 // And of course, if we weren't able to stop the process by the time we get here, it isn't
2681 // necessary (or helpful) to do any of this.
2682
2683 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
2684 {
2685 PlatformSP platform_sp = GetTarget().GetPlatform();
2686
2687 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2688 if (platform_sp
2689 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00002690 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00002691 {
2692 if (m_destroy_tried_resuming)
2693 {
2694 if (log)
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002695 log->PutCString ("ProcessGDBRemote::DoDestroy() - Tried resuming to destroy once already, not doing it again.");
Jim Ingham43c555d2012-07-04 00:35:43 +00002696 }
2697 else
2698 {
2699 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
2700 // but we really need it to happen here and it doesn't matter if we do it twice.
2701 m_thread_list.DiscardThreadPlans();
2702 DisableAllBreakpointSites();
2703
2704 bool stop_looks_like_crash = false;
2705 ThreadList &threads = GetThreadList();
2706
2707 {
Jim Ingham45350372012-09-11 00:08:52 +00002708 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002709
2710 size_t num_threads = threads.GetSize();
2711 for (size_t i = 0; i < num_threads; i++)
2712 {
2713 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002714 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002715 StopReason reason = eStopReasonInvalid;
2716 if (stop_info_sp)
2717 reason = stop_info_sp->GetStopReason();
2718 if (reason == eStopReasonBreakpoint
2719 || reason == eStopReasonException)
2720 {
2721 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002722 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
2723 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00002724 stop_info_sp->GetDescription());
2725 stop_looks_like_crash = true;
2726 break;
2727 }
2728 }
2729 }
2730
2731 if (stop_looks_like_crash)
2732 {
2733 if (log)
2734 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
2735 m_destroy_tried_resuming = true;
2736
2737 // If we are going to run again before killing, it would be good to suspend all the threads
2738 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
2739 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
2740 // have to run the risk of letting those threads proceed a bit.
2741
2742 {
Jim Ingham45350372012-09-11 00:08:52 +00002743 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002744
2745 size_t num_threads = threads.GetSize();
2746 for (size_t i = 0; i < num_threads; i++)
2747 {
2748 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002749 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002750 StopReason reason = eStopReasonInvalid;
2751 if (stop_info_sp)
2752 reason = stop_info_sp->GetStopReason();
2753 if (reason != eStopReasonBreakpoint
2754 && reason != eStopReasonException)
2755 {
2756 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002757 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
2758 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00002759 thread_sp->SetResumeState(eStateSuspended);
2760 }
2761 }
2762 }
2763 Resume ();
Jason Molendaede31932015-04-17 05:01:58 +00002764 return Destroy(false);
Jim Ingham43c555d2012-07-04 00:35:43 +00002765 }
2766 }
2767 }
2768 }
2769
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002770 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00002771 int exit_status = SIGABRT;
2772 std::string exit_string;
2773
Greg Clayton6ed95942011-01-22 07:12:45 +00002774 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002775 {
Jim Inghamaab78372011-10-28 01:11:35 +00002776 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00002777 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002778 StringExtractorGDBRemote response;
2779 bool send_async = true;
Tamas Berghammer912800c2015-02-24 10:23:39 +00002780 GDBRemoteCommunication::ScopedTimeout (m_gdb_comm, 3);
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002781
Greg Clayton3dedae12013-12-06 21:45:27 +00002782 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton513c26c2011-01-29 07:10:55 +00002783 {
2784 char packet_cmd = response.GetChar(0);
2785
2786 if (packet_cmd == 'W' || packet_cmd == 'X')
2787 {
Jim Inghameac0aa42014-02-21 22:36:11 +00002788#if defined(__APPLE__)
Jim Ingham9d67cc52014-02-21 22:35:29 +00002789 // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off
2790 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill
2791 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns
2792 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap
2793 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of
2794 // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2795 // Anyway, so call waitpid here to finally reap it.
2796 PlatformSP platform_sp(GetTarget().GetPlatform());
2797 if (platform_sp && platform_sp->IsHost())
2798 {
2799 int status;
2800 ::pid_t reap_pid;
2801 reap_pid = waitpid (GetID(), &status, WNOHANG);
2802 if (log)
2803 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2804 }
2805#endif
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002806 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002807 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00002808 exit_status = response.GetHexU8();
2809 }
2810 else
2811 {
2812 if (log)
2813 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2814 exit_string.assign("got unexpected response to k packet: ");
2815 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00002816 }
2817 }
2818 else
2819 {
Jim Inghambabfc382012-06-06 00:32:39 +00002820 if (log)
2821 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2822 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00002823 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002824 }
Jim Inghambabfc382012-06-06 00:32:39 +00002825 else
2826 {
2827 if (log)
Ed Masteb3a53332014-03-17 17:05:22 +00002828 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching");
Jim Inghamcfc09352012-07-27 23:57:19 +00002829 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00002830 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002831 }
Jim Inghambabfc382012-06-06 00:32:39 +00002832 else
2833 {
2834 // If we missed setting the exit status on the way out, do it here.
2835 // NB set exit status can be called multiple times, the first one sets the status.
2836 exit_string.assign("destroying when not connected to debugserver");
2837 }
2838
2839 SetExitStatus(exit_status, exit_string.c_str());
2840
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002841 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002842 KillDebugserverProcess ();
2843 return error;
2844}
2845
Greg Clayton8cda7f02013-05-21 21:55:59 +00002846void
2847ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2848{
Greg Clayton8cda7f02013-05-21 21:55:59 +00002849 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2850 if (did_exec)
2851 {
2852 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2853 if (log)
2854 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2855
2856 m_thread_list_real.Clear();
2857 m_thread_list.Clear();
2858 BuildDynamicRegisterInfo (true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002859 m_gdb_comm.ResetDiscoverableSettings (did_exec);
Greg Clayton8cda7f02013-05-21 21:55:59 +00002860 }
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002861
2862 // Scope the lock
2863 {
2864 // Lock the thread stack while we access it
2865 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
Greg Clayton2e309072015-07-17 23:42:28 +00002866
2867 // We are are not using non-stop mode, there can only be one last stop
2868 // reply packet, so clear the list.
2869 if (GetTarget().GetNonStopModeEnabled() == false)
2870 m_stop_packet_stack.clear();
2871
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002872 // Add this stop packet to the stop packet stack
2873 // This stack will get popped and examined when we switch to the
2874 // Stopped state
2875 m_stop_packet_stack.push_back(response);
2876 }
Greg Clayton8cda7f02013-05-21 21:55:59 +00002877}
2878
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002879//------------------------------------------------------------------
2880// Process Queries
2881//------------------------------------------------------------------
2882
2883bool
2884ProcessGDBRemote::IsAlive ()
2885{
Greg Clayton10177aa2010-12-08 05:08:21 +00002886 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002887}
2888
2889addr_t
2890ProcessGDBRemote::GetImageInfoAddress()
2891{
Aidan Doddsc0c83852015-05-08 09:36:31 +00002892 // request the link map address via the $qShlibInfoAddr packet
2893 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2894
2895 // the loaded module list can also provides a link map address
2896 if (addr == LLDB_INVALID_ADDRESS)
2897 {
2898 GDBLoadedModuleInfoList list;
2899 if (GetLoadedModuleList (list).Success())
2900 addr = list.m_link_map;
2901 }
2902
2903 return addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002904}
2905
Greg Clayton2e309072015-07-17 23:42:28 +00002906void
2907ProcessGDBRemote::WillPublicStop ()
2908{
2909 // See if the GDB remote client supports the JSON threads info.
2910 // If so, we gather stop info for all threads, expedited registers,
2911 // expedited memory, runtime queue information (iOS and MacOSX only),
2912 // and more. Expediting memory will help stack backtracing be much
2913 // faster. Expediting registers will make sure we don't have to read
2914 // the thread registers for GPRs.
2915 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
2916
2917 if (m_jthreadsinfo_sp)
2918 {
2919 // Now set the stop info for each thread and also expedite any registers
2920 // and memory that was in the jThreadsInfo response.
2921 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
2922 if (thread_infos)
2923 {
2924 const size_t n = thread_infos->GetSize();
2925 for (size_t i=0; i<n; ++i)
2926 {
2927 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
2928 if (thread_dict)
2929 SetThreadStopInfo(thread_dict);
2930 }
2931 }
2932 }
2933}
2934
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002935//------------------------------------------------------------------
2936// Process Memory
2937//------------------------------------------------------------------
2938size_t
2939ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2940{
Jason Molenda6076bf42014-05-06 04:34:52 +00002941 GetMaxMemorySize ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002942 if (size > m_max_memory_size)
2943 {
2944 // Keep memory read sizes down to a sane limit. This function will be
2945 // called multiple times in order to complete the task by
2946 // lldb_private::Process so it is ok to do this.
2947 size = m_max_memory_size;
2948 }
2949
2950 char packet[64];
Jason Molenda6076bf42014-05-06 04:34:52 +00002951 int packet_len;
2952 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2953 if (binary_memory_read)
2954 {
2955 packet_len = ::snprintf (packet, sizeof(packet), "x0x%" PRIx64 ",0x%" PRIx64, (uint64_t)addr, (uint64_t)size);
2956 }
2957 else
2958 {
2959 packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
2960 }
Andy Gibbsa297a972013-06-19 19:04:53 +00002961 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002962 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002963 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002964 {
Greg Clayton576d8832011-03-22 04:00:09 +00002965 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002966 {
2967 error.Clear();
Jason Molenda6076bf42014-05-06 04:34:52 +00002968 if (binary_memory_read)
2969 {
2970 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any
2971 // 0x7d character escaping that was present in the packet
2972
2973 size_t data_received_size = response.GetBytesLeft();
2974 if (data_received_size > size)
2975 {
2976 // Don't write past the end of BUF if the remote debug server gave us too
2977 // much data for some reason.
2978 data_received_size = size;
2979 }
2980 memcpy (buf, response.GetStringRef().data(), data_received_size);
2981 return data_received_size;
2982 }
2983 else
2984 {
2985 return response.GetHexBytes(buf, size, '\xdd');
2986 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002987 }
Greg Clayton576d8832011-03-22 04:00:09 +00002988 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002989 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002990 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002991 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002992 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002993 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002994 }
2995 else
2996 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002997 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002998 }
2999 return 0;
3000}
3001
3002size_t
3003ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
3004{
Jason Molenda6076bf42014-05-06 04:34:52 +00003005 GetMaxMemorySize ();
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00003006 if (size > m_max_memory_size)
3007 {
3008 // Keep memory read sizes down to a sane limit. This function will be
3009 // called multiple times in order to complete the task by
3010 // lldb_private::Process so it is ok to do this.
3011 size = m_max_memory_size;
3012 }
3013
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003014 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00003015 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Clayton7fb56d02011-02-01 01:31:41 +00003016 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003017 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003018 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003019 {
Greg Clayton576d8832011-03-22 04:00:09 +00003020 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003021 {
3022 error.Clear();
3023 return size;
3024 }
Greg Clayton576d8832011-03-22 04:00:09 +00003025 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00003026 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00003027 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00003028 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003029 else
Greg Clayton9944cd72012-09-19 01:46:31 +00003030 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 +00003031 }
3032 else
3033 {
Jim Ingham35579dd2013-06-03 19:34:01 +00003034 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003035 }
3036 return 0;
3037}
3038
3039lldb::addr_t
3040ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
3041{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003042 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_EXPRESSIONS));
Greg Clayton2a48f522011-05-14 01:50:35 +00003043 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
3044
Greg Clayton70b57652011-05-15 01:25:55 +00003045 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton2a48f522011-05-14 01:50:35 +00003046 switch (supported)
3047 {
3048 case eLazyBoolCalculate:
3049 case eLazyBoolYes:
3050 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
3051 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
3052 return allocated_addr;
3053
3054 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003055 // Call mmap() to create memory in the inferior..
3056 unsigned prot = 0;
3057 if (permissions & lldb::ePermissionsReadable)
3058 prot |= eMmapProtRead;
3059 if (permissions & lldb::ePermissionsWritable)
3060 prot |= eMmapProtWrite;
3061 if (permissions & lldb::ePermissionsExecutable)
3062 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00003063
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003064 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
3065 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
3066 m_addr_to_mmap_size[allocated_addr] = size;
3067 else
Todd Fialaaf245d12014-06-30 21:05:18 +00003068 {
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003069 allocated_addr = LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00003070 if (log)
3071 log->Printf ("ProcessGDBRemote::%s no direct stub support for memory allocation, and InferiorCallMmap also failed - is stub missing register context save/restore capability?", __FUNCTION__);
3072 }
Greg Clayton2a48f522011-05-14 01:50:35 +00003073 break;
3074 }
3075
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003076 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00003077 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003078 else
3079 error.Clear();
3080 return allocated_addr;
3081}
3082
3083Error
Greg Clayton46fb5582011-11-18 07:03:08 +00003084ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
3085 MemoryRegionInfo &region_info)
3086{
3087
3088 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
3089 return error;
3090}
3091
3092Error
Johnny Chen64637202012-05-23 21:09:52 +00003093ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
3094{
3095
3096 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
3097 return error;
3098}
3099
3100Error
Enrico Granataf04a2192012-07-13 23:18:48 +00003101ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
3102{
Jaydeep Patil725666c2015-08-13 03:46:01 +00003103 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after, GetTarget().GetArchitecture()));
Enrico Granataf04a2192012-07-13 23:18:48 +00003104 return error;
3105}
3106
3107Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003108ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
3109{
3110 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00003111 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
3112
3113 switch (supported)
3114 {
3115 case eLazyBoolCalculate:
3116 // We should never be deallocating memory without allocating memory
3117 // first so we should never get eLazyBoolCalculate
3118 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
3119 break;
3120
3121 case eLazyBoolYes:
3122 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00003123 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003124 break;
3125
3126 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003127 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00003128 {
3129 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003130 if (pos != m_addr_to_mmap_size.end() &&
3131 InferiorCallMunmap(this, addr, pos->second))
3132 m_addr_to_mmap_size.erase (pos);
3133 else
Daniel Malead01b2952012-11-29 21:49:15 +00003134 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003135 }
3136 break;
3137 }
3138
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003139 return error;
3140}
3141
3142
3143//------------------------------------------------------------------
3144// Process STDIO
3145//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003146size_t
3147ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
3148{
3149 if (m_stdio_communication.IsConnected())
3150 {
3151 ConnectionStatus status;
3152 m_stdio_communication.Write(src, src_len, status, NULL);
3153 }
Vince Harrondf3f00f2015-02-10 21:09:04 +00003154 else if (m_stdin_forward)
Vince Harrone0be4252015-02-06 18:32:57 +00003155 {
3156 m_gdb_comm.SendStdinNotification(src, src_len);
3157 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003158 return 0;
3159}
3160
3161Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003162ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003163{
3164 Error error;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003165 assert(bp_site != NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003166
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003167 // Get logging info
3168 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003169 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003170
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003171 // Get the breakpoint address
3172 const addr_t addr = bp_site->GetLoadAddress();
3173
3174 // Log that a breakpoint was requested
3175 if (log)
3176 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
3177
3178 // Breakpoint already exists and is enabled
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003179 if (bp_site->IsEnabled())
3180 {
3181 if (log)
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003182 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 +00003183 return error;
3184 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003185
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003186 // Get the software breakpoint trap opcode size
3187 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3188
3189 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
3190 // is supported by the remote stub. These are set to true by default, and later set to false
3191 // only after we receive an unimplemented response when sending a breakpoint packet. This means
3192 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
3193 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
3194 // indicates if the user specifically asked for hardware breakpoints. If true then we will
3195 // skip over software breakpoints.
3196 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
3197 {
3198 // Try to send off a software breakpoint packet ($Z0)
3199 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003200 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003201 // The breakpoint was placed successfully
3202 bp_site->SetEnabled(true);
3203 bp_site->SetType(BreakpointSite::eExternal);
Greg Claytoneb023e72013-10-11 19:48:25 +00003204 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003205 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003206
3207 // SendGDBStoppointTypePacket() will return an error if it was unable to set this
3208 // breakpoint. We need to differentiate between a error specific to placing this breakpoint
3209 // or if we have learned that this breakpoint type is unsupported. To do this, we
3210 // must test the support boolean for this breakpoint type to see if it now indicates that
3211 // this breakpoint type is unsupported. If they are still supported then we should return
3212 // with the error code. If they are now unsupported, then we would like to fall through
3213 // and try another form of breakpoint.
3214 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
3215 return error;
3216
3217 // We reach here when software breakpoints have been found to be unsupported. For future
3218 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
3219 // known not to be supported.
3220 if (log)
3221 log->Printf("Software breakpoints are unsupported");
3222
3223 // So we will fall through and try a hardware breakpoint
3224 }
3225
3226 // The process of setting a hardware breakpoint is much the same as above. We check the
3227 // supported boolean for this breakpoint type, and if it is thought to be supported then we
3228 // will try to set this breakpoint with a hardware breakpoint.
3229 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3230 {
3231 // Try to send off a hardware breakpoint packet ($Z1)
3232 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003233 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003234 // The breakpoint was placed successfully
3235 bp_site->SetEnabled(true);
3236 bp_site->SetType(BreakpointSite::eHardware);
3237 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003238 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003239
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003240 // Check if the error was something other then an unsupported breakpoint type
3241 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3242 {
3243 // Unable to set this hardware breakpoint
3244 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
3245 return error;
3246 }
3247
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003248 // We will reach here when the stub gives an unsupported response to a hardware breakpoint
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003249 if (log)
3250 log->Printf("Hardware breakpoints are unsupported");
3251
3252 // Finally we will falling through to a #trap style breakpoint
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003253 }
3254
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003255 // Don't fall through when hardware breakpoints were specifically requested
3256 if (bp_site->HardwareRequired())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003257 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003258 error.SetErrorString("hardware breakpoints are not supported");
3259 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003260 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003261
3262 // As a last resort we want to place a manual breakpoint. An instruction
3263 // is placed into the process memory using memory write packets.
3264 return EnableSoftwareBreakpoint(bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003265}
3266
3267Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003268ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003269{
3270 Error error;
3271 assert (bp_site != NULL);
3272 addr_t addr = bp_site->GetLoadAddress();
3273 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00003274 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003275 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003276 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003277
3278 if (bp_site->IsEnabled())
3279 {
3280 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
3281
Greg Clayton8b82f082011-04-12 05:54:46 +00003282 BreakpointSite::Type bp_type = bp_site->GetType();
3283 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003284 {
Greg Clayton8b82f082011-04-12 05:54:46 +00003285 case BreakpointSite::eSoftware:
3286 error = DisableSoftwareBreakpoint (bp_site);
3287 break;
3288
3289 case BreakpointSite::eHardware:
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003290 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003291 error.SetErrorToGenericError();
3292 break;
3293
3294 case BreakpointSite::eExternal:
Jim Inghama04ef752014-03-07 11:18:02 +00003295 {
3296 GDBStoppointType stoppoint_type;
3297 if (bp_site->IsHardware())
3298 stoppoint_type = eBreakpointHardware;
3299 else
3300 stoppoint_type = eBreakpointSoftware;
3301
3302 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003303 error.SetErrorToGenericError();
Jim Inghama04ef752014-03-07 11:18:02 +00003304 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003305 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003306 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003307 if (error.Success())
3308 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003309 }
3310 else
3311 {
3312 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003313 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 +00003314 return error;
3315 }
3316
3317 if (error.Success())
3318 error.SetErrorToGenericError();
3319 return error;
3320}
3321
Johnny Chen11309a32011-09-06 22:38:36 +00003322// Pre-requisite: wp != NULL.
3323static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00003324GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00003325{
3326 assert(wp);
3327 bool watch_read = wp->WatchpointRead();
3328 bool watch_write = wp->WatchpointWrite();
3329
3330 // watch_read and watch_write cannot both be false.
3331 assert(watch_read || watch_write);
3332 if (watch_read && watch_write)
3333 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00003334 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00003335 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00003336 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00003337 return eWatchpointWrite;
3338}
3339
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003340Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003341ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003342{
3343 Error error;
3344 if (wp)
3345 {
3346 user_id_t watchID = wp->GetID();
3347 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00003348 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003349 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003350 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003351 if (wp->IsEnabled())
3352 {
3353 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003354 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 +00003355 return error;
3356 }
Johnny Chen11309a32011-09-06 22:38:36 +00003357
3358 GDBStoppointType type = GetGDBStoppointType(wp);
3359 // Pass down an appropriate z/Z packet...
3360 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003361 {
Johnny Chen11309a32011-09-06 22:38:36 +00003362 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
3363 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003364 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003365 return error;
3366 }
3367 else
3368 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003369 }
Johnny Chen11309a32011-09-06 22:38:36 +00003370 else
3371 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003372 }
3373 else
3374 {
Johnny Chen01a67862011-10-14 00:42:25 +00003375 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003376 }
3377 if (error.Success())
3378 error.SetErrorToGenericError();
3379 return error;
3380}
3381
3382Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003383ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003384{
3385 Error error;
3386 if (wp)
3387 {
3388 user_id_t watchID = wp->GetID();
3389
Greg Clayton5160ce52013-03-27 23:08:40 +00003390 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003391
3392 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00003393
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003394 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003395 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003396
Johnny Chen11309a32011-09-06 22:38:36 +00003397 if (!wp->IsEnabled())
3398 {
3399 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003400 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 +00003401 // See also 'class WatchpointSentry' within StopInfo.cpp.
3402 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
3403 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00003404 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003405 return error;
3406 }
3407
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003408 if (wp->IsHardware())
3409 {
Johnny Chen11309a32011-09-06 22:38:36 +00003410 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003411 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00003412 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
3413 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003414 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003415 return error;
3416 }
3417 else
3418 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003419 }
3420 // TODO: clear software watchpoints if we implement them
3421 }
3422 else
3423 {
Johnny Chen01a67862011-10-14 00:42:25 +00003424 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003425 }
3426 if (error.Success())
3427 error.SetErrorToGenericError();
3428 return error;
3429}
3430
3431void
3432ProcessGDBRemote::Clear()
3433{
3434 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00003435 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003436 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003437}
3438
3439Error
3440ProcessGDBRemote::DoSignal (int signo)
3441{
3442 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00003443 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003444 if (log)
3445 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
3446
3447 if (!m_gdb_comm.SendAsyncSignal (signo))
3448 error.SetErrorStringWithFormat("failed to send signal %i", signo);
3449 return error;
3450}
3451
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003452Error
Greg Clayton91a9b2472013-12-04 19:19:12 +00003453ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003454{
3455 Error error;
3456 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
3457 {
3458 // If we locate debugserver, keep that located version around
3459 static FileSpec g_debugserver_file_spec;
3460
Han Ming Ong84647042012-02-25 01:07:38 +00003461 ProcessLaunchInfo debugserver_launch_info;
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00003462 // Make debugserver run in its own session so signals generated by
3463 // special terminal key sequences (^C) don't affect debugserver.
3464 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3465
Greg Clayton91a9b2472013-12-04 19:19:12 +00003466 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
3467 debugserver_launch_info.SetUserID(process_info.GetUserID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003468
Todd Fiala013434e2014-07-09 01:29:05 +00003469#if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__) || defined (__aarch64__))
Greg Claytonfda4fab2014-01-10 22:24:11 +00003470 // On iOS, still do a local connection using a random port
Greg Clayton16810922014-02-27 19:38:18 +00003471 const char *hostname = "127.0.0.1";
Greg Claytonfda4fab2014-01-10 22:24:11 +00003472 uint16_t port = get_random_port ();
3473#else
3474 // Set hostname being NULL to do the reverse connect where debugserver
3475 // will bind to port zero and it will communicate back to us the port
3476 // that we will connect to
3477 const char *hostname = NULL;
3478 uint16_t port = 0;
3479#endif
3480
3481 error = m_gdb_comm.StartDebugserverProcess (hostname,
3482 port,
Greg Clayton00fe87b2013-12-05 22:58:22 +00003483 debugserver_launch_info,
3484 port);
Greg Clayton91a9b2472013-12-04 19:19:12 +00003485
3486 if (error.Success ())
3487 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003488 else
Greg Clayton91a9b2472013-12-04 19:19:12 +00003489 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003490
3491 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3492 StartAsyncThread ();
Greg Clayton91a9b2472013-12-04 19:19:12 +00003493
3494 if (error.Fail())
3495 {
3496 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
3497
3498 if (log)
3499 log->Printf("failed to start debugserver process: %s", error.AsCString());
3500 return error;
3501 }
3502
Greg Clayton00fe87b2013-12-05 22:58:22 +00003503 if (m_gdb_comm.IsConnected())
3504 {
3505 // Finish the connection process by doing the handshake without connecting (send NULL URL)
3506 ConnectToDebugserver (NULL);
3507 }
3508 else
3509 {
Greg Claytonfda4fab2014-01-10 22:24:11 +00003510 StreamString connect_url;
3511 connect_url.Printf("connect://%s:%u", hostname, port);
3512 error = ConnectToDebugserver (connect_url.GetString().c_str());
Greg Clayton00fe87b2013-12-05 22:58:22 +00003513 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00003514
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003515 }
3516 return error;
3517}
3518
3519bool
3520ProcessGDBRemote::MonitorDebugserverProcess
3521(
3522 void *callback_baton,
3523 lldb::pid_t debugserver_pid,
Greg Claytone4e45922011-11-16 05:37:56 +00003524 bool exited, // True if the process did exit
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003525 int signo, // Zero for no signal
3526 int exit_status // Exit value of process if signal is zero
3527)
3528{
Greg Claytone4e45922011-11-16 05:37:56 +00003529 // The baton is a "ProcessGDBRemote *". Now this class might be gone
3530 // and might not exist anymore, so we need to carefully try to get the
3531 // target for this process first since we have a race condition when
3532 // we are done running between getting the notice that the inferior
3533 // process has died and the debugserver that was debugging this process.
3534 // In our test suite, we are also continually running process after
3535 // process, so we must be very careful to make sure:
3536 // 1 - process object hasn't been deleted already
3537 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003538
3539 // "debugserver_pid" argument passed in is the process ID for
3540 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00003541 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003542
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003543 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton6779606a2011-01-22 23:43:18 +00003544
Greg Claytone4e45922011-11-16 05:37:56 +00003545 // Get a shared pointer to the target that has a matching process pointer.
3546 // This target could be gone, or the target could already have a new process
3547 // object inside of it
3548 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
3549
Greg Clayton6779606a2011-01-22 23:43:18 +00003550 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003551 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 +00003552
Greg Claytone4e45922011-11-16 05:37:56 +00003553 if (target_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003554 {
Greg Claytone4e45922011-11-16 05:37:56 +00003555 // We found a process in a target that matches, but another thread
3556 // might be in the process of launching a new process that will
3557 // soon replace it, so get a shared pointer to the process so we
3558 // can keep it alive.
3559 ProcessSP process_sp (target_sp->GetProcessSP());
3560 // Now we have a shared pointer to the process that can't go away on us
3561 // so we now make sure it was the same as the one passed in, and also make
3562 // sure that our previous "process *" didn't get deleted and have a new
3563 // "process *" created in its place with the same pointer. To verify this
3564 // we make sure the process has our debugserver process ID. If we pass all
3565 // of these tests, then we are sure that this process is the one we were
3566 // looking for.
3567 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003568 {
Greg Claytone4e45922011-11-16 05:37:56 +00003569 // Sleep for a half a second to make sure our inferior process has
3570 // time to set its exit status before we set it incorrectly when
3571 // both the debugserver and the inferior process shut down.
3572 usleep (500000);
3573 // If our process hasn't yet exited, debugserver might have died.
3574 // If the process did exit, the we are reaping it.
3575 const StateType state = process->GetState();
3576
3577 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
3578 state != eStateInvalid &&
3579 state != eStateUnloaded &&
3580 state != eStateExited &&
3581 state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003582 {
Greg Claytone4e45922011-11-16 05:37:56 +00003583 char error_str[1024];
3584 if (signo)
3585 {
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00003586 const char *signal_cstr = process->GetUnixSignals()->GetSignalAsCString(signo);
Greg Claytone4e45922011-11-16 05:37:56 +00003587 if (signal_cstr)
3588 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3589 else
3590 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
3591 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003592 else
Greg Claytone4e45922011-11-16 05:37:56 +00003593 {
3594 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
3595 }
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003596
Greg Claytone4e45922011-11-16 05:37:56 +00003597 process->SetExitStatus (-1, error_str);
3598 }
3599 // Debugserver has exited we need to let our ProcessGDBRemote
3600 // know that it no longer has a debugserver instance
3601 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003602 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003603 }
3604 return true;
3605}
3606
3607void
3608ProcessGDBRemote::KillDebugserverProcess ()
3609{
Greg Claytonfbb76342013-11-20 21:07:01 +00003610 m_gdb_comm.Disconnect();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003611 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3612 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003613 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003614 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3615 }
3616}
3617
3618void
3619ProcessGDBRemote::Initialize()
3620{
Davide Italianoc8d69822015-04-03 04:24:32 +00003621 static std::once_flag g_once_flag;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003622
Davide Italianoc8d69822015-04-03 04:24:32 +00003623 std::call_once(g_once_flag, []()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003624 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003625 PluginManager::RegisterPlugin (GetPluginNameStatic(),
3626 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00003627 CreateInstance,
3628 DebuggerInitialize);
Davide Italianoc8d69822015-04-03 04:24:32 +00003629 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003630}
3631
Greg Clayton7f982402013-07-15 22:54:20 +00003632void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003633ProcessGDBRemote::DebuggerInitialize (Debugger &debugger)
Greg Clayton7f982402013-07-15 22:54:20 +00003634{
3635 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
3636 {
3637 const bool is_global_setting = true;
3638 PluginManager::CreateSettingForProcessPlugin (debugger,
3639 GetGlobalPluginProperties()->GetValueProperties(),
3640 ConstString ("Properties for the gdb-remote process plug-in."),
3641 is_global_setting);
3642 }
3643}
3644
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003645bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003646ProcessGDBRemote::StartAsyncThread ()
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__);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003652
3653 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003654 if (!m_async_thread.IsJoinable())
Jim Ingham455fa5c2012-11-01 01:15:33 +00003655 {
3656 // Create a thread that watches our internal state and controls which
3657 // events make it to clients (into the DCProcess event queue).
Zachary Turner39de3112014-09-09 20:54:56 +00003658
3659 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003660 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003661 else if (log)
3662 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was already running.", __FUNCTION__);
Zachary Turner39de3112014-09-09 20:54:56 +00003663
Zachary Turneracee96a2014-09-23 18:32:09 +00003664 return m_async_thread.IsJoinable();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003665}
3666
3667void
3668ProcessGDBRemote::StopAsyncThread ()
3669{
Greg Clayton5160ce52013-03-27 23:08:40 +00003670 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003671
3672 if (log)
3673 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
3674
Jim Ingham455fa5c2012-11-01 01:15:33 +00003675 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003676 if (m_async_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003677 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00003678 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
3679
3680 // This will shut down the async thread.
3681 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3682
3683 // Stop the stdio thread
Zachary Turner39de3112014-09-09 20:54:56 +00003684 m_async_thread.Join(nullptr);
Pavel Labatha55a9532015-03-11 09:53:42 +00003685 m_async_thread.Reset();
Jim Ingham455fa5c2012-11-01 01:15:33 +00003686 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003687 else if (log)
3688 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003689}
3690
Ewan Crawford76df2882015-06-23 12:32:06 +00003691bool
3692ProcessGDBRemote::HandleNotifyPacket (StringExtractorGDBRemote &packet)
3693{
3694 // get the packet at a string
3695 const std::string &pkt = packet.GetStringRef();
3696 // skip %stop:
3697 StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
3698
3699 // pass as a thread stop info packet
3700 SetLastStopPacket(stop_info);
3701
3702 // check for more stop reasons
3703 HandleStopReplySequence();
3704
3705 // if the process is stopped then we need to fake a resume
3706 // so that we can stop properly with the new break. This
3707 // is possible due to SetPrivateState() broadcasting the
3708 // state change as a side effect.
3709 if (GetPrivateState() == lldb::StateType::eStateStopped)
3710 {
3711 SetPrivateState(lldb::StateType::eStateRunning);
3712 }
3713
3714 // since we have some stopped packets we can halt the process
3715 SetPrivateState(lldb::StateType::eStateStopped);
3716
3717 return true;
3718}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003719
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003720thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003721ProcessGDBRemote::AsyncThread (void *arg)
3722{
3723 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
3724
Greg Clayton5160ce52013-03-27 23:08:40 +00003725 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003726 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003727 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003728
3729 Listener listener ("ProcessGDBRemote::AsyncThread");
3730 EventSP event_sp;
3731 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
3732 eBroadcastBitAsyncThreadShouldExit;
3733
3734 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
3735 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003736 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit |
3737 GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify);
3738
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003739 bool done = false;
3740 while (!done)
3741 {
3742 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003743 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003744 if (listener.WaitForEvent (NULL, event_sp))
3745 {
3746 const uint32_t event_type = event_sp->GetType();
Greg Clayton71337622011-02-24 22:24:29 +00003747 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003748 {
Greg Clayton71337622011-02-24 22:24:29 +00003749 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003750 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 +00003751
Greg Clayton71337622011-02-24 22:24:29 +00003752 switch (event_type)
3753 {
3754 case eBroadcastBitAsyncContinue:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003755 {
Greg Clayton71337622011-02-24 22:24:29 +00003756 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003757
Greg Clayton71337622011-02-24 22:24:29 +00003758 if (continue_packet)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003759 {
Greg Clayton71337622011-02-24 22:24:29 +00003760 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
3761 const size_t continue_cstr_len = continue_packet->GetByteSize ();
3762 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003763 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003764
Greg Clayton71337622011-02-24 22:24:29 +00003765 if (::strstr (continue_cstr, "vAttach") == NULL)
3766 process->SetPrivateState(eStateRunning);
3767 StringExtractorGDBRemote response;
Ewan Crawford76df2882015-06-23 12:32:06 +00003768
3769 // If in Non-Stop-Mode
3770 if (process->GetTarget().GetNonStopModeEnabled())
Greg Clayton71337622011-02-24 22:24:29 +00003771 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003772 // send the vCont packet
3773 if (!process->GetGDBRemote().SendvContPacket(process, continue_cstr, continue_cstr_len, response))
Jason Molendaa3329782014-03-29 18:54:20 +00003774 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003775 // Something went wrong
3776 done = true;
3777 break;
3778 }
3779 }
3780 // If in All-Stop-Mode
3781 else
3782 {
3783 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
3784
3785 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
3786 // The thread ID list might be contained within the "response", or the stop reply packet that
3787 // caused the stop. So clear it now before we give the stop reply packet to the process
3788 // using the process->SetLastStopPacket()...
3789 process->ClearThreadIDList ();
3790
3791 switch (stop_state)
3792 {
3793 case eStateStopped:
3794 case eStateCrashed:
3795 case eStateSuspended:
3796 process->SetLastStopPacket (response);
3797 process->SetPrivateState (stop_state);
3798 break;
3799
3800 case eStateExited:
3801 {
3802 process->SetLastStopPacket (response);
3803 process->ClearThreadIDList();
3804 response.SetFilePos(1);
3805
3806 int exit_status = response.GetHexU8();
3807 const char *desc_cstr = NULL;
3808 StringExtractor extractor;
3809 std::string desc_string;
3810 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';')
Jason Molendaa3329782014-03-29 18:54:20 +00003811 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003812 std::string desc_token;
3813 while (response.GetNameColonValue (desc_token, desc_string))
Jason Molendaa3329782014-03-29 18:54:20 +00003814 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003815 if (desc_token == "description")
3816 {
3817 extractor.GetStringRef().swap(desc_string);
3818 extractor.SetFilePos(0);
3819 extractor.GetHexByteString (desc_string);
3820 desc_cstr = desc_string.c_str();
3821 }
Jason Molendaa3329782014-03-29 18:54:20 +00003822 }
3823 }
Ewan Crawford76df2882015-06-23 12:32:06 +00003824 process->SetExitStatus(exit_status, desc_cstr);
3825 done = true;
3826 break;
Jason Molendaa3329782014-03-29 18:54:20 +00003827 }
Ewan Crawford76df2882015-06-23 12:32:06 +00003828 case eStateInvalid:
Jason Molenda752e1e82015-07-29 01:42:16 +00003829 {
3830 // Check to see if we were trying to attach and if we got back
3831 // the "E87" error code from debugserver -- this indicates that
3832 // the process is not debuggable. Return a slightly more helpful
3833 // error message about why the attach failed.
3834 if (::strstr (continue_cstr, "vAttach") != NULL
3835 && response.GetError() == 0x87)
3836 {
3837 process->SetExitStatus(-1, "cannot attach to process due to System Integrity Protection");
3838 }
3839 // E01 code from vAttach means that the attach failed
3840 if (::strstr (continue_cstr, "vAttach") != NULL
3841 && response.GetError() == 0x1)
3842 {
3843 process->SetExitStatus(-1, "unable to attach");
3844 }
3845 else
3846 {
3847 process->SetExitStatus(-1, "lost connection");
3848 }
3849 break;
3850 }
Greg Clayton71337622011-02-24 22:24:29 +00003851
Ewan Crawford76df2882015-06-23 12:32:06 +00003852 default:
3853 process->SetPrivateState (stop_state);
3854 break;
3855 } // switch(stop_state)
3856 } // else // if in All-stop-mode
3857 } // if (continue_packet)
3858 } // case eBroadcastBitAysncContinue
Greg Clayton71337622011-02-24 22:24:29 +00003859 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003860
Greg Clayton71337622011-02-24 22:24:29 +00003861 case eBroadcastBitAsyncThreadShouldExit:
3862 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003863 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Clayton71337622011-02-24 22:24:29 +00003864 done = true;
3865 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003866
Greg Clayton71337622011-02-24 22:24:29 +00003867 default:
3868 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003869 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 +00003870 done = true;
3871 break;
3872 }
3873 }
3874 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
3875 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003876 switch (event_type)
Greg Clayton71337622011-02-24 22:24:29 +00003877 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003878 case Communication::eBroadcastBitReadThreadDidExit:
3879 process->SetExitStatus (-1, "lost connection");
3880 done = true;
3881 break;
3882
3883 case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify:
3884 {
3885 lldb_private::Event *event = event_sp.get();
3886 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event);
3887 StringExtractorGDBRemote notify((const char*)continue_packet->GetBytes());
3888 // Hand this over to the process to handle
3889 process->HandleNotifyPacket(notify);
3890 break;
3891 }
3892
3893 default:
3894 if (log)
3895 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
3896 done = true;
3897 break;
Greg Clayton71337622011-02-24 22:24:29 +00003898 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003899 }
3900 }
3901 else
3902 {
3903 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003904 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 +00003905 done = true;
3906 }
3907 }
3908 }
3909
3910 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003911 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003912
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003913 return NULL;
3914}
3915
Greg Claytone996fd32011-03-08 22:40:15 +00003916//uint32_t
3917//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3918//{
3919// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
3920// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
3921// if (m_local_debugserver)
3922// {
3923// return Host::ListProcessesMatchingName (name, matches, pids);
3924// }
3925// else
3926// {
3927// // FIXME: Implement talking to the remote debugserver.
3928// return 0;
3929// }
3930//
3931//}
3932//
Jim Ingham1c823b42011-01-22 01:33:44 +00003933bool
3934ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003935 StoppointCallbackContext *context,
Jim Ingham1c823b42011-01-22 01:33:44 +00003936 lldb::user_id_t break_id,
3937 lldb::user_id_t break_loc_id)
3938{
3939 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3940 // run so I can stop it if that's what I want to do.
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003941 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00003942 if (log)
3943 log->Printf("Hit New Thread Notification breakpoint.");
3944 return false;
3945}
3946
3947
3948bool
3949ProcessGDBRemote::StartNoticingNewThreads()
3950{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003951 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00003952 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003953 {
Greg Clayton4116e932012-05-15 02:33:01 +00003954 if (log && log->GetVerbose())
3955 log->Printf("Enabled noticing new thread breakpoint.");
3956 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003957 }
Greg Clayton4116e932012-05-15 02:33:01 +00003958 else
Jim Ingham1c823b42011-01-22 01:33:44 +00003959 {
Greg Clayton4116e932012-05-15 02:33:01 +00003960 PlatformSP platform_sp (m_target.GetPlatform());
3961 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003962 {
Greg Clayton4116e932012-05-15 02:33:01 +00003963 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3964 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003965 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00003966 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00003967 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3968 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003969 }
3970 else
3971 {
3972 if (log)
3973 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00003974 }
3975 }
3976 }
Greg Clayton4116e932012-05-15 02:33:01 +00003977 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00003978}
3979
3980bool
3981ProcessGDBRemote::StopNoticingNewThreads()
3982{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003983 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00003984 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00003985 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00003986
3987 if (m_thread_create_bp_sp)
3988 m_thread_create_bp_sp->SetEnabled(false);
3989
Jim Ingham1c823b42011-01-22 01:33:44 +00003990 return true;
3991}
3992
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003993DynamicLoader *
Jason Molenda5e8534e2012-10-03 01:29:34 +00003994ProcessGDBRemote::GetDynamicLoader ()
3995{
3996 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00003997 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00003998 return m_dyld_ap.get();
3999}
Jim Ingham1c823b42011-01-22 01:33:44 +00004000
Jason Molendaa3329782014-03-29 18:54:20 +00004001Error
4002ProcessGDBRemote::SendEventData(const char *data)
4003{
4004 int return_value;
4005 bool was_supported;
4006
4007 Error error;
4008
4009 return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported);
4010 if (return_value != 0)
4011 {
4012 if (!was_supported)
4013 error.SetErrorString("Sending events is not supported for this process.");
4014 else
4015 error.SetErrorStringWithFormat("Error sending event data: %d.", return_value);
4016 }
4017 return error;
4018}
4019
Steve Pucci03904ac2014-03-04 23:18:46 +00004020const DataBufferSP
4021ProcessGDBRemote::GetAuxvData()
4022{
4023 DataBufferSP buf;
4024 if (m_gdb_comm.GetQXferAuxvReadSupported())
4025 {
4026 std::string response_string;
4027 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success)
4028 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length()));
4029 }
4030 return buf;
4031}
4032
Jason Molenda705b1802014-06-13 02:37:02 +00004033StructuredData::ObjectSP
4034ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid)
4035{
4036 StructuredData::ObjectSP object_sp;
4037
4038 if (m_gdb_comm.GetThreadExtendedInfoSupported())
4039 {
4040 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4041 SystemRuntime *runtime = GetSystemRuntime();
4042 if (runtime)
4043 {
4044 runtime->AddThreadExtendedInfoPacketHints (args_dict);
4045 }
4046 args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid);
4047
4048 StreamString packet;
4049 packet << "jThreadExtendedInfo:";
4050 args_dict->Dump (packet);
4051
4052 // FIXME the final character of a JSON dictionary, '}', is the escape
4053 // character in gdb-remote binary mode. lldb currently doesn't escape
4054 // these characters in its packet output -- so we add the quoted version
4055 // of the } character here manually in case we talk to a debugserver which
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004056 // un-escapes the characters at packet read time.
Jason Molenda705b1802014-06-13 02:37:02 +00004057 packet << (char) (0x7d ^ 0x20);
4058
4059 StringExtractorGDBRemote response;
4060 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4061 {
4062 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4063 if (response_type == StringExtractorGDBRemote::eResponse)
4064 {
4065 if (!response.Empty())
4066 {
Jason Molenda20ee21b2015-07-10 23:15:22 +00004067 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4068 }
4069 }
4070 }
4071 }
4072 return object_sp;
4073}
4074
4075StructuredData::ObjectSP
4076ProcessGDBRemote::GetLoadedDynamicLibrariesInfos (lldb::addr_t image_list_address, lldb::addr_t image_count)
4077{
4078 StructuredData::ObjectSP object_sp;
4079
4080 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported())
4081 {
4082 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
4083 args_dict->GetAsDictionary()->AddIntegerItem ("image_list_address", image_list_address);
4084 args_dict->GetAsDictionary()->AddIntegerItem ("image_count", image_count);
4085
4086 StreamString packet;
4087 packet << "jGetLoadedDynamicLibrariesInfos:";
4088 args_dict->Dump (packet);
4089
4090 // FIXME the final character of a JSON dictionary, '}', is the escape
4091 // character in gdb-remote binary mode. lldb currently doesn't escape
4092 // these characters in its packet output -- so we add the quoted version
4093 // of the } character here manually in case we talk to a debugserver which
4094 // un-escapes the characters at packet read time.
4095 packet << (char) (0x7d ^ 0x20);
4096
4097 StringExtractorGDBRemote response;
4098 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4099 {
4100 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4101 if (response_type == StringExtractorGDBRemote::eResponse)
4102 {
4103 if (!response.Empty())
4104 {
Jason Molenda705b1802014-06-13 02:37:02 +00004105 // The packet has already had the 0x7d xor quoting stripped out at the
4106 // GDBRemoteCommunication packet receive level.
4107 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4108 }
4109 }
4110 }
4111 }
4112 return object_sp;
4113}
4114
Jason Molenda20ee21b2015-07-10 23:15:22 +00004115
Jason Molenda6076bf42014-05-06 04:34:52 +00004116// Establish the largest memory read/write payloads we should use.
4117// If the remote stub has a max packet size, stay under that size.
4118//
4119// If the remote stub's max packet size is crazy large, use a
4120// reasonable largeish default.
4121//
4122// If the remote stub doesn't advertise a max packet size, use a
4123// conservative default.
4124
4125void
4126ProcessGDBRemote::GetMaxMemorySize()
4127{
4128 const uint64_t reasonable_largeish_default = 128 * 1024;
4129 const uint64_t conservative_default = 512;
4130
4131 if (m_max_memory_size == 0)
4132 {
4133 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4134 if (stub_max_size != UINT64_MAX && stub_max_size != 0)
4135 {
4136 // Save the stub's claimed maximum packet size
4137 m_remote_stub_max_memory_size = stub_max_size;
4138
4139 // Even if the stub says it can support ginormous packets,
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004140 // don't exceed our reasonable largeish default packet size.
Jason Molenda6076bf42014-05-06 04:34:52 +00004141 if (stub_max_size > reasonable_largeish_default)
4142 {
4143 stub_max_size = reasonable_largeish_default;
4144 }
4145
4146 m_max_memory_size = stub_max_size;
4147 }
4148 else
4149 {
4150 m_max_memory_size = conservative_default;
4151 }
4152 }
4153}
4154
4155void
4156ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max)
4157{
4158 if (user_specified_max != 0)
4159 {
4160 GetMaxMemorySize ();
4161
4162 if (m_remote_stub_max_memory_size != 0)
4163 {
4164 if (m_remote_stub_max_memory_size < user_specified_max)
4165 {
4166 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a packet size too big, go as big
4167 // as the remote stub says we can go.
4168 }
4169 else
4170 {
4171 m_max_memory_size = user_specified_max; // user's packet size is good
4172 }
4173 }
4174 else
4175 {
4176 m_max_memory_size = user_specified_max; // user's packet size is probably fine
4177 }
4178 }
4179}
4180
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004181bool
4182ProcessGDBRemote::GetModuleSpec(const FileSpec& module_file_spec,
4183 const ArchSpec& arch,
4184 ModuleSpec &module_spec)
4185{
4186 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PLATFORM);
4187
4188 if (!m_gdb_comm.GetModuleInfo (module_file_spec, arch, module_spec))
4189 {
4190 if (log)
4191 log->Printf ("ProcessGDBRemote::%s - failed to get module info for %s:%s",
4192 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4193 arch.GetTriple ().getTriple ().c_str ());
4194 return false;
4195 }
4196
4197 if (log)
4198 {
4199 StreamString stream;
4200 module_spec.Dump (stream);
4201 log->Printf ("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4202 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4203 arch.GetTriple ().getTriple ().c_str (), stream.GetString ().c_str ());
4204 }
4205
4206 return true;
4207}
4208
Colin Rileyc3c95b22015-04-16 15:51:33 +00004209namespace {
4210
4211typedef std::vector<std::string> stringVec;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004212
4213typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004214struct RegisterSetInfo
4215{
4216 ConstString name;
4217};
Colin Rileyc3c95b22015-04-16 15:51:33 +00004218
Greg Claytond04f0ed2015-05-26 18:00:51 +00004219typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4220
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004221struct GdbServerTargetInfo
4222{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004223 std::string arch;
4224 std::string osabi;
4225 stringVec includes;
4226 RegisterSetMap reg_set_map;
4227 XMLNode feature_node;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004228};
Greg Claytond04f0ed2015-05-26 18:00:51 +00004229
Colin Rileyc3c95b22015-04-16 15:51:33 +00004230bool
Greg Claytond04f0ed2015-05-26 18:00:51 +00004231ParseRegisters (XMLNode feature_node, GdbServerTargetInfo &target_info, GDBRemoteDynamicRegisterInfo &dyn_reg_info)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004232{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004233 if (!feature_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004234 return false;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004235
4236 uint32_t prev_reg_num = 0;
4237 uint32_t reg_offset = 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004238
Greg Claytond04f0ed2015-05-26 18:00:51 +00004239 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 +00004240 std::string gdb_group;
4241 std::string gdb_type;
4242 ConstString reg_name;
4243 ConstString alt_name;
4244 ConstString set_name;
4245 std::vector<uint32_t> value_regs;
4246 std::vector<uint32_t> invalidate_regs;
4247 bool encoding_set = false;
4248 bool format_set = false;
4249 RegisterInfo reg_info = { NULL, // Name
4250 NULL, // Alt name
4251 0, // byte size
4252 reg_offset, // offset
4253 eEncodingUint, // encoding
4254 eFormatHex, // formate
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004255 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004256 LLDB_INVALID_REGNUM, // GCC reg num
4257 LLDB_INVALID_REGNUM, // DWARF reg num
4258 LLDB_INVALID_REGNUM, // generic reg num
4259 prev_reg_num, // GDB reg num
4260 prev_reg_num // native register number
4261 },
4262 NULL,
4263 NULL
4264 };
4265
Ewan Crawford682e8422015-06-26 09:38:27 +00004266 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 +00004267 if (name == "name")
4268 {
4269 reg_name.SetString(value);
4270 }
4271 else if (name == "bitsize")
4272 {
4273 reg_info.byte_size = StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
4274 }
4275 else if (name == "type")
4276 {
4277 gdb_type = value.str();
4278 }
4279 else if (name == "group")
4280 {
4281 gdb_group = value.str();
4282 }
4283 else if (name == "regnum")
4284 {
4285 const uint32_t regnum = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4286 if (regnum != LLDB_INVALID_REGNUM)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004287 {
Jason Molendaa18f7072015-08-15 01:21:01 +00004288 reg_info.kinds[eRegisterKindStabs] = regnum;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004289 reg_info.kinds[eRegisterKindLLDB] = regnum;
4290 prev_reg_num = regnum;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004291 }
4292 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004293 else if (name == "offset")
4294 {
4295 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4296 }
4297 else if (name == "altname")
4298 {
4299 alt_name.SetString(value);
4300 }
4301 else if (name == "encoding")
4302 {
4303 encoding_set = true;
4304 reg_info.encoding = Args::StringToEncoding (value.data(), eEncodingUint);
4305 }
4306 else if (name == "format")
4307 {
4308 format_set = true;
4309 Format format = eFormatInvalid;
4310 if (Args::StringToFormat (value.data(), format, NULL).Success())
4311 reg_info.format = format;
4312 else if (value == "vector-sint8")
4313 reg_info.format = eFormatVectorOfSInt8;
4314 else if (value == "vector-uint8")
4315 reg_info.format = eFormatVectorOfUInt8;
4316 else if (value == "vector-sint16")
4317 reg_info.format = eFormatVectorOfSInt16;
4318 else if (value == "vector-uint16")
4319 reg_info.format = eFormatVectorOfUInt16;
4320 else if (value == "vector-sint32")
4321 reg_info.format = eFormatVectorOfSInt32;
4322 else if (value == "vector-uint32")
4323 reg_info.format = eFormatVectorOfUInt32;
4324 else if (value == "vector-float32")
4325 reg_info.format = eFormatVectorOfFloat32;
4326 else if (value == "vector-uint128")
4327 reg_info.format = eFormatVectorOfUInt128;
4328 }
4329 else if (name == "group_id")
4330 {
4331 const uint32_t set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4332 RegisterSetMap::const_iterator pos = target_info.reg_set_map.find(set_id);
4333 if (pos != target_info.reg_set_map.end())
4334 set_name = pos->second.name;
4335 }
Jason Molendaa18f7072015-08-15 01:21:01 +00004336 else if (name == "gcc_regnum" || name == "ehframe_regnum")
Greg Claytond04f0ed2015-05-26 18:00:51 +00004337 {
Jason Molendaa18f7072015-08-15 01:21:01 +00004338 reg_info.kinds[eRegisterKindEHFrame] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004339 }
4340 else if (name == "dwarf_regnum")
4341 {
4342 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4343 }
4344 else if (name == "generic")
4345 {
4346 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister(value.data());
4347 }
4348 else if (name == "value_regnums")
4349 {
4350 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
4351 }
4352 else if (name == "invalidate_regnums")
4353 {
4354 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
4355 }
4356 else
4357 {
4358 printf("unhandled attribute %s = %s\n", name.data(), value.data());
4359 }
4360 return true; // Keep iterating through all attributes
4361 });
4362
4363 if (!gdb_type.empty() && !(encoding_set || format_set))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004364 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004365 if (gdb_type.find("int") == 0)
4366 {
4367 reg_info.format = eFormatHex;
4368 reg_info.encoding = eEncodingUint;
4369 }
4370 else if (gdb_type == "data_ptr" || gdb_type == "code_ptr")
4371 {
4372 reg_info.format = eFormatAddressInfo;
4373 reg_info.encoding = eEncodingUint;
4374 }
4375 else if (gdb_type == "i387_ext" || gdb_type == "float")
4376 {
4377 reg_info.format = eFormatFloat;
4378 reg_info.encoding = eEncodingIEEE754;
4379 }
Colin Rileyc3c95b22015-04-16 15:51:33 +00004380 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004381
4382 // Only update the register set name if we didn't get a "reg_set" attribute.
4383 // "set_name" will be empty if we didn't have a "reg_set" attribute.
4384 if (!set_name && !gdb_group.empty())
4385 set_name.SetCString(gdb_group.c_str());
4386
4387 reg_info.byte_offset = reg_offset;
4388 assert (reg_info.byte_size != 0);
4389 reg_offset += reg_info.byte_size;
4390 if (!value_regs.empty())
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004391 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004392 value_regs.push_back(LLDB_INVALID_REGNUM);
4393 reg_info.value_regs = value_regs.data();
Colin Rileyc3c95b22015-04-16 15:51:33 +00004394 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004395 if (!invalidate_regs.empty())
4396 {
4397 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
4398 reg_info.invalidate_regs = invalidate_regs.data();
4399 }
4400
Ewan Crawford682e8422015-06-26 09:38:27 +00004401 ++prev_reg_num;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004402 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
4403
4404 return true; // Keep iterating through all "reg" elements
4405 });
Colin Rileyc3c95b22015-04-16 15:51:33 +00004406 return true;
4407}
Greg Claytond04f0ed2015-05-26 18:00:51 +00004408
Colin Rileyc3c95b22015-04-16 15:51:33 +00004409} // namespace {}
4410
Colin Rileyc3c95b22015-04-16 15:51:33 +00004411
4412// query the target of gdb-remote for extended target information
4413// return: 'true' on success
4414// 'false' on failure
4415bool
Aidan Doddsc0c83852015-05-08 09:36:31 +00004416ProcessGDBRemote::GetGDBServerRegisterInfo ()
Colin Rileyc3c95b22015-04-16 15:51:33 +00004417{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004418 // Make sure LLDB has an XML parser it can use first
4419 if (!XMLDocument::XMLEnabled())
4420 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004421
4422 // redirect libxml2's error handler since the default prints to stdout
Colin Rileyc3c95b22015-04-16 15:51:33 +00004423
4424 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004425
4426 // check that we have extended feature read support
4427 if ( !comm.GetQXferFeaturesReadSupported( ) )
4428 return false;
4429
4430 // request the target xml file
4431 std::string raw;
4432 lldb_private::Error lldberr;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004433 if (!comm.ReadExtFeature(ConstString("features"),
4434 ConstString("target.xml"),
4435 raw,
4436 lldberr))
4437 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00004438 return false;
4439 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004440
Colin Rileyc3c95b22015-04-16 15:51:33 +00004441
Greg Claytond04f0ed2015-05-26 18:00:51 +00004442 XMLDocument xml_document;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004443
Greg Claytond04f0ed2015-05-26 18:00:51 +00004444 if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml"))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004445 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004446 GdbServerTargetInfo target_info;
4447
4448 XMLNode target_node = xml_document.GetRootElement("target");
4449 if (target_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004450 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004451 XMLNode feature_node;
4452 target_node.ForEachChildElement([&target_info, this, &feature_node](const XMLNode &node) -> bool
4453 {
4454 llvm::StringRef name = node.GetName();
4455 if (name == "architecture")
4456 {
4457 node.GetElementText(target_info.arch);
4458 }
4459 else if (name == "osabi")
4460 {
4461 node.GetElementText(target_info.osabi);
4462 }
Ewan Crawford682e8422015-06-26 09:38:27 +00004463 else if (name == "xi:include" || name == "include")
Greg Claytond04f0ed2015-05-26 18:00:51 +00004464 {
4465 llvm::StringRef href = node.GetAttributeValue("href");
4466 if (!href.empty())
4467 target_info.includes.push_back(href.str());
4468 }
4469 else if (name == "feature")
4470 {
4471 feature_node = node;
4472 }
4473 else if (name == "groups")
4474 {
4475 node.ForEachChildElementWithName("group", [&target_info](const XMLNode &node) -> bool {
4476 uint32_t set_id = UINT32_MAX;
4477 RegisterSetInfo set_info;
4478
4479 node.ForEachAttribute([&set_id, &set_info](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
4480 if (name == "id")
4481 set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4482 if (name == "name")
4483 set_info.name = ConstString(value);
4484 return true; // Keep iterating through all attributes
4485 });
4486
4487 if (set_id != UINT32_MAX)
4488 target_info.reg_set_map[set_id] = set_info;
4489 return true; // Keep iterating through all "group" elements
4490 });
4491 }
4492 return true; // Keep iterating through all children of the target_node
4493 });
4494
4495 if (feature_node)
4496 {
4497 ParseRegisters(feature_node, target_info, this->m_register_info);
4498 }
4499
4500 for (const auto &include : target_info.includes)
4501 {
4502 // request register file
4503 std::string xml_data;
4504 if (!comm.ReadExtFeature(ConstString("features"),
4505 ConstString(include),
4506 xml_data,
4507 lldberr))
4508 continue;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004509
Greg Claytond04f0ed2015-05-26 18:00:51 +00004510 XMLDocument include_xml_document;
4511 include_xml_document.ParseMemory(xml_data.data(), xml_data.size(), include.c_str());
4512 XMLNode include_feature_node = include_xml_document.GetRootElement("feature");
4513 if (include_feature_node)
4514 {
4515 ParseRegisters(include_feature_node, target_info, this->m_register_info);
4516 }
4517 }
4518 this->m_register_info.Finalize(GetTarget().GetArchitecture());
Colin Rileyc3c95b22015-04-16 15:51:33 +00004519 }
4520 }
4521
Greg Claytond04f0ed2015-05-26 18:00:51 +00004522 return m_register_info.GetNumRegisters() > 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004523}
4524
Aidan Doddsc0c83852015-05-08 09:36:31 +00004525Error
4526ProcessGDBRemote::GetLoadedModuleList (GDBLoadedModuleInfoList & list)
4527{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004528 // Make sure LLDB has an XML parser it can use first
4529 if (!XMLDocument::XMLEnabled())
4530 return Error (0, ErrorType::eErrorTypeGeneric);
4531
Aidan Doddsc0c83852015-05-08 09:36:31 +00004532 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS);
4533 if (log)
4534 log->Printf ("ProcessGDBRemote::%s", __FUNCTION__);
4535
Aidan Doddsc0c83852015-05-08 09:36:31 +00004536 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004537
4538 // check that we have extended feature read support
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004539 if (comm.GetQXferLibrariesSVR4ReadSupported ()) {
4540 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004541
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004542 // request the loaded library list
4543 std::string raw;
4544 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004545
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004546 if (!comm.ReadExtFeature (ConstString ("libraries-svr4"), ConstString (""), raw, lldberr))
4547 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004548
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004549 // parse the xml file in memory
4550 if (log)
4551 log->Printf ("parsing: %s", raw.c_str());
4552 XMLDocument doc;
4553
4554 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4555 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004556
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004557 XMLNode root_element = doc.GetRootElement("library-list-svr4");
4558 if (!root_element)
4559 return Error();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004560
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004561 // main link map structure
4562 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4563 if (!main_lm.empty())
4564 {
4565 list.m_link_map = StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
4566 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004567
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004568 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
Aidan Doddsc0c83852015-05-08 09:36:31 +00004569
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004570 GDBLoadedModuleInfoList::LoadedModuleInfo module;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004571
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004572 library.ForEachAttribute([log, &module](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004573
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004574 if (name == "name")
4575 module.set_name (value.str());
4576 else if (name == "lm")
4577 {
4578 // the address of the link_map struct.
4579 module.set_link_map(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4580 }
4581 else if (name == "l_addr")
4582 {
4583 // the displacement as read from the field 'l_addr' of the link_map struct.
4584 module.set_base(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4585
4586 }
4587 else if (name == "l_ld")
4588 {
4589 // the memory address of the libraries PT_DYAMIC section.
4590 module.set_dynamic(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4591 }
4592
4593 return true; // Keep iterating over all properties of "library"
4594 });
4595
4596 if (log)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004597 {
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004598 std::string name;
4599 lldb::addr_t lm=0, base=0, ld=0;
4600
4601 module.get_name (name);
4602 module.get_link_map (lm);
4603 module.get_base (base);
4604 module.get_dynamic (ld);
4605
4606 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 +00004607 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004608
4609 list.add (module);
4610 return true; // Keep iterating over all "library" elements in the root node
Greg Claytond04f0ed2015-05-26 18:00:51 +00004611 });
Aidan Doddsc0c83852015-05-08 09:36:31 +00004612
4613 if (log)
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004614 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4615 } else if (comm.GetQXferLibrariesReadSupported ()) {
4616 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004617
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004618 // request the loaded library list
4619 std::string raw;
4620 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004621
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004622 if (!comm.ReadExtFeature (ConstString ("libraries"), ConstString (""), raw, lldberr))
4623 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004624
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004625 if (log)
4626 log->Printf ("parsing: %s", raw.c_str());
4627 XMLDocument doc;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004628
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004629 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4630 return Error (0, ErrorType::eErrorTypeGeneric);
4631
4632 XMLNode root_element = doc.GetRootElement("library-list");
4633 if (!root_element)
4634 return Error();
4635
4636 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
4637 GDBLoadedModuleInfoList::LoadedModuleInfo module;
4638
4639 llvm::StringRef name = library.GetAttributeValue("name");
4640 module.set_name(name.str());
4641
4642 // The base address of a given library will be the address of its
4643 // first section. Most remotes send only one section for Windows
4644 // targets for example.
4645 const XMLNode &section = library.FindFirstChildElementWithName("section");
4646 llvm::StringRef address = section.GetAttributeValue("address");
4647 module.set_base(StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0));
4648
4649 if (log)
4650 {
4651 std::string name;
4652 lldb::addr_t base = 0;
4653 module.get_name (name);
4654 module.get_base (base);
4655
4656 log->Printf ("found (base:0x%" PRIx64 ", name:'%s')", base, name.c_str());
4657 }
4658
4659 list.add (module);
4660 return true; // Keep iterating over all "library" elements in the root node
4661 });
4662
4663 if (log)
4664 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4665 } else {
4666 return Error (0, ErrorType::eErrorTypeGeneric);
4667 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004668
4669 return Error();
4670}
4671
Aidan Doddsc0c83852015-05-08 09:36:31 +00004672lldb::ModuleSP
4673ProcessGDBRemote::LoadModuleAtAddress (const FileSpec &file, lldb::addr_t base_addr)
4674{
4675 Target &target = m_process->GetTarget();
4676 ModuleList &modules = target.GetImages();
4677 ModuleSP module_sp;
4678
4679 bool changed = false;
4680
4681 ModuleSpec module_spec (file, target.GetArchitecture());
4682 if ((module_sp = modules.FindFirstModule (module_spec)))
4683 {
4684 module_sp->SetLoadAddress (target, base_addr, true, changed);
4685 }
4686 else if ((module_sp = target.GetSharedModule (module_spec)))
4687 {
4688 module_sp->SetLoadAddress (target, base_addr, true, changed);
4689 }
4690
4691 return module_sp;
4692}
4693
4694size_t
4695ProcessGDBRemote::LoadModules ()
4696{
4697 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4698
4699 // request a list of loaded libraries from GDBServer
4700 GDBLoadedModuleInfoList module_list;
4701 if (GetLoadedModuleList (module_list).Fail())
4702 return 0;
4703
4704 // get a list of all the modules
4705 ModuleList new_modules;
4706
4707 for (GDBLoadedModuleInfoList::LoadedModuleInfo & modInfo : module_list.m_list)
4708 {
4709 std::string mod_name;
4710 lldb::addr_t mod_base;
4711
4712 bool valid = true;
4713 valid &= modInfo.get_name (mod_name);
4714 valid &= modInfo.get_base (mod_base);
4715 if (!valid)
4716 continue;
4717
4718 // hack (cleaner way to get file name only?) (win/unix compat?)
Vince Harron4cc8d202015-05-10 08:33:58 +00004719 size_t marker = mod_name.rfind ('/');
Aidan Doddsc0c83852015-05-08 09:36:31 +00004720 if (marker == std::string::npos)
4721 marker = 0;
4722 else
4723 marker += 1;
4724
4725 FileSpec file (mod_name.c_str()+marker, true);
4726 lldb::ModuleSP module_sp = LoadModuleAtAddress (file, mod_base);
4727
4728 if (module_sp.get())
4729 new_modules.Append (module_sp);
4730 }
4731
4732 if (new_modules.GetSize() > 0)
4733 {
4734 Target & target = m_target;
4735
4736 new_modules.ForEach ([&target](const lldb::ModuleSP module_sp) -> bool
4737 {
4738 lldb_private::ObjectFile * obj = module_sp->GetObjectFile ();
4739 if (!obj)
4740 return true;
4741
4742 if (obj->GetType () != ObjectFile::Type::eTypeExecutable)
4743 return true;
4744
4745 lldb::ModuleSP module_copy_sp = module_sp;
4746 target.SetExecutableModule (module_copy_sp, false);
4747 return false;
4748 });
4749
4750 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4751 loaded_modules.AppendIfNeeded (new_modules);
4752 m_process->GetTarget().ModulesDidLoad (new_modules);
4753 }
4754
4755 return new_modules.GetSize();
4756}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004757
Tamas Berghammer783bfc82015-06-18 20:43:56 +00004758Error
4759ProcessGDBRemote::GetFileLoadAddress(const FileSpec& file, bool& is_loaded, lldb::addr_t& load_addr)
4760{
4761 is_loaded = false;
4762 load_addr = LLDB_INVALID_ADDRESS;
4763
4764 std::string file_path = file.GetPath(false);
4765 if (file_path.empty ())
4766 return Error("Empty file name specified");
4767
4768 StreamString packet;
4769 packet.PutCString("qFileLoadAddress:");
4770 packet.PutCStringAsRawHex8(file_path.c_str());
4771
4772 StringExtractorGDBRemote response;
4773 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString().c_str(), response, false) != GDBRemoteCommunication::PacketResult::Success)
4774 return Error("Sending qFileLoadAddress packet failed");
4775
4776 if (response.IsErrorResponse())
4777 {
4778 if (response.GetError() == 1)
4779 {
4780 // The file is not loaded into the inferior
4781 is_loaded = false;
4782 load_addr = LLDB_INVALID_ADDRESS;
4783 return Error();
4784 }
4785
4786 return Error("Fetching file load address from remote server returned an error");
4787 }
4788
4789 if (response.IsNormalResponse())
4790 {
4791 is_loaded = true;
4792 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
4793 return Error();
4794 }
4795
4796 return Error("Unknown error happened during sending the load address packet");
4797}
4798
Greg Clayton0b90be12015-06-23 21:27:50 +00004799
4800void
4801ProcessGDBRemote::ModulesDidLoad (ModuleList &module_list)
4802{
4803 // We must call the lldb_private::Process::ModulesDidLoad () first before we do anything
4804 Process::ModulesDidLoad (module_list);
4805
4806 // After loading shared libraries, we can ask our remote GDB server if
4807 // it needs any symbols.
4808 m_gdb_comm.ServeSymbolLookups(this);
4809}
4810
4811
Greg Claytone034a042015-05-21 20:52:06 +00004812class CommandObjectProcessGDBRemoteSpeedTest: public CommandObjectParsed
4813{
4814public:
4815 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter) :
4816 CommandObjectParsed (interpreter,
4817 "process plugin packet speed-test",
4818 "Tests packet speeds of various sizes to determine the performance characteristics of the GDB remote connection. ",
4819 NULL),
4820 m_option_group (interpreter),
4821 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),
4822 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),
4823 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),
4824 m_json (LLDB_OPT_SET_1, false, "json", 'j', "Print the output as JSON data for easy parsing.", false, true)
4825 {
4826 m_option_group.Append (&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4827 m_option_group.Append (&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4828 m_option_group.Append (&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4829 m_option_group.Append (&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4830 m_option_group.Finalize();
4831 }
4832
4833 ~CommandObjectProcessGDBRemoteSpeedTest ()
4834 {
4835 }
4836
4837
4838 Options *
4839 GetOptions () override
4840 {
4841 return &m_option_group;
4842 }
4843
4844 bool
4845 DoExecute (Args& command, CommandReturnObject &result) override
4846 {
4847 const size_t argc = command.GetArgumentCount();
4848 if (argc == 0)
4849 {
4850 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4851 if (process)
4852 {
4853 StreamSP output_stream_sp (m_interpreter.GetDebugger().GetAsyncOutputStream());
4854 result.SetImmediateOutputStream (output_stream_sp);
4855
4856 const uint32_t num_packets = (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
4857 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
4858 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
4859 const bool json = m_json.GetOptionValue().GetCurrentValue();
4860 if (output_stream_sp)
4861 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, *output_stream_sp);
4862 else
4863 {
4864 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, result.GetOutputStream());
4865 }
4866 result.SetStatus (eReturnStatusSuccessFinishResult);
4867 return true;
4868 }
4869 }
4870 else
4871 {
4872 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
4873 }
4874 result.SetStatus (eReturnStatusFailed);
4875 return false;
4876 }
4877protected:
4878 OptionGroupOptions m_option_group;
4879 OptionGroupUInt64 m_num_packets;
4880 OptionGroupUInt64 m_max_send;
4881 OptionGroupUInt64 m_max_recv;
4882 OptionGroupBoolean m_json;
4883
4884};
4885
Greg Clayton02686b82012-10-15 22:42:16 +00004886class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00004887{
4888private:
4889
4890public:
Greg Clayton02686b82012-10-15 22:42:16 +00004891 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00004892 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00004893 "process plugin packet history",
4894 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00004895 NULL)
4896 {
4897 }
4898
Greg Clayton02686b82012-10-15 22:42:16 +00004899 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton998255b2012-10-13 02:07:45 +00004900 {
4901 }
4902
4903 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004904 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton998255b2012-10-13 02:07:45 +00004905 {
Greg Clayton02686b82012-10-15 22:42:16 +00004906 const size_t argc = command.GetArgumentCount();
4907 if (argc == 0)
4908 {
4909 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4910 if (process)
4911 {
4912 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
4913 result.SetStatus (eReturnStatusSuccessFinishResult);
4914 return true;
4915 }
4916 }
4917 else
4918 {
4919 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
4920 }
4921 result.SetStatus (eReturnStatusFailed);
4922 return false;
4923 }
4924};
4925
Jason Molenda6076bf42014-05-06 04:34:52 +00004926class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed
4927{
4928private:
4929
4930public:
4931 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) :
4932 CommandObjectParsed (interpreter,
4933 "process plugin packet xfer-size",
4934 "Maximum size that lldb will try to read/write one one chunk.",
4935 NULL)
4936 {
4937 }
4938
4939 ~CommandObjectProcessGDBRemotePacketXferSize ()
4940 {
4941 }
4942
4943 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004944 DoExecute (Args& command, CommandReturnObject &result) override
Jason Molenda6076bf42014-05-06 04:34:52 +00004945 {
4946 const size_t argc = command.GetArgumentCount();
4947 if (argc == 0)
4948 {
4949 result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str());
4950 result.SetStatus (eReturnStatusFailed);
4951 return false;
4952 }
4953
4954 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4955 if (process)
4956 {
4957 const char *packet_size = command.GetArgumentAtIndex(0);
4958 errno = 0;
4959 uint64_t user_specified_max = strtoul (packet_size, NULL, 10);
4960 if (errno == 0 && user_specified_max != 0)
4961 {
4962 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max);
4963 result.SetStatus (eReturnStatusSuccessFinishResult);
4964 return true;
4965 }
4966 }
4967 result.SetStatus (eReturnStatusFailed);
4968 return false;
4969 }
4970};
4971
4972
Greg Clayton02686b82012-10-15 22:42:16 +00004973class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
4974{
4975private:
4976
4977public:
4978 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
4979 CommandObjectParsed (interpreter,
4980 "process plugin packet send",
4981 "Send a custom packet through the GDB remote protocol and print the answer. "
4982 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
4983 NULL)
4984 {
4985 }
4986
4987 ~CommandObjectProcessGDBRemotePacketSend ()
4988 {
4989 }
4990
4991 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004992 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton02686b82012-10-15 22:42:16 +00004993 {
4994 const size_t argc = command.GetArgumentCount();
4995 if (argc == 0)
4996 {
4997 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
4998 result.SetStatus (eReturnStatusFailed);
4999 return false;
5000 }
5001
5002 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5003 if (process)
5004 {
Han Ming Ong84145852012-11-26 20:42:03 +00005005 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00005006 {
Han Ming Ong84145852012-11-26 20:42:03 +00005007 const char *packet_cstr = command.GetArgumentAtIndex(0);
5008 bool send_async = true;
5009 StringExtractorGDBRemote response;
5010 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
5011 result.SetStatus (eReturnStatusSuccessFinishResult);
5012 Stream &output_strm = result.GetOutputStream();
5013 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00005014 std::string &response_str = response.GetStringRef();
5015
Han Ming Ong399289e2013-06-21 19:56:59 +00005016 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00005017 {
5018 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
5019 }
5020
Han Ming Ong84145852012-11-26 20:42:03 +00005021 if (response_str.empty())
5022 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
5023 else
5024 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00005025 }
Greg Clayton02686b82012-10-15 22:42:16 +00005026 }
Greg Clayton998255b2012-10-13 02:07:45 +00005027 return true;
5028 }
5029};
5030
Greg Claytonba4a0a52013-02-01 23:03:47 +00005031class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
5032{
5033private:
5034
5035public:
5036 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
5037 CommandObjectRaw (interpreter,
5038 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00005039 "Send a qRcmd packet through the GDB remote protocol and print the response."
5040 "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 +00005041 NULL)
5042 {
5043 }
5044
5045 ~CommandObjectProcessGDBRemotePacketMonitor ()
5046 {
5047 }
5048
5049 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00005050 DoExecute (const char *command, CommandReturnObject &result) override
Greg Claytonba4a0a52013-02-01 23:03:47 +00005051 {
5052 if (command == NULL || command[0] == '\0')
5053 {
5054 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
5055 result.SetStatus (eReturnStatusFailed);
5056 return false;
5057 }
5058
5059 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5060 if (process)
5061 {
5062 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00005063 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00005064 packet.PutBytesAsRawHex8(command, strlen(command));
5065 const char *packet_cstr = packet.GetString().c_str();
5066
5067 bool send_async = true;
5068 StringExtractorGDBRemote response;
5069 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
5070 result.SetStatus (eReturnStatusSuccessFinishResult);
5071 Stream &output_strm = result.GetOutputStream();
5072 output_strm.Printf (" packet: %s\n", packet_cstr);
5073 const std::string &response_str = response.GetStringRef();
5074
5075 if (response_str.empty())
5076 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
5077 else
5078 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
5079 }
5080 return true;
5081 }
5082};
5083
Greg Clayton02686b82012-10-15 22:42:16 +00005084class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
5085{
5086private:
5087
5088public:
5089 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
5090 CommandObjectMultiword (interpreter,
5091 "process plugin packet",
5092 "Commands that deal with GDB remote packets.",
5093 NULL)
5094 {
5095 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
5096 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00005097 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Jason Molenda6076bf42014-05-06 04:34:52 +00005098 LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter)));
Greg Claytone034a042015-05-21 20:52:06 +00005099 LoadSubCommand ("speed-test", CommandObjectSP (new CommandObjectProcessGDBRemoteSpeedTest (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00005100 }
5101
5102 ~CommandObjectProcessGDBRemotePacket ()
5103 {
5104 }
5105};
Greg Clayton998255b2012-10-13 02:07:45 +00005106
5107class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
5108{
5109public:
5110 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
5111 CommandObjectMultiword (interpreter,
5112 "process plugin",
5113 "A set of commands for operating on a ProcessGDBRemote process.",
5114 "process plugin <subcommand> [<subcommand-options>]")
5115 {
5116 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
5117 }
5118
5119 ~CommandObjectMultiwordProcessGDBRemote ()
5120 {
5121 }
5122};
5123
Greg Clayton998255b2012-10-13 02:07:45 +00005124CommandObject *
5125ProcessGDBRemote::GetPluginCommandObject()
5126{
5127 if (!m_command_sp)
5128 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
5129 return m_command_sp.get();
5130}