blob: 94dac0c2d4e31dec94b669e5eb15758206ca630c [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();
Pavel Labath4a4bb122015-07-16 14:14:35 +00001400 m_threads_info_sp.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001401 return Error();
1402}
1403
1404Error
1405ProcessGDBRemote::DoResume ()
1406{
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001407 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001408 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001409 if (log)
1410 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytone5219662010-12-03 06:02:24 +00001411
1412 Listener listener ("gdb-remote.resume-packet-sent");
1413 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1414 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00001415 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1416
Greg Claytond1d06e42013-04-20 00:27:58 +00001417 const size_t num_threads = GetThreadList().GetSize();
1418
Greg Clayton71fc2a32011-02-12 06:28:37 +00001419 StreamString continue_packet;
1420 bool continue_packet_error = false;
1421 if (m_gdb_comm.HasAnyVContSupport ())
1422 {
Ewan Crawford78baa192015-05-13 09:18:18 +00001423 if (!GetTarget().GetNonStopModeEnabled() &&
1424 (m_continue_c_tids.size() == num_threads ||
Greg Claytone98008c2014-02-13 23:34:38 +00001425 (m_continue_c_tids.empty() &&
1426 m_continue_C_tids.empty() &&
1427 m_continue_s_tids.empty() &&
Ewan Crawford78baa192015-05-13 09:18:18 +00001428 m_continue_S_tids.empty())))
Greg Clayton71fc2a32011-02-12 06:28:37 +00001429 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001430 // All threads are continuing, just send a "c" packet
1431 continue_packet.PutCString ("c");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001432 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001433 else
1434 {
1435 continue_packet.PutCString ("vCont");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001436
Greg Claytond1d06e42013-04-20 00:27:58 +00001437 if (!m_continue_c_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001438 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001439 if (m_gdb_comm.GetVContSupported ('c'))
1440 {
1441 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)
1442 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1443 }
1444 else
1445 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001446 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001447
1448 if (!continue_packet_error && !m_continue_C_tids.empty())
1449 {
1450 if (m_gdb_comm.GetVContSupported ('C'))
1451 {
1452 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)
1453 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1454 }
1455 else
1456 continue_packet_error = true;
1457 }
Greg Claytone5219662010-12-03 06:02:24 +00001458
Greg Claytond1d06e42013-04-20 00:27:58 +00001459 if (!continue_packet_error && !m_continue_s_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001460 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001461 if (m_gdb_comm.GetVContSupported ('s'))
1462 {
1463 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)
1464 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1465 }
1466 else
1467 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001468 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001469
1470 if (!continue_packet_error && !m_continue_S_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001471 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001472 if (m_gdb_comm.GetVContSupported ('S'))
1473 {
1474 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)
1475 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1476 }
1477 else
1478 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001479 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001480
1481 if (continue_packet_error)
1482 continue_packet.GetString().clear();
Greg Clayton71fc2a32011-02-12 06:28:37 +00001483 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001484 }
1485 else
1486 continue_packet_error = true;
1487
1488 if (continue_packet_error)
1489 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001490 // Either no vCont support, or we tried to use part of the vCont
1491 // packet that wasn't supported by the remote GDB server.
1492 // We need to try and make a simple packet that can do our continue
Greg Clayton71fc2a32011-02-12 06:28:37 +00001493 const size_t num_continue_c_tids = m_continue_c_tids.size();
1494 const size_t num_continue_C_tids = m_continue_C_tids.size();
1495 const size_t num_continue_s_tids = m_continue_s_tids.size();
1496 const size_t num_continue_S_tids = m_continue_S_tids.size();
1497 if (num_continue_c_tids > 0)
1498 {
1499 if (num_continue_c_tids == num_threads)
1500 {
1501 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001502 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001503 continue_packet.PutChar ('c');
1504 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001505 }
1506 else if (num_continue_c_tids == 1 &&
1507 num_continue_C_tids == 0 &&
1508 num_continue_s_tids == 0 &&
1509 num_continue_S_tids == 0 )
1510 {
1511 // Only one thread is continuing
Greg Clayton8b82f082011-04-12 05:54:46 +00001512 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001513 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001514 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001515 }
1516 }
1517
Greg Clayton0c74e782011-06-24 03:21:43 +00001518 if (continue_packet_error && num_continue_C_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001519 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001520 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1521 num_continue_C_tids > 0 &&
1522 num_continue_s_tids == 0 &&
1523 num_continue_S_tids == 0 )
Greg Clayton71fc2a32011-02-12 06:28:37 +00001524 {
1525 const int continue_signo = m_continue_C_tids.front().second;
Greg Clayton0c74e782011-06-24 03:21:43 +00001526 // Only one thread is continuing
Greg Clayton71fc2a32011-02-12 06:28:37 +00001527 if (num_continue_C_tids > 1)
1528 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001529 // More that one thread with a signal, yet we don't have
1530 // vCont support and we are being asked to resume each
1531 // thread with a signal, we need to make sure they are
1532 // all the same signal, or we can't issue the continue
1533 // accurately with the current support...
1534 if (num_continue_C_tids > 1)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001535 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001536 continue_packet_error = false;
1537 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1538 {
1539 if (m_continue_C_tids[i].second != continue_signo)
1540 continue_packet_error = true;
1541 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001542 }
Greg Clayton0c74e782011-06-24 03:21:43 +00001543 if (!continue_packet_error)
1544 m_gdb_comm.SetCurrentThreadForRun (-1);
1545 }
1546 else
1547 {
1548 // Set the continue thread ID
1549 continue_packet_error = false;
1550 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001551 }
1552 if (!continue_packet_error)
1553 {
1554 // Add threads continuing with the same signo...
Greg Clayton71fc2a32011-02-12 06:28:37 +00001555 continue_packet.Printf("C%2.2x", continue_signo);
1556 }
1557 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001558 }
1559
Greg Clayton0c74e782011-06-24 03:21:43 +00001560 if (continue_packet_error && num_continue_s_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001561 {
1562 if (num_continue_s_tids == num_threads)
1563 {
1564 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001565 m_gdb_comm.SetCurrentThreadForRun (-1);
Ewan Crawford76df2882015-06-23 12:32:06 +00001566
1567 // If in Non-Stop-Mode use vCont when stepping
1568 if (GetTarget().GetNonStopModeEnabled())
1569 {
1570 if (m_gdb_comm.GetVContSupported('s'))
1571 continue_packet.PutCString("vCont;s");
1572 else
1573 continue_packet.PutChar('s');
1574 }
1575 else
1576 continue_packet.PutChar('s');
1577
Greg Clayton0c74e782011-06-24 03:21:43 +00001578 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001579 }
1580 else if (num_continue_c_tids == 0 &&
1581 num_continue_C_tids == 0 &&
1582 num_continue_s_tids == 1 &&
1583 num_continue_S_tids == 0 )
1584 {
1585 // Only one thread is stepping
Greg Clayton8b82f082011-04-12 05:54:46 +00001586 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001587 continue_packet.PutChar ('s');
Greg Clayton0c74e782011-06-24 03:21:43 +00001588 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001589 }
1590 }
1591
1592 if (!continue_packet_error && num_continue_S_tids > 0)
1593 {
1594 if (num_continue_S_tids == num_threads)
1595 {
1596 const int step_signo = m_continue_S_tids.front().second;
1597 // Are all threads trying to step with the same signal?
Greg Clayton0c74e782011-06-24 03:21:43 +00001598 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001599 if (num_continue_S_tids > 1)
1600 {
1601 for (size_t i=1; i<num_threads; ++i)
1602 {
1603 if (m_continue_S_tids[i].second != step_signo)
1604 continue_packet_error = true;
1605 }
1606 }
1607 if (!continue_packet_error)
1608 {
1609 // Add threads stepping with the same signo...
Greg Clayton8b82f082011-04-12 05:54:46 +00001610 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001611 continue_packet.Printf("S%2.2x", step_signo);
1612 }
1613 }
1614 else if (num_continue_c_tids == 0 &&
1615 num_continue_C_tids == 0 &&
1616 num_continue_s_tids == 0 &&
1617 num_continue_S_tids == 1 )
1618 {
1619 // Only one thread is stepping with signal
Greg Clayton8b82f082011-04-12 05:54:46 +00001620 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001621 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Clayton0c74e782011-06-24 03:21:43 +00001622 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001623 }
1624 }
1625 }
1626
1627 if (continue_packet_error)
1628 {
1629 error.SetErrorString ("can't make continue packet for this resume");
1630 }
1631 else
1632 {
1633 EventSP event_sp;
1634 TimeValue timeout;
1635 timeout = TimeValue::Now();
1636 timeout.OffsetWithSeconds (5);
Zachary Turneracee96a2014-09-23 18:32:09 +00001637 if (!m_async_thread.IsJoinable())
Jim Inghamb1e2e842012-04-12 18:49:31 +00001638 {
1639 error.SetErrorString ("Trying to resume but the async thread is dead.");
1640 if (log)
1641 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1642 return error;
1643 }
1644
Greg Clayton71fc2a32011-02-12 06:28:37 +00001645 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1646
1647 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Inghamb1e2e842012-04-12 18:49:31 +00001648 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001649 error.SetErrorString("Resume timed out.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00001650 if (log)
1651 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1652 }
1653 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1654 {
1655 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1656 if (log)
1657 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1658 return error;
1659 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001660 }
Greg Claytone5219662010-12-03 06:02:24 +00001661 }
1662
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001663 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001664}
1665
Greg Clayton9e920902012-04-10 02:25:43 +00001666void
Ewan Crawford78baa192015-05-13 09:18:18 +00001667ProcessGDBRemote::HandleStopReplySequence ()
1668{
1669 while(true)
1670 {
1671 // Send vStopped
1672 StringExtractorGDBRemote response;
1673 m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false);
1674
1675 // OK represents end of signal list
1676 if (response.IsOKResponse())
1677 break;
1678
1679 // If not OK or a normal packet we have a problem
1680 if (!response.IsNormalResponse())
1681 break;
1682
1683 SetLastStopPacket(response);
1684 }
1685}
1686
1687void
Greg Clayton9e920902012-04-10 02:25:43 +00001688ProcessGDBRemote::ClearThreadIDList ()
1689{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001690 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001691 m_thread_ids.clear();
1692}
1693
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001694size_t
1695ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue (std::string &value)
1696{
1697 m_thread_ids.clear();
1698 size_t comma_pos;
1699 lldb::tid_t tid;
1700 while ((comma_pos = value.find(',')) != std::string::npos)
1701 {
1702 value[comma_pos] = '\0';
1703 // thread in big endian hex
1704 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1705 if (tid != LLDB_INVALID_THREAD_ID)
1706 m_thread_ids.push_back (tid);
1707 value.erase(0, comma_pos + 1);
1708 }
1709 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1710 if (tid != LLDB_INVALID_THREAD_ID)
1711 m_thread_ids.push_back (tid);
1712 return m_thread_ids.size();
1713}
1714
Greg Clayton9e920902012-04-10 02:25:43 +00001715bool
1716ProcessGDBRemote::UpdateThreadIDList ()
1717{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001718 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001719
1720 if (m_threads_info_sp)
1721 {
1722 // If we have the JSON threads info, we can get the thread list from that
1723 StructuredData::Array *thread_infos = m_threads_info_sp->GetAsArray();
1724 if (thread_infos && thread_infos->GetSize() > 0)
1725 {
1726 m_thread_ids.clear();
1727 thread_infos->ForEach([this](StructuredData::Object* object) -> bool {
1728 StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1729 if (thread_dict)
1730 {
1731 // Set the thread stop info from the JSON dictionary
1732 SetThreadStopInfo (thread_dict);
1733 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1734 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1735 m_thread_ids.push_back(tid);
1736 }
1737 return true; // Keep iterating through all thread_info objects
1738 });
1739 }
1740 if (!m_thread_ids.empty())
1741 return true;
1742 }
1743 else
1744 {
1745 // See if we can get the thread IDs from the current stop reply packets
1746 // that might contain a "threads" key/value pair
1747
1748 // Lock the thread stack while we access it
1749 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
1750 // Get the number of stop packets on the stack
1751 int nItems = m_stop_packet_stack.size();
1752 // Iterate over them
1753 for (int i = 0; i < nItems; i++)
1754 {
1755 // Get the thread stop info
1756 StringExtractorGDBRemote &stop_info = m_stop_packet_stack[i];
1757 const std::string &stop_info_str = stop_info.GetStringRef();
1758 const size_t threads_pos = stop_info_str.find(";threads:");
1759 if (threads_pos != std::string::npos)
1760 {
1761 const size_t start = threads_pos + strlen(";threads:");
1762 const size_t end = stop_info_str.find(';', start);
1763 if (end != std::string::npos)
1764 {
1765 std::string value = stop_info_str.substr(start, end - start);
1766 if (UpdateThreadIDsFromStopReplyThreadsValue(value))
1767 return true;
1768 }
1769 }
1770 }
1771 }
1772
Greg Clayton9e920902012-04-10 02:25:43 +00001773 bool sequence_mutex_unavailable = false;
1774 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1775 if (sequence_mutex_unavailable)
1776 {
Greg Clayton9e920902012-04-10 02:25:43 +00001777 return false; // We just didn't get the list
1778 }
1779 return true;
1780}
1781
Greg Clayton9fc13552012-04-10 00:18:59 +00001782bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001783ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001784{
1785 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +00001786 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Clayton73b472d2010-10-27 03:32:59 +00001787 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +00001788 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton9e920902012-04-10 02:25:43 +00001789
1790 size_t num_thread_ids = m_thread_ids.size();
1791 // The "m_thread_ids" thread ID list should always be updated after each stop
1792 // reply packet, but in case it isn't, update it here.
1793 if (num_thread_ids == 0)
1794 {
1795 if (!UpdateThreadIDList ())
1796 return false;
1797 num_thread_ids = m_thread_ids.size();
1798 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001799
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001800 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001801 if (num_thread_ids > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001802 {
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001803 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001804 {
Greg Clayton9e920902012-04-10 02:25:43 +00001805 tid_t tid = m_thread_ids[i];
Greg Clayton160c9d82013-05-01 21:54:04 +00001806 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001807 if (!thread_sp)
Jim Inghamdee1bc92013-06-22 00:27:45 +00001808 {
Jim Ingham4f465cf2012-10-10 18:32:14 +00001809 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001810 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1811 log->Printf(
1812 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001813 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001814 thread_sp->GetID());
1815 }
1816 else
1817 {
1818 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1819 log->Printf(
1820 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001821 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001822 thread_sp->GetID());
1823 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001824 new_thread_list.AddThread(thread_sp);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001825 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001826 }
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001827
1828 // Whatever that is left in old_thread_list_copy are not
1829 // present in new_thread_list. Remove non-existent threads from internal id table.
1830 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1831 for (size_t i=0; i<old_num_thread_ids; i++)
1832 {
1833 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1834 if (old_thread_sp)
1835 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001836 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001837 m_thread_id_to_index_id_map.erase(old_thread_id);
1838 }
1839 }
1840
Greg Clayton9fc13552012-04-10 00:18:59 +00001841 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001842}
1843
Greg Clayton358cf1e2015-06-25 21:46:34 +00001844bool
1845ProcessGDBRemote::CalculateThreadStopInfo (ThreadGDBRemote *thread)
1846{
1847 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet
1848 if (m_threads_info_sp)
1849 {
1850 StructuredData::Array *thread_infos = m_threads_info_sp->GetAsArray();
1851 if (thread_infos)
1852 {
1853 lldb::tid_t tid;
1854 const size_t n = thread_infos->GetSize();
1855 for (size_t i=0; i<n; ++i)
1856 {
1857 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1858 if (thread_dict)
1859 {
1860 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid, LLDB_INVALID_THREAD_ID))
1861 {
1862 if (tid == thread->GetID())
1863 return SetThreadStopInfo(thread_dict);
1864 }
1865 }
1866 }
1867 }
1868 }
1869
1870 // Fall back to using the qThreadStopInfo packet
1871 StringExtractorGDBRemote stop_packet;
1872 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1873 return SetThreadStopInfo (stop_packet) == eStateStopped;
1874 return false;
1875}
1876
1877
1878ThreadSP
1879ProcessGDBRemote::SetThreadStopInfo (lldb::tid_t tid,
1880 ExpeditedRegisterMap &expedited_register_map,
1881 uint8_t signo,
1882 const std::string &thread_name,
1883 const std::string &reason,
1884 const std::string &description,
1885 uint32_t exc_type,
1886 const std::vector<addr_t> &exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001887 addr_t thread_dispatch_qaddr,
1888 bool queue_vars_valid, // Set to true if queue_name, queue_kind and queue_serial are valid
1889 std::string &queue_name,
1890 QueueKind queue_kind,
1891 uint64_t queue_serial)
Greg Clayton358cf1e2015-06-25 21:46:34 +00001892{
1893 ThreadSP thread_sp;
1894 if (tid != LLDB_INVALID_THREAD_ID)
1895 {
1896 // Scope for "locker" below
1897 {
1898 // m_thread_list_real does have its own mutex, but we need to
1899 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1900 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1901 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1902 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1903
1904 if (!thread_sp)
1905 {
1906 // Create the thread if we need to
1907 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1908 m_thread_list_real.AddThread(thread_sp);
1909 }
1910 }
1911
1912 if (thread_sp)
1913 {
1914 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1915 gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001916
Greg Clayton358cf1e2015-06-25 21:46:34 +00001917 for (const auto &pair : expedited_register_map)
1918 {
1919 StringExtractor reg_value_extractor;
1920 reg_value_extractor.GetStringRef() = pair.second;
1921 gdb_thread->PrivateSetRegisterValue (pair.first, reg_value_extractor);
1922 }
1923
1924 // Clear the stop info just in case we don't set it to anything
1925 thread_sp->SetStopInfo (StopInfoSP());
1926 thread_sp->SetName (thread_name.empty() ? NULL : thread_name.c_str());
1927
1928 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00001929 // Check if the GDB server was able to provide the queue name, kind and serial number
1930 if (queue_vars_valid)
1931 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind, queue_serial);
1932 else
1933 gdb_thread->ClearQueueInfo();
1934
1935
Greg Clayton358cf1e2015-06-25 21:46:34 +00001936 if (exc_type != 0)
1937 {
1938 const size_t exc_data_size = exc_data.size();
1939
1940 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1941 exc_type,
1942 exc_data_size,
1943 exc_data_size >= 1 ? exc_data[0] : 0,
1944 exc_data_size >= 2 ? exc_data[1] : 0,
1945 exc_data_size >= 3 ? exc_data[2] : 0));
1946 }
1947 else
1948 {
1949 bool handled = false;
1950 bool did_exec = false;
1951 if (!reason.empty())
1952 {
1953 if (reason.compare("trace") == 0)
1954 {
1955 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1956 handled = true;
1957 }
1958 else if (reason.compare("breakpoint") == 0)
1959 {
1960 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1961 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
1962 if (bp_site_sp)
1963 {
1964 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1965 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1966 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1967 handled = true;
1968 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
1969 {
1970 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1971 }
1972 else
1973 {
1974 StopInfoSP invalid_stop_info_sp;
1975 thread_sp->SetStopInfo (invalid_stop_info_sp);
1976 }
1977 }
1978 }
1979 else if (reason.compare("trap") == 0)
1980 {
1981 // Let the trap just use the standard signal stop reason below...
1982 }
1983 else if (reason.compare("watchpoint") == 0)
1984 {
1985 StringExtractor desc_extractor(description.c_str());
1986 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1987 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
1988 watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
1989 if (wp_addr != LLDB_INVALID_ADDRESS)
1990 {
1991 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
1992 if (wp_sp)
1993 {
1994 wp_sp->SetHardwareIndex(wp_index);
1995 watch_id = wp_sp->GetID();
1996 }
1997 }
1998 if (watch_id == LLDB_INVALID_WATCH_ID)
1999 {
2000 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_WATCHPOINTS));
2001 if (log) log->Printf ("failed to find watchpoint");
2002 }
2003 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
2004 handled = true;
2005 }
2006 else if (reason.compare("exception") == 0)
2007 {
2008 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
2009 handled = true;
2010 }
2011 else if (reason.compare("exec") == 0)
2012 {
2013 did_exec = true;
2014 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
2015 handled = true;
2016 }
2017 }
2018
2019 if (!handled && signo && did_exec == false)
2020 {
2021 if (signo == SIGTRAP)
2022 {
2023 // Currently we are going to assume SIGTRAP means we are either
2024 // hitting a breakpoint or hardware single stepping.
2025 handled = true;
2026 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
2027 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2028
2029 if (bp_site_sp)
2030 {
2031 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2032 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2033 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2034 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2035 {
2036 if(m_breakpoint_pc_offset != 0)
2037 thread_sp->GetRegisterContext()->SetPC(pc);
2038 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2039 }
2040 else
2041 {
2042 StopInfoSP invalid_stop_info_sp;
2043 thread_sp->SetStopInfo (invalid_stop_info_sp);
2044 }
2045 }
2046 else
2047 {
2048 // If we were stepping then assume the stop was the result of the trace. If we were
2049 // not stepping then report the SIGTRAP.
2050 // FIXME: We are still missing the case where we single step over a trap instruction.
2051 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
2052 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
2053 else
2054 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo, description.c_str()));
2055 }
2056 }
2057 if (!handled)
2058 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo, description.c_str()));
2059 }
2060
2061 if (!description.empty())
2062 {
2063 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
2064 if (stop_info_sp)
2065 {
2066 const char *stop_info_desc = stop_info_sp->GetDescription();
2067 if (!stop_info_desc || !stop_info_desc[0])
2068 stop_info_sp->SetDescription (description.c_str());
2069 }
2070 else
2071 {
2072 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
2073 }
2074 }
2075 }
2076 }
2077 }
2078 return thread_sp;
2079}
2080
2081StateType
2082ProcessGDBRemote::SetThreadStopInfo (StructuredData::Dictionary *thread_dict)
2083{
2084 static ConstString g_key_tid("tid");
2085 static ConstString g_key_name("name");
2086 static ConstString g_key_reason("reason");
2087 static ConstString g_key_metype("metype");
2088 static ConstString g_key_medata("medata");
2089 static ConstString g_key_qaddr("qaddr");
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002090 static ConstString g_key_queue_name("qname");
2091 static ConstString g_key_queue_kind("qkind");
2092 static ConstString g_key_queue_serial("qserial");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002093 static ConstString g_key_registers("registers");
2094 static ConstString g_key_memory("memory");
2095 static ConstString g_key_address("address");
2096 static ConstString g_key_bytes("bytes");
2097 static ConstString g_key_description("description");
Pavel Labath4a4bb122015-07-16 14:14:35 +00002098 static ConstString g_key_signal("signal");
Greg Clayton358cf1e2015-06-25 21:46:34 +00002099
2100 // Stop with signal and thread info
2101 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2102 uint8_t signo = 0;
2103 std::string value;
2104 std::string thread_name;
2105 std::string reason;
2106 std::string description;
2107 uint32_t exc_type = 0;
2108 std::vector<addr_t> exc_data;
2109 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2110 ExpeditedRegisterMap expedited_register_map;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002111 bool queue_vars_valid = false;
2112 std::string queue_name;
2113 QueueKind queue_kind = eQueueKindUnknown;
2114 uint64_t queue_serial = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002115 // Iterate through all of the thread dictionary key/value pairs from the structured data dictionary
2116
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002117 thread_dict->ForEach([this,
2118 &tid,
2119 &expedited_register_map,
2120 &thread_name,
2121 &signo,
2122 &reason,
2123 &description,
2124 &exc_type,
2125 &exc_data,
2126 &thread_dispatch_qaddr,
2127 &queue_vars_valid,
2128 &queue_name,
2129 &queue_kind,
2130 &queue_serial]
2131 (ConstString key, StructuredData::Object* object) -> bool
Greg Clayton358cf1e2015-06-25 21:46:34 +00002132 {
2133 if (key == g_key_tid)
2134 {
2135 // thread in big endian hex
2136 tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
2137 }
2138 else if (key == g_key_metype)
2139 {
2140 // exception type in big endian hex
2141 exc_type = object->GetIntegerValue(0);
2142 }
2143 else if (key == g_key_medata)
2144 {
2145 // exception data in big endian hex
2146 StructuredData::Array *array = object->GetAsArray();
2147 if (array)
2148 {
2149 array->ForEach([&exc_data](StructuredData::Object* object) -> bool {
2150 exc_data.push_back(object->GetIntegerValue());
2151 return true; // Keep iterating through all array items
2152 });
2153 }
2154 }
2155 else if (key == g_key_name)
2156 {
2157 thread_name = std::move(object->GetStringValue());
2158 }
2159 else if (key == g_key_qaddr)
2160 {
2161 thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
2162 }
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002163 else if (key == g_key_queue_name)
2164 {
2165 queue_vars_valid = true;
2166 queue_name = std::move(object->GetStringValue());
2167 }
2168 else if (key == g_key_queue_kind)
2169 {
2170 std::string queue_kind_str = object->GetStringValue();
2171 if (queue_kind_str == "serial")
2172 {
2173 queue_vars_valid = true;
2174 queue_kind = eQueueKindSerial;
2175 }
2176 else if (queue_kind_str == "concurrent")
2177 {
2178 queue_vars_valid = true;
2179 queue_kind = eQueueKindConcurrent;
2180 }
2181 }
2182 else if (key == g_key_queue_serial)
2183 {
2184 queue_serial = object->GetIntegerValue(0);
2185 if (queue_serial != 0)
2186 queue_vars_valid = true;
2187 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002188 else if (key == g_key_reason)
2189 {
2190 reason = std::move(object->GetStringValue());
2191 }
2192 else if (key == g_key_description)
2193 {
2194 description = std::move(object->GetStringValue());
2195 }
2196 else if (key == g_key_registers)
2197 {
2198 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2199
2200 if (registers_dict)
2201 {
2202 registers_dict->ForEach([&expedited_register_map](ConstString key, StructuredData::Object* object) -> bool {
2203 const uint32_t reg = StringConvert::ToUInt32 (key.GetCString(), UINT32_MAX, 10);
2204 if (reg != UINT32_MAX)
2205 expedited_register_map[reg] = std::move(object->GetStringValue());
2206 return true; // Keep iterating through all array items
2207 });
2208 }
2209 }
2210 else if (key == g_key_memory)
2211 {
2212 StructuredData::Array *array = object->GetAsArray();
2213 if (array)
2214 {
2215 array->ForEach([this](StructuredData::Object* object) -> bool {
2216 StructuredData::Dictionary *mem_cache_dict = object->GetAsDictionary();
2217 if (mem_cache_dict)
2218 {
2219 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2220 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>("address", mem_cache_addr))
2221 {
2222 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
2223 {
2224 StringExtractor bytes;
2225 if (mem_cache_dict->GetValueForKeyAsString("bytes", bytes.GetStringRef()))
2226 {
2227 bytes.SetFilePos(0);
2228
2229 const size_t byte_size = bytes.GetStringRef().size()/2;
2230 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2231 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2232 if (bytes_copied == byte_size)
2233 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2234 }
2235 }
2236 }
2237 }
2238 return true; // Keep iterating through all array items
2239 });
2240 }
2241
2242 }
Pavel Labath4a4bb122015-07-16 14:14:35 +00002243 else if (key == g_key_signal)
2244 signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002245 return true; // Keep iterating through all dictionary key/value pairs
2246 });
2247
2248 SetThreadStopInfo (tid,
2249 expedited_register_map,
2250 signo,
2251 thread_name,
2252 reason,
2253 description,
2254 exc_type,
2255 exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002256 thread_dispatch_qaddr,
2257 queue_vars_valid,
2258 queue_name,
2259 queue_kind,
2260 queue_serial);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002261
2262 return eStateExited;
2263}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002264
2265StateType
2266ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
2267{
Greg Claytondd0e5a52011-06-02 22:22:38 +00002268 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002269 const char stop_type = stop_packet.GetChar();
2270 switch (stop_type)
2271 {
2272 case 'T':
2273 case 'S':
2274 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00002275 // This is a bit of a hack, but is is required. If we did exec, we
2276 // need to clear our thread lists and also know to rebuild our dynamic
2277 // register info before we lookup and threads and populate the expedited
2278 // register values so we need to know this right away so we can cleanup
2279 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00002280 const uint32_t stop_id = GetStopID();
2281 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00002282 {
2283 // Our first stop, make sure we have a process ID, and also make
2284 // sure we know about our registers
2285 if (GetID() == LLDB_INVALID_PROCESS_ID)
2286 {
Greg Claytonc574ede2011-03-10 02:26:48 +00002287 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00002288 if (pid != LLDB_INVALID_PROCESS_ID)
2289 SetID (pid);
2290 }
2291 BuildDynamicRegisterInfo (true);
2292 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002293 // Stop with signal and thread info
Greg Clayton358cf1e2015-06-25 21:46:34 +00002294 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002295 const uint8_t signo = stop_packet.GetHexU8();
Greg Clayton358cf1e2015-06-25 21:46:34 +00002296 std::string key;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002297 std::string value;
2298 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00002299 std::string reason;
2300 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002301 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00002302 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002303 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton0b90be12015-06-23 21:27:50 +00002304 bool queue_vars_valid = false; // says if locals below that start with "queue_" are valid
2305 std::string queue_name;
2306 QueueKind queue_kind = eQueueKindUnknown;
2307 uint64_t queue_serial = 0;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002308 ExpeditedRegisterMap expedited_register_map;
2309 while (stop_packet.GetNameColonValue(key, value))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002310 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002311 if (key.compare("metype") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002312 {
2313 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002314 exc_type = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002315 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002316 else if (key.compare("medata") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002317 {
2318 // exception data in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002319 exc_data.push_back(StringConvert::ToUInt64 (value.c_str(), 0, 16));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002320 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002321 else if (key.compare("thread") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002322 {
2323 // thread in big endian hex
Greg Clayton358cf1e2015-06-25 21:46:34 +00002324 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002325 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002326 else if (key.compare("threads") == 0)
Greg Clayton9e920902012-04-10 02:25:43 +00002327 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002328 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00002329 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00002330 // A comma separated list of all threads in the current
2331 // process that includes the thread for this stop reply
2332 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00002333 size_t comma_pos;
2334 lldb::tid_t tid;
2335 while ((comma_pos = value.find(',')) != std::string::npos)
2336 {
2337 value[comma_pos] = '\0';
2338 // thread in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002339 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00002340 if (tid != LLDB_INVALID_THREAD_ID)
2341 m_thread_ids.push_back (tid);
2342 value.erase(0, comma_pos + 1);
Greg Clayton9e920902012-04-10 02:25:43 +00002343 }
Vince Harron5275aaa2015-01-15 20:08:35 +00002344 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00002345 if (tid != LLDB_INVALID_THREAD_ID)
2346 m_thread_ids.push_back (tid);
2347 }
Greg Claytona5801ad2015-07-15 22:59:03 +00002348 else if (key.compare("jthreads") == 0)
2349 {
2350 StringExtractor json_extractor;
2351 // Swap "value" over into "name_extractor"
2352 json_extractor.GetStringRef().swap(value);
2353 // Now convert the HEX bytes into a string value
2354 json_extractor.GetHexByteString (value);
2355
2356 // This JSON contains thread IDs and thread stop info for all threads.
2357 // It doesn't contain expedited registers, memory or queue info.
2358 m_threads_info_sp = StructuredData::ParseJSON (value);
2359 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002360 else if (key.compare("hexname") == 0)
Greg Claytonde9d0492011-01-08 03:17:57 +00002361 {
2362 StringExtractor name_extractor;
2363 // Swap "value" over into "name_extractor"
2364 name_extractor.GetStringRef().swap(value);
2365 // Now convert the HEX bytes into a string value
2366 name_extractor.GetHexByteString (value);
2367 thread_name.swap (value);
2368 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002369 else if (key.compare("name") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002370 {
2371 thread_name.swap (value);
2372 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002373 else if (key.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002374 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002375 thread_dispatch_qaddr = StringConvert::ToUInt64 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002376 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002377 else if (key.compare("qname") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002378 {
2379 queue_vars_valid = true;
2380 StringExtractor name_extractor;
2381 // Swap "value" over into "name_extractor"
2382 name_extractor.GetStringRef().swap(value);
2383 // Now convert the HEX bytes into a string value
2384 name_extractor.GetHexByteString (value);
2385 queue_name.swap (value);
2386 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002387 else if (key.compare("qkind") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002388 {
Greg Clayton0b90be12015-06-23 21:27:50 +00002389 if (value == "serial")
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002390 {
2391 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002392 queue_kind = eQueueKindSerial;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002393 }
Greg Clayton0b90be12015-06-23 21:27:50 +00002394 else if (value == "concurrent")
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002395 {
2396 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002397 queue_kind = eQueueKindConcurrent;
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002398 }
Greg Clayton0b90be12015-06-23 21:27:50 +00002399 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002400 else if (key.compare("qserial") == 0)
Greg Clayton0b90be12015-06-23 21:27:50 +00002401 {
Greg Clayton0b90be12015-06-23 21:27:50 +00002402 queue_serial = StringConvert::ToUInt64 (value.c_str(), 0, 0);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002403 if (queue_serial != 0)
2404 queue_vars_valid = true;
Greg Clayton0b90be12015-06-23 21:27:50 +00002405 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002406 else if (key.compare("reason") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002407 {
2408 reason.swap(value);
2409 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002410 else if (key.compare("description") == 0)
Greg Claytona658fd22011-06-04 01:26:29 +00002411 {
2412 StringExtractor desc_extractor;
2413 // Swap "value" over into "name_extractor"
2414 desc_extractor.GetStringRef().swap(value);
2415 // Now convert the HEX bytes into a string value
Chaoren Lin28e57422015-02-03 01:51:25 +00002416 desc_extractor.GetHexByteString (value);
2417 description.swap(value);
Greg Claytona658fd22011-06-04 01:26:29 +00002418 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002419 else if (key.compare("memory") == 0)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002420 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002421 // Expedited memory. GDB servers can choose to send back expedited memory
2422 // that can populate the L1 memory cache in the process so that things like
2423 // the frame pointer backchain can be expedited. This will help stack
2424 // backtracing be more efficient by not having to send as many memory read
2425 // requests down the remote GDB server.
Chaoren Lin7a306082015-06-23 03:17:01 +00002426
Greg Clayton358cf1e2015-06-25 21:46:34 +00002427 // Key/value pair format: memory:<addr>=<bytes>;
2428 // <addr> is a number whose base will be interpreted by the prefix:
2429 // "0x[0-9a-fA-F]+" for hex
2430 // "0[0-7]+" for octal
2431 // "[1-9]+" for decimal
2432 // <bytes> is native endian ASCII hex bytes just like the register values
2433 llvm::StringRef value_ref(value);
2434 std::pair<llvm::StringRef, llvm::StringRef> pair;
2435 pair = value_ref.split('=');
2436 if (!pair.first.empty() && !pair.second.empty())
2437 {
2438 std::string addr_str(pair.first.str());
2439 const lldb::addr_t mem_cache_addr = StringConvert::ToUInt64(addr_str.c_str(), LLDB_INVALID_ADDRESS, 0);
2440 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
Greg Clayton3e06bd92011-01-09 21:07:35 +00002441 {
Greg Clayton358cf1e2015-06-25 21:46:34 +00002442 StringExtractor bytes;
2443 bytes.GetStringRef() = std::move(pair.second.str());
2444 const size_t byte_size = bytes.GetStringRef().size()/2;
2445 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2446 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2447 if (bytes_copied == byte_size)
2448 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
Greg Clayton3e06bd92011-01-09 21:07:35 +00002449 }
2450 }
2451 }
Greg Clayton358cf1e2015-06-25 21:46:34 +00002452 else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1]))
2453 {
2454 uint32_t reg = StringConvert::ToUInt32 (key.c_str(), UINT32_MAX, 16);
2455 if (reg != UINT32_MAX)
2456 expedited_register_map[reg] = std::move(value);
2457 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002458 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002459
Greg Clayton358cf1e2015-06-25 21:46:34 +00002460 ThreadSP thread_sp = SetThreadStopInfo (tid,
2461 expedited_register_map,
2462 signo,
2463 thread_name,
2464 reason,
2465 description,
2466 exc_type,
2467 exc_data,
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002468 thread_dispatch_qaddr,
2469 queue_vars_valid,
2470 queue_name,
2471 queue_kind,
2472 queue_serial);
Greg Clayton358cf1e2015-06-25 21:46:34 +00002473
Hafiz Abid Qadeer673b4a32014-02-20 10:23:20 +00002474 // If the response is old style 'S' packet which does not provide us with thread information
2475 // then update the thread list and choose the first one.
2476 if (!thread_sp)
2477 {
2478 UpdateThreadIDList ();
2479
2480 if (!m_thread_ids.empty ())
2481 {
2482 Mutex::Locker locker (m_thread_list_real.GetMutex ());
2483 thread_sp = m_thread_list_real.FindThreadByProtocolID (m_thread_ids.front (), false);
Hafiz Abid Qadeer673b4a32014-02-20 10:23:20 +00002484 }
2485 }
2486
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002487 return eStateStopped;
2488 }
2489 break;
2490
2491 case 'W':
Todd Fialaff6131a2014-05-19 04:57:23 +00002492 case 'X':
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002493 // process exited
2494 return eStateExited;
2495
2496 default:
2497 break;
2498 }
2499 return eStateInvalid;
2500}
2501
2502void
2503ProcessGDBRemote::RefreshStateAfterStop ()
2504{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002505 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00002506 m_thread_ids.clear();
2507 // Set the thread stop info. It might have a "threads" key whose value is
2508 // a list of all thread IDs in the current process, so m_thread_ids might
2509 // get set.
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002510
2511 // Scope for the lock
2512 {
2513 // Lock the thread stack while we access it
2514 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
2515 // Get the number of stop packets on the stack
2516 int nItems = m_stop_packet_stack.size();
2517 // Iterate over them
2518 for (int i = 0; i < nItems; i++)
2519 {
2520 // Get the thread stop info
2521 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2522 // Process thread stop info
2523 SetThreadStopInfo(stop_info);
2524 }
2525 // Clear the thread stop stack
2526 m_stop_packet_stack.clear();
2527 }
2528
Greg Clayton9e920902012-04-10 02:25:43 +00002529 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2530 if (m_thread_ids.empty())
2531 {
2532 // No, we need to fetch the thread list manually
2533 UpdateThreadIDList();
2534 }
2535
Ewan Crawford78baa192015-05-13 09:18:18 +00002536 // If we have queried for a default thread id
2537 if (m_initial_tid != LLDB_INVALID_THREAD_ID)
2538 {
2539 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2540 m_initial_tid = LLDB_INVALID_THREAD_ID;
2541 }
2542
Greg Clayton358cf1e2015-06-25 21:46:34 +00002543 // Fetch the threads via an efficient packet that gets stop infos for all threads
2544 // only if we have more than one thread
2545 if (m_thread_ids.size() > 1)
2546 m_threads_info_sp = m_gdb_comm.GetThreadsInfo();
2547
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002548 // Let all threads recover from stopping and do any clean up based
2549 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002550 m_thread_list_real.RefreshStateAfterStop();
Greg Clayton9e920902012-04-10 02:25:43 +00002551
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002552}
2553
2554Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002555ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002556{
2557 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002558
Greg Clayton6ed95942011-01-22 07:12:45 +00002559 bool timed_out = false;
2560 Mutex::Locker locker;
Greg Clayton513c26c2011-01-29 07:10:55 +00002561
2562 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002563 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002564 // We are being asked to halt during an attach. We need to just close
2565 // our file handle and debugserver will go away, and we can be done...
2566 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00002567 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002568 else
2569 {
Greg Clayton2687cd12012-03-29 01:55:41 +00002570 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton513c26c2011-01-29 07:10:55 +00002571 {
2572 if (timed_out)
2573 error.SetErrorString("timed out sending interrupt packet");
2574 else
2575 error.SetErrorString("unknown error sending interrupt packet");
2576 }
Greg Clayton2687cd12012-03-29 01:55:41 +00002577
2578 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton513c26c2011-01-29 07:10:55 +00002579 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002580 return error;
2581}
2582
2583Error
Jim Inghamacff8952013-05-02 00:27:30 +00002584ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002585{
2586 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002587 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00002588 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00002589 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2590
Jim Inghamacff8952013-05-02 00:27:30 +00002591 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002592 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002593 {
Jim Inghamacff8952013-05-02 00:27:30 +00002594 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002595 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
2596 else
Jim Inghamacff8952013-05-02 00:27:30 +00002597 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00002598 }
Jim Inghamacff8952013-05-02 00:27:30 +00002599
2600 if (!error.Success())
2601 return error;
2602
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002603 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00002604 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002605
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002606 SetPrivateState (eStateDetached);
2607 ResumePrivateStateThread();
2608
2609 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00002610 return error;
2611}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002612
Jim Ingham43c555d2012-07-04 00:35:43 +00002613
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002614Error
2615ProcessGDBRemote::DoDestroy ()
2616{
2617 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002618 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002619 if (log)
2620 log->Printf ("ProcessGDBRemote::DoDestroy()");
2621
Jim Ingham43c555d2012-07-04 00:35:43 +00002622 // There is a bug in older iOS debugservers where they don't shut down the process
2623 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
2624 // this can cause problems with restarting. So we check to see if any of our threads are stopped
2625 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
2626 // destroy it again.
2627 //
2628 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
2629 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
2630 // the debugservers with this bug are equal. There really should be a better way to test this!
2631 //
2632 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
2633 // get called here to destroy again and we're still at a breakpoint or exception, then we should
2634 // just do the straight-forward kill.
2635 //
2636 // And of course, if we weren't able to stop the process by the time we get here, it isn't
2637 // necessary (or helpful) to do any of this.
2638
2639 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
2640 {
2641 PlatformSP platform_sp = GetTarget().GetPlatform();
2642
2643 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2644 if (platform_sp
2645 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00002646 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00002647 {
2648 if (m_destroy_tried_resuming)
2649 {
2650 if (log)
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002651 log->PutCString ("ProcessGDBRemote::DoDestroy() - Tried resuming to destroy once already, not doing it again.");
Jim Ingham43c555d2012-07-04 00:35:43 +00002652 }
2653 else
2654 {
2655 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
2656 // but we really need it to happen here and it doesn't matter if we do it twice.
2657 m_thread_list.DiscardThreadPlans();
2658 DisableAllBreakpointSites();
2659
2660 bool stop_looks_like_crash = false;
2661 ThreadList &threads = GetThreadList();
2662
2663 {
Jim Ingham45350372012-09-11 00:08:52 +00002664 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002665
2666 size_t num_threads = threads.GetSize();
2667 for (size_t i = 0; i < num_threads; i++)
2668 {
2669 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002670 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002671 StopReason reason = eStopReasonInvalid;
2672 if (stop_info_sp)
2673 reason = stop_info_sp->GetStopReason();
2674 if (reason == eStopReasonBreakpoint
2675 || reason == eStopReasonException)
2676 {
2677 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002678 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
2679 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00002680 stop_info_sp->GetDescription());
2681 stop_looks_like_crash = true;
2682 break;
2683 }
2684 }
2685 }
2686
2687 if (stop_looks_like_crash)
2688 {
2689 if (log)
2690 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
2691 m_destroy_tried_resuming = true;
2692
2693 // If we are going to run again before killing, it would be good to suspend all the threads
2694 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
2695 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
2696 // have to run the risk of letting those threads proceed a bit.
2697
2698 {
Jim Ingham45350372012-09-11 00:08:52 +00002699 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002700
2701 size_t num_threads = threads.GetSize();
2702 for (size_t i = 0; i < num_threads; i++)
2703 {
2704 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002705 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002706 StopReason reason = eStopReasonInvalid;
2707 if (stop_info_sp)
2708 reason = stop_info_sp->GetStopReason();
2709 if (reason != eStopReasonBreakpoint
2710 && reason != eStopReasonException)
2711 {
2712 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002713 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
2714 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00002715 thread_sp->SetResumeState(eStateSuspended);
2716 }
2717 }
2718 }
2719 Resume ();
Jason Molendaede31932015-04-17 05:01:58 +00002720 return Destroy(false);
Jim Ingham43c555d2012-07-04 00:35:43 +00002721 }
2722 }
2723 }
2724 }
2725
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002726 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00002727 int exit_status = SIGABRT;
2728 std::string exit_string;
2729
Greg Clayton6ed95942011-01-22 07:12:45 +00002730 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002731 {
Jim Inghamaab78372011-10-28 01:11:35 +00002732 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00002733 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002734 StringExtractorGDBRemote response;
2735 bool send_async = true;
Tamas Berghammer912800c2015-02-24 10:23:39 +00002736 GDBRemoteCommunication::ScopedTimeout (m_gdb_comm, 3);
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002737
Greg Clayton3dedae12013-12-06 21:45:27 +00002738 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton513c26c2011-01-29 07:10:55 +00002739 {
2740 char packet_cmd = response.GetChar(0);
2741
2742 if (packet_cmd == 'W' || packet_cmd == 'X')
2743 {
Jim Inghameac0aa42014-02-21 22:36:11 +00002744#if defined(__APPLE__)
Jim Ingham9d67cc52014-02-21 22:35:29 +00002745 // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off
2746 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill
2747 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns
2748 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap
2749 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of
2750 // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2751 // Anyway, so call waitpid here to finally reap it.
2752 PlatformSP platform_sp(GetTarget().GetPlatform());
2753 if (platform_sp && platform_sp->IsHost())
2754 {
2755 int status;
2756 ::pid_t reap_pid;
2757 reap_pid = waitpid (GetID(), &status, WNOHANG);
2758 if (log)
2759 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2760 }
2761#endif
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002762 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002763 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00002764 exit_status = response.GetHexU8();
2765 }
2766 else
2767 {
2768 if (log)
2769 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2770 exit_string.assign("got unexpected response to k packet: ");
2771 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00002772 }
2773 }
2774 else
2775 {
Jim Inghambabfc382012-06-06 00:32:39 +00002776 if (log)
2777 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2778 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00002779 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002780 }
Jim Inghambabfc382012-06-06 00:32:39 +00002781 else
2782 {
2783 if (log)
Ed Masteb3a53332014-03-17 17:05:22 +00002784 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching");
Jim Inghamcfc09352012-07-27 23:57:19 +00002785 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00002786 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002787 }
Jim Inghambabfc382012-06-06 00:32:39 +00002788 else
2789 {
2790 // If we missed setting the exit status on the way out, do it here.
2791 // NB set exit status can be called multiple times, the first one sets the status.
2792 exit_string.assign("destroying when not connected to debugserver");
2793 }
2794
2795 SetExitStatus(exit_status, exit_string.c_str());
2796
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002797 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002798 KillDebugserverProcess ();
2799 return error;
2800}
2801
Greg Clayton8cda7f02013-05-21 21:55:59 +00002802void
2803ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2804{
Greg Clayton8cda7f02013-05-21 21:55:59 +00002805 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2806 if (did_exec)
2807 {
2808 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2809 if (log)
2810 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2811
2812 m_thread_list_real.Clear();
2813 m_thread_list.Clear();
2814 BuildDynamicRegisterInfo (true);
Greg Clayton2e59d4f2015-06-29 20:08:51 +00002815 m_gdb_comm.ResetDiscoverableSettings (did_exec);
Greg Clayton8cda7f02013-05-21 21:55:59 +00002816 }
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002817
2818 // Scope the lock
2819 {
2820 // Lock the thread stack while we access it
2821 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
2822 // Add this stop packet to the stop packet stack
2823 // This stack will get popped and examined when we switch to the
2824 // Stopped state
2825 m_stop_packet_stack.push_back(response);
2826 }
Greg Clayton8cda7f02013-05-21 21:55:59 +00002827}
2828
2829
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002830//------------------------------------------------------------------
2831// Process Queries
2832//------------------------------------------------------------------
2833
2834bool
2835ProcessGDBRemote::IsAlive ()
2836{
Greg Clayton10177aa2010-12-08 05:08:21 +00002837 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002838}
2839
2840addr_t
2841ProcessGDBRemote::GetImageInfoAddress()
2842{
Aidan Doddsc0c83852015-05-08 09:36:31 +00002843 // request the link map address via the $qShlibInfoAddr packet
2844 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2845
2846 // the loaded module list can also provides a link map address
2847 if (addr == LLDB_INVALID_ADDRESS)
2848 {
2849 GDBLoadedModuleInfoList list;
2850 if (GetLoadedModuleList (list).Success())
2851 addr = list.m_link_map;
2852 }
2853
2854 return addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002855}
2856
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002857//------------------------------------------------------------------
2858// Process Memory
2859//------------------------------------------------------------------
2860size_t
2861ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2862{
Jason Molenda6076bf42014-05-06 04:34:52 +00002863 GetMaxMemorySize ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002864 if (size > m_max_memory_size)
2865 {
2866 // Keep memory read sizes down to a sane limit. This function will be
2867 // called multiple times in order to complete the task by
2868 // lldb_private::Process so it is ok to do this.
2869 size = m_max_memory_size;
2870 }
2871
2872 char packet[64];
Jason Molenda6076bf42014-05-06 04:34:52 +00002873 int packet_len;
2874 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2875 if (binary_memory_read)
2876 {
2877 packet_len = ::snprintf (packet, sizeof(packet), "x0x%" PRIx64 ",0x%" PRIx64, (uint64_t)addr, (uint64_t)size);
2878 }
2879 else
2880 {
2881 packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
2882 }
Andy Gibbsa297a972013-06-19 19:04:53 +00002883 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002884 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002885 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002886 {
Greg Clayton576d8832011-03-22 04:00:09 +00002887 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002888 {
2889 error.Clear();
Jason Molenda6076bf42014-05-06 04:34:52 +00002890 if (binary_memory_read)
2891 {
2892 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any
2893 // 0x7d character escaping that was present in the packet
2894
2895 size_t data_received_size = response.GetBytesLeft();
2896 if (data_received_size > size)
2897 {
2898 // Don't write past the end of BUF if the remote debug server gave us too
2899 // much data for some reason.
2900 data_received_size = size;
2901 }
2902 memcpy (buf, response.GetStringRef().data(), data_received_size);
2903 return data_received_size;
2904 }
2905 else
2906 {
2907 return response.GetHexBytes(buf, size, '\xdd');
2908 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002909 }
Greg Clayton576d8832011-03-22 04:00:09 +00002910 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002911 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002912 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002913 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002914 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002915 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002916 }
2917 else
2918 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002919 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002920 }
2921 return 0;
2922}
2923
2924size_t
2925ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2926{
Jason Molenda6076bf42014-05-06 04:34:52 +00002927 GetMaxMemorySize ();
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002928 if (size > m_max_memory_size)
2929 {
2930 // Keep memory read sizes down to a sane limit. This function will be
2931 // called multiple times in order to complete the task by
2932 // lldb_private::Process so it is ok to do this.
2933 size = m_max_memory_size;
2934 }
2935
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002936 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00002937 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Clayton7fb56d02011-02-01 01:31:41 +00002938 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002939 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002940 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002941 {
Greg Clayton576d8832011-03-22 04:00:09 +00002942 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002943 {
2944 error.Clear();
2945 return size;
2946 }
Greg Clayton576d8832011-03-22 04:00:09 +00002947 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002948 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002949 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002950 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002951 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002952 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 +00002953 }
2954 else
2955 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002956 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002957 }
2958 return 0;
2959}
2960
2961lldb::addr_t
2962ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2963{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00002964 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_EXPRESSIONS));
Greg Clayton2a48f522011-05-14 01:50:35 +00002965 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2966
Greg Clayton70b57652011-05-15 01:25:55 +00002967 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton2a48f522011-05-14 01:50:35 +00002968 switch (supported)
2969 {
2970 case eLazyBoolCalculate:
2971 case eLazyBoolYes:
2972 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2973 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2974 return allocated_addr;
2975
2976 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002977 // Call mmap() to create memory in the inferior..
2978 unsigned prot = 0;
2979 if (permissions & lldb::ePermissionsReadable)
2980 prot |= eMmapProtRead;
2981 if (permissions & lldb::ePermissionsWritable)
2982 prot |= eMmapProtWrite;
2983 if (permissions & lldb::ePermissionsExecutable)
2984 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00002985
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002986 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2987 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2988 m_addr_to_mmap_size[allocated_addr] = size;
2989 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002990 {
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002991 allocated_addr = LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00002992 if (log)
2993 log->Printf ("ProcessGDBRemote::%s no direct stub support for memory allocation, and InferiorCallMmap also failed - is stub missing register context save/restore capability?", __FUNCTION__);
2994 }
Greg Clayton2a48f522011-05-14 01:50:35 +00002995 break;
2996 }
2997
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002998 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00002999 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003000 else
3001 error.Clear();
3002 return allocated_addr;
3003}
3004
3005Error
Greg Clayton46fb5582011-11-18 07:03:08 +00003006ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
3007 MemoryRegionInfo &region_info)
3008{
3009
3010 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
3011 return error;
3012}
3013
3014Error
Johnny Chen64637202012-05-23 21:09:52 +00003015ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
3016{
3017
3018 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
3019 return error;
3020}
3021
3022Error
Enrico Granataf04a2192012-07-13 23:18:48 +00003023ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
3024{
3025 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
3026 return error;
3027}
3028
3029Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003030ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
3031{
3032 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00003033 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
3034
3035 switch (supported)
3036 {
3037 case eLazyBoolCalculate:
3038 // We should never be deallocating memory without allocating memory
3039 // first so we should never get eLazyBoolCalculate
3040 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
3041 break;
3042
3043 case eLazyBoolYes:
3044 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00003045 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003046 break;
3047
3048 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003049 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00003050 {
3051 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00003052 if (pos != m_addr_to_mmap_size.end() &&
3053 InferiorCallMunmap(this, addr, pos->second))
3054 m_addr_to_mmap_size.erase (pos);
3055 else
Daniel Malead01b2952012-11-29 21:49:15 +00003056 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00003057 }
3058 break;
3059 }
3060
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003061 return error;
3062}
3063
3064
3065//------------------------------------------------------------------
3066// Process STDIO
3067//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003068size_t
3069ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
3070{
3071 if (m_stdio_communication.IsConnected())
3072 {
3073 ConnectionStatus status;
3074 m_stdio_communication.Write(src, src_len, status, NULL);
3075 }
Vince Harrondf3f00f2015-02-10 21:09:04 +00003076 else if (m_stdin_forward)
Vince Harrone0be4252015-02-06 18:32:57 +00003077 {
3078 m_gdb_comm.SendStdinNotification(src, src_len);
3079 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003080 return 0;
3081}
3082
3083Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003084ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003085{
3086 Error error;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003087 assert(bp_site != NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003088
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003089 // Get logging info
3090 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003091 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003092
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003093 // Get the breakpoint address
3094 const addr_t addr = bp_site->GetLoadAddress();
3095
3096 // Log that a breakpoint was requested
3097 if (log)
3098 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
3099
3100 // Breakpoint already exists and is enabled
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003101 if (bp_site->IsEnabled())
3102 {
3103 if (log)
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003104 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 +00003105 return error;
3106 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003107
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003108 // Get the software breakpoint trap opcode size
3109 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3110
3111 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
3112 // is supported by the remote stub. These are set to true by default, and later set to false
3113 // only after we receive an unimplemented response when sending a breakpoint packet. This means
3114 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
3115 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
3116 // indicates if the user specifically asked for hardware breakpoints. If true then we will
3117 // skip over software breakpoints.
3118 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
3119 {
3120 // Try to send off a software breakpoint packet ($Z0)
3121 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003122 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003123 // The breakpoint was placed successfully
3124 bp_site->SetEnabled(true);
3125 bp_site->SetType(BreakpointSite::eExternal);
Greg Claytoneb023e72013-10-11 19:48:25 +00003126 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003127 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003128
3129 // SendGDBStoppointTypePacket() will return an error if it was unable to set this
3130 // breakpoint. We need to differentiate between a error specific to placing this breakpoint
3131 // or if we have learned that this breakpoint type is unsupported. To do this, we
3132 // must test the support boolean for this breakpoint type to see if it now indicates that
3133 // this breakpoint type is unsupported. If they are still supported then we should return
3134 // with the error code. If they are now unsupported, then we would like to fall through
3135 // and try another form of breakpoint.
3136 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
3137 return error;
3138
3139 // We reach here when software breakpoints have been found to be unsupported. For future
3140 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
3141 // known not to be supported.
3142 if (log)
3143 log->Printf("Software breakpoints are unsupported");
3144
3145 // So we will fall through and try a hardware breakpoint
3146 }
3147
3148 // The process of setting a hardware breakpoint is much the same as above. We check the
3149 // supported boolean for this breakpoint type, and if it is thought to be supported then we
3150 // will try to set this breakpoint with a hardware breakpoint.
3151 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3152 {
3153 // Try to send off a hardware breakpoint packet ($Z1)
3154 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003155 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003156 // The breakpoint was placed successfully
3157 bp_site->SetEnabled(true);
3158 bp_site->SetType(BreakpointSite::eHardware);
3159 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003160 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003161
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003162 // Check if the error was something other then an unsupported breakpoint type
3163 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3164 {
3165 // Unable to set this hardware breakpoint
3166 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
3167 return error;
3168 }
3169
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003170 // We will reach here when the stub gives an unsupported response to a hardware breakpoint
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003171 if (log)
3172 log->Printf("Hardware breakpoints are unsupported");
3173
3174 // Finally we will falling through to a #trap style breakpoint
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003175 }
3176
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003177 // Don't fall through when hardware breakpoints were specifically requested
3178 if (bp_site->HardwareRequired())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003179 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003180 error.SetErrorString("hardware breakpoints are not supported");
3181 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003182 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003183
3184 // As a last resort we want to place a manual breakpoint. An instruction
3185 // is placed into the process memory using memory write packets.
3186 return EnableSoftwareBreakpoint(bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003187}
3188
3189Error
Jim Ingham299c0c12013-02-15 02:06:30 +00003190ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003191{
3192 Error error;
3193 assert (bp_site != NULL);
3194 addr_t addr = bp_site->GetLoadAddress();
3195 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00003196 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003197 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003198 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003199
3200 if (bp_site->IsEnabled())
3201 {
3202 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
3203
Greg Clayton8b82f082011-04-12 05:54:46 +00003204 BreakpointSite::Type bp_type = bp_site->GetType();
3205 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003206 {
Greg Clayton8b82f082011-04-12 05:54:46 +00003207 case BreakpointSite::eSoftware:
3208 error = DisableSoftwareBreakpoint (bp_site);
3209 break;
3210
3211 case BreakpointSite::eHardware:
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003212 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003213 error.SetErrorToGenericError();
3214 break;
3215
3216 case BreakpointSite::eExternal:
Jim Inghama04ef752014-03-07 11:18:02 +00003217 {
3218 GDBStoppointType stoppoint_type;
3219 if (bp_site->IsHardware())
3220 stoppoint_type = eBreakpointHardware;
3221 else
3222 stoppoint_type = eBreakpointSoftware;
3223
3224 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00003225 error.SetErrorToGenericError();
Jim Inghama04ef752014-03-07 11:18:02 +00003226 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003227 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003228 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003229 if (error.Success())
3230 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003231 }
3232 else
3233 {
3234 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00003235 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 +00003236 return error;
3237 }
3238
3239 if (error.Success())
3240 error.SetErrorToGenericError();
3241 return error;
3242}
3243
Johnny Chen11309a32011-09-06 22:38:36 +00003244// Pre-requisite: wp != NULL.
3245static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00003246GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00003247{
3248 assert(wp);
3249 bool watch_read = wp->WatchpointRead();
3250 bool watch_write = wp->WatchpointWrite();
3251
3252 // watch_read and watch_write cannot both be false.
3253 assert(watch_read || watch_write);
3254 if (watch_read && watch_write)
3255 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00003256 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00003257 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00003258 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00003259 return eWatchpointWrite;
3260}
3261
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003262Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003263ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003264{
3265 Error error;
3266 if (wp)
3267 {
3268 user_id_t watchID = wp->GetID();
3269 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00003270 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003271 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003272 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003273 if (wp->IsEnabled())
3274 {
3275 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003276 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 +00003277 return error;
3278 }
Johnny Chen11309a32011-09-06 22:38:36 +00003279
3280 GDBStoppointType type = GetGDBStoppointType(wp);
3281 // Pass down an appropriate z/Z packet...
3282 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003283 {
Johnny Chen11309a32011-09-06 22:38:36 +00003284 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
3285 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003286 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003287 return error;
3288 }
3289 else
3290 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003291 }
Johnny Chen11309a32011-09-06 22:38:36 +00003292 else
3293 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003294 }
3295 else
3296 {
Johnny Chen01a67862011-10-14 00:42:25 +00003297 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003298 }
3299 if (error.Success())
3300 error.SetErrorToGenericError();
3301 return error;
3302}
3303
3304Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003305ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003306{
3307 Error error;
3308 if (wp)
3309 {
3310 user_id_t watchID = wp->GetID();
3311
Greg Clayton5160ce52013-03-27 23:08:40 +00003312 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003313
3314 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00003315
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003316 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003317 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003318
Johnny Chen11309a32011-09-06 22:38:36 +00003319 if (!wp->IsEnabled())
3320 {
3321 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003322 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 +00003323 // See also 'class WatchpointSentry' within StopInfo.cpp.
3324 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
3325 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00003326 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003327 return error;
3328 }
3329
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003330 if (wp->IsHardware())
3331 {
Johnny Chen11309a32011-09-06 22:38:36 +00003332 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003333 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00003334 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
3335 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00003336 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00003337 return error;
3338 }
3339 else
3340 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003341 }
3342 // TODO: clear software watchpoints if we implement them
3343 }
3344 else
3345 {
Johnny Chen01a67862011-10-14 00:42:25 +00003346 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003347 }
3348 if (error.Success())
3349 error.SetErrorToGenericError();
3350 return error;
3351}
3352
3353void
3354ProcessGDBRemote::Clear()
3355{
3356 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00003357 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003358 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003359}
3360
3361Error
3362ProcessGDBRemote::DoSignal (int signo)
3363{
3364 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00003365 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003366 if (log)
3367 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
3368
3369 if (!m_gdb_comm.SendAsyncSignal (signo))
3370 error.SetErrorStringWithFormat("failed to send signal %i", signo);
3371 return error;
3372}
3373
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003374Error
Greg Clayton91a9b2472013-12-04 19:19:12 +00003375ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003376{
3377 Error error;
3378 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
3379 {
3380 // If we locate debugserver, keep that located version around
3381 static FileSpec g_debugserver_file_spec;
3382
Han Ming Ong84647042012-02-25 01:07:38 +00003383 ProcessLaunchInfo debugserver_launch_info;
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00003384 // Make debugserver run in its own session so signals generated by
3385 // special terminal key sequences (^C) don't affect debugserver.
3386 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3387
Greg Clayton91a9b2472013-12-04 19:19:12 +00003388 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
3389 debugserver_launch_info.SetUserID(process_info.GetUserID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003390
Todd Fiala013434e2014-07-09 01:29:05 +00003391#if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__) || defined (__aarch64__))
Greg Claytonfda4fab2014-01-10 22:24:11 +00003392 // On iOS, still do a local connection using a random port
Greg Clayton16810922014-02-27 19:38:18 +00003393 const char *hostname = "127.0.0.1";
Greg Claytonfda4fab2014-01-10 22:24:11 +00003394 uint16_t port = get_random_port ();
3395#else
3396 // Set hostname being NULL to do the reverse connect where debugserver
3397 // will bind to port zero and it will communicate back to us the port
3398 // that we will connect to
3399 const char *hostname = NULL;
3400 uint16_t port = 0;
3401#endif
3402
3403 error = m_gdb_comm.StartDebugserverProcess (hostname,
3404 port,
Greg Clayton00fe87b2013-12-05 22:58:22 +00003405 debugserver_launch_info,
3406 port);
Greg Clayton91a9b2472013-12-04 19:19:12 +00003407
3408 if (error.Success ())
3409 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003410 else
Greg Clayton91a9b2472013-12-04 19:19:12 +00003411 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003412
3413 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3414 StartAsyncThread ();
Greg Clayton91a9b2472013-12-04 19:19:12 +00003415
3416 if (error.Fail())
3417 {
3418 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
3419
3420 if (log)
3421 log->Printf("failed to start debugserver process: %s", error.AsCString());
3422 return error;
3423 }
3424
Greg Clayton00fe87b2013-12-05 22:58:22 +00003425 if (m_gdb_comm.IsConnected())
3426 {
3427 // Finish the connection process by doing the handshake without connecting (send NULL URL)
3428 ConnectToDebugserver (NULL);
3429 }
3430 else
3431 {
Greg Claytonfda4fab2014-01-10 22:24:11 +00003432 StreamString connect_url;
3433 connect_url.Printf("connect://%s:%u", hostname, port);
3434 error = ConnectToDebugserver (connect_url.GetString().c_str());
Greg Clayton00fe87b2013-12-05 22:58:22 +00003435 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00003436
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003437 }
3438 return error;
3439}
3440
3441bool
3442ProcessGDBRemote::MonitorDebugserverProcess
3443(
3444 void *callback_baton,
3445 lldb::pid_t debugserver_pid,
Greg Claytone4e45922011-11-16 05:37:56 +00003446 bool exited, // True if the process did exit
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003447 int signo, // Zero for no signal
3448 int exit_status // Exit value of process if signal is zero
3449)
3450{
Greg Claytone4e45922011-11-16 05:37:56 +00003451 // The baton is a "ProcessGDBRemote *". Now this class might be gone
3452 // and might not exist anymore, so we need to carefully try to get the
3453 // target for this process first since we have a race condition when
3454 // we are done running between getting the notice that the inferior
3455 // process has died and the debugserver that was debugging this process.
3456 // In our test suite, we are also continually running process after
3457 // process, so we must be very careful to make sure:
3458 // 1 - process object hasn't been deleted already
3459 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003460
3461 // "debugserver_pid" argument passed in is the process ID for
3462 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00003463 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003464
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003465 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton6779606a2011-01-22 23:43:18 +00003466
Greg Claytone4e45922011-11-16 05:37:56 +00003467 // Get a shared pointer to the target that has a matching process pointer.
3468 // This target could be gone, or the target could already have a new process
3469 // object inside of it
3470 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
3471
Greg Clayton6779606a2011-01-22 23:43:18 +00003472 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003473 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 +00003474
Greg Claytone4e45922011-11-16 05:37:56 +00003475 if (target_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003476 {
Greg Claytone4e45922011-11-16 05:37:56 +00003477 // We found a process in a target that matches, but another thread
3478 // might be in the process of launching a new process that will
3479 // soon replace it, so get a shared pointer to the process so we
3480 // can keep it alive.
3481 ProcessSP process_sp (target_sp->GetProcessSP());
3482 // Now we have a shared pointer to the process that can't go away on us
3483 // so we now make sure it was the same as the one passed in, and also make
3484 // sure that our previous "process *" didn't get deleted and have a new
3485 // "process *" created in its place with the same pointer. To verify this
3486 // we make sure the process has our debugserver process ID. If we pass all
3487 // of these tests, then we are sure that this process is the one we were
3488 // looking for.
3489 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003490 {
Greg Claytone4e45922011-11-16 05:37:56 +00003491 // Sleep for a half a second to make sure our inferior process has
3492 // time to set its exit status before we set it incorrectly when
3493 // both the debugserver and the inferior process shut down.
3494 usleep (500000);
3495 // If our process hasn't yet exited, debugserver might have died.
3496 // If the process did exit, the we are reaping it.
3497 const StateType state = process->GetState();
3498
3499 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
3500 state != eStateInvalid &&
3501 state != eStateUnloaded &&
3502 state != eStateExited &&
3503 state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003504 {
Greg Claytone4e45922011-11-16 05:37:56 +00003505 char error_str[1024];
3506 if (signo)
3507 {
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00003508 const char *signal_cstr = process->GetUnixSignals()->GetSignalAsCString(signo);
Greg Claytone4e45922011-11-16 05:37:56 +00003509 if (signal_cstr)
3510 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3511 else
3512 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
3513 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003514 else
Greg Claytone4e45922011-11-16 05:37:56 +00003515 {
3516 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
3517 }
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003518
Greg Claytone4e45922011-11-16 05:37:56 +00003519 process->SetExitStatus (-1, error_str);
3520 }
3521 // Debugserver has exited we need to let our ProcessGDBRemote
3522 // know that it no longer has a debugserver instance
3523 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003524 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003525 }
3526 return true;
3527}
3528
3529void
3530ProcessGDBRemote::KillDebugserverProcess ()
3531{
Greg Claytonfbb76342013-11-20 21:07:01 +00003532 m_gdb_comm.Disconnect();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003533 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3534 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003535 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003536 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3537 }
3538}
3539
3540void
3541ProcessGDBRemote::Initialize()
3542{
Davide Italianoc8d69822015-04-03 04:24:32 +00003543 static std::once_flag g_once_flag;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003544
Davide Italianoc8d69822015-04-03 04:24:32 +00003545 std::call_once(g_once_flag, []()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003546 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003547 PluginManager::RegisterPlugin (GetPluginNameStatic(),
3548 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00003549 CreateInstance,
3550 DebuggerInitialize);
Davide Italianoc8d69822015-04-03 04:24:32 +00003551 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003552}
3553
Greg Clayton7f982402013-07-15 22:54:20 +00003554void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003555ProcessGDBRemote::DebuggerInitialize (Debugger &debugger)
Greg Clayton7f982402013-07-15 22:54:20 +00003556{
3557 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
3558 {
3559 const bool is_global_setting = true;
3560 PluginManager::CreateSettingForProcessPlugin (debugger,
3561 GetGlobalPluginProperties()->GetValueProperties(),
3562 ConstString ("Properties for the gdb-remote process plug-in."),
3563 is_global_setting);
3564 }
3565}
3566
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003567bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003568ProcessGDBRemote::StartAsyncThread ()
3569{
Greg Clayton5160ce52013-03-27 23:08:40 +00003570 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003571
3572 if (log)
3573 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003574
3575 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003576 if (!m_async_thread.IsJoinable())
Jim Ingham455fa5c2012-11-01 01:15:33 +00003577 {
3578 // Create a thread that watches our internal state and controls which
3579 // events make it to clients (into the DCProcess event queue).
Zachary Turner39de3112014-09-09 20:54:56 +00003580
3581 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003582 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003583 else if (log)
3584 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was already running.", __FUNCTION__);
Zachary Turner39de3112014-09-09 20:54:56 +00003585
Zachary Turneracee96a2014-09-23 18:32:09 +00003586 return m_async_thread.IsJoinable();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003587}
3588
3589void
3590ProcessGDBRemote::StopAsyncThread ()
3591{
Greg Clayton5160ce52013-03-27 23:08:40 +00003592 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003593
3594 if (log)
3595 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
3596
Jim Ingham455fa5c2012-11-01 01:15:33 +00003597 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003598 if (m_async_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003599 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00003600 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
3601
3602 // This will shut down the async thread.
3603 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3604
3605 // Stop the stdio thread
Zachary Turner39de3112014-09-09 20:54:56 +00003606 m_async_thread.Join(nullptr);
Pavel Labatha55a9532015-03-11 09:53:42 +00003607 m_async_thread.Reset();
Jim Ingham455fa5c2012-11-01 01:15:33 +00003608 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003609 else if (log)
3610 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003611}
3612
Ewan Crawford76df2882015-06-23 12:32:06 +00003613bool
3614ProcessGDBRemote::HandleNotifyPacket (StringExtractorGDBRemote &packet)
3615{
3616 // get the packet at a string
3617 const std::string &pkt = packet.GetStringRef();
3618 // skip %stop:
3619 StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
3620
3621 // pass as a thread stop info packet
3622 SetLastStopPacket(stop_info);
3623
3624 // check for more stop reasons
3625 HandleStopReplySequence();
3626
3627 // if the process is stopped then we need to fake a resume
3628 // so that we can stop properly with the new break. This
3629 // is possible due to SetPrivateState() broadcasting the
3630 // state change as a side effect.
3631 if (GetPrivateState() == lldb::StateType::eStateStopped)
3632 {
3633 SetPrivateState(lldb::StateType::eStateRunning);
3634 }
3635
3636 // since we have some stopped packets we can halt the process
3637 SetPrivateState(lldb::StateType::eStateStopped);
3638
3639 return true;
3640}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003641
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003642thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003643ProcessGDBRemote::AsyncThread (void *arg)
3644{
3645 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
3646
Greg Clayton5160ce52013-03-27 23:08:40 +00003647 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003648 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003649 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003650
3651 Listener listener ("ProcessGDBRemote::AsyncThread");
3652 EventSP event_sp;
3653 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
3654 eBroadcastBitAsyncThreadShouldExit;
3655
3656 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
3657 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003658 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit |
3659 GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify);
3660
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003661 bool done = false;
3662 while (!done)
3663 {
3664 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003665 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003666 if (listener.WaitForEvent (NULL, event_sp))
3667 {
3668 const uint32_t event_type = event_sp->GetType();
Greg Clayton71337622011-02-24 22:24:29 +00003669 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003670 {
Greg Clayton71337622011-02-24 22:24:29 +00003671 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003672 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 +00003673
Greg Clayton71337622011-02-24 22:24:29 +00003674 switch (event_type)
3675 {
3676 case eBroadcastBitAsyncContinue:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003677 {
Greg Clayton71337622011-02-24 22:24:29 +00003678 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003679
Greg Clayton71337622011-02-24 22:24:29 +00003680 if (continue_packet)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003681 {
Greg Clayton71337622011-02-24 22:24:29 +00003682 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
3683 const size_t continue_cstr_len = continue_packet->GetByteSize ();
3684 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003685 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003686
Greg Clayton71337622011-02-24 22:24:29 +00003687 if (::strstr (continue_cstr, "vAttach") == NULL)
3688 process->SetPrivateState(eStateRunning);
3689 StringExtractorGDBRemote response;
Ewan Crawford76df2882015-06-23 12:32:06 +00003690
3691 // If in Non-Stop-Mode
3692 if (process->GetTarget().GetNonStopModeEnabled())
Greg Clayton71337622011-02-24 22:24:29 +00003693 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003694 // send the vCont packet
3695 if (!process->GetGDBRemote().SendvContPacket(process, continue_cstr, continue_cstr_len, response))
Jason Molendaa3329782014-03-29 18:54:20 +00003696 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003697 // Something went wrong
3698 done = true;
3699 break;
3700 }
3701 }
3702 // If in All-Stop-Mode
3703 else
3704 {
3705 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
3706
3707 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
3708 // The thread ID list might be contained within the "response", or the stop reply packet that
3709 // caused the stop. So clear it now before we give the stop reply packet to the process
3710 // using the process->SetLastStopPacket()...
3711 process->ClearThreadIDList ();
3712
3713 switch (stop_state)
3714 {
3715 case eStateStopped:
3716 case eStateCrashed:
3717 case eStateSuspended:
3718 process->SetLastStopPacket (response);
3719 process->SetPrivateState (stop_state);
3720 break;
3721
3722 case eStateExited:
3723 {
3724 process->SetLastStopPacket (response);
3725 process->ClearThreadIDList();
3726 response.SetFilePos(1);
3727
3728 int exit_status = response.GetHexU8();
3729 const char *desc_cstr = NULL;
3730 StringExtractor extractor;
3731 std::string desc_string;
3732 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';')
Jason Molendaa3329782014-03-29 18:54:20 +00003733 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003734 std::string desc_token;
3735 while (response.GetNameColonValue (desc_token, desc_string))
Jason Molendaa3329782014-03-29 18:54:20 +00003736 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003737 if (desc_token == "description")
3738 {
3739 extractor.GetStringRef().swap(desc_string);
3740 extractor.SetFilePos(0);
3741 extractor.GetHexByteString (desc_string);
3742 desc_cstr = desc_string.c_str();
3743 }
Jason Molendaa3329782014-03-29 18:54:20 +00003744 }
3745 }
Ewan Crawford76df2882015-06-23 12:32:06 +00003746 process->SetExitStatus(exit_status, desc_cstr);
3747 done = true;
3748 break;
Jason Molendaa3329782014-03-29 18:54:20 +00003749 }
Ewan Crawford76df2882015-06-23 12:32:06 +00003750 case eStateInvalid:
3751 process->SetExitStatus(-1, "lost connection");
3752 break;
Greg Clayton71337622011-02-24 22:24:29 +00003753
Ewan Crawford76df2882015-06-23 12:32:06 +00003754 default:
3755 process->SetPrivateState (stop_state);
3756 break;
3757 } // switch(stop_state)
3758 } // else // if in All-stop-mode
3759 } // if (continue_packet)
3760 } // case eBroadcastBitAysncContinue
Greg Clayton71337622011-02-24 22:24:29 +00003761 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003762
Greg Clayton71337622011-02-24 22:24:29 +00003763 case eBroadcastBitAsyncThreadShouldExit:
3764 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003765 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Clayton71337622011-02-24 22:24:29 +00003766 done = true;
3767 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003768
Greg Clayton71337622011-02-24 22:24:29 +00003769 default:
3770 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003771 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 +00003772 done = true;
3773 break;
3774 }
3775 }
3776 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
3777 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003778 switch (event_type)
Greg Clayton71337622011-02-24 22:24:29 +00003779 {
Ewan Crawford76df2882015-06-23 12:32:06 +00003780 case Communication::eBroadcastBitReadThreadDidExit:
3781 process->SetExitStatus (-1, "lost connection");
3782 done = true;
3783 break;
3784
3785 case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify:
3786 {
3787 lldb_private::Event *event = event_sp.get();
3788 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event);
3789 StringExtractorGDBRemote notify((const char*)continue_packet->GetBytes());
3790 // Hand this over to the process to handle
3791 process->HandleNotifyPacket(notify);
3792 break;
3793 }
3794
3795 default:
3796 if (log)
3797 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
3798 done = true;
3799 break;
Greg Clayton71337622011-02-24 22:24:29 +00003800 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003801 }
3802 }
3803 else
3804 {
3805 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003806 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 +00003807 done = true;
3808 }
3809 }
3810 }
3811
3812 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003813 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003814
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003815 return NULL;
3816}
3817
Greg Claytone996fd32011-03-08 22:40:15 +00003818//uint32_t
3819//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3820//{
3821// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
3822// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
3823// if (m_local_debugserver)
3824// {
3825// return Host::ListProcessesMatchingName (name, matches, pids);
3826// }
3827// else
3828// {
3829// // FIXME: Implement talking to the remote debugserver.
3830// return 0;
3831// }
3832//
3833//}
3834//
Jim Ingham1c823b42011-01-22 01:33:44 +00003835bool
3836ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003837 StoppointCallbackContext *context,
Jim Ingham1c823b42011-01-22 01:33:44 +00003838 lldb::user_id_t break_id,
3839 lldb::user_id_t break_loc_id)
3840{
3841 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3842 // run so I can stop it if that's what I want to do.
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003843 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00003844 if (log)
3845 log->Printf("Hit New Thread Notification breakpoint.");
3846 return false;
3847}
3848
3849
3850bool
3851ProcessGDBRemote::StartNoticingNewThreads()
3852{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003853 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00003854 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003855 {
Greg Clayton4116e932012-05-15 02:33:01 +00003856 if (log && log->GetVerbose())
3857 log->Printf("Enabled noticing new thread breakpoint.");
3858 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003859 }
Greg Clayton4116e932012-05-15 02:33:01 +00003860 else
Jim Ingham1c823b42011-01-22 01:33:44 +00003861 {
Greg Clayton4116e932012-05-15 02:33:01 +00003862 PlatformSP platform_sp (m_target.GetPlatform());
3863 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003864 {
Greg Clayton4116e932012-05-15 02:33:01 +00003865 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3866 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003867 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00003868 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00003869 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3870 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003871 }
3872 else
3873 {
3874 if (log)
3875 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00003876 }
3877 }
3878 }
Greg Clayton4116e932012-05-15 02:33:01 +00003879 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00003880}
3881
3882bool
3883ProcessGDBRemote::StopNoticingNewThreads()
3884{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003885 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00003886 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00003887 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00003888
3889 if (m_thread_create_bp_sp)
3890 m_thread_create_bp_sp->SetEnabled(false);
3891
Jim Ingham1c823b42011-01-22 01:33:44 +00003892 return true;
3893}
3894
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003895DynamicLoader *
Jason Molenda5e8534e2012-10-03 01:29:34 +00003896ProcessGDBRemote::GetDynamicLoader ()
3897{
3898 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00003899 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00003900 return m_dyld_ap.get();
3901}
Jim Ingham1c823b42011-01-22 01:33:44 +00003902
Jason Molendaa3329782014-03-29 18:54:20 +00003903Error
3904ProcessGDBRemote::SendEventData(const char *data)
3905{
3906 int return_value;
3907 bool was_supported;
3908
3909 Error error;
3910
3911 return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported);
3912 if (return_value != 0)
3913 {
3914 if (!was_supported)
3915 error.SetErrorString("Sending events is not supported for this process.");
3916 else
3917 error.SetErrorStringWithFormat("Error sending event data: %d.", return_value);
3918 }
3919 return error;
3920}
3921
Steve Pucci03904ac2014-03-04 23:18:46 +00003922const DataBufferSP
3923ProcessGDBRemote::GetAuxvData()
3924{
3925 DataBufferSP buf;
3926 if (m_gdb_comm.GetQXferAuxvReadSupported())
3927 {
3928 std::string response_string;
3929 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success)
3930 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length()));
3931 }
3932 return buf;
3933}
3934
Jason Molenda705b1802014-06-13 02:37:02 +00003935StructuredData::ObjectSP
3936ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid)
3937{
3938 StructuredData::ObjectSP object_sp;
3939
3940 if (m_gdb_comm.GetThreadExtendedInfoSupported())
3941 {
3942 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3943 SystemRuntime *runtime = GetSystemRuntime();
3944 if (runtime)
3945 {
3946 runtime->AddThreadExtendedInfoPacketHints (args_dict);
3947 }
3948 args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid);
3949
3950 StreamString packet;
3951 packet << "jThreadExtendedInfo:";
3952 args_dict->Dump (packet);
3953
3954 // FIXME the final character of a JSON dictionary, '}', is the escape
3955 // character in gdb-remote binary mode. lldb currently doesn't escape
3956 // these characters in its packet output -- so we add the quoted version
3957 // of the } character here manually in case we talk to a debugserver which
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003958 // un-escapes the characters at packet read time.
Jason Molenda705b1802014-06-13 02:37:02 +00003959 packet << (char) (0x7d ^ 0x20);
3960
3961 StringExtractorGDBRemote response;
3962 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
3963 {
3964 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
3965 if (response_type == StringExtractorGDBRemote::eResponse)
3966 {
3967 if (!response.Empty())
3968 {
Jason Molenda20ee21b2015-07-10 23:15:22 +00003969 object_sp = StructuredData::ParseJSON (response.GetStringRef());
3970 }
3971 }
3972 }
3973 }
3974 return object_sp;
3975}
3976
3977StructuredData::ObjectSP
3978ProcessGDBRemote::GetLoadedDynamicLibrariesInfos (lldb::addr_t image_list_address, lldb::addr_t image_count)
3979{
3980 StructuredData::ObjectSP object_sp;
3981
3982 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported())
3983 {
3984 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3985 args_dict->GetAsDictionary()->AddIntegerItem ("image_list_address", image_list_address);
3986 args_dict->GetAsDictionary()->AddIntegerItem ("image_count", image_count);
3987
3988 StreamString packet;
3989 packet << "jGetLoadedDynamicLibrariesInfos:";
3990 args_dict->Dump (packet);
3991
3992 // FIXME the final character of a JSON dictionary, '}', is the escape
3993 // character in gdb-remote binary mode. lldb currently doesn't escape
3994 // these characters in its packet output -- so we add the quoted version
3995 // of the } character here manually in case we talk to a debugserver which
3996 // un-escapes the characters at packet read time.
3997 packet << (char) (0x7d ^ 0x20);
3998
3999 StringExtractorGDBRemote response;
4000 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4001 {
4002 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4003 if (response_type == StringExtractorGDBRemote::eResponse)
4004 {
4005 if (!response.Empty())
4006 {
Jason Molenda705b1802014-06-13 02:37:02 +00004007 // The packet has already had the 0x7d xor quoting stripped out at the
4008 // GDBRemoteCommunication packet receive level.
4009 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4010 }
4011 }
4012 }
4013 }
4014 return object_sp;
4015}
4016
Jason Molenda20ee21b2015-07-10 23:15:22 +00004017
Jason Molenda6076bf42014-05-06 04:34:52 +00004018// Establish the largest memory read/write payloads we should use.
4019// If the remote stub has a max packet size, stay under that size.
4020//
4021// If the remote stub's max packet size is crazy large, use a
4022// reasonable largeish default.
4023//
4024// If the remote stub doesn't advertise a max packet size, use a
4025// conservative default.
4026
4027void
4028ProcessGDBRemote::GetMaxMemorySize()
4029{
4030 const uint64_t reasonable_largeish_default = 128 * 1024;
4031 const uint64_t conservative_default = 512;
4032
4033 if (m_max_memory_size == 0)
4034 {
4035 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4036 if (stub_max_size != UINT64_MAX && stub_max_size != 0)
4037 {
4038 // Save the stub's claimed maximum packet size
4039 m_remote_stub_max_memory_size = stub_max_size;
4040
4041 // Even if the stub says it can support ginormous packets,
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004042 // don't exceed our reasonable largeish default packet size.
Jason Molenda6076bf42014-05-06 04:34:52 +00004043 if (stub_max_size > reasonable_largeish_default)
4044 {
4045 stub_max_size = reasonable_largeish_default;
4046 }
4047
4048 m_max_memory_size = stub_max_size;
4049 }
4050 else
4051 {
4052 m_max_memory_size = conservative_default;
4053 }
4054 }
4055}
4056
4057void
4058ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max)
4059{
4060 if (user_specified_max != 0)
4061 {
4062 GetMaxMemorySize ();
4063
4064 if (m_remote_stub_max_memory_size != 0)
4065 {
4066 if (m_remote_stub_max_memory_size < user_specified_max)
4067 {
4068 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a packet size too big, go as big
4069 // as the remote stub says we can go.
4070 }
4071 else
4072 {
4073 m_max_memory_size = user_specified_max; // user's packet size is good
4074 }
4075 }
4076 else
4077 {
4078 m_max_memory_size = user_specified_max; // user's packet size is probably fine
4079 }
4080 }
4081}
4082
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004083bool
4084ProcessGDBRemote::GetModuleSpec(const FileSpec& module_file_spec,
4085 const ArchSpec& arch,
4086 ModuleSpec &module_spec)
4087{
4088 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PLATFORM);
4089
4090 if (!m_gdb_comm.GetModuleInfo (module_file_spec, arch, module_spec))
4091 {
4092 if (log)
4093 log->Printf ("ProcessGDBRemote::%s - failed to get module info for %s:%s",
4094 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4095 arch.GetTriple ().getTriple ().c_str ());
4096 return false;
4097 }
4098
4099 if (log)
4100 {
4101 StreamString stream;
4102 module_spec.Dump (stream);
4103 log->Printf ("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4104 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4105 arch.GetTriple ().getTriple ().c_str (), stream.GetString ().c_str ());
4106 }
4107
4108 return true;
4109}
4110
Colin Rileyc3c95b22015-04-16 15:51:33 +00004111namespace {
4112
4113typedef std::vector<std::string> stringVec;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004114
4115typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004116struct RegisterSetInfo
4117{
4118 ConstString name;
4119};
Colin Rileyc3c95b22015-04-16 15:51:33 +00004120
Greg Claytond04f0ed2015-05-26 18:00:51 +00004121typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4122
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004123struct GdbServerTargetInfo
4124{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004125 std::string arch;
4126 std::string osabi;
4127 stringVec includes;
4128 RegisterSetMap reg_set_map;
4129 XMLNode feature_node;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004130};
Greg Claytond04f0ed2015-05-26 18:00:51 +00004131
Colin Rileyc3c95b22015-04-16 15:51:33 +00004132bool
Greg Claytond04f0ed2015-05-26 18:00:51 +00004133ParseRegisters (XMLNode feature_node, GdbServerTargetInfo &target_info, GDBRemoteDynamicRegisterInfo &dyn_reg_info)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004134{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004135 if (!feature_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004136 return false;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004137
4138 uint32_t prev_reg_num = 0;
4139 uint32_t reg_offset = 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004140
Greg Claytond04f0ed2015-05-26 18:00:51 +00004141 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 +00004142 std::string gdb_group;
4143 std::string gdb_type;
4144 ConstString reg_name;
4145 ConstString alt_name;
4146 ConstString set_name;
4147 std::vector<uint32_t> value_regs;
4148 std::vector<uint32_t> invalidate_regs;
4149 bool encoding_set = false;
4150 bool format_set = false;
4151 RegisterInfo reg_info = { NULL, // Name
4152 NULL, // Alt name
4153 0, // byte size
4154 reg_offset, // offset
4155 eEncodingUint, // encoding
4156 eFormatHex, // formate
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004157 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004158 LLDB_INVALID_REGNUM, // GCC reg num
4159 LLDB_INVALID_REGNUM, // DWARF reg num
4160 LLDB_INVALID_REGNUM, // generic reg num
4161 prev_reg_num, // GDB reg num
4162 prev_reg_num // native register number
4163 },
4164 NULL,
4165 NULL
4166 };
4167
Ewan Crawford682e8422015-06-26 09:38:27 +00004168 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 +00004169 if (name == "name")
4170 {
4171 reg_name.SetString(value);
4172 }
4173 else if (name == "bitsize")
4174 {
4175 reg_info.byte_size = StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
4176 }
4177 else if (name == "type")
4178 {
4179 gdb_type = value.str();
4180 }
4181 else if (name == "group")
4182 {
4183 gdb_group = value.str();
4184 }
4185 else if (name == "regnum")
4186 {
4187 const uint32_t regnum = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4188 if (regnum != LLDB_INVALID_REGNUM)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004189 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004190 reg_info.kinds[eRegisterKindGDB] = regnum;
4191 reg_info.kinds[eRegisterKindLLDB] = regnum;
4192 prev_reg_num = regnum;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004193 }
4194 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004195 else if (name == "offset")
4196 {
4197 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4198 }
4199 else if (name == "altname")
4200 {
4201 alt_name.SetString(value);
4202 }
4203 else if (name == "encoding")
4204 {
4205 encoding_set = true;
4206 reg_info.encoding = Args::StringToEncoding (value.data(), eEncodingUint);
4207 }
4208 else if (name == "format")
4209 {
4210 format_set = true;
4211 Format format = eFormatInvalid;
4212 if (Args::StringToFormat (value.data(), format, NULL).Success())
4213 reg_info.format = format;
4214 else if (value == "vector-sint8")
4215 reg_info.format = eFormatVectorOfSInt8;
4216 else if (value == "vector-uint8")
4217 reg_info.format = eFormatVectorOfUInt8;
4218 else if (value == "vector-sint16")
4219 reg_info.format = eFormatVectorOfSInt16;
4220 else if (value == "vector-uint16")
4221 reg_info.format = eFormatVectorOfUInt16;
4222 else if (value == "vector-sint32")
4223 reg_info.format = eFormatVectorOfSInt32;
4224 else if (value == "vector-uint32")
4225 reg_info.format = eFormatVectorOfUInt32;
4226 else if (value == "vector-float32")
4227 reg_info.format = eFormatVectorOfFloat32;
4228 else if (value == "vector-uint128")
4229 reg_info.format = eFormatVectorOfUInt128;
4230 }
4231 else if (name == "group_id")
4232 {
4233 const uint32_t set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4234 RegisterSetMap::const_iterator pos = target_info.reg_set_map.find(set_id);
4235 if (pos != target_info.reg_set_map.end())
4236 set_name = pos->second.name;
4237 }
4238 else if (name == "gcc_regnum")
4239 {
4240 reg_info.kinds[eRegisterKindGCC] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4241 }
4242 else if (name == "dwarf_regnum")
4243 {
4244 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4245 }
4246 else if (name == "generic")
4247 {
4248 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister(value.data());
4249 }
4250 else if (name == "value_regnums")
4251 {
4252 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
4253 }
4254 else if (name == "invalidate_regnums")
4255 {
4256 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
4257 }
4258 else
4259 {
4260 printf("unhandled attribute %s = %s\n", name.data(), value.data());
4261 }
4262 return true; // Keep iterating through all attributes
4263 });
4264
4265 if (!gdb_type.empty() && !(encoding_set || format_set))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004266 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004267 if (gdb_type.find("int") == 0)
4268 {
4269 reg_info.format = eFormatHex;
4270 reg_info.encoding = eEncodingUint;
4271 }
4272 else if (gdb_type == "data_ptr" || gdb_type == "code_ptr")
4273 {
4274 reg_info.format = eFormatAddressInfo;
4275 reg_info.encoding = eEncodingUint;
4276 }
4277 else if (gdb_type == "i387_ext" || gdb_type == "float")
4278 {
4279 reg_info.format = eFormatFloat;
4280 reg_info.encoding = eEncodingIEEE754;
4281 }
Colin Rileyc3c95b22015-04-16 15:51:33 +00004282 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004283
4284 // Only update the register set name if we didn't get a "reg_set" attribute.
4285 // "set_name" will be empty if we didn't have a "reg_set" attribute.
4286 if (!set_name && !gdb_group.empty())
4287 set_name.SetCString(gdb_group.c_str());
4288
4289 reg_info.byte_offset = reg_offset;
4290 assert (reg_info.byte_size != 0);
4291 reg_offset += reg_info.byte_size;
4292 if (!value_regs.empty())
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004293 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004294 value_regs.push_back(LLDB_INVALID_REGNUM);
4295 reg_info.value_regs = value_regs.data();
Colin Rileyc3c95b22015-04-16 15:51:33 +00004296 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004297 if (!invalidate_regs.empty())
4298 {
4299 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
4300 reg_info.invalidate_regs = invalidate_regs.data();
4301 }
4302
Ewan Crawford682e8422015-06-26 09:38:27 +00004303 ++prev_reg_num;
Greg Claytond04f0ed2015-05-26 18:00:51 +00004304 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
4305
4306 return true; // Keep iterating through all "reg" elements
4307 });
Colin Rileyc3c95b22015-04-16 15:51:33 +00004308 return true;
4309}
Greg Claytond04f0ed2015-05-26 18:00:51 +00004310
Colin Rileyc3c95b22015-04-16 15:51:33 +00004311} // namespace {}
4312
Colin Rileyc3c95b22015-04-16 15:51:33 +00004313
4314// query the target of gdb-remote for extended target information
4315// return: 'true' on success
4316// 'false' on failure
4317bool
Aidan Doddsc0c83852015-05-08 09:36:31 +00004318ProcessGDBRemote::GetGDBServerRegisterInfo ()
Colin Rileyc3c95b22015-04-16 15:51:33 +00004319{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004320 // Make sure LLDB has an XML parser it can use first
4321 if (!XMLDocument::XMLEnabled())
4322 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004323
4324 // redirect libxml2's error handler since the default prints to stdout
Colin Rileyc3c95b22015-04-16 15:51:33 +00004325
4326 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004327
4328 // check that we have extended feature read support
4329 if ( !comm.GetQXferFeaturesReadSupported( ) )
4330 return false;
4331
4332 // request the target xml file
4333 std::string raw;
4334 lldb_private::Error lldberr;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004335 if (!comm.ReadExtFeature(ConstString("features"),
4336 ConstString("target.xml"),
4337 raw,
4338 lldberr))
4339 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00004340 return false;
4341 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004342
Colin Rileyc3c95b22015-04-16 15:51:33 +00004343
Greg Claytond04f0ed2015-05-26 18:00:51 +00004344 XMLDocument xml_document;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004345
Greg Claytond04f0ed2015-05-26 18:00:51 +00004346 if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml"))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004347 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004348 GdbServerTargetInfo target_info;
4349
4350 XMLNode target_node = xml_document.GetRootElement("target");
4351 if (target_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00004352 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004353 XMLNode feature_node;
4354 target_node.ForEachChildElement([&target_info, this, &feature_node](const XMLNode &node) -> bool
4355 {
4356 llvm::StringRef name = node.GetName();
4357 if (name == "architecture")
4358 {
4359 node.GetElementText(target_info.arch);
4360 }
4361 else if (name == "osabi")
4362 {
4363 node.GetElementText(target_info.osabi);
4364 }
Ewan Crawford682e8422015-06-26 09:38:27 +00004365 else if (name == "xi:include" || name == "include")
Greg Claytond04f0ed2015-05-26 18:00:51 +00004366 {
4367 llvm::StringRef href = node.GetAttributeValue("href");
4368 if (!href.empty())
4369 target_info.includes.push_back(href.str());
4370 }
4371 else if (name == "feature")
4372 {
4373 feature_node = node;
4374 }
4375 else if (name == "groups")
4376 {
4377 node.ForEachChildElementWithName("group", [&target_info](const XMLNode &node) -> bool {
4378 uint32_t set_id = UINT32_MAX;
4379 RegisterSetInfo set_info;
4380
4381 node.ForEachAttribute([&set_id, &set_info](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
4382 if (name == "id")
4383 set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4384 if (name == "name")
4385 set_info.name = ConstString(value);
4386 return true; // Keep iterating through all attributes
4387 });
4388
4389 if (set_id != UINT32_MAX)
4390 target_info.reg_set_map[set_id] = set_info;
4391 return true; // Keep iterating through all "group" elements
4392 });
4393 }
4394 return true; // Keep iterating through all children of the target_node
4395 });
4396
4397 if (feature_node)
4398 {
4399 ParseRegisters(feature_node, target_info, this->m_register_info);
4400 }
4401
4402 for (const auto &include : target_info.includes)
4403 {
4404 // request register file
4405 std::string xml_data;
4406 if (!comm.ReadExtFeature(ConstString("features"),
4407 ConstString(include),
4408 xml_data,
4409 lldberr))
4410 continue;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004411
Greg Claytond04f0ed2015-05-26 18:00:51 +00004412 XMLDocument include_xml_document;
4413 include_xml_document.ParseMemory(xml_data.data(), xml_data.size(), include.c_str());
4414 XMLNode include_feature_node = include_xml_document.GetRootElement("feature");
4415 if (include_feature_node)
4416 {
4417 ParseRegisters(include_feature_node, target_info, this->m_register_info);
4418 }
4419 }
4420 this->m_register_info.Finalize(GetTarget().GetArchitecture());
Colin Rileyc3c95b22015-04-16 15:51:33 +00004421 }
4422 }
4423
Greg Claytond04f0ed2015-05-26 18:00:51 +00004424 return m_register_info.GetNumRegisters() > 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004425}
4426
Aidan Doddsc0c83852015-05-08 09:36:31 +00004427Error
4428ProcessGDBRemote::GetLoadedModuleList (GDBLoadedModuleInfoList & list)
4429{
Greg Claytond04f0ed2015-05-26 18:00:51 +00004430 // Make sure LLDB has an XML parser it can use first
4431 if (!XMLDocument::XMLEnabled())
4432 return Error (0, ErrorType::eErrorTypeGeneric);
4433
Aidan Doddsc0c83852015-05-08 09:36:31 +00004434 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS);
4435 if (log)
4436 log->Printf ("ProcessGDBRemote::%s", __FUNCTION__);
4437
Aidan Doddsc0c83852015-05-08 09:36:31 +00004438 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004439
4440 // check that we have extended feature read support
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004441 if (comm.GetQXferLibrariesSVR4ReadSupported ()) {
4442 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004443
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004444 // request the loaded library list
4445 std::string raw;
4446 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004447
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004448 if (!comm.ReadExtFeature (ConstString ("libraries-svr4"), ConstString (""), raw, lldberr))
4449 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004450
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004451 // parse the xml file in memory
4452 if (log)
4453 log->Printf ("parsing: %s", raw.c_str());
4454 XMLDocument doc;
4455
4456 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4457 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004458
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004459 XMLNode root_element = doc.GetRootElement("library-list-svr4");
4460 if (!root_element)
4461 return Error();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004462
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004463 // main link map structure
4464 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4465 if (!main_lm.empty())
4466 {
4467 list.m_link_map = StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
4468 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004469
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004470 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
Aidan Doddsc0c83852015-05-08 09:36:31 +00004471
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004472 GDBLoadedModuleInfoList::LoadedModuleInfo module;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004473
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004474 library.ForEachAttribute([log, &module](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004475
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004476 if (name == "name")
4477 module.set_name (value.str());
4478 else if (name == "lm")
4479 {
4480 // the address of the link_map struct.
4481 module.set_link_map(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4482 }
4483 else if (name == "l_addr")
4484 {
4485 // the displacement as read from the field 'l_addr' of the link_map struct.
4486 module.set_base(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4487
4488 }
4489 else if (name == "l_ld")
4490 {
4491 // the memory address of the libraries PT_DYAMIC section.
4492 module.set_dynamic(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4493 }
4494
4495 return true; // Keep iterating over all properties of "library"
4496 });
4497
4498 if (log)
Aidan Doddsc0c83852015-05-08 09:36:31 +00004499 {
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004500 std::string name;
4501 lldb::addr_t lm=0, base=0, ld=0;
4502
4503 module.get_name (name);
4504 module.get_link_map (lm);
4505 module.get_base (base);
4506 module.get_dynamic (ld);
4507
4508 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 +00004509 }
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004510
4511 list.add (module);
4512 return true; // Keep iterating over all "library" elements in the root node
Greg Claytond04f0ed2015-05-26 18:00:51 +00004513 });
Aidan Doddsc0c83852015-05-08 09:36:31 +00004514
4515 if (log)
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004516 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4517 } else if (comm.GetQXferLibrariesReadSupported ()) {
4518 list.clear ();
Aidan Doddsc0c83852015-05-08 09:36:31 +00004519
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004520 // request the loaded library list
4521 std::string raw;
4522 lldb_private::Error lldberr;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004523
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004524 if (!comm.ReadExtFeature (ConstString ("libraries"), ConstString (""), raw, lldberr))
4525 return Error (0, ErrorType::eErrorTypeGeneric);
Aidan Doddsc0c83852015-05-08 09:36:31 +00004526
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004527 if (log)
4528 log->Printf ("parsing: %s", raw.c_str());
4529 XMLDocument doc;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004530
Stephane Sezer9a7cacb2015-07-08 19:14:03 +00004531 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4532 return Error (0, ErrorType::eErrorTypeGeneric);
4533
4534 XMLNode root_element = doc.GetRootElement("library-list");
4535 if (!root_element)
4536 return Error();
4537
4538 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
4539 GDBLoadedModuleInfoList::LoadedModuleInfo module;
4540
4541 llvm::StringRef name = library.GetAttributeValue("name");
4542 module.set_name(name.str());
4543
4544 // The base address of a given library will be the address of its
4545 // first section. Most remotes send only one section for Windows
4546 // targets for example.
4547 const XMLNode &section = library.FindFirstChildElementWithName("section");
4548 llvm::StringRef address = section.GetAttributeValue("address");
4549 module.set_base(StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0));
4550
4551 if (log)
4552 {
4553 std::string name;
4554 lldb::addr_t base = 0;
4555 module.get_name (name);
4556 module.get_base (base);
4557
4558 log->Printf ("found (base:0x%" PRIx64 ", name:'%s')", base, name.c_str());
4559 }
4560
4561 list.add (module);
4562 return true; // Keep iterating over all "library" elements in the root node
4563 });
4564
4565 if (log)
4566 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4567 } else {
4568 return Error (0, ErrorType::eErrorTypeGeneric);
4569 }
Aidan Doddsc0c83852015-05-08 09:36:31 +00004570
4571 return Error();
4572}
4573
Aidan Doddsc0c83852015-05-08 09:36:31 +00004574lldb::ModuleSP
4575ProcessGDBRemote::LoadModuleAtAddress (const FileSpec &file, lldb::addr_t base_addr)
4576{
4577 Target &target = m_process->GetTarget();
4578 ModuleList &modules = target.GetImages();
4579 ModuleSP module_sp;
4580
4581 bool changed = false;
4582
4583 ModuleSpec module_spec (file, target.GetArchitecture());
4584 if ((module_sp = modules.FindFirstModule (module_spec)))
4585 {
4586 module_sp->SetLoadAddress (target, base_addr, true, changed);
4587 }
4588 else if ((module_sp = target.GetSharedModule (module_spec)))
4589 {
4590 module_sp->SetLoadAddress (target, base_addr, true, changed);
4591 }
4592
4593 return module_sp;
4594}
4595
4596size_t
4597ProcessGDBRemote::LoadModules ()
4598{
4599 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4600
4601 // request a list of loaded libraries from GDBServer
4602 GDBLoadedModuleInfoList module_list;
4603 if (GetLoadedModuleList (module_list).Fail())
4604 return 0;
4605
4606 // get a list of all the modules
4607 ModuleList new_modules;
4608
4609 for (GDBLoadedModuleInfoList::LoadedModuleInfo & modInfo : module_list.m_list)
4610 {
4611 std::string mod_name;
4612 lldb::addr_t mod_base;
4613
4614 bool valid = true;
4615 valid &= modInfo.get_name (mod_name);
4616 valid &= modInfo.get_base (mod_base);
4617 if (!valid)
4618 continue;
4619
4620 // hack (cleaner way to get file name only?) (win/unix compat?)
Vince Harron4cc8d202015-05-10 08:33:58 +00004621 size_t marker = mod_name.rfind ('/');
Aidan Doddsc0c83852015-05-08 09:36:31 +00004622 if (marker == std::string::npos)
4623 marker = 0;
4624 else
4625 marker += 1;
4626
4627 FileSpec file (mod_name.c_str()+marker, true);
4628 lldb::ModuleSP module_sp = LoadModuleAtAddress (file, mod_base);
4629
4630 if (module_sp.get())
4631 new_modules.Append (module_sp);
4632 }
4633
4634 if (new_modules.GetSize() > 0)
4635 {
4636 Target & target = m_target;
4637
4638 new_modules.ForEach ([&target](const lldb::ModuleSP module_sp) -> bool
4639 {
4640 lldb_private::ObjectFile * obj = module_sp->GetObjectFile ();
4641 if (!obj)
4642 return true;
4643
4644 if (obj->GetType () != ObjectFile::Type::eTypeExecutable)
4645 return true;
4646
4647 lldb::ModuleSP module_copy_sp = module_sp;
4648 target.SetExecutableModule (module_copy_sp, false);
4649 return false;
4650 });
4651
4652 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4653 loaded_modules.AppendIfNeeded (new_modules);
4654 m_process->GetTarget().ModulesDidLoad (new_modules);
4655 }
4656
4657 return new_modules.GetSize();
4658}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004659
Tamas Berghammer783bfc82015-06-18 20:43:56 +00004660Error
4661ProcessGDBRemote::GetFileLoadAddress(const FileSpec& file, bool& is_loaded, lldb::addr_t& load_addr)
4662{
4663 is_loaded = false;
4664 load_addr = LLDB_INVALID_ADDRESS;
4665
4666 std::string file_path = file.GetPath(false);
4667 if (file_path.empty ())
4668 return Error("Empty file name specified");
4669
4670 StreamString packet;
4671 packet.PutCString("qFileLoadAddress:");
4672 packet.PutCStringAsRawHex8(file_path.c_str());
4673
4674 StringExtractorGDBRemote response;
4675 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString().c_str(), response, false) != GDBRemoteCommunication::PacketResult::Success)
4676 return Error("Sending qFileLoadAddress packet failed");
4677
4678 if (response.IsErrorResponse())
4679 {
4680 if (response.GetError() == 1)
4681 {
4682 // The file is not loaded into the inferior
4683 is_loaded = false;
4684 load_addr = LLDB_INVALID_ADDRESS;
4685 return Error();
4686 }
4687
4688 return Error("Fetching file load address from remote server returned an error");
4689 }
4690
4691 if (response.IsNormalResponse())
4692 {
4693 is_loaded = true;
4694 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
4695 return Error();
4696 }
4697
4698 return Error("Unknown error happened during sending the load address packet");
4699}
4700
Greg Clayton0b90be12015-06-23 21:27:50 +00004701
4702void
4703ProcessGDBRemote::ModulesDidLoad (ModuleList &module_list)
4704{
4705 // We must call the lldb_private::Process::ModulesDidLoad () first before we do anything
4706 Process::ModulesDidLoad (module_list);
4707
4708 // After loading shared libraries, we can ask our remote GDB server if
4709 // it needs any symbols.
4710 m_gdb_comm.ServeSymbolLookups(this);
4711}
4712
4713
Greg Claytone034a042015-05-21 20:52:06 +00004714class CommandObjectProcessGDBRemoteSpeedTest: public CommandObjectParsed
4715{
4716public:
4717 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter) :
4718 CommandObjectParsed (interpreter,
4719 "process plugin packet speed-test",
4720 "Tests packet speeds of various sizes to determine the performance characteristics of the GDB remote connection. ",
4721 NULL),
4722 m_option_group (interpreter),
4723 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),
4724 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),
4725 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),
4726 m_json (LLDB_OPT_SET_1, false, "json", 'j', "Print the output as JSON data for easy parsing.", false, true)
4727 {
4728 m_option_group.Append (&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4729 m_option_group.Append (&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4730 m_option_group.Append (&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4731 m_option_group.Append (&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4732 m_option_group.Finalize();
4733 }
4734
4735 ~CommandObjectProcessGDBRemoteSpeedTest ()
4736 {
4737 }
4738
4739
4740 Options *
4741 GetOptions () override
4742 {
4743 return &m_option_group;
4744 }
4745
4746 bool
4747 DoExecute (Args& command, CommandReturnObject &result) override
4748 {
4749 const size_t argc = command.GetArgumentCount();
4750 if (argc == 0)
4751 {
4752 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4753 if (process)
4754 {
4755 StreamSP output_stream_sp (m_interpreter.GetDebugger().GetAsyncOutputStream());
4756 result.SetImmediateOutputStream (output_stream_sp);
4757
4758 const uint32_t num_packets = (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
4759 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
4760 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
4761 const bool json = m_json.GetOptionValue().GetCurrentValue();
4762 if (output_stream_sp)
4763 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, *output_stream_sp);
4764 else
4765 {
4766 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, result.GetOutputStream());
4767 }
4768 result.SetStatus (eReturnStatusSuccessFinishResult);
4769 return true;
4770 }
4771 }
4772 else
4773 {
4774 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
4775 }
4776 result.SetStatus (eReturnStatusFailed);
4777 return false;
4778 }
4779protected:
4780 OptionGroupOptions m_option_group;
4781 OptionGroupUInt64 m_num_packets;
4782 OptionGroupUInt64 m_max_send;
4783 OptionGroupUInt64 m_max_recv;
4784 OptionGroupBoolean m_json;
4785
4786};
4787
Greg Clayton02686b82012-10-15 22:42:16 +00004788class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00004789{
4790private:
4791
4792public:
Greg Clayton02686b82012-10-15 22:42:16 +00004793 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00004794 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00004795 "process plugin packet history",
4796 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00004797 NULL)
4798 {
4799 }
4800
Greg Clayton02686b82012-10-15 22:42:16 +00004801 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton998255b2012-10-13 02:07:45 +00004802 {
4803 }
4804
4805 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004806 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton998255b2012-10-13 02:07:45 +00004807 {
Greg Clayton02686b82012-10-15 22:42:16 +00004808 const size_t argc = command.GetArgumentCount();
4809 if (argc == 0)
4810 {
4811 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4812 if (process)
4813 {
4814 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
4815 result.SetStatus (eReturnStatusSuccessFinishResult);
4816 return true;
4817 }
4818 }
4819 else
4820 {
4821 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
4822 }
4823 result.SetStatus (eReturnStatusFailed);
4824 return false;
4825 }
4826};
4827
Jason Molenda6076bf42014-05-06 04:34:52 +00004828class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed
4829{
4830private:
4831
4832public:
4833 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) :
4834 CommandObjectParsed (interpreter,
4835 "process plugin packet xfer-size",
4836 "Maximum size that lldb will try to read/write one one chunk.",
4837 NULL)
4838 {
4839 }
4840
4841 ~CommandObjectProcessGDBRemotePacketXferSize ()
4842 {
4843 }
4844
4845 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004846 DoExecute (Args& command, CommandReturnObject &result) override
Jason Molenda6076bf42014-05-06 04:34:52 +00004847 {
4848 const size_t argc = command.GetArgumentCount();
4849 if (argc == 0)
4850 {
4851 result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str());
4852 result.SetStatus (eReturnStatusFailed);
4853 return false;
4854 }
4855
4856 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4857 if (process)
4858 {
4859 const char *packet_size = command.GetArgumentAtIndex(0);
4860 errno = 0;
4861 uint64_t user_specified_max = strtoul (packet_size, NULL, 10);
4862 if (errno == 0 && user_specified_max != 0)
4863 {
4864 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max);
4865 result.SetStatus (eReturnStatusSuccessFinishResult);
4866 return true;
4867 }
4868 }
4869 result.SetStatus (eReturnStatusFailed);
4870 return false;
4871 }
4872};
4873
4874
Greg Clayton02686b82012-10-15 22:42:16 +00004875class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
4876{
4877private:
4878
4879public:
4880 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
4881 CommandObjectParsed (interpreter,
4882 "process plugin packet send",
4883 "Send a custom packet through the GDB remote protocol and print the answer. "
4884 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
4885 NULL)
4886 {
4887 }
4888
4889 ~CommandObjectProcessGDBRemotePacketSend ()
4890 {
4891 }
4892
4893 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004894 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton02686b82012-10-15 22:42:16 +00004895 {
4896 const size_t argc = command.GetArgumentCount();
4897 if (argc == 0)
4898 {
4899 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
4900 result.SetStatus (eReturnStatusFailed);
4901 return false;
4902 }
4903
4904 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4905 if (process)
4906 {
Han Ming Ong84145852012-11-26 20:42:03 +00004907 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00004908 {
Han Ming Ong84145852012-11-26 20:42:03 +00004909 const char *packet_cstr = command.GetArgumentAtIndex(0);
4910 bool send_async = true;
4911 StringExtractorGDBRemote response;
4912 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
4913 result.SetStatus (eReturnStatusSuccessFinishResult);
4914 Stream &output_strm = result.GetOutputStream();
4915 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00004916 std::string &response_str = response.GetStringRef();
4917
Han Ming Ong399289e2013-06-21 19:56:59 +00004918 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00004919 {
4920 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
4921 }
4922
Han Ming Ong84145852012-11-26 20:42:03 +00004923 if (response_str.empty())
4924 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
4925 else
4926 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00004927 }
Greg Clayton02686b82012-10-15 22:42:16 +00004928 }
Greg Clayton998255b2012-10-13 02:07:45 +00004929 return true;
4930 }
4931};
4932
Greg Claytonba4a0a52013-02-01 23:03:47 +00004933class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
4934{
4935private:
4936
4937public:
4938 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
4939 CommandObjectRaw (interpreter,
4940 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00004941 "Send a qRcmd packet through the GDB remote protocol and print the response."
4942 "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 +00004943 NULL)
4944 {
4945 }
4946
4947 ~CommandObjectProcessGDBRemotePacketMonitor ()
4948 {
4949 }
4950
4951 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004952 DoExecute (const char *command, CommandReturnObject &result) override
Greg Claytonba4a0a52013-02-01 23:03:47 +00004953 {
4954 if (command == NULL || command[0] == '\0')
4955 {
4956 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
4957 result.SetStatus (eReturnStatusFailed);
4958 return false;
4959 }
4960
4961 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4962 if (process)
4963 {
4964 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00004965 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00004966 packet.PutBytesAsRawHex8(command, strlen(command));
4967 const char *packet_cstr = packet.GetString().c_str();
4968
4969 bool send_async = true;
4970 StringExtractorGDBRemote response;
4971 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
4972 result.SetStatus (eReturnStatusSuccessFinishResult);
4973 Stream &output_strm = result.GetOutputStream();
4974 output_strm.Printf (" packet: %s\n", packet_cstr);
4975 const std::string &response_str = response.GetStringRef();
4976
4977 if (response_str.empty())
4978 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
4979 else
4980 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
4981 }
4982 return true;
4983 }
4984};
4985
Greg Clayton02686b82012-10-15 22:42:16 +00004986class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
4987{
4988private:
4989
4990public:
4991 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
4992 CommandObjectMultiword (interpreter,
4993 "process plugin packet",
4994 "Commands that deal with GDB remote packets.",
4995 NULL)
4996 {
4997 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
4998 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00004999 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Jason Molenda6076bf42014-05-06 04:34:52 +00005000 LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter)));
Greg Claytone034a042015-05-21 20:52:06 +00005001 LoadSubCommand ("speed-test", CommandObjectSP (new CommandObjectProcessGDBRemoteSpeedTest (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00005002 }
5003
5004 ~CommandObjectProcessGDBRemotePacket ()
5005 {
5006 }
5007};
Greg Clayton998255b2012-10-13 02:07:45 +00005008
5009class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
5010{
5011public:
5012 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
5013 CommandObjectMultiword (interpreter,
5014 "process plugin",
5015 "A set of commands for operating on a ProcessGDBRemote process.",
5016 "process plugin <subcommand> [<subcommand-options>]")
5017 {
5018 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
5019 }
5020
5021 ~CommandObjectMultiwordProcessGDBRemote ()
5022 {
5023 }
5024};
5025
Greg Clayton998255b2012-10-13 02:07:45 +00005026CommandObject *
5027ProcessGDBRemote::GetPluginCommandObject()
5028{
5029 if (!m_command_sp)
5030 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
5031 return m_command_sp.get();
5032}