blob: dbd68b47d57474a89d381238b055f3d8ad3a99e3 [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;
195 };
196
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),
Greg Clayton09c3e3d2011-12-06 04:51:14 +0000374 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
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 Clayton358cf1e2015-06-25 21:46:34 +0000379 m_threads_info_sp (),
Greg Clayton71fc2a32011-02-12 06:28:37 +0000380 m_continue_c_tids (),
381 m_continue_C_tids (),
382 m_continue_s_tids (),
383 m_continue_S_tids (),
Jason Molenda6076bf42014-05-06 04:34:52 +0000384 m_max_memory_size (0),
385 m_remote_stub_max_memory_size (0),
Greg Clayton4116e932012-05-15 02:33:01 +0000386 m_addr_to_mmap_size (),
387 m_thread_create_bp_sp (),
Jim Ingham43c555d2012-07-04 00:35:43 +0000388 m_waiting_for_attach (false),
Jason Molenda5e8534e2012-10-03 01:29:34 +0000389 m_destroy_tried_resuming (false),
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000390 m_command_sp (),
Ewan Crawford78baa192015-05-13 09:18:18 +0000391 m_breakpoint_pc_offset (0),
392 m_initial_tid (LLDB_INVALID_THREAD_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000393{
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000394 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
395 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Inghamb1e2e842012-04-12 18:49:31 +0000396 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Greg Clayton7f982402013-07-15 22:54:20 +0000397 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
398 if (timeout_seconds > 0)
399 m_gdb_comm.SetPacketTimeout(timeout_seconds);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000400}
401
402//----------------------------------------------------------------------
403// Destructor
404//----------------------------------------------------------------------
405ProcessGDBRemote::~ProcessGDBRemote()
406{
407 // m_mach_process.UnregisterNotificationCallbacks (this);
408 Clear();
Greg Clayton1ed54f52011-10-01 00:45:15 +0000409 // We need to call finalize on the process before destroying ourselves
410 // to make sure all of the broadcaster cleanup goes as planned. If we
411 // destruct this class, then Process::~Process() might have problems
412 // trying to fully destroy the broadcaster.
413 Finalize();
Jim Ingham455fa5c2012-11-01 01:15:33 +0000414
415 // The general Finalize is going to try to destroy the process and that SHOULD
416 // shut down the async thread. However, if we don't kill it it will get stranded and
417 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
418 StopAsyncThread();
419 KillDebugserverProcess();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000420}
421
422//----------------------------------------------------------------------
423// PluginInterface
424//----------------------------------------------------------------------
Greg Clayton57abc5d2013-05-10 21:47:16 +0000425ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000426ProcessGDBRemote::GetPluginName()
427{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000428 return GetPluginNameStatic();
429}
430
431uint32_t
432ProcessGDBRemote::GetPluginVersion()
433{
434 return 1;
435}
436
Greg Claytonef8180a2013-10-15 00:14:28 +0000437bool
438ProcessGDBRemote::ParsePythonTargetDefinition(const FileSpec &target_definition_fspec)
439{
440 ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
441 Error error;
Zachary Turner0641ca12015-03-17 20:04:04 +0000442 StructuredData::ObjectSP module_object_sp(interpreter->LoadPluginModule(target_definition_fspec, error));
Greg Claytonef8180a2013-10-15 00:14:28 +0000443 if (module_object_sp)
444 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000445 StructuredData::DictionarySP target_definition_sp(
446 interpreter->GetDynamicSettings(module_object_sp, &GetTarget(), "gdb-server-target-definition", error));
Greg Claytonef8180a2013-10-15 00:14:28 +0000447
Zachary Turner0641ca12015-03-17 20:04:04 +0000448 if (target_definition_sp)
Greg Claytonef8180a2013-10-15 00:14:28 +0000449 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000450 StructuredData::ObjectSP target_object(target_definition_sp->GetValueForKey("host-info"));
451 if (target_object)
Greg Clayton312bcbe2013-10-17 01:10:23 +0000452 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000453 if (auto host_info_dict = target_object->GetAsDictionary())
Greg Clayton312bcbe2013-10-17 01:10:23 +0000454 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000455 StructuredData::ObjectSP triple_value = host_info_dict->GetValueForKey("triple");
456 if (auto triple_string_value = triple_value->GetAsString())
457 {
458 std::string triple_string = triple_string_value->GetValue();
459 ArchSpec host_arch(triple_string.c_str());
460 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture()))
461 {
462 GetTarget().SetArchitecture(host_arch);
463 }
464 }
Greg Clayton312bcbe2013-10-17 01:10:23 +0000465 }
Greg Clayton312bcbe2013-10-17 01:10:23 +0000466 }
Zachary Turner0641ca12015-03-17 20:04:04 +0000467 m_breakpoint_pc_offset = 0;
468 StructuredData::ObjectSP breakpoint_pc_offset_value = target_definition_sp->GetValueForKey("breakpoint-pc-offset");
469 if (breakpoint_pc_offset_value)
470 {
471 if (auto breakpoint_pc_int_value = breakpoint_pc_offset_value->GetAsInteger())
472 m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
473 }
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000474
Greg Claytond04f0ed2015-05-26 18:00:51 +0000475 if (m_register_info.SetRegisterInfo(*target_definition_sp, GetTarget().GetArchitecture()) > 0)
Greg Claytonef8180a2013-10-15 00:14:28 +0000476 {
477 return true;
478 }
479 }
480 }
481 return false;
482}
483
Greg Claytond04f0ed2015-05-26 18:00:51 +0000484static size_t
485SplitCommaSeparatedRegisterNumberString(const llvm::StringRef &comma_separated_regiter_numbers, std::vector<uint32_t> &regnums, int base)
486{
487 regnums.clear();
488 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
489 value_pair.second = comma_separated_regiter_numbers;
490 do
491 {
492 value_pair = value_pair.second.split(',');
493 if (!value_pair.first.empty())
494 {
495 uint32_t reg = StringConvert::ToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, base);
496 if (reg != LLDB_INVALID_REGNUM)
497 regnums.push_back (reg);
498 }
499 } while (!value_pair.second.empty());
500 return regnums.size();
501}
502
Greg Claytonef8180a2013-10-15 00:14:28 +0000503
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000504void
Greg Clayton513c26c2011-01-29 07:10:55 +0000505ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000506{
Greg Clayton513c26c2011-01-29 07:10:55 +0000507 if (!force && m_register_info.GetNumRegisters() > 0)
508 return;
509
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000510 m_register_info.Clear();
Greg Claytond04f0ed2015-05-26 18:00:51 +0000511
512 // Check if qHostInfo specified a specific packet timeout for this connection.
513 // If so then lets update our setting so the user knows what the timeout is
514 // and can see it.
515 const uint32_t host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
516 if (host_packet_timeout)
517 {
518 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout);
519 }
520
Ewan Crawford0c996a92015-06-30 13:08:44 +0000521 // Register info search order:
522 // 1 - Use the target definition python file if one is specified.
523 // 2 - If the target definition doesn't have any of the info from the target.xml (registers) then proceed to read the target.xml.
524 // 3 - Fall back on the qRegisterInfo packets.
525
526 FileSpec target_definition_fspec = GetGlobalPluginProperties()->GetTargetDefinitionFile ();
527 if (target_definition_fspec)
528 {
529 // See if we can get register definitions from a python file
530 if (ParsePythonTargetDefinition (target_definition_fspec))
531 return;
532 }
533
Greg Claytond04f0ed2015-05-26 18:00:51 +0000534 if (GetGDBServerRegisterInfo ())
535 return;
536
537 char packet[128];
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000538 uint32_t reg_offset = 0;
539 uint32_t reg_num = 0;
Greg Clayton23f59502012-07-17 03:23:13 +0000540 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Greg Clayton576d8832011-03-22 04:00:09 +0000541 response_type == StringExtractorGDBRemote::eResponse;
542 ++reg_num)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000543 {
Greg Clayton513c26c2011-01-29 07:10:55 +0000544 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
Andy Gibbsa297a972013-06-19 19:04:53 +0000545 assert (packet_len < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000546 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000547 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000548 {
Greg Clayton576d8832011-03-22 04:00:09 +0000549 response_type = response.GetResponseType();
550 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000551 {
552 std::string name;
553 std::string value;
554 ConstString reg_name;
555 ConstString alt_name;
556 ConstString set_name;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000557 std::vector<uint32_t> value_regs;
558 std::vector<uint32_t> invalidate_regs;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000559 RegisterInfo reg_info = { NULL, // Name
560 NULL, // Alt name
561 0, // byte size
562 reg_offset, // offset
563 eEncodingUint, // encoding
564 eFormatHex, // formate
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000565 {
566 LLDB_INVALID_REGNUM, // GCC reg num
567 LLDB_INVALID_REGNUM, // DWARF reg num
568 LLDB_INVALID_REGNUM, // generic reg num
Jason Molendafbcb7f22010-09-10 07:49:16 +0000569 reg_num, // GDB reg num
570 reg_num // native register number
Greg Clayton435d85a2012-02-29 19:27:27 +0000571 },
572 NULL,
573 NULL
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000574 };
575
576 while (response.GetNameColonValue(name, value))
577 {
578 if (name.compare("name") == 0)
579 {
580 reg_name.SetCString(value.c_str());
581 }
582 else if (name.compare("alt-name") == 0)
583 {
584 alt_name.SetCString(value.c_str());
585 }
586 else if (name.compare("bitsize") == 0)
587 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000588 reg_info.byte_size = StringConvert::ToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000589 }
590 else if (name.compare("offset") == 0)
591 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000592 uint32_t offset = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda743e86a2010-06-11 23:44:18 +0000593 if (reg_offset != offset)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000594 {
595 reg_offset = offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000596 }
597 }
598 else if (name.compare("encoding") == 0)
599 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000600 const Encoding encoding = Args::StringToEncoding (value.c_str());
601 if (encoding != eEncodingInvalid)
602 reg_info.encoding = encoding;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000603 }
604 else if (name.compare("format") == 0)
605 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000606 Format format = eFormatInvalid;
607 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
608 reg_info.format = format;
609 else if (value.compare("binary") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000610 reg_info.format = eFormatBinary;
611 else if (value.compare("decimal") == 0)
612 reg_info.format = eFormatDecimal;
613 else if (value.compare("hex") == 0)
614 reg_info.format = eFormatHex;
615 else if (value.compare("float") == 0)
616 reg_info.format = eFormatFloat;
617 else if (value.compare("vector-sint8") == 0)
618 reg_info.format = eFormatVectorOfSInt8;
619 else if (value.compare("vector-uint8") == 0)
620 reg_info.format = eFormatVectorOfUInt8;
621 else if (value.compare("vector-sint16") == 0)
622 reg_info.format = eFormatVectorOfSInt16;
623 else if (value.compare("vector-uint16") == 0)
624 reg_info.format = eFormatVectorOfUInt16;
625 else if (value.compare("vector-sint32") == 0)
626 reg_info.format = eFormatVectorOfSInt32;
627 else if (value.compare("vector-uint32") == 0)
628 reg_info.format = eFormatVectorOfUInt32;
629 else if (value.compare("vector-float32") == 0)
630 reg_info.format = eFormatVectorOfFloat32;
631 else if (value.compare("vector-uint128") == 0)
632 reg_info.format = eFormatVectorOfUInt128;
633 }
634 else if (name.compare("set") == 0)
635 {
636 set_name.SetCString(value.c_str());
637 }
638 else if (name.compare("gcc") == 0)
639 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000640 reg_info.kinds[eRegisterKindGCC] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000641 }
642 else if (name.compare("dwarf") == 0)
643 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000644 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000645 }
646 else if (name.compare("generic") == 0)
647 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000648 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000649 }
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000650 else if (name.compare("container-regs") == 0)
651 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000652 SplitCommaSeparatedRegisterNumberString(value, value_regs, 16);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000653 }
654 else if (name.compare("invalidate-regs") == 0)
655 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000656 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 16);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000657 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000658 }
659
Jason Molenda743e86a2010-06-11 23:44:18 +0000660 reg_info.byte_offset = reg_offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000661 assert (reg_info.byte_size != 0);
662 reg_offset += reg_info.byte_size;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000663 if (!value_regs.empty())
664 {
665 value_regs.push_back(LLDB_INVALID_REGNUM);
666 reg_info.value_regs = value_regs.data();
667 }
668 if (!invalidate_regs.empty())
669 {
670 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
671 reg_info.invalidate_regs = invalidate_regs.data();
672 }
673
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000674 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
675 }
Todd Fiala1a634402014-01-08 07:52:40 +0000676 else
677 {
678 break; // ensure exit before reg_num is incremented
679 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000680 }
681 else
682 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000683 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000684 }
685 }
686
Greg Claytond04f0ed2015-05-26 18:00:51 +0000687 if (m_register_info.GetNumRegisters() > 0)
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000688 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000689 m_register_info.Finalize(GetTarget().GetArchitecture());
690 return;
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000691 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000692
Johnny Chen2fa9de12012-05-14 18:44:23 +0000693 // We didn't get anything if the accumulated reg_num is zero. See if we are
694 // debugging ARM and fill with a hard coded register set until we can get an
695 // updated debugserver down on the devices.
696 // On the other hand, if the accumulated reg_num is positive, see if we can
697 // add composite registers to the existing primordial ones.
Greg Claytond04f0ed2015-05-26 18:00:51 +0000698 bool from_scratch = (m_register_info.GetNumRegisters() == 0);
Johnny Chen2fa9de12012-05-14 18:44:23 +0000699
700 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000701 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
702 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
703
704 // Use the process' architecture instead of the host arch, if available
705 ArchSpec remote_arch;
706 if (remote_process_arch.IsValid ())
707 remote_arch = remote_process_arch;
708 else
709 remote_arch = remote_host_arch;
710
Johnny Chen2fa9de12012-05-14 18:44:23 +0000711 if (!target_arch.IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000712 {
Johnny Chen2fa9de12012-05-14 18:44:23 +0000713 if (remote_arch.IsValid()
714 && remote_arch.GetMachine() == llvm::Triple::arm
715 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
716 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000717 }
Johnny Chen2fa9de12012-05-14 18:44:23 +0000718 else if (target_arch.GetMachine() == llvm::Triple::arm)
719 {
720 m_register_info.HardcodeARMRegisters(from_scratch);
721 }
722
723 // At this point, we can finalize our register info.
Greg Claytond04f0ed2015-05-26 18:00:51 +0000724 m_register_info.Finalize (GetTarget().GetArchitecture());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000725}
726
727Error
728ProcessGDBRemote::WillLaunch (Module* module)
729{
730 return WillLaunchOrAttach ();
731}
732
733Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000734ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000735{
736 return WillLaunchOrAttach ();
737}
738
739Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000740ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000741{
742 return WillLaunchOrAttach ();
743}
744
745Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000746ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +0000747{
Todd Fialaaf245d12014-06-30 21:05:18 +0000748 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Claytonb766a732011-02-04 01:58:07 +0000749 Error error (WillLaunchOrAttach ());
750
751 if (error.Fail())
752 return error;
753
Greg Clayton2289fa42011-04-30 01:09:13 +0000754 error = ConnectToDebugserver (remote_url);
Greg Claytonb766a732011-02-04 01:58:07 +0000755
756 if (error.Fail())
757 return error;
758 StartAsyncThread ();
759
Greg Claytonc574ede2011-03-10 02:26:48 +0000760 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonb766a732011-02-04 01:58:07 +0000761 if (pid == LLDB_INVALID_PROCESS_ID)
762 {
763 // We don't have a valid process ID, so note that we are connected
764 // and could now request to launch or attach, or get remote process
765 // listings...
766 SetPrivateState (eStateConnected);
767 }
768 else
769 {
770 // We have a valid process
771 SetID (pid);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000772 GetThreadList();
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000773 StringExtractorGDBRemote response;
774 if (m_gdb_comm.GetStopReply(response))
Greg Claytonb766a732011-02-04 01:58:07 +0000775 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000776 SetLastStopPacket(response);
Ewan Crawford78baa192015-05-13 09:18:18 +0000777
778 // '?' Packets must be handled differently in non-stop mode
779 if (GetTarget().GetNonStopModeEnabled())
780 HandleStopReplySequence();
781
Jason Molendac62bd7b2013-12-21 05:20:36 +0000782 if (!m_target.GetArchitecture().IsValid())
783 {
784 if (m_gdb_comm.GetProcessArchitecture().IsValid())
785 {
786 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
787 }
788 else
789 {
790 m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
791 }
Carlo Kok74389122013-10-14 07:09:13 +0000792 }
793
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000794 const StateType state = SetThreadStopInfo (response);
Greg Claytonb766a732011-02-04 01:58:07 +0000795 if (state == eStateStopped)
796 {
797 SetPrivateState (state);
798 }
799 else
Daniel Malead01b2952012-11-29 21:49:15 +0000800 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 +0000801 }
802 else
Daniel Malead01b2952012-11-29 21:49:15 +0000803 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 +0000804 }
Jason Molenda16d127c2012-05-03 22:37:30 +0000805
Todd Fialaaf245d12014-06-30 21:05:18 +0000806 if (log)
807 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");
808
809
810 if (error.Success()
Jason Molenda16d127c2012-05-03 22:37:30 +0000811 && !GetTarget().GetArchitecture().IsValid()
812 && m_gdb_comm.GetHostArchitecture().IsValid())
813 {
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000814 // Prefer the *process'* architecture over that of the *host*, if available.
815 if (m_gdb_comm.GetProcessArchitecture().IsValid())
816 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
817 else
818 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molenda16d127c2012-05-03 22:37:30 +0000819 }
820
Todd Fialaaf245d12014-06-30 21:05:18 +0000821 if (log)
822 log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": normalized target architecture triple: %s", __FUNCTION__, GetID (), GetTarget ().GetArchitecture ().GetTriple ().getTriple ().c_str ());
823
Chaoren Lin98d0a4b2015-07-14 01:09:28 +0000824 if (error.Success())
825 SetUnixSignals(std::make_shared<GDBRemoteSignals>(GetTarget().GetPlatform()->GetUnixSignals()));
Todd Fialaaf245d12014-06-30 21:05:18 +0000826
Greg Claytonb766a732011-02-04 01:58:07 +0000827 return error;
828}
829
830Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000831ProcessGDBRemote::WillLaunchOrAttach ()
832{
833 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000834 m_stdio_communication.Clear ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000835 return error;
836}
837
838//----------------------------------------------------------------------
839// Process Control
840//----------------------------------------------------------------------
841Error
Jean-Daniel Dupas7782de92013-12-09 22:52:50 +0000842ProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000843{
Todd Fiala75f47c32014-10-11 21:42:09 +0000844 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton4957bf62010-09-30 21:49:03 +0000845 Error error;
Greg Clayton982c9762011-11-03 21:22:33 +0000846
Todd Fiala75f47c32014-10-11 21:42:09 +0000847 if (log)
848 log->Printf ("ProcessGDBRemote::%s() entered", __FUNCTION__);
849
Greg Clayton982c9762011-11-03 21:22:33 +0000850 uint32_t launch_flags = launch_info.GetFlags().Get();
Chaoren Lind3173f32015-05-29 19:52:29 +0000851 FileSpec stdin_file_spec{};
852 FileSpec stdout_file_spec{};
853 FileSpec stderr_file_spec{};
854 FileSpec working_dir = launch_info.GetWorkingDirectory();
Greg Clayton982c9762011-11-03 21:22:33 +0000855
Zachary Turner696b5282014-08-14 16:01:25 +0000856 const FileAction *file_action;
Greg Clayton982c9762011-11-03 21:22:33 +0000857 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
858 if (file_action)
859 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000860 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000861 stdin_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000862 }
863 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
864 if (file_action)
865 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000866 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000867 stdout_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000868 }
869 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
870 if (file_action)
871 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000872 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000873 stderr_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000874 }
875
Todd Fiala75f47c32014-10-11 21:42:09 +0000876 if (log)
877 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000878 if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
Vince Harron4a8abd32015-02-13 19:15:24 +0000879 log->Printf ("ProcessGDBRemote::%s provided with STDIO paths via launch_info: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000880 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000881 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
882 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
883 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Todd Fiala75f47c32014-10-11 21:42:09 +0000884 else
885 log->Printf ("ProcessGDBRemote::%s no STDIO paths given via launch_info", __FUNCTION__);
886 }
887
Vince Harrondf3f00f2015-02-10 21:09:04 +0000888 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Chaoren Lind3173f32015-05-29 19:52:29 +0000889 if (stdin_file_spec || disable_stdio)
Vince Harrondf3f00f2015-02-10 21:09:04 +0000890 {
891 // the inferior will be reading stdin from the specified file
892 // or stdio is completely disabled
893 m_stdin_forward = false;
894 }
895 else
896 {
897 m_stdin_forward = true;
898 }
899
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000900 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
901 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
902 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000903
Greg Clayton982c9762011-11-03 21:22:33 +0000904 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000905 if (object_file)
906 {
Greg Clayton71337622011-02-24 22:24:29 +0000907 // Make sure we aren't already connected?
908 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000909 {
Greg Clayton91a9b2472013-12-04 19:19:12 +0000910 error = LaunchAndConnectToDebugserver (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000911 }
912
913 if (error.Success())
914 {
915 lldb_utility::PseudoTerminal pty;
916 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000917
Greg Claytonf58c2692011-06-24 22:32:10 +0000918 PlatformSP platform_sp (m_target.GetPlatform());
Vince Harrondf3f00f2015-02-10 21:09:04 +0000919 if (disable_stdio)
Greg Clayton71337622011-02-24 22:24:29 +0000920 {
Vince Harrondf3f00f2015-02-10 21:09:04 +0000921 // set to /dev/null unless redirected to a file above
Chaoren Lind3173f32015-05-29 19:52:29 +0000922 if (!stdin_file_spec)
923 stdin_file_spec.SetFile("/dev/null", false);
924 if (!stdout_file_spec)
925 stdout_file_spec.SetFile("/dev/null", false);
926 if (!stderr_file_spec)
927 stderr_file_spec.SetFile("/dev/null", false);
Vince Harrondf3f00f2015-02-10 21:09:04 +0000928 }
929 else if (platform_sp && platform_sp->IsHost())
930 {
931 // If the debugserver is local and we aren't disabling STDIO, lets use
932 // a pseudo terminal to instead of relying on the 'O' packets for stdio
933 // since 'O' packets can really slow down debugging if the inferior
934 // does a lot of output.
Chaoren Lind3173f32015-05-29 19:52:29 +0000935 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
936 pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000937 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000938 FileSpec slave_name{pty.GetSlaveName(NULL, 0), false};
939
940 if (!stdin_file_spec)
941 stdin_file_spec = slave_name;
942
943 if (!stdout_file_spec)
944 stdout_file_spec = slave_name;
945
946 if (!stderr_file_spec)
947 stderr_file_spec = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000948 }
Todd Fiala75f47c32014-10-11 21:42:09 +0000949 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +0000950 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 +0000951 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000952 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
953 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
954 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Greg Clayton71337622011-02-24 22:24:29 +0000955 }
956
Todd Fiala75f47c32014-10-11 21:42:09 +0000957 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +0000958 log->Printf ("ProcessGDBRemote::%s final STDIO paths after all adjustments: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000959 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000960 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
961 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
962 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Todd Fiala75f47c32014-10-11 21:42:09 +0000963
Chaoren Lind3173f32015-05-29 19:52:29 +0000964 if (stdin_file_spec)
965 m_gdb_comm.SetSTDIN(stdin_file_spec);
966 if (stdout_file_spec)
967 m_gdb_comm.SetSTDOUT(stdout_file_spec);
968 if (stderr_file_spec)
969 m_gdb_comm.SetSTDERR(stderr_file_spec);
Greg Clayton71337622011-02-24 22:24:29 +0000970
971 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
Jim Ingham106d0282014-06-25 02:32:56 +0000972 m_gdb_comm.SetDetachOnError (launch_flags & eLaunchFlagDetachOnError);
Greg Clayton71337622011-02-24 22:24:29 +0000973
Greg Claytonc4103b32011-05-08 04:53:50 +0000974 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Clayton71337622011-02-24 22:24:29 +0000975
Jason Molendaa3329782014-03-29 18:54:20 +0000976 const char * launch_event_data = launch_info.GetLaunchEventData();
977 if (launch_event_data != NULL && *launch_event_data != '\0')
978 m_gdb_comm.SendLaunchEventDataPacket (launch_event_data);
979
Chaoren Lind3173f32015-05-29 19:52:29 +0000980 if (working_dir)
Greg Clayton71337622011-02-24 22:24:29 +0000981 {
982 m_gdb_comm.SetWorkingDir (working_dir);
983 }
984
985 // Send the environment and the program + arguments after we connect
Greg Clayton982c9762011-11-03 21:22:33 +0000986 const Args &environment = launch_info.GetEnvironmentEntries();
987 if (environment.GetArgumentCount())
Greg Clayton71337622011-02-24 22:24:29 +0000988 {
Greg Clayton982c9762011-11-03 21:22:33 +0000989 size_t num_environment_entries = environment.GetArgumentCount();
990 for (size_t i=0; i<num_environment_entries; ++i)
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000991 {
Greg Clayton982c9762011-11-03 21:22:33 +0000992 const char *env_entry = environment.GetArgumentAtIndex(i);
993 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Clayton71337622011-02-24 22:24:29 +0000994 break;
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000995 }
Greg Clayton71337622011-02-24 22:24:29 +0000996 }
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000997
Greg Clayton71337622011-02-24 22:24:29 +0000998 {
Tamas Berghammer912800c2015-02-24 10:23:39 +0000999 // Scope for the scoped timeout object
1000 GDBRemoteCommunication::ScopedTimeout timeout (m_gdb_comm, 10);
1001
1002 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
1003 if (arg_packet_err == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001004 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001005 std::string error_str;
1006 if (m_gdb_comm.GetLaunchSuccess (error_str))
1007 {
1008 SetID (m_gdb_comm.GetCurrentProcessID ());
1009 }
1010 else
1011 {
1012 error.SetErrorString (error_str.c_str());
1013 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001014 }
1015 else
1016 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001017 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001018 }
Greg Clayton71337622011-02-24 22:24:29 +00001019 }
Tamas Berghammer912800c2015-02-24 10:23:39 +00001020
Greg Clayton71337622011-02-24 22:24:29 +00001021 if (GetID() == LLDB_INVALID_PROCESS_ID)
1022 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001023 if (log)
1024 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton71337622011-02-24 22:24:29 +00001025 KillDebugserverProcess ();
1026 return error;
1027 }
1028
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001029 StringExtractorGDBRemote response;
1030 if (m_gdb_comm.GetStopReply(response))
Greg Clayton71337622011-02-24 22:24:29 +00001031 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001032 SetLastStopPacket(response);
Ewan Crawford78baa192015-05-13 09:18:18 +00001033 // '?' Packets must be handled differently in non-stop mode
1034 if (GetTarget().GetNonStopModeEnabled())
1035 HandleStopReplySequence();
1036
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001037 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
1038
1039 if (process_arch.IsValid())
Jason Molendac62bd7b2013-12-21 05:20:36 +00001040 {
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001041 m_target.MergeArchitecture(process_arch);
1042 }
1043 else
1044 {
1045 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
1046 if (host_arch.IsValid())
1047 m_target.MergeArchitecture(host_arch);
Carlo Kok74389122013-10-14 07:09:13 +00001048 }
1049
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001050 SetPrivateState (SetThreadStopInfo (response));
Greg Clayton71337622011-02-24 22:24:29 +00001051
1052 if (!disable_stdio)
1053 {
1054 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Claytonee95ed52011-11-17 22:14:31 +00001055 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Clayton71337622011-02-24 22:24:29 +00001056 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001057 }
1058 }
Greg Claytonc235ac72011-08-09 05:20:29 +00001059 else
1060 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001061 if (log)
1062 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytonc235ac72011-08-09 05:20:29 +00001063 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001064 }
1065 else
1066 {
1067 // Set our user ID to an invalid process ID.
1068 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton982c9762011-11-03 21:22:33 +00001069 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
1070 exe_module->GetFileSpec().GetFilename().AsCString(),
1071 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001072 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001073 return error;
Greg Clayton4957bf62010-09-30 21:49:03 +00001074
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001075}
1076
1077
1078Error
Greg Claytonb766a732011-02-04 01:58:07 +00001079ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001080{
1081 Error error;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001082 // Only connect if we have a valid connect URL
Vince Harron1b5a74e2015-01-21 22:42:49 +00001083 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton00fe87b2013-12-05 22:58:22 +00001084
1085 if (connect_url && connect_url[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001086 {
Vince Harron1b5a74e2015-01-21 22:42:49 +00001087 if (log)
1088 log->Printf("ProcessGDBRemote::%s Connecting to %s", __FUNCTION__, connect_url);
Greg Clayton00fe87b2013-12-05 22:58:22 +00001089 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
1090 if (conn_ap.get())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001091 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001092 const uint32_t max_retry_count = 50;
1093 uint32_t retry_count = 0;
1094 while (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001095 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001096 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
1097 {
1098 m_gdb_comm.SetConnection (conn_ap.release());
1099 break;
1100 }
1101 else if (error.WasInterrupted())
1102 {
1103 // If we were interrupted, don't keep retrying.
1104 break;
1105 }
1106
1107 retry_count++;
1108
1109 if (retry_count >= max_retry_count)
1110 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001111
Greg Clayton00fe87b2013-12-05 22:58:22 +00001112 usleep (100000);
1113 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001114 }
1115 }
1116
1117 if (!m_gdb_comm.IsConnected())
1118 {
1119 if (error.Success())
1120 error.SetErrorString("not connected to remote gdb server");
1121 return error;
1122 }
1123
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001124
1125 // Start the communications read thread so all incoming data can be
1126 // parsed into packets and queued as they arrive.
1127 if (GetTarget().GetNonStopModeEnabled())
1128 m_gdb_comm.StartReadThread();
1129
Greg Clayton32e0a752011-03-30 18:16:51 +00001130 // We always seem to be able to open a connection to a local port
1131 // so we need to make sure we can then send data to it. If we can't
1132 // then we aren't actually connected to anything, so try and do the
1133 // handshake with the remote GDB server and make sure that goes
1134 // alright.
Greg Claytonfb909312013-11-23 01:58:15 +00001135 if (!m_gdb_comm.HandshakeWithServer (&error))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001136 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001137 m_gdb_comm.Disconnect();
1138 if (error.Success())
1139 error.SetErrorString("not connected to remote gdb server");
1140 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001141 }
Ewan Crawford78baa192015-05-13 09:18:18 +00001142
1143 // Send $QNonStop:1 packet on startup if required
1144 if (GetTarget().GetNonStopModeEnabled())
Ewan Crawfordaa7eda72015-06-24 15:14:26 +00001145 GetTarget().SetNonStopModeEnabled (m_gdb_comm.SetNonStopMode(true));
Ewan Crawford78baa192015-05-13 09:18:18 +00001146
Greg Claytonb30c50c2015-05-29 00:01:55 +00001147 m_gdb_comm.GetEchoSupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001148 m_gdb_comm.GetThreadSuffixSupported ();
Greg Clayton44633992012-04-10 03:22:03 +00001149 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001150 m_gdb_comm.GetHostInfo ();
1151 m_gdb_comm.GetVContSupported ('c');
Jim Inghamcd16df92012-07-20 21:37:13 +00001152 m_gdb_comm.GetVAttachOrWaitSupported();
Ewan Crawford78baa192015-05-13 09:18:18 +00001153
1154 // Ask the remote server for the default thread id
1155 if (GetTarget().GetNonStopModeEnabled())
1156 m_gdb_comm.GetDefaultThreadId(m_initial_tid);
1157
1158
Jim Ingham03afad82012-07-02 05:40:07 +00001159 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1160 for (size_t idx = 0; idx < num_cmds; idx++)
1161 {
1162 StringExtractorGDBRemote response;
Jim Ingham03afad82012-07-02 05:40:07 +00001163 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1164 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001165 return error;
1166}
1167
1168void
Jim Inghambb006ce2014-08-02 00:33:35 +00001169ProcessGDBRemote::DidLaunchOrAttach (ArchSpec& process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001170{
Greg Clayton5160ce52013-03-27 23:08:40 +00001171 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001172 if (log)
1173 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton93d3c8332011-02-16 04:46:07 +00001174 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001175 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001176 BuildDynamicRegisterInfo (false);
Greg Clayton3af9ea52010-11-18 05:57:03 +00001177
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001178 // See if the GDB server supports the qHostInfo information
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001179
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001180
1181 // See if the GDB server supports the qProcessInfo packet, if so
1182 // prefer that over the Host information as it will be more specific
1183 // to our process.
1184
Todd Fiala75f47c32014-10-11 21:42:09 +00001185 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1186 if (remote_process_arch.IsValid())
1187 {
1188 process_arch = remote_process_arch;
1189 if (log)
1190 log->Printf ("ProcessGDBRemote::%s gdb-remote had process architecture, using %s %s",
1191 __FUNCTION__,
1192 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1193 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1194 }
Jim Inghambb006ce2014-08-02 00:33:35 +00001195 else
Todd Fiala75f47c32014-10-11 21:42:09 +00001196 {
Jim Inghambb006ce2014-08-02 00:33:35 +00001197 process_arch = m_gdb_comm.GetHostArchitecture();
Todd Fiala75f47c32014-10-11 21:42:09 +00001198 if (log)
1199 log->Printf ("ProcessGDBRemote::%s gdb-remote did not have process architecture, using gdb-remote host architecture %s %s",
1200 __FUNCTION__,
1201 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1202 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1203 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001204
Jim Inghambb006ce2014-08-02 00:33:35 +00001205 if (process_arch.IsValid())
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001206 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001207 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Greg Claytond314e812011-03-23 00:09:55 +00001208 if (target_arch.IsValid())
1209 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001210 if (log)
1211 log->Printf ("ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1212 __FUNCTION__,
1213 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1214 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
1215
1216 // If the remote host is ARM and we have apple as the vendor, then
Greg Claytond314e812011-03-23 00:09:55 +00001217 // ARM executables and shared libraries can have mixed ARM architectures.
1218 // You can have an armv6 executable, and if the host is armv7, then the
1219 // system will load the best possible architecture for all shared libraries
1220 // it has, so we really need to take the remote host architecture as our
1221 // defacto architecture in this case.
1222
Jim Inghambb006ce2014-08-02 00:33:35 +00001223 if (process_arch.GetMachine() == llvm::Triple::arm &&
1224 process_arch.GetTriple().getVendor() == llvm::Triple::Apple)
Greg Claytond314e812011-03-23 00:09:55 +00001225 {
Jason Molenda921c01b2014-08-03 21:42:52 +00001226 GetTarget().SetArchitecture (process_arch);
Todd Fiala75f47c32014-10-11 21:42:09 +00001227 if (log)
1228 log->Printf ("ProcessGDBRemote::%s remote process is ARM/Apple, setting target arch to %s %s",
1229 __FUNCTION__,
1230 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1231 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001232 }
1233 else
1234 {
1235 // Fill in what is missing in the triple
Jim Inghambb006ce2014-08-02 00:33:35 +00001236 const llvm::Triple &remote_triple = process_arch.GetTriple();
Tamas Berghammere724af12015-03-13 10:32:37 +00001237 llvm::Triple new_target_triple = target_arch.GetTriple();
1238 if (new_target_triple.getVendorName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001239 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001240 new_target_triple.setVendor (remote_triple.getVendor());
Greg Claytond314e812011-03-23 00:09:55 +00001241
Tamas Berghammere724af12015-03-13 10:32:37 +00001242 if (new_target_triple.getOSName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001243 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001244 new_target_triple.setOS (remote_triple.getOS());
Greg Claytond314e812011-03-23 00:09:55 +00001245
Tamas Berghammere724af12015-03-13 10:32:37 +00001246 if (new_target_triple.getEnvironmentName().size() == 0)
1247 new_target_triple.setEnvironment (remote_triple.getEnvironment());
Greg Clayton70b57652011-05-15 01:25:55 +00001248 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001249
Tamas Berghammere724af12015-03-13 10:32:37 +00001250 ArchSpec new_target_arch = target_arch;
1251 new_target_arch.SetTriple(new_target_triple);
1252 GetTarget().SetArchitecture(new_target_arch);
1253 }
Greg Claytond314e812011-03-23 00:09:55 +00001254 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001255
1256 if (log)
1257 log->Printf ("ProcessGDBRemote::%s final target arch after adjustments for remote architecture: %s %s",
1258 __FUNCTION__,
1259 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1260 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001261 }
1262 else
1263 {
1264 // The target doesn't have a valid architecture yet, set it from
1265 // the architecture we got from the remote GDB server
Jason Molenda921c01b2014-08-03 21:42:52 +00001266 GetTarget().SetArchitecture (process_arch);
Greg Claytond314e812011-03-23 00:09:55 +00001267 }
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001268 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001269 }
1270}
1271
1272void
1273ProcessGDBRemote::DidLaunch ()
1274{
Jim Inghambb006ce2014-08-02 00:33:35 +00001275 ArchSpec process_arch;
1276 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001277}
1278
1279Error
Han Ming Ong84647042012-02-25 01:07:38 +00001280ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1281{
Todd Fiala75f47c32014-10-11 21:42:09 +00001282 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001283 Error error;
Todd Fiala75f47c32014-10-11 21:42:09 +00001284
1285 if (log)
1286 log->Printf ("ProcessGDBRemote::%s()", __FUNCTION__);
1287
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001288 // Clear out and clean up from any current state
1289 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001290 if (attach_pid != LLDB_INVALID_PROCESS_ID)
1291 {
Greg Clayton71337622011-02-24 22:24:29 +00001292 // Make sure we aren't already connected?
1293 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001294 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001295 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001296
1297 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001298 {
Greg Clayton71337622011-02-24 22:24:29 +00001299 const char *error_string = error.AsCString();
1300 if (error_string == NULL)
1301 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1302
1303 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001304 }
Greg Clayton71337622011-02-24 22:24:29 +00001305 }
1306
1307 if (error.Success())
1308 {
Jim Ingham106d0282014-06-25 02:32:56 +00001309 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
Todd Fiala75f47c32014-10-11 21:42:09 +00001310
Greg Clayton71337622011-02-24 22:24:29 +00001311 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001312 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Greg Clayton3b608422011-11-19 02:11:30 +00001313 SetID (attach_pid);
Greg Clayton71337622011-02-24 22:24:29 +00001314 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001315 }
1316 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001317
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001318 return error;
1319}
1320
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001321Error
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001322ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001323{
1324 Error error;
1325 // Clear out and clean up from any current state
1326 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001327
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001328 if (process_name && process_name[0])
1329 {
Greg Clayton71337622011-02-24 22:24:29 +00001330 // Make sure we aren't already connected?
1331 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001332 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001333 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001334
Greg Clayton71337622011-02-24 22:24:29 +00001335 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001336 {
Greg Clayton71337622011-02-24 22:24:29 +00001337 const char *error_string = error.AsCString();
1338 if (error_string == NULL)
1339 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001340
Greg Clayton71337622011-02-24 22:24:29 +00001341 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001342 }
Greg Clayton71337622011-02-24 22:24:29 +00001343 }
1344
1345 if (error.Success())
1346 {
1347 StreamString packet;
1348
Jim Ingham106d0282014-06-25 02:32:56 +00001349 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1350
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001351 if (attach_info.GetWaitForLaunch())
Jim Inghamcd16df92012-07-20 21:37:13 +00001352 {
1353 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1354 {
1355 packet.PutCString ("vAttachWait");
1356 }
1357 else
1358 {
1359 if (attach_info.GetIgnoreExisting())
1360 packet.PutCString("vAttachWait");
1361 else
1362 packet.PutCString ("vAttachOrWait");
1363 }
1364 }
Greg Clayton71337622011-02-24 22:24:29 +00001365 else
1366 packet.PutCString("vAttachName");
1367 packet.PutChar(';');
1368 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1369
1370 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1371
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001372 }
1373 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001374 return error;
1375}
1376
Greg Clayton5df78fa2015-05-23 03:54:53 +00001377void
1378ProcessGDBRemote::DidExit ()
Greg Claytonfbb76342013-11-20 21:07:01 +00001379{
Greg Clayton5df78fa2015-05-23 03:54:53 +00001380 // When we exit, disconnect from the GDB server communications
Greg Claytonfbb76342013-11-20 21:07:01 +00001381 m_gdb_comm.Disconnect();
Greg Claytonfbb76342013-11-20 21:07:01 +00001382}
1383
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001384void
Jim Inghambb006ce2014-08-02 00:33:35 +00001385ProcessGDBRemote::DidAttach (ArchSpec &process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001386{
Jim Inghambb006ce2014-08-02 00:33:35 +00001387 // If you can figure out what the architecture is, fill it in here.
1388 process_arch.Clear();
1389 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001390}
1391
Greg Clayton90ba8112012-12-05 00:16:59 +00001392
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001393Error
1394ProcessGDBRemote::WillResume ()
1395{
Greg Clayton71fc2a32011-02-12 06:28:37 +00001396 m_continue_c_tids.clear();
1397 m_continue_C_tids.clear();
1398 m_continue_s_tids.clear();
1399 m_continue_S_tids.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001400 return Error();
1401}
1402
1403Error
1404ProcessGDBRemote::DoResume ()
1405{
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001406 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001407 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001408 if (log)
1409 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytone5219662010-12-03 06:02:24 +00001410
1411 Listener listener ("gdb-remote.resume-packet-sent");
1412 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1413 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00001414 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1415
Greg Claytond1d06e42013-04-20 00:27:58 +00001416 const size_t num_threads = GetThreadList().GetSize();
1417
Greg Clayton71fc2a32011-02-12 06:28:37 +00001418 StreamString continue_packet;
1419 bool continue_packet_error = false;
1420 if (m_gdb_comm.HasAnyVContSupport ())
1421 {
Ewan Crawford78baa192015-05-13 09:18:18 +00001422 if (!GetTarget().GetNonStopModeEnabled() &&
1423 (m_continue_c_tids.size() == num_threads ||
Greg Claytone98008c2014-02-13 23:34:38 +00001424 (m_continue_c_tids.empty() &&
1425 m_continue_C_tids.empty() &&
1426 m_continue_s_tids.empty() &&
Ewan Crawford78baa192015-05-13 09:18:18 +00001427 m_continue_S_tids.empty())))
Greg Clayton71fc2a32011-02-12 06:28:37 +00001428 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001429 // All threads are continuing, just send a "c" packet
1430 continue_packet.PutCString ("c");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001431 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001432 else
1433 {
1434 continue_packet.PutCString ("vCont");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001435
Greg Claytond1d06e42013-04-20 00:27:58 +00001436 if (!m_continue_c_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001437 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001438 if (m_gdb_comm.GetVContSupported ('c'))
1439 {
1440 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)
1441 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1442 }
1443 else
1444 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001445 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001446
1447 if (!continue_packet_error && !m_continue_C_tids.empty())
1448 {
1449 if (m_gdb_comm.GetVContSupported ('C'))
1450 {
1451 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)
1452 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1453 }
1454 else
1455 continue_packet_error = true;
1456 }
Greg Claytone5219662010-12-03 06:02:24 +00001457
Greg Claytond1d06e42013-04-20 00:27:58 +00001458 if (!continue_packet_error && !m_continue_s_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001459 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001460 if (m_gdb_comm.GetVContSupported ('s'))
1461 {
1462 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)
1463 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1464 }
1465 else
1466 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001467 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001468
1469 if (!continue_packet_error && !m_continue_S_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001470 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001471 if (m_gdb_comm.GetVContSupported ('S'))
1472 {
1473 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)
1474 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1475 }
1476 else
1477 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001478 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001479
1480 if (continue_packet_error)
1481 continue_packet.GetString().clear();
Greg Clayton71fc2a32011-02-12 06:28:37 +00001482 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001483 }
1484 else
1485 continue_packet_error = true;
1486
1487 if (continue_packet_error)
1488 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001489 // Either no vCont support, or we tried to use part of the vCont
1490 // packet that wasn't supported by the remote GDB server.
1491 // We need to try and make a simple packet that can do our continue
Greg Clayton71fc2a32011-02-12 06:28:37 +00001492 const size_t num_continue_c_tids = m_continue_c_tids.size();
1493 const size_t num_continue_C_tids = m_continue_C_tids.size();
1494 const size_t num_continue_s_tids = m_continue_s_tids.size();
1495 const size_t num_continue_S_tids = m_continue_S_tids.size();
1496 if (num_continue_c_tids > 0)
1497 {
1498 if (num_continue_c_tids == num_threads)
1499 {
1500 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001501 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001502 continue_packet.PutChar ('c');
1503 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001504 }
1505 else if (num_continue_c_tids == 1 &&
1506 num_continue_C_tids == 0 &&
1507 num_continue_s_tids == 0 &&
1508 num_continue_S_tids == 0 )
1509 {
1510 // Only one thread is continuing
Greg Clayton8b82f082011-04-12 05:54:46 +00001511 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001512 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001513 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001514 }
1515 }
1516
Greg Clayton0c74e782011-06-24 03:21:43 +00001517 if (continue_packet_error && num_continue_C_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001518 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001519 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1520 num_continue_C_tids > 0 &&
1521 num_continue_s_tids == 0 &&
1522 num_continue_S_tids == 0 )
Greg Clayton71fc2a32011-02-12 06:28:37 +00001523 {
1524 const int continue_signo = m_continue_C_tids.front().second;
Greg Clayton0c74e782011-06-24 03:21:43 +00001525 // Only one thread is continuing
Greg Clayton71fc2a32011-02-12 06:28:37 +00001526 if (num_continue_C_tids > 1)
1527 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001528 // More that one thread with a signal, yet we don't have
1529 // vCont support and we are being asked to resume each
1530 // thread with a signal, we need to make sure they are
1531 // all the same signal, or we can't issue the continue
1532 // accurately with the current support...
1533 if (num_continue_C_tids > 1)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001534 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001535 continue_packet_error = false;
1536 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1537 {
1538 if (m_continue_C_tids[i].second != continue_signo)
1539 continue_packet_error = true;
1540 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001541 }
Greg Clayton0c74e782011-06-24 03:21:43 +00001542 if (!continue_packet_error)
1543 m_gdb_comm.SetCurrentThreadForRun (-1);
1544 }
1545 else
1546 {
1547 // Set the continue thread ID
1548 continue_packet_error = false;
1549 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001550 }
1551 if (!continue_packet_error)
1552 {
1553 // Add threads continuing with the same signo...
Greg Clayton71fc2a32011-02-12 06:28:37 +00001554 continue_packet.Printf("C%2.2x", continue_signo);
1555 }
1556 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001557 }
1558
Greg Clayton0c74e782011-06-24 03:21:43 +00001559 if (continue_packet_error && num_continue_s_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001560 {
1561 if (num_continue_s_tids == num_threads)
1562 {
1563 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001564 m_gdb_comm.SetCurrentThreadForRun (-1);
Ewan Crawford76df2882015-06-23 12:32:06 +00001565
1566 // If in Non-Stop-Mode use vCont when stepping
1567 if (GetTarget().GetNonStopModeEnabled())
1568 {
1569 if (m_gdb_comm.GetVContSupported('s'))
1570 continue_packet.PutCString("vCont;s");
1571 else
1572 continue_packet.PutChar('s');
1573 }
1574 else
1575 continue_packet.PutChar('s');
1576
Greg Clayton0c74e782011-06-24 03:21:43 +00001577 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001578 }
1579 else if (num_continue_c_tids == 0 &&
1580 num_continue_C_tids == 0 &&
1581 num_continue_s_tids == 1 &&
1582 num_continue_S_tids == 0 )
1583 {
1584 // Only one thread is stepping
Greg Clayton8b82f082011-04-12 05:54:46 +00001585 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001586 continue_packet.PutChar ('s');
Greg Clayton0c74e782011-06-24 03:21:43 +00001587 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001588 }
1589 }
1590
1591 if (!continue_packet_error && num_continue_S_tids > 0)
1592 {
1593 if (num_continue_S_tids == num_threads)
1594 {
1595 const int step_signo = m_continue_S_tids.front().second;
1596 // Are all threads trying to step with the same signal?
Greg Clayton0c74e782011-06-24 03:21:43 +00001597 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001598 if (num_continue_S_tids > 1)
1599 {
1600 for (size_t i=1; i<num_threads; ++i)
1601 {
1602 if (m_continue_S_tids[i].second != step_signo)
1603 continue_packet_error = true;
1604 }
1605 }
1606 if (!continue_packet_error)
1607 {
1608 // Add threads stepping with the same signo...
Greg Clayton8b82f082011-04-12 05:54:46 +00001609 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001610 continue_packet.Printf("S%2.2x", step_signo);
1611 }
1612 }
1613 else if (num_continue_c_tids == 0 &&
1614 num_continue_C_tids == 0 &&
1615 num_continue_s_tids == 0 &&
1616 num_continue_S_tids == 1 )
1617 {
1618 // Only one thread is stepping with signal
Greg Clayton8b82f082011-04-12 05:54:46 +00001619 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001620 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Clayton0c74e782011-06-24 03:21:43 +00001621 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001622 }
1623 }
1624 }
1625
1626 if (continue_packet_error)
1627 {
1628 error.SetErrorString ("can't make continue packet for this resume");
1629 }
1630 else
1631 {
1632 EventSP event_sp;
1633 TimeValue timeout;
1634 timeout = TimeValue::Now();
1635 timeout.OffsetWithSeconds (5);
Zachary Turneracee96a2014-09-23 18:32:09 +00001636 if (!m_async_thread.IsJoinable())
Jim Inghamb1e2e842012-04-12 18:49:31 +00001637 {
1638 error.SetErrorString ("Trying to resume but the async thread is dead.");
1639 if (log)
1640 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1641 return error;
1642 }
1643
Greg Clayton71fc2a32011-02-12 06:28:37 +00001644 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1645
1646 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Inghamb1e2e842012-04-12 18:49:31 +00001647 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001648 error.SetErrorString("Resume timed out.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00001649 if (log)
1650 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1651 }
1652 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1653 {
1654 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1655 if (log)
1656 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1657 return error;
1658 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001659 }
Greg Claytone5219662010-12-03 06:02:24 +00001660 }
1661
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001662 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001663}
1664
Greg Clayton9e920902012-04-10 02:25:43 +00001665void
Ewan Crawford78baa192015-05-13 09:18:18 +00001666ProcessGDBRemote::HandleStopReplySequence ()
1667{
1668 while(true)
1669 {
1670 // Send vStopped
1671 StringExtractorGDBRemote response;
1672 m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false);
1673
1674 // OK represents end of signal list
1675 if (response.IsOKResponse())
1676 break;
1677
1678 // If not OK or a normal packet we have a problem
1679 if (!response.IsNormalResponse())
1680 break;
1681
1682 SetLastStopPacket(response);
1683 }
1684}
1685
1686void
Greg Clayton9e920902012-04-10 02:25:43 +00001687ProcessGDBRemote::ClearThreadIDList ()
1688{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001689 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001690 m_thread_ids.clear();
1691}
1692
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001693size_t
1694ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue (std::string &value)
1695{
1696 m_thread_ids.clear();
1697 size_t comma_pos;
1698 lldb::tid_t tid;
1699 while ((comma_pos = value.find(',')) != std::string::npos)
1700 {
1701 value[comma_pos] = '\0';
1702 // thread in big endian hex
1703 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1704 if (tid != LLDB_INVALID_THREAD_ID)
1705 m_thread_ids.push_back (tid);
1706 value.erase(0, comma_pos + 1);
1707 }
1708 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1709 if (tid != LLDB_INVALID_THREAD_ID)
1710 m_thread_ids.push_back (tid);
1711 return m_thread_ids.size();
1712}
1713
Greg Clayton9e920902012-04-10 02:25:43 +00001714bool
1715ProcessGDBRemote::UpdateThreadIDList ()
1716{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001717 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001718
1719 if (m_threads_info_sp)
1720 {
1721 // If we have the JSON threads info, we can get the thread list from that
1722 StructuredData::Array *thread_infos = m_threads_info_sp->GetAsArray();
1723 if (thread_infos && thread_infos->GetSize() > 0)
1724 {
1725 m_thread_ids.clear();
1726 thread_infos->ForEach([this](StructuredData::Object* object) -> bool {
1727 StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1728 if (thread_dict)
1729 {
1730 // Set the thread stop info from the JSON dictionary
1731 SetThreadStopInfo (thread_dict);
1732 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1733 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1734 m_thread_ids.push_back(tid);
1735 }
1736 return true; // Keep iterating through all thread_info objects
1737 });
1738 }
1739 if (!m_thread_ids.empty())
1740 return true;
1741 }
1742 else
1743 {
1744 // See if we can get the thread IDs from the current stop reply packets
1745 // that might contain a "threads" key/value pair
1746
1747 // Lock the thread stack while we access it
1748 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
1749 // Get the number of stop packets on the stack
1750 int nItems = m_stop_packet_stack.size();
1751 // Iterate over them
1752 for (int i = 0; i < nItems; i++)
1753 {
1754 // Get the thread stop info
1755 StringExtractorGDBRemote &stop_info = m_stop_packet_stack[i];
1756 const std::string &stop_info_str = stop_info.GetStringRef();
1757 const size_t threads_pos = stop_info_str.find(";threads:");
1758 if (threads_pos != std::string::npos)
1759 {
1760 const size_t start = threads_pos + strlen(";threads:");
1761 const size_t end = stop_info_str.find(';', start);
1762 if (end != std::string::npos)
1763 {
1764 std::string value = stop_info_str.substr(start, end - start);
1765 if (UpdateThreadIDsFromStopReplyThreadsValue(value))
1766 return true;
1767 }
1768 }
1769 }
1770 }
1771
Greg Clayton9e920902012-04-10 02:25:43 +00001772 bool sequence_mutex_unavailable = false;
1773 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1774 if (sequence_mutex_unavailable)
1775 {
Greg Clayton9e920902012-04-10 02:25:43 +00001776 return false; // We just didn't get the list
1777 }
1778 return true;
1779}
1780
Greg Clayton9fc13552012-04-10 00:18:59 +00001781bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001782ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001783{
1784 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +00001785 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Clayton73b472d2010-10-27 03:32:59 +00001786 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +00001787 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton9e920902012-04-10 02:25:43 +00001788
1789 size_t num_thread_ids = m_thread_ids.size();
1790 // The "m_thread_ids" thread ID list should always be updated after each stop
1791 // reply packet, but in case it isn't, update it here.
1792 if (num_thread_ids == 0)
1793 {
1794 if (!UpdateThreadIDList ())
1795 return false;
1796 num_thread_ids = m_thread_ids.size();
1797 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001798
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001799 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001800 if (num_thread_ids > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001801 {
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001802 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001803 {
Greg Clayton9e920902012-04-10 02:25:43 +00001804 tid_t tid = m_thread_ids[i];
Greg Clayton160c9d82013-05-01 21:54:04 +00001805 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001806 if (!thread_sp)
Jim Inghamdee1bc92013-06-22 00:27:45 +00001807 {
Jim Ingham4f465cf2012-10-10 18:32:14 +00001808 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001809 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1810 log->Printf(
1811 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001812 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001813 thread_sp->GetID());
1814 }
1815 else
1816 {
1817 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1818 log->Printf(
1819 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001820 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001821 thread_sp->GetID());
1822 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001823 new_thread_list.AddThread(thread_sp);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001824 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001825 }
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001826
1827 // Whatever that is left in old_thread_list_copy are not
1828 // present in new_thread_list. Remove non-existent threads from internal id table.
1829 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1830 for (size_t i=0; i<old_num_thread_ids; i++)
1831 {
1832 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1833 if (old_thread_sp)
1834 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001835 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001836 m_thread_id_to_index_id_map.erase(old_thread_id);
1837 }
1838 }
1839
Greg Clayton9fc13552012-04-10 00:18:59 +00001840 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001841}
1842
Greg Clayton358cf1e2015-06-25 21:46:34 +00001843bool
1844ProcessGDBRemote::CalculateThreadStopInfo (ThreadGDBRemote *thread)
1845{
1846 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet
1847 if (m_threads_info_sp)
1848 {
1849 StructuredData::Array *thread_infos = m_threads_info_sp->GetAsArray();
1850 if (thread_infos)
1851 {
1852 lldb::tid_t tid;
1853 const size_t n = thread_infos->GetSize();
1854 for (size_t i=0; i<n; ++i)
1855 {
1856 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1857 if (thread_dict)
1858 {
1859 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid, LLDB_INVALID_THREAD_ID))
1860 {
1861 if (tid == thread->GetID())
1862 return SetThreadStopInfo(thread_dict);
1863 }
1864 }
1865 }
1866 }
1867 }
1868
1869 // Fall back to using the qThreadStopInfo packet
1870 StringExtractorGDBRemote stop_packet;
1871 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1872 return SetThreadStopInfo (stop_packet) == eStateStopped;
1873 return false;
1874}
1875
1876
1877ThreadSP
1878ProcessGDBRemote::SetThreadStopInfo (lldb::tid_t tid,
1879 ExpeditedRegisterMap &expedited_register_map,
1880 uint8_t signo,
1881 const std::string &thread_name,
1882 const std::string &reason,
1883 const std::string &description,
1884 uint32_t exc_type,
1885 const std::vector<addr_t> &exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001886 addr_t thread_dispatch_qaddr,
1887 bool queue_vars_valid, // Set to true if queue_name, queue_kind and queue_serial are valid
1888 std::string &queue_name,
1889 QueueKind queue_kind,
1890 uint64_t queue_serial)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001891{
1892 ThreadSP thread_sp;
1893 if (tid != LLDB_INVALID_THREAD_ID)
1894 {
1895 // Scope for "locker" below
1896 {
1897 // m_thread_list_real does have its own mutex, but we need to
1898 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1899 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1900 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1901 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1902
1903 if (!thread_sp)
1904 {
1905 // Create the thread if we need to
1906 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1907 m_thread_list_real.AddThread(thread_sp);
1908 }
1909 }
1910
1911 if (thread_sp)
1912 {
1913 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1914 gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001915
Greg Clayton358cf1e2015-06-25 21:46:34 +00001916 for (const auto &pair : expedited_register_map)
1917 {
1918 StringExtractor reg_value_extractor;
1919 reg_value_extractor.GetStringRef() = pair.second;
1920 gdb_thread->PrivateSetRegisterValue (pair.first, reg_value_extractor);
1921 }
1922
1923 // Clear the stop info just in case we don't set it to anything
1924 thread_sp->SetStopInfo (StopInfoSP());
1925 thread_sp->SetName (thread_name.empty() ? NULL : thread_name.c_str());
1926
1927 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001928 // Check if the GDB server was able to provide the queue name, kind and serial number
1929 if (queue_vars_valid)
1930 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind, queue_serial);
1931 else
1932 gdb_thread->ClearQueueInfo();
1933
1934
Greg Clayton358cf1e2015-06-25 21:46:34 +00001935 if (exc_type != 0)
1936 {
1937 const size_t exc_data_size = exc_data.size();
1938
1939 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1940 exc_type,
1941 exc_data_size,
1942 exc_data_size >= 1 ? exc_data[0] : 0,
1943 exc_data_size >= 2 ? exc_data[1] : 0,
1944 exc_data_size >= 3 ? exc_data[2] : 0));
1945 }
1946 else
1947 {
1948 bool handled = false;
1949 bool did_exec = false;
1950 if (!reason.empty())
1951 {
1952 if (reason.compare("trace") == 0)
1953 {
1954 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1955 handled = true;
1956 }
1957 else if (reason.compare("breakpoint") == 0)
1958 {
1959 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1960 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
1961 if (bp_site_sp)
1962 {
1963 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1964 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1965 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1966 handled = true;
1967 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
1968 {
1969 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1970 }
1971 else
1972 {
1973 StopInfoSP invalid_stop_info_sp;
1974 thread_sp->SetStopInfo (invalid_stop_info_sp);
1975 }
1976 }
1977 }
1978 else if (reason.compare("trap") == 0)
1979 {
1980 // Let the trap just use the standard signal stop reason below...
1981 }
1982 else if (reason.compare("watchpoint") == 0)
1983 {
1984 StringExtractor desc_extractor(description.c_str());
1985 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1986 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
1987 watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
1988 if (wp_addr != LLDB_INVALID_ADDRESS)
1989 {
1990 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
1991 if (wp_sp)
1992 {
1993 wp_sp->SetHardwareIndex(wp_index);
1994 watch_id = wp_sp->GetID();
1995 }
1996 }
1997 if (watch_id == LLDB_INVALID_WATCH_ID)
1998 {
1999 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_WATCHPOINTS));
2000 if (log) log->Printf ("failed to find watchpoint");
2001 }
2002 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
2003 handled = true;
2004 }
2005 else if (reason.compare("exception") == 0)
2006 {
2007 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
2008 handled = true;
2009 }
2010 else if (reason.compare("exec") == 0)
2011 {
2012 did_exec = true;
2013 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
2014 handled = true;
2015 }
2016 }
2017
2018 if (!handled && signo && did_exec == false)
2019 {
2020 if (signo == SIGTRAP)
2021 {
2022 // Currently we are going to assume SIGTRAP means we are either
2023 // hitting a breakpoint or hardware single stepping.
2024 handled = true;
2025 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
2026 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2027
2028 if (bp_site_sp)
2029 {
2030 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2031 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2032 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2033 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2034 {
2035 if(m_breakpoint_pc_offset != 0)
2036 thread_sp->GetRegisterContext()->SetPC(pc);
2037 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2038 }
2039 else
2040 {
2041 StopInfoSP invalid_stop_info_sp;
2042 thread_sp->SetStopInfo (invalid_stop_info_sp);
2043 }
2044 }
2045 else
2046 {
2047 // If we were stepping then assume the stop was the result of the trace. If we were
2048 // not stepping then report the SIGTRAP.
2049 // FIXME: We are still missing the case where we single step over a trap instruction.
2050 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
2051 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
2052 else
2053 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo, description.c_str()));
2054 }
2055 }
2056 if (!handled)
2057 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo, description.c_str()));
2058 }
2059
2060 if (!description.empty())
2061 {
2062 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
2063 if (stop_info_sp)
2064 {
2065 const char *stop_info_desc = stop_info_sp->GetDescription();
2066 if (!stop_info_desc || !stop_info_desc[0])
2067 stop_info_sp->SetDescription (description.c_str());
2068 }
2069 else
2070 {
2071 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
2072 }
2073 }
2074 }
2075 }
2076 }
2077 return thread_sp;
2078}
2079
2080StateType
2081ProcessGDBRemote::SetThreadStopInfo (StructuredData::Dictionary *thread_dict)
2082{
2083 static ConstString g_key_tid("tid");
2084 static ConstString g_key_name("name");
2085 static ConstString g_key_reason("reason");
2086 static ConstString g_key_metype("metype");
2087 static ConstString g_key_medata("medata");
2088 static ConstString g_key_qaddr("qaddr");
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002089 static ConstString g_key_queue_name("qname");
2090 static ConstString g_key_queue_kind("qkind");
2091 static ConstString g_key_queue_serial("qserial");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002092 static ConstString g_key_registers("registers");
2093 static ConstString g_key_memory("memory");
2094 static ConstString g_key_address("address");
2095 static ConstString g_key_bytes("bytes");
2096 static ConstString g_key_description("description");
2097
2098 // Stop with signal and thread info
2099 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2100 uint8_t signo = 0;
2101 std::string value;
2102 std::string thread_name;
2103 std::string reason;
2104 std::string description;
2105 uint32_t exc_type = 0;
2106 std::vector<addr_t> exc_data;
2107 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2108 ExpeditedRegisterMap expedited_register_map;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002109 bool queue_vars_valid = false;
2110 std::string queue_name;
2111 QueueKind queue_kind = eQueueKindUnknown;
2112 uint64_t queue_serial = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002113 // Iterate through all of the thread dictionary key/value pairs from the structured data dictionary
2114
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002115 thread_dict->ForEach([this,
2116 &tid,
2117 &expedited_register_map,
2118 &thread_name,
2119 &signo,
2120 &reason,
2121 &description,
2122 &exc_type,
2123 &exc_data,
2124 &thread_dispatch_qaddr,
2125 &queue_vars_valid,
2126 &queue_name,
2127 &queue_kind,
2128 &queue_serial]
2129 (ConstString key, StructuredData::Object* object) -> bool
Greg Clayton358cf1e2015-06-25 21:46:34 +00002130 {
2131 if (key == g_key_tid)
2132 {
2133 // thread in big endian hex
2134 tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
2135 }
2136 else if (key == g_key_metype)
2137 {
2138 // exception type in big endian hex
2139 exc_type = object->GetIntegerValue(0);
2140 }
2141 else if (key == g_key_medata)
2142 {
2143 // exception data in big endian hex
2144 StructuredData::Array *array = object->GetAsArray();
2145 if (array)
2146 {
2147 array->ForEach([&exc_data](StructuredData::Object* object) -> bool {
2148 exc_data.push_back(object->GetIntegerValue());
2149 return true; // Keep iterating through all array items
2150 });
2151 }
2152 }
2153 else if (key == g_key_name)
2154 {
2155 thread_name = std::move(object->GetStringValue());
2156 }
2157 else if (key == g_key_qaddr)
2158 {
2159 thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
2160 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002161 else if (key == g_key_queue_name)
2162 {
2163 queue_vars_valid = true;
2164 queue_name = std::move(object->GetStringValue());
2165 }
2166 else if (key == g_key_queue_kind)
2167 {
2168 std::string queue_kind_str = object->GetStringValue();
2169 if (queue_kind_str == "serial")
2170 {
2171 queue_vars_valid = true;
2172 queue_kind = eQueueKindSerial;
2173 }
2174 else if (queue_kind_str == "concurrent")
2175 {
2176 queue_vars_valid = true;
2177 queue_kind = eQueueKindConcurrent;
2178 }
2179 }
2180 else if (key == g_key_queue_serial)
2181 {
2182 queue_serial = object->GetIntegerValue(0);
2183 if (queue_serial != 0)
2184 queue_vars_valid = true;
2185 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002186 else if (key == g_key_reason)
2187 {
2188 reason = std::move(object->GetStringValue());
2189 }
2190 else if (key == g_key_description)
2191 {
2192 description = std::move(object->GetStringValue());
2193 }
2194 else if (key == g_key_registers)
2195 {
2196 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2197
2198 if (registers_dict)
2199 {
2200 registers_dict->ForEach([&expedited_register_map](ConstString key, StructuredData::Object* object) -> bool {
2201 const uint32_t reg = StringConvert::ToUInt32 (key.GetCString(), UINT32_MAX, 10);
2202 if (reg != UINT32_MAX)
2203 expedited_register_map[reg] = std::move(object->GetStringValue());
2204 return true; // Keep iterating through all array items
2205 });
2206 }
2207 }
2208 else if (key == g_key_memory)
2209 {
2210 StructuredData::Array *array = object->GetAsArray();
2211 if (array)
2212 {
2213 array->ForEach([this](StructuredData::Object* object) -> bool {
2214 StructuredData::Dictionary *mem_cache_dict = object->GetAsDictionary();
2215 if (mem_cache_dict)
2216 {
2217 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2218 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>("address", mem_cache_addr))
2219 {
2220 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
2221 {
2222 StringExtractor bytes;
2223 if (mem_cache_dict->GetValueForKeyAsString("bytes", bytes.GetStringRef()))
2224 {
2225 bytes.SetFilePos(0);
2226
2227 const size_t byte_size = bytes.GetStringRef().size()/2;
2228 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2229 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2230 if (bytes_copied == byte_size)
2231 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2232 }
2233 }
2234 }
2235 }
2236 return true; // Keep iterating through all array items
2237 });
2238 }
2239
2240 }
2241 return true; // Keep iterating through all dictionary key/value pairs
2242 });
2243
2244 SetThreadStopInfo (tid,
2245 expedited_register_map,
2246 signo,
2247 thread_name,
2248 reason,
2249 description,
2250 exc_type,
2251 exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002252 thread_dispatch_qaddr,
2253 queue_vars_valid,
2254 queue_name,
2255 queue_kind,
2256 queue_serial);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002257
2258 return eStateExited;
2259}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002260
2261StateType
2262ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
2263{
Greg Claytondd0e5a52011-06-02 22:22:38 +00002264 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002265 const char stop_type = stop_packet.GetChar();
2266 switch (stop_type)
2267 {
2268 case 'T':
2269 case 'S':
2270 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00002271 // This is a bit of a hack, but is is required. If we did exec, we
2272 // need to clear our thread lists and also know to rebuild our dynamic
2273 // register info before we lookup and threads and populate the expedited
2274 // register values so we need to know this right away so we can cleanup
2275 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00002276 const uint32_t stop_id = GetStopID();
2277 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00002278 {
2279 // Our first stop, make sure we have a process ID, and also make
2280 // sure we know about our registers
2281 if (GetID() == LLDB_INVALID_PROCESS_ID)
2282 {
Greg Claytonc574ede2011-03-10 02:26:48 +00002283 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00002284 if (pid != LLDB_INVALID_PROCESS_ID)
2285 SetID (pid);
2286 }
2287 BuildDynamicRegisterInfo (true);
2288 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002289 // Stop with signal and thread info
Greg Clayton358cf1e2015-06-25 21:46:34 +00002290 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002291 const uint8_t signo = stop_packet.GetHexU8();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002292 std::string key;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002293 std::string value;
2294 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00002295 std::string reason;
2296 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002297 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00002298 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002299 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton0b90be12015-06-23 21:27:50 +00002300 bool queue_vars_valid = false; // says if locals below that start with "queue_" are valid
2301 std::string queue_name;
2302 QueueKind queue_kind = eQueueKindUnknown;
2303 uint64_t queue_serial = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002304 ExpeditedRegisterMap expedited_register_map;
2305 while (stop_packet.GetNameColonValue(key, value))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002306 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002307 if (key.compare("metype") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002308 {
2309 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002310 exc_type = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002311 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002312 else if (key.compare("medata") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002313 {
2314 // exception data in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002315 exc_data.push_back(StringConvert::ToUInt64 (value.c_str(), 0, 16));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002316 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002317 else if (key.compare("thread") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002318 {
2319 // thread in big endian hex
Greg Clayton358cf1e2015-06-25 21:46:34 +00002320 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002321 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002322 else if (key.compare("threads") == 0)
Greg Clayton9e920902012-04-10 02:25:43 +00002323 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002324 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00002325 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00002326 // A comma separated list of all threads in the current
2327 // process that includes the thread for this stop reply
2328 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00002329 size_t comma_pos;
2330 lldb::tid_t tid;
2331 while ((comma_pos = value.find(',')) != std::string::npos)
2332 {
2333 value[comma_pos] = '\0';
2334 // thread in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002335 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00002336 if (tid != LLDB_INVALID_THREAD_ID)
2337 m_thread_ids.push_back (tid);
2338 value.erase(0, comma_pos + 1);
Greg Clayton9e920902012-04-10 02:25:43 +00002339 }
Vince Harron5275aaa2015-01-15 20:08:35 +00002340 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00002341 if (tid != LLDB_INVALID_THREAD_ID)
2342 m_thread_ids.push_back (tid);
2343 }
Greg Claytona5801ad2015-07-15 22:59:03 +00002344 else if (key.compare("jthreads") == 0)
2345 {
2346 StringExtractor json_extractor;
2347 // Swap "value" over into "name_extractor"
2348 json_extractor.GetStringRef().swap(value);
2349 // Now convert the HEX bytes into a string value
2350 json_extractor.GetHexByteString (value);
2351
2352 // This JSON contains thread IDs and thread stop info for all threads.
2353 // It doesn't contain expedited registers, memory or queue info.
2354 m_threads_info_sp = StructuredData::ParseJSON (value);
2355 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002356 else if (key.compare("hexname") == 0)
Greg Claytonde9d0492011-01-08 03:17:57 +00002357 {
2358 StringExtractor name_extractor;
2359 // Swap "value" over into "name_extractor"
2360 name_extractor.GetStringRef().swap(value);
2361 // Now convert the HEX bytes into a string value
2362 name_extractor.GetHexByteString (value);
2363 thread_name.swap (value);
2364 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002365 else if (key.compare("name") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002366 {
2367 thread_name.swap (value);
2368 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002369 else if (key.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002370 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002371 thread_dispatch_qaddr = StringConvert::ToUInt64 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002372 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002373 else if (key.compare("qname") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002374 {
2375 queue_vars_valid = true;
2376 StringExtractor name_extractor;
2377 // Swap "value" over into "name_extractor"
2378 name_extractor.GetStringRef().swap(value);
2379 // Now convert the HEX bytes into a string value
2380 name_extractor.GetHexByteString (value);
2381 queue_name.swap (value);
2382 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002383 else if (key.compare("qkind") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002384 {
Greg Clayton0b90be12015-06-23 21:27:50 +00002385 if (value == "serial")
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002386 {
2387 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002388 queue_kind = eQueueKindSerial;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002389 }
Greg Clayton0b90be12015-06-23 21:27:50 +00002390 else if (value == "concurrent")
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002391 {
2392 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002393 queue_kind = eQueueKindConcurrent;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002394 }
Greg Clayton0b90be12015-06-23 21:27:50 +00002395 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002396 else if (key.compare("qserial") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002397 {
Greg Clayton0b90be12015-06-23 21:27:50 +00002398 queue_serial = StringConvert::ToUInt64 (value.c_str(), 0, 0);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002399 if (queue_serial != 0)
2400 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002401 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002402 else if (key.compare("reason") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002403 {
2404 reason.swap(value);
2405 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002406 else if (key.compare("description") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002407 {
2408 StringExtractor desc_extractor;
2409 // Swap "value" over into "name_extractor"
2410 desc_extractor.GetStringRef().swap(value);
2411 // Now convert the HEX bytes into a string value
Chaoren Lin28e57422015-02-03 01:51:25 +00002412 desc_extractor.GetHexByteString (value);
2413 description.swap(value);
Greg Claytona658fd22011-06-04 01:26:29 +00002414 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002415 else if (key.compare("memory") == 0)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002416 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002417 // Expedited memory. GDB servers can choose to send back expedited memory
2418 // that can populate the L1 memory cache in the process so that things like
2419 // the frame pointer backchain can be expedited. This will help stack
2420 // backtracing be more efficient by not having to send as many memory read
2421 // requests down the remote GDB server.
Chaoren Lin7a306082015-06-23 03:17:01 +00002422
Greg Clayton358cf1e2015-06-25 21:46:34 +00002423 // Key/value pair format: memory:<addr>=<bytes>;
2424 // <addr> is a number whose base will be interpreted by the prefix:
2425 // "0x[0-9a-fA-F]+" for hex
2426 // "0[0-7]+" for octal
2427 // "[1-9]+" for decimal
2428 // <bytes> is native endian ASCII hex bytes just like the register values
2429 llvm::StringRef value_ref(value);
2430 std::pair<llvm::StringRef, llvm::StringRef> pair;
2431 pair = value_ref.split('=');
2432 if (!pair.first.empty() && !pair.second.empty())
2433 {
2434 std::string addr_str(pair.first.str());
2435 const lldb::addr_t mem_cache_addr = StringConvert::ToUInt64(addr_str.c_str(), LLDB_INVALID_ADDRESS, 0);
2436 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002437 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002438 StringExtractor bytes;
2439 bytes.GetStringRef() = std::move(pair.second.str());
2440 const size_t byte_size = bytes.GetStringRef().size()/2;
2441 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2442 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2443 if (bytes_copied == byte_size)
2444 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
Greg Clayton3e06bd92011-01-09 21:07:35 +00002445 }
2446 }
2447 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002448 else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1]))
2449 {
2450 uint32_t reg = StringConvert::ToUInt32 (key.c_str(), UINT32_MAX, 16);
2451 if (reg != UINT32_MAX)
2452 expedited_register_map[reg] = std::move(value);
2453 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002454 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002455
Greg Clayton358cf1e2015-06-25 21:46:34 +00002456 ThreadSP thread_sp = SetThreadStopInfo (tid,
2457 expedited_register_map,
2458 signo,
2459 thread_name,
2460 reason,
2461 description,
2462 exc_type,
2463 exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002464 thread_dispatch_qaddr,
2465 queue_vars_valid,
2466 queue_name,
2467 queue_kind,
2468 queue_serial);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002469
Hafiz Abid Qadeer673b4a32014-02-20 10:23:20 +00002470 // If the response is old style 'S' packet which does not provide us with thread information
2471 // then update the thread list and choose the first one.
2472 if (!thread_sp)
2473 {
2474 UpdateThreadIDList ();
2475
2476 if (!m_thread_ids.empty ())
2477 {
2478 Mutex::Locker locker (m_thread_list_real.GetMutex ());
2479 thread_sp = m_thread_list_real.FindThreadByProtocolID (m_thread_ids.front (), false);
Hafiz Abid Qadeer673b4a32014-02-20 10:23:20 +00002480 }
2481 }
2482
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002483 return eStateStopped;
2484 }
2485 break;
2486
2487 case 'W':
Todd Fialaff6131a2014-05-19 04:57:23 +00002488 case 'X':
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002489 // process exited
2490 return eStateExited;
2491
2492 default:
2493 break;
2494 }
2495 return eStateInvalid;
2496}
2497
2498void
2499ProcessGDBRemote::RefreshStateAfterStop ()
2500{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002501 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00002502 m_thread_ids.clear();
2503 // Set the thread stop info. It might have a "threads" key whose value is
2504 // a list of all thread IDs in the current process, so m_thread_ids might
2505 // get set.
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002506
2507 // Scope for the lock
2508 {
2509 // Lock the thread stack while we access it
2510 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
2511 // Get the number of stop packets on the stack
2512 int nItems = m_stop_packet_stack.size();
2513 // Iterate over them
2514 for (int i = 0; i < nItems; i++)
2515 {
2516 // Get the thread stop info
2517 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2518 // Process thread stop info
2519 SetThreadStopInfo(stop_info);
2520 }
2521 // Clear the thread stop stack
2522 m_stop_packet_stack.clear();
2523 }
2524
Greg Clayton9e920902012-04-10 02:25:43 +00002525 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2526 if (m_thread_ids.empty())
2527 {
2528 // No, we need to fetch the thread list manually
2529 UpdateThreadIDList();
2530 }
2531
Ewan Crawford78baa192015-05-13 09:18:18 +00002532 // If we have queried for a default thread id
2533 if (m_initial_tid != LLDB_INVALID_THREAD_ID)
2534 {
2535 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2536 m_initial_tid = LLDB_INVALID_THREAD_ID;
2537 }
2538
Greg Clayton358cf1e2015-06-25 21:46:34 +00002539 // Fetch the threads via an efficient packet that gets stop infos for all threads
2540 // only if we have more than one thread
2541 if (m_thread_ids.size() > 1)
2542 m_threads_info_sp = m_gdb_comm.GetThreadsInfo();
2543
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002544 // Let all threads recover from stopping and do any clean up based
2545 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002546 m_thread_list_real.RefreshStateAfterStop();
Greg Clayton9e920902012-04-10 02:25:43 +00002547
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002548}
2549
2550Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002551ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002552{
2553 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002554
Greg Clayton6ed95942011-01-22 07:12:45 +00002555 bool timed_out = false;
2556 Mutex::Locker locker;
Greg Clayton513c26c2011-01-29 07:10:55 +00002557
2558 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002559 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002560 // We are being asked to halt during an attach. We need to just close
2561 // our file handle and debugserver will go away, and we can be done...
2562 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00002563 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002564 else
2565 {
Greg Clayton2687cd12012-03-29 01:55:41 +00002566 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton513c26c2011-01-29 07:10:55 +00002567 {
2568 if (timed_out)
2569 error.SetErrorString("timed out sending interrupt packet");
2570 else
2571 error.SetErrorString("unknown error sending interrupt packet");
2572 }
Greg Clayton2687cd12012-03-29 01:55:41 +00002573
2574 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton513c26c2011-01-29 07:10:55 +00002575 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002576 return error;
2577}
2578
2579Error
Jim Inghamacff8952013-05-02 00:27:30 +00002580ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002581{
2582 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002583 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00002584 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00002585 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2586
Jim Inghamacff8952013-05-02 00:27:30 +00002587 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002588 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002589 {
Jim Inghamacff8952013-05-02 00:27:30 +00002590 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002591 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
2592 else
Jim Inghamacff8952013-05-02 00:27:30 +00002593 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00002594 }
Jim Inghamacff8952013-05-02 00:27:30 +00002595
2596 if (!error.Success())
2597 return error;
2598
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002599 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00002600 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002601
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002602 SetPrivateState (eStateDetached);
2603 ResumePrivateStateThread();
2604
2605 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00002606 return error;
2607}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002608
Jim Ingham43c555d2012-07-04 00:35:43 +00002609
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002610Error
2611ProcessGDBRemote::DoDestroy ()
2612{
2613 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002614 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002615 if (log)
2616 log->Printf ("ProcessGDBRemote::DoDestroy()");
2617
Jim Ingham43c555d2012-07-04 00:35:43 +00002618 // There is a bug in older iOS debugservers where they don't shut down the process
2619 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
2620 // this can cause problems with restarting. So we check to see if any of our threads are stopped
2621 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
2622 // destroy it again.
2623 //
2624 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
2625 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
2626 // the debugservers with this bug are equal. There really should be a better way to test this!
2627 //
2628 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
2629 // get called here to destroy again and we're still at a breakpoint or exception, then we should
2630 // just do the straight-forward kill.
2631 //
2632 // And of course, if we weren't able to stop the process by the time we get here, it isn't
2633 // necessary (or helpful) to do any of this.
2634
2635 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
2636 {
2637 PlatformSP platform_sp = GetTarget().GetPlatform();
2638
2639 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2640 if (platform_sp
2641 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00002642 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00002643 {
2644 if (m_destroy_tried_resuming)
2645 {
2646 if (log)
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002647 log->PutCString ("ProcessGDBRemote::DoDestroy() - Tried resuming to destroy once already, not doing it again.");
Jim Ingham43c555d2012-07-04 00:35:43 +00002648 }
2649 else
2650 {
2651 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
2652 // but we really need it to happen here and it doesn't matter if we do it twice.
2653 m_thread_list.DiscardThreadPlans();
2654 DisableAllBreakpointSites();
2655
2656 bool stop_looks_like_crash = false;
2657 ThreadList &threads = GetThreadList();
2658
2659 {
Jim Ingham45350372012-09-11 00:08:52 +00002660 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002661
2662 size_t num_threads = threads.GetSize();
2663 for (size_t i = 0; i < num_threads; i++)
2664 {
2665 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002666 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002667 StopReason reason = eStopReasonInvalid;
2668 if (stop_info_sp)
2669 reason = stop_info_sp->GetStopReason();
2670 if (reason == eStopReasonBreakpoint
2671 || reason == eStopReasonException)
2672 {
2673 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002674 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
2675 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00002676 stop_info_sp->GetDescription());
2677 stop_looks_like_crash = true;
2678 break;
2679 }
2680 }
2681 }
2682
2683 if (stop_looks_like_crash)
2684 {
2685 if (log)
2686 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
2687 m_destroy_tried_resuming = true;
2688
2689 // If we are going to run again before killing, it would be good to suspend all the threads
2690 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
2691 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
2692 // have to run the risk of letting those threads proceed a bit.
2693
2694 {
Jim Ingham45350372012-09-11 00:08:52 +00002695 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002696
2697 size_t num_threads = threads.GetSize();
2698 for (size_t i = 0; i < num_threads; i++)
2699 {
2700 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002701 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002702 StopReason reason = eStopReasonInvalid;
2703 if (stop_info_sp)
2704 reason = stop_info_sp->GetStopReason();
2705 if (reason != eStopReasonBreakpoint
2706 && reason != eStopReasonException)
2707 {
2708 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002709 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
2710 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00002711 thread_sp->SetResumeState(eStateSuspended);
2712 }
2713 }
2714 }
2715 Resume ();
Jason Molendaede31932015-04-17 05:01:58 +00002716 return Destroy(false);
Jim Ingham43c555d2012-07-04 00:35:43 +00002717 }
2718 }
2719 }
2720 }
2721
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002722 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00002723 int exit_status = SIGABRT;
2724 std::string exit_string;
2725
Greg Clayton6ed95942011-01-22 07:12:45 +00002726 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002727 {
Jim Inghamaab78372011-10-28 01:11:35 +00002728 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00002729 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002730 StringExtractorGDBRemote response;
2731 bool send_async = true;
Tamas Berghammer912800c2015-02-24 10:23:39 +00002732 GDBRemoteCommunication::ScopedTimeout (m_gdb_comm, 3);
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002733
Greg Clayton3dedae12013-12-06 21:45:27 +00002734 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton513c26c2011-01-29 07:10:55 +00002735 {
2736 char packet_cmd = response.GetChar(0);
2737
2738 if (packet_cmd == 'W' || packet_cmd == 'X')
2739 {
Jim Inghameac0aa42014-02-21 22:36:11 +00002740#if defined(__APPLE__)
Jim Ingham9d67cc52014-02-21 22:35:29 +00002741 // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off
2742 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill
2743 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns
2744 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap
2745 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of
2746 // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2747 // Anyway, so call waitpid here to finally reap it.
2748 PlatformSP platform_sp(GetTarget().GetPlatform());
2749 if (platform_sp && platform_sp->IsHost())
2750 {
2751 int status;
2752 ::pid_t reap_pid;
2753 reap_pid = waitpid (GetID(), &status, WNOHANG);
2754 if (log)
2755 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2756 }
2757#endif
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002758 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002759 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00002760 exit_status = response.GetHexU8();
2761 }
2762 else
2763 {
2764 if (log)
2765 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2766 exit_string.assign("got unexpected response to k packet: ");
2767 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00002768 }
2769 }
2770 else
2771 {
Jim Inghambabfc382012-06-06 00:32:39 +00002772 if (log)
2773 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2774 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00002775 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002776 }
Jim Inghambabfc382012-06-06 00:32:39 +00002777 else
2778 {
2779 if (log)
Ed Masteb3a53332014-03-17 17:05:22 +00002780 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching");
Jim Inghamcfc09352012-07-27 23:57:19 +00002781 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00002782 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002783 }
Jim Inghambabfc382012-06-06 00:32:39 +00002784 else
2785 {
2786 // If we missed setting the exit status on the way out, do it here.
2787 // NB set exit status can be called multiple times, the first one sets the status.
2788 exit_string.assign("destroying when not connected to debugserver");
2789 }
2790
2791 SetExitStatus(exit_status, exit_string.c_str());
2792
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002793 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002794 KillDebugserverProcess ();
2795 return error;
2796}
2797
Greg Clayton8cda7f02013-05-21 21:55:59 +00002798void
2799ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2800{
Greg Clayton8cda7f02013-05-21 21:55:59 +00002801 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2802 if (did_exec)
2803 {
2804 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2805 if (log)
2806 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2807
2808 m_thread_list_real.Clear();
2809 m_thread_list.Clear();
2810 BuildDynamicRegisterInfo (true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002811 m_gdb_comm.ResetDiscoverableSettings (did_exec);
Greg Clayton8cda7f02013-05-21 21:55:59 +00002812 }
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002813
2814 // Scope the lock
2815 {
2816 // Lock the thread stack while we access it
2817 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
2818 // Add this stop packet to the stop packet stack
2819 // This stack will get popped and examined when we switch to the
2820 // Stopped state
2821 m_stop_packet_stack.push_back(response);
2822 }
Greg Clayton8cda7f02013-05-21 21:55:59 +00002823}
2824
2825
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002826//------------------------------------------------------------------
2827// Process Queries
2828//------------------------------------------------------------------
2829
2830bool
2831ProcessGDBRemote::IsAlive ()
2832{
Greg Clayton10177aa2010-12-08 05:08:21 +00002833 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002834}
2835
2836addr_t
2837ProcessGDBRemote::GetImageInfoAddress()
2838{
Aidan Doddsc0c83852015-05-08 09:36:31 +00002839 // request the link map address via the $qShlibInfoAddr packet
2840 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2841
2842 // the loaded module list can also provides a link map address
2843 if (addr == LLDB_INVALID_ADDRESS)
2844 {
2845 GDBLoadedModuleInfoList list;
2846 if (GetLoadedModuleList (list).Success())
2847 addr = list.m_link_map;
2848 }
2849
2850 return addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002851}
2852
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002853//------------------------------------------------------------------
2854// Process Memory
2855//------------------------------------------------------------------
2856size_t
2857ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2858{
Jason Molenda6076bf42014-05-06 04:34:52 +00002859 GetMaxMemorySize ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002860 if (size > m_max_memory_size)
2861 {
2862 // Keep memory read sizes down to a sane limit. This function will be
2863 // called multiple times in order to complete the task by
2864 // lldb_private::Process so it is ok to do this.
2865 size = m_max_memory_size;
2866 }
2867
2868 char packet[64];
Jason Molenda6076bf42014-05-06 04:34:52 +00002869 int packet_len;
2870 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2871 if (binary_memory_read)
2872 {
2873 packet_len = ::snprintf (packet, sizeof(packet), "x0x%" PRIx64 ",0x%" PRIx64, (uint64_t)addr, (uint64_t)size);
2874 }
2875 else
2876 {
2877 packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
2878 }
Andy Gibbsa297a972013-06-19 19:04:53 +00002879 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002880 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002881 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002882 {
Greg Clayton576d8832011-03-22 04:00:09 +00002883 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002884 {
2885 error.Clear();
Jason Molenda6076bf42014-05-06 04:34:52 +00002886 if (binary_memory_read)
2887 {
2888 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any
2889 // 0x7d character escaping that was present in the packet
2890
2891 size_t data_received_size = response.GetBytesLeft();
2892 if (data_received_size > size)
2893 {
2894 // Don't write past the end of BUF if the remote debug server gave us too
2895 // much data for some reason.
2896 data_received_size = size;
2897 }
2898 memcpy (buf, response.GetStringRef().data(), data_received_size);
2899 return data_received_size;
2900 }
2901 else
2902 {
2903 return response.GetHexBytes(buf, size, '\xdd');
2904 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002905 }
Greg Clayton576d8832011-03-22 04:00:09 +00002906 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002907 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002908 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002909 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002910 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002911 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002912 }
2913 else
2914 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002915 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002916 }
2917 return 0;
2918}
2919
2920size_t
2921ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2922{
Jason Molenda6076bf42014-05-06 04:34:52 +00002923 GetMaxMemorySize ();
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002924 if (size > m_max_memory_size)
2925 {
2926 // Keep memory read sizes down to a sane limit. This function will be
2927 // called multiple times in order to complete the task by
2928 // lldb_private::Process so it is ok to do this.
2929 size = m_max_memory_size;
2930 }
2931
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002932 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00002933 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Clayton7fb56d02011-02-01 01:31:41 +00002934 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002935 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002936 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002937 {
Greg Clayton576d8832011-03-22 04:00:09 +00002938 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002939 {
2940 error.Clear();
2941 return size;
2942 }
Greg Clayton576d8832011-03-22 04:00:09 +00002943 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002944 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002945 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002946 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002947 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002948 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 +00002949 }
2950 else
2951 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002952 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002953 }
2954 return 0;
2955}
2956
2957lldb::addr_t
2958ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2959{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00002960 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_EXPRESSIONS));
Greg Clayton2a48f522011-05-14 01:50:35 +00002961 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2962
Greg Clayton70b57652011-05-15 01:25:55 +00002963 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton2a48f522011-05-14 01:50:35 +00002964 switch (supported)
2965 {
2966 case eLazyBoolCalculate:
2967 case eLazyBoolYes:
2968 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2969 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2970 return allocated_addr;
2971
2972 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002973 // Call mmap() to create memory in the inferior..
2974 unsigned prot = 0;
2975 if (permissions & lldb::ePermissionsReadable)
2976 prot |= eMmapProtRead;
2977 if (permissions & lldb::ePermissionsWritable)
2978 prot |= eMmapProtWrite;
2979 if (permissions & lldb::ePermissionsExecutable)
2980 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00002981
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002982 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2983 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2984 m_addr_to_mmap_size[allocated_addr] = size;
2985 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002986 {
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002987 allocated_addr = LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00002988 if (log)
2989 log->Printf ("ProcessGDBRemote::%s no direct stub support for memory allocation, and InferiorCallMmap also failed - is stub missing register context save/restore capability?", __FUNCTION__);
2990 }
Greg Clayton2a48f522011-05-14 01:50:35 +00002991 break;
2992 }
2993
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002994 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00002995 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002996 else
2997 error.Clear();
2998 return allocated_addr;
2999}
3000
3001Error
Greg Clayton46fb5582011-11-18 07:03:08 +00003002ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
3003 MemoryRegionInfo &region_info)
3004{
3005
3006 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
3007 return error;
3008}
3009
3010Error
Johnny Chen64637202012-05-23 21:09:52 +00003011ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
3012{
3013
3014 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
3015 return error;
3016}
3017
3018Error
Enrico Granataf04a2192012-07-13 23:18:48 +00003019ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
3020{
3021 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
3022 return error;
3023}
3024
3025Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003026ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
3027{
3028 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00003029 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
3030
3031 switch (supported)
3032 {
3033 case eLazyBoolCalculate:
3034 // We should never be deallocating memory without allocating memory
3035 // first so we should never get eLazyBoolCalculate
3036 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
3037 break;
3038
3039 case eLazyBoolYes:
3040 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00003041 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003042 break;
3043
3044 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003045 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00003046 {
3047 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003048 if (pos != m_addr_to_mmap_size.end() &&
3049 InferiorCallMunmap(this, addr, pos->second))
3050 m_addr_to_mmap_size.erase (pos);
3051 else
Daniel Malead01b2952012-11-29 21:49:15 +00003052 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003053 }
3054 break;
3055 }
3056
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003057 return error;
3058}
3059
3060
3061//------------------------------------------------------------------
3062// Process STDIO
3063//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003064size_t
3065ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
3066{
3067 if (m_stdio_communication.IsConnected())
3068 {
3069 ConnectionStatus status;
3070 m_stdio_communication.Write(src, src_len, status, NULL);
3071 }
Vince Harrondf3f00f2015-02-10 21:09:04 +00003072 else if (m_stdin_forward)
Vince Harrone0be4252015-02-06 18:32:57 +00003073 {
3074 m_gdb_comm.SendStdinNotification(src, src_len);
3075 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003076 return 0;
3077}
3078
3079Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003080ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003081{
3082 Error error;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003083 assert(bp_site != NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003084
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003085 // Get logging info
3086 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003087 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003088
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003089 // Get the breakpoint address
3090 const addr_t addr = bp_site->GetLoadAddress();
3091
3092 // Log that a breakpoint was requested
3093 if (log)
3094 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
3095
3096 // Breakpoint already exists and is enabled
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003097 if (bp_site->IsEnabled())
3098 {
3099 if (log)
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003100 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 +00003101 return error;
3102 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003103
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003104 // Get the software breakpoint trap opcode size
3105 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3106
3107 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
3108 // is supported by the remote stub. These are set to true by default, and later set to false
3109 // only after we receive an unimplemented response when sending a breakpoint packet. This means
3110 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
3111 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
3112 // indicates if the user specifically asked for hardware breakpoints. If true then we will
3113 // skip over software breakpoints.
3114 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
3115 {
3116 // Try to send off a software breakpoint packet ($Z0)
3117 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003118 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003119 // The breakpoint was placed successfully
3120 bp_site->SetEnabled(true);
3121 bp_site->SetType(BreakpointSite::eExternal);
Greg Claytoneb023e72013-10-11 19:48:25 +00003122 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003123 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003124
3125 // SendGDBStoppointTypePacket() will return an error if it was unable to set this
3126 // breakpoint. We need to differentiate between a error specific to placing this breakpoint
3127 // or if we have learned that this breakpoint type is unsupported. To do this, we
3128 // must test the support boolean for this breakpoint type to see if it now indicates that
3129 // this breakpoint type is unsupported. If they are still supported then we should return
3130 // with the error code. If they are now unsupported, then we would like to fall through
3131 // and try another form of breakpoint.
3132 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
3133 return error;
3134
3135 // We reach here when software breakpoints have been found to be unsupported. For future
3136 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
3137 // known not to be supported.
3138 if (log)
3139 log->Printf("Software breakpoints are unsupported");
3140
3141 // So we will fall through and try a hardware breakpoint
3142 }
3143
3144 // The process of setting a hardware breakpoint is much the same as above. We check the
3145 // supported boolean for this breakpoint type, and if it is thought to be supported then we
3146 // will try to set this breakpoint with a hardware breakpoint.
3147 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3148 {
3149 // Try to send off a hardware breakpoint packet ($Z1)
3150 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003151 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003152 // The breakpoint was placed successfully
3153 bp_site->SetEnabled(true);
3154 bp_site->SetType(BreakpointSite::eHardware);
3155 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003156 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003157
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003158 // Check if the error was something other then an unsupported breakpoint type
3159 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3160 {
3161 // Unable to set this hardware breakpoint
3162 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
3163 return error;
3164 }
3165
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003166 // We will reach here when the stub gives an unsupported response to a hardware breakpoint
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003167 if (log)
3168 log->Printf("Hardware breakpoints are unsupported");
3169
3170 // Finally we will falling through to a #trap style breakpoint
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003171 }
3172
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003173 // Don't fall through when hardware breakpoints were specifically requested
3174 if (bp_site->HardwareRequired())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003175 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003176 error.SetErrorString("hardware breakpoints are not supported");
3177 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003178 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003179
3180 // As a last resort we want to place a manual breakpoint. An instruction
3181 // is placed into the process memory using memory write packets.
3182 return EnableSoftwareBreakpoint(bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003183}
3184
3185Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003186ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003187{
3188 Error error;
3189 assert (bp_site != NULL);
3190 addr_t addr = bp_site->GetLoadAddress();
3191 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00003192 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003193 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003194 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003195
3196 if (bp_site->IsEnabled())
3197 {
3198 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
3199
Greg Clayton8b82f082011-04-12 05:54:46 +00003200 BreakpointSite::Type bp_type = bp_site->GetType();
3201 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003202 {
Greg Clayton8b82f082011-04-12 05:54:46 +00003203 case BreakpointSite::eSoftware:
3204 error = DisableSoftwareBreakpoint (bp_site);
3205 break;
3206
3207 case BreakpointSite::eHardware:
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003208 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003209 error.SetErrorToGenericError();
3210 break;
3211
3212 case BreakpointSite::eExternal:
Jim Inghama04ef752014-03-07 11:18:02 +00003213 {
3214 GDBStoppointType stoppoint_type;
3215 if (bp_site->IsHardware())
3216 stoppoint_type = eBreakpointHardware;
3217 else
3218 stoppoint_type = eBreakpointSoftware;
3219
3220 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003221 error.SetErrorToGenericError();
Jim Inghama04ef752014-03-07 11:18:02 +00003222 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003223 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003224 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003225 if (error.Success())
3226 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003227 }
3228 else
3229 {
3230 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003231 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 +00003232 return error;
3233 }
3234
3235 if (error.Success())
3236 error.SetErrorToGenericError();
3237 return error;
3238}
3239
Johnny Chen11309a32011-09-06 22:38:36 +00003240// Pre-requisite: wp != NULL.
3241static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00003242GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00003243{
3244 assert(wp);
3245 bool watch_read = wp->WatchpointRead();
3246 bool watch_write = wp->WatchpointWrite();
3247
3248 // watch_read and watch_write cannot both be false.
3249 assert(watch_read || watch_write);
3250 if (watch_read && watch_write)
3251 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00003252 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00003253 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00003254 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00003255 return eWatchpointWrite;
3256}
3257
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003258Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003259ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003260{
3261 Error error;
3262 if (wp)
3263 {
3264 user_id_t watchID = wp->GetID();
3265 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00003266 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003267 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003268 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003269 if (wp->IsEnabled())
3270 {
3271 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003272 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 +00003273 return error;
3274 }
Johnny Chen11309a32011-09-06 22:38:36 +00003275
3276 GDBStoppointType type = GetGDBStoppointType(wp);
3277 // Pass down an appropriate z/Z packet...
3278 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003279 {
Johnny Chen11309a32011-09-06 22:38:36 +00003280 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
3281 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003282 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003283 return error;
3284 }
3285 else
3286 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003287 }
Johnny Chen11309a32011-09-06 22:38:36 +00003288 else
3289 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003290 }
3291 else
3292 {
Johnny Chen01a67862011-10-14 00:42:25 +00003293 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003294 }
3295 if (error.Success())
3296 error.SetErrorToGenericError();
3297 return error;
3298}
3299
3300Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003301ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003302{
3303 Error error;
3304 if (wp)
3305 {
3306 user_id_t watchID = wp->GetID();
3307
Greg Clayton5160ce52013-03-27 23:08:40 +00003308 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003309
3310 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00003311
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003312 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003313 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003314
Johnny Chen11309a32011-09-06 22:38:36 +00003315 if (!wp->IsEnabled())
3316 {
3317 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003318 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 +00003319 // See also 'class WatchpointSentry' within StopInfo.cpp.
3320 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
3321 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00003322 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003323 return error;
3324 }
3325
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003326 if (wp->IsHardware())
3327 {
Johnny Chen11309a32011-09-06 22:38:36 +00003328 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003329 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00003330 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
3331 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003332 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003333 return error;
3334 }
3335 else
3336 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003337 }
3338 // TODO: clear software watchpoints if we implement them
3339 }
3340 else
3341 {
Johnny Chen01a67862011-10-14 00:42:25 +00003342 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003343 }
3344 if (error.Success())
3345 error.SetErrorToGenericError();
3346 return error;
3347}
3348
3349void
3350ProcessGDBRemote::Clear()
3351{
3352 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00003353 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003354 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003355}
3356
3357Error
3358ProcessGDBRemote::DoSignal (int signo)
3359{
3360 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00003361 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003362 if (log)
3363 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
3364
3365 if (!m_gdb_comm.SendAsyncSignal (signo))
3366 error.SetErrorStringWithFormat("failed to send signal %i", signo);
3367 return error;
3368}
3369
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003370Error
Greg Clayton91a9b2472013-12-04 19:19:12 +00003371ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003372{
3373 Error error;
3374 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
3375 {
3376 // If we locate debugserver, keep that located version around
3377 static FileSpec g_debugserver_file_spec;
3378
Han Ming Ong84647042012-02-25 01:07:38 +00003379 ProcessLaunchInfo debugserver_launch_info;
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00003380 // Make debugserver run in its own session so signals generated by
3381 // special terminal key sequences (^C) don't affect debugserver.
3382 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3383
Greg Clayton91a9b2472013-12-04 19:19:12 +00003384 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
3385 debugserver_launch_info.SetUserID(process_info.GetUserID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003386
Todd Fiala013434e2014-07-09 01:29:05 +00003387#if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__) || defined (__aarch64__))
Greg Claytonfda4fab2014-01-10 22:24:11 +00003388 // On iOS, still do a local connection using a random port
Greg Clayton16810922014-02-27 19:38:18 +00003389 const char *hostname = "127.0.0.1";
Greg Claytonfda4fab2014-01-10 22:24:11 +00003390 uint16_t port = get_random_port ();
3391#else
3392 // Set hostname being NULL to do the reverse connect where debugserver
3393 // will bind to port zero and it will communicate back to us the port
3394 // that we will connect to
3395 const char *hostname = NULL;
3396 uint16_t port = 0;
3397#endif
3398
3399 error = m_gdb_comm.StartDebugserverProcess (hostname,
3400 port,
Greg Clayton00fe87b2013-12-05 22:58:22 +00003401 debugserver_launch_info,
3402 port);
Greg Clayton91a9b2472013-12-04 19:19:12 +00003403
3404 if (error.Success ())
3405 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003406 else
Greg Clayton91a9b2472013-12-04 19:19:12 +00003407 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003408
3409 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3410 StartAsyncThread ();
Greg Clayton91a9b2472013-12-04 19:19:12 +00003411
3412 if (error.Fail())
3413 {
3414 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
3415
3416 if (log)
3417 log->Printf("failed to start debugserver process: %s", error.AsCString());
3418 return error;
3419 }
3420
Greg Clayton00fe87b2013-12-05 22:58:22 +00003421 if (m_gdb_comm.IsConnected())
3422 {
3423 // Finish the connection process by doing the handshake without connecting (send NULL URL)
3424 ConnectToDebugserver (NULL);
3425 }
3426 else
3427 {
Greg Claytonfda4fab2014-01-10 22:24:11 +00003428 StreamString connect_url;
3429 connect_url.Printf("connect://%s:%u", hostname, port);
3430 error = ConnectToDebugserver (connect_url.GetString().c_str());
Greg Clayton00fe87b2013-12-05 22:58:22 +00003431 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00003432
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003433 }
3434 return error;
3435}
3436
3437bool
3438ProcessGDBRemote::MonitorDebugserverProcess
3439(
3440 void *callback_baton,
3441 lldb::pid_t debugserver_pid,
Greg Claytone4e45922011-11-16 05:37:56 +00003442 bool exited, // True if the process did exit
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003443 int signo, // Zero for no signal
3444 int exit_status // Exit value of process if signal is zero
3445)
3446{
Greg Claytone4e45922011-11-16 05:37:56 +00003447 // The baton is a "ProcessGDBRemote *". Now this class might be gone
3448 // and might not exist anymore, so we need to carefully try to get the
3449 // target for this process first since we have a race condition when
3450 // we are done running between getting the notice that the inferior
3451 // process has died and the debugserver that was debugging this process.
3452 // In our test suite, we are also continually running process after
3453 // process, so we must be very careful to make sure:
3454 // 1 - process object hasn't been deleted already
3455 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003456
3457 // "debugserver_pid" argument passed in is the process ID for
3458 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00003459 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003460
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003461 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton6779606a2011-01-22 23:43:18 +00003462
Greg Claytone4e45922011-11-16 05:37:56 +00003463 // Get a shared pointer to the target that has a matching process pointer.
3464 // This target could be gone, or the target could already have a new process
3465 // object inside of it
3466 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
3467
Greg Clayton6779606a2011-01-22 23:43:18 +00003468 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003469 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 +00003470
Greg Claytone4e45922011-11-16 05:37:56 +00003471 if (target_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003472 {
Greg Claytone4e45922011-11-16 05:37:56 +00003473 // We found a process in a target that matches, but another thread
3474 // might be in the process of launching a new process that will
3475 // soon replace it, so get a shared pointer to the process so we
3476 // can keep it alive.
3477 ProcessSP process_sp (target_sp->GetProcessSP());
3478 // Now we have a shared pointer to the process that can't go away on us
3479 // so we now make sure it was the same as the one passed in, and also make
3480 // sure that our previous "process *" didn't get deleted and have a new
3481 // "process *" created in its place with the same pointer. To verify this
3482 // we make sure the process has our debugserver process ID. If we pass all
3483 // of these tests, then we are sure that this process is the one we were
3484 // looking for.
3485 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003486 {
Greg Claytone4e45922011-11-16 05:37:56 +00003487 // Sleep for a half a second to make sure our inferior process has
3488 // time to set its exit status before we set it incorrectly when
3489 // both the debugserver and the inferior process shut down.
3490 usleep (500000);
3491 // If our process hasn't yet exited, debugserver might have died.
3492 // If the process did exit, the we are reaping it.
3493 const StateType state = process->GetState();
3494
3495 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
3496 state != eStateInvalid &&
3497 state != eStateUnloaded &&
3498 state != eStateExited &&
3499 state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003500 {
Greg Claytone4e45922011-11-16 05:37:56 +00003501 char error_str[1024];
3502 if (signo)
3503 {
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00003504 const char *signal_cstr = process->GetUnixSignals()->GetSignalAsCString(signo);
Greg Claytone4e45922011-11-16 05:37:56 +00003505 if (signal_cstr)
3506 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3507 else
3508 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
3509 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003510 else
Greg Claytone4e45922011-11-16 05:37:56 +00003511 {
3512 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
3513 }
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003514
Greg Claytone4e45922011-11-16 05:37:56 +00003515 process->SetExitStatus (-1, error_str);
3516 }
3517 // Debugserver has exited we need to let our ProcessGDBRemote
3518 // know that it no longer has a debugserver instance
3519 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003520 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003521 }
3522 return true;
3523}
3524
3525void
3526ProcessGDBRemote::KillDebugserverProcess ()
3527{
Greg Claytonfbb76342013-11-20 21:07:01 +00003528 m_gdb_comm.Disconnect();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003529 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3530 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003531 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003532 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3533 }
3534}
3535
3536void
3537ProcessGDBRemote::Initialize()
3538{
Davide Italianoc8d69822015-04-03 04:24:32 +00003539 static std::once_flag g_once_flag;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003540
Davide Italianoc8d69822015-04-03 04:24:32 +00003541 std::call_once(g_once_flag, []()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003542 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003543 PluginManager::RegisterPlugin (GetPluginNameStatic(),
3544 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00003545 CreateInstance,
3546 DebuggerInitialize);
Davide Italianoc8d69822015-04-03 04:24:32 +00003547 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003548}
3549
Greg Clayton7f982402013-07-15 22:54:20 +00003550void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003551ProcessGDBRemote::DebuggerInitialize (Debugger &debugger)
Greg Clayton7f982402013-07-15 22:54:20 +00003552{
3553 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
3554 {
3555 const bool is_global_setting = true;
3556 PluginManager::CreateSettingForProcessPlugin (debugger,
3557 GetGlobalPluginProperties()->GetValueProperties(),
3558 ConstString ("Properties for the gdb-remote process plug-in."),
3559 is_global_setting);
3560 }
3561}
3562
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003563bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003564ProcessGDBRemote::StartAsyncThread ()
3565{
Greg Clayton5160ce52013-03-27 23:08:40 +00003566 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003567
3568 if (log)
3569 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003570
3571 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003572 if (!m_async_thread.IsJoinable())
Jim Ingham455fa5c2012-11-01 01:15:33 +00003573 {
3574 // Create a thread that watches our internal state and controls which
3575 // events make it to clients (into the DCProcess event queue).
Zachary Turner39de3112014-09-09 20:54:56 +00003576
3577 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003578 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003579 else if (log)
3580 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was already running.", __FUNCTION__);
Zachary Turner39de3112014-09-09 20:54:56 +00003581
Zachary Turneracee96a2014-09-23 18:32:09 +00003582 return m_async_thread.IsJoinable();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003583}
3584
3585void
3586ProcessGDBRemote::StopAsyncThread ()
3587{
Greg Clayton5160ce52013-03-27 23:08:40 +00003588 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003589
3590 if (log)
3591 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
3592
Jim Ingham455fa5c2012-11-01 01:15:33 +00003593 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003594 if (m_async_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003595 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00003596 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
3597
3598 // This will shut down the async thread.
3599 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3600
3601 // Stop the stdio thread
Zachary Turner39de3112014-09-09 20:54:56 +00003602 m_async_thread.Join(nullptr);
Pavel Labatha55a9532015-03-11 09:53:42 +00003603 m_async_thread.Reset();
Jim Ingham455fa5c2012-11-01 01:15:33 +00003604 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003605 else if (log)
3606 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003607}
3608
Ewan Crawford76df2882015-06-23 12:32:06 +00003609bool
3610ProcessGDBRemote::HandleNotifyPacket (StringExtractorGDBRemote &packet)
3611{
3612 // get the packet at a string
3613 const std::string &pkt = packet.GetStringRef();
3614 // skip %stop:
3615 StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
3616
3617 // pass as a thread stop info packet
3618 SetLastStopPacket(stop_info);
3619
3620 // check for more stop reasons
3621 HandleStopReplySequence();
3622
3623 // if the process is stopped then we need to fake a resume
3624 // so that we can stop properly with the new break. This
3625 // is possible due to SetPrivateState() broadcasting the
3626 // state change as a side effect.
3627 if (GetPrivateState() == lldb::StateType::eStateStopped)
3628 {
3629 SetPrivateState(lldb::StateType::eStateRunning);
3630 }
3631
3632 // since we have some stopped packets we can halt the process
3633 SetPrivateState(lldb::StateType::eStateStopped);
3634
3635 return true;
3636}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003637
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003638thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003639ProcessGDBRemote::AsyncThread (void *arg)
3640{
3641 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
3642
Greg Clayton5160ce52013-03-27 23:08:40 +00003643 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003644 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003645 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003646
3647 Listener listener ("ProcessGDBRemote::AsyncThread");
3648 EventSP event_sp;
3649 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
3650 eBroadcastBitAsyncThreadShouldExit;
3651
3652 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
3653 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003654 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit |
3655 GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify);
3656
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003657 bool done = false;
3658 while (!done)
3659 {
3660 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003661 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003662 if (listener.WaitForEvent (NULL, event_sp))
3663 {
3664 const uint32_t event_type = event_sp->GetType();
Greg Clayton71337622011-02-24 22:24:29 +00003665 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003666 {
Greg Clayton71337622011-02-24 22:24:29 +00003667 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003668 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 +00003669
Greg Clayton71337622011-02-24 22:24:29 +00003670 switch (event_type)
3671 {
3672 case eBroadcastBitAsyncContinue:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003673 {
Greg Clayton71337622011-02-24 22:24:29 +00003674 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003675
Greg Clayton71337622011-02-24 22:24:29 +00003676 if (continue_packet)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003677 {
Greg Clayton71337622011-02-24 22:24:29 +00003678 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
3679 const size_t continue_cstr_len = continue_packet->GetByteSize ();
3680 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003681 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003682
Greg Clayton71337622011-02-24 22:24:29 +00003683 if (::strstr (continue_cstr, "vAttach") == NULL)
3684 process->SetPrivateState(eStateRunning);
3685 StringExtractorGDBRemote response;
Ewan Crawford76df2882015-06-23 12:32:06 +00003686
3687 // If in Non-Stop-Mode
3688 if (process->GetTarget().GetNonStopModeEnabled())
Greg Clayton71337622011-02-24 22:24:29 +00003689 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003690 // send the vCont packet
3691 if (!process->GetGDBRemote().SendvContPacket(process, continue_cstr, continue_cstr_len, response))
Jason Molendaa3329782014-03-29 18:54:20 +00003692 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003693 // Something went wrong
3694 done = true;
3695 break;
3696 }
3697 }
3698 // If in All-Stop-Mode
3699 else
3700 {
3701 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
3702
3703 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
3704 // The thread ID list might be contained within the "response", or the stop reply packet that
3705 // caused the stop. So clear it now before we give the stop reply packet to the process
3706 // using the process->SetLastStopPacket()...
3707 process->ClearThreadIDList ();
3708
3709 switch (stop_state)
3710 {
3711 case eStateStopped:
3712 case eStateCrashed:
3713 case eStateSuspended:
3714 process->SetLastStopPacket (response);
3715 process->SetPrivateState (stop_state);
3716 break;
3717
3718 case eStateExited:
3719 {
3720 process->SetLastStopPacket (response);
3721 process->ClearThreadIDList();
3722 response.SetFilePos(1);
3723
3724 int exit_status = response.GetHexU8();
3725 const char *desc_cstr = NULL;
3726 StringExtractor extractor;
3727 std::string desc_string;
3728 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';')
Jason Molendaa3329782014-03-29 18:54:20 +00003729 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003730 std::string desc_token;
3731 while (response.GetNameColonValue (desc_token, desc_string))
Jason Molendaa3329782014-03-29 18:54:20 +00003732 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003733 if (desc_token == "description")
3734 {
3735 extractor.GetStringRef().swap(desc_string);
3736 extractor.SetFilePos(0);
3737 extractor.GetHexByteString (desc_string);
3738 desc_cstr = desc_string.c_str();
3739 }
Jason Molendaa3329782014-03-29 18:54:20 +00003740 }
3741 }
Ewan Crawford76df2882015-06-23 12:32:06 +00003742 process->SetExitStatus(exit_status, desc_cstr);
3743 done = true;
3744 break;
Jason Molendaa3329782014-03-29 18:54:20 +00003745 }
Ewan Crawford76df2882015-06-23 12:32:06 +00003746 case eStateInvalid:
3747 process->SetExitStatus(-1, "lost connection");
3748 break;
Greg Clayton71337622011-02-24 22:24:29 +00003749
Ewan Crawford76df2882015-06-23 12:32:06 +00003750 default:
3751 process->SetPrivateState (stop_state);
3752 break;
3753 } // switch(stop_state)
3754 } // else // if in All-stop-mode
3755 } // if (continue_packet)
3756 } // case eBroadcastBitAysncContinue
Greg Clayton71337622011-02-24 22:24:29 +00003757 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003758
Greg Clayton71337622011-02-24 22:24:29 +00003759 case eBroadcastBitAsyncThreadShouldExit:
3760 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003761 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Clayton71337622011-02-24 22:24:29 +00003762 done = true;
3763 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003764
Greg Clayton71337622011-02-24 22:24:29 +00003765 default:
3766 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003767 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 +00003768 done = true;
3769 break;
3770 }
3771 }
3772 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
3773 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003774 switch (event_type)
Greg Clayton71337622011-02-24 22:24:29 +00003775 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003776 case Communication::eBroadcastBitReadThreadDidExit:
3777 process->SetExitStatus (-1, "lost connection");
3778 done = true;
3779 break;
3780
3781 case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify:
3782 {
3783 lldb_private::Event *event = event_sp.get();
3784 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event);
3785 StringExtractorGDBRemote notify((const char*)continue_packet->GetBytes());
3786 // Hand this over to the process to handle
3787 process->HandleNotifyPacket(notify);
3788 break;
3789 }
3790
3791 default:
3792 if (log)
3793 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
3794 done = true;
3795 break;
Greg Clayton71337622011-02-24 22:24:29 +00003796 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003797 }
3798 }
3799 else
3800 {
3801 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003802 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 +00003803 done = true;
3804 }
3805 }
3806 }
3807
3808 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003809 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003810
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003811 return NULL;
3812}
3813
Greg Claytone996fd32011-03-08 22:40:15 +00003814//uint32_t
3815//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3816//{
3817// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
3818// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
3819// if (m_local_debugserver)
3820// {
3821// return Host::ListProcessesMatchingName (name, matches, pids);
3822// }
3823// else
3824// {
3825// // FIXME: Implement talking to the remote debugserver.
3826// return 0;
3827// }
3828//
3829//}
3830//
Jim Ingham1c823b42011-01-22 01:33:44 +00003831bool
3832ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003833 StoppointCallbackContext *context,
Jim Ingham1c823b42011-01-22 01:33:44 +00003834 lldb::user_id_t break_id,
3835 lldb::user_id_t break_loc_id)
3836{
3837 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3838 // run so I can stop it if that's what I want to do.
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003839 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00003840 if (log)
3841 log->Printf("Hit New Thread Notification breakpoint.");
3842 return false;
3843}
3844
3845
3846bool
3847ProcessGDBRemote::StartNoticingNewThreads()
3848{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003849 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00003850 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003851 {
Greg Clayton4116e932012-05-15 02:33:01 +00003852 if (log && log->GetVerbose())
3853 log->Printf("Enabled noticing new thread breakpoint.");
3854 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003855 }
Greg Clayton4116e932012-05-15 02:33:01 +00003856 else
Jim Ingham1c823b42011-01-22 01:33:44 +00003857 {
Greg Clayton4116e932012-05-15 02:33:01 +00003858 PlatformSP platform_sp (m_target.GetPlatform());
3859 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003860 {
Greg Clayton4116e932012-05-15 02:33:01 +00003861 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3862 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003863 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00003864 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00003865 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3866 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003867 }
3868 else
3869 {
3870 if (log)
3871 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00003872 }
3873 }
3874 }
Greg Clayton4116e932012-05-15 02:33:01 +00003875 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00003876}
3877
3878bool
3879ProcessGDBRemote::StopNoticingNewThreads()
3880{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003881 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00003882 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00003883 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00003884
3885 if (m_thread_create_bp_sp)
3886 m_thread_create_bp_sp->SetEnabled(false);
3887
Jim Ingham1c823b42011-01-22 01:33:44 +00003888 return true;
3889}
3890
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003891DynamicLoader *
Jason Molenda5e8534e2012-10-03 01:29:34 +00003892ProcessGDBRemote::GetDynamicLoader ()
3893{
3894 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00003895 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00003896 return m_dyld_ap.get();
3897}
Jim Ingham1c823b42011-01-22 01:33:44 +00003898
Jason Molendaa3329782014-03-29 18:54:20 +00003899Error
3900ProcessGDBRemote::SendEventData(const char *data)
3901{
3902 int return_value;
3903 bool was_supported;
3904
3905 Error error;
3906
3907 return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported);
3908 if (return_value != 0)
3909 {
3910 if (!was_supported)
3911 error.SetErrorString("Sending events is not supported for this process.");
3912 else
3913 error.SetErrorStringWithFormat("Error sending event data: %d.", return_value);
3914 }
3915 return error;
3916}
3917
Steve Pucci03904ac2014-03-04 23:18:46 +00003918const DataBufferSP
3919ProcessGDBRemote::GetAuxvData()
3920{
3921 DataBufferSP buf;
3922 if (m_gdb_comm.GetQXferAuxvReadSupported())
3923 {
3924 std::string response_string;
3925 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success)
3926 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length()));
3927 }
3928 return buf;
3929}
3930
Jason Molenda705b1802014-06-13 02:37:02 +00003931StructuredData::ObjectSP
3932ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid)
3933{
3934 StructuredData::ObjectSP object_sp;
3935
3936 if (m_gdb_comm.GetThreadExtendedInfoSupported())
3937 {
3938 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3939 SystemRuntime *runtime = GetSystemRuntime();
3940 if (runtime)
3941 {
3942 runtime->AddThreadExtendedInfoPacketHints (args_dict);
3943 }
3944 args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid);
3945
3946 StreamString packet;
3947 packet << "jThreadExtendedInfo:";
3948 args_dict->Dump (packet);
3949
3950 // FIXME the final character of a JSON dictionary, '}', is the escape
3951 // character in gdb-remote binary mode. lldb currently doesn't escape
3952 // these characters in its packet output -- so we add the quoted version
3953 // of the } character here manually in case we talk to a debugserver which
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003954 // un-escapes the characters at packet read time.
Jason Molenda705b1802014-06-13 02:37:02 +00003955 packet << (char) (0x7d ^ 0x20);
3956
3957 StringExtractorGDBRemote response;
3958 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
3959 {
3960 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
3961 if (response_type == StringExtractorGDBRemote::eResponse)
3962 {
3963 if (!response.Empty())
3964 {
Jason Molenda20ee21b2015-07-10 23:15:22 +00003965 object_sp = StructuredData::ParseJSON (response.GetStringRef());
3966 }
3967 }
3968 }
3969 }
3970 return object_sp;
3971}
3972
3973StructuredData::ObjectSP
3974ProcessGDBRemote::GetLoadedDynamicLibrariesInfos (lldb::addr_t image_list_address, lldb::addr_t image_count)
3975{
3976 StructuredData::ObjectSP object_sp;
3977
3978 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported())
3979 {
3980 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3981 args_dict->GetAsDictionary()->AddIntegerItem ("image_list_address", image_list_address);
3982 args_dict->GetAsDictionary()->AddIntegerItem ("image_count", image_count);
3983
3984 StreamString packet;
3985 packet << "jGetLoadedDynamicLibrariesInfos:";
3986 args_dict->Dump (packet);
3987
3988 // FIXME the final character of a JSON dictionary, '}', is the escape
3989 // character in gdb-remote binary mode. lldb currently doesn't escape
3990 // these characters in its packet output -- so we add the quoted version
3991 // of the } character here manually in case we talk to a debugserver which
3992 // un-escapes the characters at packet read time.
3993 packet << (char) (0x7d ^ 0x20);
3994
3995 StringExtractorGDBRemote response;
3996 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
3997 {
3998 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
3999 if (response_type == StringExtractorGDBRemote::eResponse)
4000 {
4001 if (!response.Empty())
4002 {
Jason Molenda705b1802014-06-13 02:37:02 +00004003 // The packet has already had the 0x7d xor quoting stripped out at the
4004 // GDBRemoteCommunication packet receive level.
4005 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4006 }
4007 }
4008 }
4009 }
4010 return object_sp;
4011}
4012
Jason Molenda20ee21b2015-07-10 23:15:22 +00004013
Jason Molenda6076bf42014-05-06 04:34:52 +00004014// Establish the largest memory read/write payloads we should use.
4015// If the remote stub has a max packet size, stay under that size.
4016//
4017// If the remote stub's max packet size is crazy large, use a
4018// reasonable largeish default.
4019//
4020// If the remote stub doesn't advertise a max packet size, use a
4021// conservative default.
4022
4023void
4024ProcessGDBRemote::GetMaxMemorySize()
4025{
4026 const uint64_t reasonable_largeish_default = 128 * 1024;
4027 const uint64_t conservative_default = 512;
4028
4029 if (m_max_memory_size == 0)
4030 {
4031 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4032 if (stub_max_size != UINT64_MAX && stub_max_size != 0)
4033 {
4034 // Save the stub's claimed maximum packet size
4035 m_remote_stub_max_memory_size = stub_max_size;
4036
4037 // Even if the stub says it can support ginormous packets,
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004038 // don't exceed our reasonable largeish default packet size.
Jason Molenda6076bf42014-05-06 04:34:52 +00004039 if (stub_max_size > reasonable_largeish_default)
4040 {
4041 stub_max_size = reasonable_largeish_default;
4042 }
4043
4044 m_max_memory_size = stub_max_size;
4045 }
4046 else
4047 {
4048 m_max_memory_size = conservative_default;
4049 }
4050 }
4051}
4052
4053void
4054ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max)
4055{
4056 if (user_specified_max != 0)
4057 {
4058 GetMaxMemorySize ();
4059
4060 if (m_remote_stub_max_memory_size != 0)
4061 {
4062 if (m_remote_stub_max_memory_size < user_specified_max)
4063 {
4064 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a packet size too big, go as big
4065 // as the remote stub says we can go.
4066 }
4067 else
4068 {
4069 m_max_memory_size = user_specified_max; // user's packet size is good
4070 }
4071 }
4072 else
4073 {
4074 m_max_memory_size = user_specified_max; // user's packet size is probably fine
4075 }
4076 }
4077}
4078
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004079bool
4080ProcessGDBRemote::GetModuleSpec(const FileSpec& module_file_spec,
4081 const ArchSpec& arch,
4082 ModuleSpec &module_spec)
4083{
4084 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PLATFORM);
4085
4086 if (!m_gdb_comm.GetModuleInfo (module_file_spec, arch, module_spec))
4087 {
4088 if (log)
4089 log->Printf ("ProcessGDBRemote::%s - failed to get module info for %s:%s",
4090 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4091 arch.GetTriple ().getTriple ().c_str ());
4092 return false;
4093 }
4094
4095 if (log)
4096 {
4097 StreamString stream;
4098 module_spec.Dump (stream);
4099 log->Printf ("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4100 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4101 arch.GetTriple ().getTriple ().c_str (), stream.GetString ().c_str ());
4102 }
4103
4104 return true;
4105}
4106
Colin Rileyc3c95b22015-04-16 15:51:33 +00004107namespace {
4108
4109typedef std::vector<std::string> stringVec;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004110
4111typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004112struct RegisterSetInfo
4113{
4114 ConstString name;
4115};
Colin Rileyc3c95b22015-04-16 15:51:33 +00004116
Greg Claytond04f0ed2015-05-26 18:00:51 +00004117typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4118
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004119struct GdbServerTargetInfo
4120{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004121 std::string arch;
4122 std::string osabi;
4123 stringVec includes;
4124 RegisterSetMap reg_set_map;
4125 XMLNode feature_node;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004126};
Greg Claytond04f0ed2015-05-26 18:00:51 +00004127
Colin Rileyc3c95b22015-04-16 15:51:33 +00004128bool
Greg Claytond04f0ed2015-05-26 18:00:51 +00004129ParseRegisters (XMLNode feature_node, GdbServerTargetInfo &target_info, GDBRemoteDynamicRegisterInfo &dyn_reg_info)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004130{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004131 if (!feature_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004132 return false;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004133
4134 uint32_t prev_reg_num = 0;
4135 uint32_t reg_offset = 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004136
Greg Claytond04f0ed2015-05-26 18:00:51 +00004137 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 +00004138 std::string gdb_group;
4139 std::string gdb_type;
4140 ConstString reg_name;
4141 ConstString alt_name;
4142 ConstString set_name;
4143 std::vector<uint32_t> value_regs;
4144 std::vector<uint32_t> invalidate_regs;
4145 bool encoding_set = false;
4146 bool format_set = false;
4147 RegisterInfo reg_info = { NULL, // Name
4148 NULL, // Alt name
4149 0, // byte size
4150 reg_offset, // offset
4151 eEncodingUint, // encoding
4152 eFormatHex, // formate
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004153 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004154 LLDB_INVALID_REGNUM, // GCC reg num
4155 LLDB_INVALID_REGNUM, // DWARF reg num
4156 LLDB_INVALID_REGNUM, // generic reg num
4157 prev_reg_num, // GDB reg num
4158 prev_reg_num // native register number
4159 },
4160 NULL,
4161 NULL
4162 };
4163
Ewan Crawford682e8422015-06-26 09:38:27 +00004164 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 +00004165 if (name == "name")
4166 {
4167 reg_name.SetString(value);
4168 }
4169 else if (name == "bitsize")
4170 {
4171 reg_info.byte_size = StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
4172 }
4173 else if (name == "type")
4174 {
4175 gdb_type = value.str();
4176 }
4177 else if (name == "group")
4178 {
4179 gdb_group = value.str();
4180 }
4181 else if (name == "regnum")
4182 {
4183 const uint32_t regnum = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4184 if (regnum != LLDB_INVALID_REGNUM)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004185 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004186 reg_info.kinds[eRegisterKindGDB] = regnum;
4187 reg_info.kinds[eRegisterKindLLDB] = regnum;
4188 prev_reg_num = regnum;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004189 }
4190 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004191 else if (name == "offset")
4192 {
4193 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4194 }
4195 else if (name == "altname")
4196 {
4197 alt_name.SetString(value);
4198 }
4199 else if (name == "encoding")
4200 {
4201 encoding_set = true;
4202 reg_info.encoding = Args::StringToEncoding (value.data(), eEncodingUint);
4203 }
4204 else if (name == "format")
4205 {
4206 format_set = true;
4207 Format format = eFormatInvalid;
4208 if (Args::StringToFormat (value.data(), format, NULL).Success())
4209 reg_info.format = format;
4210 else if (value == "vector-sint8")
4211 reg_info.format = eFormatVectorOfSInt8;
4212 else if (value == "vector-uint8")
4213 reg_info.format = eFormatVectorOfUInt8;
4214 else if (value == "vector-sint16")
4215 reg_info.format = eFormatVectorOfSInt16;
4216 else if (value == "vector-uint16")
4217 reg_info.format = eFormatVectorOfUInt16;
4218 else if (value == "vector-sint32")
4219 reg_info.format = eFormatVectorOfSInt32;
4220 else if (value == "vector-uint32")
4221 reg_info.format = eFormatVectorOfUInt32;
4222 else if (value == "vector-float32")
4223 reg_info.format = eFormatVectorOfFloat32;
4224 else if (value == "vector-uint128")
4225 reg_info.format = eFormatVectorOfUInt128;
4226 }
4227 else if (name == "group_id")
4228 {
4229 const uint32_t set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4230 RegisterSetMap::const_iterator pos = target_info.reg_set_map.find(set_id);
4231 if (pos != target_info.reg_set_map.end())
4232 set_name = pos->second.name;
4233 }
4234 else if (name == "gcc_regnum")
4235 {
4236 reg_info.kinds[eRegisterKindGCC] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4237 }
4238 else if (name == "dwarf_regnum")
4239 {
4240 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4241 }
4242 else if (name == "generic")
4243 {
4244 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister(value.data());
4245 }
4246 else if (name == "value_regnums")
4247 {
4248 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
4249 }
4250 else if (name == "invalidate_regnums")
4251 {
4252 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
4253 }
4254 else
4255 {
4256 printf("unhandled attribute %s = %s\n", name.data(), value.data());
4257 }
4258 return true; // Keep iterating through all attributes
4259 });
4260
4261 if (!gdb_type.empty() && !(encoding_set || format_set))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004262 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004263 if (gdb_type.find("int") == 0)
4264 {
4265 reg_info.format = eFormatHex;
4266 reg_info.encoding = eEncodingUint;
4267 }
4268 else if (gdb_type == "data_ptr" || gdb_type == "code_ptr")
4269 {
4270 reg_info.format = eFormatAddressInfo;
4271 reg_info.encoding = eEncodingUint;
4272 }
4273 else if (gdb_type == "i387_ext" || gdb_type == "float")
4274 {
4275 reg_info.format = eFormatFloat;
4276 reg_info.encoding = eEncodingIEEE754;
4277 }
Colin Rileyc3c95b22015-04-16 15:51:33 +00004278 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004279
4280 // Only update the register set name if we didn't get a "reg_set" attribute.
4281 // "set_name" will be empty if we didn't have a "reg_set" attribute.
4282 if (!set_name && !gdb_group.empty())
4283 set_name.SetCString(gdb_group.c_str());
4284
4285 reg_info.byte_offset = reg_offset;
4286 assert (reg_info.byte_size != 0);
4287 reg_offset += reg_info.byte_size;
4288 if (!value_regs.empty())
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004289 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004290 value_regs.push_back(LLDB_INVALID_REGNUM);
4291 reg_info.value_regs = value_regs.data();
Colin Rileyc3c95b22015-04-16 15:51:33 +00004292 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004293 if (!invalidate_regs.empty())
4294 {
4295 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
4296 reg_info.invalidate_regs = invalidate_regs.data();
4297 }
4298
Ewan Crawford682e8422015-06-26 09:38:27 +00004299 ++prev_reg_num;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004300 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
4301
4302 return true; // Keep iterating through all "reg" elements
4303 });
Colin Rileyc3c95b22015-04-16 15:51:33 +00004304 return true;
4305}
Greg Claytond04f0ed2015-05-26 18:00:51 +00004306
Colin Rileyc3c95b22015-04-16 15:51:33 +00004307} // namespace {}
4308
Colin Rileyc3c95b22015-04-16 15:51:33 +00004309
4310// query the target of gdb-remote for extended target information
4311// return: 'true' on success
4312// 'false' on failure
4313bool
Aidan Doddsc0c83852015-05-08 09:36:31 +00004314ProcessGDBRemote::GetGDBServerRegisterInfo ()
Colin Rileyc3c95b22015-04-16 15:51:33 +00004315{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004316 // Make sure LLDB has an XML parser it can use first
4317 if (!XMLDocument::XMLEnabled())
4318 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004319
4320 // redirect libxml2's error handler since the default prints to stdout
Colin Rileyc3c95b22015-04-16 15:51:33 +00004321
4322 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004323
4324 // check that we have extended feature read support
4325 if ( !comm.GetQXferFeaturesReadSupported( ) )
4326 return false;
4327
4328 // request the target xml file
4329 std::string raw;
4330 lldb_private::Error lldberr;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004331 if (!comm.ReadExtFeature(ConstString("features"),
4332 ConstString("target.xml"),
4333 raw,
4334 lldberr))
4335 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00004336 return false;
4337 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004338
Colin Rileyc3c95b22015-04-16 15:51:33 +00004339
Greg Claytond04f0ed2015-05-26 18:00:51 +00004340 XMLDocument xml_document;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004341
Greg Claytond04f0ed2015-05-26 18:00:51 +00004342 if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml"))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004343 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004344 GdbServerTargetInfo target_info;
4345
4346 XMLNode target_node = xml_document.GetRootElement("target");
4347 if (target_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004348 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004349 XMLNode feature_node;
4350 target_node.ForEachChildElement([&target_info, this, &feature_node](const XMLNode &node) -> bool
4351 {
4352 llvm::StringRef name = node.GetName();
4353 if (name == "architecture")
4354 {
4355 node.GetElementText(target_info.arch);
4356 }
4357 else if (name == "osabi")
4358 {
4359 node.GetElementText(target_info.osabi);
4360 }
Ewan Crawford682e8422015-06-26 09:38:27 +00004361 else if (name == "xi:include" || name == "include")
Greg Claytond04f0ed2015-05-26 18:00:51 +00004362 {
4363 llvm::StringRef href = node.GetAttributeValue("href");
4364 if (!href.empty())
4365 target_info.includes.push_back(href.str());
4366 }
4367 else if (name == "feature")
4368 {
4369 feature_node = node;
4370 }
4371 else if (name == "groups")
4372 {
4373 node.ForEachChildElementWithName("group", [&target_info](const XMLNode &node) -> bool {
4374 uint32_t set_id = UINT32_MAX;
4375 RegisterSetInfo set_info;
4376
4377 node.ForEachAttribute([&set_id, &set_info](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
4378 if (name == "id")
4379 set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4380 if (name == "name")
4381 set_info.name = ConstString(value);
4382 return true; // Keep iterating through all attributes
4383 });
4384
4385 if (set_id != UINT32_MAX)
4386 target_info.reg_set_map[set_id] = set_info;
4387 return true; // Keep iterating through all "group" elements
4388 });
4389 }
4390 return true; // Keep iterating through all children of the target_node
4391 });
4392
4393 if (feature_node)
4394 {
4395 ParseRegisters(feature_node, target_info, this->m_register_info);
4396 }
4397
4398 for (const auto &include : target_info.includes)
4399 {
4400 // request register file
4401 std::string xml_data;
4402 if (!comm.ReadExtFeature(ConstString("features"),
4403 ConstString(include),
4404 xml_data,
4405 lldberr))
4406 continue;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004407
Greg Claytond04f0ed2015-05-26 18:00:51 +00004408 XMLDocument include_xml_document;
4409 include_xml_document.ParseMemory(xml_data.data(), xml_data.size(), include.c_str());
4410 XMLNode include_feature_node = include_xml_document.GetRootElement("feature");
4411 if (include_feature_node)
4412 {
4413 ParseRegisters(include_feature_node, target_info, this->m_register_info);
4414 }
4415 }
4416 this->m_register_info.Finalize(GetTarget().GetArchitecture());
Colin Rileyc3c95b22015-04-16 15:51:33 +00004417 }
4418 }
4419
Greg Claytond04f0ed2015-05-26 18:00:51 +00004420 return m_register_info.GetNumRegisters() > 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004421}
4422
Aidan Doddsc0c83852015-05-08 09:36:31 +00004423Error
4424ProcessGDBRemote::GetLoadedModuleList (GDBLoadedModuleInfoList & list)
4425{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004426 // Make sure LLDB has an XML parser it can use first
4427 if (!XMLDocument::XMLEnabled())
4428 return Error (0, ErrorType::eErrorTypeGeneric);
4429
Aidan Doddsc0c83852015-05-08 09:36:31 +00004430 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS);
4431 if (log)
4432 log->Printf ("ProcessGDBRemote::%s", __FUNCTION__);
4433
Aidan Doddsc0c83852015-05-08 09:36:31 +00004434 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004435
4436 // check that we have extended feature read support
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004437 if (comm.GetQXferLibrariesSVR4ReadSupported ()) {
4438 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004439
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004440 // request the loaded library list
4441 std::string raw;
4442 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004443
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004444 if (!comm.ReadExtFeature (ConstString ("libraries-svr4"), ConstString (""), raw, lldberr))
4445 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004446
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004447 // parse the xml file in memory
4448 if (log)
4449 log->Printf ("parsing: %s", raw.c_str());
4450 XMLDocument doc;
4451
4452 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4453 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004454
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004455 XMLNode root_element = doc.GetRootElement("library-list-svr4");
4456 if (!root_element)
4457 return Error();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004458
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004459 // main link map structure
4460 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4461 if (!main_lm.empty())
4462 {
4463 list.m_link_map = StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
4464 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004465
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004466 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
Aidan Doddsc0c83852015-05-08 09:36:31 +00004467
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004468 GDBLoadedModuleInfoList::LoadedModuleInfo module;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004469
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004470 library.ForEachAttribute([log, &module](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004471
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004472 if (name == "name")
4473 module.set_name (value.str());
4474 else if (name == "lm")
4475 {
4476 // the address of the link_map struct.
4477 module.set_link_map(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4478 }
4479 else if (name == "l_addr")
4480 {
4481 // the displacement as read from the field 'l_addr' of the link_map struct.
4482 module.set_base(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4483
4484 }
4485 else if (name == "l_ld")
4486 {
4487 // the memory address of the libraries PT_DYAMIC section.
4488 module.set_dynamic(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4489 }
4490
4491 return true; // Keep iterating over all properties of "library"
4492 });
4493
4494 if (log)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004495 {
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004496 std::string name;
4497 lldb::addr_t lm=0, base=0, ld=0;
4498
4499 module.get_name (name);
4500 module.get_link_map (lm);
4501 module.get_base (base);
4502 module.get_dynamic (ld);
4503
4504 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 +00004505 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004506
4507 list.add (module);
4508 return true; // Keep iterating over all "library" elements in the root node
Greg Claytond04f0ed2015-05-26 18:00:51 +00004509 });
Aidan Doddsc0c83852015-05-08 09:36:31 +00004510
4511 if (log)
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004512 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4513 } else if (comm.GetQXferLibrariesReadSupported ()) {
4514 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004515
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004516 // request the loaded library list
4517 std::string raw;
4518 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004519
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004520 if (!comm.ReadExtFeature (ConstString ("libraries"), ConstString (""), raw, lldberr))
4521 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004522
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004523 if (log)
4524 log->Printf ("parsing: %s", raw.c_str());
4525 XMLDocument doc;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004526
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004527 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4528 return Error (0, ErrorType::eErrorTypeGeneric);
4529
4530 XMLNode root_element = doc.GetRootElement("library-list");
4531 if (!root_element)
4532 return Error();
4533
4534 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
4535 GDBLoadedModuleInfoList::LoadedModuleInfo module;
4536
4537 llvm::StringRef name = library.GetAttributeValue("name");
4538 module.set_name(name.str());
4539
4540 // The base address of a given library will be the address of its
4541 // first section. Most remotes send only one section for Windows
4542 // targets for example.
4543 const XMLNode &section = library.FindFirstChildElementWithName("section");
4544 llvm::StringRef address = section.GetAttributeValue("address");
4545 module.set_base(StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0));
4546
4547 if (log)
4548 {
4549 std::string name;
4550 lldb::addr_t base = 0;
4551 module.get_name (name);
4552 module.get_base (base);
4553
4554 log->Printf ("found (base:0x%" PRIx64 ", name:'%s')", base, name.c_str());
4555 }
4556
4557 list.add (module);
4558 return true; // Keep iterating over all "library" elements in the root node
4559 });
4560
4561 if (log)
4562 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4563 } else {
4564 return Error (0, ErrorType::eErrorTypeGeneric);
4565 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004566
4567 return Error();
4568}
4569
Aidan Doddsc0c83852015-05-08 09:36:31 +00004570lldb::ModuleSP
4571ProcessGDBRemote::LoadModuleAtAddress (const FileSpec &file, lldb::addr_t base_addr)
4572{
4573 Target &target = m_process->GetTarget();
4574 ModuleList &modules = target.GetImages();
4575 ModuleSP module_sp;
4576
4577 bool changed = false;
4578
4579 ModuleSpec module_spec (file, target.GetArchitecture());
4580 if ((module_sp = modules.FindFirstModule (module_spec)))
4581 {
4582 module_sp->SetLoadAddress (target, base_addr, true, changed);
4583 }
4584 else if ((module_sp = target.GetSharedModule (module_spec)))
4585 {
4586 module_sp->SetLoadAddress (target, base_addr, true, changed);
4587 }
4588
4589 return module_sp;
4590}
4591
4592size_t
4593ProcessGDBRemote::LoadModules ()
4594{
4595 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4596
4597 // request a list of loaded libraries from GDBServer
4598 GDBLoadedModuleInfoList module_list;
4599 if (GetLoadedModuleList (module_list).Fail())
4600 return 0;
4601
4602 // get a list of all the modules
4603 ModuleList new_modules;
4604
4605 for (GDBLoadedModuleInfoList::LoadedModuleInfo & modInfo : module_list.m_list)
4606 {
4607 std::string mod_name;
4608 lldb::addr_t mod_base;
4609
4610 bool valid = true;
4611 valid &= modInfo.get_name (mod_name);
4612 valid &= modInfo.get_base (mod_base);
4613 if (!valid)
4614 continue;
4615
4616 // hack (cleaner way to get file name only?) (win/unix compat?)
Vince Harron4cc8d202015-05-10 08:33:58 +00004617 size_t marker = mod_name.rfind ('/');
Aidan Doddsc0c83852015-05-08 09:36:31 +00004618 if (marker == std::string::npos)
4619 marker = 0;
4620 else
4621 marker += 1;
4622
4623 FileSpec file (mod_name.c_str()+marker, true);
4624 lldb::ModuleSP module_sp = LoadModuleAtAddress (file, mod_base);
4625
4626 if (module_sp.get())
4627 new_modules.Append (module_sp);
4628 }
4629
4630 if (new_modules.GetSize() > 0)
4631 {
4632 Target & target = m_target;
4633
4634 new_modules.ForEach ([&target](const lldb::ModuleSP module_sp) -> bool
4635 {
4636 lldb_private::ObjectFile * obj = module_sp->GetObjectFile ();
4637 if (!obj)
4638 return true;
4639
4640 if (obj->GetType () != ObjectFile::Type::eTypeExecutable)
4641 return true;
4642
4643 lldb::ModuleSP module_copy_sp = module_sp;
4644 target.SetExecutableModule (module_copy_sp, false);
4645 return false;
4646 });
4647
4648 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4649 loaded_modules.AppendIfNeeded (new_modules);
4650 m_process->GetTarget().ModulesDidLoad (new_modules);
4651 }
4652
4653 return new_modules.GetSize();
4654}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004655
Tamas Berghammer783bfc82015-06-18 20:43:56 +00004656Error
4657ProcessGDBRemote::GetFileLoadAddress(const FileSpec& file, bool& is_loaded, lldb::addr_t& load_addr)
4658{
4659 is_loaded = false;
4660 load_addr = LLDB_INVALID_ADDRESS;
4661
4662 std::string file_path = file.GetPath(false);
4663 if (file_path.empty ())
4664 return Error("Empty file name specified");
4665
4666 StreamString packet;
4667 packet.PutCString("qFileLoadAddress:");
4668 packet.PutCStringAsRawHex8(file_path.c_str());
4669
4670 StringExtractorGDBRemote response;
4671 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString().c_str(), response, false) != GDBRemoteCommunication::PacketResult::Success)
4672 return Error("Sending qFileLoadAddress packet failed");
4673
4674 if (response.IsErrorResponse())
4675 {
4676 if (response.GetError() == 1)
4677 {
4678 // The file is not loaded into the inferior
4679 is_loaded = false;
4680 load_addr = LLDB_INVALID_ADDRESS;
4681 return Error();
4682 }
4683
4684 return Error("Fetching file load address from remote server returned an error");
4685 }
4686
4687 if (response.IsNormalResponse())
4688 {
4689 is_loaded = true;
4690 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
4691 return Error();
4692 }
4693
4694 return Error("Unknown error happened during sending the load address packet");
4695}
4696
Greg Clayton0b90be12015-06-23 21:27:50 +00004697
4698void
4699ProcessGDBRemote::ModulesDidLoad (ModuleList &module_list)
4700{
4701 // We must call the lldb_private::Process::ModulesDidLoad () first before we do anything
4702 Process::ModulesDidLoad (module_list);
4703
4704 // After loading shared libraries, we can ask our remote GDB server if
4705 // it needs any symbols.
4706 m_gdb_comm.ServeSymbolLookups(this);
4707}
4708
4709
Greg Claytone034a042015-05-21 20:52:06 +00004710class CommandObjectProcessGDBRemoteSpeedTest: public CommandObjectParsed
4711{
4712public:
4713 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter) :
4714 CommandObjectParsed (interpreter,
4715 "process plugin packet speed-test",
4716 "Tests packet speeds of various sizes to determine the performance characteristics of the GDB remote connection. ",
4717 NULL),
4718 m_option_group (interpreter),
4719 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),
4720 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),
4721 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),
4722 m_json (LLDB_OPT_SET_1, false, "json", 'j', "Print the output as JSON data for easy parsing.", false, true)
4723 {
4724 m_option_group.Append (&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4725 m_option_group.Append (&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4726 m_option_group.Append (&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4727 m_option_group.Append (&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4728 m_option_group.Finalize();
4729 }
4730
4731 ~CommandObjectProcessGDBRemoteSpeedTest ()
4732 {
4733 }
4734
4735
4736 Options *
4737 GetOptions () override
4738 {
4739 return &m_option_group;
4740 }
4741
4742 bool
4743 DoExecute (Args& command, CommandReturnObject &result) override
4744 {
4745 const size_t argc = command.GetArgumentCount();
4746 if (argc == 0)
4747 {
4748 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4749 if (process)
4750 {
4751 StreamSP output_stream_sp (m_interpreter.GetDebugger().GetAsyncOutputStream());
4752 result.SetImmediateOutputStream (output_stream_sp);
4753
4754 const uint32_t num_packets = (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
4755 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
4756 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
4757 const bool json = m_json.GetOptionValue().GetCurrentValue();
4758 if (output_stream_sp)
4759 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, *output_stream_sp);
4760 else
4761 {
4762 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, result.GetOutputStream());
4763 }
4764 result.SetStatus (eReturnStatusSuccessFinishResult);
4765 return true;
4766 }
4767 }
4768 else
4769 {
4770 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
4771 }
4772 result.SetStatus (eReturnStatusFailed);
4773 return false;
4774 }
4775protected:
4776 OptionGroupOptions m_option_group;
4777 OptionGroupUInt64 m_num_packets;
4778 OptionGroupUInt64 m_max_send;
4779 OptionGroupUInt64 m_max_recv;
4780 OptionGroupBoolean m_json;
4781
4782};
4783
Greg Clayton02686b82012-10-15 22:42:16 +00004784class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00004785{
4786private:
4787
4788public:
Greg Clayton02686b82012-10-15 22:42:16 +00004789 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00004790 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00004791 "process plugin packet history",
4792 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00004793 NULL)
4794 {
4795 }
4796
Greg Clayton02686b82012-10-15 22:42:16 +00004797 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton998255b2012-10-13 02:07:45 +00004798 {
4799 }
4800
4801 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004802 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton998255b2012-10-13 02:07:45 +00004803 {
Greg Clayton02686b82012-10-15 22:42:16 +00004804 const size_t argc = command.GetArgumentCount();
4805 if (argc == 0)
4806 {
4807 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4808 if (process)
4809 {
4810 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
4811 result.SetStatus (eReturnStatusSuccessFinishResult);
4812 return true;
4813 }
4814 }
4815 else
4816 {
4817 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
4818 }
4819 result.SetStatus (eReturnStatusFailed);
4820 return false;
4821 }
4822};
4823
Jason Molenda6076bf42014-05-06 04:34:52 +00004824class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed
4825{
4826private:
4827
4828public:
4829 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) :
4830 CommandObjectParsed (interpreter,
4831 "process plugin packet xfer-size",
4832 "Maximum size that lldb will try to read/write one one chunk.",
4833 NULL)
4834 {
4835 }
4836
4837 ~CommandObjectProcessGDBRemotePacketXferSize ()
4838 {
4839 }
4840
4841 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004842 DoExecute (Args& command, CommandReturnObject &result) override
Jason Molenda6076bf42014-05-06 04:34:52 +00004843 {
4844 const size_t argc = command.GetArgumentCount();
4845 if (argc == 0)
4846 {
4847 result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str());
4848 result.SetStatus (eReturnStatusFailed);
4849 return false;
4850 }
4851
4852 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4853 if (process)
4854 {
4855 const char *packet_size = command.GetArgumentAtIndex(0);
4856 errno = 0;
4857 uint64_t user_specified_max = strtoul (packet_size, NULL, 10);
4858 if (errno == 0 && user_specified_max != 0)
4859 {
4860 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max);
4861 result.SetStatus (eReturnStatusSuccessFinishResult);
4862 return true;
4863 }
4864 }
4865 result.SetStatus (eReturnStatusFailed);
4866 return false;
4867 }
4868};
4869
4870
Greg Clayton02686b82012-10-15 22:42:16 +00004871class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
4872{
4873private:
4874
4875public:
4876 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
4877 CommandObjectParsed (interpreter,
4878 "process plugin packet send",
4879 "Send a custom packet through the GDB remote protocol and print the answer. "
4880 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
4881 NULL)
4882 {
4883 }
4884
4885 ~CommandObjectProcessGDBRemotePacketSend ()
4886 {
4887 }
4888
4889 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004890 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton02686b82012-10-15 22:42:16 +00004891 {
4892 const size_t argc = command.GetArgumentCount();
4893 if (argc == 0)
4894 {
4895 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
4896 result.SetStatus (eReturnStatusFailed);
4897 return false;
4898 }
4899
4900 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4901 if (process)
4902 {
Han Ming Ong84145852012-11-26 20:42:03 +00004903 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00004904 {
Han Ming Ong84145852012-11-26 20:42:03 +00004905 const char *packet_cstr = command.GetArgumentAtIndex(0);
4906 bool send_async = true;
4907 StringExtractorGDBRemote response;
4908 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
4909 result.SetStatus (eReturnStatusSuccessFinishResult);
4910 Stream &output_strm = result.GetOutputStream();
4911 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00004912 std::string &response_str = response.GetStringRef();
4913
Han Ming Ong399289e2013-06-21 19:56:59 +00004914 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00004915 {
4916 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
4917 }
4918
Han Ming Ong84145852012-11-26 20:42:03 +00004919 if (response_str.empty())
4920 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
4921 else
4922 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00004923 }
Greg Clayton02686b82012-10-15 22:42:16 +00004924 }
Greg Clayton998255b2012-10-13 02:07:45 +00004925 return true;
4926 }
4927};
4928
Greg Claytonba4a0a52013-02-01 23:03:47 +00004929class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
4930{
4931private:
4932
4933public:
4934 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
4935 CommandObjectRaw (interpreter,
4936 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00004937 "Send a qRcmd packet through the GDB remote protocol and print the response."
4938 "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 +00004939 NULL)
4940 {
4941 }
4942
4943 ~CommandObjectProcessGDBRemotePacketMonitor ()
4944 {
4945 }
4946
4947 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004948 DoExecute (const char *command, CommandReturnObject &result) override
Greg Claytonba4a0a52013-02-01 23:03:47 +00004949 {
4950 if (command == NULL || command[0] == '\0')
4951 {
4952 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
4953 result.SetStatus (eReturnStatusFailed);
4954 return false;
4955 }
4956
4957 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4958 if (process)
4959 {
4960 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00004961 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00004962 packet.PutBytesAsRawHex8(command, strlen(command));
4963 const char *packet_cstr = packet.GetString().c_str();
4964
4965 bool send_async = true;
4966 StringExtractorGDBRemote response;
4967 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
4968 result.SetStatus (eReturnStatusSuccessFinishResult);
4969 Stream &output_strm = result.GetOutputStream();
4970 output_strm.Printf (" packet: %s\n", packet_cstr);
4971 const std::string &response_str = response.GetStringRef();
4972
4973 if (response_str.empty())
4974 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
4975 else
4976 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
4977 }
4978 return true;
4979 }
4980};
4981
Greg Clayton02686b82012-10-15 22:42:16 +00004982class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
4983{
4984private:
4985
4986public:
4987 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
4988 CommandObjectMultiword (interpreter,
4989 "process plugin packet",
4990 "Commands that deal with GDB remote packets.",
4991 NULL)
4992 {
4993 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
4994 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00004995 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Jason Molenda6076bf42014-05-06 04:34:52 +00004996 LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter)));
Greg Claytone034a042015-05-21 20:52:06 +00004997 LoadSubCommand ("speed-test", CommandObjectSP (new CommandObjectProcessGDBRemoteSpeedTest (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00004998 }
4999
5000 ~CommandObjectProcessGDBRemotePacket ()
5001 {
5002 }
5003};
Greg Clayton998255b2012-10-13 02:07:45 +00005004
5005class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
5006{
5007public:
5008 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
5009 CommandObjectMultiword (interpreter,
5010 "process plugin",
5011 "A set of commands for operating on a ProcessGDBRemote process.",
5012 "process plugin <subcommand> [<subcommand-options>]")
5013 {
5014 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
5015 }
5016
5017 ~CommandObjectMultiwordProcessGDBRemote ()
5018 {
5019 }
5020};
5021
Greg Clayton998255b2012-10-13 02:07:45 +00005022CommandObject *
5023ProcessGDBRemote::GetPluginCommandObject()
5024{
5025 if (!m_command_sp)
5026 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
5027 return m_command_sp.get();
5028}