blob: de165454f5893c17b28ad60535489fc3373cc210 [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
Daniel Malea93a64302012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
Virgile Bellob2f1fb22013-08-23 12:44:05 +000011#include "lldb/Host/Config.h"
Daniel Malea93a64302012-12-05 00:20:57 +000012
Chris Lattner30fdc8d2010-06-08 16:52:24 +000013// C Includes
14#include <errno.h>
Stephen Wilsona78867b2011-03-25 18:16:28 +000015#include <stdlib.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000016#ifndef LLDB_DISABLE_POSIX
Sean Callanan224f6f52012-07-19 18:07:36 +000017#include <netinet/in.h>
Greg Clayton2a48f522011-05-14 01:50:35 +000018#include <sys/mman.h> // for mmap
Virgile Bellob2f1fb22013-08-23 12:44:05 +000019#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include <sys/stat.h>
Greg Clayton2a48f522011-05-14 01:50:35 +000021#include <sys/types.h>
Stephen Wilsondc916862011-03-30 00:12:40 +000022#include <time.h>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000023
24// C++ Includes
25#include <algorithm>
26#include <map>
27
28// Other libraries and framework includes
29
Johnny Chen01a67862011-10-14 00:42:25 +000030#include "lldb/Breakpoint/Watchpoint.h"
Jim Ingham40af72e2010-06-15 19:49:27 +000031#include "lldb/Interpreter/Args.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000032#include "lldb/Core/ArchSpec.h"
33#include "lldb/Core/Debugger.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000034#include "lldb/Host/ConnectionFileDescriptor.h"
Greg Clayton53239f02011-02-08 05:05:52 +000035#include "lldb/Host/FileSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000036#include "lldb/Core/Module.h"
Greg Clayton1f746072012-08-29 21:13:06 +000037#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000038#include "lldb/Core/PluginManager.h"
39#include "lldb/Core/State.h"
Greg Claytond451c1a2012-04-13 21:24:18 +000040#include "lldb/Core/StreamFile.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000041#include "lldb/Core/StreamString.h"
42#include "lldb/Core/Timer.h"
Greg Clayton70b57652011-05-15 01:25:55 +000043#include "lldb/Core/Value.h"
Zachary Turner39de3112014-09-09 20:54:56 +000044#include "lldb/Host/HostThread.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000045#include "lldb/Host/StringConvert.h"
Jason Molendad1fae142012-09-29 08:03:33 +000046#include "lldb/Host/Symbols.h"
Zachary Turner39de3112014-09-09 20:54:56 +000047#include "lldb/Host/ThreadLauncher.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000048#include "lldb/Host/TimeValue.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"
Joerg Sonnenbergere77b0422013-10-20 17:36:05 +000053#ifndef LLDB_DISABLE_PYTHON
Greg Claytonef8180a2013-10-15 00:14:28 +000054#include "lldb/Interpreter/PythonDataObjects.h"
Joerg Sonnenbergere77b0422013-10-20 17:36:05 +000055#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000056#include "lldb/Symbol/ObjectFile.h"
57#include "lldb/Target/DynamicLoader.h"
58#include "lldb/Target/Target.h"
59#include "lldb/Target/TargetList.h"
Greg Clayton2a48f522011-05-14 01:50:35 +000060#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molenda705b1802014-06-13 02:37:02 +000061#include "lldb/Target/SystemRuntime.h"
Jason Molendaa34a0c62010-06-09 21:28:42 +000062#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000063
64// Project includes
65#include "lldb/Host/Host.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000066#include "Plugins/Process/Utility/FreeBSDSignals.h"
Peter Collingbourne99f9aa02011-06-03 20:40:38 +000067#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000068#include "Plugins/Process/Utility/LinuxSignals.h"
Jason Molendac42d2432012-07-25 03:40:06 +000069#include "Plugins/Process/Utility/StopInfoMachException.h"
Jim Ingham43c555d2012-07-04 00:35:43 +000070#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
Greg Claytonc982c762010-07-09 20:39:50 +000071#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000072#include "GDBRemoteRegisterContext.h"
73#include "ProcessGDBRemote.h"
74#include "ProcessGDBRemoteLog.h"
75#include "ThreadGDBRemote.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000076
Jason Molenda5e8534e2012-10-03 01:29:34 +000077
Greg Claytonc1422c12012-04-09 22:46:21 +000078namespace lldb
79{
80 // Provide a function that can easily dump the packet history if we know a
81 // ProcessGDBRemote * value (which we can get from logs or from debugging).
82 // We need the function in the lldb namespace so it makes it into the final
83 // executable since the LLDB shared library only exports stuff in the lldb
84 // namespace. This allows you to attach with a debugger and call this
85 // function and get the packet history dumped to a file.
86 void
87 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
88 {
Greg Claytond451c1a2012-04-13 21:24:18 +000089 lldb_private::StreamFile strm;
90 lldb_private::Error error (strm.GetFile().Open(path, lldb_private::File::eOpenOptionWrite | lldb_private::File::eOpenOptionCanCreate));
91 if (error.Success())
92 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
Greg Claytonc1422c12012-04-09 22:46:21 +000093 }
Filipe Cabecinhasc34f7762012-05-23 16:27:09 +000094}
Chris Lattner30fdc8d2010-06-08 16:52:24 +000095
Chris Lattner30fdc8d2010-06-08 16:52:24 +000096#define DEBUGSERVER_BASENAME "debugserver"
97using namespace lldb;
98using namespace lldb_private;
99
Greg Clayton7f982402013-07-15 22:54:20 +0000100
101namespace {
Steve Pucci5ec012d2014-01-16 22:18:14 +0000102
Greg Clayton7f982402013-07-15 22:54:20 +0000103 static PropertyDefinition
104 g_properties[] =
105 {
106 { "packet-timeout" , OptionValue::eTypeUInt64 , true , 1, NULL, NULL, "Specify the default packet timeout in seconds." },
Greg Claytonef8180a2013-10-15 00:14:28 +0000107 { "target-definition-file" , OptionValue::eTypeFileSpec , true, 0 , NULL, NULL, "The file that provides the description for remote target registers." },
Greg Clayton7f982402013-07-15 22:54:20 +0000108 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
109 };
110
111 enum
112 {
Greg Claytonef8180a2013-10-15 00:14:28 +0000113 ePropertyPacketTimeout,
114 ePropertyTargetDefinitionFile
Greg Clayton7f982402013-07-15 22:54:20 +0000115 };
116
117 class PluginProperties : public Properties
118 {
119 public:
120
121 static ConstString
122 GetSettingName ()
123 {
124 return ProcessGDBRemote::GetPluginNameStatic();
125 }
126
127 PluginProperties() :
128 Properties ()
129 {
130 m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
131 m_collection_sp->Initialize(g_properties);
132 }
133
134 virtual
135 ~PluginProperties()
136 {
137 }
138
139 uint64_t
140 GetPacketTimeout()
141 {
142 const uint32_t idx = ePropertyPacketTimeout;
143 return m_collection_sp->GetPropertyAtIndexAsUInt64(NULL, idx, g_properties[idx].default_uint_value);
144 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000145
146 bool
147 SetPacketTimeout(uint64_t timeout)
148 {
149 const uint32_t idx = ePropertyPacketTimeout;
150 return m_collection_sp->SetPropertyAtIndexAsUInt64(NULL, idx, timeout);
151 }
152
Greg Claytonef8180a2013-10-15 00:14:28 +0000153 FileSpec
154 GetTargetDefinitionFile () const
155 {
156 const uint32_t idx = ePropertyTargetDefinitionFile;
157 return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
158 }
Greg Clayton7f982402013-07-15 22:54:20 +0000159 };
160
161 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
162
163 static const ProcessKDPPropertiesSP &
164 GetGlobalPluginProperties()
165 {
166 static ProcessKDPPropertiesSP g_settings_sp;
167 if (!g_settings_sp)
168 g_settings_sp.reset (new PluginProperties ());
169 return g_settings_sp;
170 }
171
172} // anonymous namespace end
173
Greg Claytonfda4fab2014-01-10 22:24:11 +0000174// TODO Randomly assigning a port is unsafe. We should get an unused
175// ephemeral port from the kernel and make sure we reserve it before passing
176// it to debugserver.
177
178#if defined (__APPLE__)
179#define LOW_PORT (IPPORT_RESERVED)
180#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
181#else
182#define LOW_PORT (1024u)
183#define HIGH_PORT (49151u)
184#endif
185
Todd Fiala013434e2014-07-09 01:29:05 +0000186#if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000187static bool rand_initialized = false;
188
Greg Claytonfda4fab2014-01-10 22:24:11 +0000189static inline uint16_t
190get_random_port ()
191{
192 if (!rand_initialized)
193 {
194 time_t seed = time(NULL);
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000195
Greg Claytonfda4fab2014-01-10 22:24:11 +0000196 rand_initialized = true;
197 srand(seed);
198 }
199 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
200}
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000201#endif
Greg Claytonfda4fab2014-01-10 22:24:11 +0000202
Greg Clayton57abc5d2013-05-10 21:47:16 +0000203lldb_private::ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000204ProcessGDBRemote::GetPluginNameStatic()
205{
Greg Clayton57abc5d2013-05-10 21:47:16 +0000206 static ConstString g_name("gdb-remote");
207 return g_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000208}
209
210const char *
211ProcessGDBRemote::GetPluginDescriptionStatic()
212{
213 return "GDB Remote protocol based debugging plug-in.";
214}
215
216void
217ProcessGDBRemote::Terminate()
218{
219 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
220}
221
222
Greg Claytonc3776bf2012-02-09 06:16:32 +0000223lldb::ProcessSP
224ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000225{
Greg Claytonc3776bf2012-02-09 06:16:32 +0000226 lldb::ProcessSP process_sp;
227 if (crash_file_path == NULL)
228 process_sp.reset (new ProcessGDBRemote (target, listener));
229 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000230}
231
232bool
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000233ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000234{
Greg Clayton596ed242011-10-21 21:41:45 +0000235 if (plugin_specified_by_name)
236 return true;
237
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000238 // For now we are just making sure the file exists for a given module
Greg Claytonaa149cb2011-08-11 02:48:45 +0000239 Module *exe_module = target.GetExecutableModulePointer();
240 if (exe_module)
Greg Claytonc3776bf2012-02-09 06:16:32 +0000241 {
242 ObjectFile *exe_objfile = exe_module->GetObjectFile();
243 // We can't debug core files...
244 switch (exe_objfile->GetType())
245 {
246 case ObjectFile::eTypeInvalid:
247 case ObjectFile::eTypeCoreFile:
248 case ObjectFile::eTypeDebugInfo:
249 case ObjectFile::eTypeObjectFile:
250 case ObjectFile::eTypeSharedLibrary:
251 case ObjectFile::eTypeStubLibrary:
Greg Clayton23f8c952014-03-24 23:10:19 +0000252 case ObjectFile::eTypeJIT:
Greg Claytonc3776bf2012-02-09 06:16:32 +0000253 return false;
254 case ObjectFile::eTypeExecutable:
255 case ObjectFile::eTypeDynamicLinker:
256 case ObjectFile::eTypeUnknown:
257 break;
258 }
Greg Claytonaa149cb2011-08-11 02:48:45 +0000259 return exe_module->GetFileSpec().Exists();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000260 }
Jim Ingham5aee1622010-08-09 23:31:02 +0000261 // However, if there is no executable module, we return true since we might be preparing to attach.
262 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000263}
264
265//----------------------------------------------------------------------
266// ProcessGDBRemote constructor
267//----------------------------------------------------------------------
268ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
269 Process (target, listener),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000270 m_flags (0),
Greg Clayton8b82f082011-04-12 05:54:46 +0000271 m_gdb_comm(false),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000272 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Claytonc982c762010-07-09 20:39:50 +0000273 m_last_stop_packet (),
Greg Clayton09c3e3d2011-12-06 04:51:14 +0000274 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000275 m_register_info (),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000276 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
Jim Ingham455fa5c2012-11-01 01:15:33 +0000277 m_async_thread_state_mutex(Mutex::eMutexTypeRecursive),
Greg Clayton9e920902012-04-10 02:25:43 +0000278 m_thread_ids (),
Greg Clayton71fc2a32011-02-12 06:28:37 +0000279 m_continue_c_tids (),
280 m_continue_C_tids (),
281 m_continue_s_tids (),
282 m_continue_S_tids (),
Jason Molenda6076bf42014-05-06 04:34:52 +0000283 m_max_memory_size (0),
284 m_remote_stub_max_memory_size (0),
Greg Clayton4116e932012-05-15 02:33:01 +0000285 m_addr_to_mmap_size (),
286 m_thread_create_bp_sp (),
Jim Ingham43c555d2012-07-04 00:35:43 +0000287 m_waiting_for_attach (false),
Jason Molenda5e8534e2012-10-03 01:29:34 +0000288 m_destroy_tried_resuming (false),
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000289 m_command_sp (),
Todd Fiala4ceced32014-08-29 17:35:57 +0000290 m_breakpoint_pc_offset (0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000291{
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000292 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
293 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Inghamb1e2e842012-04-12 18:49:31 +0000294 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Greg Clayton7f982402013-07-15 22:54:20 +0000295 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
296 if (timeout_seconds > 0)
297 m_gdb_comm.SetPacketTimeout(timeout_seconds);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000298}
299
300//----------------------------------------------------------------------
301// Destructor
302//----------------------------------------------------------------------
303ProcessGDBRemote::~ProcessGDBRemote()
304{
305 // m_mach_process.UnregisterNotificationCallbacks (this);
306 Clear();
Greg Clayton1ed54f52011-10-01 00:45:15 +0000307 // We need to call finalize on the process before destroying ourselves
308 // to make sure all of the broadcaster cleanup goes as planned. If we
309 // destruct this class, then Process::~Process() might have problems
310 // trying to fully destroy the broadcaster.
311 Finalize();
Jim Ingham455fa5c2012-11-01 01:15:33 +0000312
313 // The general Finalize is going to try to destroy the process and that SHOULD
314 // shut down the async thread. However, if we don't kill it it will get stranded and
315 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
316 StopAsyncThread();
317 KillDebugserverProcess();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000318}
319
320//----------------------------------------------------------------------
321// PluginInterface
322//----------------------------------------------------------------------
Greg Clayton57abc5d2013-05-10 21:47:16 +0000323ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000324ProcessGDBRemote::GetPluginName()
325{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000326 return GetPluginNameStatic();
327}
328
329uint32_t
330ProcessGDBRemote::GetPluginVersion()
331{
332 return 1;
333}
334
Greg Claytonef8180a2013-10-15 00:14:28 +0000335bool
336ProcessGDBRemote::ParsePythonTargetDefinition(const FileSpec &target_definition_fspec)
337{
Joerg Sonnenbergere77b0422013-10-20 17:36:05 +0000338#ifndef LLDB_DISABLE_PYTHON
Greg Claytonef8180a2013-10-15 00:14:28 +0000339 ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
340 Error error;
341 lldb::ScriptInterpreterObjectSP module_object_sp (interpreter->LoadPluginModule(target_definition_fspec, error));
342 if (module_object_sp)
343 {
344 lldb::ScriptInterpreterObjectSP target_definition_sp (interpreter->GetDynamicSettings(module_object_sp,
345 &GetTarget(),
346 "gdb-server-target-definition",
347 error));
348
349 PythonDictionary target_dict(target_definition_sp);
350
351 if (target_dict)
352 {
Greg Clayton312bcbe2013-10-17 01:10:23 +0000353 PythonDictionary host_info_dict (target_dict.GetItemForKey("host-info"));
354 if (host_info_dict)
355 {
356 ArchSpec host_arch (host_info_dict.GetItemForKeyAsString(PythonString("triple")));
357
358 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture()))
359 {
360 GetTarget().SetArchitecture(host_arch);
361 }
362
363 }
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000364 m_breakpoint_pc_offset = target_dict.GetItemForKeyAsInteger("breakpoint-pc-offset", 0);
365
Greg Clayton312bcbe2013-10-17 01:10:23 +0000366 if (m_register_info.SetRegisterInfo (target_dict, GetTarget().GetArchitecture().GetByteOrder()) > 0)
Greg Claytonef8180a2013-10-15 00:14:28 +0000367 {
368 return true;
369 }
370 }
371 }
Joerg Sonnenbergere77b0422013-10-20 17:36:05 +0000372#endif
Greg Claytonef8180a2013-10-15 00:14:28 +0000373 return false;
374}
375
376
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000377void
Greg Clayton513c26c2011-01-29 07:10:55 +0000378ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000379{
Greg Clayton513c26c2011-01-29 07:10:55 +0000380 if (!force && m_register_info.GetNumRegisters() > 0)
381 return;
382
383 char packet[128];
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000384 m_register_info.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000385 uint32_t reg_offset = 0;
386 uint32_t reg_num = 0;
Greg Clayton23f59502012-07-17 03:23:13 +0000387 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Greg Clayton576d8832011-03-22 04:00:09 +0000388 response_type == StringExtractorGDBRemote::eResponse;
389 ++reg_num)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000390 {
Greg Clayton513c26c2011-01-29 07:10:55 +0000391 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
Andy Gibbsa297a972013-06-19 19:04:53 +0000392 assert (packet_len < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000393 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000394 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000395 {
Greg Clayton576d8832011-03-22 04:00:09 +0000396 response_type = response.GetResponseType();
397 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000398 {
399 std::string name;
400 std::string value;
401 ConstString reg_name;
402 ConstString alt_name;
403 ConstString set_name;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000404 std::vector<uint32_t> value_regs;
405 std::vector<uint32_t> invalidate_regs;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000406 RegisterInfo reg_info = { NULL, // Name
407 NULL, // Alt name
408 0, // byte size
409 reg_offset, // offset
410 eEncodingUint, // encoding
411 eFormatHex, // formate
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000412 {
413 LLDB_INVALID_REGNUM, // GCC reg num
414 LLDB_INVALID_REGNUM, // DWARF reg num
415 LLDB_INVALID_REGNUM, // generic reg num
Jason Molendafbcb7f22010-09-10 07:49:16 +0000416 reg_num, // GDB reg num
417 reg_num // native register number
Greg Clayton435d85a2012-02-29 19:27:27 +0000418 },
419 NULL,
420 NULL
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000421 };
422
423 while (response.GetNameColonValue(name, value))
424 {
425 if (name.compare("name") == 0)
426 {
427 reg_name.SetCString(value.c_str());
428 }
429 else if (name.compare("alt-name") == 0)
430 {
431 alt_name.SetCString(value.c_str());
432 }
433 else if (name.compare("bitsize") == 0)
434 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000435 reg_info.byte_size = StringConvert::ToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000436 }
437 else if (name.compare("offset") == 0)
438 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000439 uint32_t offset = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda743e86a2010-06-11 23:44:18 +0000440 if (reg_offset != offset)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000441 {
442 reg_offset = offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000443 }
444 }
445 else if (name.compare("encoding") == 0)
446 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000447 const Encoding encoding = Args::StringToEncoding (value.c_str());
448 if (encoding != eEncodingInvalid)
449 reg_info.encoding = encoding;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000450 }
451 else if (name.compare("format") == 0)
452 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000453 Format format = eFormatInvalid;
454 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
455 reg_info.format = format;
456 else if (value.compare("binary") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000457 reg_info.format = eFormatBinary;
458 else if (value.compare("decimal") == 0)
459 reg_info.format = eFormatDecimal;
460 else if (value.compare("hex") == 0)
461 reg_info.format = eFormatHex;
462 else if (value.compare("float") == 0)
463 reg_info.format = eFormatFloat;
464 else if (value.compare("vector-sint8") == 0)
465 reg_info.format = eFormatVectorOfSInt8;
466 else if (value.compare("vector-uint8") == 0)
467 reg_info.format = eFormatVectorOfUInt8;
468 else if (value.compare("vector-sint16") == 0)
469 reg_info.format = eFormatVectorOfSInt16;
470 else if (value.compare("vector-uint16") == 0)
471 reg_info.format = eFormatVectorOfUInt16;
472 else if (value.compare("vector-sint32") == 0)
473 reg_info.format = eFormatVectorOfSInt32;
474 else if (value.compare("vector-uint32") == 0)
475 reg_info.format = eFormatVectorOfUInt32;
476 else if (value.compare("vector-float32") == 0)
477 reg_info.format = eFormatVectorOfFloat32;
478 else if (value.compare("vector-uint128") == 0)
479 reg_info.format = eFormatVectorOfUInt128;
480 }
481 else if (name.compare("set") == 0)
482 {
483 set_name.SetCString(value.c_str());
484 }
485 else if (name.compare("gcc") == 0)
486 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000487 reg_info.kinds[eRegisterKindGCC] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000488 }
489 else if (name.compare("dwarf") == 0)
490 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000491 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000492 }
493 else if (name.compare("generic") == 0)
494 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000495 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000496 }
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000497 else if (name.compare("container-regs") == 0)
498 {
499 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
500 value_pair.second = value;
501 do
502 {
503 value_pair = value_pair.second.split(',');
504 if (!value_pair.first.empty())
505 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000506 uint32_t reg = StringConvert::ToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
Greg Clayton0ba20242013-01-21 23:32:42 +0000507 if (reg != LLDB_INVALID_REGNUM)
508 value_regs.push_back (reg);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000509 }
510 } while (!value_pair.second.empty());
511 }
512 else if (name.compare("invalidate-regs") == 0)
513 {
514 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
515 value_pair.second = value;
516 do
517 {
518 value_pair = value_pair.second.split(',');
519 if (!value_pair.first.empty())
520 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000521 uint32_t reg = StringConvert::ToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
Greg Clayton0ba20242013-01-21 23:32:42 +0000522 if (reg != LLDB_INVALID_REGNUM)
523 invalidate_regs.push_back (reg);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000524 }
525 } while (!value_pair.second.empty());
526 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000527 }
528
Jason Molenda743e86a2010-06-11 23:44:18 +0000529 reg_info.byte_offset = reg_offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000530 assert (reg_info.byte_size != 0);
531 reg_offset += reg_info.byte_size;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000532 if (!value_regs.empty())
533 {
534 value_regs.push_back(LLDB_INVALID_REGNUM);
535 reg_info.value_regs = value_regs.data();
536 }
537 if (!invalidate_regs.empty())
538 {
539 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
540 reg_info.invalidate_regs = invalidate_regs.data();
541 }
542
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000543 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
544 }
Todd Fiala1a634402014-01-08 07:52:40 +0000545 else
546 {
547 break; // ensure exit before reg_num is incremented
548 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000549 }
550 else
551 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000552 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000553 }
554 }
555
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000556 // Check if qHostInfo specified a specific packet timeout for this connection.
557 // If so then lets update our setting so the user knows what the timeout is
558 // and can see it.
559 const uint32_t host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
560 if (host_packet_timeout)
561 {
562 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout);
563 }
564
565
Greg Claytonef8180a2013-10-15 00:14:28 +0000566 if (reg_num == 0)
567 {
568 FileSpec target_definition_fspec = GetGlobalPluginProperties()->GetTargetDefinitionFile ();
Greg Clayton312bcbe2013-10-17 01:10:23 +0000569
570 if (target_definition_fspec)
Greg Claytonef8180a2013-10-15 00:14:28 +0000571 {
Greg Clayton312bcbe2013-10-17 01:10:23 +0000572 // See if we can get register definitions from a python file
573 if (ParsePythonTargetDefinition (target_definition_fspec))
574 return;
Greg Claytonef8180a2013-10-15 00:14:28 +0000575 }
576 }
577
Johnny Chen2fa9de12012-05-14 18:44:23 +0000578 // We didn't get anything if the accumulated reg_num is zero. See if we are
579 // debugging ARM and fill with a hard coded register set until we can get an
580 // updated debugserver down on the devices.
581 // On the other hand, if the accumulated reg_num is positive, see if we can
582 // add composite registers to the existing primordial ones.
583 bool from_scratch = (reg_num == 0);
584
585 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000586 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
587 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
588
589 // Use the process' architecture instead of the host arch, if available
590 ArchSpec remote_arch;
591 if (remote_process_arch.IsValid ())
592 remote_arch = remote_process_arch;
593 else
594 remote_arch = remote_host_arch;
595
Johnny Chen2fa9de12012-05-14 18:44:23 +0000596 if (!target_arch.IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000597 {
Johnny Chen2fa9de12012-05-14 18:44:23 +0000598 if (remote_arch.IsValid()
599 && remote_arch.GetMachine() == llvm::Triple::arm
600 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
601 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000602 }
Johnny Chen2fa9de12012-05-14 18:44:23 +0000603 else if (target_arch.GetMachine() == llvm::Triple::arm)
604 {
605 m_register_info.HardcodeARMRegisters(from_scratch);
606 }
607
608 // At this point, we can finalize our register info.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000609 m_register_info.Finalize ();
610}
611
612Error
613ProcessGDBRemote::WillLaunch (Module* module)
614{
615 return WillLaunchOrAttach ();
616}
617
618Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000619ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000620{
621 return WillLaunchOrAttach ();
622}
623
624Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000625ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000626{
627 return WillLaunchOrAttach ();
628}
629
630Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000631ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +0000632{
Todd Fialaaf245d12014-06-30 21:05:18 +0000633 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Claytonb766a732011-02-04 01:58:07 +0000634 Error error (WillLaunchOrAttach ());
635
636 if (error.Fail())
637 return error;
638
Greg Clayton2289fa42011-04-30 01:09:13 +0000639 error = ConnectToDebugserver (remote_url);
Greg Claytonb766a732011-02-04 01:58:07 +0000640
641 if (error.Fail())
642 return error;
643 StartAsyncThread ();
644
Greg Claytonc574ede2011-03-10 02:26:48 +0000645 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonb766a732011-02-04 01:58:07 +0000646 if (pid == LLDB_INVALID_PROCESS_ID)
647 {
648 // We don't have a valid process ID, so note that we are connected
649 // and could now request to launch or attach, or get remote process
650 // listings...
651 SetPrivateState (eStateConnected);
652 }
653 else
654 {
655 // We have a valid process
656 SetID (pid);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000657 GetThreadList();
Greg Clayton3dedae12013-12-06 21:45:27 +0000658 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false) == GDBRemoteCommunication::PacketResult::Success)
Greg Claytonb766a732011-02-04 01:58:07 +0000659 {
Jason Molendac62bd7b2013-12-21 05:20:36 +0000660 if (!m_target.GetArchitecture().IsValid())
661 {
662 if (m_gdb_comm.GetProcessArchitecture().IsValid())
663 {
664 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
665 }
666 else
667 {
668 m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
669 }
Carlo Kok74389122013-10-14 07:09:13 +0000670 }
671
Greg Claytondd0e5a52011-06-02 22:22:38 +0000672 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytonb766a732011-02-04 01:58:07 +0000673 if (state == eStateStopped)
674 {
675 SetPrivateState (state);
676 }
677 else
Daniel Malead01b2952012-11-29 21:49:15 +0000678 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 +0000679 }
680 else
Daniel Malead01b2952012-11-29 21:49:15 +0000681 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 +0000682 }
Jason Molenda16d127c2012-05-03 22:37:30 +0000683
Todd Fialaaf245d12014-06-30 21:05:18 +0000684 if (log)
685 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");
686
687
688 if (error.Success()
Jason Molenda16d127c2012-05-03 22:37:30 +0000689 && !GetTarget().GetArchitecture().IsValid()
690 && m_gdb_comm.GetHostArchitecture().IsValid())
691 {
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000692 // Prefer the *process'* architecture over that of the *host*, if available.
693 if (m_gdb_comm.GetProcessArchitecture().IsValid())
694 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
695 else
696 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molenda16d127c2012-05-03 22:37:30 +0000697 }
698
Todd Fialaaf245d12014-06-30 21:05:18 +0000699 if (log)
700 log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": normalized target architecture triple: %s", __FUNCTION__, GetID (), GetTarget ().GetArchitecture ().GetTriple ().getTriple ().c_str ());
701
702 // Set the Unix signals properly for the target.
703 // FIXME Add a gdb-remote packet to discover dynamically.
704 if (error.Success ())
705 {
706 const ArchSpec arch_spec = GetTarget ().GetArchitecture ();
707 if (arch_spec.IsValid ())
708 {
709 if (log)
710 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 ());
711
712 switch (arch_spec.GetTriple ().getOS ())
713 {
714 case llvm::Triple::Linux:
Todd Fiala4ceced32014-08-29 17:35:57 +0000715 SetUnixSignals (UnixSignalsSP (new process_linux::LinuxSignals ()));
Todd Fialaaf245d12014-06-30 21:05:18 +0000716 if (log)
717 log->Printf ("ProcessGDBRemote::%s using Linux unix signals type for pid %" PRIu64, __FUNCTION__, GetID ());
718 break;
719 case llvm::Triple::OpenBSD:
720 case llvm::Triple::FreeBSD:
721 case llvm::Triple::NetBSD:
Todd Fiala4ceced32014-08-29 17:35:57 +0000722 SetUnixSignals (UnixSignalsSP (new FreeBSDSignals ()));
Todd Fialaaf245d12014-06-30 21:05:18 +0000723 if (log)
724 log->Printf ("ProcessGDBRemote::%s using *BSD unix signals type for pid %" PRIu64, __FUNCTION__, GetID ());
725 break;
726 default:
Todd Fiala4ceced32014-08-29 17:35:57 +0000727 SetUnixSignals (UnixSignalsSP (new UnixSignals ()));
Todd Fialaaf245d12014-06-30 21:05:18 +0000728 if (log)
729 log->Printf ("ProcessGDBRemote::%s using generic unix signals type for pid %" PRIu64, __FUNCTION__, GetID ());
730 break;
731 }
732 }
733 }
734
Greg Claytonb766a732011-02-04 01:58:07 +0000735 return error;
736}
737
738Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000739ProcessGDBRemote::WillLaunchOrAttach ()
740{
741 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000742 m_stdio_communication.Clear ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000743 return error;
744}
745
746//----------------------------------------------------------------------
747// Process Control
748//----------------------------------------------------------------------
749Error
Jean-Daniel Dupas7782de92013-12-09 22:52:50 +0000750ProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000751{
Todd Fiala75f47c32014-10-11 21:42:09 +0000752 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton4957bf62010-09-30 21:49:03 +0000753 Error error;
Greg Clayton982c9762011-11-03 21:22:33 +0000754
Todd Fiala75f47c32014-10-11 21:42:09 +0000755 if (log)
756 log->Printf ("ProcessGDBRemote::%s() entered", __FUNCTION__);
757
Greg Clayton982c9762011-11-03 21:22:33 +0000758 uint32_t launch_flags = launch_info.GetFlags().Get();
759 const char *stdin_path = NULL;
760 const char *stdout_path = NULL;
761 const char *stderr_path = NULL;
762 const char *working_dir = launch_info.GetWorkingDirectory();
763
Zachary Turner696b5282014-08-14 16:01:25 +0000764 const FileAction *file_action;
Greg Clayton982c9762011-11-03 21:22:33 +0000765 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
766 if (file_action)
767 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000768 if (file_action->GetAction() == FileAction::eFileActionOpen)
Greg Clayton982c9762011-11-03 21:22:33 +0000769 stdin_path = file_action->GetPath();
770 }
771 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
772 if (file_action)
773 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000774 if (file_action->GetAction() == FileAction::eFileActionOpen)
Greg Clayton982c9762011-11-03 21:22:33 +0000775 stdout_path = file_action->GetPath();
776 }
777 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
778 if (file_action)
779 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000780 if (file_action->GetAction() == FileAction::eFileActionOpen)
Greg Clayton982c9762011-11-03 21:22:33 +0000781 stderr_path = file_action->GetPath();
782 }
783
Todd Fiala75f47c32014-10-11 21:42:09 +0000784 if (log)
785 {
786 if (stdin_path || stdout_path || stderr_path)
787 log->Printf ("ProcessGDBRemote::%s provided with STDIO paths via launch_info: stdin=%s, stdout=%s, stdout=%s",
788 __FUNCTION__,
789 stdin_path ? stdin_path : "<null>",
790 stdout_path ? stdout_path : "<null>",
791 stderr_path ? stderr_path : "<null>");
792 else
793 log->Printf ("ProcessGDBRemote::%s no STDIO paths given via launch_info", __FUNCTION__);
794 }
795
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000796 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
797 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
798 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000799
Greg Clayton982c9762011-11-03 21:22:33 +0000800 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000801 if (object_file)
802 {
Greg Clayton71337622011-02-24 22:24:29 +0000803 // Make sure we aren't already connected?
804 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000805 {
Greg Clayton91a9b2472013-12-04 19:19:12 +0000806 error = LaunchAndConnectToDebugserver (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000807 }
808
809 if (error.Success())
810 {
811 lldb_utility::PseudoTerminal pty;
812 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000813
814 // If the debugserver is local and we aren't disabling STDIO, lets use
815 // a pseudo terminal to instead of relying on the 'O' packets for stdio
816 // since 'O' packets can really slow down debugging if the inferior
817 // does a lot of output.
Greg Claytonf58c2692011-06-24 22:32:10 +0000818 PlatformSP platform_sp (m_target.GetPlatform());
819 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Clayton71337622011-02-24 22:24:29 +0000820 {
821 const char *slave_name = NULL;
822 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000823 {
Greg Clayton71337622011-02-24 22:24:29 +0000824 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
825 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000826 }
Greg Clayton71337622011-02-24 22:24:29 +0000827 if (stdin_path == NULL)
828 stdin_path = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000829
Greg Clayton71337622011-02-24 22:24:29 +0000830 if (stdout_path == NULL)
831 stdout_path = slave_name;
832
833 if (stderr_path == NULL)
834 stderr_path = slave_name;
Todd Fiala75f47c32014-10-11 21:42:09 +0000835
836 if (log)
837 log->Printf ("ProcessGDBRemote::%s adjusted STDIO paths for local platform (IsHost() is true) using slave: stdin=%s, stdout=%s, stdout=%s",
838 __FUNCTION__,
839 stdin_path ? stdin_path : "<null>",
840 stdout_path ? stdout_path : "<null>",
841 stderr_path ? stderr_path : "<null>");
Greg Clayton71337622011-02-24 22:24:29 +0000842 }
843
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000844 // Set STDIN to /dev/null if we want STDIO disabled or if either
845 // STDOUT or STDERR have been set to something and STDIN hasn't
846 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000847 stdin_path = "/dev/null";
848
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000849 // Set STDOUT to /dev/null if we want STDIO disabled or if either
850 // STDIN or STDERR have been set to something and STDOUT hasn't
851 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000852 stdout_path = "/dev/null";
853
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000854 // Set STDERR to /dev/null if we want STDIO disabled or if either
855 // STDIN or STDOUT have been set to something and STDERR hasn't
856 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000857 stderr_path = "/dev/null";
858
Todd Fiala75f47c32014-10-11 21:42:09 +0000859 if (log)
860 log->Printf ("ProcessGDBRemote::%s final STDIO paths after all adjustments: stdin=%s, stdout=%s, stdout=%s",
861 __FUNCTION__,
862 stdin_path ? stdin_path : "<null>",
863 stdout_path ? stdout_path : "<null>",
864 stderr_path ? stderr_path : "<null>");
865
866 if (stdin_path)
Greg Clayton71337622011-02-24 22:24:29 +0000867 m_gdb_comm.SetSTDIN (stdin_path);
868 if (stdout_path)
869 m_gdb_comm.SetSTDOUT (stdout_path);
870 if (stderr_path)
871 m_gdb_comm.SetSTDERR (stderr_path);
872
873 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
Jim Ingham106d0282014-06-25 02:32:56 +0000874 m_gdb_comm.SetDetachOnError (launch_flags & eLaunchFlagDetachOnError);
Greg Clayton71337622011-02-24 22:24:29 +0000875
Greg Claytonc4103b32011-05-08 04:53:50 +0000876 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Clayton71337622011-02-24 22:24:29 +0000877
Jason Molendaa3329782014-03-29 18:54:20 +0000878 const char * launch_event_data = launch_info.GetLaunchEventData();
879 if (launch_event_data != NULL && *launch_event_data != '\0')
880 m_gdb_comm.SendLaunchEventDataPacket (launch_event_data);
881
Greg Clayton71337622011-02-24 22:24:29 +0000882 if (working_dir && working_dir[0])
883 {
884 m_gdb_comm.SetWorkingDir (working_dir);
885 }
886
887 // Send the environment and the program + arguments after we connect
Greg Clayton982c9762011-11-03 21:22:33 +0000888 const Args &environment = launch_info.GetEnvironmentEntries();
889 if (environment.GetArgumentCount())
Greg Clayton71337622011-02-24 22:24:29 +0000890 {
Greg Clayton982c9762011-11-03 21:22:33 +0000891 size_t num_environment_entries = environment.GetArgumentCount();
892 for (size_t i=0; i<num_environment_entries; ++i)
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000893 {
Greg Clayton982c9762011-11-03 21:22:33 +0000894 const char *env_entry = environment.GetArgumentAtIndex(i);
895 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Clayton71337622011-02-24 22:24:29 +0000896 break;
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000897 }
Greg Clayton71337622011-02-24 22:24:29 +0000898 }
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000899
Greg Claytonc574ede2011-03-10 02:26:48 +0000900 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Claytonfbb76342013-11-20 21:07:01 +0000901 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000902 if (arg_packet_err == 0)
903 {
904 std::string error_str;
Greg Claytonc574ede2011-03-10 02:26:48 +0000905 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000906 {
Greg Claytonc574ede2011-03-10 02:26:48 +0000907 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000908 }
909 else
910 {
Greg Clayton71337622011-02-24 22:24:29 +0000911 error.SetErrorString (error_str.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000912 }
Greg Clayton71337622011-02-24 22:24:29 +0000913 }
914 else
915 {
Greg Clayton86edbf42011-10-26 00:56:27 +0000916 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Clayton71337622011-02-24 22:24:29 +0000917 }
Greg Clayton8b45bee2011-08-10 22:05:39 +0000918
919 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000920
Greg Clayton71337622011-02-24 22:24:29 +0000921 if (GetID() == LLDB_INVALID_PROCESS_ID)
922 {
Johnny Chen4c1e9202011-08-09 18:56:45 +0000923 if (log)
924 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton71337622011-02-24 22:24:29 +0000925 KillDebugserverProcess ();
926 return error;
927 }
928
Greg Clayton3dedae12013-12-06 21:45:27 +0000929 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton71337622011-02-24 22:24:29 +0000930 {
Jason Molendac62bd7b2013-12-21 05:20:36 +0000931 if (!m_target.GetArchitecture().IsValid())
932 {
933 if (m_gdb_comm.GetProcessArchitecture().IsValid())
934 {
935 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
936 }
937 else
938 {
939 m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
940 }
Carlo Kok74389122013-10-14 07:09:13 +0000941 }
942
Greg Claytondd0e5a52011-06-02 22:22:38 +0000943 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Clayton71337622011-02-24 22:24:29 +0000944
945 if (!disable_stdio)
946 {
947 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Claytonee95ed52011-11-17 22:14:31 +0000948 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Clayton71337622011-02-24 22:24:29 +0000949 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000950 }
951 }
Greg Claytonc235ac72011-08-09 05:20:29 +0000952 else
953 {
Johnny Chen4c1e9202011-08-09 18:56:45 +0000954 if (log)
955 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytonc235ac72011-08-09 05:20:29 +0000956 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000957 }
958 else
959 {
960 // Set our user ID to an invalid process ID.
961 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton982c9762011-11-03 21:22:33 +0000962 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
963 exe_module->GetFileSpec().GetFilename().AsCString(),
964 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000965 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000966 return error;
Greg Clayton4957bf62010-09-30 21:49:03 +0000967
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000968}
969
970
971Error
Greg Claytonb766a732011-02-04 01:58:07 +0000972ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000973{
974 Error error;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000975 // Only connect if we have a valid connect URL
976
977 if (connect_url && connect_url[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000978 {
Greg Clayton00fe87b2013-12-05 22:58:22 +0000979 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
980 if (conn_ap.get())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000981 {
Greg Clayton00fe87b2013-12-05 22:58:22 +0000982 const uint32_t max_retry_count = 50;
983 uint32_t retry_count = 0;
984 while (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000985 {
Greg Clayton00fe87b2013-12-05 22:58:22 +0000986 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
987 {
988 m_gdb_comm.SetConnection (conn_ap.release());
989 break;
990 }
991 else if (error.WasInterrupted())
992 {
993 // If we were interrupted, don't keep retrying.
994 break;
995 }
996
997 retry_count++;
998
999 if (retry_count >= max_retry_count)
1000 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001001
Greg Clayton00fe87b2013-12-05 22:58:22 +00001002 usleep (100000);
1003 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001004 }
1005 }
1006
1007 if (!m_gdb_comm.IsConnected())
1008 {
1009 if (error.Success())
1010 error.SetErrorString("not connected to remote gdb server");
1011 return error;
1012 }
1013
Greg Clayton32e0a752011-03-30 18:16:51 +00001014 // We always seem to be able to open a connection to a local port
1015 // so we need to make sure we can then send data to it. If we can't
1016 // then we aren't actually connected to anything, so try and do the
1017 // handshake with the remote GDB server and make sure that goes
1018 // alright.
Greg Claytonfb909312013-11-23 01:58:15 +00001019 if (!m_gdb_comm.HandshakeWithServer (&error))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001020 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001021 m_gdb_comm.Disconnect();
1022 if (error.Success())
1023 error.SetErrorString("not connected to remote gdb server");
1024 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001025 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001026 m_gdb_comm.GetThreadSuffixSupported ();
Greg Clayton44633992012-04-10 03:22:03 +00001027 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001028 m_gdb_comm.GetHostInfo ();
1029 m_gdb_comm.GetVContSupported ('c');
Jim Inghamcd16df92012-07-20 21:37:13 +00001030 m_gdb_comm.GetVAttachOrWaitSupported();
Jim Ingham03afad82012-07-02 05:40:07 +00001031
1032 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1033 for (size_t idx = 0; idx < num_cmds; idx++)
1034 {
1035 StringExtractorGDBRemote response;
Jim Ingham03afad82012-07-02 05:40:07 +00001036 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1037 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001038 return error;
1039}
1040
1041void
Jim Inghambb006ce2014-08-02 00:33:35 +00001042ProcessGDBRemote::DidLaunchOrAttach (ArchSpec& process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001043{
Greg Clayton5160ce52013-03-27 23:08:40 +00001044 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001045 if (log)
1046 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton93d3c8332011-02-16 04:46:07 +00001047 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001048 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001049 BuildDynamicRegisterInfo (false);
Greg Clayton3af9ea52010-11-18 05:57:03 +00001050
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001051 // See if the GDB server supports the qHostInfo information
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001052
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001053
1054 // See if the GDB server supports the qProcessInfo packet, if so
1055 // prefer that over the Host information as it will be more specific
1056 // to our process.
1057
Todd Fiala75f47c32014-10-11 21:42:09 +00001058 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1059 if (remote_process_arch.IsValid())
1060 {
1061 process_arch = remote_process_arch;
1062 if (log)
1063 log->Printf ("ProcessGDBRemote::%s gdb-remote had process architecture, using %s %s",
1064 __FUNCTION__,
1065 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1066 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1067 }
Jim Inghambb006ce2014-08-02 00:33:35 +00001068 else
Todd Fiala75f47c32014-10-11 21:42:09 +00001069 {
Jim Inghambb006ce2014-08-02 00:33:35 +00001070 process_arch = m_gdb_comm.GetHostArchitecture();
Todd Fiala75f47c32014-10-11 21:42:09 +00001071 if (log)
1072 log->Printf ("ProcessGDBRemote::%s gdb-remote did not have process architecture, using gdb-remote host architecture %s %s",
1073 __FUNCTION__,
1074 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1075 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1076 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001077
Jim Inghambb006ce2014-08-02 00:33:35 +00001078 if (process_arch.IsValid())
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001079 {
Greg Claytond314e812011-03-23 00:09:55 +00001080 ArchSpec &target_arch = GetTarget().GetArchitecture();
Greg Claytond314e812011-03-23 00:09:55 +00001081 if (target_arch.IsValid())
1082 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001083 if (log)
1084 log->Printf ("ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1085 __FUNCTION__,
1086 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1087 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
1088
1089 // If the remote host is ARM and we have apple as the vendor, then
Greg Claytond314e812011-03-23 00:09:55 +00001090 // ARM executables and shared libraries can have mixed ARM architectures.
1091 // You can have an armv6 executable, and if the host is armv7, then the
1092 // system will load the best possible architecture for all shared libraries
1093 // it has, so we really need to take the remote host architecture as our
1094 // defacto architecture in this case.
1095
Jim Inghambb006ce2014-08-02 00:33:35 +00001096 if (process_arch.GetMachine() == llvm::Triple::arm &&
1097 process_arch.GetTriple().getVendor() == llvm::Triple::Apple)
Greg Claytond314e812011-03-23 00:09:55 +00001098 {
Jason Molenda921c01b2014-08-03 21:42:52 +00001099 GetTarget().SetArchitecture (process_arch);
Todd Fiala75f47c32014-10-11 21:42:09 +00001100 if (log)
1101 log->Printf ("ProcessGDBRemote::%s remote process is ARM/Apple, setting target arch to %s %s",
1102 __FUNCTION__,
1103 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1104 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001105 }
1106 else
1107 {
1108 // Fill in what is missing in the triple
Jim Inghambb006ce2014-08-02 00:33:35 +00001109 const llvm::Triple &remote_triple = process_arch.GetTriple();
Greg Claytond314e812011-03-23 00:09:55 +00001110 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton70b57652011-05-15 01:25:55 +00001111 if (target_triple.getVendorName().size() == 0)
1112 {
Greg Claytond314e812011-03-23 00:09:55 +00001113 target_triple.setVendor (remote_triple.getVendor());
1114
Greg Clayton70b57652011-05-15 01:25:55 +00001115 if (target_triple.getOSName().size() == 0)
1116 {
1117 target_triple.setOS (remote_triple.getOS());
Greg Claytond314e812011-03-23 00:09:55 +00001118
Greg Clayton70b57652011-05-15 01:25:55 +00001119 if (target_triple.getEnvironmentName().size() == 0)
1120 target_triple.setEnvironment (remote_triple.getEnvironment());
1121 }
1122 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001123
Greg Claytond314e812011-03-23 00:09:55 +00001124 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001125
1126 if (log)
1127 log->Printf ("ProcessGDBRemote::%s final target arch after adjustments for remote architecture: %s %s",
1128 __FUNCTION__,
1129 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1130 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001131 }
1132 else
1133 {
1134 // The target doesn't have a valid architecture yet, set it from
1135 // the architecture we got from the remote GDB server
Jason Molenda921c01b2014-08-03 21:42:52 +00001136 GetTarget().SetArchitecture (process_arch);
Greg Claytond314e812011-03-23 00:09:55 +00001137 }
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001138 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001139 }
1140}
1141
1142void
1143ProcessGDBRemote::DidLaunch ()
1144{
Jim Inghambb006ce2014-08-02 00:33:35 +00001145 ArchSpec process_arch;
1146 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001147}
1148
1149Error
Greg Claytonc982c762010-07-09 20:39:50 +00001150ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001151{
Han Ming Ong84647042012-02-25 01:07:38 +00001152 ProcessAttachInfo attach_info;
1153 return DoAttachToProcessWithID(attach_pid, attach_info);
1154}
1155
1156Error
1157ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1158{
Todd Fiala75f47c32014-10-11 21:42:09 +00001159 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001160 Error error;
Todd Fiala75f47c32014-10-11 21:42:09 +00001161
1162 if (log)
1163 log->Printf ("ProcessGDBRemote::%s()", __FUNCTION__);
1164
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001165 // Clear out and clean up from any current state
1166 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001167 if (attach_pid != LLDB_INVALID_PROCESS_ID)
1168 {
Greg Clayton71337622011-02-24 22:24:29 +00001169 // Make sure we aren't already connected?
1170 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001171 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001172 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001173
1174 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001175 {
Greg Clayton71337622011-02-24 22:24:29 +00001176 const char *error_string = error.AsCString();
1177 if (error_string == NULL)
1178 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1179
1180 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001181 }
Greg Clayton71337622011-02-24 22:24:29 +00001182 }
1183
1184 if (error.Success())
1185 {
Jim Ingham106d0282014-06-25 02:32:56 +00001186 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
Todd Fiala75f47c32014-10-11 21:42:09 +00001187
Greg Clayton71337622011-02-24 22:24:29 +00001188 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001189 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Greg Clayton3b608422011-11-19 02:11:30 +00001190 SetID (attach_pid);
Greg Clayton71337622011-02-24 22:24:29 +00001191 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001192 }
1193 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001194
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001195 return error;
1196}
1197
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001198Error
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001199ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001200{
1201 Error error;
1202 // Clear out and clean up from any current state
1203 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001204
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001205 if (process_name && process_name[0])
1206 {
Greg Clayton71337622011-02-24 22:24:29 +00001207 // Make sure we aren't already connected?
1208 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001209 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001210 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001211
Greg Clayton71337622011-02-24 22:24:29 +00001212 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001213 {
Greg Clayton71337622011-02-24 22:24:29 +00001214 const char *error_string = error.AsCString();
1215 if (error_string == NULL)
1216 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001217
Greg Clayton71337622011-02-24 22:24:29 +00001218 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001219 }
Greg Clayton71337622011-02-24 22:24:29 +00001220 }
1221
1222 if (error.Success())
1223 {
1224 StreamString packet;
1225
Jim Ingham106d0282014-06-25 02:32:56 +00001226 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1227
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001228 if (attach_info.GetWaitForLaunch())
Jim Inghamcd16df92012-07-20 21:37:13 +00001229 {
1230 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1231 {
1232 packet.PutCString ("vAttachWait");
1233 }
1234 else
1235 {
1236 if (attach_info.GetIgnoreExisting())
1237 packet.PutCString("vAttachWait");
1238 else
1239 packet.PutCString ("vAttachOrWait");
1240 }
1241 }
Greg Clayton71337622011-02-24 22:24:29 +00001242 else
1243 packet.PutCString("vAttachName");
1244 packet.PutChar(';');
1245 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1246
1247 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1248
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001249 }
1250 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001251 return error;
1252}
1253
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001254
Greg Claytonfbb76342013-11-20 21:07:01 +00001255bool
1256ProcessGDBRemote::SetExitStatus (int exit_status, const char *cstr)
1257{
1258 m_gdb_comm.Disconnect();
1259 return Process::SetExitStatus (exit_status, cstr);
1260}
1261
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001262void
Jim Inghambb006ce2014-08-02 00:33:35 +00001263ProcessGDBRemote::DidAttach (ArchSpec &process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001264{
Jim Inghambb006ce2014-08-02 00:33:35 +00001265 // If you can figure out what the architecture is, fill it in here.
1266 process_arch.Clear();
1267 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001268}
1269
Greg Clayton90ba8112012-12-05 00:16:59 +00001270
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001271Error
1272ProcessGDBRemote::WillResume ()
1273{
Greg Clayton71fc2a32011-02-12 06:28:37 +00001274 m_continue_c_tids.clear();
1275 m_continue_C_tids.clear();
1276 m_continue_s_tids.clear();
1277 m_continue_S_tids.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001278 return Error();
1279}
1280
1281Error
1282ProcessGDBRemote::DoResume ()
1283{
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001284 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001285 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001286 if (log)
1287 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytone5219662010-12-03 06:02:24 +00001288
1289 Listener listener ("gdb-remote.resume-packet-sent");
1290 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1291 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00001292 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1293
Greg Claytond1d06e42013-04-20 00:27:58 +00001294 const size_t num_threads = GetThreadList().GetSize();
1295
Greg Clayton71fc2a32011-02-12 06:28:37 +00001296 StreamString continue_packet;
1297 bool continue_packet_error = false;
1298 if (m_gdb_comm.HasAnyVContSupport ())
1299 {
Greg Claytone98008c2014-02-13 23:34:38 +00001300 if (m_continue_c_tids.size() == num_threads ||
1301 (m_continue_c_tids.empty() &&
1302 m_continue_C_tids.empty() &&
1303 m_continue_s_tids.empty() &&
1304 m_continue_S_tids.empty()))
Greg Clayton71fc2a32011-02-12 06:28:37 +00001305 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001306 // All threads are continuing, just send a "c" packet
1307 continue_packet.PutCString ("c");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001308 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001309 else
1310 {
1311 continue_packet.PutCString ("vCont");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001312
Greg Claytond1d06e42013-04-20 00:27:58 +00001313 if (!m_continue_c_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001314 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001315 if (m_gdb_comm.GetVContSupported ('c'))
1316 {
1317 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)
1318 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1319 }
1320 else
1321 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001322 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001323
1324 if (!continue_packet_error && !m_continue_C_tids.empty())
1325 {
1326 if (m_gdb_comm.GetVContSupported ('C'))
1327 {
1328 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)
1329 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1330 }
1331 else
1332 continue_packet_error = true;
1333 }
Greg Claytone5219662010-12-03 06:02:24 +00001334
Greg Claytond1d06e42013-04-20 00:27:58 +00001335 if (!continue_packet_error && !m_continue_s_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001336 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001337 if (m_gdb_comm.GetVContSupported ('s'))
1338 {
1339 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)
1340 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1341 }
1342 else
1343 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001344 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001345
1346 if (!continue_packet_error && !m_continue_S_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001347 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001348 if (m_gdb_comm.GetVContSupported ('S'))
1349 {
1350 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)
1351 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1352 }
1353 else
1354 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001355 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001356
1357 if (continue_packet_error)
1358 continue_packet.GetString().clear();
Greg Clayton71fc2a32011-02-12 06:28:37 +00001359 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001360 }
1361 else
1362 continue_packet_error = true;
1363
1364 if (continue_packet_error)
1365 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001366 // Either no vCont support, or we tried to use part of the vCont
1367 // packet that wasn't supported by the remote GDB server.
1368 // We need to try and make a simple packet that can do our continue
Greg Clayton71fc2a32011-02-12 06:28:37 +00001369 const size_t num_continue_c_tids = m_continue_c_tids.size();
1370 const size_t num_continue_C_tids = m_continue_C_tids.size();
1371 const size_t num_continue_s_tids = m_continue_s_tids.size();
1372 const size_t num_continue_S_tids = m_continue_S_tids.size();
1373 if (num_continue_c_tids > 0)
1374 {
1375 if (num_continue_c_tids == num_threads)
1376 {
1377 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001378 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001379 continue_packet.PutChar ('c');
1380 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001381 }
1382 else if (num_continue_c_tids == 1 &&
1383 num_continue_C_tids == 0 &&
1384 num_continue_s_tids == 0 &&
1385 num_continue_S_tids == 0 )
1386 {
1387 // Only one thread is continuing
Greg Clayton8b82f082011-04-12 05:54:46 +00001388 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001389 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001390 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001391 }
1392 }
1393
Greg Clayton0c74e782011-06-24 03:21:43 +00001394 if (continue_packet_error && num_continue_C_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001395 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001396 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1397 num_continue_C_tids > 0 &&
1398 num_continue_s_tids == 0 &&
1399 num_continue_S_tids == 0 )
Greg Clayton71fc2a32011-02-12 06:28:37 +00001400 {
1401 const int continue_signo = m_continue_C_tids.front().second;
Greg Clayton0c74e782011-06-24 03:21:43 +00001402 // Only one thread is continuing
Greg Clayton71fc2a32011-02-12 06:28:37 +00001403 if (num_continue_C_tids > 1)
1404 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001405 // More that one thread with a signal, yet we don't have
1406 // vCont support and we are being asked to resume each
1407 // thread with a signal, we need to make sure they are
1408 // all the same signal, or we can't issue the continue
1409 // accurately with the current support...
1410 if (num_continue_C_tids > 1)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001411 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001412 continue_packet_error = false;
1413 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1414 {
1415 if (m_continue_C_tids[i].second != continue_signo)
1416 continue_packet_error = true;
1417 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001418 }
Greg Clayton0c74e782011-06-24 03:21:43 +00001419 if (!continue_packet_error)
1420 m_gdb_comm.SetCurrentThreadForRun (-1);
1421 }
1422 else
1423 {
1424 // Set the continue thread ID
1425 continue_packet_error = false;
1426 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001427 }
1428 if (!continue_packet_error)
1429 {
1430 // Add threads continuing with the same signo...
Greg Clayton71fc2a32011-02-12 06:28:37 +00001431 continue_packet.Printf("C%2.2x", continue_signo);
1432 }
1433 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001434 }
1435
Greg Clayton0c74e782011-06-24 03:21:43 +00001436 if (continue_packet_error && num_continue_s_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001437 {
1438 if (num_continue_s_tids == num_threads)
1439 {
1440 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001441 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001442 continue_packet.PutChar ('s');
1443 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001444 }
1445 else if (num_continue_c_tids == 0 &&
1446 num_continue_C_tids == 0 &&
1447 num_continue_s_tids == 1 &&
1448 num_continue_S_tids == 0 )
1449 {
1450 // Only one thread is stepping
Greg Clayton8b82f082011-04-12 05:54:46 +00001451 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001452 continue_packet.PutChar ('s');
Greg Clayton0c74e782011-06-24 03:21:43 +00001453 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001454 }
1455 }
1456
1457 if (!continue_packet_error && num_continue_S_tids > 0)
1458 {
1459 if (num_continue_S_tids == num_threads)
1460 {
1461 const int step_signo = m_continue_S_tids.front().second;
1462 // Are all threads trying to step with the same signal?
Greg Clayton0c74e782011-06-24 03:21:43 +00001463 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001464 if (num_continue_S_tids > 1)
1465 {
1466 for (size_t i=1; i<num_threads; ++i)
1467 {
1468 if (m_continue_S_tids[i].second != step_signo)
1469 continue_packet_error = true;
1470 }
1471 }
1472 if (!continue_packet_error)
1473 {
1474 // Add threads stepping with the same signo...
Greg Clayton8b82f082011-04-12 05:54:46 +00001475 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001476 continue_packet.Printf("S%2.2x", step_signo);
1477 }
1478 }
1479 else if (num_continue_c_tids == 0 &&
1480 num_continue_C_tids == 0 &&
1481 num_continue_s_tids == 0 &&
1482 num_continue_S_tids == 1 )
1483 {
1484 // Only one thread is stepping with signal
Greg Clayton8b82f082011-04-12 05:54:46 +00001485 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001486 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Clayton0c74e782011-06-24 03:21:43 +00001487 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001488 }
1489 }
1490 }
1491
1492 if (continue_packet_error)
1493 {
1494 error.SetErrorString ("can't make continue packet for this resume");
1495 }
1496 else
1497 {
1498 EventSP event_sp;
1499 TimeValue timeout;
1500 timeout = TimeValue::Now();
1501 timeout.OffsetWithSeconds (5);
Zachary Turneracee96a2014-09-23 18:32:09 +00001502 if (!m_async_thread.IsJoinable())
Jim Inghamb1e2e842012-04-12 18:49:31 +00001503 {
1504 error.SetErrorString ("Trying to resume but the async thread is dead.");
1505 if (log)
1506 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1507 return error;
1508 }
1509
Greg Clayton71fc2a32011-02-12 06:28:37 +00001510 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1511
1512 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Inghamb1e2e842012-04-12 18:49:31 +00001513 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001514 error.SetErrorString("Resume timed out.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00001515 if (log)
1516 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1517 }
1518 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1519 {
1520 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1521 if (log)
1522 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1523 return error;
1524 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001525 }
Greg Claytone5219662010-12-03 06:02:24 +00001526 }
1527
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001528 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001529}
1530
Greg Clayton9e920902012-04-10 02:25:43 +00001531void
1532ProcessGDBRemote::ClearThreadIDList ()
1533{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001534 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001535 m_thread_ids.clear();
1536}
1537
1538bool
1539ProcessGDBRemote::UpdateThreadIDList ()
1540{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001541 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001542 bool sequence_mutex_unavailable = false;
1543 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1544 if (sequence_mutex_unavailable)
1545 {
Greg Clayton9e920902012-04-10 02:25:43 +00001546 return false; // We just didn't get the list
1547 }
1548 return true;
1549}
1550
Greg Clayton9fc13552012-04-10 00:18:59 +00001551bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001552ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001553{
1554 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +00001555 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Clayton73b472d2010-10-27 03:32:59 +00001556 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +00001557 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton9e920902012-04-10 02:25:43 +00001558
1559 size_t num_thread_ids = m_thread_ids.size();
1560 // The "m_thread_ids" thread ID list should always be updated after each stop
1561 // reply packet, but in case it isn't, update it here.
1562 if (num_thread_ids == 0)
1563 {
1564 if (!UpdateThreadIDList ())
1565 return false;
1566 num_thread_ids = m_thread_ids.size();
1567 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001568
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001569 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001570 if (num_thread_ids > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001571 {
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001572 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001573 {
Greg Clayton9e920902012-04-10 02:25:43 +00001574 tid_t tid = m_thread_ids[i];
Greg Clayton160c9d82013-05-01 21:54:04 +00001575 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001576 if (!thread_sp)
Jim Inghamdee1bc92013-06-22 00:27:45 +00001577 {
Jim Ingham4f465cf2012-10-10 18:32:14 +00001578 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001579 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1580 log->Printf(
1581 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001582 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001583 thread_sp->GetID());
1584 }
1585 else
1586 {
1587 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1588 log->Printf(
1589 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001590 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001591 thread_sp->GetID());
1592 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001593 new_thread_list.AddThread(thread_sp);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001594 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001595 }
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001596
1597 // Whatever that is left in old_thread_list_copy are not
1598 // present in new_thread_list. Remove non-existent threads from internal id table.
1599 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1600 for (size_t i=0; i<old_num_thread_ids; i++)
1601 {
1602 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1603 if (old_thread_sp)
1604 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001605 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001606 m_thread_id_to_index_id_map.erase(old_thread_id);
1607 }
1608 }
1609
Greg Clayton9fc13552012-04-10 00:18:59 +00001610 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001611}
1612
1613
1614StateType
1615ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1616{
Greg Claytondd0e5a52011-06-02 22:22:38 +00001617 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001618 const char stop_type = stop_packet.GetChar();
1619 switch (stop_type)
1620 {
1621 case 'T':
1622 case 'S':
1623 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00001624 // This is a bit of a hack, but is is required. If we did exec, we
1625 // need to clear our thread lists and also know to rebuild our dynamic
1626 // register info before we lookup and threads and populate the expedited
1627 // register values so we need to know this right away so we can cleanup
1628 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00001629 const uint32_t stop_id = GetStopID();
1630 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00001631 {
1632 // Our first stop, make sure we have a process ID, and also make
1633 // sure we know about our registers
1634 if (GetID() == LLDB_INVALID_PROCESS_ID)
1635 {
Greg Claytonc574ede2011-03-10 02:26:48 +00001636 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00001637 if (pid != LLDB_INVALID_PROCESS_ID)
1638 SetID (pid);
1639 }
1640 BuildDynamicRegisterInfo (true);
1641 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001642 // Stop with signal and thread info
1643 const uint8_t signo = stop_packet.GetHexU8();
1644 std::string name;
1645 std::string value;
1646 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00001647 std::string reason;
1648 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001649 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00001650 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001651 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001652 ThreadSP thread_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001653 ThreadGDBRemote *gdb_thread = NULL;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001654
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001655 while (stop_packet.GetNameColonValue(name, value))
1656 {
1657 if (name.compare("metype") == 0)
1658 {
1659 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001660 exc_type = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001661 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001662 else if (name.compare("medata") == 0)
1663 {
1664 // exception data in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001665 exc_data.push_back(StringConvert::ToUInt64 (value.c_str(), 0, 16));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001666 }
1667 else if (name.compare("thread") == 0)
1668 {
1669 // thread in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001670 lldb::tid_t tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001671 // m_thread_list_real does have its own mutex, but we need to
1672 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1673 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1674 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1675 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
Greg Clayton160c9d82013-05-01 21:54:04 +00001676
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001677 if (!thread_sp)
Greg Claytond1d06e42013-04-20 00:27:58 +00001678 {
Greg Claytone576ab22011-02-15 00:19:15 +00001679 // Create the thread if we need to
Jim Ingham4f465cf2012-10-10 18:32:14 +00001680 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001681 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
1682 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1683 log->Printf ("ProcessGDBRemote::%s Adding new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1684 __FUNCTION__,
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001685 static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001686 thread_sp->GetID());
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001687
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001688 m_thread_list_real.AddThread(thread_sp);
Greg Claytone576ab22011-02-15 00:19:15 +00001689 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001690 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1691
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001692 }
Greg Clayton9e920902012-04-10 02:25:43 +00001693 else if (name.compare("threads") == 0)
1694 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001695 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001696 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00001697 // A comma separated list of all threads in the current
1698 // process that includes the thread for this stop reply
1699 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00001700 size_t comma_pos;
1701 lldb::tid_t tid;
1702 while ((comma_pos = value.find(',')) != std::string::npos)
1703 {
1704 value[comma_pos] = '\0';
1705 // thread in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001706 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00001707 if (tid != LLDB_INVALID_THREAD_ID)
1708 m_thread_ids.push_back (tid);
1709 value.erase(0, comma_pos + 1);
Greg Clayton9e920902012-04-10 02:25:43 +00001710 }
Vince Harron5275aaa2015-01-15 20:08:35 +00001711 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00001712 if (tid != LLDB_INVALID_THREAD_ID)
1713 m_thread_ids.push_back (tid);
1714 }
Greg Claytonde9d0492011-01-08 03:17:57 +00001715 else if (name.compare("hexname") == 0)
1716 {
1717 StringExtractor name_extractor;
1718 // Swap "value" over into "name_extractor"
1719 name_extractor.GetStringRef().swap(value);
1720 // Now convert the HEX bytes into a string value
1721 name_extractor.GetHexByteString (value);
1722 thread_name.swap (value);
1723 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001724 else if (name.compare("name") == 0)
1725 {
1726 thread_name.swap (value);
1727 }
Greg Clayton6f35f5c2010-09-09 06:32:46 +00001728 else if (name.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001729 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001730 thread_dispatch_qaddr = StringConvert::ToUInt64 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001731 }
Greg Claytona658fd22011-06-04 01:26:29 +00001732 else if (name.compare("reason") == 0)
1733 {
1734 reason.swap(value);
1735 }
1736 else if (name.compare("description") == 0)
1737 {
1738 StringExtractor desc_extractor;
1739 // Swap "value" over into "name_extractor"
1740 desc_extractor.GetStringRef().swap(value);
1741 // Now convert the HEX bytes into a string value
1742 desc_extractor.GetHexByteString (thread_name);
1743 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001744 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1745 {
1746 // We have a register number that contains an expedited
1747 // register value. Lets supply this register to our thread
1748 // so it won't have to go and read it.
Greg Clayton160c9d82013-05-01 21:54:04 +00001749 if (gdb_thread)
Greg Clayton3e06bd92011-01-09 21:07:35 +00001750 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001751 uint32_t reg = StringConvert::ToUInt32 (name.c_str(), UINT32_MAX, 16);
Greg Clayton3e06bd92011-01-09 21:07:35 +00001752
1753 if (reg != UINT32_MAX)
1754 {
1755 StringExtractor reg_value_extractor;
1756 // Swap "value" over into "reg_value_extractor"
1757 reg_value_extractor.GetStringRef().swap(value);
Greg Clayton160c9d82013-05-01 21:54:04 +00001758 if (!gdb_thread->PrivateSetRegisterValue (reg, reg_value_extractor))
Greg Claytone576ab22011-02-15 00:19:15 +00001759 {
1760 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1761 name.c_str(),
1762 reg,
1763 reg,
1764 reg_value_extractor.GetStringRef().c_str(),
1765 stop_packet.GetStringRef().c_str());
1766 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001767 }
1768 }
1769 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001770 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001771
Hafiz Abid Qadeer673b4a32014-02-20 10:23:20 +00001772 // If the response is old style 'S' packet which does not provide us with thread information
1773 // then update the thread list and choose the first one.
1774 if (!thread_sp)
1775 {
1776 UpdateThreadIDList ();
1777
1778 if (!m_thread_ids.empty ())
1779 {
1780 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1781 thread_sp = m_thread_list_real.FindThreadByProtocolID (m_thread_ids.front (), false);
1782 if (thread_sp)
1783 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get ());
1784 }
1785 }
1786
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001787 if (thread_sp)
1788 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001789 // Clear the stop info just in case we don't set it to anything
1790 thread_sp->SetStopInfo (StopInfoSP());
1791
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001792 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Inghamdd2fe7a2011-01-28 02:23:12 +00001793 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001794 if (exc_type != 0)
1795 {
Greg Clayton1a65ae12011-01-25 23:55:37 +00001796 const size_t exc_data_size = exc_data.size();
Greg Claytonf4b47e12010-08-04 01:40:35 +00001797
Greg Clayton160c9d82013-05-01 21:54:04 +00001798 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1799 exc_type,
1800 exc_data_size,
1801 exc_data_size >= 1 ? exc_data[0] : 0,
1802 exc_data_size >= 2 ? exc_data[1] : 0,
1803 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001804 }
Greg Claytona658fd22011-06-04 01:26:29 +00001805 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001806 {
Greg Claytona658fd22011-06-04 01:26:29 +00001807 bool handled = false;
Greg Clayton8cda7f02013-05-21 21:55:59 +00001808 bool did_exec = false;
Greg Claytona658fd22011-06-04 01:26:29 +00001809 if (!reason.empty())
1810 {
1811 if (reason.compare("trace") == 0)
1812 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001813 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Greg Claytona658fd22011-06-04 01:26:29 +00001814 handled = true;
1815 }
1816 else if (reason.compare("breakpoint") == 0)
1817 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001818 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1819 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Claytona658fd22011-06-04 01:26:29 +00001820 if (bp_site_sp)
1821 {
1822 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1823 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1824 // 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 +00001825 handled = true;
Greg Clayton160c9d82013-05-01 21:54:04 +00001826 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00001827 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001828 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00001829 }
1830 else
1831 {
1832 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001833 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00001834 }
1835 }
Greg Claytona658fd22011-06-04 01:26:29 +00001836 }
1837 else if (reason.compare("trap") == 0)
1838 {
1839 // Let the trap just use the standard signal stop reason below...
1840 }
1841 else if (reason.compare("watchpoint") == 0)
1842 {
1843 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1844 // TODO: locate the watchpoint somehow...
Greg Clayton160c9d82013-05-01 21:54:04 +00001845 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
Greg Claytona658fd22011-06-04 01:26:29 +00001846 handled = true;
1847 }
1848 else if (reason.compare("exception") == 0)
1849 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001850 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00001851 handled = true;
1852 }
Greg Clayton15fc2be2013-05-21 01:00:52 +00001853 else if (reason.compare("exec") == 0)
1854 {
Greg Clayton8cda7f02013-05-21 21:55:59 +00001855 did_exec = true;
Greg Clayton15fc2be2013-05-21 01:00:52 +00001856 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
1857 handled = true;
1858 }
Greg Claytona658fd22011-06-04 01:26:29 +00001859 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001860
Jim Ingham40083a42014-02-24 19:49:46 +00001861 if (!handled && signo && did_exec == false)
Greg Claytona658fd22011-06-04 01:26:29 +00001862 {
1863 if (signo == SIGTRAP)
1864 {
1865 // Currently we are going to assume SIGTRAP means we are either
1866 // hitting a breakpoint or hardware single stepping.
Jim Ingham54cc6e42012-07-11 21:41:19 +00001867 handled = true;
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +00001868 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
Greg Clayton160c9d82013-05-01 21:54:04 +00001869 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001870
Greg Claytona658fd22011-06-04 01:26:29 +00001871 if (bp_site_sp)
1872 {
1873 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1874 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1875 // 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 +00001876 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00001877 {
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +00001878 if(m_breakpoint_pc_offset != 0)
1879 thread_sp->GetRegisterContext()->SetPC(pc);
Greg Clayton160c9d82013-05-01 21:54:04 +00001880 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00001881 }
1882 else
1883 {
1884 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001885 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00001886 }
1887 }
Jim Ingham54cc6e42012-07-11 21:41:19 +00001888 else
Greg Claytona658fd22011-06-04 01:26:29 +00001889 {
Jim Ingham4dc613b2012-10-27 02:52:04 +00001890 // If we were stepping then assume the stop was the result of the trace. If we were
1891 // not stepping then report the SIGTRAP.
1892 // FIXME: We are still missing the case where we single step over a trap instruction.
Greg Clayton160c9d82013-05-01 21:54:04 +00001893 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1894 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Jim Ingham4dc613b2012-10-27 02:52:04 +00001895 else
Greg Clayton160c9d82013-05-01 21:54:04 +00001896 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo));
Greg Claytona658fd22011-06-04 01:26:29 +00001897 }
1898 }
1899 if (!handled)
Greg Clayton160c9d82013-05-01 21:54:04 +00001900 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Jason Molenda8214b012013-04-25 01:33:46 +00001901 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001902
Greg Claytona658fd22011-06-04 01:26:29 +00001903 if (!description.empty())
1904 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001905 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
Greg Claytona658fd22011-06-04 01:26:29 +00001906 if (stop_info_sp)
1907 {
1908 stop_info_sp->SetDescription (description.c_str());
Greg Clayton3418c852011-08-10 02:10:13 +00001909 }
Greg Claytona658fd22011-06-04 01:26:29 +00001910 else
1911 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001912 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00001913 }
1914 }
1915 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001916 }
1917 return eStateStopped;
1918 }
1919 break;
1920
1921 case 'W':
Todd Fialaff6131a2014-05-19 04:57:23 +00001922 case 'X':
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001923 // process exited
1924 return eStateExited;
1925
1926 default:
1927 break;
1928 }
1929 return eStateInvalid;
1930}
1931
1932void
1933ProcessGDBRemote::RefreshStateAfterStop ()
1934{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001935 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001936 m_thread_ids.clear();
1937 // Set the thread stop info. It might have a "threads" key whose value is
1938 // a list of all thread IDs in the current process, so m_thread_ids might
1939 // get set.
1940 SetThreadStopInfo (m_last_stop_packet);
1941 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1942 if (m_thread_ids.empty())
1943 {
1944 // No, we need to fetch the thread list manually
1945 UpdateThreadIDList();
1946 }
1947
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001948 // Let all threads recover from stopping and do any clean up based
1949 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001950 m_thread_list_real.RefreshStateAfterStop();
Greg Clayton9e920902012-04-10 02:25:43 +00001951
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001952}
1953
1954Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001955ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001956{
1957 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001958
Greg Clayton6ed95942011-01-22 07:12:45 +00001959 bool timed_out = false;
1960 Mutex::Locker locker;
Greg Clayton513c26c2011-01-29 07:10:55 +00001961
1962 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00001963 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001964 // We are being asked to halt during an attach. We need to just close
1965 // our file handle and debugserver will go away, and we can be done...
1966 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00001967 }
Greg Clayton513c26c2011-01-29 07:10:55 +00001968 else
1969 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001970 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton513c26c2011-01-29 07:10:55 +00001971 {
1972 if (timed_out)
1973 error.SetErrorString("timed out sending interrupt packet");
1974 else
1975 error.SetErrorString("unknown error sending interrupt packet");
1976 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001977
1978 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton513c26c2011-01-29 07:10:55 +00001979 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001980 return error;
1981}
1982
1983Error
Jim Inghamacff8952013-05-02 00:27:30 +00001984ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00001985{
1986 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001987 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00001988 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00001989 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
1990
Jim Inghamacff8952013-05-02 00:27:30 +00001991 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001992 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00001993 {
Jim Inghamacff8952013-05-02 00:27:30 +00001994 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001995 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1996 else
Jim Inghamacff8952013-05-02 00:27:30 +00001997 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00001998 }
Jim Inghamacff8952013-05-02 00:27:30 +00001999
2000 if (!error.Success())
2001 return error;
2002
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002003 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00002004 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002005
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002006 SetPrivateState (eStateDetached);
2007 ResumePrivateStateThread();
2008
2009 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00002010 return error;
2011}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002012
Jim Ingham43c555d2012-07-04 00:35:43 +00002013
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002014Error
2015ProcessGDBRemote::DoDestroy ()
2016{
2017 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002018 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002019 if (log)
2020 log->Printf ("ProcessGDBRemote::DoDestroy()");
2021
Jim Ingham43c555d2012-07-04 00:35:43 +00002022 // There is a bug in older iOS debugservers where they don't shut down the process
2023 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
2024 // this can cause problems with restarting. So we check to see if any of our threads are stopped
2025 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
2026 // destroy it again.
2027 //
2028 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
2029 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
2030 // the debugservers with this bug are equal. There really should be a better way to test this!
2031 //
2032 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
2033 // get called here to destroy again and we're still at a breakpoint or exception, then we should
2034 // just do the straight-forward kill.
2035 //
2036 // And of course, if we weren't able to stop the process by the time we get here, it isn't
2037 // necessary (or helpful) to do any of this.
2038
2039 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
2040 {
2041 PlatformSP platform_sp = GetTarget().GetPlatform();
2042
2043 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2044 if (platform_sp
2045 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00002046 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00002047 {
2048 if (m_destroy_tried_resuming)
2049 {
2050 if (log)
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002051 log->PutCString ("ProcessGDBRemote::DoDestroy() - Tried resuming to destroy once already, not doing it again.");
Jim Ingham43c555d2012-07-04 00:35:43 +00002052 }
2053 else
2054 {
2055 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
2056 // but we really need it to happen here and it doesn't matter if we do it twice.
2057 m_thread_list.DiscardThreadPlans();
2058 DisableAllBreakpointSites();
2059
2060 bool stop_looks_like_crash = false;
2061 ThreadList &threads = GetThreadList();
2062
2063 {
Jim Ingham45350372012-09-11 00:08:52 +00002064 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002065
2066 size_t num_threads = threads.GetSize();
2067 for (size_t i = 0; i < num_threads; i++)
2068 {
2069 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002070 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002071 StopReason reason = eStopReasonInvalid;
2072 if (stop_info_sp)
2073 reason = stop_info_sp->GetStopReason();
2074 if (reason == eStopReasonBreakpoint
2075 || reason == eStopReasonException)
2076 {
2077 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002078 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
2079 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00002080 stop_info_sp->GetDescription());
2081 stop_looks_like_crash = true;
2082 break;
2083 }
2084 }
2085 }
2086
2087 if (stop_looks_like_crash)
2088 {
2089 if (log)
2090 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
2091 m_destroy_tried_resuming = true;
2092
2093 // If we are going to run again before killing, it would be good to suspend all the threads
2094 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
2095 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
2096 // have to run the risk of letting those threads proceed a bit.
2097
2098 {
Jim Ingham45350372012-09-11 00:08:52 +00002099 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002100
2101 size_t num_threads = threads.GetSize();
2102 for (size_t i = 0; i < num_threads; i++)
2103 {
2104 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002105 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002106 StopReason reason = eStopReasonInvalid;
2107 if (stop_info_sp)
2108 reason = stop_info_sp->GetStopReason();
2109 if (reason != eStopReasonBreakpoint
2110 && reason != eStopReasonException)
2111 {
2112 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002113 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
2114 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00002115 thread_sp->SetResumeState(eStateSuspended);
2116 }
2117 }
2118 }
2119 Resume ();
2120 return Destroy();
2121 }
2122 }
2123 }
2124 }
2125
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002126 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00002127 int exit_status = SIGABRT;
2128 std::string exit_string;
2129
Greg Clayton6ed95942011-01-22 07:12:45 +00002130 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002131 {
Jim Inghamaab78372011-10-28 01:11:35 +00002132 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00002133 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002134
2135 StringExtractorGDBRemote response;
2136 bool send_async = true;
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002137 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3);
2138
Greg Clayton3dedae12013-12-06 21:45:27 +00002139 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton513c26c2011-01-29 07:10:55 +00002140 {
2141 char packet_cmd = response.GetChar(0);
2142
2143 if (packet_cmd == 'W' || packet_cmd == 'X')
2144 {
Jim Inghameac0aa42014-02-21 22:36:11 +00002145#if defined(__APPLE__)
Jim Ingham9d67cc52014-02-21 22:35:29 +00002146 // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off
2147 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill
2148 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns
2149 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap
2150 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of
2151 // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2152 // Anyway, so call waitpid here to finally reap it.
2153 PlatformSP platform_sp(GetTarget().GetPlatform());
2154 if (platform_sp && platform_sp->IsHost())
2155 {
2156 int status;
2157 ::pid_t reap_pid;
2158 reap_pid = waitpid (GetID(), &status, WNOHANG);
2159 if (log)
2160 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2161 }
2162#endif
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002163 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002164 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00002165 exit_status = response.GetHexU8();
2166 }
2167 else
2168 {
2169 if (log)
2170 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2171 exit_string.assign("got unexpected response to k packet: ");
2172 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00002173 }
2174 }
2175 else
2176 {
Jim Inghambabfc382012-06-06 00:32:39 +00002177 if (log)
2178 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2179 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00002180 }
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002181
2182 m_gdb_comm.SetPacketTimeout(old_packet_timeout);
Greg Clayton6779606a2011-01-22 23:43:18 +00002183 }
Jim Inghambabfc382012-06-06 00:32:39 +00002184 else
2185 {
2186 if (log)
Ed Masteb3a53332014-03-17 17:05:22 +00002187 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching");
Jim Inghamcfc09352012-07-27 23:57:19 +00002188 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00002189 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002190 }
Jim Inghambabfc382012-06-06 00:32:39 +00002191 else
2192 {
2193 // If we missed setting the exit status on the way out, do it here.
2194 // NB set exit status can be called multiple times, the first one sets the status.
2195 exit_string.assign("destroying when not connected to debugserver");
2196 }
2197
2198 SetExitStatus(exit_status, exit_string.c_str());
2199
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002200 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002201 KillDebugserverProcess ();
2202 return error;
2203}
2204
Greg Clayton8cda7f02013-05-21 21:55:59 +00002205void
2206ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2207{
2208 lldb_private::Mutex::Locker locker (m_last_stop_packet_mutex);
2209 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2210 if (did_exec)
2211 {
2212 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2213 if (log)
2214 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2215
2216 m_thread_list_real.Clear();
2217 m_thread_list.Clear();
2218 BuildDynamicRegisterInfo (true);
2219 m_gdb_comm.ResetDiscoverableSettings();
2220 }
2221 m_last_stop_packet = response;
2222}
2223
2224
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002225//------------------------------------------------------------------
2226// Process Queries
2227//------------------------------------------------------------------
2228
2229bool
2230ProcessGDBRemote::IsAlive ()
2231{
Greg Clayton10177aa2010-12-08 05:08:21 +00002232 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002233}
2234
2235addr_t
2236ProcessGDBRemote::GetImageInfoAddress()
2237{
Jason Molenda6ba6d3d2013-01-30 04:39:32 +00002238 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002239}
2240
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002241//------------------------------------------------------------------
2242// Process Memory
2243//------------------------------------------------------------------
2244size_t
2245ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2246{
Jason Molenda6076bf42014-05-06 04:34:52 +00002247 GetMaxMemorySize ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002248 if (size > m_max_memory_size)
2249 {
2250 // Keep memory read sizes down to a sane limit. This function will be
2251 // called multiple times in order to complete the task by
2252 // lldb_private::Process so it is ok to do this.
2253 size = m_max_memory_size;
2254 }
2255
2256 char packet[64];
Jason Molenda6076bf42014-05-06 04:34:52 +00002257 int packet_len;
2258 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2259 if (binary_memory_read)
2260 {
2261 packet_len = ::snprintf (packet, sizeof(packet), "x0x%" PRIx64 ",0x%" PRIx64, (uint64_t)addr, (uint64_t)size);
2262 }
2263 else
2264 {
2265 packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
2266 }
Andy Gibbsa297a972013-06-19 19:04:53 +00002267 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002268 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002269 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002270 {
Greg Clayton576d8832011-03-22 04:00:09 +00002271 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002272 {
2273 error.Clear();
Jason Molenda6076bf42014-05-06 04:34:52 +00002274 if (binary_memory_read)
2275 {
2276 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any
2277 // 0x7d character escaping that was present in the packet
2278
2279 size_t data_received_size = response.GetBytesLeft();
2280 if (data_received_size > size)
2281 {
2282 // Don't write past the end of BUF if the remote debug server gave us too
2283 // much data for some reason.
2284 data_received_size = size;
2285 }
2286 memcpy (buf, response.GetStringRef().data(), data_received_size);
2287 return data_received_size;
2288 }
2289 else
2290 {
2291 return response.GetHexBytes(buf, size, '\xdd');
2292 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002293 }
Greg Clayton576d8832011-03-22 04:00:09 +00002294 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002295 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002296 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002297 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002298 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002299 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002300 }
2301 else
2302 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002303 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002304 }
2305 return 0;
2306}
2307
2308size_t
2309ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2310{
Jason Molenda6076bf42014-05-06 04:34:52 +00002311 GetMaxMemorySize ();
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002312 if (size > m_max_memory_size)
2313 {
2314 // Keep memory read sizes down to a sane limit. This function will be
2315 // called multiple times in order to complete the task by
2316 // lldb_private::Process so it is ok to do this.
2317 size = m_max_memory_size;
2318 }
2319
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002320 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00002321 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Clayton7fb56d02011-02-01 01:31:41 +00002322 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002323 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002324 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002325 {
Greg Clayton576d8832011-03-22 04:00:09 +00002326 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002327 {
2328 error.Clear();
2329 return size;
2330 }
Greg Clayton576d8832011-03-22 04:00:09 +00002331 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002332 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002333 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002334 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002335 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002336 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 +00002337 }
2338 else
2339 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002340 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002341 }
2342 return 0;
2343}
2344
2345lldb::addr_t
2346ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2347{
Todd Fialaaf245d12014-06-30 21:05:18 +00002348 lldb_private::Log *log (lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_EXPRESSIONS));
Greg Clayton2a48f522011-05-14 01:50:35 +00002349 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2350
Greg Clayton70b57652011-05-15 01:25:55 +00002351 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton2a48f522011-05-14 01:50:35 +00002352 switch (supported)
2353 {
2354 case eLazyBoolCalculate:
2355 case eLazyBoolYes:
2356 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2357 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2358 return allocated_addr;
2359
2360 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002361 // Call mmap() to create memory in the inferior..
2362 unsigned prot = 0;
2363 if (permissions & lldb::ePermissionsReadable)
2364 prot |= eMmapProtRead;
2365 if (permissions & lldb::ePermissionsWritable)
2366 prot |= eMmapProtWrite;
2367 if (permissions & lldb::ePermissionsExecutable)
2368 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00002369
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002370 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2371 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2372 m_addr_to_mmap_size[allocated_addr] = size;
2373 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002374 {
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002375 allocated_addr = LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00002376 if (log)
2377 log->Printf ("ProcessGDBRemote::%s no direct stub support for memory allocation, and InferiorCallMmap also failed - is stub missing register context save/restore capability?", __FUNCTION__);
2378 }
Greg Clayton2a48f522011-05-14 01:50:35 +00002379 break;
2380 }
2381
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002382 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00002383 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002384 else
2385 error.Clear();
2386 return allocated_addr;
2387}
2388
2389Error
Greg Clayton46fb5582011-11-18 07:03:08 +00002390ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2391 MemoryRegionInfo &region_info)
2392{
2393
2394 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2395 return error;
2396}
2397
2398Error
Johnny Chen64637202012-05-23 21:09:52 +00002399ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2400{
2401
2402 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2403 return error;
2404}
2405
2406Error
Enrico Granataf04a2192012-07-13 23:18:48 +00002407ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2408{
2409 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2410 return error;
2411}
2412
2413Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002414ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2415{
2416 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00002417 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2418
2419 switch (supported)
2420 {
2421 case eLazyBoolCalculate:
2422 // We should never be deallocating memory without allocating memory
2423 // first so we should never get eLazyBoolCalculate
2424 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2425 break;
2426
2427 case eLazyBoolYes:
2428 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00002429 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002430 break;
2431
2432 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002433 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00002434 {
2435 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002436 if (pos != m_addr_to_mmap_size.end() &&
2437 InferiorCallMunmap(this, addr, pos->second))
2438 m_addr_to_mmap_size.erase (pos);
2439 else
Daniel Malead01b2952012-11-29 21:49:15 +00002440 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002441 }
2442 break;
2443 }
2444
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002445 return error;
2446}
2447
2448
2449//------------------------------------------------------------------
2450// Process STDIO
2451//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002452size_t
2453ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2454{
2455 if (m_stdio_communication.IsConnected())
2456 {
2457 ConnectionStatus status;
2458 m_stdio_communication.Write(src, src_len, status, NULL);
2459 }
2460 return 0;
2461}
2462
2463Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002464ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002465{
2466 Error error;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002467 assert(bp_site != NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002468
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002469 // Get logging info
2470 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002471 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002472
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002473 // Get the breakpoint address
2474 const addr_t addr = bp_site->GetLoadAddress();
2475
2476 // Log that a breakpoint was requested
2477 if (log)
2478 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
2479
2480 // Breakpoint already exists and is enabled
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002481 if (bp_site->IsEnabled())
2482 {
2483 if (log)
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002484 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 +00002485 return error;
2486 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002487
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002488 // Get the software breakpoint trap opcode size
2489 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2490
2491 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
2492 // is supported by the remote stub. These are set to true by default, and later set to false
2493 // only after we receive an unimplemented response when sending a breakpoint packet. This means
2494 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
2495 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
2496 // indicates if the user specifically asked for hardware breakpoints. If true then we will
2497 // skip over software breakpoints.
2498 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
2499 {
2500 // Try to send off a software breakpoint packet ($Z0)
2501 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002502 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002503 // The breakpoint was placed successfully
2504 bp_site->SetEnabled(true);
2505 bp_site->SetType(BreakpointSite::eExternal);
Greg Claytoneb023e72013-10-11 19:48:25 +00002506 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002507 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002508
2509 // SendGDBStoppointTypePacket() will return an error if it was unable to set this
2510 // breakpoint. We need to differentiate between a error specific to placing this breakpoint
2511 // or if we have learned that this breakpoint type is unsupported. To do this, we
2512 // must test the support boolean for this breakpoint type to see if it now indicates that
2513 // this breakpoint type is unsupported. If they are still supported then we should return
2514 // with the error code. If they are now unsupported, then we would like to fall through
2515 // and try another form of breakpoint.
2516 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
2517 return error;
2518
2519 // We reach here when software breakpoints have been found to be unsupported. For future
2520 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
2521 // known not to be supported.
2522 if (log)
2523 log->Printf("Software breakpoints are unsupported");
2524
2525 // So we will fall through and try a hardware breakpoint
2526 }
2527
2528 // The process of setting a hardware breakpoint is much the same as above. We check the
2529 // supported boolean for this breakpoint type, and if it is thought to be supported then we
2530 // will try to set this breakpoint with a hardware breakpoint.
2531 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
2532 {
2533 // Try to send off a hardware breakpoint packet ($Z1)
2534 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002535 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002536 // The breakpoint was placed successfully
2537 bp_site->SetEnabled(true);
2538 bp_site->SetType(BreakpointSite::eHardware);
2539 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002540 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002541
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002542 // Check if the error was something other then an unsupported breakpoint type
2543 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
2544 {
2545 // Unable to set this hardware breakpoint
2546 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
2547 return error;
2548 }
2549
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002550 // We will reach here when the stub gives an unsupported response to a hardware breakpoint
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002551 if (log)
2552 log->Printf("Hardware breakpoints are unsupported");
2553
2554 // Finally we will falling through to a #trap style breakpoint
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002555 }
2556
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002557 // Don't fall through when hardware breakpoints were specifically requested
2558 if (bp_site->HardwareRequired())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002559 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002560 error.SetErrorString("hardware breakpoints are not supported");
2561 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002562 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002563
2564 // As a last resort we want to place a manual breakpoint. An instruction
2565 // is placed into the process memory using memory write packets.
2566 return EnableSoftwareBreakpoint(bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002567}
2568
2569Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002570ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002571{
2572 Error error;
2573 assert (bp_site != NULL);
2574 addr_t addr = bp_site->GetLoadAddress();
2575 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00002576 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002577 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002578 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002579
2580 if (bp_site->IsEnabled())
2581 {
2582 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2583
Greg Clayton8b82f082011-04-12 05:54:46 +00002584 BreakpointSite::Type bp_type = bp_site->GetType();
2585 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002586 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002587 case BreakpointSite::eSoftware:
2588 error = DisableSoftwareBreakpoint (bp_site);
2589 break;
2590
2591 case BreakpointSite::eHardware:
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002592 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00002593 error.SetErrorToGenericError();
2594 break;
2595
2596 case BreakpointSite::eExternal:
Jim Inghama04ef752014-03-07 11:18:02 +00002597 {
2598 GDBStoppointType stoppoint_type;
2599 if (bp_site->IsHardware())
2600 stoppoint_type = eBreakpointHardware;
2601 else
2602 stoppoint_type = eBreakpointSoftware;
2603
2604 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00002605 error.SetErrorToGenericError();
Jim Inghama04ef752014-03-07 11:18:02 +00002606 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002607 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002608 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002609 if (error.Success())
2610 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002611 }
2612 else
2613 {
2614 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002615 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 +00002616 return error;
2617 }
2618
2619 if (error.Success())
2620 error.SetErrorToGenericError();
2621 return error;
2622}
2623
Johnny Chen11309a32011-09-06 22:38:36 +00002624// Pre-requisite: wp != NULL.
2625static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00002626GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00002627{
2628 assert(wp);
2629 bool watch_read = wp->WatchpointRead();
2630 bool watch_write = wp->WatchpointWrite();
2631
2632 // watch_read and watch_write cannot both be false.
2633 assert(watch_read || watch_write);
2634 if (watch_read && watch_write)
2635 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00002636 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00002637 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00002638 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00002639 return eWatchpointWrite;
2640}
2641
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002642Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002643ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002644{
2645 Error error;
2646 if (wp)
2647 {
2648 user_id_t watchID = wp->GetID();
2649 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00002650 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002651 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002652 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002653 if (wp->IsEnabled())
2654 {
2655 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002656 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 +00002657 return error;
2658 }
Johnny Chen11309a32011-09-06 22:38:36 +00002659
2660 GDBStoppointType type = GetGDBStoppointType(wp);
2661 // Pass down an appropriate z/Z packet...
2662 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002663 {
Johnny Chen11309a32011-09-06 22:38:36 +00002664 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2665 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002666 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002667 return error;
2668 }
2669 else
2670 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002671 }
Johnny Chen11309a32011-09-06 22:38:36 +00002672 else
2673 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002674 }
2675 else
2676 {
Johnny Chen01a67862011-10-14 00:42:25 +00002677 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002678 }
2679 if (error.Success())
2680 error.SetErrorToGenericError();
2681 return error;
2682}
2683
2684Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002685ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002686{
2687 Error error;
2688 if (wp)
2689 {
2690 user_id_t watchID = wp->GetID();
2691
Greg Clayton5160ce52013-03-27 23:08:40 +00002692 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002693
2694 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00002695
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002696 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002697 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002698
Johnny Chen11309a32011-09-06 22:38:36 +00002699 if (!wp->IsEnabled())
2700 {
2701 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002702 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 +00002703 // See also 'class WatchpointSentry' within StopInfo.cpp.
2704 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2705 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00002706 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002707 return error;
2708 }
2709
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002710 if (wp->IsHardware())
2711 {
Johnny Chen11309a32011-09-06 22:38:36 +00002712 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002713 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00002714 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2715 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002716 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002717 return error;
2718 }
2719 else
2720 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002721 }
2722 // TODO: clear software watchpoints if we implement them
2723 }
2724 else
2725 {
Johnny Chen01a67862011-10-14 00:42:25 +00002726 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002727 }
2728 if (error.Success())
2729 error.SetErrorToGenericError();
2730 return error;
2731}
2732
2733void
2734ProcessGDBRemote::Clear()
2735{
2736 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002737 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002738 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002739}
2740
2741Error
2742ProcessGDBRemote::DoSignal (int signo)
2743{
2744 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002745 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002746 if (log)
2747 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2748
2749 if (!m_gdb_comm.SendAsyncSignal (signo))
2750 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2751 return error;
2752}
2753
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002754Error
Greg Clayton91a9b2472013-12-04 19:19:12 +00002755ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002756{
2757 Error error;
2758 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2759 {
2760 // If we locate debugserver, keep that located version around
2761 static FileSpec g_debugserver_file_spec;
2762
Han Ming Ong84647042012-02-25 01:07:38 +00002763 ProcessLaunchInfo debugserver_launch_info;
Greg Clayton91a9b2472013-12-04 19:19:12 +00002764 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2765 debugserver_launch_info.SetUserID(process_info.GetUserID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002766
Todd Fiala013434e2014-07-09 01:29:05 +00002767#if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__) || defined (__aarch64__))
Greg Claytonfda4fab2014-01-10 22:24:11 +00002768 // On iOS, still do a local connection using a random port
Greg Clayton16810922014-02-27 19:38:18 +00002769 const char *hostname = "127.0.0.1";
Greg Claytonfda4fab2014-01-10 22:24:11 +00002770 uint16_t port = get_random_port ();
2771#else
2772 // Set hostname being NULL to do the reverse connect where debugserver
2773 // will bind to port zero and it will communicate back to us the port
2774 // that we will connect to
2775 const char *hostname = NULL;
2776 uint16_t port = 0;
2777#endif
2778
2779 error = m_gdb_comm.StartDebugserverProcess (hostname,
2780 port,
Greg Clayton00fe87b2013-12-05 22:58:22 +00002781 debugserver_launch_info,
2782 port);
Greg Clayton91a9b2472013-12-04 19:19:12 +00002783
2784 if (error.Success ())
2785 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002786 else
Greg Clayton91a9b2472013-12-04 19:19:12 +00002787 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002788
2789 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2790 StartAsyncThread ();
Greg Clayton91a9b2472013-12-04 19:19:12 +00002791
2792 if (error.Fail())
2793 {
2794 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
2795
2796 if (log)
2797 log->Printf("failed to start debugserver process: %s", error.AsCString());
2798 return error;
2799 }
2800
Greg Clayton00fe87b2013-12-05 22:58:22 +00002801 if (m_gdb_comm.IsConnected())
2802 {
2803 // Finish the connection process by doing the handshake without connecting (send NULL URL)
2804 ConnectToDebugserver (NULL);
2805 }
2806 else
2807 {
Greg Claytonfda4fab2014-01-10 22:24:11 +00002808 StreamString connect_url;
2809 connect_url.Printf("connect://%s:%u", hostname, port);
2810 error = ConnectToDebugserver (connect_url.GetString().c_str());
Greg Clayton00fe87b2013-12-05 22:58:22 +00002811 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00002812
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002813 }
2814 return error;
2815}
2816
2817bool
2818ProcessGDBRemote::MonitorDebugserverProcess
2819(
2820 void *callback_baton,
2821 lldb::pid_t debugserver_pid,
Greg Claytone4e45922011-11-16 05:37:56 +00002822 bool exited, // True if the process did exit
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002823 int signo, // Zero for no signal
2824 int exit_status // Exit value of process if signal is zero
2825)
2826{
Greg Claytone4e45922011-11-16 05:37:56 +00002827 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2828 // and might not exist anymore, so we need to carefully try to get the
2829 // target for this process first since we have a race condition when
2830 // we are done running between getting the notice that the inferior
2831 // process has died and the debugserver that was debugging this process.
2832 // In our test suite, we are also continually running process after
2833 // process, so we must be very careful to make sure:
2834 // 1 - process object hasn't been deleted already
2835 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002836
2837 // "debugserver_pid" argument passed in is the process ID for
2838 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00002839 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002840
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002841 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton6779606a2011-01-22 23:43:18 +00002842
Greg Claytone4e45922011-11-16 05:37:56 +00002843 // Get a shared pointer to the target that has a matching process pointer.
2844 // This target could be gone, or the target could already have a new process
2845 // object inside of it
2846 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2847
Greg Clayton6779606a2011-01-22 23:43:18 +00002848 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002849 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 +00002850
Greg Claytone4e45922011-11-16 05:37:56 +00002851 if (target_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002852 {
Greg Claytone4e45922011-11-16 05:37:56 +00002853 // We found a process in a target that matches, but another thread
2854 // might be in the process of launching a new process that will
2855 // soon replace it, so get a shared pointer to the process so we
2856 // can keep it alive.
2857 ProcessSP process_sp (target_sp->GetProcessSP());
2858 // Now we have a shared pointer to the process that can't go away on us
2859 // so we now make sure it was the same as the one passed in, and also make
2860 // sure that our previous "process *" didn't get deleted and have a new
2861 // "process *" created in its place with the same pointer. To verify this
2862 // we make sure the process has our debugserver process ID. If we pass all
2863 // of these tests, then we are sure that this process is the one we were
2864 // looking for.
2865 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002866 {
Greg Claytone4e45922011-11-16 05:37:56 +00002867 // Sleep for a half a second to make sure our inferior process has
2868 // time to set its exit status before we set it incorrectly when
2869 // both the debugserver and the inferior process shut down.
2870 usleep (500000);
2871 // If our process hasn't yet exited, debugserver might have died.
2872 // If the process did exit, the we are reaping it.
2873 const StateType state = process->GetState();
2874
2875 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2876 state != eStateInvalid &&
2877 state != eStateUnloaded &&
2878 state != eStateExited &&
2879 state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002880 {
Greg Claytone4e45922011-11-16 05:37:56 +00002881 char error_str[1024];
2882 if (signo)
2883 {
2884 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2885 if (signal_cstr)
2886 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2887 else
2888 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2889 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002890 else
Greg Claytone4e45922011-11-16 05:37:56 +00002891 {
2892 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2893 }
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002894
Greg Claytone4e45922011-11-16 05:37:56 +00002895 process->SetExitStatus (-1, error_str);
2896 }
2897 // Debugserver has exited we need to let our ProcessGDBRemote
2898 // know that it no longer has a debugserver instance
2899 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002900 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002901 }
2902 return true;
2903}
2904
2905void
2906ProcessGDBRemote::KillDebugserverProcess ()
2907{
Greg Claytonfbb76342013-11-20 21:07:01 +00002908 m_gdb_comm.Disconnect();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002909 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2910 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002911 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002912 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2913 }
2914}
2915
2916void
2917ProcessGDBRemote::Initialize()
2918{
2919 static bool g_initialized = false;
2920
2921 if (g_initialized == false)
2922 {
2923 g_initialized = true;
2924 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2925 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00002926 CreateInstance,
2927 DebuggerInitialize);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002928
2929 Log::Callbacks log_callbacks = {
2930 ProcessGDBRemoteLog::DisableLog,
2931 ProcessGDBRemoteLog::EnableLog,
2932 ProcessGDBRemoteLog::ListLogCategories
2933 };
2934
2935 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2936 }
2937}
2938
Greg Clayton7f982402013-07-15 22:54:20 +00002939void
2940ProcessGDBRemote::DebuggerInitialize (lldb_private::Debugger &debugger)
2941{
2942 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
2943 {
2944 const bool is_global_setting = true;
2945 PluginManager::CreateSettingForProcessPlugin (debugger,
2946 GetGlobalPluginProperties()->GetValueProperties(),
2947 ConstString ("Properties for the gdb-remote process plug-in."),
2948 is_global_setting);
2949 }
2950}
2951
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002952bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002953ProcessGDBRemote::StartAsyncThread ()
2954{
Greg Clayton5160ce52013-03-27 23:08:40 +00002955 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002956
2957 if (log)
2958 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Ingham455fa5c2012-11-01 01:15:33 +00002959
2960 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00002961 if (!m_async_thread.IsJoinable())
Jim Ingham455fa5c2012-11-01 01:15:33 +00002962 {
2963 // Create a thread that watches our internal state and controls which
2964 // events make it to clients (into the DCProcess event queue).
Zachary Turner39de3112014-09-09 20:54:56 +00002965
2966 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Jim Ingham455fa5c2012-11-01 01:15:33 +00002967 }
Zachary Turneracee96a2014-09-23 18:32:09 +00002968 else if (log)
2969 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was already running.", __FUNCTION__);
Zachary Turner39de3112014-09-09 20:54:56 +00002970
Zachary Turneracee96a2014-09-23 18:32:09 +00002971 return m_async_thread.IsJoinable();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002972}
2973
2974void
2975ProcessGDBRemote::StopAsyncThread ()
2976{
Greg Clayton5160ce52013-03-27 23:08:40 +00002977 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002978
2979 if (log)
2980 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2981
Jim Ingham455fa5c2012-11-01 01:15:33 +00002982 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00002983 if (m_async_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002984 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00002985 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2986
2987 // This will shut down the async thread.
2988 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
2989
2990 // Stop the stdio thread
Zachary Turner39de3112014-09-09 20:54:56 +00002991 m_async_thread.Join(nullptr);
Jim Ingham455fa5c2012-11-01 01:15:33 +00002992 }
Zachary Turneracee96a2014-09-23 18:32:09 +00002993 else if (log)
2994 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002995}
2996
2997
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002998thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002999ProcessGDBRemote::AsyncThread (void *arg)
3000{
3001 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
3002
Greg Clayton5160ce52013-03-27 23:08:40 +00003003 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003004 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003005 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003006
3007 Listener listener ("ProcessGDBRemote::AsyncThread");
3008 EventSP event_sp;
3009 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
3010 eBroadcastBitAsyncThreadShouldExit;
3011
3012 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
3013 {
Greg Clayton71337622011-02-24 22:24:29 +00003014 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
3015
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003016 bool done = false;
3017 while (!done)
3018 {
3019 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003020 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003021 if (listener.WaitForEvent (NULL, event_sp))
3022 {
3023 const uint32_t event_type = event_sp->GetType();
Greg Clayton71337622011-02-24 22:24:29 +00003024 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003025 {
Greg Clayton71337622011-02-24 22:24:29 +00003026 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003027 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 +00003028
Greg Clayton71337622011-02-24 22:24:29 +00003029 switch (event_type)
3030 {
3031 case eBroadcastBitAsyncContinue:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003032 {
Greg Clayton71337622011-02-24 22:24:29 +00003033 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003034
Greg Clayton71337622011-02-24 22:24:29 +00003035 if (continue_packet)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003036 {
Greg Clayton71337622011-02-24 22:24:29 +00003037 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
3038 const size_t continue_cstr_len = continue_packet->GetByteSize ();
3039 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003040 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003041
Greg Clayton71337622011-02-24 22:24:29 +00003042 if (::strstr (continue_cstr, "vAttach") == NULL)
3043 process->SetPrivateState(eStateRunning);
3044 StringExtractorGDBRemote response;
3045 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003046
Greg Clayton0772ded2012-05-16 02:48:06 +00003047 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
3048 // The thread ID list might be contained within the "response", or the stop reply packet that
3049 // caused the stop. So clear it now before we give the stop reply packet to the process
3050 // using the process->SetLastStopPacket()...
3051 process->ClearThreadIDList ();
3052
Greg Clayton71337622011-02-24 22:24:29 +00003053 switch (stop_state)
3054 {
3055 case eStateStopped:
3056 case eStateCrashed:
3057 case eStateSuspended:
Greg Clayton09c3e3d2011-12-06 04:51:14 +00003058 process->SetLastStopPacket (response);
Greg Clayton71337622011-02-24 22:24:29 +00003059 process->SetPrivateState (stop_state);
3060 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003061
Greg Clayton71337622011-02-24 22:24:29 +00003062 case eStateExited:
Jason Molendaa3329782014-03-29 18:54:20 +00003063 {
Greg Clayton09c3e3d2011-12-06 04:51:14 +00003064 process->SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00003065 process->ClearThreadIDList();
Greg Clayton71337622011-02-24 22:24:29 +00003066 response.SetFilePos(1);
Jason Molendaa3329782014-03-29 18:54:20 +00003067
3068 int exit_status = response.GetHexU8();
3069 const char *desc_cstr = NULL;
3070 StringExtractor extractor;
3071 std::string desc_string;
3072 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';')
3073 {
3074 std::string desc_token;
3075 while (response.GetNameColonValue (desc_token, desc_string))
3076 {
3077 if (desc_token == "description")
3078 {
3079 extractor.GetStringRef().swap(desc_string);
3080 extractor.SetFilePos(0);
3081 extractor.GetHexByteString (desc_string);
3082 desc_cstr = desc_string.c_str();
3083 }
3084 }
3085 }
3086 process->SetExitStatus(exit_status, desc_cstr);
Greg Clayton71337622011-02-24 22:24:29 +00003087 done = true;
3088 break;
Jason Molendaa3329782014-03-29 18:54:20 +00003089 }
Greg Clayton71337622011-02-24 22:24:29 +00003090 case eStateInvalid:
3091 process->SetExitStatus(-1, "lost connection");
3092 break;
3093
3094 default:
3095 process->SetPrivateState (stop_state);
3096 break;
3097 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003098 }
3099 }
Greg Clayton71337622011-02-24 22:24:29 +00003100 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003101
Greg Clayton71337622011-02-24 22:24:29 +00003102 case eBroadcastBitAsyncThreadShouldExit:
3103 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003104 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Clayton71337622011-02-24 22:24:29 +00003105 done = true;
3106 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003107
Greg Clayton71337622011-02-24 22:24:29 +00003108 default:
3109 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003110 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 +00003111 done = true;
3112 break;
3113 }
3114 }
3115 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
3116 {
3117 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
3118 {
3119 process->SetExitStatus (-1, "lost connection");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003120 done = true;
Greg Clayton71337622011-02-24 22:24:29 +00003121 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003122 }
3123 }
3124 else
3125 {
3126 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003127 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 +00003128 done = true;
3129 }
3130 }
3131 }
3132
3133 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003134 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003135
Zachary Turner39de3112014-09-09 20:54:56 +00003136 process->m_async_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003137 return NULL;
3138}
3139
Greg Claytone996fd32011-03-08 22:40:15 +00003140//uint32_t
3141//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3142//{
3143// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
3144// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
3145// if (m_local_debugserver)
3146// {
3147// return Host::ListProcessesMatchingName (name, matches, pids);
3148// }
3149// else
3150// {
3151// // FIXME: Implement talking to the remote debugserver.
3152// return 0;
3153// }
3154//
3155//}
3156//
Jim Ingham1c823b42011-01-22 01:33:44 +00003157bool
3158ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
3159 lldb_private::StoppointCallbackContext *context,
3160 lldb::user_id_t break_id,
3161 lldb::user_id_t break_loc_id)
3162{
3163 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3164 // run so I can stop it if that's what I want to do.
Greg Clayton5160ce52013-03-27 23:08:40 +00003165 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00003166 if (log)
3167 log->Printf("Hit New Thread Notification breakpoint.");
3168 return false;
3169}
3170
3171
3172bool
3173ProcessGDBRemote::StartNoticingNewThreads()
3174{
Greg Clayton5160ce52013-03-27 23:08:40 +00003175 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00003176 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003177 {
Greg Clayton4116e932012-05-15 02:33:01 +00003178 if (log && log->GetVerbose())
3179 log->Printf("Enabled noticing new thread breakpoint.");
3180 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003181 }
Greg Clayton4116e932012-05-15 02:33:01 +00003182 else
Jim Ingham1c823b42011-01-22 01:33:44 +00003183 {
Greg Clayton4116e932012-05-15 02:33:01 +00003184 PlatformSP platform_sp (m_target.GetPlatform());
3185 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003186 {
Greg Clayton4116e932012-05-15 02:33:01 +00003187 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3188 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003189 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00003190 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00003191 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3192 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003193 }
3194 else
3195 {
3196 if (log)
3197 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00003198 }
3199 }
3200 }
Greg Clayton4116e932012-05-15 02:33:01 +00003201 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00003202}
3203
3204bool
3205ProcessGDBRemote::StopNoticingNewThreads()
3206{
Greg Clayton5160ce52013-03-27 23:08:40 +00003207 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00003208 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00003209 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00003210
3211 if (m_thread_create_bp_sp)
3212 m_thread_create_bp_sp->SetEnabled(false);
3213
Jim Ingham1c823b42011-01-22 01:33:44 +00003214 return true;
3215}
3216
Jason Molenda5e8534e2012-10-03 01:29:34 +00003217lldb_private::DynamicLoader *
3218ProcessGDBRemote::GetDynamicLoader ()
3219{
3220 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00003221 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00003222 return m_dyld_ap.get();
3223}
Jim Ingham1c823b42011-01-22 01:33:44 +00003224
Jason Molendaa3329782014-03-29 18:54:20 +00003225Error
3226ProcessGDBRemote::SendEventData(const char *data)
3227{
3228 int return_value;
3229 bool was_supported;
3230
3231 Error error;
3232
3233 return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported);
3234 if (return_value != 0)
3235 {
3236 if (!was_supported)
3237 error.SetErrorString("Sending events is not supported for this process.");
3238 else
3239 error.SetErrorStringWithFormat("Error sending event data: %d.", return_value);
3240 }
3241 return error;
3242}
3243
Steve Pucci03904ac2014-03-04 23:18:46 +00003244const DataBufferSP
3245ProcessGDBRemote::GetAuxvData()
3246{
3247 DataBufferSP buf;
3248 if (m_gdb_comm.GetQXferAuxvReadSupported())
3249 {
3250 std::string response_string;
3251 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success)
3252 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length()));
3253 }
3254 return buf;
3255}
3256
Jason Molenda705b1802014-06-13 02:37:02 +00003257StructuredData::ObjectSP
3258ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid)
3259{
3260 StructuredData::ObjectSP object_sp;
3261
3262 if (m_gdb_comm.GetThreadExtendedInfoSupported())
3263 {
3264 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3265 SystemRuntime *runtime = GetSystemRuntime();
3266 if (runtime)
3267 {
3268 runtime->AddThreadExtendedInfoPacketHints (args_dict);
3269 }
3270 args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid);
3271
3272 StreamString packet;
3273 packet << "jThreadExtendedInfo:";
3274 args_dict->Dump (packet);
3275
3276 // FIXME the final character of a JSON dictionary, '}', is the escape
3277 // character in gdb-remote binary mode. lldb currently doesn't escape
3278 // these characters in its packet output -- so we add the quoted version
3279 // of the } character here manually in case we talk to a debugserver which
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003280 // un-escapes the characters at packet read time.
Jason Molenda705b1802014-06-13 02:37:02 +00003281 packet << (char) (0x7d ^ 0x20);
3282
3283 StringExtractorGDBRemote response;
3284 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
3285 {
3286 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
3287 if (response_type == StringExtractorGDBRemote::eResponse)
3288 {
3289 if (!response.Empty())
3290 {
3291 // The packet has already had the 0x7d xor quoting stripped out at the
3292 // GDBRemoteCommunication packet receive level.
3293 object_sp = StructuredData::ParseJSON (response.GetStringRef());
3294 }
3295 }
3296 }
3297 }
3298 return object_sp;
3299}
3300
Jason Molenda6076bf42014-05-06 04:34:52 +00003301// Establish the largest memory read/write payloads we should use.
3302// If the remote stub has a max packet size, stay under that size.
3303//
3304// If the remote stub's max packet size is crazy large, use a
3305// reasonable largeish default.
3306//
3307// If the remote stub doesn't advertise a max packet size, use a
3308// conservative default.
3309
3310void
3311ProcessGDBRemote::GetMaxMemorySize()
3312{
3313 const uint64_t reasonable_largeish_default = 128 * 1024;
3314 const uint64_t conservative_default = 512;
3315
3316 if (m_max_memory_size == 0)
3317 {
3318 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
3319 if (stub_max_size != UINT64_MAX && stub_max_size != 0)
3320 {
3321 // Save the stub's claimed maximum packet size
3322 m_remote_stub_max_memory_size = stub_max_size;
3323
3324 // Even if the stub says it can support ginormous packets,
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003325 // don't exceed our reasonable largeish default packet size.
Jason Molenda6076bf42014-05-06 04:34:52 +00003326 if (stub_max_size > reasonable_largeish_default)
3327 {
3328 stub_max_size = reasonable_largeish_default;
3329 }
3330
3331 m_max_memory_size = stub_max_size;
3332 }
3333 else
3334 {
3335 m_max_memory_size = conservative_default;
3336 }
3337 }
3338}
3339
3340void
3341ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max)
3342{
3343 if (user_specified_max != 0)
3344 {
3345 GetMaxMemorySize ();
3346
3347 if (m_remote_stub_max_memory_size != 0)
3348 {
3349 if (m_remote_stub_max_memory_size < user_specified_max)
3350 {
3351 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a packet size too big, go as big
3352 // as the remote stub says we can go.
3353 }
3354 else
3355 {
3356 m_max_memory_size = user_specified_max; // user's packet size is good
3357 }
3358 }
3359 else
3360 {
3361 m_max_memory_size = user_specified_max; // user's packet size is probably fine
3362 }
3363 }
3364}
3365
Greg Clayton02686b82012-10-15 22:42:16 +00003366class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00003367{
3368private:
3369
3370public:
Greg Clayton02686b82012-10-15 22:42:16 +00003371 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00003372 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00003373 "process plugin packet history",
3374 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00003375 NULL)
3376 {
3377 }
3378
Greg Clayton02686b82012-10-15 22:42:16 +00003379 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton998255b2012-10-13 02:07:45 +00003380 {
3381 }
3382
3383 bool
3384 DoExecute (Args& command, CommandReturnObject &result)
3385 {
Greg Clayton02686b82012-10-15 22:42:16 +00003386 const size_t argc = command.GetArgumentCount();
3387 if (argc == 0)
3388 {
3389 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3390 if (process)
3391 {
3392 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
3393 result.SetStatus (eReturnStatusSuccessFinishResult);
3394 return true;
3395 }
3396 }
3397 else
3398 {
3399 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
3400 }
3401 result.SetStatus (eReturnStatusFailed);
3402 return false;
3403 }
3404};
3405
Jason Molenda6076bf42014-05-06 04:34:52 +00003406class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed
3407{
3408private:
3409
3410public:
3411 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) :
3412 CommandObjectParsed (interpreter,
3413 "process plugin packet xfer-size",
3414 "Maximum size that lldb will try to read/write one one chunk.",
3415 NULL)
3416 {
3417 }
3418
3419 ~CommandObjectProcessGDBRemotePacketXferSize ()
3420 {
3421 }
3422
3423 bool
3424 DoExecute (Args& command, CommandReturnObject &result)
3425 {
3426 const size_t argc = command.GetArgumentCount();
3427 if (argc == 0)
3428 {
3429 result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str());
3430 result.SetStatus (eReturnStatusFailed);
3431 return false;
3432 }
3433
3434 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3435 if (process)
3436 {
3437 const char *packet_size = command.GetArgumentAtIndex(0);
3438 errno = 0;
3439 uint64_t user_specified_max = strtoul (packet_size, NULL, 10);
3440 if (errno == 0 && user_specified_max != 0)
3441 {
3442 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max);
3443 result.SetStatus (eReturnStatusSuccessFinishResult);
3444 return true;
3445 }
3446 }
3447 result.SetStatus (eReturnStatusFailed);
3448 return false;
3449 }
3450};
3451
3452
Greg Clayton02686b82012-10-15 22:42:16 +00003453class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
3454{
3455private:
3456
3457public:
3458 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
3459 CommandObjectParsed (interpreter,
3460 "process plugin packet send",
3461 "Send a custom packet through the GDB remote protocol and print the answer. "
3462 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
3463 NULL)
3464 {
3465 }
3466
3467 ~CommandObjectProcessGDBRemotePacketSend ()
3468 {
3469 }
3470
3471 bool
3472 DoExecute (Args& command, CommandReturnObject &result)
3473 {
3474 const size_t argc = command.GetArgumentCount();
3475 if (argc == 0)
3476 {
3477 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
3478 result.SetStatus (eReturnStatusFailed);
3479 return false;
3480 }
3481
3482 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3483 if (process)
3484 {
Han Ming Ong84145852012-11-26 20:42:03 +00003485 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00003486 {
Han Ming Ong84145852012-11-26 20:42:03 +00003487 const char *packet_cstr = command.GetArgumentAtIndex(0);
3488 bool send_async = true;
3489 StringExtractorGDBRemote response;
3490 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3491 result.SetStatus (eReturnStatusSuccessFinishResult);
3492 Stream &output_strm = result.GetOutputStream();
3493 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00003494 std::string &response_str = response.GetStringRef();
3495
Han Ming Ong399289e2013-06-21 19:56:59 +00003496 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00003497 {
3498 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
3499 }
3500
Han Ming Ong84145852012-11-26 20:42:03 +00003501 if (response_str.empty())
3502 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3503 else
3504 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00003505 }
Greg Clayton02686b82012-10-15 22:42:16 +00003506 }
Greg Clayton998255b2012-10-13 02:07:45 +00003507 return true;
3508 }
3509};
3510
Greg Claytonba4a0a52013-02-01 23:03:47 +00003511class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
3512{
3513private:
3514
3515public:
3516 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
3517 CommandObjectRaw (interpreter,
3518 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00003519 "Send a qRcmd packet through the GDB remote protocol and print the response."
3520 "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 +00003521 NULL)
3522 {
3523 }
3524
3525 ~CommandObjectProcessGDBRemotePacketMonitor ()
3526 {
3527 }
3528
3529 bool
3530 DoExecute (const char *command, CommandReturnObject &result)
3531 {
3532 if (command == NULL || command[0] == '\0')
3533 {
3534 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
3535 result.SetStatus (eReturnStatusFailed);
3536 return false;
3537 }
3538
3539 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3540 if (process)
3541 {
3542 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00003543 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00003544 packet.PutBytesAsRawHex8(command, strlen(command));
3545 const char *packet_cstr = packet.GetString().c_str();
3546
3547 bool send_async = true;
3548 StringExtractorGDBRemote response;
3549 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3550 result.SetStatus (eReturnStatusSuccessFinishResult);
3551 Stream &output_strm = result.GetOutputStream();
3552 output_strm.Printf (" packet: %s\n", packet_cstr);
3553 const std::string &response_str = response.GetStringRef();
3554
3555 if (response_str.empty())
3556 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3557 else
3558 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
3559 }
3560 return true;
3561 }
3562};
3563
Greg Clayton02686b82012-10-15 22:42:16 +00003564class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
3565{
3566private:
3567
3568public:
3569 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
3570 CommandObjectMultiword (interpreter,
3571 "process plugin packet",
3572 "Commands that deal with GDB remote packets.",
3573 NULL)
3574 {
3575 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
3576 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00003577 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Jason Molenda6076bf42014-05-06 04:34:52 +00003578 LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00003579 }
3580
3581 ~CommandObjectProcessGDBRemotePacket ()
3582 {
3583 }
3584};
Greg Clayton998255b2012-10-13 02:07:45 +00003585
3586class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
3587{
3588public:
3589 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
3590 CommandObjectMultiword (interpreter,
3591 "process plugin",
3592 "A set of commands for operating on a ProcessGDBRemote process.",
3593 "process plugin <subcommand> [<subcommand-options>]")
3594 {
3595 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
3596 }
3597
3598 ~CommandObjectMultiwordProcessGDBRemote ()
3599 {
3600 }
3601};
3602
Greg Clayton998255b2012-10-13 02:07:45 +00003603CommandObject *
3604ProcessGDBRemote::GetPluginCommandObject()
3605{
3606 if (!m_command_sp)
3607 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
3608 return m_command_sp.get();
3609}