blob: 64972dfda36275cb77034b5eaa32670015ed0be7 [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"
Todd Fialaaf245d12014-06-30 21:05:18 +000068#include "Plugins/Process/Utility/FreeBSDSignals.h"
Peter Collingbourne99f9aa02011-06-03 20:40:38 +000069#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000070#include "Plugins/Process/Utility/LinuxSignals.h"
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +000071#include "Plugins/Process/Utility/MipsLinuxSignals.h"
Jason Molendac42d2432012-07-25 03:40:06 +000072#include "Plugins/Process/Utility/StopInfoMachException.h"
Jim Ingham43c555d2012-07-04 00:35:43 +000073#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
Greg Claytonc982c762010-07-09 20:39:50 +000074#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000075#include "GDBRemoteRegisterContext.h"
76#include "ProcessGDBRemote.h"
77#include "ProcessGDBRemoteLog.h"
78#include "ThreadGDBRemote.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000079
Tamas Berghammerdb264a62015-03-31 09:52:22 +000080#define DEBUGSERVER_BASENAME "debugserver"
81using namespace lldb;
82using namespace lldb_private;
83using namespace lldb_private::process_gdb_remote;
Jason Molenda5e8534e2012-10-03 01:29:34 +000084
Greg Claytonc1422c12012-04-09 22:46:21 +000085namespace lldb
86{
87 // Provide a function that can easily dump the packet history if we know a
88 // ProcessGDBRemote * value (which we can get from logs or from debugging).
89 // We need the function in the lldb namespace so it makes it into the final
90 // executable since the LLDB shared library only exports stuff in the lldb
91 // namespace. This allows you to attach with a debugger and call this
92 // function and get the packet history dumped to a file.
93 void
94 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
95 {
Tamas Berghammerdb264a62015-03-31 09:52:22 +000096 StreamFile strm;
97 Error error (strm.GetFile().Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate));
Greg Claytond451c1a2012-04-13 21:24:18 +000098 if (error.Success())
99 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
Greg Claytonc1422c12012-04-09 22:46:21 +0000100 }
Filipe Cabecinhasc34f7762012-05-23 16:27:09 +0000101}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000102
Greg Clayton7f982402013-07-15 22:54:20 +0000103namespace {
Steve Pucci5ec012d2014-01-16 22:18:14 +0000104
Greg Clayton7f982402013-07-15 22:54:20 +0000105 static PropertyDefinition
106 g_properties[] =
107 {
108 { "packet-timeout" , OptionValue::eTypeUInt64 , true , 1, NULL, NULL, "Specify the default packet timeout in seconds." },
Greg Claytonef8180a2013-10-15 00:14:28 +0000109 { "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 +0000110 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
111 };
112
113 enum
114 {
Greg Claytonef8180a2013-10-15 00:14:28 +0000115 ePropertyPacketTimeout,
116 ePropertyTargetDefinitionFile
Greg Clayton7f982402013-07-15 22:54:20 +0000117 };
118
119 class PluginProperties : public Properties
120 {
121 public:
122
123 static ConstString
124 GetSettingName ()
125 {
126 return ProcessGDBRemote::GetPluginNameStatic();
127 }
128
129 PluginProperties() :
130 Properties ()
131 {
132 m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
133 m_collection_sp->Initialize(g_properties);
134 }
135
136 virtual
137 ~PluginProperties()
138 {
139 }
140
141 uint64_t
142 GetPacketTimeout()
143 {
144 const uint32_t idx = ePropertyPacketTimeout;
145 return m_collection_sp->GetPropertyAtIndexAsUInt64(NULL, idx, g_properties[idx].default_uint_value);
146 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000147
148 bool
149 SetPacketTimeout(uint64_t timeout)
150 {
151 const uint32_t idx = ePropertyPacketTimeout;
152 return m_collection_sp->SetPropertyAtIndexAsUInt64(NULL, idx, timeout);
153 }
154
Greg Claytonef8180a2013-10-15 00:14:28 +0000155 FileSpec
156 GetTargetDefinitionFile () const
157 {
158 const uint32_t idx = ePropertyTargetDefinitionFile;
159 return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
160 }
Greg Clayton7f982402013-07-15 22:54:20 +0000161 };
162
163 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
164
165 static const ProcessKDPPropertiesSP &
166 GetGlobalPluginProperties()
167 {
168 static ProcessKDPPropertiesSP g_settings_sp;
169 if (!g_settings_sp)
170 g_settings_sp.reset (new PluginProperties ());
171 return g_settings_sp;
172 }
173
174} // anonymous namespace end
175
Aidan Doddsc0c83852015-05-08 09:36:31 +0000176class ProcessGDBRemote::GDBLoadedModuleInfoList
177{
178public:
179
180 class LoadedModuleInfo
181 {
182 public:
183
184 enum e_data_point
185 {
186 e_has_name = 0,
187 e_has_base ,
188 e_has_dynamic ,
189 e_has_link_map ,
190 e_num
191 };
192
193 LoadedModuleInfo ()
194 {
195 for (uint32_t i = 0; i < e_num; ++i)
196 m_has[i] = false;
197 };
198
199 void set_name (const std::string & name)
200 {
201 m_name = name;
202 m_has[e_has_name] = true;
203 }
204 bool get_name (std::string & out) const
205 {
206 out = m_name;
207 return m_has[e_has_name];
208 }
209
210 void set_base (const lldb::addr_t base)
211 {
212 m_base = base;
213 m_has[e_has_base] = true;
214 }
215 bool get_base (lldb::addr_t & out) const
216 {
217 out = m_base;
218 return m_has[e_has_base];
219 }
220
221 void set_link_map (const lldb::addr_t addr)
222 {
223 m_link_map = addr;
224 m_has[e_has_link_map] = true;
225 }
226 bool get_link_map (lldb::addr_t & out) const
227 {
228 out = m_link_map;
229 return m_has[e_has_link_map];
230 }
231
232 void set_dynamic (const lldb::addr_t addr)
233 {
234 m_dynamic = addr;
235 m_has[e_has_dynamic] = true;
236 }
237 bool get_dynamic (lldb::addr_t & out) const
238 {
239 out = m_dynamic;
240 return m_has[e_has_dynamic];
241 }
242
243 bool has_info (e_data_point datum)
244 {
245 assert (datum < e_num);
246 return m_has[datum];
247 }
248
249 protected:
250
251 bool m_has[e_num];
252 std::string m_name;
253 lldb::addr_t m_link_map;
254 lldb::addr_t m_base;
255 lldb::addr_t m_dynamic;
256 };
257
258 GDBLoadedModuleInfoList ()
259 : m_list ()
260 , m_link_map (LLDB_INVALID_ADDRESS)
261 {}
262
263 void add (const LoadedModuleInfo & mod)
264 {
265 m_list.push_back (mod);
266 }
267
268 void clear ()
269 {
270 m_list.clear ();
271 }
272
273 std::vector<LoadedModuleInfo> m_list;
274 lldb::addr_t m_link_map;
275};
276
Greg Claytonfda4fab2014-01-10 22:24:11 +0000277// TODO Randomly assigning a port is unsafe. We should get an unused
278// ephemeral port from the kernel and make sure we reserve it before passing
279// it to debugserver.
280
281#if defined (__APPLE__)
282#define LOW_PORT (IPPORT_RESERVED)
283#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
284#else
285#define LOW_PORT (1024u)
286#define HIGH_PORT (49151u)
287#endif
288
Todd Fiala013434e2014-07-09 01:29:05 +0000289#if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000290static bool rand_initialized = false;
291
Greg Claytonfda4fab2014-01-10 22:24:11 +0000292static inline uint16_t
293get_random_port ()
294{
295 if (!rand_initialized)
296 {
297 time_t seed = time(NULL);
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000298
Greg Claytonfda4fab2014-01-10 22:24:11 +0000299 rand_initialized = true;
300 srand(seed);
301 }
302 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
303}
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000304#endif
Greg Claytonfda4fab2014-01-10 22:24:11 +0000305
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000306ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000307ProcessGDBRemote::GetPluginNameStatic()
308{
Greg Clayton57abc5d2013-05-10 21:47:16 +0000309 static ConstString g_name("gdb-remote");
310 return g_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000311}
312
313const char *
314ProcessGDBRemote::GetPluginDescriptionStatic()
315{
316 return "GDB Remote protocol based debugging plug-in.";
317}
318
319void
320ProcessGDBRemote::Terminate()
321{
322 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
323}
324
325
Greg Claytonc3776bf2012-02-09 06:16:32 +0000326lldb::ProcessSP
327ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000328{
Greg Claytonc3776bf2012-02-09 06:16:32 +0000329 lldb::ProcessSP process_sp;
330 if (crash_file_path == NULL)
331 process_sp.reset (new ProcessGDBRemote (target, listener));
332 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000333}
334
335bool
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000336ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000337{
Greg Clayton596ed242011-10-21 21:41:45 +0000338 if (plugin_specified_by_name)
339 return true;
340
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000341 // For now we are just making sure the file exists for a given module
Greg Claytonaa149cb2011-08-11 02:48:45 +0000342 Module *exe_module = target.GetExecutableModulePointer();
343 if (exe_module)
Greg Claytonc3776bf2012-02-09 06:16:32 +0000344 {
345 ObjectFile *exe_objfile = exe_module->GetObjectFile();
346 // We can't debug core files...
347 switch (exe_objfile->GetType())
348 {
349 case ObjectFile::eTypeInvalid:
350 case ObjectFile::eTypeCoreFile:
351 case ObjectFile::eTypeDebugInfo:
352 case ObjectFile::eTypeObjectFile:
353 case ObjectFile::eTypeSharedLibrary:
354 case ObjectFile::eTypeStubLibrary:
Greg Clayton23f8c952014-03-24 23:10:19 +0000355 case ObjectFile::eTypeJIT:
Greg Claytonc3776bf2012-02-09 06:16:32 +0000356 return false;
357 case ObjectFile::eTypeExecutable:
358 case ObjectFile::eTypeDynamicLinker:
359 case ObjectFile::eTypeUnknown:
360 break;
361 }
Greg Claytonaa149cb2011-08-11 02:48:45 +0000362 return exe_module->GetFileSpec().Exists();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000363 }
Jim Ingham5aee1622010-08-09 23:31:02 +0000364 // However, if there is no executable module, we return true since we might be preparing to attach.
365 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000366}
367
368//----------------------------------------------------------------------
369// ProcessGDBRemote constructor
370//----------------------------------------------------------------------
371ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
372 Process (target, listener),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000373 m_flags (0),
Tamas Berghammere13c2732015-02-11 10:29:30 +0000374 m_gdb_comm (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000375 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton09c3e3d2011-12-06 04:51:14 +0000376 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000377 m_register_info (),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000378 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
Jim Ingham455fa5c2012-11-01 01:15:33 +0000379 m_async_thread_state_mutex(Mutex::eMutexTypeRecursive),
Greg Clayton9e920902012-04-10 02:25:43 +0000380 m_thread_ids (),
Greg Clayton71fc2a32011-02-12 06:28:37 +0000381 m_continue_c_tids (),
382 m_continue_C_tids (),
383 m_continue_s_tids (),
384 m_continue_S_tids (),
Jason Molenda6076bf42014-05-06 04:34:52 +0000385 m_max_memory_size (0),
386 m_remote_stub_max_memory_size (0),
Greg Clayton4116e932012-05-15 02:33:01 +0000387 m_addr_to_mmap_size (),
388 m_thread_create_bp_sp (),
Jim Ingham43c555d2012-07-04 00:35:43 +0000389 m_waiting_for_attach (false),
Jason Molenda5e8534e2012-10-03 01:29:34 +0000390 m_destroy_tried_resuming (false),
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000391 m_command_sp (),
Ewan Crawford78baa192015-05-13 09:18:18 +0000392 m_breakpoint_pc_offset (0),
393 m_initial_tid (LLDB_INVALID_THREAD_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000394{
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000395 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
396 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Inghamb1e2e842012-04-12 18:49:31 +0000397 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Greg Clayton7f982402013-07-15 22:54:20 +0000398 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
399 if (timeout_seconds > 0)
400 m_gdb_comm.SetPacketTimeout(timeout_seconds);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000401}
402
403//----------------------------------------------------------------------
404// Destructor
405//----------------------------------------------------------------------
406ProcessGDBRemote::~ProcessGDBRemote()
407{
408 // m_mach_process.UnregisterNotificationCallbacks (this);
409 Clear();
Greg Clayton1ed54f52011-10-01 00:45:15 +0000410 // We need to call finalize on the process before destroying ourselves
411 // to make sure all of the broadcaster cleanup goes as planned. If we
412 // destruct this class, then Process::~Process() might have problems
413 // trying to fully destroy the broadcaster.
414 Finalize();
Jim Ingham455fa5c2012-11-01 01:15:33 +0000415
416 // The general Finalize is going to try to destroy the process and that SHOULD
417 // shut down the async thread. However, if we don't kill it it will get stranded and
418 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
419 StopAsyncThread();
420 KillDebugserverProcess();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000421}
422
423//----------------------------------------------------------------------
424// PluginInterface
425//----------------------------------------------------------------------
Greg Clayton57abc5d2013-05-10 21:47:16 +0000426ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000427ProcessGDBRemote::GetPluginName()
428{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000429 return GetPluginNameStatic();
430}
431
432uint32_t
433ProcessGDBRemote::GetPluginVersion()
434{
435 return 1;
436}
437
Greg Claytonef8180a2013-10-15 00:14:28 +0000438bool
439ProcessGDBRemote::ParsePythonTargetDefinition(const FileSpec &target_definition_fspec)
440{
441 ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
442 Error error;
Zachary Turner0641ca12015-03-17 20:04:04 +0000443 StructuredData::ObjectSP module_object_sp(interpreter->LoadPluginModule(target_definition_fspec, error));
Greg Claytonef8180a2013-10-15 00:14:28 +0000444 if (module_object_sp)
445 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000446 StructuredData::DictionarySP target_definition_sp(
447 interpreter->GetDynamicSettings(module_object_sp, &GetTarget(), "gdb-server-target-definition", error));
Greg Claytonef8180a2013-10-15 00:14:28 +0000448
Zachary Turner0641ca12015-03-17 20:04:04 +0000449 if (target_definition_sp)
Greg Claytonef8180a2013-10-15 00:14:28 +0000450 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000451 StructuredData::ObjectSP target_object(target_definition_sp->GetValueForKey("host-info"));
452 if (target_object)
Greg Clayton312bcbe2013-10-17 01:10:23 +0000453 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000454 if (auto host_info_dict = target_object->GetAsDictionary())
Greg Clayton312bcbe2013-10-17 01:10:23 +0000455 {
Zachary Turner0641ca12015-03-17 20:04:04 +0000456 StructuredData::ObjectSP triple_value = host_info_dict->GetValueForKey("triple");
457 if (auto triple_string_value = triple_value->GetAsString())
458 {
459 std::string triple_string = triple_string_value->GetValue();
460 ArchSpec host_arch(triple_string.c_str());
461 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture()))
462 {
463 GetTarget().SetArchitecture(host_arch);
464 }
465 }
Greg Clayton312bcbe2013-10-17 01:10:23 +0000466 }
Greg Clayton312bcbe2013-10-17 01:10:23 +0000467 }
Zachary Turner0641ca12015-03-17 20:04:04 +0000468 m_breakpoint_pc_offset = 0;
469 StructuredData::ObjectSP breakpoint_pc_offset_value = target_definition_sp->GetValueForKey("breakpoint-pc-offset");
470 if (breakpoint_pc_offset_value)
471 {
472 if (auto breakpoint_pc_int_value = breakpoint_pc_offset_value->GetAsInteger())
473 m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
474 }
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000475
Greg Claytond04f0ed2015-05-26 18:00:51 +0000476 if (m_register_info.SetRegisterInfo(*target_definition_sp, GetTarget().GetArchitecture()) > 0)
Greg Claytonef8180a2013-10-15 00:14:28 +0000477 {
478 return true;
479 }
480 }
481 }
482 return false;
483}
484
Greg Claytond04f0ed2015-05-26 18:00:51 +0000485static size_t
486SplitCommaSeparatedRegisterNumberString(const llvm::StringRef &comma_separated_regiter_numbers, std::vector<uint32_t> &regnums, int base)
487{
488 regnums.clear();
489 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
490 value_pair.second = comma_separated_regiter_numbers;
491 do
492 {
493 value_pair = value_pair.second.split(',');
494 if (!value_pair.first.empty())
495 {
496 uint32_t reg = StringConvert::ToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, base);
497 if (reg != LLDB_INVALID_REGNUM)
498 regnums.push_back (reg);
499 }
500 } while (!value_pair.second.empty());
501 return regnums.size();
502}
503
Greg Claytonef8180a2013-10-15 00:14:28 +0000504
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000505void
Greg Clayton513c26c2011-01-29 07:10:55 +0000506ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000507{
Greg Clayton513c26c2011-01-29 07:10:55 +0000508 if (!force && m_register_info.GetNumRegisters() > 0)
509 return;
510
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000511 m_register_info.Clear();
Greg Claytond04f0ed2015-05-26 18:00:51 +0000512
513 // Check if qHostInfo specified a specific packet timeout for this connection.
514 // If so then lets update our setting so the user knows what the timeout is
515 // and can see it.
516 const uint32_t host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
517 if (host_packet_timeout)
518 {
519 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout);
520 }
521
522 if (GetGDBServerRegisterInfo ())
523 return;
524
525 char packet[128];
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000526 uint32_t reg_offset = 0;
527 uint32_t reg_num = 0;
Greg Clayton23f59502012-07-17 03:23:13 +0000528 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Greg Clayton576d8832011-03-22 04:00:09 +0000529 response_type == StringExtractorGDBRemote::eResponse;
530 ++reg_num)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000531 {
Greg Clayton513c26c2011-01-29 07:10:55 +0000532 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
Andy Gibbsa297a972013-06-19 19:04:53 +0000533 assert (packet_len < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000534 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000535 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000536 {
Greg Clayton576d8832011-03-22 04:00:09 +0000537 response_type = response.GetResponseType();
538 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000539 {
540 std::string name;
541 std::string value;
542 ConstString reg_name;
543 ConstString alt_name;
544 ConstString set_name;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000545 std::vector<uint32_t> value_regs;
546 std::vector<uint32_t> invalidate_regs;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000547 RegisterInfo reg_info = { NULL, // Name
548 NULL, // Alt name
549 0, // byte size
550 reg_offset, // offset
551 eEncodingUint, // encoding
552 eFormatHex, // formate
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000553 {
554 LLDB_INVALID_REGNUM, // GCC reg num
555 LLDB_INVALID_REGNUM, // DWARF reg num
556 LLDB_INVALID_REGNUM, // generic reg num
Jason Molendafbcb7f22010-09-10 07:49:16 +0000557 reg_num, // GDB reg num
558 reg_num // native register number
Greg Clayton435d85a2012-02-29 19:27:27 +0000559 },
560 NULL,
561 NULL
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000562 };
563
564 while (response.GetNameColonValue(name, value))
565 {
566 if (name.compare("name") == 0)
567 {
568 reg_name.SetCString(value.c_str());
569 }
570 else if (name.compare("alt-name") == 0)
571 {
572 alt_name.SetCString(value.c_str());
573 }
574 else if (name.compare("bitsize") == 0)
575 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000576 reg_info.byte_size = StringConvert::ToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000577 }
578 else if (name.compare("offset") == 0)
579 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000580 uint32_t offset = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda743e86a2010-06-11 23:44:18 +0000581 if (reg_offset != offset)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000582 {
583 reg_offset = offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000584 }
585 }
586 else if (name.compare("encoding") == 0)
587 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000588 const Encoding encoding = Args::StringToEncoding (value.c_str());
589 if (encoding != eEncodingInvalid)
590 reg_info.encoding = encoding;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000591 }
592 else if (name.compare("format") == 0)
593 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000594 Format format = eFormatInvalid;
595 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
596 reg_info.format = format;
597 else if (value.compare("binary") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000598 reg_info.format = eFormatBinary;
599 else if (value.compare("decimal") == 0)
600 reg_info.format = eFormatDecimal;
601 else if (value.compare("hex") == 0)
602 reg_info.format = eFormatHex;
603 else if (value.compare("float") == 0)
604 reg_info.format = eFormatFloat;
605 else if (value.compare("vector-sint8") == 0)
606 reg_info.format = eFormatVectorOfSInt8;
607 else if (value.compare("vector-uint8") == 0)
608 reg_info.format = eFormatVectorOfUInt8;
609 else if (value.compare("vector-sint16") == 0)
610 reg_info.format = eFormatVectorOfSInt16;
611 else if (value.compare("vector-uint16") == 0)
612 reg_info.format = eFormatVectorOfUInt16;
613 else if (value.compare("vector-sint32") == 0)
614 reg_info.format = eFormatVectorOfSInt32;
615 else if (value.compare("vector-uint32") == 0)
616 reg_info.format = eFormatVectorOfUInt32;
617 else if (value.compare("vector-float32") == 0)
618 reg_info.format = eFormatVectorOfFloat32;
619 else if (value.compare("vector-uint128") == 0)
620 reg_info.format = eFormatVectorOfUInt128;
621 }
622 else if (name.compare("set") == 0)
623 {
624 set_name.SetCString(value.c_str());
625 }
626 else if (name.compare("gcc") == 0)
627 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000628 reg_info.kinds[eRegisterKindGCC] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000629 }
630 else if (name.compare("dwarf") == 0)
631 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000632 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000633 }
634 else if (name.compare("generic") == 0)
635 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000636 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000637 }
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000638 else if (name.compare("container-regs") == 0)
639 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000640 SplitCommaSeparatedRegisterNumberString(value, value_regs, 16);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000641 }
642 else if (name.compare("invalidate-regs") == 0)
643 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000644 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 16);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000645 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000646 }
647
Jason Molenda743e86a2010-06-11 23:44:18 +0000648 reg_info.byte_offset = reg_offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000649 assert (reg_info.byte_size != 0);
650 reg_offset += reg_info.byte_size;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000651 if (!value_regs.empty())
652 {
653 value_regs.push_back(LLDB_INVALID_REGNUM);
654 reg_info.value_regs = value_regs.data();
655 }
656 if (!invalidate_regs.empty())
657 {
658 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
659 reg_info.invalidate_regs = invalidate_regs.data();
660 }
661
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000662 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
663 }
Todd Fiala1a634402014-01-08 07:52:40 +0000664 else
665 {
666 break; // ensure exit before reg_num is incremented
667 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000668 }
669 else
670 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000671 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000672 }
673 }
674
Greg Claytond04f0ed2015-05-26 18:00:51 +0000675 if (m_register_info.GetNumRegisters() > 0)
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000676 {
Greg Claytond04f0ed2015-05-26 18:00:51 +0000677 m_register_info.Finalize(GetTarget().GetArchitecture());
678 return;
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000679 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000680
Greg Claytond04f0ed2015-05-26 18:00:51 +0000681 FileSpec target_definition_fspec = GetGlobalPluginProperties()->GetTargetDefinitionFile ();
Greg Clayton312bcbe2013-10-17 01:10:23 +0000682
Greg Claytond04f0ed2015-05-26 18:00:51 +0000683 if (target_definition_fspec)
684 {
685 // See if we can get register definitions from a python file
686 if (ParsePythonTargetDefinition (target_definition_fspec))
687 return;
Greg Claytonef8180a2013-10-15 00:14:28 +0000688 }
689
Johnny Chen2fa9de12012-05-14 18:44:23 +0000690 // We didn't get anything if the accumulated reg_num is zero. See if we are
691 // debugging ARM and fill with a hard coded register set until we can get an
692 // updated debugserver down on the devices.
693 // On the other hand, if the accumulated reg_num is positive, see if we can
694 // add composite registers to the existing primordial ones.
Greg Claytond04f0ed2015-05-26 18:00:51 +0000695 bool from_scratch = (m_register_info.GetNumRegisters() == 0);
Johnny Chen2fa9de12012-05-14 18:44:23 +0000696
697 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000698 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
699 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
700
701 // Use the process' architecture instead of the host arch, if available
702 ArchSpec remote_arch;
703 if (remote_process_arch.IsValid ())
704 remote_arch = remote_process_arch;
705 else
706 remote_arch = remote_host_arch;
707
Johnny Chen2fa9de12012-05-14 18:44:23 +0000708 if (!target_arch.IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000709 {
Johnny Chen2fa9de12012-05-14 18:44:23 +0000710 if (remote_arch.IsValid()
711 && remote_arch.GetMachine() == llvm::Triple::arm
712 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
713 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000714 }
Johnny Chen2fa9de12012-05-14 18:44:23 +0000715 else if (target_arch.GetMachine() == llvm::Triple::arm)
716 {
717 m_register_info.HardcodeARMRegisters(from_scratch);
718 }
719
720 // At this point, we can finalize our register info.
Greg Claytond04f0ed2015-05-26 18:00:51 +0000721 m_register_info.Finalize (GetTarget().GetArchitecture());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000722}
723
724Error
725ProcessGDBRemote::WillLaunch (Module* module)
726{
727 return WillLaunchOrAttach ();
728}
729
730Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000731ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000732{
733 return WillLaunchOrAttach ();
734}
735
736Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000737ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000738{
739 return WillLaunchOrAttach ();
740}
741
742Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000743ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +0000744{
Todd Fialaaf245d12014-06-30 21:05:18 +0000745 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Claytonb766a732011-02-04 01:58:07 +0000746 Error error (WillLaunchOrAttach ());
747
748 if (error.Fail())
749 return error;
750
Greg Clayton2289fa42011-04-30 01:09:13 +0000751 error = ConnectToDebugserver (remote_url);
Greg Claytonb766a732011-02-04 01:58:07 +0000752
753 if (error.Fail())
754 return error;
755 StartAsyncThread ();
756
Greg Claytonc574ede2011-03-10 02:26:48 +0000757 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonb766a732011-02-04 01:58:07 +0000758 if (pid == LLDB_INVALID_PROCESS_ID)
759 {
760 // We don't have a valid process ID, so note that we are connected
761 // and could now request to launch or attach, or get remote process
762 // listings...
763 SetPrivateState (eStateConnected);
764 }
765 else
766 {
767 // We have a valid process
768 SetID (pid);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000769 GetThreadList();
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000770 StringExtractorGDBRemote response;
771 if (m_gdb_comm.GetStopReply(response))
Greg Claytonb766a732011-02-04 01:58:07 +0000772 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000773 SetLastStopPacket(response);
Ewan Crawford78baa192015-05-13 09:18:18 +0000774
775 // '?' Packets must be handled differently in non-stop mode
776 if (GetTarget().GetNonStopModeEnabled())
777 HandleStopReplySequence();
778
Jason Molendac62bd7b2013-12-21 05:20:36 +0000779 if (!m_target.GetArchitecture().IsValid())
780 {
781 if (m_gdb_comm.GetProcessArchitecture().IsValid())
782 {
783 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
784 }
785 else
786 {
787 m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
788 }
Carlo Kok74389122013-10-14 07:09:13 +0000789 }
790
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000791 const StateType state = SetThreadStopInfo (response);
Greg Claytonb766a732011-02-04 01:58:07 +0000792 if (state == eStateStopped)
793 {
794 SetPrivateState (state);
795 }
796 else
Daniel Malead01b2952012-11-29 21:49:15 +0000797 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 +0000798 }
799 else
Daniel Malead01b2952012-11-29 21:49:15 +0000800 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 +0000801 }
Jason Molenda16d127c2012-05-03 22:37:30 +0000802
Todd Fialaaf245d12014-06-30 21:05:18 +0000803 if (log)
804 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");
805
806
807 if (error.Success()
Jason Molenda16d127c2012-05-03 22:37:30 +0000808 && !GetTarget().GetArchitecture().IsValid()
809 && m_gdb_comm.GetHostArchitecture().IsValid())
810 {
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000811 // Prefer the *process'* architecture over that of the *host*, if available.
812 if (m_gdb_comm.GetProcessArchitecture().IsValid())
813 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
814 else
815 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molenda16d127c2012-05-03 22:37:30 +0000816 }
817
Todd Fialaaf245d12014-06-30 21:05:18 +0000818 if (log)
819 log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": normalized target architecture triple: %s", __FUNCTION__, GetID (), GetTarget ().GetArchitecture ().GetTriple ().getTriple ().c_str ());
820
821 // Set the Unix signals properly for the target.
822 // FIXME Add a gdb-remote packet to discover dynamically.
823 if (error.Success ())
824 {
Tamas Berghammerac839822015-03-04 11:34:10 +0000825 const ArchSpec arch_spec = m_gdb_comm.GetHostArchitecture();
Todd Fialaaf245d12014-06-30 21:05:18 +0000826 if (arch_spec.IsValid ())
827 {
828 if (log)
829 log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": determining unix signals type based on architecture %s, triple %s", __FUNCTION__, GetID (), arch_spec.GetArchitectureName () ? arch_spec.GetArchitectureName () : "<null>", arch_spec.GetTriple ().getTriple ().c_str ());
830
831 switch (arch_spec.GetTriple ().getOS ())
832 {
833 case llvm::Triple::Linux:
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +0000834 if (arch_spec.GetTriple ().getArch () == llvm::Triple::mips64 || arch_spec.GetTriple ().getArch () == llvm::Triple::mips64el)
835 SetUnixSignals (UnixSignalsSP (new process_linux::MipsLinuxSignals ()));
836 else
837 SetUnixSignals (UnixSignalsSP (new process_linux::LinuxSignals ()));
Todd Fialaaf245d12014-06-30 21:05:18 +0000838 if (log)
839 log->Printf ("ProcessGDBRemote::%s using Linux unix signals type for pid %" PRIu64, __FUNCTION__, GetID ());
840 break;
841 case llvm::Triple::OpenBSD:
842 case llvm::Triple::FreeBSD:
843 case llvm::Triple::NetBSD:
Todd Fiala4ceced32014-08-29 17:35:57 +0000844 SetUnixSignals (UnixSignalsSP (new FreeBSDSignals ()));
Todd Fialaaf245d12014-06-30 21:05:18 +0000845 if (log)
846 log->Printf ("ProcessGDBRemote::%s using *BSD unix signals type for pid %" PRIu64, __FUNCTION__, GetID ());
847 break;
848 default:
Todd Fiala4ceced32014-08-29 17:35:57 +0000849 SetUnixSignals (UnixSignalsSP (new UnixSignals ()));
Todd Fialaaf245d12014-06-30 21:05:18 +0000850 if (log)
851 log->Printf ("ProcessGDBRemote::%s using generic unix signals type for pid %" PRIu64, __FUNCTION__, GetID ());
852 break;
853 }
854 }
855 }
856
Greg Claytonb766a732011-02-04 01:58:07 +0000857 return error;
858}
859
860Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000861ProcessGDBRemote::WillLaunchOrAttach ()
862{
863 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000864 m_stdio_communication.Clear ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000865 return error;
866}
867
868//----------------------------------------------------------------------
869// Process Control
870//----------------------------------------------------------------------
871Error
Jean-Daniel Dupas7782de92013-12-09 22:52:50 +0000872ProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000873{
Todd Fiala75f47c32014-10-11 21:42:09 +0000874 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton4957bf62010-09-30 21:49:03 +0000875 Error error;
Greg Clayton982c9762011-11-03 21:22:33 +0000876
Todd Fiala75f47c32014-10-11 21:42:09 +0000877 if (log)
878 log->Printf ("ProcessGDBRemote::%s() entered", __FUNCTION__);
879
Greg Clayton982c9762011-11-03 21:22:33 +0000880 uint32_t launch_flags = launch_info.GetFlags().Get();
Chaoren Lind3173f32015-05-29 19:52:29 +0000881 FileSpec stdin_file_spec{};
882 FileSpec stdout_file_spec{};
883 FileSpec stderr_file_spec{};
884 FileSpec working_dir = launch_info.GetWorkingDirectory();
Greg Clayton982c9762011-11-03 21:22:33 +0000885
Zachary Turner696b5282014-08-14 16:01:25 +0000886 const FileAction *file_action;
Greg Clayton982c9762011-11-03 21:22:33 +0000887 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
888 if (file_action)
889 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000890 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000891 stdin_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000892 }
893 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
894 if (file_action)
895 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000896 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000897 stdout_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000898 }
899 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
900 if (file_action)
901 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000902 if (file_action->GetAction() == FileAction::eFileActionOpen)
Chaoren Lind3173f32015-05-29 19:52:29 +0000903 stderr_file_spec = file_action->GetFileSpec();
Greg Clayton982c9762011-11-03 21:22:33 +0000904 }
905
Todd Fiala75f47c32014-10-11 21:42:09 +0000906 if (log)
907 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000908 if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
Vince Harron4a8abd32015-02-13 19:15:24 +0000909 log->Printf ("ProcessGDBRemote::%s provided with STDIO paths via launch_info: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000910 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000911 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
912 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
913 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Todd Fiala75f47c32014-10-11 21:42:09 +0000914 else
915 log->Printf ("ProcessGDBRemote::%s no STDIO paths given via launch_info", __FUNCTION__);
916 }
917
Vince Harrondf3f00f2015-02-10 21:09:04 +0000918 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Chaoren Lind3173f32015-05-29 19:52:29 +0000919 if (stdin_file_spec || disable_stdio)
Vince Harrondf3f00f2015-02-10 21:09:04 +0000920 {
921 // the inferior will be reading stdin from the specified file
922 // or stdio is completely disabled
923 m_stdin_forward = false;
924 }
925 else
926 {
927 m_stdin_forward = true;
928 }
929
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000930 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
931 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
932 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000933
Greg Clayton982c9762011-11-03 21:22:33 +0000934 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000935 if (object_file)
936 {
Greg Clayton71337622011-02-24 22:24:29 +0000937 // Make sure we aren't already connected?
938 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000939 {
Greg Clayton91a9b2472013-12-04 19:19:12 +0000940 error = LaunchAndConnectToDebugserver (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000941 }
942
943 if (error.Success())
944 {
945 lldb_utility::PseudoTerminal pty;
946 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000947
Greg Claytonf58c2692011-06-24 22:32:10 +0000948 PlatformSP platform_sp (m_target.GetPlatform());
Vince Harrondf3f00f2015-02-10 21:09:04 +0000949 if (disable_stdio)
Greg Clayton71337622011-02-24 22:24:29 +0000950 {
Vince Harrondf3f00f2015-02-10 21:09:04 +0000951 // set to /dev/null unless redirected to a file above
Chaoren Lind3173f32015-05-29 19:52:29 +0000952 if (!stdin_file_spec)
953 stdin_file_spec.SetFile("/dev/null", false);
954 if (!stdout_file_spec)
955 stdout_file_spec.SetFile("/dev/null", false);
956 if (!stderr_file_spec)
957 stderr_file_spec.SetFile("/dev/null", false);
Vince Harrondf3f00f2015-02-10 21:09:04 +0000958 }
959 else if (platform_sp && platform_sp->IsHost())
960 {
961 // If the debugserver is local and we aren't disabling STDIO, lets use
962 // a pseudo terminal to instead of relying on the 'O' packets for stdio
963 // since 'O' packets can really slow down debugging if the inferior
964 // does a lot of output.
Chaoren Lind3173f32015-05-29 19:52:29 +0000965 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
966 pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000967 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000968 FileSpec slave_name{pty.GetSlaveName(NULL, 0), false};
969
970 if (!stdin_file_spec)
971 stdin_file_spec = slave_name;
972
973 if (!stdout_file_spec)
974 stdout_file_spec = slave_name;
975
976 if (!stderr_file_spec)
977 stderr_file_spec = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000978 }
Todd Fiala75f47c32014-10-11 21:42:09 +0000979 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +0000980 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 +0000981 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000982 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
983 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
984 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Greg Clayton71337622011-02-24 22:24:29 +0000985 }
986
Todd Fiala75f47c32014-10-11 21:42:09 +0000987 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +0000988 log->Printf ("ProcessGDBRemote::%s final STDIO paths after all adjustments: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000989 __FUNCTION__,
Chaoren Lind3173f32015-05-29 19:52:29 +0000990 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
991 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
992 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
Todd Fiala75f47c32014-10-11 21:42:09 +0000993
Chaoren Lind3173f32015-05-29 19:52:29 +0000994 if (stdin_file_spec)
995 m_gdb_comm.SetSTDIN(stdin_file_spec);
996 if (stdout_file_spec)
997 m_gdb_comm.SetSTDOUT(stdout_file_spec);
998 if (stderr_file_spec)
999 m_gdb_comm.SetSTDERR(stderr_file_spec);
Greg Clayton71337622011-02-24 22:24:29 +00001000
1001 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
Jim Ingham106d0282014-06-25 02:32:56 +00001002 m_gdb_comm.SetDetachOnError (launch_flags & eLaunchFlagDetachOnError);
Greg Clayton71337622011-02-24 22:24:29 +00001003
Greg Claytonc4103b32011-05-08 04:53:50 +00001004 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Clayton71337622011-02-24 22:24:29 +00001005
Jason Molendaa3329782014-03-29 18:54:20 +00001006 const char * launch_event_data = launch_info.GetLaunchEventData();
1007 if (launch_event_data != NULL && *launch_event_data != '\0')
1008 m_gdb_comm.SendLaunchEventDataPacket (launch_event_data);
1009
Chaoren Lind3173f32015-05-29 19:52:29 +00001010 if (working_dir)
Greg Clayton71337622011-02-24 22:24:29 +00001011 {
1012 m_gdb_comm.SetWorkingDir (working_dir);
1013 }
1014
1015 // Send the environment and the program + arguments after we connect
Greg Clayton982c9762011-11-03 21:22:33 +00001016 const Args &environment = launch_info.GetEnvironmentEntries();
1017 if (environment.GetArgumentCount())
Greg Clayton71337622011-02-24 22:24:29 +00001018 {
Greg Clayton982c9762011-11-03 21:22:33 +00001019 size_t num_environment_entries = environment.GetArgumentCount();
1020 for (size_t i=0; i<num_environment_entries; ++i)
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001021 {
Greg Clayton982c9762011-11-03 21:22:33 +00001022 const char *env_entry = environment.GetArgumentAtIndex(i);
1023 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Clayton71337622011-02-24 22:24:29 +00001024 break;
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001025 }
Greg Clayton71337622011-02-24 22:24:29 +00001026 }
Greg Claytonb0b9fe62010-08-03 00:35:52 +00001027
Greg Clayton71337622011-02-24 22:24:29 +00001028 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001029 // Scope for the scoped timeout object
1030 GDBRemoteCommunication::ScopedTimeout timeout (m_gdb_comm, 10);
1031
1032 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
1033 if (arg_packet_err == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001034 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001035 std::string error_str;
1036 if (m_gdb_comm.GetLaunchSuccess (error_str))
1037 {
1038 SetID (m_gdb_comm.GetCurrentProcessID ());
1039 }
1040 else
1041 {
1042 error.SetErrorString (error_str.c_str());
1043 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001044 }
1045 else
1046 {
Tamas Berghammer912800c2015-02-24 10:23:39 +00001047 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001048 }
Greg Clayton71337622011-02-24 22:24:29 +00001049 }
Tamas Berghammer912800c2015-02-24 10:23:39 +00001050
Greg Clayton71337622011-02-24 22:24:29 +00001051 if (GetID() == LLDB_INVALID_PROCESS_ID)
1052 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001053 if (log)
1054 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton71337622011-02-24 22:24:29 +00001055 KillDebugserverProcess ();
1056 return error;
1057 }
1058
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001059 StringExtractorGDBRemote response;
1060 if (m_gdb_comm.GetStopReply(response))
Greg Clayton71337622011-02-24 22:24:29 +00001061 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001062 SetLastStopPacket(response);
Ewan Crawford78baa192015-05-13 09:18:18 +00001063 // '?' Packets must be handled differently in non-stop mode
1064 if (GetTarget().GetNonStopModeEnabled())
1065 HandleStopReplySequence();
1066
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001067 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
1068
1069 if (process_arch.IsValid())
Jason Molendac62bd7b2013-12-21 05:20:36 +00001070 {
Tamas Berghammere9f4dfe2015-03-13 10:32:42 +00001071 m_target.MergeArchitecture(process_arch);
1072 }
1073 else
1074 {
1075 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
1076 if (host_arch.IsValid())
1077 m_target.MergeArchitecture(host_arch);
Carlo Kok74389122013-10-14 07:09:13 +00001078 }
1079
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001080 SetPrivateState (SetThreadStopInfo (response));
Greg Clayton71337622011-02-24 22:24:29 +00001081
1082 if (!disable_stdio)
1083 {
1084 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Claytonee95ed52011-11-17 22:14:31 +00001085 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Clayton71337622011-02-24 22:24:29 +00001086 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001087 }
1088 }
Greg Claytonc235ac72011-08-09 05:20:29 +00001089 else
1090 {
Johnny Chen4c1e9202011-08-09 18:56:45 +00001091 if (log)
1092 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytonc235ac72011-08-09 05:20:29 +00001093 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001094 }
1095 else
1096 {
1097 // Set our user ID to an invalid process ID.
1098 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton982c9762011-11-03 21:22:33 +00001099 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
1100 exe_module->GetFileSpec().GetFilename().AsCString(),
1101 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001102 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001103 return error;
Greg Clayton4957bf62010-09-30 21:49:03 +00001104
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001105}
1106
1107
1108Error
Greg Claytonb766a732011-02-04 01:58:07 +00001109ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001110{
1111 Error error;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001112 // Only connect if we have a valid connect URL
Vince Harron1b5a74e2015-01-21 22:42:49 +00001113 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton00fe87b2013-12-05 22:58:22 +00001114
1115 if (connect_url && connect_url[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001116 {
Vince Harron1b5a74e2015-01-21 22:42:49 +00001117 if (log)
1118 log->Printf("ProcessGDBRemote::%s Connecting to %s", __FUNCTION__, connect_url);
Greg Clayton00fe87b2013-12-05 22:58:22 +00001119 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
1120 if (conn_ap.get())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001121 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001122 const uint32_t max_retry_count = 50;
1123 uint32_t retry_count = 0;
1124 while (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001125 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001126 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
1127 {
1128 m_gdb_comm.SetConnection (conn_ap.release());
1129 break;
1130 }
1131 else if (error.WasInterrupted())
1132 {
1133 // If we were interrupted, don't keep retrying.
1134 break;
1135 }
1136
1137 retry_count++;
1138
1139 if (retry_count >= max_retry_count)
1140 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001141
Greg Clayton00fe87b2013-12-05 22:58:22 +00001142 usleep (100000);
1143 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001144 }
1145 }
1146
1147 if (!m_gdb_comm.IsConnected())
1148 {
1149 if (error.Success())
1150 error.SetErrorString("not connected to remote gdb server");
1151 return error;
1152 }
1153
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001154
1155 // Start the communications read thread so all incoming data can be
1156 // parsed into packets and queued as they arrive.
1157 if (GetTarget().GetNonStopModeEnabled())
1158 m_gdb_comm.StartReadThread();
1159
Greg Clayton32e0a752011-03-30 18:16:51 +00001160 // We always seem to be able to open a connection to a local port
1161 // so we need to make sure we can then send data to it. If we can't
1162 // then we aren't actually connected to anything, so try and do the
1163 // handshake with the remote GDB server and make sure that goes
1164 // alright.
Greg Claytonfb909312013-11-23 01:58:15 +00001165 if (!m_gdb_comm.HandshakeWithServer (&error))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001166 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001167 m_gdb_comm.Disconnect();
1168 if (error.Success())
1169 error.SetErrorString("not connected to remote gdb server");
1170 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001171 }
Ewan Crawford78baa192015-05-13 09:18:18 +00001172
1173 // Send $QNonStop:1 packet on startup if required
1174 if (GetTarget().GetNonStopModeEnabled())
1175 m_gdb_comm.SetNonStopMode(true);
1176
Greg Claytonb30c50c2015-05-29 00:01:55 +00001177 m_gdb_comm.GetEchoSupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001178 m_gdb_comm.GetThreadSuffixSupported ();
Greg Clayton44633992012-04-10 03:22:03 +00001179 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001180 m_gdb_comm.GetHostInfo ();
1181 m_gdb_comm.GetVContSupported ('c');
Jim Inghamcd16df92012-07-20 21:37:13 +00001182 m_gdb_comm.GetVAttachOrWaitSupported();
Ewan Crawford78baa192015-05-13 09:18:18 +00001183
1184 // Ask the remote server for the default thread id
1185 if (GetTarget().GetNonStopModeEnabled())
1186 m_gdb_comm.GetDefaultThreadId(m_initial_tid);
1187
1188
Jim Ingham03afad82012-07-02 05:40:07 +00001189 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1190 for (size_t idx = 0; idx < num_cmds; idx++)
1191 {
1192 StringExtractorGDBRemote response;
Jim Ingham03afad82012-07-02 05:40:07 +00001193 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1194 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001195 return error;
1196}
1197
1198void
Jim Inghambb006ce2014-08-02 00:33:35 +00001199ProcessGDBRemote::DidLaunchOrAttach (ArchSpec& process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001200{
Greg Clayton5160ce52013-03-27 23:08:40 +00001201 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001202 if (log)
1203 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton93d3c8332011-02-16 04:46:07 +00001204 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001205 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001206 BuildDynamicRegisterInfo (false);
Greg Clayton3af9ea52010-11-18 05:57:03 +00001207
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001208 // See if the GDB server supports the qHostInfo information
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001209
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001210
1211 // See if the GDB server supports the qProcessInfo packet, if so
1212 // prefer that over the Host information as it will be more specific
1213 // to our process.
1214
Todd Fiala75f47c32014-10-11 21:42:09 +00001215 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1216 if (remote_process_arch.IsValid())
1217 {
1218 process_arch = remote_process_arch;
1219 if (log)
1220 log->Printf ("ProcessGDBRemote::%s gdb-remote had process architecture, using %s %s",
1221 __FUNCTION__,
1222 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1223 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1224 }
Jim Inghambb006ce2014-08-02 00:33:35 +00001225 else
Todd Fiala75f47c32014-10-11 21:42:09 +00001226 {
Jim Inghambb006ce2014-08-02 00:33:35 +00001227 process_arch = m_gdb_comm.GetHostArchitecture();
Todd Fiala75f47c32014-10-11 21:42:09 +00001228 if (log)
1229 log->Printf ("ProcessGDBRemote::%s gdb-remote did not have process architecture, using gdb-remote host architecture %s %s",
1230 __FUNCTION__,
1231 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1232 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1233 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001234
Jim Inghambb006ce2014-08-02 00:33:35 +00001235 if (process_arch.IsValid())
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001236 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001237 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Greg Claytond314e812011-03-23 00:09:55 +00001238 if (target_arch.IsValid())
1239 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001240 if (log)
1241 log->Printf ("ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1242 __FUNCTION__,
1243 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1244 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
1245
1246 // If the remote host is ARM and we have apple as the vendor, then
Greg Claytond314e812011-03-23 00:09:55 +00001247 // ARM executables and shared libraries can have mixed ARM architectures.
1248 // You can have an armv6 executable, and if the host is armv7, then the
1249 // system will load the best possible architecture for all shared libraries
1250 // it has, so we really need to take the remote host architecture as our
1251 // defacto architecture in this case.
1252
Jim Inghambb006ce2014-08-02 00:33:35 +00001253 if (process_arch.GetMachine() == llvm::Triple::arm &&
1254 process_arch.GetTriple().getVendor() == llvm::Triple::Apple)
Greg Claytond314e812011-03-23 00:09:55 +00001255 {
Jason Molenda921c01b2014-08-03 21:42:52 +00001256 GetTarget().SetArchitecture (process_arch);
Todd Fiala75f47c32014-10-11 21:42:09 +00001257 if (log)
1258 log->Printf ("ProcessGDBRemote::%s remote process is ARM/Apple, setting target arch to %s %s",
1259 __FUNCTION__,
1260 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1261 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001262 }
1263 else
1264 {
1265 // Fill in what is missing in the triple
Jim Inghambb006ce2014-08-02 00:33:35 +00001266 const llvm::Triple &remote_triple = process_arch.GetTriple();
Tamas Berghammere724af12015-03-13 10:32:37 +00001267 llvm::Triple new_target_triple = target_arch.GetTriple();
1268 if (new_target_triple.getVendorName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001269 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001270 new_target_triple.setVendor (remote_triple.getVendor());
Greg Claytond314e812011-03-23 00:09:55 +00001271
Tamas Berghammere724af12015-03-13 10:32:37 +00001272 if (new_target_triple.getOSName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001273 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001274 new_target_triple.setOS (remote_triple.getOS());
Greg Claytond314e812011-03-23 00:09:55 +00001275
Tamas Berghammere724af12015-03-13 10:32:37 +00001276 if (new_target_triple.getEnvironmentName().size() == 0)
1277 new_target_triple.setEnvironment (remote_triple.getEnvironment());
Greg Clayton70b57652011-05-15 01:25:55 +00001278 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001279
Tamas Berghammere724af12015-03-13 10:32:37 +00001280 ArchSpec new_target_arch = target_arch;
1281 new_target_arch.SetTriple(new_target_triple);
1282 GetTarget().SetArchitecture(new_target_arch);
1283 }
Greg Claytond314e812011-03-23 00:09:55 +00001284 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001285
1286 if (log)
1287 log->Printf ("ProcessGDBRemote::%s final target arch after adjustments for remote architecture: %s %s",
1288 __FUNCTION__,
1289 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1290 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001291 }
1292 else
1293 {
1294 // The target doesn't have a valid architecture yet, set it from
1295 // the architecture we got from the remote GDB server
Jason Molenda921c01b2014-08-03 21:42:52 +00001296 GetTarget().SetArchitecture (process_arch);
Greg Claytond314e812011-03-23 00:09:55 +00001297 }
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001298 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001299 }
1300}
1301
1302void
1303ProcessGDBRemote::DidLaunch ()
1304{
Jim Inghambb006ce2014-08-02 00:33:35 +00001305 ArchSpec process_arch;
1306 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001307}
1308
1309Error
Han Ming Ong84647042012-02-25 01:07:38 +00001310ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1311{
Todd Fiala75f47c32014-10-11 21:42:09 +00001312 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001313 Error error;
Todd Fiala75f47c32014-10-11 21:42:09 +00001314
1315 if (log)
1316 log->Printf ("ProcessGDBRemote::%s()", __FUNCTION__);
1317
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001318 // Clear out and clean up from any current state
1319 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001320 if (attach_pid != LLDB_INVALID_PROCESS_ID)
1321 {
Greg Clayton71337622011-02-24 22:24:29 +00001322 // Make sure we aren't already connected?
1323 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001324 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001325 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001326
1327 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001328 {
Greg Clayton71337622011-02-24 22:24:29 +00001329 const char *error_string = error.AsCString();
1330 if (error_string == NULL)
1331 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1332
1333 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001334 }
Greg Clayton71337622011-02-24 22:24:29 +00001335 }
1336
1337 if (error.Success())
1338 {
Jim Ingham106d0282014-06-25 02:32:56 +00001339 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
Todd Fiala75f47c32014-10-11 21:42:09 +00001340
Greg Clayton71337622011-02-24 22:24:29 +00001341 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001342 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Greg Clayton3b608422011-11-19 02:11:30 +00001343 SetID (attach_pid);
Greg Clayton71337622011-02-24 22:24:29 +00001344 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001345 }
1346 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001347
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001348 return error;
1349}
1350
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001351Error
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001352ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001353{
1354 Error error;
1355 // Clear out and clean up from any current state
1356 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001357
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001358 if (process_name && process_name[0])
1359 {
Greg Clayton71337622011-02-24 22:24:29 +00001360 // Make sure we aren't already connected?
1361 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001362 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001363 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001364
Greg Clayton71337622011-02-24 22:24:29 +00001365 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001366 {
Greg Clayton71337622011-02-24 22:24:29 +00001367 const char *error_string = error.AsCString();
1368 if (error_string == NULL)
1369 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001370
Greg Clayton71337622011-02-24 22:24:29 +00001371 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001372 }
Greg Clayton71337622011-02-24 22:24:29 +00001373 }
1374
1375 if (error.Success())
1376 {
1377 StreamString packet;
1378
Jim Ingham106d0282014-06-25 02:32:56 +00001379 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1380
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001381 if (attach_info.GetWaitForLaunch())
Jim Inghamcd16df92012-07-20 21:37:13 +00001382 {
1383 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1384 {
1385 packet.PutCString ("vAttachWait");
1386 }
1387 else
1388 {
1389 if (attach_info.GetIgnoreExisting())
1390 packet.PutCString("vAttachWait");
1391 else
1392 packet.PutCString ("vAttachOrWait");
1393 }
1394 }
Greg Clayton71337622011-02-24 22:24:29 +00001395 else
1396 packet.PutCString("vAttachName");
1397 packet.PutChar(';');
1398 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1399
1400 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1401
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001402 }
1403 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001404 return error;
1405}
1406
Greg Clayton5df78fa2015-05-23 03:54:53 +00001407void
1408ProcessGDBRemote::DidExit ()
Greg Claytonfbb76342013-11-20 21:07:01 +00001409{
Greg Clayton5df78fa2015-05-23 03:54:53 +00001410 // When we exit, disconnect from the GDB server communications
Greg Claytonfbb76342013-11-20 21:07:01 +00001411 m_gdb_comm.Disconnect();
Greg Claytonfbb76342013-11-20 21:07:01 +00001412}
1413
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001414void
Jim Inghambb006ce2014-08-02 00:33:35 +00001415ProcessGDBRemote::DidAttach (ArchSpec &process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001416{
Jim Inghambb006ce2014-08-02 00:33:35 +00001417 // If you can figure out what the architecture is, fill it in here.
1418 process_arch.Clear();
1419 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001420}
1421
Greg Clayton90ba8112012-12-05 00:16:59 +00001422
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001423Error
1424ProcessGDBRemote::WillResume ()
1425{
Greg Clayton71fc2a32011-02-12 06:28:37 +00001426 m_continue_c_tids.clear();
1427 m_continue_C_tids.clear();
1428 m_continue_s_tids.clear();
1429 m_continue_S_tids.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001430 return Error();
1431}
1432
1433Error
1434ProcessGDBRemote::DoResume ()
1435{
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001436 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001437 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001438 if (log)
1439 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytone5219662010-12-03 06:02:24 +00001440
1441 Listener listener ("gdb-remote.resume-packet-sent");
1442 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1443 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00001444 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1445
Greg Claytond1d06e42013-04-20 00:27:58 +00001446 const size_t num_threads = GetThreadList().GetSize();
1447
Greg Clayton71fc2a32011-02-12 06:28:37 +00001448 StreamString continue_packet;
1449 bool continue_packet_error = false;
1450 if (m_gdb_comm.HasAnyVContSupport ())
1451 {
Ewan Crawford78baa192015-05-13 09:18:18 +00001452 if (!GetTarget().GetNonStopModeEnabled() &&
1453 (m_continue_c_tids.size() == num_threads ||
Greg Claytone98008c2014-02-13 23:34:38 +00001454 (m_continue_c_tids.empty() &&
1455 m_continue_C_tids.empty() &&
1456 m_continue_s_tids.empty() &&
Ewan Crawford78baa192015-05-13 09:18:18 +00001457 m_continue_S_tids.empty())))
Greg Clayton71fc2a32011-02-12 06:28:37 +00001458 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001459 // All threads are continuing, just send a "c" packet
1460 continue_packet.PutCString ("c");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001461 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001462 else
1463 {
1464 continue_packet.PutCString ("vCont");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001465
Greg Claytond1d06e42013-04-20 00:27:58 +00001466 if (!m_continue_c_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001467 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001468 if (m_gdb_comm.GetVContSupported ('c'))
1469 {
1470 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)
1471 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1472 }
1473 else
1474 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001475 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001476
1477 if (!continue_packet_error && !m_continue_C_tids.empty())
1478 {
1479 if (m_gdb_comm.GetVContSupported ('C'))
1480 {
1481 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)
1482 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1483 }
1484 else
1485 continue_packet_error = true;
1486 }
Greg Claytone5219662010-12-03 06:02:24 +00001487
Greg Claytond1d06e42013-04-20 00:27:58 +00001488 if (!continue_packet_error && !m_continue_s_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001489 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001490 if (m_gdb_comm.GetVContSupported ('s'))
1491 {
1492 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)
1493 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1494 }
1495 else
1496 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001497 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001498
1499 if (!continue_packet_error && !m_continue_S_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001500 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001501 if (m_gdb_comm.GetVContSupported ('S'))
1502 {
1503 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)
1504 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1505 }
1506 else
1507 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001508 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001509
1510 if (continue_packet_error)
1511 continue_packet.GetString().clear();
Greg Clayton71fc2a32011-02-12 06:28:37 +00001512 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001513 }
1514 else
1515 continue_packet_error = true;
1516
1517 if (continue_packet_error)
1518 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001519 // Either no vCont support, or we tried to use part of the vCont
1520 // packet that wasn't supported by the remote GDB server.
1521 // We need to try and make a simple packet that can do our continue
Greg Clayton71fc2a32011-02-12 06:28:37 +00001522 const size_t num_continue_c_tids = m_continue_c_tids.size();
1523 const size_t num_continue_C_tids = m_continue_C_tids.size();
1524 const size_t num_continue_s_tids = m_continue_s_tids.size();
1525 const size_t num_continue_S_tids = m_continue_S_tids.size();
1526 if (num_continue_c_tids > 0)
1527 {
1528 if (num_continue_c_tids == num_threads)
1529 {
1530 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001531 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001532 continue_packet.PutChar ('c');
1533 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001534 }
1535 else if (num_continue_c_tids == 1 &&
1536 num_continue_C_tids == 0 &&
1537 num_continue_s_tids == 0 &&
1538 num_continue_S_tids == 0 )
1539 {
1540 // Only one thread is continuing
Greg Clayton8b82f082011-04-12 05:54:46 +00001541 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001542 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001543 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001544 }
1545 }
1546
Greg Clayton0c74e782011-06-24 03:21:43 +00001547 if (continue_packet_error && num_continue_C_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001548 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001549 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1550 num_continue_C_tids > 0 &&
1551 num_continue_s_tids == 0 &&
1552 num_continue_S_tids == 0 )
Greg Clayton71fc2a32011-02-12 06:28:37 +00001553 {
1554 const int continue_signo = m_continue_C_tids.front().second;
Greg Clayton0c74e782011-06-24 03:21:43 +00001555 // Only one thread is continuing
Greg Clayton71fc2a32011-02-12 06:28:37 +00001556 if (num_continue_C_tids > 1)
1557 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001558 // More that one thread with a signal, yet we don't have
1559 // vCont support and we are being asked to resume each
1560 // thread with a signal, we need to make sure they are
1561 // all the same signal, or we can't issue the continue
1562 // accurately with the current support...
1563 if (num_continue_C_tids > 1)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001564 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001565 continue_packet_error = false;
1566 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1567 {
1568 if (m_continue_C_tids[i].second != continue_signo)
1569 continue_packet_error = true;
1570 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001571 }
Greg Clayton0c74e782011-06-24 03:21:43 +00001572 if (!continue_packet_error)
1573 m_gdb_comm.SetCurrentThreadForRun (-1);
1574 }
1575 else
1576 {
1577 // Set the continue thread ID
1578 continue_packet_error = false;
1579 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001580 }
1581 if (!continue_packet_error)
1582 {
1583 // Add threads continuing with the same signo...
Greg Clayton71fc2a32011-02-12 06:28:37 +00001584 continue_packet.Printf("C%2.2x", continue_signo);
1585 }
1586 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001587 }
1588
Greg Clayton0c74e782011-06-24 03:21:43 +00001589 if (continue_packet_error && num_continue_s_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001590 {
1591 if (num_continue_s_tids == num_threads)
1592 {
1593 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001594 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001595 continue_packet.PutChar ('s');
1596 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001597 }
1598 else if (num_continue_c_tids == 0 &&
1599 num_continue_C_tids == 0 &&
1600 num_continue_s_tids == 1 &&
1601 num_continue_S_tids == 0 )
1602 {
1603 // Only one thread is stepping
Greg Clayton8b82f082011-04-12 05:54:46 +00001604 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001605 continue_packet.PutChar ('s');
Greg Clayton0c74e782011-06-24 03:21:43 +00001606 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001607 }
1608 }
1609
1610 if (!continue_packet_error && num_continue_S_tids > 0)
1611 {
1612 if (num_continue_S_tids == num_threads)
1613 {
1614 const int step_signo = m_continue_S_tids.front().second;
1615 // Are all threads trying to step with the same signal?
Greg Clayton0c74e782011-06-24 03:21:43 +00001616 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001617 if (num_continue_S_tids > 1)
1618 {
1619 for (size_t i=1; i<num_threads; ++i)
1620 {
1621 if (m_continue_S_tids[i].second != step_signo)
1622 continue_packet_error = true;
1623 }
1624 }
1625 if (!continue_packet_error)
1626 {
1627 // Add threads stepping with the same signo...
Greg Clayton8b82f082011-04-12 05:54:46 +00001628 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001629 continue_packet.Printf("S%2.2x", step_signo);
1630 }
1631 }
1632 else if (num_continue_c_tids == 0 &&
1633 num_continue_C_tids == 0 &&
1634 num_continue_s_tids == 0 &&
1635 num_continue_S_tids == 1 )
1636 {
1637 // Only one thread is stepping with signal
Greg Clayton8b82f082011-04-12 05:54:46 +00001638 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001639 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Clayton0c74e782011-06-24 03:21:43 +00001640 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001641 }
1642 }
1643 }
1644
1645 if (continue_packet_error)
1646 {
1647 error.SetErrorString ("can't make continue packet for this resume");
1648 }
1649 else
1650 {
1651 EventSP event_sp;
1652 TimeValue timeout;
1653 timeout = TimeValue::Now();
1654 timeout.OffsetWithSeconds (5);
Zachary Turneracee96a2014-09-23 18:32:09 +00001655 if (!m_async_thread.IsJoinable())
Jim Inghamb1e2e842012-04-12 18:49:31 +00001656 {
1657 error.SetErrorString ("Trying to resume but the async thread is dead.");
1658 if (log)
1659 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1660 return error;
1661 }
1662
Greg Clayton71fc2a32011-02-12 06:28:37 +00001663 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1664
1665 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Inghamb1e2e842012-04-12 18:49:31 +00001666 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001667 error.SetErrorString("Resume timed out.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00001668 if (log)
1669 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1670 }
1671 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1672 {
1673 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1674 if (log)
1675 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1676 return error;
1677 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001678 }
Greg Claytone5219662010-12-03 06:02:24 +00001679 }
1680
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001681 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001682}
1683
Greg Clayton9e920902012-04-10 02:25:43 +00001684void
Ewan Crawford78baa192015-05-13 09:18:18 +00001685ProcessGDBRemote::HandleStopReplySequence ()
1686{
1687 while(true)
1688 {
1689 // Send vStopped
1690 StringExtractorGDBRemote response;
1691 m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false);
1692
1693 // OK represents end of signal list
1694 if (response.IsOKResponse())
1695 break;
1696
1697 // If not OK or a normal packet we have a problem
1698 if (!response.IsNormalResponse())
1699 break;
1700
1701 SetLastStopPacket(response);
1702 }
1703}
1704
1705void
Greg Clayton9e920902012-04-10 02:25:43 +00001706ProcessGDBRemote::ClearThreadIDList ()
1707{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001708 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001709 m_thread_ids.clear();
1710}
1711
1712bool
1713ProcessGDBRemote::UpdateThreadIDList ()
1714{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001715 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001716 bool sequence_mutex_unavailable = false;
1717 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1718 if (sequence_mutex_unavailable)
1719 {
Greg Clayton9e920902012-04-10 02:25:43 +00001720 return false; // We just didn't get the list
1721 }
1722 return true;
1723}
1724
Greg Clayton9fc13552012-04-10 00:18:59 +00001725bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001726ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001727{
1728 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +00001729 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Clayton73b472d2010-10-27 03:32:59 +00001730 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +00001731 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton9e920902012-04-10 02:25:43 +00001732
1733 size_t num_thread_ids = m_thread_ids.size();
1734 // The "m_thread_ids" thread ID list should always be updated after each stop
1735 // reply packet, but in case it isn't, update it here.
1736 if (num_thread_ids == 0)
1737 {
1738 if (!UpdateThreadIDList ())
1739 return false;
1740 num_thread_ids = m_thread_ids.size();
1741 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001742
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001743 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001744 if (num_thread_ids > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001745 {
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001746 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001747 {
Greg Clayton9e920902012-04-10 02:25:43 +00001748 tid_t tid = m_thread_ids[i];
Greg Clayton160c9d82013-05-01 21:54:04 +00001749 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001750 if (!thread_sp)
Jim Inghamdee1bc92013-06-22 00:27:45 +00001751 {
Jim Ingham4f465cf2012-10-10 18:32:14 +00001752 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001753 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1754 log->Printf(
1755 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001756 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001757 thread_sp->GetID());
1758 }
1759 else
1760 {
1761 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1762 log->Printf(
1763 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001764 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001765 thread_sp->GetID());
1766 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001767 new_thread_list.AddThread(thread_sp);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001768 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001769 }
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001770
1771 // Whatever that is left in old_thread_list_copy are not
1772 // present in new_thread_list. Remove non-existent threads from internal id table.
1773 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1774 for (size_t i=0; i<old_num_thread_ids; i++)
1775 {
1776 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1777 if (old_thread_sp)
1778 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001779 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001780 m_thread_id_to_index_id_map.erase(old_thread_id);
1781 }
1782 }
1783
Greg Clayton9fc13552012-04-10 00:18:59 +00001784 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001785}
1786
1787
1788StateType
1789ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1790{
Greg Claytondd0e5a52011-06-02 22:22:38 +00001791 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001792 const char stop_type = stop_packet.GetChar();
1793 switch (stop_type)
1794 {
1795 case 'T':
1796 case 'S':
1797 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00001798 // This is a bit of a hack, but is is required. If we did exec, we
1799 // need to clear our thread lists and also know to rebuild our dynamic
1800 // register info before we lookup and threads and populate the expedited
1801 // register values so we need to know this right away so we can cleanup
1802 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00001803 const uint32_t stop_id = GetStopID();
1804 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00001805 {
1806 // Our first stop, make sure we have a process ID, and also make
1807 // sure we know about our registers
1808 if (GetID() == LLDB_INVALID_PROCESS_ID)
1809 {
Greg Claytonc574ede2011-03-10 02:26:48 +00001810 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00001811 if (pid != LLDB_INVALID_PROCESS_ID)
1812 SetID (pid);
1813 }
1814 BuildDynamicRegisterInfo (true);
1815 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001816 // Stop with signal and thread info
1817 const uint8_t signo = stop_packet.GetHexU8();
1818 std::string name;
1819 std::string value;
1820 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00001821 std::string reason;
1822 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001823 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00001824 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001825 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001826 ThreadSP thread_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001827 ThreadGDBRemote *gdb_thread = NULL;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001828
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001829 while (stop_packet.GetNameColonValue(name, value))
1830 {
1831 if (name.compare("metype") == 0)
1832 {
1833 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001834 exc_type = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001835 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001836 else if (name.compare("medata") == 0)
1837 {
1838 // exception data in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001839 exc_data.push_back(StringConvert::ToUInt64 (value.c_str(), 0, 16));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001840 }
1841 else if (name.compare("thread") == 0)
1842 {
1843 // thread in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001844 lldb::tid_t tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001845 // m_thread_list_real does have its own mutex, but we need to
1846 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1847 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1848 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1849 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
Greg Clayton160c9d82013-05-01 21:54:04 +00001850
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001851 if (!thread_sp)
Greg Claytond1d06e42013-04-20 00:27:58 +00001852 {
Greg Claytone576ab22011-02-15 00:19:15 +00001853 // Create the thread if we need to
Jim Ingham4f465cf2012-10-10 18:32:14 +00001854 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001855 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
1856 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1857 log->Printf ("ProcessGDBRemote::%s Adding new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1858 __FUNCTION__,
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001859 static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001860 thread_sp->GetID());
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001861
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001862 m_thread_list_real.AddThread(thread_sp);
Greg Claytone576ab22011-02-15 00:19:15 +00001863 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001864 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1865
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001866 }
Greg Clayton9e920902012-04-10 02:25:43 +00001867 else if (name.compare("threads") == 0)
1868 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001869 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001870 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00001871 // A comma separated list of all threads in the current
1872 // process that includes the thread for this stop reply
1873 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00001874 size_t comma_pos;
1875 lldb::tid_t tid;
1876 while ((comma_pos = value.find(',')) != std::string::npos)
1877 {
1878 value[comma_pos] = '\0';
1879 // thread in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001880 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00001881 if (tid != LLDB_INVALID_THREAD_ID)
1882 m_thread_ids.push_back (tid);
1883 value.erase(0, comma_pos + 1);
Greg Clayton9e920902012-04-10 02:25:43 +00001884 }
Vince Harron5275aaa2015-01-15 20:08:35 +00001885 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00001886 if (tid != LLDB_INVALID_THREAD_ID)
1887 m_thread_ids.push_back (tid);
1888 }
Greg Claytonde9d0492011-01-08 03:17:57 +00001889 else if (name.compare("hexname") == 0)
1890 {
1891 StringExtractor name_extractor;
1892 // Swap "value" over into "name_extractor"
1893 name_extractor.GetStringRef().swap(value);
1894 // Now convert the HEX bytes into a string value
1895 name_extractor.GetHexByteString (value);
1896 thread_name.swap (value);
1897 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001898 else if (name.compare("name") == 0)
1899 {
1900 thread_name.swap (value);
1901 }
Greg Clayton6f35f5c2010-09-09 06:32:46 +00001902 else if (name.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001903 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001904 thread_dispatch_qaddr = StringConvert::ToUInt64 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001905 }
Greg Claytona658fd22011-06-04 01:26:29 +00001906 else if (name.compare("reason") == 0)
1907 {
1908 reason.swap(value);
1909 }
1910 else if (name.compare("description") == 0)
1911 {
1912 StringExtractor desc_extractor;
1913 // Swap "value" over into "name_extractor"
1914 desc_extractor.GetStringRef().swap(value);
1915 // Now convert the HEX bytes into a string value
Chaoren Lin28e57422015-02-03 01:51:25 +00001916 desc_extractor.GetHexByteString (value);
1917 description.swap(value);
Greg Claytona658fd22011-06-04 01:26:29 +00001918 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001919 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1920 {
1921 // We have a register number that contains an expedited
1922 // register value. Lets supply this register to our thread
1923 // so it won't have to go and read it.
Greg Clayton160c9d82013-05-01 21:54:04 +00001924 if (gdb_thread)
Greg Clayton3e06bd92011-01-09 21:07:35 +00001925 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001926 uint32_t reg = StringConvert::ToUInt32 (name.c_str(), UINT32_MAX, 16);
Greg Clayton3e06bd92011-01-09 21:07:35 +00001927
1928 if (reg != UINT32_MAX)
1929 {
1930 StringExtractor reg_value_extractor;
1931 // Swap "value" over into "reg_value_extractor"
1932 reg_value_extractor.GetStringRef().swap(value);
Greg Clayton160c9d82013-05-01 21:54:04 +00001933 if (!gdb_thread->PrivateSetRegisterValue (reg, reg_value_extractor))
Greg Claytone576ab22011-02-15 00:19:15 +00001934 {
1935 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1936 name.c_str(),
1937 reg,
1938 reg,
1939 reg_value_extractor.GetStringRef().c_str(),
1940 stop_packet.GetStringRef().c_str());
1941 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001942 }
1943 }
1944 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001945 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001946
Hafiz Abid Qadeer673b4a32014-02-20 10:23:20 +00001947 // If the response is old style 'S' packet which does not provide us with thread information
1948 // then update the thread list and choose the first one.
1949 if (!thread_sp)
1950 {
1951 UpdateThreadIDList ();
1952
1953 if (!m_thread_ids.empty ())
1954 {
1955 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1956 thread_sp = m_thread_list_real.FindThreadByProtocolID (m_thread_ids.front (), false);
1957 if (thread_sp)
1958 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get ());
1959 }
1960 }
1961
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001962 if (thread_sp)
1963 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001964 // Clear the stop info just in case we don't set it to anything
1965 thread_sp->SetStopInfo (StopInfoSP());
1966
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001967 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Inghamdd2fe7a2011-01-28 02:23:12 +00001968 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001969 if (exc_type != 0)
1970 {
Greg Clayton1a65ae12011-01-25 23:55:37 +00001971 const size_t exc_data_size = exc_data.size();
Greg Claytonf4b47e12010-08-04 01:40:35 +00001972
Greg Clayton160c9d82013-05-01 21:54:04 +00001973 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1974 exc_type,
1975 exc_data_size,
1976 exc_data_size >= 1 ? exc_data[0] : 0,
1977 exc_data_size >= 2 ? exc_data[1] : 0,
1978 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001979 }
Greg Claytona658fd22011-06-04 01:26:29 +00001980 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001981 {
Greg Claytona658fd22011-06-04 01:26:29 +00001982 bool handled = false;
Greg Clayton8cda7f02013-05-21 21:55:59 +00001983 bool did_exec = false;
Greg Claytona658fd22011-06-04 01:26:29 +00001984 if (!reason.empty())
1985 {
1986 if (reason.compare("trace") == 0)
1987 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001988 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Greg Claytona658fd22011-06-04 01:26:29 +00001989 handled = true;
1990 }
1991 else if (reason.compare("breakpoint") == 0)
1992 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001993 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1994 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Claytona658fd22011-06-04 01:26:29 +00001995 if (bp_site_sp)
1996 {
1997 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1998 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1999 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
Jim Ingham54cc6e42012-07-11 21:41:19 +00002000 handled = true;
Greg Clayton160c9d82013-05-01 21:54:04 +00002001 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00002002 {
Greg Clayton160c9d82013-05-01 21:54:04 +00002003 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00002004 }
2005 else
2006 {
2007 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00002008 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00002009 }
2010 }
Greg Claytona658fd22011-06-04 01:26:29 +00002011 }
2012 else if (reason.compare("trap") == 0)
2013 {
2014 // Let the trap just use the standard signal stop reason below...
2015 }
2016 else if (reason.compare("watchpoint") == 0)
2017 {
Chaoren Lin18fe6402015-02-03 01:51:47 +00002018 StringExtractor desc_extractor(description.c_str());
2019 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
2020 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
2021 watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
2022 if (wp_addr != LLDB_INVALID_ADDRESS)
2023 {
2024 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2025 if (wp_sp)
2026 {
2027 wp_sp->SetHardwareIndex(wp_index);
2028 watch_id = wp_sp->GetID();
2029 }
2030 }
2031 if (watch_id == LLDB_INVALID_WATCH_ID)
2032 {
2033 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_WATCHPOINTS));
2034 if (log) log->Printf ("failed to find watchpoint");
2035 }
Greg Clayton160c9d82013-05-01 21:54:04 +00002036 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
Greg Claytona658fd22011-06-04 01:26:29 +00002037 handled = true;
2038 }
2039 else if (reason.compare("exception") == 0)
2040 {
Greg Clayton160c9d82013-05-01 21:54:04 +00002041 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00002042 handled = true;
2043 }
Greg Clayton15fc2be2013-05-21 01:00:52 +00002044 else if (reason.compare("exec") == 0)
2045 {
Greg Clayton8cda7f02013-05-21 21:55:59 +00002046 did_exec = true;
Greg Clayton15fc2be2013-05-21 01:00:52 +00002047 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
2048 handled = true;
2049 }
Greg Claytona658fd22011-06-04 01:26:29 +00002050 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00002051
Jim Ingham40083a42014-02-24 19:49:46 +00002052 if (!handled && signo && did_exec == false)
Greg Claytona658fd22011-06-04 01:26:29 +00002053 {
2054 if (signo == SIGTRAP)
2055 {
2056 // Currently we are going to assume SIGTRAP means we are either
2057 // hitting a breakpoint or hardware single stepping.
Jim Ingham54cc6e42012-07-11 21:41:19 +00002058 handled = true;
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +00002059 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
Greg Clayton160c9d82013-05-01 21:54:04 +00002060 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00002061
Greg Claytona658fd22011-06-04 01:26:29 +00002062 if (bp_site_sp)
2063 {
2064 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2065 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2066 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
Greg Clayton160c9d82013-05-01 21:54:04 +00002067 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00002068 {
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +00002069 if(m_breakpoint_pc_offset != 0)
2070 thread_sp->GetRegisterContext()->SetPC(pc);
Greg Clayton160c9d82013-05-01 21:54:04 +00002071 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00002072 }
2073 else
2074 {
2075 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00002076 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00002077 }
2078 }
Jim Ingham54cc6e42012-07-11 21:41:19 +00002079 else
Greg Claytona658fd22011-06-04 01:26:29 +00002080 {
Jim Ingham4dc613b2012-10-27 02:52:04 +00002081 // If we were stepping then assume the stop was the result of the trace. If we were
2082 // not stepping then report the SIGTRAP.
2083 // FIXME: We are still missing the case where we single step over a trap instruction.
Greg Clayton160c9d82013-05-01 21:54:04 +00002084 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
2085 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Jim Ingham4dc613b2012-10-27 02:52:04 +00002086 else
Pavel Labathc4e25c92015-05-29 10:13:03 +00002087 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00002088 }
2089 }
2090 if (!handled)
Pavel Labathc4e25c92015-05-29 10:13:03 +00002091 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo, description.c_str()));
Jason Molenda8214b012013-04-25 01:33:46 +00002092 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00002093
Greg Claytona658fd22011-06-04 01:26:29 +00002094 if (!description.empty())
2095 {
Greg Clayton160c9d82013-05-01 21:54:04 +00002096 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
Greg Claytona658fd22011-06-04 01:26:29 +00002097 if (stop_info_sp)
2098 {
Pavel Labath48fca3b2015-05-15 10:14:51 +00002099 const char *stop_info_desc = stop_info_sp->GetDescription();
2100 if (!stop_info_desc || !stop_info_desc[0])
2101 stop_info_sp->SetDescription (description.c_str());
Greg Clayton3418c852011-08-10 02:10:13 +00002102 }
Greg Claytona658fd22011-06-04 01:26:29 +00002103 else
2104 {
Greg Clayton160c9d82013-05-01 21:54:04 +00002105 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00002106 }
2107 }
2108 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002109 }
2110 return eStateStopped;
2111 }
2112 break;
2113
2114 case 'W':
Todd Fialaff6131a2014-05-19 04:57:23 +00002115 case 'X':
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002116 // process exited
2117 return eStateExited;
2118
2119 default:
2120 break;
2121 }
2122 return eStateInvalid;
2123}
2124
2125void
2126ProcessGDBRemote::RefreshStateAfterStop ()
2127{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002128 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00002129 m_thread_ids.clear();
2130 // Set the thread stop info. It might have a "threads" key whose value is
2131 // a list of all thread IDs in the current process, so m_thread_ids might
2132 // get set.
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002133
2134 // Scope for the lock
2135 {
2136 // Lock the thread stack while we access it
2137 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
2138 // Get the number of stop packets on the stack
2139 int nItems = m_stop_packet_stack.size();
2140 // Iterate over them
2141 for (int i = 0; i < nItems; i++)
2142 {
2143 // Get the thread stop info
2144 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2145 // Process thread stop info
2146 SetThreadStopInfo(stop_info);
2147 }
2148 // Clear the thread stop stack
2149 m_stop_packet_stack.clear();
2150 }
2151
Greg Clayton9e920902012-04-10 02:25:43 +00002152 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2153 if (m_thread_ids.empty())
2154 {
2155 // No, we need to fetch the thread list manually
2156 UpdateThreadIDList();
2157 }
2158
Ewan Crawford78baa192015-05-13 09:18:18 +00002159 // If we have queried for a default thread id
2160 if (m_initial_tid != LLDB_INVALID_THREAD_ID)
2161 {
2162 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2163 m_initial_tid = LLDB_INVALID_THREAD_ID;
2164 }
2165
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002166 // Let all threads recover from stopping and do any clean up based
2167 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002168 m_thread_list_real.RefreshStateAfterStop();
Greg Clayton9e920902012-04-10 02:25:43 +00002169
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002170}
2171
2172Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002173ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002174{
2175 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002176
Greg Clayton6ed95942011-01-22 07:12:45 +00002177 bool timed_out = false;
2178 Mutex::Locker locker;
Greg Clayton513c26c2011-01-29 07:10:55 +00002179
2180 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002181 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002182 // We are being asked to halt during an attach. We need to just close
2183 // our file handle and debugserver will go away, and we can be done...
2184 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00002185 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002186 else
2187 {
Greg Clayton2687cd12012-03-29 01:55:41 +00002188 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton513c26c2011-01-29 07:10:55 +00002189 {
2190 if (timed_out)
2191 error.SetErrorString("timed out sending interrupt packet");
2192 else
2193 error.SetErrorString("unknown error sending interrupt packet");
2194 }
Greg Clayton2687cd12012-03-29 01:55:41 +00002195
2196 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton513c26c2011-01-29 07:10:55 +00002197 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002198 return error;
2199}
2200
2201Error
Jim Inghamacff8952013-05-02 00:27:30 +00002202ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002203{
2204 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002205 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00002206 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00002207 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2208
Jim Inghamacff8952013-05-02 00:27:30 +00002209 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002210 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002211 {
Jim Inghamacff8952013-05-02 00:27:30 +00002212 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002213 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
2214 else
Jim Inghamacff8952013-05-02 00:27:30 +00002215 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00002216 }
Jim Inghamacff8952013-05-02 00:27:30 +00002217
2218 if (!error.Success())
2219 return error;
2220
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002221 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00002222 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002223
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002224 SetPrivateState (eStateDetached);
2225 ResumePrivateStateThread();
2226
2227 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00002228 return error;
2229}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002230
Jim Ingham43c555d2012-07-04 00:35:43 +00002231
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002232Error
2233ProcessGDBRemote::DoDestroy ()
2234{
2235 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002236 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002237 if (log)
2238 log->Printf ("ProcessGDBRemote::DoDestroy()");
2239
Jim Ingham43c555d2012-07-04 00:35:43 +00002240 // There is a bug in older iOS debugservers where they don't shut down the process
2241 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
2242 // this can cause problems with restarting. So we check to see if any of our threads are stopped
2243 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
2244 // destroy it again.
2245 //
2246 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
2247 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
2248 // the debugservers with this bug are equal. There really should be a better way to test this!
2249 //
2250 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
2251 // get called here to destroy again and we're still at a breakpoint or exception, then we should
2252 // just do the straight-forward kill.
2253 //
2254 // And of course, if we weren't able to stop the process by the time we get here, it isn't
2255 // necessary (or helpful) to do any of this.
2256
2257 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
2258 {
2259 PlatformSP platform_sp = GetTarget().GetPlatform();
2260
2261 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2262 if (platform_sp
2263 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00002264 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00002265 {
2266 if (m_destroy_tried_resuming)
2267 {
2268 if (log)
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002269 log->PutCString ("ProcessGDBRemote::DoDestroy() - Tried resuming to destroy once already, not doing it again.");
Jim Ingham43c555d2012-07-04 00:35:43 +00002270 }
2271 else
2272 {
2273 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
2274 // but we really need it to happen here and it doesn't matter if we do it twice.
2275 m_thread_list.DiscardThreadPlans();
2276 DisableAllBreakpointSites();
2277
2278 bool stop_looks_like_crash = false;
2279 ThreadList &threads = GetThreadList();
2280
2281 {
Jim Ingham45350372012-09-11 00:08:52 +00002282 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002283
2284 size_t num_threads = threads.GetSize();
2285 for (size_t i = 0; i < num_threads; i++)
2286 {
2287 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002288 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002289 StopReason reason = eStopReasonInvalid;
2290 if (stop_info_sp)
2291 reason = stop_info_sp->GetStopReason();
2292 if (reason == eStopReasonBreakpoint
2293 || reason == eStopReasonException)
2294 {
2295 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002296 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
2297 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00002298 stop_info_sp->GetDescription());
2299 stop_looks_like_crash = true;
2300 break;
2301 }
2302 }
2303 }
2304
2305 if (stop_looks_like_crash)
2306 {
2307 if (log)
2308 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
2309 m_destroy_tried_resuming = true;
2310
2311 // If we are going to run again before killing, it would be good to suspend all the threads
2312 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
2313 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
2314 // have to run the risk of letting those threads proceed a bit.
2315
2316 {
Jim Ingham45350372012-09-11 00:08:52 +00002317 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002318
2319 size_t num_threads = threads.GetSize();
2320 for (size_t i = 0; i < num_threads; i++)
2321 {
2322 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002323 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002324 StopReason reason = eStopReasonInvalid;
2325 if (stop_info_sp)
2326 reason = stop_info_sp->GetStopReason();
2327 if (reason != eStopReasonBreakpoint
2328 && reason != eStopReasonException)
2329 {
2330 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002331 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
2332 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00002333 thread_sp->SetResumeState(eStateSuspended);
2334 }
2335 }
2336 }
2337 Resume ();
Jason Molendaede31932015-04-17 05:01:58 +00002338 return Destroy(false);
Jim Ingham43c555d2012-07-04 00:35:43 +00002339 }
2340 }
2341 }
2342 }
2343
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002344 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00002345 int exit_status = SIGABRT;
2346 std::string exit_string;
2347
Greg Clayton6ed95942011-01-22 07:12:45 +00002348 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002349 {
Jim Inghamaab78372011-10-28 01:11:35 +00002350 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00002351 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002352 StringExtractorGDBRemote response;
2353 bool send_async = true;
Tamas Berghammer912800c2015-02-24 10:23:39 +00002354 GDBRemoteCommunication::ScopedTimeout (m_gdb_comm, 3);
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002355
Greg Clayton3dedae12013-12-06 21:45:27 +00002356 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton513c26c2011-01-29 07:10:55 +00002357 {
2358 char packet_cmd = response.GetChar(0);
2359
2360 if (packet_cmd == 'W' || packet_cmd == 'X')
2361 {
Jim Inghameac0aa42014-02-21 22:36:11 +00002362#if defined(__APPLE__)
Jim Ingham9d67cc52014-02-21 22:35:29 +00002363 // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off
2364 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill
2365 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns
2366 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap
2367 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of
2368 // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2369 // Anyway, so call waitpid here to finally reap it.
2370 PlatformSP platform_sp(GetTarget().GetPlatform());
2371 if (platform_sp && platform_sp->IsHost())
2372 {
2373 int status;
2374 ::pid_t reap_pid;
2375 reap_pid = waitpid (GetID(), &status, WNOHANG);
2376 if (log)
2377 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2378 }
2379#endif
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002380 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002381 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00002382 exit_status = response.GetHexU8();
2383 }
2384 else
2385 {
2386 if (log)
2387 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2388 exit_string.assign("got unexpected response to k packet: ");
2389 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00002390 }
2391 }
2392 else
2393 {
Jim Inghambabfc382012-06-06 00:32:39 +00002394 if (log)
2395 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2396 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00002397 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002398 }
Jim Inghambabfc382012-06-06 00:32:39 +00002399 else
2400 {
2401 if (log)
Ed Masteb3a53332014-03-17 17:05:22 +00002402 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching");
Jim Inghamcfc09352012-07-27 23:57:19 +00002403 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00002404 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002405 }
Jim Inghambabfc382012-06-06 00:32:39 +00002406 else
2407 {
2408 // If we missed setting the exit status on the way out, do it here.
2409 // NB set exit status can be called multiple times, the first one sets the status.
2410 exit_string.assign("destroying when not connected to debugserver");
2411 }
2412
2413 SetExitStatus(exit_status, exit_string.c_str());
2414
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002415 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002416 KillDebugserverProcess ();
2417 return error;
2418}
2419
Greg Clayton8cda7f02013-05-21 21:55:59 +00002420void
2421ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2422{
Greg Clayton8cda7f02013-05-21 21:55:59 +00002423 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2424 if (did_exec)
2425 {
2426 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2427 if (log)
2428 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2429
2430 m_thread_list_real.Clear();
2431 m_thread_list.Clear();
2432 BuildDynamicRegisterInfo (true);
2433 m_gdb_comm.ResetDiscoverableSettings();
2434 }
Ewan Crawford9aa2da002015-05-27 14:12:34 +00002435
2436 // Scope the lock
2437 {
2438 // Lock the thread stack while we access it
2439 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
2440 // Add this stop packet to the stop packet stack
2441 // This stack will get popped and examined when we switch to the
2442 // Stopped state
2443 m_stop_packet_stack.push_back(response);
2444 }
Greg Clayton8cda7f02013-05-21 21:55:59 +00002445}
2446
2447
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002448//------------------------------------------------------------------
2449// Process Queries
2450//------------------------------------------------------------------
2451
2452bool
2453ProcessGDBRemote::IsAlive ()
2454{
Greg Clayton10177aa2010-12-08 05:08:21 +00002455 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002456}
2457
2458addr_t
2459ProcessGDBRemote::GetImageInfoAddress()
2460{
Aidan Doddsc0c83852015-05-08 09:36:31 +00002461 // request the link map address via the $qShlibInfoAddr packet
2462 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2463
2464 // the loaded module list can also provides a link map address
2465 if (addr == LLDB_INVALID_ADDRESS)
2466 {
2467 GDBLoadedModuleInfoList list;
2468 if (GetLoadedModuleList (list).Success())
2469 addr = list.m_link_map;
2470 }
2471
2472 return addr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002473}
2474
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002475//------------------------------------------------------------------
2476// Process Memory
2477//------------------------------------------------------------------
2478size_t
2479ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2480{
Jason Molenda6076bf42014-05-06 04:34:52 +00002481 GetMaxMemorySize ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002482 if (size > m_max_memory_size)
2483 {
2484 // Keep memory read sizes down to a sane limit. This function will be
2485 // called multiple times in order to complete the task by
2486 // lldb_private::Process so it is ok to do this.
2487 size = m_max_memory_size;
2488 }
2489
2490 char packet[64];
Jason Molenda6076bf42014-05-06 04:34:52 +00002491 int packet_len;
2492 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2493 if (binary_memory_read)
2494 {
2495 packet_len = ::snprintf (packet, sizeof(packet), "x0x%" PRIx64 ",0x%" PRIx64, (uint64_t)addr, (uint64_t)size);
2496 }
2497 else
2498 {
2499 packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
2500 }
Andy Gibbsa297a972013-06-19 19:04:53 +00002501 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002502 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002503 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002504 {
Greg Clayton576d8832011-03-22 04:00:09 +00002505 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002506 {
2507 error.Clear();
Jason Molenda6076bf42014-05-06 04:34:52 +00002508 if (binary_memory_read)
2509 {
2510 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any
2511 // 0x7d character escaping that was present in the packet
2512
2513 size_t data_received_size = response.GetBytesLeft();
2514 if (data_received_size > size)
2515 {
2516 // Don't write past the end of BUF if the remote debug server gave us too
2517 // much data for some reason.
2518 data_received_size = size;
2519 }
2520 memcpy (buf, response.GetStringRef().data(), data_received_size);
2521 return data_received_size;
2522 }
2523 else
2524 {
2525 return response.GetHexBytes(buf, size, '\xdd');
2526 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002527 }
Greg Clayton576d8832011-03-22 04:00:09 +00002528 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002529 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002530 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002531 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002532 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002533 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002534 }
2535 else
2536 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002537 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002538 }
2539 return 0;
2540}
2541
2542size_t
2543ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2544{
Jason Molenda6076bf42014-05-06 04:34:52 +00002545 GetMaxMemorySize ();
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002546 if (size > m_max_memory_size)
2547 {
2548 // Keep memory read sizes down to a sane limit. This function will be
2549 // called multiple times in order to complete the task by
2550 // lldb_private::Process so it is ok to do this.
2551 size = m_max_memory_size;
2552 }
2553
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002554 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00002555 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Clayton7fb56d02011-02-01 01:31:41 +00002556 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002557 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002558 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002559 {
Greg Clayton576d8832011-03-22 04:00:09 +00002560 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002561 {
2562 error.Clear();
2563 return size;
2564 }
Greg Clayton576d8832011-03-22 04:00:09 +00002565 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002566 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002567 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002568 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002569 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002570 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 +00002571 }
2572 else
2573 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002574 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002575 }
2576 return 0;
2577}
2578
2579lldb::addr_t
2580ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2581{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00002582 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_EXPRESSIONS));
Greg Clayton2a48f522011-05-14 01:50:35 +00002583 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2584
Greg Clayton70b57652011-05-15 01:25:55 +00002585 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton2a48f522011-05-14 01:50:35 +00002586 switch (supported)
2587 {
2588 case eLazyBoolCalculate:
2589 case eLazyBoolYes:
2590 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2591 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2592 return allocated_addr;
2593
2594 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002595 // Call mmap() to create memory in the inferior..
2596 unsigned prot = 0;
2597 if (permissions & lldb::ePermissionsReadable)
2598 prot |= eMmapProtRead;
2599 if (permissions & lldb::ePermissionsWritable)
2600 prot |= eMmapProtWrite;
2601 if (permissions & lldb::ePermissionsExecutable)
2602 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00002603
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002604 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2605 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2606 m_addr_to_mmap_size[allocated_addr] = size;
2607 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002608 {
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002609 allocated_addr = LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00002610 if (log)
2611 log->Printf ("ProcessGDBRemote::%s no direct stub support for memory allocation, and InferiorCallMmap also failed - is stub missing register context save/restore capability?", __FUNCTION__);
2612 }
Greg Clayton2a48f522011-05-14 01:50:35 +00002613 break;
2614 }
2615
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002616 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00002617 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002618 else
2619 error.Clear();
2620 return allocated_addr;
2621}
2622
2623Error
Greg Clayton46fb5582011-11-18 07:03:08 +00002624ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2625 MemoryRegionInfo &region_info)
2626{
2627
2628 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2629 return error;
2630}
2631
2632Error
Johnny Chen64637202012-05-23 21:09:52 +00002633ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2634{
2635
2636 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2637 return error;
2638}
2639
2640Error
Enrico Granataf04a2192012-07-13 23:18:48 +00002641ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2642{
2643 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2644 return error;
2645}
2646
2647Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002648ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2649{
2650 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00002651 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2652
2653 switch (supported)
2654 {
2655 case eLazyBoolCalculate:
2656 // We should never be deallocating memory without allocating memory
2657 // first so we should never get eLazyBoolCalculate
2658 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2659 break;
2660
2661 case eLazyBoolYes:
2662 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00002663 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002664 break;
2665
2666 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002667 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00002668 {
2669 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002670 if (pos != m_addr_to_mmap_size.end() &&
2671 InferiorCallMunmap(this, addr, pos->second))
2672 m_addr_to_mmap_size.erase (pos);
2673 else
Daniel Malead01b2952012-11-29 21:49:15 +00002674 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002675 }
2676 break;
2677 }
2678
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002679 return error;
2680}
2681
2682
2683//------------------------------------------------------------------
2684// Process STDIO
2685//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002686size_t
2687ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2688{
2689 if (m_stdio_communication.IsConnected())
2690 {
2691 ConnectionStatus status;
2692 m_stdio_communication.Write(src, src_len, status, NULL);
2693 }
Vince Harrondf3f00f2015-02-10 21:09:04 +00002694 else if (m_stdin_forward)
Vince Harrone0be4252015-02-06 18:32:57 +00002695 {
2696 m_gdb_comm.SendStdinNotification(src, src_len);
2697 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002698 return 0;
2699}
2700
2701Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002702ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002703{
2704 Error error;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002705 assert(bp_site != NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002706
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002707 // Get logging info
2708 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002709 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002710
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002711 // Get the breakpoint address
2712 const addr_t addr = bp_site->GetLoadAddress();
2713
2714 // Log that a breakpoint was requested
2715 if (log)
2716 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
2717
2718 // Breakpoint already exists and is enabled
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002719 if (bp_site->IsEnabled())
2720 {
2721 if (log)
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002722 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 +00002723 return error;
2724 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002725
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002726 // Get the software breakpoint trap opcode size
2727 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2728
2729 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
2730 // is supported by the remote stub. These are set to true by default, and later set to false
2731 // only after we receive an unimplemented response when sending a breakpoint packet. This means
2732 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
2733 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
2734 // indicates if the user specifically asked for hardware breakpoints. If true then we will
2735 // skip over software breakpoints.
2736 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
2737 {
2738 // Try to send off a software breakpoint packet ($Z0)
2739 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002740 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002741 // The breakpoint was placed successfully
2742 bp_site->SetEnabled(true);
2743 bp_site->SetType(BreakpointSite::eExternal);
Greg Claytoneb023e72013-10-11 19:48:25 +00002744 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002745 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002746
2747 // SendGDBStoppointTypePacket() will return an error if it was unable to set this
2748 // breakpoint. We need to differentiate between a error specific to placing this breakpoint
2749 // or if we have learned that this breakpoint type is unsupported. To do this, we
2750 // must test the support boolean for this breakpoint type to see if it now indicates that
2751 // this breakpoint type is unsupported. If they are still supported then we should return
2752 // with the error code. If they are now unsupported, then we would like to fall through
2753 // and try another form of breakpoint.
2754 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
2755 return error;
2756
2757 // We reach here when software breakpoints have been found to be unsupported. For future
2758 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
2759 // known not to be supported.
2760 if (log)
2761 log->Printf("Software breakpoints are unsupported");
2762
2763 // So we will fall through and try a hardware breakpoint
2764 }
2765
2766 // The process of setting a hardware breakpoint is much the same as above. We check the
2767 // supported boolean for this breakpoint type, and if it is thought to be supported then we
2768 // will try to set this breakpoint with a hardware breakpoint.
2769 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
2770 {
2771 // Try to send off a hardware breakpoint packet ($Z1)
2772 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002773 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002774 // The breakpoint was placed successfully
2775 bp_site->SetEnabled(true);
2776 bp_site->SetType(BreakpointSite::eHardware);
2777 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002778 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002779
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002780 // Check if the error was something other then an unsupported breakpoint type
2781 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
2782 {
2783 // Unable to set this hardware breakpoint
2784 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
2785 return error;
2786 }
2787
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002788 // We will reach here when the stub gives an unsupported response to a hardware breakpoint
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002789 if (log)
2790 log->Printf("Hardware breakpoints are unsupported");
2791
2792 // Finally we will falling through to a #trap style breakpoint
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002793 }
2794
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002795 // Don't fall through when hardware breakpoints were specifically requested
2796 if (bp_site->HardwareRequired())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002797 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002798 error.SetErrorString("hardware breakpoints are not supported");
2799 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002800 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002801
2802 // As a last resort we want to place a manual breakpoint. An instruction
2803 // is placed into the process memory using memory write packets.
2804 return EnableSoftwareBreakpoint(bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002805}
2806
2807Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002808ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002809{
2810 Error error;
2811 assert (bp_site != NULL);
2812 addr_t addr = bp_site->GetLoadAddress();
2813 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00002814 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002815 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002816 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002817
2818 if (bp_site->IsEnabled())
2819 {
2820 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2821
Greg Clayton8b82f082011-04-12 05:54:46 +00002822 BreakpointSite::Type bp_type = bp_site->GetType();
2823 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002824 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002825 case BreakpointSite::eSoftware:
2826 error = DisableSoftwareBreakpoint (bp_site);
2827 break;
2828
2829 case BreakpointSite::eHardware:
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002830 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00002831 error.SetErrorToGenericError();
2832 break;
2833
2834 case BreakpointSite::eExternal:
Jim Inghama04ef752014-03-07 11:18:02 +00002835 {
2836 GDBStoppointType stoppoint_type;
2837 if (bp_site->IsHardware())
2838 stoppoint_type = eBreakpointHardware;
2839 else
2840 stoppoint_type = eBreakpointSoftware;
2841
2842 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00002843 error.SetErrorToGenericError();
Jim Inghama04ef752014-03-07 11:18:02 +00002844 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002845 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002846 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002847 if (error.Success())
2848 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002849 }
2850 else
2851 {
2852 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002853 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 +00002854 return error;
2855 }
2856
2857 if (error.Success())
2858 error.SetErrorToGenericError();
2859 return error;
2860}
2861
Johnny Chen11309a32011-09-06 22:38:36 +00002862// Pre-requisite: wp != NULL.
2863static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00002864GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00002865{
2866 assert(wp);
2867 bool watch_read = wp->WatchpointRead();
2868 bool watch_write = wp->WatchpointWrite();
2869
2870 // watch_read and watch_write cannot both be false.
2871 assert(watch_read || watch_write);
2872 if (watch_read && watch_write)
2873 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00002874 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00002875 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00002876 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00002877 return eWatchpointWrite;
2878}
2879
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002880Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002881ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002882{
2883 Error error;
2884 if (wp)
2885 {
2886 user_id_t watchID = wp->GetID();
2887 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00002888 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002889 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002890 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002891 if (wp->IsEnabled())
2892 {
2893 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002894 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 +00002895 return error;
2896 }
Johnny Chen11309a32011-09-06 22:38:36 +00002897
2898 GDBStoppointType type = GetGDBStoppointType(wp);
2899 // Pass down an appropriate z/Z packet...
2900 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002901 {
Johnny Chen11309a32011-09-06 22:38:36 +00002902 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2903 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002904 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002905 return error;
2906 }
2907 else
2908 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002909 }
Johnny Chen11309a32011-09-06 22:38:36 +00002910 else
2911 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002912 }
2913 else
2914 {
Johnny Chen01a67862011-10-14 00:42:25 +00002915 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002916 }
2917 if (error.Success())
2918 error.SetErrorToGenericError();
2919 return error;
2920}
2921
2922Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002923ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002924{
2925 Error error;
2926 if (wp)
2927 {
2928 user_id_t watchID = wp->GetID();
2929
Greg Clayton5160ce52013-03-27 23:08:40 +00002930 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002931
2932 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00002933
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002934 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002935 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002936
Johnny Chen11309a32011-09-06 22:38:36 +00002937 if (!wp->IsEnabled())
2938 {
2939 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002940 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 +00002941 // See also 'class WatchpointSentry' within StopInfo.cpp.
2942 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2943 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00002944 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002945 return error;
2946 }
2947
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002948 if (wp->IsHardware())
2949 {
Johnny Chen11309a32011-09-06 22:38:36 +00002950 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002951 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00002952 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2953 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002954 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002955 return error;
2956 }
2957 else
2958 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002959 }
2960 // TODO: clear software watchpoints if we implement them
2961 }
2962 else
2963 {
Johnny Chen01a67862011-10-14 00:42:25 +00002964 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002965 }
2966 if (error.Success())
2967 error.SetErrorToGenericError();
2968 return error;
2969}
2970
2971void
2972ProcessGDBRemote::Clear()
2973{
2974 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002975 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002976 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002977}
2978
2979Error
2980ProcessGDBRemote::DoSignal (int signo)
2981{
2982 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002983 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002984 if (log)
2985 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2986
2987 if (!m_gdb_comm.SendAsyncSignal (signo))
2988 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2989 return error;
2990}
2991
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002992Error
Greg Clayton91a9b2472013-12-04 19:19:12 +00002993ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002994{
2995 Error error;
2996 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2997 {
2998 // If we locate debugserver, keep that located version around
2999 static FileSpec g_debugserver_file_spec;
3000
Han Ming Ong84647042012-02-25 01:07:38 +00003001 ProcessLaunchInfo debugserver_launch_info;
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00003002 // Make debugserver run in its own session so signals generated by
3003 // special terminal key sequences (^C) don't affect debugserver.
3004 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3005
Greg Clayton91a9b2472013-12-04 19:19:12 +00003006 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
3007 debugserver_launch_info.SetUserID(process_info.GetUserID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003008
Todd Fiala013434e2014-07-09 01:29:05 +00003009#if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__) || defined (__aarch64__))
Greg Claytonfda4fab2014-01-10 22:24:11 +00003010 // On iOS, still do a local connection using a random port
Greg Clayton16810922014-02-27 19:38:18 +00003011 const char *hostname = "127.0.0.1";
Greg Claytonfda4fab2014-01-10 22:24:11 +00003012 uint16_t port = get_random_port ();
3013#else
3014 // Set hostname being NULL to do the reverse connect where debugserver
3015 // will bind to port zero and it will communicate back to us the port
3016 // that we will connect to
3017 const char *hostname = NULL;
3018 uint16_t port = 0;
3019#endif
3020
3021 error = m_gdb_comm.StartDebugserverProcess (hostname,
3022 port,
Greg Clayton00fe87b2013-12-05 22:58:22 +00003023 debugserver_launch_info,
3024 port);
Greg Clayton91a9b2472013-12-04 19:19:12 +00003025
3026 if (error.Success ())
3027 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003028 else
Greg Clayton91a9b2472013-12-04 19:19:12 +00003029 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003030
3031 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3032 StartAsyncThread ();
Greg Clayton91a9b2472013-12-04 19:19:12 +00003033
3034 if (error.Fail())
3035 {
3036 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
3037
3038 if (log)
3039 log->Printf("failed to start debugserver process: %s", error.AsCString());
3040 return error;
3041 }
3042
Greg Clayton00fe87b2013-12-05 22:58:22 +00003043 if (m_gdb_comm.IsConnected())
3044 {
3045 // Finish the connection process by doing the handshake without connecting (send NULL URL)
3046 ConnectToDebugserver (NULL);
3047 }
3048 else
3049 {
Greg Claytonfda4fab2014-01-10 22:24:11 +00003050 StreamString connect_url;
3051 connect_url.Printf("connect://%s:%u", hostname, port);
3052 error = ConnectToDebugserver (connect_url.GetString().c_str());
Greg Clayton00fe87b2013-12-05 22:58:22 +00003053 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00003054
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003055 }
3056 return error;
3057}
3058
3059bool
3060ProcessGDBRemote::MonitorDebugserverProcess
3061(
3062 void *callback_baton,
3063 lldb::pid_t debugserver_pid,
Greg Claytone4e45922011-11-16 05:37:56 +00003064 bool exited, // True if the process did exit
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003065 int signo, // Zero for no signal
3066 int exit_status // Exit value of process if signal is zero
3067)
3068{
Greg Claytone4e45922011-11-16 05:37:56 +00003069 // The baton is a "ProcessGDBRemote *". Now this class might be gone
3070 // and might not exist anymore, so we need to carefully try to get the
3071 // target for this process first since we have a race condition when
3072 // we are done running between getting the notice that the inferior
3073 // process has died and the debugserver that was debugging this process.
3074 // In our test suite, we are also continually running process after
3075 // process, so we must be very careful to make sure:
3076 // 1 - process object hasn't been deleted already
3077 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003078
3079 // "debugserver_pid" argument passed in is the process ID for
3080 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00003081 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003082
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003083 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton6779606a2011-01-22 23:43:18 +00003084
Greg Claytone4e45922011-11-16 05:37:56 +00003085 // Get a shared pointer to the target that has a matching process pointer.
3086 // This target could be gone, or the target could already have a new process
3087 // object inside of it
3088 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
3089
Greg Clayton6779606a2011-01-22 23:43:18 +00003090 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003091 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 +00003092
Greg Claytone4e45922011-11-16 05:37:56 +00003093 if (target_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003094 {
Greg Claytone4e45922011-11-16 05:37:56 +00003095 // We found a process in a target that matches, but another thread
3096 // might be in the process of launching a new process that will
3097 // soon replace it, so get a shared pointer to the process so we
3098 // can keep it alive.
3099 ProcessSP process_sp (target_sp->GetProcessSP());
3100 // Now we have a shared pointer to the process that can't go away on us
3101 // so we now make sure it was the same as the one passed in, and also make
3102 // sure that our previous "process *" didn't get deleted and have a new
3103 // "process *" created in its place with the same pointer. To verify this
3104 // we make sure the process has our debugserver process ID. If we pass all
3105 // of these tests, then we are sure that this process is the one we were
3106 // looking for.
3107 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003108 {
Greg Claytone4e45922011-11-16 05:37:56 +00003109 // Sleep for a half a second to make sure our inferior process has
3110 // time to set its exit status before we set it incorrectly when
3111 // both the debugserver and the inferior process shut down.
3112 usleep (500000);
3113 // If our process hasn't yet exited, debugserver might have died.
3114 // If the process did exit, the we are reaping it.
3115 const StateType state = process->GetState();
3116
3117 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
3118 state != eStateInvalid &&
3119 state != eStateUnloaded &&
3120 state != eStateExited &&
3121 state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003122 {
Greg Claytone4e45922011-11-16 05:37:56 +00003123 char error_str[1024];
3124 if (signo)
3125 {
3126 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
3127 if (signal_cstr)
3128 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3129 else
3130 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
3131 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003132 else
Greg Claytone4e45922011-11-16 05:37:56 +00003133 {
3134 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
3135 }
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003136
Greg Claytone4e45922011-11-16 05:37:56 +00003137 process->SetExitStatus (-1, error_str);
3138 }
3139 // Debugserver has exited we need to let our ProcessGDBRemote
3140 // know that it no longer has a debugserver instance
3141 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton0b76a2c2010-08-21 02:22:51 +00003142 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003143 }
3144 return true;
3145}
3146
3147void
3148ProcessGDBRemote::KillDebugserverProcess ()
3149{
Greg Claytonfbb76342013-11-20 21:07:01 +00003150 m_gdb_comm.Disconnect();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003151 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3152 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003153 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003154 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3155 }
3156}
3157
3158void
3159ProcessGDBRemote::Initialize()
3160{
Davide Italianoc8d69822015-04-03 04:24:32 +00003161 static std::once_flag g_once_flag;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003162
Davide Italianoc8d69822015-04-03 04:24:32 +00003163 std::call_once(g_once_flag, []()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003164 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003165 PluginManager::RegisterPlugin (GetPluginNameStatic(),
3166 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00003167 CreateInstance,
3168 DebuggerInitialize);
Davide Italianoc8d69822015-04-03 04:24:32 +00003169 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003170}
3171
Greg Clayton7f982402013-07-15 22:54:20 +00003172void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003173ProcessGDBRemote::DebuggerInitialize (Debugger &debugger)
Greg Clayton7f982402013-07-15 22:54:20 +00003174{
3175 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
3176 {
3177 const bool is_global_setting = true;
3178 PluginManager::CreateSettingForProcessPlugin (debugger,
3179 GetGlobalPluginProperties()->GetValueProperties(),
3180 ConstString ("Properties for the gdb-remote process plug-in."),
3181 is_global_setting);
3182 }
3183}
3184
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003185bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003186ProcessGDBRemote::StartAsyncThread ()
3187{
Greg Clayton5160ce52013-03-27 23:08:40 +00003188 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003189
3190 if (log)
3191 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003192
3193 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003194 if (!m_async_thread.IsJoinable())
Jim Ingham455fa5c2012-11-01 01:15:33 +00003195 {
3196 // Create a thread that watches our internal state and controls which
3197 // events make it to clients (into the DCProcess event queue).
Zachary Turner39de3112014-09-09 20:54:56 +00003198
3199 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Jim Ingham455fa5c2012-11-01 01:15:33 +00003200 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003201 else if (log)
3202 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was already running.", __FUNCTION__);
Zachary Turner39de3112014-09-09 20:54:56 +00003203
Zachary Turneracee96a2014-09-23 18:32:09 +00003204 return m_async_thread.IsJoinable();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003205}
3206
3207void
3208ProcessGDBRemote::StopAsyncThread ()
3209{
Greg Clayton5160ce52013-03-27 23:08:40 +00003210 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003211
3212 if (log)
3213 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
3214
Jim Ingham455fa5c2012-11-01 01:15:33 +00003215 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003216 if (m_async_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003217 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00003218 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
3219
3220 // This will shut down the async thread.
3221 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3222
3223 // Stop the stdio thread
Zachary Turner39de3112014-09-09 20:54:56 +00003224 m_async_thread.Join(nullptr);
Pavel Labatha55a9532015-03-11 09:53:42 +00003225 m_async_thread.Reset();
Jim Ingham455fa5c2012-11-01 01:15:33 +00003226 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003227 else if (log)
3228 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003229}
3230
3231
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003232thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003233ProcessGDBRemote::AsyncThread (void *arg)
3234{
3235 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
3236
Greg Clayton5160ce52013-03-27 23:08:40 +00003237 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003238 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003239 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003240
3241 Listener listener ("ProcessGDBRemote::AsyncThread");
3242 EventSP event_sp;
3243 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
3244 eBroadcastBitAsyncThreadShouldExit;
3245
3246 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
3247 {
Greg Clayton71337622011-02-24 22:24:29 +00003248 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
3249
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003250 bool done = false;
3251 while (!done)
3252 {
3253 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003254 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003255 if (listener.WaitForEvent (NULL, event_sp))
3256 {
3257 const uint32_t event_type = event_sp->GetType();
Greg Clayton71337622011-02-24 22:24:29 +00003258 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003259 {
Greg Clayton71337622011-02-24 22:24:29 +00003260 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003261 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 +00003262
Greg Clayton71337622011-02-24 22:24:29 +00003263 switch (event_type)
3264 {
3265 case eBroadcastBitAsyncContinue:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003266 {
Greg Clayton71337622011-02-24 22:24:29 +00003267 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003268
Greg Clayton71337622011-02-24 22:24:29 +00003269 if (continue_packet)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003270 {
Greg Clayton71337622011-02-24 22:24:29 +00003271 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
3272 const size_t continue_cstr_len = continue_packet->GetByteSize ();
3273 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003274 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003275
Greg Clayton71337622011-02-24 22:24:29 +00003276 if (::strstr (continue_cstr, "vAttach") == NULL)
3277 process->SetPrivateState(eStateRunning);
3278 StringExtractorGDBRemote response;
3279 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003280
Greg Clayton0772ded2012-05-16 02:48:06 +00003281 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
3282 // The thread ID list might be contained within the "response", or the stop reply packet that
3283 // caused the stop. So clear it now before we give the stop reply packet to the process
3284 // using the process->SetLastStopPacket()...
3285 process->ClearThreadIDList ();
3286
Greg Clayton71337622011-02-24 22:24:29 +00003287 switch (stop_state)
3288 {
3289 case eStateStopped:
3290 case eStateCrashed:
3291 case eStateSuspended:
Greg Clayton09c3e3d2011-12-06 04:51:14 +00003292 process->SetLastStopPacket (response);
Greg Clayton71337622011-02-24 22:24:29 +00003293 process->SetPrivateState (stop_state);
3294 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003295
Greg Clayton71337622011-02-24 22:24:29 +00003296 case eStateExited:
Jason Molendaa3329782014-03-29 18:54:20 +00003297 {
Greg Clayton09c3e3d2011-12-06 04:51:14 +00003298 process->SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00003299 process->ClearThreadIDList();
Greg Clayton71337622011-02-24 22:24:29 +00003300 response.SetFilePos(1);
Jason Molendaa3329782014-03-29 18:54:20 +00003301
3302 int exit_status = response.GetHexU8();
3303 const char *desc_cstr = NULL;
3304 StringExtractor extractor;
3305 std::string desc_string;
3306 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';')
3307 {
3308 std::string desc_token;
3309 while (response.GetNameColonValue (desc_token, desc_string))
3310 {
3311 if (desc_token == "description")
3312 {
3313 extractor.GetStringRef().swap(desc_string);
3314 extractor.SetFilePos(0);
3315 extractor.GetHexByteString (desc_string);
3316 desc_cstr = desc_string.c_str();
3317 }
3318 }
3319 }
3320 process->SetExitStatus(exit_status, desc_cstr);
Greg Clayton71337622011-02-24 22:24:29 +00003321 done = true;
3322 break;
Jason Molendaa3329782014-03-29 18:54:20 +00003323 }
Greg Clayton71337622011-02-24 22:24:29 +00003324 case eStateInvalid:
3325 process->SetExitStatus(-1, "lost connection");
3326 break;
3327
3328 default:
3329 process->SetPrivateState (stop_state);
3330 break;
3331 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003332 }
3333 }
Greg Clayton71337622011-02-24 22:24:29 +00003334 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003335
Greg Clayton71337622011-02-24 22:24:29 +00003336 case eBroadcastBitAsyncThreadShouldExit:
3337 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003338 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Clayton71337622011-02-24 22:24:29 +00003339 done = true;
3340 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003341
Greg Clayton71337622011-02-24 22:24:29 +00003342 default:
3343 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003344 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 +00003345 done = true;
3346 break;
3347 }
3348 }
3349 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
3350 {
3351 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
3352 {
3353 process->SetExitStatus (-1, "lost connection");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003354 done = true;
Greg Clayton71337622011-02-24 22:24:29 +00003355 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003356 }
3357 }
3358 else
3359 {
3360 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003361 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 +00003362 done = true;
3363 }
3364 }
3365 }
3366
3367 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003368 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003369
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003370 return NULL;
3371}
3372
Greg Claytone996fd32011-03-08 22:40:15 +00003373//uint32_t
3374//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3375//{
3376// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
3377// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
3378// if (m_local_debugserver)
3379// {
3380// return Host::ListProcessesMatchingName (name, matches, pids);
3381// }
3382// else
3383// {
3384// // FIXME: Implement talking to the remote debugserver.
3385// return 0;
3386// }
3387//
3388//}
3389//
Jim Ingham1c823b42011-01-22 01:33:44 +00003390bool
3391ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003392 StoppointCallbackContext *context,
Jim Ingham1c823b42011-01-22 01:33:44 +00003393 lldb::user_id_t break_id,
3394 lldb::user_id_t break_loc_id)
3395{
3396 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3397 // run so I can stop it if that's what I want to do.
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003398 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00003399 if (log)
3400 log->Printf("Hit New Thread Notification breakpoint.");
3401 return false;
3402}
3403
3404
3405bool
3406ProcessGDBRemote::StartNoticingNewThreads()
3407{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003408 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00003409 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003410 {
Greg Clayton4116e932012-05-15 02:33:01 +00003411 if (log && log->GetVerbose())
3412 log->Printf("Enabled noticing new thread breakpoint.");
3413 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003414 }
Greg Clayton4116e932012-05-15 02:33:01 +00003415 else
Jim Ingham1c823b42011-01-22 01:33:44 +00003416 {
Greg Clayton4116e932012-05-15 02:33:01 +00003417 PlatformSP platform_sp (m_target.GetPlatform());
3418 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003419 {
Greg Clayton4116e932012-05-15 02:33:01 +00003420 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3421 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003422 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00003423 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00003424 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3425 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003426 }
3427 else
3428 {
3429 if (log)
3430 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00003431 }
3432 }
3433 }
Greg Clayton4116e932012-05-15 02:33:01 +00003434 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00003435}
3436
3437bool
3438ProcessGDBRemote::StopNoticingNewThreads()
3439{
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003440 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00003441 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00003442 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00003443
3444 if (m_thread_create_bp_sp)
3445 m_thread_create_bp_sp->SetEnabled(false);
3446
Jim Ingham1c823b42011-01-22 01:33:44 +00003447 return true;
3448}
3449
Tamas Berghammerdb264a62015-03-31 09:52:22 +00003450DynamicLoader *
Jason Molenda5e8534e2012-10-03 01:29:34 +00003451ProcessGDBRemote::GetDynamicLoader ()
3452{
3453 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00003454 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00003455 return m_dyld_ap.get();
3456}
Jim Ingham1c823b42011-01-22 01:33:44 +00003457
Jason Molendaa3329782014-03-29 18:54:20 +00003458Error
3459ProcessGDBRemote::SendEventData(const char *data)
3460{
3461 int return_value;
3462 bool was_supported;
3463
3464 Error error;
3465
3466 return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported);
3467 if (return_value != 0)
3468 {
3469 if (!was_supported)
3470 error.SetErrorString("Sending events is not supported for this process.");
3471 else
3472 error.SetErrorStringWithFormat("Error sending event data: %d.", return_value);
3473 }
3474 return error;
3475}
3476
Steve Pucci03904ac2014-03-04 23:18:46 +00003477const DataBufferSP
3478ProcessGDBRemote::GetAuxvData()
3479{
3480 DataBufferSP buf;
3481 if (m_gdb_comm.GetQXferAuxvReadSupported())
3482 {
3483 std::string response_string;
3484 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success)
3485 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length()));
3486 }
3487 return buf;
3488}
3489
Jason Molenda705b1802014-06-13 02:37:02 +00003490StructuredData::ObjectSP
3491ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid)
3492{
3493 StructuredData::ObjectSP object_sp;
3494
3495 if (m_gdb_comm.GetThreadExtendedInfoSupported())
3496 {
3497 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3498 SystemRuntime *runtime = GetSystemRuntime();
3499 if (runtime)
3500 {
3501 runtime->AddThreadExtendedInfoPacketHints (args_dict);
3502 }
3503 args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid);
3504
3505 StreamString packet;
3506 packet << "jThreadExtendedInfo:";
3507 args_dict->Dump (packet);
3508
3509 // FIXME the final character of a JSON dictionary, '}', is the escape
3510 // character in gdb-remote binary mode. lldb currently doesn't escape
3511 // these characters in its packet output -- so we add the quoted version
3512 // of the } character here manually in case we talk to a debugserver which
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003513 // un-escapes the characters at packet read time.
Jason Molenda705b1802014-06-13 02:37:02 +00003514 packet << (char) (0x7d ^ 0x20);
3515
3516 StringExtractorGDBRemote response;
3517 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
3518 {
3519 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
3520 if (response_type == StringExtractorGDBRemote::eResponse)
3521 {
3522 if (!response.Empty())
3523 {
3524 // The packet has already had the 0x7d xor quoting stripped out at the
3525 // GDBRemoteCommunication packet receive level.
3526 object_sp = StructuredData::ParseJSON (response.GetStringRef());
3527 }
3528 }
3529 }
3530 }
3531 return object_sp;
3532}
3533
Jason Molenda6076bf42014-05-06 04:34:52 +00003534// Establish the largest memory read/write payloads we should use.
3535// If the remote stub has a max packet size, stay under that size.
3536//
3537// If the remote stub's max packet size is crazy large, use a
3538// reasonable largeish default.
3539//
3540// If the remote stub doesn't advertise a max packet size, use a
3541// conservative default.
3542
3543void
3544ProcessGDBRemote::GetMaxMemorySize()
3545{
3546 const uint64_t reasonable_largeish_default = 128 * 1024;
3547 const uint64_t conservative_default = 512;
3548
3549 if (m_max_memory_size == 0)
3550 {
3551 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
3552 if (stub_max_size != UINT64_MAX && stub_max_size != 0)
3553 {
3554 // Save the stub's claimed maximum packet size
3555 m_remote_stub_max_memory_size = stub_max_size;
3556
3557 // Even if the stub says it can support ginormous packets,
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003558 // don't exceed our reasonable largeish default packet size.
Jason Molenda6076bf42014-05-06 04:34:52 +00003559 if (stub_max_size > reasonable_largeish_default)
3560 {
3561 stub_max_size = reasonable_largeish_default;
3562 }
3563
3564 m_max_memory_size = stub_max_size;
3565 }
3566 else
3567 {
3568 m_max_memory_size = conservative_default;
3569 }
3570 }
3571}
3572
3573void
3574ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max)
3575{
3576 if (user_specified_max != 0)
3577 {
3578 GetMaxMemorySize ();
3579
3580 if (m_remote_stub_max_memory_size != 0)
3581 {
3582 if (m_remote_stub_max_memory_size < user_specified_max)
3583 {
3584 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a packet size too big, go as big
3585 // as the remote stub says we can go.
3586 }
3587 else
3588 {
3589 m_max_memory_size = user_specified_max; // user's packet size is good
3590 }
3591 }
3592 else
3593 {
3594 m_max_memory_size = user_specified_max; // user's packet size is probably fine
3595 }
3596 }
3597}
3598
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003599bool
3600ProcessGDBRemote::GetModuleSpec(const FileSpec& module_file_spec,
3601 const ArchSpec& arch,
3602 ModuleSpec &module_spec)
3603{
3604 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PLATFORM);
3605
3606 if (!m_gdb_comm.GetModuleInfo (module_file_spec, arch, module_spec))
3607 {
3608 if (log)
3609 log->Printf ("ProcessGDBRemote::%s - failed to get module info for %s:%s",
3610 __FUNCTION__, module_file_spec.GetPath ().c_str (),
3611 arch.GetTriple ().getTriple ().c_str ());
3612 return false;
3613 }
3614
3615 if (log)
3616 {
3617 StreamString stream;
3618 module_spec.Dump (stream);
3619 log->Printf ("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
3620 __FUNCTION__, module_file_spec.GetPath ().c_str (),
3621 arch.GetTriple ().getTriple ().c_str (), stream.GetString ().c_str ());
3622 }
3623
3624 return true;
3625}
3626
Colin Rileyc3c95b22015-04-16 15:51:33 +00003627namespace {
3628
3629typedef std::vector<std::string> stringVec;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003630
3631typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
Greg Claytond04f0ed2015-05-26 18:00:51 +00003632struct RegisterSetInfo
3633{
3634 ConstString name;
3635};
Colin Rileyc3c95b22015-04-16 15:51:33 +00003636
Greg Claytond04f0ed2015-05-26 18:00:51 +00003637typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
3638
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003639struct GdbServerTargetInfo
3640{
Greg Claytond04f0ed2015-05-26 18:00:51 +00003641 std::string arch;
3642 std::string osabi;
3643 stringVec includes;
3644 RegisterSetMap reg_set_map;
3645 XMLNode feature_node;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003646};
Greg Claytond04f0ed2015-05-26 18:00:51 +00003647
Colin Rileyc3c95b22015-04-16 15:51:33 +00003648bool
Greg Claytond04f0ed2015-05-26 18:00:51 +00003649ParseRegisters (XMLNode feature_node, GdbServerTargetInfo &target_info, GDBRemoteDynamicRegisterInfo &dyn_reg_info)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003650{
Greg Claytond04f0ed2015-05-26 18:00:51 +00003651 if (!feature_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003652 return false;
Greg Claytond04f0ed2015-05-26 18:00:51 +00003653
3654 uint32_t prev_reg_num = 0;
3655 uint32_t reg_offset = 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003656
Greg Claytond04f0ed2015-05-26 18:00:51 +00003657 feature_node.ForEachChildElementWithName("reg", [&target_info, &dyn_reg_info, &prev_reg_num, &reg_offset](const XMLNode &reg_node) -> bool {
3658 std::string name;
3659 std::string gdb_group;
3660 std::string gdb_type;
3661 ConstString reg_name;
3662 ConstString alt_name;
3663 ConstString set_name;
3664 std::vector<uint32_t> value_regs;
3665 std::vector<uint32_t> invalidate_regs;
3666 bool encoding_set = false;
3667 bool format_set = false;
3668 RegisterInfo reg_info = { NULL, // Name
3669 NULL, // Alt name
3670 0, // byte size
3671 reg_offset, // offset
3672 eEncodingUint, // encoding
3673 eFormatHex, // formate
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003674 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00003675 LLDB_INVALID_REGNUM, // GCC reg num
3676 LLDB_INVALID_REGNUM, // DWARF reg num
3677 LLDB_INVALID_REGNUM, // generic reg num
3678 prev_reg_num, // GDB reg num
3679 prev_reg_num // native register number
3680 },
3681 NULL,
3682 NULL
3683 };
3684
3685 reg_node.ForEachAttribute([&target_info, &name, &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 {
3686 if (name == "name")
3687 {
3688 reg_name.SetString(value);
3689 }
3690 else if (name == "bitsize")
3691 {
3692 reg_info.byte_size = StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
3693 }
3694 else if (name == "type")
3695 {
3696 gdb_type = value.str();
3697 }
3698 else if (name == "group")
3699 {
3700 gdb_group = value.str();
3701 }
3702 else if (name == "regnum")
3703 {
3704 const uint32_t regnum = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
3705 if (regnum != LLDB_INVALID_REGNUM)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003706 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00003707 reg_info.kinds[eRegisterKindGDB] = regnum;
3708 reg_info.kinds[eRegisterKindLLDB] = regnum;
3709 prev_reg_num = regnum;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003710 }
3711 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00003712 else if (name == "offset")
3713 {
3714 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
3715 }
3716 else if (name == "altname")
3717 {
3718 alt_name.SetString(value);
3719 }
3720 else if (name == "encoding")
3721 {
3722 encoding_set = true;
3723 reg_info.encoding = Args::StringToEncoding (value.data(), eEncodingUint);
3724 }
3725 else if (name == "format")
3726 {
3727 format_set = true;
3728 Format format = eFormatInvalid;
3729 if (Args::StringToFormat (value.data(), format, NULL).Success())
3730 reg_info.format = format;
3731 else if (value == "vector-sint8")
3732 reg_info.format = eFormatVectorOfSInt8;
3733 else if (value == "vector-uint8")
3734 reg_info.format = eFormatVectorOfUInt8;
3735 else if (value == "vector-sint16")
3736 reg_info.format = eFormatVectorOfSInt16;
3737 else if (value == "vector-uint16")
3738 reg_info.format = eFormatVectorOfUInt16;
3739 else if (value == "vector-sint32")
3740 reg_info.format = eFormatVectorOfSInt32;
3741 else if (value == "vector-uint32")
3742 reg_info.format = eFormatVectorOfUInt32;
3743 else if (value == "vector-float32")
3744 reg_info.format = eFormatVectorOfFloat32;
3745 else if (value == "vector-uint128")
3746 reg_info.format = eFormatVectorOfUInt128;
3747 }
3748 else if (name == "group_id")
3749 {
3750 const uint32_t set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
3751 RegisterSetMap::const_iterator pos = target_info.reg_set_map.find(set_id);
3752 if (pos != target_info.reg_set_map.end())
3753 set_name = pos->second.name;
3754 }
3755 else if (name == "gcc_regnum")
3756 {
3757 reg_info.kinds[eRegisterKindGCC] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
3758 }
3759 else if (name == "dwarf_regnum")
3760 {
3761 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
3762 }
3763 else if (name == "generic")
3764 {
3765 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister(value.data());
3766 }
3767 else if (name == "value_regnums")
3768 {
3769 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
3770 }
3771 else if (name == "invalidate_regnums")
3772 {
3773 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
3774 }
3775 else
3776 {
3777 printf("unhandled attribute %s = %s\n", name.data(), value.data());
3778 }
3779 return true; // Keep iterating through all attributes
3780 });
3781
3782 if (!gdb_type.empty() && !(encoding_set || format_set))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003783 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00003784 if (gdb_type.find("int") == 0)
3785 {
3786 reg_info.format = eFormatHex;
3787 reg_info.encoding = eEncodingUint;
3788 }
3789 else if (gdb_type == "data_ptr" || gdb_type == "code_ptr")
3790 {
3791 reg_info.format = eFormatAddressInfo;
3792 reg_info.encoding = eEncodingUint;
3793 }
3794 else if (gdb_type == "i387_ext" || gdb_type == "float")
3795 {
3796 reg_info.format = eFormatFloat;
3797 reg_info.encoding = eEncodingIEEE754;
3798 }
Colin Rileyc3c95b22015-04-16 15:51:33 +00003799 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00003800
3801 // Only update the register set name if we didn't get a "reg_set" attribute.
3802 // "set_name" will be empty if we didn't have a "reg_set" attribute.
3803 if (!set_name && !gdb_group.empty())
3804 set_name.SetCString(gdb_group.c_str());
3805
3806 reg_info.byte_offset = reg_offset;
3807 assert (reg_info.byte_size != 0);
3808 reg_offset += reg_info.byte_size;
3809 if (!value_regs.empty())
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003810 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00003811 value_regs.push_back(LLDB_INVALID_REGNUM);
3812 reg_info.value_regs = value_regs.data();
Colin Rileyc3c95b22015-04-16 15:51:33 +00003813 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00003814 if (!invalidate_regs.empty())
3815 {
3816 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
3817 reg_info.invalidate_regs = invalidate_regs.data();
3818 }
3819
3820 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
3821
3822 return true; // Keep iterating through all "reg" elements
3823 });
Colin Rileyc3c95b22015-04-16 15:51:33 +00003824 return true;
3825}
Greg Claytond04f0ed2015-05-26 18:00:51 +00003826
Colin Rileyc3c95b22015-04-16 15:51:33 +00003827} // namespace {}
3828
Colin Rileyc3c95b22015-04-16 15:51:33 +00003829
3830// query the target of gdb-remote for extended target information
3831// return: 'true' on success
3832// 'false' on failure
3833bool
Aidan Doddsc0c83852015-05-08 09:36:31 +00003834ProcessGDBRemote::GetGDBServerRegisterInfo ()
Colin Rileyc3c95b22015-04-16 15:51:33 +00003835{
Greg Claytond04f0ed2015-05-26 18:00:51 +00003836 // Make sure LLDB has an XML parser it can use first
3837 if (!XMLDocument::XMLEnabled())
3838 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003839
3840 // redirect libxml2's error handler since the default prints to stdout
Colin Rileyc3c95b22015-04-16 15:51:33 +00003841
3842 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003843
3844 // check that we have extended feature read support
3845 if ( !comm.GetQXferFeaturesReadSupported( ) )
3846 return false;
3847
3848 // request the target xml file
3849 std::string raw;
3850 lldb_private::Error lldberr;
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003851 if (!comm.ReadExtFeature(ConstString("features"),
3852 ConstString("target.xml"),
3853 raw,
3854 lldberr))
3855 {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003856 return false;
3857 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00003858
Colin Rileyc3c95b22015-04-16 15:51:33 +00003859
Greg Claytond04f0ed2015-05-26 18:00:51 +00003860 XMLDocument xml_document;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003861
Greg Claytond04f0ed2015-05-26 18:00:51 +00003862 if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml"))
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003863 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00003864 GdbServerTargetInfo target_info;
3865
3866 XMLNode target_node = xml_document.GetRootElement("target");
3867 if (target_node)
Jason Molenda6ae1aab2015-04-17 19:15:02 +00003868 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00003869 XMLNode feature_node;
3870 target_node.ForEachChildElement([&target_info, this, &feature_node](const XMLNode &node) -> bool
3871 {
3872 llvm::StringRef name = node.GetName();
3873 if (name == "architecture")
3874 {
3875 node.GetElementText(target_info.arch);
3876 }
3877 else if (name == "osabi")
3878 {
3879 node.GetElementText(target_info.osabi);
3880 }
3881 else if (name == "xi:include")
3882 {
3883 llvm::StringRef href = node.GetAttributeValue("href");
3884 if (!href.empty())
3885 target_info.includes.push_back(href.str());
3886 }
3887 else if (name == "feature")
3888 {
3889 feature_node = node;
3890 }
3891 else if (name == "groups")
3892 {
3893 node.ForEachChildElementWithName("group", [&target_info](const XMLNode &node) -> bool {
3894 uint32_t set_id = UINT32_MAX;
3895 RegisterSetInfo set_info;
3896
3897 node.ForEachAttribute([&set_id, &set_info](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
3898 if (name == "id")
3899 set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
3900 if (name == "name")
3901 set_info.name = ConstString(value);
3902 return true; // Keep iterating through all attributes
3903 });
3904
3905 if (set_id != UINT32_MAX)
3906 target_info.reg_set_map[set_id] = set_info;
3907 return true; // Keep iterating through all "group" elements
3908 });
3909 }
3910 return true; // Keep iterating through all children of the target_node
3911 });
3912
3913 if (feature_node)
3914 {
3915 ParseRegisters(feature_node, target_info, this->m_register_info);
3916 }
3917
3918 for (const auto &include : target_info.includes)
3919 {
3920 // request register file
3921 std::string xml_data;
3922 if (!comm.ReadExtFeature(ConstString("features"),
3923 ConstString(include),
3924 xml_data,
3925 lldberr))
3926 continue;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003927
Greg Claytond04f0ed2015-05-26 18:00:51 +00003928 XMLDocument include_xml_document;
3929 include_xml_document.ParseMemory(xml_data.data(), xml_data.size(), include.c_str());
3930 XMLNode include_feature_node = include_xml_document.GetRootElement("feature");
3931 if (include_feature_node)
3932 {
3933 ParseRegisters(include_feature_node, target_info, this->m_register_info);
3934 }
3935 }
3936 this->m_register_info.Finalize(GetTarget().GetArchitecture());
Colin Rileyc3c95b22015-04-16 15:51:33 +00003937 }
3938 }
3939
Greg Claytond04f0ed2015-05-26 18:00:51 +00003940 return m_register_info.GetNumRegisters() > 0;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003941}
3942
Aidan Doddsc0c83852015-05-08 09:36:31 +00003943Error
3944ProcessGDBRemote::GetLoadedModuleList (GDBLoadedModuleInfoList & list)
3945{
Greg Claytond04f0ed2015-05-26 18:00:51 +00003946 // Make sure LLDB has an XML parser it can use first
3947 if (!XMLDocument::XMLEnabled())
3948 return Error (0, ErrorType::eErrorTypeGeneric);
3949
Aidan Doddsc0c83852015-05-08 09:36:31 +00003950 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS);
3951 if (log)
3952 log->Printf ("ProcessGDBRemote::%s", __FUNCTION__);
3953
Aidan Doddsc0c83852015-05-08 09:36:31 +00003954 GDBRemoteCommunicationClient & comm = m_gdb_comm;
Aidan Doddsc0c83852015-05-08 09:36:31 +00003955
3956 // check that we have extended feature read support
3957 if (!comm.GetQXferLibrariesSVR4ReadSupported ())
3958 return Error (0, ErrorType::eErrorTypeGeneric);
3959
3960 list.clear ();
3961
3962 // request the loaded library list
3963 std::string raw;
3964 lldb_private::Error lldberr;
3965 if (!comm.ReadExtFeature (ConstString ("libraries-svr4"), ConstString (""), raw, lldberr))
3966 return Error (0, ErrorType::eErrorTypeGeneric);
3967
3968 // parse the xml file in memory
3969 if (log)
3970 log->Printf ("parsing: %s", raw.c_str());
Greg Claytond04f0ed2015-05-26 18:00:51 +00003971 XMLDocument doc;
3972
3973 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
Aidan Doddsc0c83852015-05-08 09:36:31 +00003974 return Error (0, ErrorType::eErrorTypeGeneric);
3975
Greg Claytond04f0ed2015-05-26 18:00:51 +00003976 XMLNode root_element = doc.GetRootElement("library-list-svr4");
3977 if (!root_element)
Aidan Doddsc0c83852015-05-08 09:36:31 +00003978 return Error();
3979
3980 // main link map structure
Greg Claytond04f0ed2015-05-26 18:00:51 +00003981 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
3982 if (!main_lm.empty())
Aidan Doddsc0c83852015-05-08 09:36:31 +00003983 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00003984 list.m_link_map = StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
Aidan Doddsc0c83852015-05-08 09:36:31 +00003985 }
3986
Greg Claytond04f0ed2015-05-26 18:00:51 +00003987 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
Aidan Doddsc0c83852015-05-08 09:36:31 +00003988
3989 GDBLoadedModuleInfoList::LoadedModuleInfo module;
3990
Greg Claytond04f0ed2015-05-26 18:00:51 +00003991 library.ForEachAttribute([log, &module](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
3992
3993 if (name == "name")
3994 module.set_name (value.str());
3995 else if (name == "lm")
Aidan Doddsc0c83852015-05-08 09:36:31 +00003996 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00003997 // the address of the link_map struct.
3998 module.set_link_map(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
Aidan Doddsc0c83852015-05-08 09:36:31 +00003999 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004000 else if (name == "l_addr")
Aidan Doddsc0c83852015-05-08 09:36:31 +00004001 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004002 // the displacement as read from the field 'l_addr' of the link_map struct.
4003 module.set_base(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4004
Aidan Doddsc0c83852015-05-08 09:36:31 +00004005 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004006 else if (name == "l_ld")
Aidan Doddsc0c83852015-05-08 09:36:31 +00004007 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004008 // the memory address of the libraries PT_DYAMIC section.
4009 module.set_dynamic(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
Aidan Doddsc0c83852015-05-08 09:36:31 +00004010 }
Greg Claytond04f0ed2015-05-26 18:00:51 +00004011
4012 return true; // Keep iterating over all properties of "library"
4013 });
Aidan Doddsc0c83852015-05-08 09:36:31 +00004014
4015 if (log)
4016 {
Greg Claytond04f0ed2015-05-26 18:00:51 +00004017 std::string name;
Aidan Doddsc0c83852015-05-08 09:36:31 +00004018 lldb::addr_t lm=0, base=0, ld=0;
4019
4020 module.get_name (name);
4021 module.get_link_map (lm);
4022 module.get_base (base);
4023 module.get_dynamic (ld);
4024
4025 log->Printf ("found (link_map:0x08%" PRIx64 ", base:0x08%" PRIx64 ", ld:0x08%" PRIx64 ", name:'%s')", lm, base, ld, name.c_str());
4026 }
4027
4028 list.add (module);
Greg Claytond04f0ed2015-05-26 18:00:51 +00004029 return true; // Keep iterating over all "library" elements in the root node
4030 });
Aidan Doddsc0c83852015-05-08 09:36:31 +00004031
4032 if (log)
4033 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4034
4035 return Error();
4036}
4037
Aidan Doddsc0c83852015-05-08 09:36:31 +00004038lldb::ModuleSP
4039ProcessGDBRemote::LoadModuleAtAddress (const FileSpec &file, lldb::addr_t base_addr)
4040{
4041 Target &target = m_process->GetTarget();
4042 ModuleList &modules = target.GetImages();
4043 ModuleSP module_sp;
4044
4045 bool changed = false;
4046
4047 ModuleSpec module_spec (file, target.GetArchitecture());
4048 if ((module_sp = modules.FindFirstModule (module_spec)))
4049 {
4050 module_sp->SetLoadAddress (target, base_addr, true, changed);
4051 }
4052 else if ((module_sp = target.GetSharedModule (module_spec)))
4053 {
4054 module_sp->SetLoadAddress (target, base_addr, true, changed);
4055 }
4056
4057 return module_sp;
4058}
4059
4060size_t
4061ProcessGDBRemote::LoadModules ()
4062{
4063 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4064
4065 // request a list of loaded libraries from GDBServer
4066 GDBLoadedModuleInfoList module_list;
4067 if (GetLoadedModuleList (module_list).Fail())
4068 return 0;
4069
4070 // get a list of all the modules
4071 ModuleList new_modules;
4072
4073 for (GDBLoadedModuleInfoList::LoadedModuleInfo & modInfo : module_list.m_list)
4074 {
4075 std::string mod_name;
4076 lldb::addr_t mod_base;
4077
4078 bool valid = true;
4079 valid &= modInfo.get_name (mod_name);
4080 valid &= modInfo.get_base (mod_base);
4081 if (!valid)
4082 continue;
4083
4084 // hack (cleaner way to get file name only?) (win/unix compat?)
Vince Harron4cc8d202015-05-10 08:33:58 +00004085 size_t marker = mod_name.rfind ('/');
Aidan Doddsc0c83852015-05-08 09:36:31 +00004086 if (marker == std::string::npos)
4087 marker = 0;
4088 else
4089 marker += 1;
4090
4091 FileSpec file (mod_name.c_str()+marker, true);
4092 lldb::ModuleSP module_sp = LoadModuleAtAddress (file, mod_base);
4093
4094 if (module_sp.get())
4095 new_modules.Append (module_sp);
4096 }
4097
4098 if (new_modules.GetSize() > 0)
4099 {
4100 Target & target = m_target;
4101
4102 new_modules.ForEach ([&target](const lldb::ModuleSP module_sp) -> bool
4103 {
4104 lldb_private::ObjectFile * obj = module_sp->GetObjectFile ();
4105 if (!obj)
4106 return true;
4107
4108 if (obj->GetType () != ObjectFile::Type::eTypeExecutable)
4109 return true;
4110
4111 lldb::ModuleSP module_copy_sp = module_sp;
4112 target.SetExecutableModule (module_copy_sp, false);
4113 return false;
4114 });
4115
4116 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4117 loaded_modules.AppendIfNeeded (new_modules);
4118 m_process->GetTarget().ModulesDidLoad (new_modules);
4119 }
4120
4121 return new_modules.GetSize();
4122}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004123
Tamas Berghammer783bfc82015-06-18 20:43:56 +00004124Error
4125ProcessGDBRemote::GetFileLoadAddress(const FileSpec& file, bool& is_loaded, lldb::addr_t& load_addr)
4126{
4127 is_loaded = false;
4128 load_addr = LLDB_INVALID_ADDRESS;
4129
4130 std::string file_path = file.GetPath(false);
4131 if (file_path.empty ())
4132 return Error("Empty file name specified");
4133
4134 StreamString packet;
4135 packet.PutCString("qFileLoadAddress:");
4136 packet.PutCStringAsRawHex8(file_path.c_str());
4137
4138 StringExtractorGDBRemote response;
4139 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString().c_str(), response, false) != GDBRemoteCommunication::PacketResult::Success)
4140 return Error("Sending qFileLoadAddress packet failed");
4141
4142 if (response.IsErrorResponse())
4143 {
4144 if (response.GetError() == 1)
4145 {
4146 // The file is not loaded into the inferior
4147 is_loaded = false;
4148 load_addr = LLDB_INVALID_ADDRESS;
4149 return Error();
4150 }
4151
4152 return Error("Fetching file load address from remote server returned an error");
4153 }
4154
4155 if (response.IsNormalResponse())
4156 {
4157 is_loaded = true;
4158 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
4159 return Error();
4160 }
4161
4162 return Error("Unknown error happened during sending the load address packet");
4163}
4164
Greg Claytone034a042015-05-21 20:52:06 +00004165class CommandObjectProcessGDBRemoteSpeedTest: public CommandObjectParsed
4166{
4167public:
4168 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter) :
4169 CommandObjectParsed (interpreter,
4170 "process plugin packet speed-test",
4171 "Tests packet speeds of various sizes to determine the performance characteristics of the GDB remote connection. ",
4172 NULL),
4173 m_option_group (interpreter),
4174 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),
4175 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),
4176 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),
4177 m_json (LLDB_OPT_SET_1, false, "json", 'j', "Print the output as JSON data for easy parsing.", false, true)
4178 {
4179 m_option_group.Append (&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4180 m_option_group.Append (&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4181 m_option_group.Append (&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4182 m_option_group.Append (&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4183 m_option_group.Finalize();
4184 }
4185
4186 ~CommandObjectProcessGDBRemoteSpeedTest ()
4187 {
4188 }
4189
4190
4191 Options *
4192 GetOptions () override
4193 {
4194 return &m_option_group;
4195 }
4196
4197 bool
4198 DoExecute (Args& command, CommandReturnObject &result) override
4199 {
4200 const size_t argc = command.GetArgumentCount();
4201 if (argc == 0)
4202 {
4203 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4204 if (process)
4205 {
4206 StreamSP output_stream_sp (m_interpreter.GetDebugger().GetAsyncOutputStream());
4207 result.SetImmediateOutputStream (output_stream_sp);
4208
4209 const uint32_t num_packets = (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
4210 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
4211 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
4212 const bool json = m_json.GetOptionValue().GetCurrentValue();
4213 if (output_stream_sp)
4214 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, *output_stream_sp);
4215 else
4216 {
4217 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, result.GetOutputStream());
4218 }
4219 result.SetStatus (eReturnStatusSuccessFinishResult);
4220 return true;
4221 }
4222 }
4223 else
4224 {
4225 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
4226 }
4227 result.SetStatus (eReturnStatusFailed);
4228 return false;
4229 }
4230protected:
4231 OptionGroupOptions m_option_group;
4232 OptionGroupUInt64 m_num_packets;
4233 OptionGroupUInt64 m_max_send;
4234 OptionGroupUInt64 m_max_recv;
4235 OptionGroupBoolean m_json;
4236
4237};
4238
Greg Clayton02686b82012-10-15 22:42:16 +00004239class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00004240{
4241private:
4242
4243public:
Greg Clayton02686b82012-10-15 22:42:16 +00004244 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00004245 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00004246 "process plugin packet history",
4247 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00004248 NULL)
4249 {
4250 }
4251
Greg Clayton02686b82012-10-15 22:42:16 +00004252 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton998255b2012-10-13 02:07:45 +00004253 {
4254 }
4255
4256 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004257 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton998255b2012-10-13 02:07:45 +00004258 {
Greg Clayton02686b82012-10-15 22:42:16 +00004259 const size_t argc = command.GetArgumentCount();
4260 if (argc == 0)
4261 {
4262 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4263 if (process)
4264 {
4265 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
4266 result.SetStatus (eReturnStatusSuccessFinishResult);
4267 return true;
4268 }
4269 }
4270 else
4271 {
4272 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
4273 }
4274 result.SetStatus (eReturnStatusFailed);
4275 return false;
4276 }
4277};
4278
Jason Molenda6076bf42014-05-06 04:34:52 +00004279class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed
4280{
4281private:
4282
4283public:
4284 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) :
4285 CommandObjectParsed (interpreter,
4286 "process plugin packet xfer-size",
4287 "Maximum size that lldb will try to read/write one one chunk.",
4288 NULL)
4289 {
4290 }
4291
4292 ~CommandObjectProcessGDBRemotePacketXferSize ()
4293 {
4294 }
4295
4296 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004297 DoExecute (Args& command, CommandReturnObject &result) override
Jason Molenda6076bf42014-05-06 04:34:52 +00004298 {
4299 const size_t argc = command.GetArgumentCount();
4300 if (argc == 0)
4301 {
4302 result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str());
4303 result.SetStatus (eReturnStatusFailed);
4304 return false;
4305 }
4306
4307 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4308 if (process)
4309 {
4310 const char *packet_size = command.GetArgumentAtIndex(0);
4311 errno = 0;
4312 uint64_t user_specified_max = strtoul (packet_size, NULL, 10);
4313 if (errno == 0 && user_specified_max != 0)
4314 {
4315 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max);
4316 result.SetStatus (eReturnStatusSuccessFinishResult);
4317 return true;
4318 }
4319 }
4320 result.SetStatus (eReturnStatusFailed);
4321 return false;
4322 }
4323};
4324
4325
Greg Clayton02686b82012-10-15 22:42:16 +00004326class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
4327{
4328private:
4329
4330public:
4331 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
4332 CommandObjectParsed (interpreter,
4333 "process plugin packet send",
4334 "Send a custom packet through the GDB remote protocol and print the answer. "
4335 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
4336 NULL)
4337 {
4338 }
4339
4340 ~CommandObjectProcessGDBRemotePacketSend ()
4341 {
4342 }
4343
4344 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004345 DoExecute (Args& command, CommandReturnObject &result) override
Greg Clayton02686b82012-10-15 22:42:16 +00004346 {
4347 const size_t argc = command.GetArgumentCount();
4348 if (argc == 0)
4349 {
4350 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
4351 result.SetStatus (eReturnStatusFailed);
4352 return false;
4353 }
4354
4355 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4356 if (process)
4357 {
Han Ming Ong84145852012-11-26 20:42:03 +00004358 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00004359 {
Han Ming Ong84145852012-11-26 20:42:03 +00004360 const char *packet_cstr = command.GetArgumentAtIndex(0);
4361 bool send_async = true;
4362 StringExtractorGDBRemote response;
4363 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
4364 result.SetStatus (eReturnStatusSuccessFinishResult);
4365 Stream &output_strm = result.GetOutputStream();
4366 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00004367 std::string &response_str = response.GetStringRef();
4368
Han Ming Ong399289e2013-06-21 19:56:59 +00004369 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00004370 {
4371 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
4372 }
4373
Han Ming Ong84145852012-11-26 20:42:03 +00004374 if (response_str.empty())
4375 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
4376 else
4377 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00004378 }
Greg Clayton02686b82012-10-15 22:42:16 +00004379 }
Greg Clayton998255b2012-10-13 02:07:45 +00004380 return true;
4381 }
4382};
4383
Greg Claytonba4a0a52013-02-01 23:03:47 +00004384class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
4385{
4386private:
4387
4388public:
4389 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
4390 CommandObjectRaw (interpreter,
4391 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00004392 "Send a qRcmd packet through the GDB remote protocol and print the response."
4393 "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 +00004394 NULL)
4395 {
4396 }
4397
4398 ~CommandObjectProcessGDBRemotePacketMonitor ()
4399 {
4400 }
4401
4402 bool
Tamas Berghammer30b8cd32015-03-23 15:50:03 +00004403 DoExecute (const char *command, CommandReturnObject &result) override
Greg Claytonba4a0a52013-02-01 23:03:47 +00004404 {
4405 if (command == NULL || command[0] == '\0')
4406 {
4407 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
4408 result.SetStatus (eReturnStatusFailed);
4409 return false;
4410 }
4411
4412 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4413 if (process)
4414 {
4415 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00004416 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00004417 packet.PutBytesAsRawHex8(command, strlen(command));
4418 const char *packet_cstr = packet.GetString().c_str();
4419
4420 bool send_async = true;
4421 StringExtractorGDBRemote response;
4422 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
4423 result.SetStatus (eReturnStatusSuccessFinishResult);
4424 Stream &output_strm = result.GetOutputStream();
4425 output_strm.Printf (" packet: %s\n", packet_cstr);
4426 const std::string &response_str = response.GetStringRef();
4427
4428 if (response_str.empty())
4429 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
4430 else
4431 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
4432 }
4433 return true;
4434 }
4435};
4436
Greg Clayton02686b82012-10-15 22:42:16 +00004437class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
4438{
4439private:
4440
4441public:
4442 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
4443 CommandObjectMultiword (interpreter,
4444 "process plugin packet",
4445 "Commands that deal with GDB remote packets.",
4446 NULL)
4447 {
4448 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
4449 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00004450 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Jason Molenda6076bf42014-05-06 04:34:52 +00004451 LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter)));
Greg Claytone034a042015-05-21 20:52:06 +00004452 LoadSubCommand ("speed-test", CommandObjectSP (new CommandObjectProcessGDBRemoteSpeedTest (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00004453 }
4454
4455 ~CommandObjectProcessGDBRemotePacket ()
4456 {
4457 }
4458};
Greg Clayton998255b2012-10-13 02:07:45 +00004459
4460class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
4461{
4462public:
4463 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
4464 CommandObjectMultiword (interpreter,
4465 "process plugin",
4466 "A set of commands for operating on a ProcessGDBRemote process.",
4467 "process plugin <subcommand> [<subcommand-options>]")
4468 {
4469 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
4470 }
4471
4472 ~CommandObjectMultiwordProcessGDBRemote ()
4473 {
4474 }
4475};
4476
Greg Clayton998255b2012-10-13 02:07:45 +00004477CommandObject *
4478ProcessGDBRemote::GetPluginCommandObject()
4479{
4480 if (!m_command_sp)
4481 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
4482 return m_command_sp.get();
4483}