blob: fe99706969c85f807f8cdf4e4253144984fcb13c [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"
Jason Molendad1fae142012-09-29 08:03:33 +000045#include "lldb/Host/Symbols.h"
Zachary Turner39de3112014-09-09 20:54:56 +000046#include "lldb/Host/ThreadLauncher.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000047#include "lldb/Host/TimeValue.h"
Greg Clayton02686b82012-10-15 22:42:16 +000048#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton1d19a2f2012-10-19 22:22:57 +000049#include "lldb/Interpreter/CommandObject.h"
50#include "lldb/Interpreter/CommandObjectMultiword.h"
Greg Clayton02686b82012-10-15 22:42:16 +000051#include "lldb/Interpreter/CommandReturnObject.h"
Joerg Sonnenbergere77b0422013-10-20 17:36:05 +000052#ifndef LLDB_DISABLE_PYTHON
Greg Claytonef8180a2013-10-15 00:14:28 +000053#include "lldb/Interpreter/PythonDataObjects.h"
Joerg Sonnenbergere77b0422013-10-20 17:36:05 +000054#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000055#include "lldb/Symbol/ObjectFile.h"
56#include "lldb/Target/DynamicLoader.h"
57#include "lldb/Target/Target.h"
58#include "lldb/Target/TargetList.h"
Greg Clayton2a48f522011-05-14 01:50:35 +000059#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molenda705b1802014-06-13 02:37:02 +000060#include "lldb/Target/SystemRuntime.h"
Jason Molendaa34a0c62010-06-09 21:28:42 +000061#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000062
63// Project includes
64#include "lldb/Host/Host.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000065#include "Plugins/Process/Utility/FreeBSDSignals.h"
Peter Collingbourne99f9aa02011-06-03 20:40:38 +000066#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000067#include "Plugins/Process/Utility/LinuxSignals.h"
Jason Molendac42d2432012-07-25 03:40:06 +000068#include "Plugins/Process/Utility/StopInfoMachException.h"
Jim Ingham43c555d2012-07-04 00:35:43 +000069#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
Greg Claytonc982c762010-07-09 20:39:50 +000070#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000071#include "GDBRemoteRegisterContext.h"
72#include "ProcessGDBRemote.h"
73#include "ProcessGDBRemoteLog.h"
74#include "ThreadGDBRemote.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000075
Jason Molenda5e8534e2012-10-03 01:29:34 +000076
Greg Claytonc1422c12012-04-09 22:46:21 +000077namespace lldb
78{
79 // Provide a function that can easily dump the packet history if we know a
80 // ProcessGDBRemote * value (which we can get from logs or from debugging).
81 // We need the function in the lldb namespace so it makes it into the final
82 // executable since the LLDB shared library only exports stuff in the lldb
83 // namespace. This allows you to attach with a debugger and call this
84 // function and get the packet history dumped to a file.
85 void
86 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
87 {
Greg Claytond451c1a2012-04-13 21:24:18 +000088 lldb_private::StreamFile strm;
89 lldb_private::Error error (strm.GetFile().Open(path, lldb_private::File::eOpenOptionWrite | lldb_private::File::eOpenOptionCanCreate));
90 if (error.Success())
91 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
Greg Claytonc1422c12012-04-09 22:46:21 +000092 }
Filipe Cabecinhasc34f7762012-05-23 16:27:09 +000093}
Chris Lattner30fdc8d2010-06-08 16:52:24 +000094
Chris Lattner30fdc8d2010-06-08 16:52:24 +000095#define DEBUGSERVER_BASENAME "debugserver"
96using namespace lldb;
97using namespace lldb_private;
98
Greg Clayton7f982402013-07-15 22:54:20 +000099
100namespace {
Steve Pucci5ec012d2014-01-16 22:18:14 +0000101
Greg Clayton7f982402013-07-15 22:54:20 +0000102 static PropertyDefinition
103 g_properties[] =
104 {
105 { "packet-timeout" , OptionValue::eTypeUInt64 , true , 1, NULL, NULL, "Specify the default packet timeout in seconds." },
Greg Claytonef8180a2013-10-15 00:14:28 +0000106 { "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 +0000107 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
108 };
109
110 enum
111 {
Greg Claytonef8180a2013-10-15 00:14:28 +0000112 ePropertyPacketTimeout,
113 ePropertyTargetDefinitionFile
Greg Clayton7f982402013-07-15 22:54:20 +0000114 };
115
116 class PluginProperties : public Properties
117 {
118 public:
119
120 static ConstString
121 GetSettingName ()
122 {
123 return ProcessGDBRemote::GetPluginNameStatic();
124 }
125
126 PluginProperties() :
127 Properties ()
128 {
129 m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
130 m_collection_sp->Initialize(g_properties);
131 }
132
133 virtual
134 ~PluginProperties()
135 {
136 }
137
138 uint64_t
139 GetPacketTimeout()
140 {
141 const uint32_t idx = ePropertyPacketTimeout;
142 return m_collection_sp->GetPropertyAtIndexAsUInt64(NULL, idx, g_properties[idx].default_uint_value);
143 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000144
145 bool
146 SetPacketTimeout(uint64_t timeout)
147 {
148 const uint32_t idx = ePropertyPacketTimeout;
149 return m_collection_sp->SetPropertyAtIndexAsUInt64(NULL, idx, timeout);
150 }
151
Greg Claytonef8180a2013-10-15 00:14:28 +0000152 FileSpec
153 GetTargetDefinitionFile () const
154 {
155 const uint32_t idx = ePropertyTargetDefinitionFile;
156 return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
157 }
Greg Clayton7f982402013-07-15 22:54:20 +0000158 };
159
160 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
161
162 static const ProcessKDPPropertiesSP &
163 GetGlobalPluginProperties()
164 {
165 static ProcessKDPPropertiesSP g_settings_sp;
166 if (!g_settings_sp)
167 g_settings_sp.reset (new PluginProperties ());
168 return g_settings_sp;
169 }
170
171} // anonymous namespace end
172
Greg Claytonfda4fab2014-01-10 22:24:11 +0000173// TODO Randomly assigning a port is unsafe. We should get an unused
174// ephemeral port from the kernel and make sure we reserve it before passing
175// it to debugserver.
176
177#if defined (__APPLE__)
178#define LOW_PORT (IPPORT_RESERVED)
179#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
180#else
181#define LOW_PORT (1024u)
182#define HIGH_PORT (49151u)
183#endif
184
Todd Fiala013434e2014-07-09 01:29:05 +0000185#if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000186static bool rand_initialized = false;
187
Greg Claytonfda4fab2014-01-10 22:24:11 +0000188static inline uint16_t
189get_random_port ()
190{
191 if (!rand_initialized)
192 {
193 time_t seed = time(NULL);
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000194
Greg Claytonfda4fab2014-01-10 22:24:11 +0000195 rand_initialized = true;
196 srand(seed);
197 }
198 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
199}
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000200#endif
Greg Claytonfda4fab2014-01-10 22:24:11 +0000201
Greg Clayton57abc5d2013-05-10 21:47:16 +0000202lldb_private::ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000203ProcessGDBRemote::GetPluginNameStatic()
204{
Greg Clayton57abc5d2013-05-10 21:47:16 +0000205 static ConstString g_name("gdb-remote");
206 return g_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000207}
208
209const char *
210ProcessGDBRemote::GetPluginDescriptionStatic()
211{
212 return "GDB Remote protocol based debugging plug-in.";
213}
214
215void
216ProcessGDBRemote::Terminate()
217{
218 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
219}
220
221
Greg Claytonc3776bf2012-02-09 06:16:32 +0000222lldb::ProcessSP
223ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000224{
Greg Claytonc3776bf2012-02-09 06:16:32 +0000225 lldb::ProcessSP process_sp;
226 if (crash_file_path == NULL)
227 process_sp.reset (new ProcessGDBRemote (target, listener));
228 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000229}
230
231bool
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000232ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000233{
Greg Clayton596ed242011-10-21 21:41:45 +0000234 if (plugin_specified_by_name)
235 return true;
236
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000237 // For now we are just making sure the file exists for a given module
Greg Claytonaa149cb2011-08-11 02:48:45 +0000238 Module *exe_module = target.GetExecutableModulePointer();
239 if (exe_module)
Greg Claytonc3776bf2012-02-09 06:16:32 +0000240 {
241 ObjectFile *exe_objfile = exe_module->GetObjectFile();
242 // We can't debug core files...
243 switch (exe_objfile->GetType())
244 {
245 case ObjectFile::eTypeInvalid:
246 case ObjectFile::eTypeCoreFile:
247 case ObjectFile::eTypeDebugInfo:
248 case ObjectFile::eTypeObjectFile:
249 case ObjectFile::eTypeSharedLibrary:
250 case ObjectFile::eTypeStubLibrary:
Greg Clayton23f8c952014-03-24 23:10:19 +0000251 case ObjectFile::eTypeJIT:
Greg Claytonc3776bf2012-02-09 06:16:32 +0000252 return false;
253 case ObjectFile::eTypeExecutable:
254 case ObjectFile::eTypeDynamicLinker:
255 case ObjectFile::eTypeUnknown:
256 break;
257 }
Greg Claytonaa149cb2011-08-11 02:48:45 +0000258 return exe_module->GetFileSpec().Exists();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000259 }
Jim Ingham5aee1622010-08-09 23:31:02 +0000260 // However, if there is no executable module, we return true since we might be preparing to attach.
261 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000262}
263
264//----------------------------------------------------------------------
265// ProcessGDBRemote constructor
266//----------------------------------------------------------------------
267ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
268 Process (target, listener),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000269 m_flags (0),
Greg Clayton8b82f082011-04-12 05:54:46 +0000270 m_gdb_comm(false),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000271 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Claytonc982c762010-07-09 20:39:50 +0000272 m_last_stop_packet (),
Greg Clayton09c3e3d2011-12-06 04:51:14 +0000273 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000274 m_register_info (),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000275 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
Jim Ingham455fa5c2012-11-01 01:15:33 +0000276 m_async_thread_state_mutex(Mutex::eMutexTypeRecursive),
Greg Clayton9e920902012-04-10 02:25:43 +0000277 m_thread_ids (),
Greg Clayton71fc2a32011-02-12 06:28:37 +0000278 m_continue_c_tids (),
279 m_continue_C_tids (),
280 m_continue_s_tids (),
281 m_continue_S_tids (),
Jason Molenda6076bf42014-05-06 04:34:52 +0000282 m_max_memory_size (0),
283 m_remote_stub_max_memory_size (0),
Greg Clayton4116e932012-05-15 02:33:01 +0000284 m_addr_to_mmap_size (),
285 m_thread_create_bp_sp (),
Jim Ingham43c555d2012-07-04 00:35:43 +0000286 m_waiting_for_attach (false),
Jason Molenda5e8534e2012-10-03 01:29:34 +0000287 m_destroy_tried_resuming (false),
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000288 m_command_sp (),
Todd Fiala4ceced32014-08-29 17:35:57 +0000289 m_breakpoint_pc_offset (0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000290{
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000291 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
292 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Inghamb1e2e842012-04-12 18:49:31 +0000293 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Greg Clayton7f982402013-07-15 22:54:20 +0000294 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
295 if (timeout_seconds > 0)
296 m_gdb_comm.SetPacketTimeout(timeout_seconds);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000297}
298
299//----------------------------------------------------------------------
300// Destructor
301//----------------------------------------------------------------------
302ProcessGDBRemote::~ProcessGDBRemote()
303{
304 // m_mach_process.UnregisterNotificationCallbacks (this);
305 Clear();
Greg Clayton1ed54f52011-10-01 00:45:15 +0000306 // We need to call finalize on the process before destroying ourselves
307 // to make sure all of the broadcaster cleanup goes as planned. If we
308 // destruct this class, then Process::~Process() might have problems
309 // trying to fully destroy the broadcaster.
310 Finalize();
Jim Ingham455fa5c2012-11-01 01:15:33 +0000311
312 // The general Finalize is going to try to destroy the process and that SHOULD
313 // shut down the async thread. However, if we don't kill it it will get stranded and
314 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
315 StopAsyncThread();
316 KillDebugserverProcess();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000317}
318
319//----------------------------------------------------------------------
320// PluginInterface
321//----------------------------------------------------------------------
Greg Clayton57abc5d2013-05-10 21:47:16 +0000322ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000323ProcessGDBRemote::GetPluginName()
324{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000325 return GetPluginNameStatic();
326}
327
328uint32_t
329ProcessGDBRemote::GetPluginVersion()
330{
331 return 1;
332}
333
Greg Claytonef8180a2013-10-15 00:14:28 +0000334bool
335ProcessGDBRemote::ParsePythonTargetDefinition(const FileSpec &target_definition_fspec)
336{
Joerg Sonnenbergere77b0422013-10-20 17:36:05 +0000337#ifndef LLDB_DISABLE_PYTHON
Greg Claytonef8180a2013-10-15 00:14:28 +0000338 ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
339 Error error;
340 lldb::ScriptInterpreterObjectSP module_object_sp (interpreter->LoadPluginModule(target_definition_fspec, error));
341 if (module_object_sp)
342 {
343 lldb::ScriptInterpreterObjectSP target_definition_sp (interpreter->GetDynamicSettings(module_object_sp,
344 &GetTarget(),
345 "gdb-server-target-definition",
346 error));
347
348 PythonDictionary target_dict(target_definition_sp);
349
350 if (target_dict)
351 {
Greg Clayton312bcbe2013-10-17 01:10:23 +0000352 PythonDictionary host_info_dict (target_dict.GetItemForKey("host-info"));
353 if (host_info_dict)
354 {
355 ArchSpec host_arch (host_info_dict.GetItemForKeyAsString(PythonString("triple")));
356
357 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture()))
358 {
359 GetTarget().SetArchitecture(host_arch);
360 }
361
362 }
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000363 m_breakpoint_pc_offset = target_dict.GetItemForKeyAsInteger("breakpoint-pc-offset", 0);
364
Greg Clayton312bcbe2013-10-17 01:10:23 +0000365 if (m_register_info.SetRegisterInfo (target_dict, GetTarget().GetArchitecture().GetByteOrder()) > 0)
Greg Claytonef8180a2013-10-15 00:14:28 +0000366 {
367 return true;
368 }
369 }
370 }
Joerg Sonnenbergere77b0422013-10-20 17:36:05 +0000371#endif
Greg Claytonef8180a2013-10-15 00:14:28 +0000372 return false;
373}
374
375
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000376void
Greg Clayton513c26c2011-01-29 07:10:55 +0000377ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000378{
Greg Clayton513c26c2011-01-29 07:10:55 +0000379 if (!force && m_register_info.GetNumRegisters() > 0)
380 return;
381
382 char packet[128];
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000383 m_register_info.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000384 uint32_t reg_offset = 0;
385 uint32_t reg_num = 0;
Greg Clayton23f59502012-07-17 03:23:13 +0000386 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Greg Clayton576d8832011-03-22 04:00:09 +0000387 response_type == StringExtractorGDBRemote::eResponse;
388 ++reg_num)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000389 {
Greg Clayton513c26c2011-01-29 07:10:55 +0000390 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
Andy Gibbsa297a972013-06-19 19:04:53 +0000391 assert (packet_len < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000392 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000393 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000394 {
Greg Clayton576d8832011-03-22 04:00:09 +0000395 response_type = response.GetResponseType();
396 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000397 {
398 std::string name;
399 std::string value;
400 ConstString reg_name;
401 ConstString alt_name;
402 ConstString set_name;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000403 std::vector<uint32_t> value_regs;
404 std::vector<uint32_t> invalidate_regs;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000405 RegisterInfo reg_info = { NULL, // Name
406 NULL, // Alt name
407 0, // byte size
408 reg_offset, // offset
409 eEncodingUint, // encoding
410 eFormatHex, // formate
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000411 {
412 LLDB_INVALID_REGNUM, // GCC reg num
413 LLDB_INVALID_REGNUM, // DWARF reg num
414 LLDB_INVALID_REGNUM, // generic reg num
Jason Molendafbcb7f22010-09-10 07:49:16 +0000415 reg_num, // GDB reg num
416 reg_num // native register number
Greg Clayton435d85a2012-02-29 19:27:27 +0000417 },
418 NULL,
419 NULL
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000420 };
421
422 while (response.GetNameColonValue(name, value))
423 {
424 if (name.compare("name") == 0)
425 {
426 reg_name.SetCString(value.c_str());
427 }
428 else if (name.compare("alt-name") == 0)
429 {
430 alt_name.SetCString(value.c_str());
431 }
432 else if (name.compare("bitsize") == 0)
433 {
434 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
435 }
436 else if (name.compare("offset") == 0)
437 {
438 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda743e86a2010-06-11 23:44:18 +0000439 if (reg_offset != offset)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000440 {
441 reg_offset = offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000442 }
443 }
444 else if (name.compare("encoding") == 0)
445 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000446 const Encoding encoding = Args::StringToEncoding (value.c_str());
447 if (encoding != eEncodingInvalid)
448 reg_info.encoding = encoding;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000449 }
450 else if (name.compare("format") == 0)
451 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000452 Format format = eFormatInvalid;
453 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
454 reg_info.format = format;
455 else if (value.compare("binary") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000456 reg_info.format = eFormatBinary;
457 else if (value.compare("decimal") == 0)
458 reg_info.format = eFormatDecimal;
459 else if (value.compare("hex") == 0)
460 reg_info.format = eFormatHex;
461 else if (value.compare("float") == 0)
462 reg_info.format = eFormatFloat;
463 else if (value.compare("vector-sint8") == 0)
464 reg_info.format = eFormatVectorOfSInt8;
465 else if (value.compare("vector-uint8") == 0)
466 reg_info.format = eFormatVectorOfUInt8;
467 else if (value.compare("vector-sint16") == 0)
468 reg_info.format = eFormatVectorOfSInt16;
469 else if (value.compare("vector-uint16") == 0)
470 reg_info.format = eFormatVectorOfUInt16;
471 else if (value.compare("vector-sint32") == 0)
472 reg_info.format = eFormatVectorOfSInt32;
473 else if (value.compare("vector-uint32") == 0)
474 reg_info.format = eFormatVectorOfUInt32;
475 else if (value.compare("vector-float32") == 0)
476 reg_info.format = eFormatVectorOfFloat32;
477 else if (value.compare("vector-uint128") == 0)
478 reg_info.format = eFormatVectorOfUInt128;
479 }
480 else if (name.compare("set") == 0)
481 {
482 set_name.SetCString(value.c_str());
483 }
484 else if (name.compare("gcc") == 0)
485 {
486 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
487 }
488 else if (name.compare("dwarf") == 0)
489 {
490 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
491 }
492 else if (name.compare("generic") == 0)
493 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000494 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000495 }
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000496 else if (name.compare("container-regs") == 0)
497 {
498 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
499 value_pair.second = value;
500 do
501 {
502 value_pair = value_pair.second.split(',');
503 if (!value_pair.first.empty())
504 {
Greg Clayton0ba20242013-01-21 23:32:42 +0000505 uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
506 if (reg != LLDB_INVALID_REGNUM)
507 value_regs.push_back (reg);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000508 }
509 } while (!value_pair.second.empty());
510 }
511 else if (name.compare("invalidate-regs") == 0)
512 {
513 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
514 value_pair.second = value;
515 do
516 {
517 value_pair = value_pair.second.split(',');
518 if (!value_pair.first.empty())
519 {
Greg Clayton0ba20242013-01-21 23:32:42 +0000520 uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
521 if (reg != LLDB_INVALID_REGNUM)
522 invalidate_regs.push_back (reg);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000523 }
524 } while (!value_pair.second.empty());
525 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000526 }
527
Jason Molenda743e86a2010-06-11 23:44:18 +0000528 reg_info.byte_offset = reg_offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000529 assert (reg_info.byte_size != 0);
530 reg_offset += reg_info.byte_size;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000531 if (!value_regs.empty())
532 {
533 value_regs.push_back(LLDB_INVALID_REGNUM);
534 reg_info.value_regs = value_regs.data();
535 }
536 if (!invalidate_regs.empty())
537 {
538 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
539 reg_info.invalidate_regs = invalidate_regs.data();
540 }
541
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000542 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
543 }
Todd Fiala1a634402014-01-08 07:52:40 +0000544 else
545 {
546 break; // ensure exit before reg_num is incremented
547 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000548 }
549 else
550 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000551 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000552 }
553 }
554
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000555 // Check if qHostInfo specified a specific packet timeout for this connection.
556 // If so then lets update our setting so the user knows what the timeout is
557 // and can see it.
558 const uint32_t host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
559 if (host_packet_timeout)
560 {
561 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout);
562 }
563
564
Greg Claytonef8180a2013-10-15 00:14:28 +0000565 if (reg_num == 0)
566 {
567 FileSpec target_definition_fspec = GetGlobalPluginProperties()->GetTargetDefinitionFile ();
Greg Clayton312bcbe2013-10-17 01:10:23 +0000568
569 if (target_definition_fspec)
Greg Claytonef8180a2013-10-15 00:14:28 +0000570 {
Greg Clayton312bcbe2013-10-17 01:10:23 +0000571 // See if we can get register definitions from a python file
572 if (ParsePythonTargetDefinition (target_definition_fspec))
573 return;
Greg Claytonef8180a2013-10-15 00:14:28 +0000574 }
575 }
576
Johnny Chen2fa9de12012-05-14 18:44:23 +0000577 // We didn't get anything if the accumulated reg_num is zero. See if we are
578 // debugging ARM and fill with a hard coded register set until we can get an
579 // updated debugserver down on the devices.
580 // On the other hand, if the accumulated reg_num is positive, see if we can
581 // add composite registers to the existing primordial ones.
582 bool from_scratch = (reg_num == 0);
583
584 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000585 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
586 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
587
588 // Use the process' architecture instead of the host arch, if available
589 ArchSpec remote_arch;
590 if (remote_process_arch.IsValid ())
591 remote_arch = remote_process_arch;
592 else
593 remote_arch = remote_host_arch;
594
Johnny Chen2fa9de12012-05-14 18:44:23 +0000595 if (!target_arch.IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000596 {
Johnny Chen2fa9de12012-05-14 18:44:23 +0000597 if (remote_arch.IsValid()
598 && remote_arch.GetMachine() == llvm::Triple::arm
599 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
600 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000601 }
Johnny Chen2fa9de12012-05-14 18:44:23 +0000602 else if (target_arch.GetMachine() == llvm::Triple::arm)
603 {
604 m_register_info.HardcodeARMRegisters(from_scratch);
605 }
606
607 // At this point, we can finalize our register info.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000608 m_register_info.Finalize ();
609}
610
611Error
612ProcessGDBRemote::WillLaunch (Module* module)
613{
614 return WillLaunchOrAttach ();
615}
616
617Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000618ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000619{
620 return WillLaunchOrAttach ();
621}
622
623Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000624ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000625{
626 return WillLaunchOrAttach ();
627}
628
629Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000630ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +0000631{
Todd Fialaaf245d12014-06-30 21:05:18 +0000632 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Claytonb766a732011-02-04 01:58:07 +0000633 Error error (WillLaunchOrAttach ());
634
635 if (error.Fail())
636 return error;
637
Greg Clayton2289fa42011-04-30 01:09:13 +0000638 error = ConnectToDebugserver (remote_url);
Greg Claytonb766a732011-02-04 01:58:07 +0000639
640 if (error.Fail())
641 return error;
642 StartAsyncThread ();
643
Greg Claytonc574ede2011-03-10 02:26:48 +0000644 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonb766a732011-02-04 01:58:07 +0000645 if (pid == LLDB_INVALID_PROCESS_ID)
646 {
647 // We don't have a valid process ID, so note that we are connected
648 // and could now request to launch or attach, or get remote process
649 // listings...
650 SetPrivateState (eStateConnected);
651 }
652 else
653 {
654 // We have a valid process
655 SetID (pid);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000656 GetThreadList();
Greg Clayton3dedae12013-12-06 21:45:27 +0000657 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false) == GDBRemoteCommunication::PacketResult::Success)
Greg Claytonb766a732011-02-04 01:58:07 +0000658 {
Jason Molendac62bd7b2013-12-21 05:20:36 +0000659 if (!m_target.GetArchitecture().IsValid())
660 {
661 if (m_gdb_comm.GetProcessArchitecture().IsValid())
662 {
663 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
664 }
665 else
666 {
667 m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
668 }
Carlo Kok74389122013-10-14 07:09:13 +0000669 }
670
Greg Claytondd0e5a52011-06-02 22:22:38 +0000671 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytonb766a732011-02-04 01:58:07 +0000672 if (state == eStateStopped)
673 {
674 SetPrivateState (state);
675 }
676 else
Daniel Malead01b2952012-11-29 21:49:15 +0000677 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 +0000678 }
679 else
Daniel Malead01b2952012-11-29 21:49:15 +0000680 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 +0000681 }
Jason Molenda16d127c2012-05-03 22:37:30 +0000682
Todd Fialaaf245d12014-06-30 21:05:18 +0000683 if (log)
684 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");
685
686
687 if (error.Success()
Jason Molenda16d127c2012-05-03 22:37:30 +0000688 && !GetTarget().GetArchitecture().IsValid()
689 && m_gdb_comm.GetHostArchitecture().IsValid())
690 {
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000691 // Prefer the *process'* architecture over that of the *host*, if available.
692 if (m_gdb_comm.GetProcessArchitecture().IsValid())
693 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
694 else
695 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molenda16d127c2012-05-03 22:37:30 +0000696 }
697
Todd Fialaaf245d12014-06-30 21:05:18 +0000698 if (log)
699 log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": normalized target architecture triple: %s", __FUNCTION__, GetID (), GetTarget ().GetArchitecture ().GetTriple ().getTriple ().c_str ());
700
701 // Set the Unix signals properly for the target.
702 // FIXME Add a gdb-remote packet to discover dynamically.
703 if (error.Success ())
704 {
705 const ArchSpec arch_spec = GetTarget ().GetArchitecture ();
706 if (arch_spec.IsValid ())
707 {
708 if (log)
709 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 ());
710
711 switch (arch_spec.GetTriple ().getOS ())
712 {
713 case llvm::Triple::Linux:
Todd Fiala4ceced32014-08-29 17:35:57 +0000714 SetUnixSignals (UnixSignalsSP (new process_linux::LinuxSignals ()));
Todd Fialaaf245d12014-06-30 21:05:18 +0000715 if (log)
716 log->Printf ("ProcessGDBRemote::%s using Linux unix signals type for pid %" PRIu64, __FUNCTION__, GetID ());
717 break;
718 case llvm::Triple::OpenBSD:
719 case llvm::Triple::FreeBSD:
720 case llvm::Triple::NetBSD:
Todd Fiala4ceced32014-08-29 17:35:57 +0000721 SetUnixSignals (UnixSignalsSP (new FreeBSDSignals ()));
Todd Fialaaf245d12014-06-30 21:05:18 +0000722 if (log)
723 log->Printf ("ProcessGDBRemote::%s using *BSD unix signals type for pid %" PRIu64, __FUNCTION__, GetID ());
724 break;
725 default:
Todd Fiala4ceced32014-08-29 17:35:57 +0000726 SetUnixSignals (UnixSignalsSP (new UnixSignals ()));
Todd Fialaaf245d12014-06-30 21:05:18 +0000727 if (log)
728 log->Printf ("ProcessGDBRemote::%s using generic unix signals type for pid %" PRIu64, __FUNCTION__, GetID ());
729 break;
730 }
731 }
732 }
733
Greg Claytonb766a732011-02-04 01:58:07 +0000734 return error;
735}
736
737Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000738ProcessGDBRemote::WillLaunchOrAttach ()
739{
740 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000741 m_stdio_communication.Clear ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000742 return error;
743}
744
745//----------------------------------------------------------------------
746// Process Control
747//----------------------------------------------------------------------
748Error
Jean-Daniel Dupas7782de92013-12-09 22:52:50 +0000749ProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000750{
Todd Fiala75f47c32014-10-11 21:42:09 +0000751 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton4957bf62010-09-30 21:49:03 +0000752 Error error;
Greg Clayton982c9762011-11-03 21:22:33 +0000753
Todd Fiala75f47c32014-10-11 21:42:09 +0000754 if (log)
755 log->Printf ("ProcessGDBRemote::%s() entered", __FUNCTION__);
756
Greg Clayton982c9762011-11-03 21:22:33 +0000757 uint32_t launch_flags = launch_info.GetFlags().Get();
758 const char *stdin_path = NULL;
759 const char *stdout_path = NULL;
760 const char *stderr_path = NULL;
761 const char *working_dir = launch_info.GetWorkingDirectory();
762
Zachary Turner696b5282014-08-14 16:01:25 +0000763 const FileAction *file_action;
Greg Clayton982c9762011-11-03 21:22:33 +0000764 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
765 if (file_action)
766 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000767 if (file_action->GetAction() == FileAction::eFileActionOpen)
Greg Clayton982c9762011-11-03 21:22:33 +0000768 stdin_path = file_action->GetPath();
769 }
770 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
771 if (file_action)
772 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000773 if (file_action->GetAction() == FileAction::eFileActionOpen)
Greg Clayton982c9762011-11-03 21:22:33 +0000774 stdout_path = file_action->GetPath();
775 }
776 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
777 if (file_action)
778 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000779 if (file_action->GetAction() == FileAction::eFileActionOpen)
Greg Clayton982c9762011-11-03 21:22:33 +0000780 stderr_path = file_action->GetPath();
781 }
782
Todd Fiala75f47c32014-10-11 21:42:09 +0000783 if (log)
784 {
785 if (stdin_path || stdout_path || stderr_path)
786 log->Printf ("ProcessGDBRemote::%s provided with STDIO paths via launch_info: stdin=%s, stdout=%s, stdout=%s",
787 __FUNCTION__,
788 stdin_path ? stdin_path : "<null>",
789 stdout_path ? stdout_path : "<null>",
790 stderr_path ? stderr_path : "<null>");
791 else
792 log->Printf ("ProcessGDBRemote::%s no STDIO paths given via launch_info", __FUNCTION__);
793 }
794
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000795 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
796 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
797 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000798
Greg Clayton982c9762011-11-03 21:22:33 +0000799 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000800 if (object_file)
801 {
Greg Clayton71337622011-02-24 22:24:29 +0000802 // Make sure we aren't already connected?
803 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000804 {
Greg Clayton91a9b2472013-12-04 19:19:12 +0000805 error = LaunchAndConnectToDebugserver (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000806 }
807
808 if (error.Success())
809 {
810 lldb_utility::PseudoTerminal pty;
811 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000812
813 // If the debugserver is local and we aren't disabling STDIO, lets use
814 // a pseudo terminal to instead of relying on the 'O' packets for stdio
815 // since 'O' packets can really slow down debugging if the inferior
816 // does a lot of output.
Greg Claytonf58c2692011-06-24 22:32:10 +0000817 PlatformSP platform_sp (m_target.GetPlatform());
818 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Clayton71337622011-02-24 22:24:29 +0000819 {
820 const char *slave_name = NULL;
821 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000822 {
Greg Clayton71337622011-02-24 22:24:29 +0000823 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
824 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000825 }
Greg Clayton71337622011-02-24 22:24:29 +0000826 if (stdin_path == NULL)
827 stdin_path = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000828
Greg Clayton71337622011-02-24 22:24:29 +0000829 if (stdout_path == NULL)
830 stdout_path = slave_name;
831
832 if (stderr_path == NULL)
833 stderr_path = slave_name;
Todd Fiala75f47c32014-10-11 21:42:09 +0000834
835 if (log)
836 log->Printf ("ProcessGDBRemote::%s adjusted STDIO paths for local platform (IsHost() is true) using slave: stdin=%s, stdout=%s, stdout=%s",
837 __FUNCTION__,
838 stdin_path ? stdin_path : "<null>",
839 stdout_path ? stdout_path : "<null>",
840 stderr_path ? stderr_path : "<null>");
Greg Clayton71337622011-02-24 22:24:29 +0000841 }
842
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000843 // Set STDIN to /dev/null if we want STDIO disabled or if either
844 // STDOUT or STDERR have been set to something and STDIN hasn't
845 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000846 stdin_path = "/dev/null";
847
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000848 // Set STDOUT to /dev/null if we want STDIO disabled or if either
849 // STDIN or STDERR have been set to something and STDOUT hasn't
850 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000851 stdout_path = "/dev/null";
852
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000853 // Set STDERR to /dev/null if we want STDIO disabled or if either
854 // STDIN or STDOUT have been set to something and STDERR hasn't
855 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000856 stderr_path = "/dev/null";
857
Todd Fiala75f47c32014-10-11 21:42:09 +0000858 if (log)
859 log->Printf ("ProcessGDBRemote::%s final STDIO paths after all adjustments: stdin=%s, stdout=%s, stdout=%s",
860 __FUNCTION__,
861 stdin_path ? stdin_path : "<null>",
862 stdout_path ? stdout_path : "<null>",
863 stderr_path ? stderr_path : "<null>");
864
865 if (stdin_path)
Greg Clayton71337622011-02-24 22:24:29 +0000866 m_gdb_comm.SetSTDIN (stdin_path);
867 if (stdout_path)
868 m_gdb_comm.SetSTDOUT (stdout_path);
869 if (stderr_path)
870 m_gdb_comm.SetSTDERR (stderr_path);
871
872 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
Jim Ingham106d0282014-06-25 02:32:56 +0000873 m_gdb_comm.SetDetachOnError (launch_flags & eLaunchFlagDetachOnError);
Greg Clayton71337622011-02-24 22:24:29 +0000874
Greg Claytonc4103b32011-05-08 04:53:50 +0000875 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Clayton71337622011-02-24 22:24:29 +0000876
Jason Molendaa3329782014-03-29 18:54:20 +0000877 const char * launch_event_data = launch_info.GetLaunchEventData();
878 if (launch_event_data != NULL && *launch_event_data != '\0')
879 m_gdb_comm.SendLaunchEventDataPacket (launch_event_data);
880
Greg Clayton71337622011-02-24 22:24:29 +0000881 if (working_dir && working_dir[0])
882 {
883 m_gdb_comm.SetWorkingDir (working_dir);
884 }
885
886 // Send the environment and the program + arguments after we connect
Greg Clayton982c9762011-11-03 21:22:33 +0000887 const Args &environment = launch_info.GetEnvironmentEntries();
888 if (environment.GetArgumentCount())
Greg Clayton71337622011-02-24 22:24:29 +0000889 {
Greg Clayton982c9762011-11-03 21:22:33 +0000890 size_t num_environment_entries = environment.GetArgumentCount();
891 for (size_t i=0; i<num_environment_entries; ++i)
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000892 {
Greg Clayton982c9762011-11-03 21:22:33 +0000893 const char *env_entry = environment.GetArgumentAtIndex(i);
894 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Clayton71337622011-02-24 22:24:29 +0000895 break;
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000896 }
Greg Clayton71337622011-02-24 22:24:29 +0000897 }
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000898
Greg Claytonc574ede2011-03-10 02:26:48 +0000899 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Claytonfbb76342013-11-20 21:07:01 +0000900 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000901 if (arg_packet_err == 0)
902 {
903 std::string error_str;
Greg Claytonc574ede2011-03-10 02:26:48 +0000904 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000905 {
Greg Claytonc574ede2011-03-10 02:26:48 +0000906 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000907 }
908 else
909 {
Greg Clayton71337622011-02-24 22:24:29 +0000910 error.SetErrorString (error_str.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000911 }
Greg Clayton71337622011-02-24 22:24:29 +0000912 }
913 else
914 {
Greg Clayton86edbf42011-10-26 00:56:27 +0000915 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Clayton71337622011-02-24 22:24:29 +0000916 }
Greg Clayton8b45bee2011-08-10 22:05:39 +0000917
918 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000919
Greg Clayton71337622011-02-24 22:24:29 +0000920 if (GetID() == LLDB_INVALID_PROCESS_ID)
921 {
Johnny Chen4c1e9202011-08-09 18:56:45 +0000922 if (log)
923 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton71337622011-02-24 22:24:29 +0000924 KillDebugserverProcess ();
925 return error;
926 }
927
Greg Clayton3dedae12013-12-06 21:45:27 +0000928 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton71337622011-02-24 22:24:29 +0000929 {
Jason Molendac62bd7b2013-12-21 05:20:36 +0000930 if (!m_target.GetArchitecture().IsValid())
931 {
932 if (m_gdb_comm.GetProcessArchitecture().IsValid())
933 {
934 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
935 }
936 else
937 {
938 m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
939 }
Carlo Kok74389122013-10-14 07:09:13 +0000940 }
941
Greg Claytondd0e5a52011-06-02 22:22:38 +0000942 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Clayton71337622011-02-24 22:24:29 +0000943
944 if (!disable_stdio)
945 {
946 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Claytonee95ed52011-11-17 22:14:31 +0000947 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Clayton71337622011-02-24 22:24:29 +0000948 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000949 }
950 }
Greg Claytonc235ac72011-08-09 05:20:29 +0000951 else
952 {
Johnny Chen4c1e9202011-08-09 18:56:45 +0000953 if (log)
954 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytonc235ac72011-08-09 05:20:29 +0000955 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000956 }
957 else
958 {
959 // Set our user ID to an invalid process ID.
960 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton982c9762011-11-03 21:22:33 +0000961 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
962 exe_module->GetFileSpec().GetFilename().AsCString(),
963 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000964 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000965 return error;
Greg Clayton4957bf62010-09-30 21:49:03 +0000966
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000967}
968
969
970Error
Greg Claytonb766a732011-02-04 01:58:07 +0000971ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000972{
973 Error error;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000974 // Only connect if we have a valid connect URL
975
976 if (connect_url && connect_url[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000977 {
Greg Clayton00fe87b2013-12-05 22:58:22 +0000978 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
979 if (conn_ap.get())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000980 {
Greg Clayton00fe87b2013-12-05 22:58:22 +0000981 const uint32_t max_retry_count = 50;
982 uint32_t retry_count = 0;
983 while (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000984 {
Greg Clayton00fe87b2013-12-05 22:58:22 +0000985 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
986 {
987 m_gdb_comm.SetConnection (conn_ap.release());
988 break;
989 }
990 else if (error.WasInterrupted())
991 {
992 // If we were interrupted, don't keep retrying.
993 break;
994 }
995
996 retry_count++;
997
998 if (retry_count >= max_retry_count)
999 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001000
Greg Clayton00fe87b2013-12-05 22:58:22 +00001001 usleep (100000);
1002 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001003 }
1004 }
1005
1006 if (!m_gdb_comm.IsConnected())
1007 {
1008 if (error.Success())
1009 error.SetErrorString("not connected to remote gdb server");
1010 return error;
1011 }
1012
Greg Clayton32e0a752011-03-30 18:16:51 +00001013 // We always seem to be able to open a connection to a local port
1014 // so we need to make sure we can then send data to it. If we can't
1015 // then we aren't actually connected to anything, so try and do the
1016 // handshake with the remote GDB server and make sure that goes
1017 // alright.
Greg Claytonfb909312013-11-23 01:58:15 +00001018 if (!m_gdb_comm.HandshakeWithServer (&error))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001019 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001020 m_gdb_comm.Disconnect();
1021 if (error.Success())
1022 error.SetErrorString("not connected to remote gdb server");
1023 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001024 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001025 m_gdb_comm.GetThreadSuffixSupported ();
Greg Clayton44633992012-04-10 03:22:03 +00001026 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001027 m_gdb_comm.GetHostInfo ();
1028 m_gdb_comm.GetVContSupported ('c');
Jim Inghamcd16df92012-07-20 21:37:13 +00001029 m_gdb_comm.GetVAttachOrWaitSupported();
Jim Ingham03afad82012-07-02 05:40:07 +00001030
1031 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1032 for (size_t idx = 0; idx < num_cmds; idx++)
1033 {
1034 StringExtractorGDBRemote response;
Jim Ingham03afad82012-07-02 05:40:07 +00001035 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1036 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001037 return error;
1038}
1039
1040void
Jim Inghambb006ce2014-08-02 00:33:35 +00001041ProcessGDBRemote::DidLaunchOrAttach (ArchSpec& process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001042{
Greg Clayton5160ce52013-03-27 23:08:40 +00001043 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001044 if (log)
1045 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton93d3c8332011-02-16 04:46:07 +00001046 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001047 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001048 BuildDynamicRegisterInfo (false);
Greg Clayton3af9ea52010-11-18 05:57:03 +00001049
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001050 // See if the GDB server supports the qHostInfo information
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001051
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001052
1053 // See if the GDB server supports the qProcessInfo packet, if so
1054 // prefer that over the Host information as it will be more specific
1055 // to our process.
1056
Todd Fiala75f47c32014-10-11 21:42:09 +00001057 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1058 if (remote_process_arch.IsValid())
1059 {
1060 process_arch = remote_process_arch;
1061 if (log)
1062 log->Printf ("ProcessGDBRemote::%s gdb-remote had process architecture, using %s %s",
1063 __FUNCTION__,
1064 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1065 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1066 }
Jim Inghambb006ce2014-08-02 00:33:35 +00001067 else
Todd Fiala75f47c32014-10-11 21:42:09 +00001068 {
Jim Inghambb006ce2014-08-02 00:33:35 +00001069 process_arch = m_gdb_comm.GetHostArchitecture();
Todd Fiala75f47c32014-10-11 21:42:09 +00001070 if (log)
1071 log->Printf ("ProcessGDBRemote::%s gdb-remote did not have process architecture, using gdb-remote host architecture %s %s",
1072 __FUNCTION__,
1073 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1074 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1075 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001076
Jim Inghambb006ce2014-08-02 00:33:35 +00001077 if (process_arch.IsValid())
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001078 {
Greg Claytond314e812011-03-23 00:09:55 +00001079 ArchSpec &target_arch = GetTarget().GetArchitecture();
Greg Claytond314e812011-03-23 00:09:55 +00001080 if (target_arch.IsValid())
1081 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001082 if (log)
1083 log->Printf ("ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1084 __FUNCTION__,
1085 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1086 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
1087
1088 // If the remote host is ARM and we have apple as the vendor, then
Greg Claytond314e812011-03-23 00:09:55 +00001089 // ARM executables and shared libraries can have mixed ARM architectures.
1090 // You can have an armv6 executable, and if the host is armv7, then the
1091 // system will load the best possible architecture for all shared libraries
1092 // it has, so we really need to take the remote host architecture as our
1093 // defacto architecture in this case.
1094
Jim Inghambb006ce2014-08-02 00:33:35 +00001095 if (process_arch.GetMachine() == llvm::Triple::arm &&
1096 process_arch.GetTriple().getVendor() == llvm::Triple::Apple)
Greg Claytond314e812011-03-23 00:09:55 +00001097 {
Jason Molenda921c01b2014-08-03 21:42:52 +00001098 GetTarget().SetArchitecture (process_arch);
Todd Fiala75f47c32014-10-11 21:42:09 +00001099 if (log)
1100 log->Printf ("ProcessGDBRemote::%s remote process is ARM/Apple, setting target arch to %s %s",
1101 __FUNCTION__,
1102 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1103 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001104 }
1105 else
1106 {
1107 // Fill in what is missing in the triple
Jim Inghambb006ce2014-08-02 00:33:35 +00001108 const llvm::Triple &remote_triple = process_arch.GetTriple();
Greg Claytond314e812011-03-23 00:09:55 +00001109 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton70b57652011-05-15 01:25:55 +00001110 if (target_triple.getVendorName().size() == 0)
1111 {
Greg Claytond314e812011-03-23 00:09:55 +00001112 target_triple.setVendor (remote_triple.getVendor());
1113
Greg Clayton70b57652011-05-15 01:25:55 +00001114 if (target_triple.getOSName().size() == 0)
1115 {
1116 target_triple.setOS (remote_triple.getOS());
Greg Claytond314e812011-03-23 00:09:55 +00001117
Greg Clayton70b57652011-05-15 01:25:55 +00001118 if (target_triple.getEnvironmentName().size() == 0)
1119 target_triple.setEnvironment (remote_triple.getEnvironment());
1120 }
1121 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001122
Greg Claytond314e812011-03-23 00:09:55 +00001123 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001124
1125 if (log)
1126 log->Printf ("ProcessGDBRemote::%s final target arch after adjustments for remote architecture: %s %s",
1127 __FUNCTION__,
1128 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1129 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001130 }
1131 else
1132 {
1133 // The target doesn't have a valid architecture yet, set it from
1134 // the architecture we got from the remote GDB server
Jason Molenda921c01b2014-08-03 21:42:52 +00001135 GetTarget().SetArchitecture (process_arch);
Greg Claytond314e812011-03-23 00:09:55 +00001136 }
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001137 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001138 }
1139}
1140
1141void
1142ProcessGDBRemote::DidLaunch ()
1143{
Jim Inghambb006ce2014-08-02 00:33:35 +00001144 ArchSpec process_arch;
1145 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001146}
1147
1148Error
Greg Claytonc982c762010-07-09 20:39:50 +00001149ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001150{
Han Ming Ong84647042012-02-25 01:07:38 +00001151 ProcessAttachInfo attach_info;
1152 return DoAttachToProcessWithID(attach_pid, attach_info);
1153}
1154
1155Error
1156ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1157{
Todd Fiala75f47c32014-10-11 21:42:09 +00001158 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001159 Error error;
Todd Fiala75f47c32014-10-11 21:42:09 +00001160
1161 if (log)
1162 log->Printf ("ProcessGDBRemote::%s()", __FUNCTION__);
1163
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001164 // Clear out and clean up from any current state
1165 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001166 if (attach_pid != LLDB_INVALID_PROCESS_ID)
1167 {
Greg Clayton71337622011-02-24 22:24:29 +00001168 // Make sure we aren't already connected?
1169 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001170 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001171 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001172
1173 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001174 {
Greg Clayton71337622011-02-24 22:24:29 +00001175 const char *error_string = error.AsCString();
1176 if (error_string == NULL)
1177 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1178
1179 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001180 }
Greg Clayton71337622011-02-24 22:24:29 +00001181 }
1182
1183 if (error.Success())
1184 {
Jim Ingham106d0282014-06-25 02:32:56 +00001185 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
Todd Fiala75f47c32014-10-11 21:42:09 +00001186
Greg Clayton71337622011-02-24 22:24:29 +00001187 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001188 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Greg Clayton3b608422011-11-19 02:11:30 +00001189 SetID (attach_pid);
Greg Clayton71337622011-02-24 22:24:29 +00001190 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001191 }
1192 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001193
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001194 return error;
1195}
1196
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001197Error
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001198ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001199{
1200 Error error;
1201 // Clear out and clean up from any current state
1202 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001203
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001204 if (process_name && process_name[0])
1205 {
Greg Clayton71337622011-02-24 22:24:29 +00001206 // Make sure we aren't already connected?
1207 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001208 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001209 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001210
Greg Clayton71337622011-02-24 22:24:29 +00001211 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001212 {
Greg Clayton71337622011-02-24 22:24:29 +00001213 const char *error_string = error.AsCString();
1214 if (error_string == NULL)
1215 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001216
Greg Clayton71337622011-02-24 22:24:29 +00001217 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001218 }
Greg Clayton71337622011-02-24 22:24:29 +00001219 }
1220
1221 if (error.Success())
1222 {
1223 StreamString packet;
1224
Jim Ingham106d0282014-06-25 02:32:56 +00001225 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1226
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001227 if (attach_info.GetWaitForLaunch())
Jim Inghamcd16df92012-07-20 21:37:13 +00001228 {
1229 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1230 {
1231 packet.PutCString ("vAttachWait");
1232 }
1233 else
1234 {
1235 if (attach_info.GetIgnoreExisting())
1236 packet.PutCString("vAttachWait");
1237 else
1238 packet.PutCString ("vAttachOrWait");
1239 }
1240 }
Greg Clayton71337622011-02-24 22:24:29 +00001241 else
1242 packet.PutCString("vAttachName");
1243 packet.PutChar(';');
1244 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1245
1246 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1247
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001248 }
1249 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001250 return error;
1251}
1252
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001253
Greg Claytonfbb76342013-11-20 21:07:01 +00001254bool
1255ProcessGDBRemote::SetExitStatus (int exit_status, const char *cstr)
1256{
1257 m_gdb_comm.Disconnect();
1258 return Process::SetExitStatus (exit_status, cstr);
1259}
1260
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001261void
Jim Inghambb006ce2014-08-02 00:33:35 +00001262ProcessGDBRemote::DidAttach (ArchSpec &process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001263{
Jim Inghambb006ce2014-08-02 00:33:35 +00001264 // If you can figure out what the architecture is, fill it in here.
1265 process_arch.Clear();
1266 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001267}
1268
Greg Clayton90ba8112012-12-05 00:16:59 +00001269
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001270Error
1271ProcessGDBRemote::WillResume ()
1272{
Greg Clayton71fc2a32011-02-12 06:28:37 +00001273 m_continue_c_tids.clear();
1274 m_continue_C_tids.clear();
1275 m_continue_s_tids.clear();
1276 m_continue_S_tids.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001277 return Error();
1278}
1279
1280Error
1281ProcessGDBRemote::DoResume ()
1282{
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001283 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001284 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001285 if (log)
1286 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytone5219662010-12-03 06:02:24 +00001287
1288 Listener listener ("gdb-remote.resume-packet-sent");
1289 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1290 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00001291 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1292
Greg Claytond1d06e42013-04-20 00:27:58 +00001293 const size_t num_threads = GetThreadList().GetSize();
1294
Greg Clayton71fc2a32011-02-12 06:28:37 +00001295 StreamString continue_packet;
1296 bool continue_packet_error = false;
1297 if (m_gdb_comm.HasAnyVContSupport ())
1298 {
Greg Claytone98008c2014-02-13 23:34:38 +00001299 if (m_continue_c_tids.size() == num_threads ||
1300 (m_continue_c_tids.empty() &&
1301 m_continue_C_tids.empty() &&
1302 m_continue_s_tids.empty() &&
1303 m_continue_S_tids.empty()))
Greg Clayton71fc2a32011-02-12 06:28:37 +00001304 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001305 // All threads are continuing, just send a "c" packet
1306 continue_packet.PutCString ("c");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001307 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001308 else
1309 {
1310 continue_packet.PutCString ("vCont");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001311
Greg Claytond1d06e42013-04-20 00:27:58 +00001312 if (!m_continue_c_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001313 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001314 if (m_gdb_comm.GetVContSupported ('c'))
1315 {
1316 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)
1317 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1318 }
1319 else
1320 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001321 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001322
1323 if (!continue_packet_error && !m_continue_C_tids.empty())
1324 {
1325 if (m_gdb_comm.GetVContSupported ('C'))
1326 {
1327 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)
1328 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1329 }
1330 else
1331 continue_packet_error = true;
1332 }
Greg Claytone5219662010-12-03 06:02:24 +00001333
Greg Claytond1d06e42013-04-20 00:27:58 +00001334 if (!continue_packet_error && !m_continue_s_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001335 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001336 if (m_gdb_comm.GetVContSupported ('s'))
1337 {
1338 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)
1339 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1340 }
1341 else
1342 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001343 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001344
1345 if (!continue_packet_error && !m_continue_S_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001346 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001347 if (m_gdb_comm.GetVContSupported ('S'))
1348 {
1349 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)
1350 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1351 }
1352 else
1353 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001354 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001355
1356 if (continue_packet_error)
1357 continue_packet.GetString().clear();
Greg Clayton71fc2a32011-02-12 06:28:37 +00001358 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001359 }
1360 else
1361 continue_packet_error = true;
1362
1363 if (continue_packet_error)
1364 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001365 // Either no vCont support, or we tried to use part of the vCont
1366 // packet that wasn't supported by the remote GDB server.
1367 // We need to try and make a simple packet that can do our continue
Greg Clayton71fc2a32011-02-12 06:28:37 +00001368 const size_t num_continue_c_tids = m_continue_c_tids.size();
1369 const size_t num_continue_C_tids = m_continue_C_tids.size();
1370 const size_t num_continue_s_tids = m_continue_s_tids.size();
1371 const size_t num_continue_S_tids = m_continue_S_tids.size();
1372 if (num_continue_c_tids > 0)
1373 {
1374 if (num_continue_c_tids == num_threads)
1375 {
1376 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001377 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001378 continue_packet.PutChar ('c');
1379 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001380 }
1381 else if (num_continue_c_tids == 1 &&
1382 num_continue_C_tids == 0 &&
1383 num_continue_s_tids == 0 &&
1384 num_continue_S_tids == 0 )
1385 {
1386 // Only one thread is continuing
Greg Clayton8b82f082011-04-12 05:54:46 +00001387 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001388 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001389 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001390 }
1391 }
1392
Greg Clayton0c74e782011-06-24 03:21:43 +00001393 if (continue_packet_error && num_continue_C_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001394 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001395 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1396 num_continue_C_tids > 0 &&
1397 num_continue_s_tids == 0 &&
1398 num_continue_S_tids == 0 )
Greg Clayton71fc2a32011-02-12 06:28:37 +00001399 {
1400 const int continue_signo = m_continue_C_tids.front().second;
Greg Clayton0c74e782011-06-24 03:21:43 +00001401 // Only one thread is continuing
Greg Clayton71fc2a32011-02-12 06:28:37 +00001402 if (num_continue_C_tids > 1)
1403 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001404 // More that one thread with a signal, yet we don't have
1405 // vCont support and we are being asked to resume each
1406 // thread with a signal, we need to make sure they are
1407 // all the same signal, or we can't issue the continue
1408 // accurately with the current support...
1409 if (num_continue_C_tids > 1)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001410 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001411 continue_packet_error = false;
1412 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1413 {
1414 if (m_continue_C_tids[i].second != continue_signo)
1415 continue_packet_error = true;
1416 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001417 }
Greg Clayton0c74e782011-06-24 03:21:43 +00001418 if (!continue_packet_error)
1419 m_gdb_comm.SetCurrentThreadForRun (-1);
1420 }
1421 else
1422 {
1423 // Set the continue thread ID
1424 continue_packet_error = false;
1425 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001426 }
1427 if (!continue_packet_error)
1428 {
1429 // Add threads continuing with the same signo...
Greg Clayton71fc2a32011-02-12 06:28:37 +00001430 continue_packet.Printf("C%2.2x", continue_signo);
1431 }
1432 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001433 }
1434
Greg Clayton0c74e782011-06-24 03:21:43 +00001435 if (continue_packet_error && num_continue_s_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001436 {
1437 if (num_continue_s_tids == num_threads)
1438 {
1439 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001440 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001441 continue_packet.PutChar ('s');
1442 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001443 }
1444 else if (num_continue_c_tids == 0 &&
1445 num_continue_C_tids == 0 &&
1446 num_continue_s_tids == 1 &&
1447 num_continue_S_tids == 0 )
1448 {
1449 // Only one thread is stepping
Greg Clayton8b82f082011-04-12 05:54:46 +00001450 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001451 continue_packet.PutChar ('s');
Greg Clayton0c74e782011-06-24 03:21:43 +00001452 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001453 }
1454 }
1455
1456 if (!continue_packet_error && num_continue_S_tids > 0)
1457 {
1458 if (num_continue_S_tids == num_threads)
1459 {
1460 const int step_signo = m_continue_S_tids.front().second;
1461 // Are all threads trying to step with the same signal?
Greg Clayton0c74e782011-06-24 03:21:43 +00001462 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001463 if (num_continue_S_tids > 1)
1464 {
1465 for (size_t i=1; i<num_threads; ++i)
1466 {
1467 if (m_continue_S_tids[i].second != step_signo)
1468 continue_packet_error = true;
1469 }
1470 }
1471 if (!continue_packet_error)
1472 {
1473 // Add threads stepping with the same signo...
Greg Clayton8b82f082011-04-12 05:54:46 +00001474 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001475 continue_packet.Printf("S%2.2x", step_signo);
1476 }
1477 }
1478 else if (num_continue_c_tids == 0 &&
1479 num_continue_C_tids == 0 &&
1480 num_continue_s_tids == 0 &&
1481 num_continue_S_tids == 1 )
1482 {
1483 // Only one thread is stepping with signal
Greg Clayton8b82f082011-04-12 05:54:46 +00001484 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001485 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Clayton0c74e782011-06-24 03:21:43 +00001486 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001487 }
1488 }
1489 }
1490
1491 if (continue_packet_error)
1492 {
1493 error.SetErrorString ("can't make continue packet for this resume");
1494 }
1495 else
1496 {
1497 EventSP event_sp;
1498 TimeValue timeout;
1499 timeout = TimeValue::Now();
1500 timeout.OffsetWithSeconds (5);
Zachary Turneracee96a2014-09-23 18:32:09 +00001501 if (!m_async_thread.IsJoinable())
Jim Inghamb1e2e842012-04-12 18:49:31 +00001502 {
1503 error.SetErrorString ("Trying to resume but the async thread is dead.");
1504 if (log)
1505 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1506 return error;
1507 }
1508
Greg Clayton71fc2a32011-02-12 06:28:37 +00001509 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1510
1511 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Inghamb1e2e842012-04-12 18:49:31 +00001512 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001513 error.SetErrorString("Resume timed out.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00001514 if (log)
1515 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1516 }
1517 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1518 {
1519 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1520 if (log)
1521 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1522 return error;
1523 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001524 }
Greg Claytone5219662010-12-03 06:02:24 +00001525 }
1526
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001527 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001528}
1529
Greg Clayton9e920902012-04-10 02:25:43 +00001530void
1531ProcessGDBRemote::ClearThreadIDList ()
1532{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001533 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001534 m_thread_ids.clear();
1535}
1536
1537bool
1538ProcessGDBRemote::UpdateThreadIDList ()
1539{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001540 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001541 bool sequence_mutex_unavailable = false;
1542 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1543 if (sequence_mutex_unavailable)
1544 {
Greg Clayton9e920902012-04-10 02:25:43 +00001545 return false; // We just didn't get the list
1546 }
1547 return true;
1548}
1549
Greg Clayton9fc13552012-04-10 00:18:59 +00001550bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001551ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001552{
1553 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +00001554 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Clayton73b472d2010-10-27 03:32:59 +00001555 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +00001556 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton9e920902012-04-10 02:25:43 +00001557
1558 size_t num_thread_ids = m_thread_ids.size();
1559 // The "m_thread_ids" thread ID list should always be updated after each stop
1560 // reply packet, but in case it isn't, update it here.
1561 if (num_thread_ids == 0)
1562 {
1563 if (!UpdateThreadIDList ())
1564 return false;
1565 num_thread_ids = m_thread_ids.size();
1566 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001567
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001568 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001569 if (num_thread_ids > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001570 {
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001571 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001572 {
Greg Clayton9e920902012-04-10 02:25:43 +00001573 tid_t tid = m_thread_ids[i];
Greg Clayton160c9d82013-05-01 21:54:04 +00001574 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001575 if (!thread_sp)
Jim Inghamdee1bc92013-06-22 00:27:45 +00001576 {
Jim Ingham4f465cf2012-10-10 18:32:14 +00001577 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001578 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1579 log->Printf(
1580 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001581 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001582 thread_sp->GetID());
1583 }
1584 else
1585 {
1586 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1587 log->Printf(
1588 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001589 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001590 thread_sp->GetID());
1591 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001592 new_thread_list.AddThread(thread_sp);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001593 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001594 }
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001595
1596 // Whatever that is left in old_thread_list_copy are not
1597 // present in new_thread_list. Remove non-existent threads from internal id table.
1598 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1599 for (size_t i=0; i<old_num_thread_ids; i++)
1600 {
1601 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1602 if (old_thread_sp)
1603 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001604 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001605 m_thread_id_to_index_id_map.erase(old_thread_id);
1606 }
1607 }
1608
Greg Clayton9fc13552012-04-10 00:18:59 +00001609 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001610}
1611
1612
1613StateType
1614ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1615{
Greg Claytondd0e5a52011-06-02 22:22:38 +00001616 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001617 const char stop_type = stop_packet.GetChar();
1618 switch (stop_type)
1619 {
1620 case 'T':
1621 case 'S':
1622 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00001623 // This is a bit of a hack, but is is required. If we did exec, we
1624 // need to clear our thread lists and also know to rebuild our dynamic
1625 // register info before we lookup and threads and populate the expedited
1626 // register values so we need to know this right away so we can cleanup
1627 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00001628 const uint32_t stop_id = GetStopID();
1629 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00001630 {
1631 // Our first stop, make sure we have a process ID, and also make
1632 // sure we know about our registers
1633 if (GetID() == LLDB_INVALID_PROCESS_ID)
1634 {
Greg Claytonc574ede2011-03-10 02:26:48 +00001635 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00001636 if (pid != LLDB_INVALID_PROCESS_ID)
1637 SetID (pid);
1638 }
1639 BuildDynamicRegisterInfo (true);
1640 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001641 // Stop with signal and thread info
1642 const uint8_t signo = stop_packet.GetHexU8();
1643 std::string name;
1644 std::string value;
1645 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00001646 std::string reason;
1647 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001648 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00001649 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001650 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001651 ThreadSP thread_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001652 ThreadGDBRemote *gdb_thread = NULL;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001653
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001654 while (stop_packet.GetNameColonValue(name, value))
1655 {
1656 if (name.compare("metype") == 0)
1657 {
1658 // exception type in big endian hex
1659 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1660 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001661 else if (name.compare("medata") == 0)
1662 {
1663 // exception data in big endian hex
1664 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1665 }
1666 else if (name.compare("thread") == 0)
1667 {
1668 // thread in big endian hex
Greg Clayton9e920902012-04-10 02:25:43 +00001669 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001670 // m_thread_list_real does have its own mutex, but we need to
1671 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1672 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1673 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1674 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
Greg Clayton160c9d82013-05-01 21:54:04 +00001675
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001676 if (!thread_sp)
Greg Claytond1d06e42013-04-20 00:27:58 +00001677 {
Greg Claytone576ab22011-02-15 00:19:15 +00001678 // Create the thread if we need to
Jim Ingham4f465cf2012-10-10 18:32:14 +00001679 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001680 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
1681 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1682 log->Printf ("ProcessGDBRemote::%s Adding new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1683 __FUNCTION__,
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001684 static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001685 thread_sp->GetID());
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001686
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001687 m_thread_list_real.AddThread(thread_sp);
Greg Claytone576ab22011-02-15 00:19:15 +00001688 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001689 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1690
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001691 }
Greg Clayton9e920902012-04-10 02:25:43 +00001692 else if (name.compare("threads") == 0)
1693 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001694 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001695 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00001696 // A comma separated list of all threads in the current
1697 // process that includes the thread for this stop reply
1698 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00001699 size_t comma_pos;
1700 lldb::tid_t tid;
1701 while ((comma_pos = value.find(',')) != std::string::npos)
1702 {
1703 value[comma_pos] = '\0';
1704 // thread in big endian hex
1705 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1706 if (tid != LLDB_INVALID_THREAD_ID)
1707 m_thread_ids.push_back (tid);
1708 value.erase(0, comma_pos + 1);
Greg Clayton9e920902012-04-10 02:25:43 +00001709 }
1710 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1711 if (tid != LLDB_INVALID_THREAD_ID)
1712 m_thread_ids.push_back (tid);
1713 }
Greg Claytonde9d0492011-01-08 03:17:57 +00001714 else if (name.compare("hexname") == 0)
1715 {
1716 StringExtractor name_extractor;
1717 // Swap "value" over into "name_extractor"
1718 name_extractor.GetStringRef().swap(value);
1719 // Now convert the HEX bytes into a string value
1720 name_extractor.GetHexByteString (value);
1721 thread_name.swap (value);
1722 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001723 else if (name.compare("name") == 0)
1724 {
1725 thread_name.swap (value);
1726 }
Greg Clayton6f35f5c2010-09-09 06:32:46 +00001727 else if (name.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001728 {
1729 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1730 }
Greg Claytona658fd22011-06-04 01:26:29 +00001731 else if (name.compare("reason") == 0)
1732 {
1733 reason.swap(value);
1734 }
1735 else if (name.compare("description") == 0)
1736 {
1737 StringExtractor desc_extractor;
1738 // Swap "value" over into "name_extractor"
1739 desc_extractor.GetStringRef().swap(value);
1740 // Now convert the HEX bytes into a string value
1741 desc_extractor.GetHexByteString (thread_name);
1742 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001743 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1744 {
1745 // We have a register number that contains an expedited
1746 // register value. Lets supply this register to our thread
1747 // so it won't have to go and read it.
Greg Clayton160c9d82013-05-01 21:54:04 +00001748 if (gdb_thread)
Greg Clayton3e06bd92011-01-09 21:07:35 +00001749 {
1750 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1751
1752 if (reg != UINT32_MAX)
1753 {
1754 StringExtractor reg_value_extractor;
1755 // Swap "value" over into "reg_value_extractor"
1756 reg_value_extractor.GetStringRef().swap(value);
Greg Clayton160c9d82013-05-01 21:54:04 +00001757 if (!gdb_thread->PrivateSetRegisterValue (reg, reg_value_extractor))
Greg Claytone576ab22011-02-15 00:19:15 +00001758 {
1759 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1760 name.c_str(),
1761 reg,
1762 reg,
1763 reg_value_extractor.GetStringRef().c_str(),
1764 stop_packet.GetStringRef().c_str());
1765 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001766 }
1767 }
1768 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001769 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001770
Hafiz Abid Qadeer673b4a32014-02-20 10:23:20 +00001771 // If the response is old style 'S' packet which does not provide us with thread information
1772 // then update the thread list and choose the first one.
1773 if (!thread_sp)
1774 {
1775 UpdateThreadIDList ();
1776
1777 if (!m_thread_ids.empty ())
1778 {
1779 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1780 thread_sp = m_thread_list_real.FindThreadByProtocolID (m_thread_ids.front (), false);
1781 if (thread_sp)
1782 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get ());
1783 }
1784 }
1785
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001786 if (thread_sp)
1787 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001788 // Clear the stop info just in case we don't set it to anything
1789 thread_sp->SetStopInfo (StopInfoSP());
1790
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001791 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Inghamdd2fe7a2011-01-28 02:23:12 +00001792 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001793 if (exc_type != 0)
1794 {
Greg Clayton1a65ae12011-01-25 23:55:37 +00001795 const size_t exc_data_size = exc_data.size();
Greg Claytonf4b47e12010-08-04 01:40:35 +00001796
Greg Clayton160c9d82013-05-01 21:54:04 +00001797 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1798 exc_type,
1799 exc_data_size,
1800 exc_data_size >= 1 ? exc_data[0] : 0,
1801 exc_data_size >= 2 ? exc_data[1] : 0,
1802 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001803 }
Greg Claytona658fd22011-06-04 01:26:29 +00001804 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001805 {
Greg Claytona658fd22011-06-04 01:26:29 +00001806 bool handled = false;
Greg Clayton8cda7f02013-05-21 21:55:59 +00001807 bool did_exec = false;
Greg Claytona658fd22011-06-04 01:26:29 +00001808 if (!reason.empty())
1809 {
1810 if (reason.compare("trace") == 0)
1811 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001812 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Greg Claytona658fd22011-06-04 01:26:29 +00001813 handled = true;
1814 }
1815 else if (reason.compare("breakpoint") == 0)
1816 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001817 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1818 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Claytona658fd22011-06-04 01:26:29 +00001819 if (bp_site_sp)
1820 {
1821 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1822 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1823 // 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 +00001824 handled = true;
Greg Clayton160c9d82013-05-01 21:54:04 +00001825 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00001826 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001827 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00001828 }
1829 else
1830 {
1831 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001832 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00001833 }
1834 }
Greg Claytona658fd22011-06-04 01:26:29 +00001835 }
1836 else if (reason.compare("trap") == 0)
1837 {
1838 // Let the trap just use the standard signal stop reason below...
1839 }
1840 else if (reason.compare("watchpoint") == 0)
1841 {
1842 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1843 // TODO: locate the watchpoint somehow...
Greg Clayton160c9d82013-05-01 21:54:04 +00001844 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
Greg Claytona658fd22011-06-04 01:26:29 +00001845 handled = true;
1846 }
1847 else if (reason.compare("exception") == 0)
1848 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001849 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00001850 handled = true;
1851 }
Greg Clayton15fc2be2013-05-21 01:00:52 +00001852 else if (reason.compare("exec") == 0)
1853 {
Greg Clayton8cda7f02013-05-21 21:55:59 +00001854 did_exec = true;
Greg Clayton15fc2be2013-05-21 01:00:52 +00001855 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
1856 handled = true;
1857 }
Greg Claytona658fd22011-06-04 01:26:29 +00001858 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001859
Jim Ingham40083a42014-02-24 19:49:46 +00001860 if (!handled && signo && did_exec == false)
Greg Claytona658fd22011-06-04 01:26:29 +00001861 {
1862 if (signo == SIGTRAP)
1863 {
1864 // Currently we are going to assume SIGTRAP means we are either
1865 // hitting a breakpoint or hardware single stepping.
Jim Ingham54cc6e42012-07-11 21:41:19 +00001866 handled = true;
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +00001867 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
Greg Clayton160c9d82013-05-01 21:54:04 +00001868 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001869
Greg Claytona658fd22011-06-04 01:26:29 +00001870 if (bp_site_sp)
1871 {
1872 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1873 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1874 // 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 +00001875 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00001876 {
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +00001877 if(m_breakpoint_pc_offset != 0)
1878 thread_sp->GetRegisterContext()->SetPC(pc);
Greg Clayton160c9d82013-05-01 21:54:04 +00001879 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00001880 }
1881 else
1882 {
1883 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001884 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00001885 }
1886 }
Jim Ingham54cc6e42012-07-11 21:41:19 +00001887 else
Greg Claytona658fd22011-06-04 01:26:29 +00001888 {
Jim Ingham4dc613b2012-10-27 02:52:04 +00001889 // If we were stepping then assume the stop was the result of the trace. If we were
1890 // not stepping then report the SIGTRAP.
1891 // FIXME: We are still missing the case where we single step over a trap instruction.
Greg Clayton160c9d82013-05-01 21:54:04 +00001892 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1893 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Jim Ingham4dc613b2012-10-27 02:52:04 +00001894 else
Greg Clayton160c9d82013-05-01 21:54:04 +00001895 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo));
Greg Claytona658fd22011-06-04 01:26:29 +00001896 }
1897 }
1898 if (!handled)
Greg Clayton160c9d82013-05-01 21:54:04 +00001899 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Jason Molenda8214b012013-04-25 01:33:46 +00001900 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001901
Greg Claytona658fd22011-06-04 01:26:29 +00001902 if (!description.empty())
1903 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001904 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
Greg Claytona658fd22011-06-04 01:26:29 +00001905 if (stop_info_sp)
1906 {
1907 stop_info_sp->SetDescription (description.c_str());
Greg Clayton3418c852011-08-10 02:10:13 +00001908 }
Greg Claytona658fd22011-06-04 01:26:29 +00001909 else
1910 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001911 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00001912 }
1913 }
1914 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001915 }
1916 return eStateStopped;
1917 }
1918 break;
1919
1920 case 'W':
Todd Fialaff6131a2014-05-19 04:57:23 +00001921 case 'X':
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001922 // process exited
1923 return eStateExited;
1924
1925 default:
1926 break;
1927 }
1928 return eStateInvalid;
1929}
1930
1931void
1932ProcessGDBRemote::RefreshStateAfterStop ()
1933{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001934 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001935 m_thread_ids.clear();
1936 // Set the thread stop info. It might have a "threads" key whose value is
1937 // a list of all thread IDs in the current process, so m_thread_ids might
1938 // get set.
1939 SetThreadStopInfo (m_last_stop_packet);
1940 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1941 if (m_thread_ids.empty())
1942 {
1943 // No, we need to fetch the thread list manually
1944 UpdateThreadIDList();
1945 }
1946
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001947 // Let all threads recover from stopping and do any clean up based
1948 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001949 m_thread_list_real.RefreshStateAfterStop();
Greg Clayton9e920902012-04-10 02:25:43 +00001950
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001951}
1952
1953Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001954ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001955{
1956 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001957
Greg Clayton6ed95942011-01-22 07:12:45 +00001958 bool timed_out = false;
1959 Mutex::Locker locker;
Greg Clayton513c26c2011-01-29 07:10:55 +00001960
1961 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00001962 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001963 // We are being asked to halt during an attach. We need to just close
1964 // our file handle and debugserver will go away, and we can be done...
1965 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00001966 }
Greg Clayton513c26c2011-01-29 07:10:55 +00001967 else
1968 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001969 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton513c26c2011-01-29 07:10:55 +00001970 {
1971 if (timed_out)
1972 error.SetErrorString("timed out sending interrupt packet");
1973 else
1974 error.SetErrorString("unknown error sending interrupt packet");
1975 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001976
1977 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton513c26c2011-01-29 07:10:55 +00001978 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001979 return error;
1980}
1981
1982Error
Jim Inghamacff8952013-05-02 00:27:30 +00001983ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00001984{
1985 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001986 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00001987 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00001988 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
1989
Jim Inghamacff8952013-05-02 00:27:30 +00001990 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001991 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00001992 {
Jim Inghamacff8952013-05-02 00:27:30 +00001993 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001994 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1995 else
Jim Inghamacff8952013-05-02 00:27:30 +00001996 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00001997 }
Jim Inghamacff8952013-05-02 00:27:30 +00001998
1999 if (!error.Success())
2000 return error;
2001
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002002 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00002003 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002004
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002005 SetPrivateState (eStateDetached);
2006 ResumePrivateStateThread();
2007
2008 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00002009 return error;
2010}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002011
Jim Ingham43c555d2012-07-04 00:35:43 +00002012
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002013Error
2014ProcessGDBRemote::DoDestroy ()
2015{
2016 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002017 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002018 if (log)
2019 log->Printf ("ProcessGDBRemote::DoDestroy()");
2020
Jim Ingham43c555d2012-07-04 00:35:43 +00002021 // There is a bug in older iOS debugservers where they don't shut down the process
2022 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
2023 // this can cause problems with restarting. So we check to see if any of our threads are stopped
2024 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
2025 // destroy it again.
2026 //
2027 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
2028 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
2029 // the debugservers with this bug are equal. There really should be a better way to test this!
2030 //
2031 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
2032 // get called here to destroy again and we're still at a breakpoint or exception, then we should
2033 // just do the straight-forward kill.
2034 //
2035 // And of course, if we weren't able to stop the process by the time we get here, it isn't
2036 // necessary (or helpful) to do any of this.
2037
2038 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
2039 {
2040 PlatformSP platform_sp = GetTarget().GetPlatform();
2041
2042 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2043 if (platform_sp
2044 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00002045 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00002046 {
2047 if (m_destroy_tried_resuming)
2048 {
2049 if (log)
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002050 log->PutCString ("ProcessGDBRemote::DoDestroy() - Tried resuming to destroy once already, not doing it again.");
Jim Ingham43c555d2012-07-04 00:35:43 +00002051 }
2052 else
2053 {
2054 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
2055 // but we really need it to happen here and it doesn't matter if we do it twice.
2056 m_thread_list.DiscardThreadPlans();
2057 DisableAllBreakpointSites();
2058
2059 bool stop_looks_like_crash = false;
2060 ThreadList &threads = GetThreadList();
2061
2062 {
Jim Ingham45350372012-09-11 00:08:52 +00002063 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002064
2065 size_t num_threads = threads.GetSize();
2066 for (size_t i = 0; i < num_threads; i++)
2067 {
2068 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002069 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002070 StopReason reason = eStopReasonInvalid;
2071 if (stop_info_sp)
2072 reason = stop_info_sp->GetStopReason();
2073 if (reason == eStopReasonBreakpoint
2074 || reason == eStopReasonException)
2075 {
2076 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002077 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
2078 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00002079 stop_info_sp->GetDescription());
2080 stop_looks_like_crash = true;
2081 break;
2082 }
2083 }
2084 }
2085
2086 if (stop_looks_like_crash)
2087 {
2088 if (log)
2089 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
2090 m_destroy_tried_resuming = true;
2091
2092 // If we are going to run again before killing, it would be good to suspend all the threads
2093 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
2094 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
2095 // have to run the risk of letting those threads proceed a bit.
2096
2097 {
Jim Ingham45350372012-09-11 00:08:52 +00002098 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002099
2100 size_t num_threads = threads.GetSize();
2101 for (size_t i = 0; i < num_threads; i++)
2102 {
2103 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002104 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002105 StopReason reason = eStopReasonInvalid;
2106 if (stop_info_sp)
2107 reason = stop_info_sp->GetStopReason();
2108 if (reason != eStopReasonBreakpoint
2109 && reason != eStopReasonException)
2110 {
2111 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002112 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
2113 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00002114 thread_sp->SetResumeState(eStateSuspended);
2115 }
2116 }
2117 }
2118 Resume ();
2119 return Destroy();
2120 }
2121 }
2122 }
2123 }
2124
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002125 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00002126 int exit_status = SIGABRT;
2127 std::string exit_string;
2128
Greg Clayton6ed95942011-01-22 07:12:45 +00002129 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002130 {
Jim Inghamaab78372011-10-28 01:11:35 +00002131 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00002132 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002133
2134 StringExtractorGDBRemote response;
2135 bool send_async = true;
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002136 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3);
2137
Greg Clayton3dedae12013-12-06 21:45:27 +00002138 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton513c26c2011-01-29 07:10:55 +00002139 {
2140 char packet_cmd = response.GetChar(0);
2141
2142 if (packet_cmd == 'W' || packet_cmd == 'X')
2143 {
Jim Inghameac0aa42014-02-21 22:36:11 +00002144#if defined(__APPLE__)
Jim Ingham9d67cc52014-02-21 22:35:29 +00002145 // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off
2146 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill
2147 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns
2148 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap
2149 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of
2150 // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2151 // Anyway, so call waitpid here to finally reap it.
2152 PlatformSP platform_sp(GetTarget().GetPlatform());
2153 if (platform_sp && platform_sp->IsHost())
2154 {
2155 int status;
2156 ::pid_t reap_pid;
2157 reap_pid = waitpid (GetID(), &status, WNOHANG);
2158 if (log)
2159 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2160 }
2161#endif
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002162 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002163 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00002164 exit_status = response.GetHexU8();
2165 }
2166 else
2167 {
2168 if (log)
2169 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2170 exit_string.assign("got unexpected response to k packet: ");
2171 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00002172 }
2173 }
2174 else
2175 {
Jim Inghambabfc382012-06-06 00:32:39 +00002176 if (log)
2177 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2178 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00002179 }
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002180
2181 m_gdb_comm.SetPacketTimeout(old_packet_timeout);
Greg Clayton6779606a2011-01-22 23:43:18 +00002182 }
Jim Inghambabfc382012-06-06 00:32:39 +00002183 else
2184 {
2185 if (log)
Ed Masteb3a53332014-03-17 17:05:22 +00002186 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching");
Jim Inghamcfc09352012-07-27 23:57:19 +00002187 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00002188 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002189 }
Jim Inghambabfc382012-06-06 00:32:39 +00002190 else
2191 {
2192 // If we missed setting the exit status on the way out, do it here.
2193 // NB set exit status can be called multiple times, the first one sets the status.
2194 exit_string.assign("destroying when not connected to debugserver");
2195 }
2196
2197 SetExitStatus(exit_status, exit_string.c_str());
2198
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002199 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002200 KillDebugserverProcess ();
2201 return error;
2202}
2203
Greg Clayton8cda7f02013-05-21 21:55:59 +00002204void
2205ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2206{
2207 lldb_private::Mutex::Locker locker (m_last_stop_packet_mutex);
2208 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2209 if (did_exec)
2210 {
2211 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2212 if (log)
2213 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2214
2215 m_thread_list_real.Clear();
2216 m_thread_list.Clear();
2217 BuildDynamicRegisterInfo (true);
2218 m_gdb_comm.ResetDiscoverableSettings();
2219 }
2220 m_last_stop_packet = response;
2221}
2222
2223
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002224//------------------------------------------------------------------
2225// Process Queries
2226//------------------------------------------------------------------
2227
2228bool
2229ProcessGDBRemote::IsAlive ()
2230{
Greg Clayton10177aa2010-12-08 05:08:21 +00002231 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002232}
2233
2234addr_t
2235ProcessGDBRemote::GetImageInfoAddress()
2236{
Jason Molenda6ba6d3d2013-01-30 04:39:32 +00002237 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002238}
2239
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002240//------------------------------------------------------------------
2241// Process Memory
2242//------------------------------------------------------------------
2243size_t
2244ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2245{
Jason Molenda6076bf42014-05-06 04:34:52 +00002246 GetMaxMemorySize ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002247 if (size > m_max_memory_size)
2248 {
2249 // Keep memory read sizes down to a sane limit. This function will be
2250 // called multiple times in order to complete the task by
2251 // lldb_private::Process so it is ok to do this.
2252 size = m_max_memory_size;
2253 }
2254
2255 char packet[64];
Jason Molenda6076bf42014-05-06 04:34:52 +00002256 int packet_len;
2257 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2258 if (binary_memory_read)
2259 {
2260 packet_len = ::snprintf (packet, sizeof(packet), "x0x%" PRIx64 ",0x%" PRIx64, (uint64_t)addr, (uint64_t)size);
2261 }
2262 else
2263 {
2264 packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
2265 }
Andy Gibbsa297a972013-06-19 19:04:53 +00002266 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002267 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002268 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002269 {
Greg Clayton576d8832011-03-22 04:00:09 +00002270 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002271 {
2272 error.Clear();
Jason Molenda6076bf42014-05-06 04:34:52 +00002273 if (binary_memory_read)
2274 {
2275 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any
2276 // 0x7d character escaping that was present in the packet
2277
2278 size_t data_received_size = response.GetBytesLeft();
2279 if (data_received_size > size)
2280 {
2281 // Don't write past the end of BUF if the remote debug server gave us too
2282 // much data for some reason.
2283 data_received_size = size;
2284 }
2285 memcpy (buf, response.GetStringRef().data(), data_received_size);
2286 return data_received_size;
2287 }
2288 else
2289 {
2290 return response.GetHexBytes(buf, size, '\xdd');
2291 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002292 }
Greg Clayton576d8832011-03-22 04:00:09 +00002293 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002294 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002295 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002296 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002297 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002298 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002299 }
2300 else
2301 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002302 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002303 }
2304 return 0;
2305}
2306
2307size_t
2308ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2309{
Jason Molenda6076bf42014-05-06 04:34:52 +00002310 GetMaxMemorySize ();
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002311 if (size > m_max_memory_size)
2312 {
2313 // Keep memory read sizes down to a sane limit. This function will be
2314 // called multiple times in order to complete the task by
2315 // lldb_private::Process so it is ok to do this.
2316 size = m_max_memory_size;
2317 }
2318
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002319 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00002320 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Clayton7fb56d02011-02-01 01:31:41 +00002321 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002322 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002323 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002324 {
Greg Clayton576d8832011-03-22 04:00:09 +00002325 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002326 {
2327 error.Clear();
2328 return size;
2329 }
Greg Clayton576d8832011-03-22 04:00:09 +00002330 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002331 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002332 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002333 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002334 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002335 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 +00002336 }
2337 else
2338 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002339 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002340 }
2341 return 0;
2342}
2343
2344lldb::addr_t
2345ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2346{
Todd Fialaaf245d12014-06-30 21:05:18 +00002347 lldb_private::Log *log (lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_EXPRESSIONS));
Greg Clayton2a48f522011-05-14 01:50:35 +00002348 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2349
Greg Clayton70b57652011-05-15 01:25:55 +00002350 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton2a48f522011-05-14 01:50:35 +00002351 switch (supported)
2352 {
2353 case eLazyBoolCalculate:
2354 case eLazyBoolYes:
2355 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2356 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2357 return allocated_addr;
2358
2359 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002360 // Call mmap() to create memory in the inferior..
2361 unsigned prot = 0;
2362 if (permissions & lldb::ePermissionsReadable)
2363 prot |= eMmapProtRead;
2364 if (permissions & lldb::ePermissionsWritable)
2365 prot |= eMmapProtWrite;
2366 if (permissions & lldb::ePermissionsExecutable)
2367 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00002368
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002369 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2370 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2371 m_addr_to_mmap_size[allocated_addr] = size;
2372 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002373 {
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002374 allocated_addr = LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00002375 if (log)
2376 log->Printf ("ProcessGDBRemote::%s no direct stub support for memory allocation, and InferiorCallMmap also failed - is stub missing register context save/restore capability?", __FUNCTION__);
2377 }
Greg Clayton2a48f522011-05-14 01:50:35 +00002378 break;
2379 }
2380
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002381 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00002382 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002383 else
2384 error.Clear();
2385 return allocated_addr;
2386}
2387
2388Error
Greg Clayton46fb5582011-11-18 07:03:08 +00002389ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2390 MemoryRegionInfo &region_info)
2391{
2392
2393 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2394 return error;
2395}
2396
2397Error
Johnny Chen64637202012-05-23 21:09:52 +00002398ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2399{
2400
2401 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2402 return error;
2403}
2404
2405Error
Enrico Granataf04a2192012-07-13 23:18:48 +00002406ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2407{
2408 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2409 return error;
2410}
2411
2412Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002413ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2414{
2415 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00002416 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2417
2418 switch (supported)
2419 {
2420 case eLazyBoolCalculate:
2421 // We should never be deallocating memory without allocating memory
2422 // first so we should never get eLazyBoolCalculate
2423 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2424 break;
2425
2426 case eLazyBoolYes:
2427 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00002428 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002429 break;
2430
2431 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002432 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00002433 {
2434 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002435 if (pos != m_addr_to_mmap_size.end() &&
2436 InferiorCallMunmap(this, addr, pos->second))
2437 m_addr_to_mmap_size.erase (pos);
2438 else
Daniel Malead01b2952012-11-29 21:49:15 +00002439 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002440 }
2441 break;
2442 }
2443
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002444 return error;
2445}
2446
2447
2448//------------------------------------------------------------------
2449// Process STDIO
2450//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002451size_t
2452ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2453{
2454 if (m_stdio_communication.IsConnected())
2455 {
2456 ConnectionStatus status;
2457 m_stdio_communication.Write(src, src_len, status, NULL);
2458 }
2459 return 0;
2460}
2461
2462Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002463ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002464{
2465 Error error;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002466 assert(bp_site != NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002467
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002468 // Get logging info
2469 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002470 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002471
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002472 // Get the breakpoint address
2473 const addr_t addr = bp_site->GetLoadAddress();
2474
2475 // Log that a breakpoint was requested
2476 if (log)
2477 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
2478
2479 // Breakpoint already exists and is enabled
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002480 if (bp_site->IsEnabled())
2481 {
2482 if (log)
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002483 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 +00002484 return error;
2485 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002486
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002487 // Get the software breakpoint trap opcode size
2488 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2489
2490 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
2491 // is supported by the remote stub. These are set to true by default, and later set to false
2492 // only after we receive an unimplemented response when sending a breakpoint packet. This means
2493 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
2494 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
2495 // indicates if the user specifically asked for hardware breakpoints. If true then we will
2496 // skip over software breakpoints.
2497 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
2498 {
2499 // Try to send off a software breakpoint packet ($Z0)
2500 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002501 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002502 // The breakpoint was placed successfully
2503 bp_site->SetEnabled(true);
2504 bp_site->SetType(BreakpointSite::eExternal);
Greg Claytoneb023e72013-10-11 19:48:25 +00002505 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002506 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002507
2508 // SendGDBStoppointTypePacket() will return an error if it was unable to set this
2509 // breakpoint. We need to differentiate between a error specific to placing this breakpoint
2510 // or if we have learned that this breakpoint type is unsupported. To do this, we
2511 // must test the support boolean for this breakpoint type to see if it now indicates that
2512 // this breakpoint type is unsupported. If they are still supported then we should return
2513 // with the error code. If they are now unsupported, then we would like to fall through
2514 // and try another form of breakpoint.
2515 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
2516 return error;
2517
2518 // We reach here when software breakpoints have been found to be unsupported. For future
2519 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
2520 // known not to be supported.
2521 if (log)
2522 log->Printf("Software breakpoints are unsupported");
2523
2524 // So we will fall through and try a hardware breakpoint
2525 }
2526
2527 // The process of setting a hardware breakpoint is much the same as above. We check the
2528 // supported boolean for this breakpoint type, and if it is thought to be supported then we
2529 // will try to set this breakpoint with a hardware breakpoint.
2530 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
2531 {
2532 // Try to send off a hardware breakpoint packet ($Z1)
2533 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002534 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002535 // The breakpoint was placed successfully
2536 bp_site->SetEnabled(true);
2537 bp_site->SetType(BreakpointSite::eHardware);
2538 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002539 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002540
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002541 // Check if the error was something other then an unsupported breakpoint type
2542 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
2543 {
2544 // Unable to set this hardware breakpoint
2545 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
2546 return error;
2547 }
2548
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002549 // We will reach here when the stub gives an unsupported response to a hardware breakpoint
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002550 if (log)
2551 log->Printf("Hardware breakpoints are unsupported");
2552
2553 // Finally we will falling through to a #trap style breakpoint
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002554 }
2555
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002556 // Don't fall through when hardware breakpoints were specifically requested
2557 if (bp_site->HardwareRequired())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002558 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002559 error.SetErrorString("hardware breakpoints are not supported");
2560 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002561 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002562
2563 // As a last resort we want to place a manual breakpoint. An instruction
2564 // is placed into the process memory using memory write packets.
2565 return EnableSoftwareBreakpoint(bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002566}
2567
2568Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002569ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002570{
2571 Error error;
2572 assert (bp_site != NULL);
2573 addr_t addr = bp_site->GetLoadAddress();
2574 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00002575 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002576 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002577 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002578
2579 if (bp_site->IsEnabled())
2580 {
2581 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2582
Greg Clayton8b82f082011-04-12 05:54:46 +00002583 BreakpointSite::Type bp_type = bp_site->GetType();
2584 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002585 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002586 case BreakpointSite::eSoftware:
2587 error = DisableSoftwareBreakpoint (bp_site);
2588 break;
2589
2590 case BreakpointSite::eHardware:
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002591 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00002592 error.SetErrorToGenericError();
2593 break;
2594
2595 case BreakpointSite::eExternal:
Jim Inghama04ef752014-03-07 11:18:02 +00002596 {
2597 GDBStoppointType stoppoint_type;
2598 if (bp_site->IsHardware())
2599 stoppoint_type = eBreakpointHardware;
2600 else
2601 stoppoint_type = eBreakpointSoftware;
2602
2603 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00002604 error.SetErrorToGenericError();
Jim Inghama04ef752014-03-07 11:18:02 +00002605 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002606 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002607 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002608 if (error.Success())
2609 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002610 }
2611 else
2612 {
2613 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002614 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 +00002615 return error;
2616 }
2617
2618 if (error.Success())
2619 error.SetErrorToGenericError();
2620 return error;
2621}
2622
Johnny Chen11309a32011-09-06 22:38:36 +00002623// Pre-requisite: wp != NULL.
2624static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00002625GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00002626{
2627 assert(wp);
2628 bool watch_read = wp->WatchpointRead();
2629 bool watch_write = wp->WatchpointWrite();
2630
2631 // watch_read and watch_write cannot both be false.
2632 assert(watch_read || watch_write);
2633 if (watch_read && watch_write)
2634 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00002635 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00002636 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00002637 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00002638 return eWatchpointWrite;
2639}
2640
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002641Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002642ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002643{
2644 Error error;
2645 if (wp)
2646 {
2647 user_id_t watchID = wp->GetID();
2648 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00002649 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002650 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002651 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002652 if (wp->IsEnabled())
2653 {
2654 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002655 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 +00002656 return error;
2657 }
Johnny Chen11309a32011-09-06 22:38:36 +00002658
2659 GDBStoppointType type = GetGDBStoppointType(wp);
2660 // Pass down an appropriate z/Z packet...
2661 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002662 {
Johnny Chen11309a32011-09-06 22:38:36 +00002663 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2664 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002665 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002666 return error;
2667 }
2668 else
2669 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002670 }
Johnny Chen11309a32011-09-06 22:38:36 +00002671 else
2672 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002673 }
2674 else
2675 {
Johnny Chen01a67862011-10-14 00:42:25 +00002676 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002677 }
2678 if (error.Success())
2679 error.SetErrorToGenericError();
2680 return error;
2681}
2682
2683Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002684ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002685{
2686 Error error;
2687 if (wp)
2688 {
2689 user_id_t watchID = wp->GetID();
2690
Greg Clayton5160ce52013-03-27 23:08:40 +00002691 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002692
2693 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00002694
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002695 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002696 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002697
Johnny Chen11309a32011-09-06 22:38:36 +00002698 if (!wp->IsEnabled())
2699 {
2700 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002701 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 +00002702 // See also 'class WatchpointSentry' within StopInfo.cpp.
2703 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2704 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00002705 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002706 return error;
2707 }
2708
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002709 if (wp->IsHardware())
2710 {
Johnny Chen11309a32011-09-06 22:38:36 +00002711 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002712 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00002713 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2714 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002715 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002716 return error;
2717 }
2718 else
2719 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002720 }
2721 // TODO: clear software watchpoints if we implement them
2722 }
2723 else
2724 {
Johnny Chen01a67862011-10-14 00:42:25 +00002725 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002726 }
2727 if (error.Success())
2728 error.SetErrorToGenericError();
2729 return error;
2730}
2731
2732void
2733ProcessGDBRemote::Clear()
2734{
2735 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002736 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002737 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002738}
2739
2740Error
2741ProcessGDBRemote::DoSignal (int signo)
2742{
2743 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002744 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002745 if (log)
2746 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2747
2748 if (!m_gdb_comm.SendAsyncSignal (signo))
2749 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2750 return error;
2751}
2752
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002753Error
Greg Clayton91a9b2472013-12-04 19:19:12 +00002754ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002755{
2756 Error error;
2757 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2758 {
2759 // If we locate debugserver, keep that located version around
2760 static FileSpec g_debugserver_file_spec;
2761
Han Ming Ong84647042012-02-25 01:07:38 +00002762 ProcessLaunchInfo debugserver_launch_info;
Greg Clayton91a9b2472013-12-04 19:19:12 +00002763 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2764 debugserver_launch_info.SetUserID(process_info.GetUserID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002765
Todd Fiala013434e2014-07-09 01:29:05 +00002766#if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__) || defined (__aarch64__))
Greg Claytonfda4fab2014-01-10 22:24:11 +00002767 // On iOS, still do a local connection using a random port
Greg Clayton16810922014-02-27 19:38:18 +00002768 const char *hostname = "127.0.0.1";
Greg Claytonfda4fab2014-01-10 22:24:11 +00002769 uint16_t port = get_random_port ();
2770#else
2771 // Set hostname being NULL to do the reverse connect where debugserver
2772 // will bind to port zero and it will communicate back to us the port
2773 // that we will connect to
2774 const char *hostname = NULL;
2775 uint16_t port = 0;
2776#endif
2777
2778 error = m_gdb_comm.StartDebugserverProcess (hostname,
2779 port,
Greg Clayton00fe87b2013-12-05 22:58:22 +00002780 debugserver_launch_info,
2781 port);
Greg Clayton91a9b2472013-12-04 19:19:12 +00002782
2783 if (error.Success ())
2784 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002785 else
Greg Clayton91a9b2472013-12-04 19:19:12 +00002786 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002787
2788 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2789 StartAsyncThread ();
Greg Clayton91a9b2472013-12-04 19:19:12 +00002790
2791 if (error.Fail())
2792 {
2793 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
2794
2795 if (log)
2796 log->Printf("failed to start debugserver process: %s", error.AsCString());
2797 return error;
2798 }
2799
Greg Clayton00fe87b2013-12-05 22:58:22 +00002800 if (m_gdb_comm.IsConnected())
2801 {
2802 // Finish the connection process by doing the handshake without connecting (send NULL URL)
2803 ConnectToDebugserver (NULL);
2804 }
2805 else
2806 {
Greg Claytonfda4fab2014-01-10 22:24:11 +00002807 StreamString connect_url;
2808 connect_url.Printf("connect://%s:%u", hostname, port);
2809 error = ConnectToDebugserver (connect_url.GetString().c_str());
Greg Clayton00fe87b2013-12-05 22:58:22 +00002810 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00002811
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002812 }
2813 return error;
2814}
2815
2816bool
2817ProcessGDBRemote::MonitorDebugserverProcess
2818(
2819 void *callback_baton,
2820 lldb::pid_t debugserver_pid,
Greg Claytone4e45922011-11-16 05:37:56 +00002821 bool exited, // True if the process did exit
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002822 int signo, // Zero for no signal
2823 int exit_status // Exit value of process if signal is zero
2824)
2825{
Greg Claytone4e45922011-11-16 05:37:56 +00002826 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2827 // and might not exist anymore, so we need to carefully try to get the
2828 // target for this process first since we have a race condition when
2829 // we are done running between getting the notice that the inferior
2830 // process has died and the debugserver that was debugging this process.
2831 // In our test suite, we are also continually running process after
2832 // process, so we must be very careful to make sure:
2833 // 1 - process object hasn't been deleted already
2834 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002835
2836 // "debugserver_pid" argument passed in is the process ID for
2837 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00002838 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002839
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002840 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton6779606a2011-01-22 23:43:18 +00002841
Greg Claytone4e45922011-11-16 05:37:56 +00002842 // Get a shared pointer to the target that has a matching process pointer.
2843 // This target could be gone, or the target could already have a new process
2844 // object inside of it
2845 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2846
Greg Clayton6779606a2011-01-22 23:43:18 +00002847 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002848 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 +00002849
Greg Claytone4e45922011-11-16 05:37:56 +00002850 if (target_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002851 {
Greg Claytone4e45922011-11-16 05:37:56 +00002852 // We found a process in a target that matches, but another thread
2853 // might be in the process of launching a new process that will
2854 // soon replace it, so get a shared pointer to the process so we
2855 // can keep it alive.
2856 ProcessSP process_sp (target_sp->GetProcessSP());
2857 // Now we have a shared pointer to the process that can't go away on us
2858 // so we now make sure it was the same as the one passed in, and also make
2859 // sure that our previous "process *" didn't get deleted and have a new
2860 // "process *" created in its place with the same pointer. To verify this
2861 // we make sure the process has our debugserver process ID. If we pass all
2862 // of these tests, then we are sure that this process is the one we were
2863 // looking for.
2864 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002865 {
Greg Claytone4e45922011-11-16 05:37:56 +00002866 // Sleep for a half a second to make sure our inferior process has
2867 // time to set its exit status before we set it incorrectly when
2868 // both the debugserver and the inferior process shut down.
2869 usleep (500000);
2870 // If our process hasn't yet exited, debugserver might have died.
2871 // If the process did exit, the we are reaping it.
2872 const StateType state = process->GetState();
2873
2874 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2875 state != eStateInvalid &&
2876 state != eStateUnloaded &&
2877 state != eStateExited &&
2878 state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002879 {
Greg Claytone4e45922011-11-16 05:37:56 +00002880 char error_str[1024];
2881 if (signo)
2882 {
2883 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2884 if (signal_cstr)
2885 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2886 else
2887 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2888 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002889 else
Greg Claytone4e45922011-11-16 05:37:56 +00002890 {
2891 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2892 }
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002893
Greg Claytone4e45922011-11-16 05:37:56 +00002894 process->SetExitStatus (-1, error_str);
2895 }
2896 // Debugserver has exited we need to let our ProcessGDBRemote
2897 // know that it no longer has a debugserver instance
2898 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002899 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002900 }
2901 return true;
2902}
2903
2904void
2905ProcessGDBRemote::KillDebugserverProcess ()
2906{
Greg Claytonfbb76342013-11-20 21:07:01 +00002907 m_gdb_comm.Disconnect();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002908 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2909 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002910 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002911 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2912 }
2913}
2914
2915void
2916ProcessGDBRemote::Initialize()
2917{
2918 static bool g_initialized = false;
2919
2920 if (g_initialized == false)
2921 {
2922 g_initialized = true;
2923 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2924 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00002925 CreateInstance,
2926 DebuggerInitialize);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002927
2928 Log::Callbacks log_callbacks = {
2929 ProcessGDBRemoteLog::DisableLog,
2930 ProcessGDBRemoteLog::EnableLog,
2931 ProcessGDBRemoteLog::ListLogCategories
2932 };
2933
2934 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2935 }
2936}
2937
Greg Clayton7f982402013-07-15 22:54:20 +00002938void
2939ProcessGDBRemote::DebuggerInitialize (lldb_private::Debugger &debugger)
2940{
2941 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
2942 {
2943 const bool is_global_setting = true;
2944 PluginManager::CreateSettingForProcessPlugin (debugger,
2945 GetGlobalPluginProperties()->GetValueProperties(),
2946 ConstString ("Properties for the gdb-remote process plug-in."),
2947 is_global_setting);
2948 }
2949}
2950
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002951bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002952ProcessGDBRemote::StartAsyncThread ()
2953{
Greg Clayton5160ce52013-03-27 23:08:40 +00002954 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002955
2956 if (log)
2957 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Ingham455fa5c2012-11-01 01:15:33 +00002958
2959 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00002960 if (!m_async_thread.IsJoinable())
Jim Ingham455fa5c2012-11-01 01:15:33 +00002961 {
2962 // Create a thread that watches our internal state and controls which
2963 // events make it to clients (into the DCProcess event queue).
Zachary Turner39de3112014-09-09 20:54:56 +00002964
2965 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Jim Ingham455fa5c2012-11-01 01:15:33 +00002966 }
Zachary Turneracee96a2014-09-23 18:32:09 +00002967 else if (log)
2968 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was already running.", __FUNCTION__);
Zachary Turner39de3112014-09-09 20:54:56 +00002969
Zachary Turneracee96a2014-09-23 18:32:09 +00002970 return m_async_thread.IsJoinable();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002971}
2972
2973void
2974ProcessGDBRemote::StopAsyncThread ()
2975{
Greg Clayton5160ce52013-03-27 23:08:40 +00002976 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002977
2978 if (log)
2979 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2980
Jim Ingham455fa5c2012-11-01 01:15:33 +00002981 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00002982 if (m_async_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002983 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00002984 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2985
2986 // This will shut down the async thread.
2987 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
2988
2989 // Stop the stdio thread
Zachary Turner39de3112014-09-09 20:54:56 +00002990 m_async_thread.Join(nullptr);
Jim Ingham455fa5c2012-11-01 01:15:33 +00002991 }
Zachary Turneracee96a2014-09-23 18:32:09 +00002992 else if (log)
2993 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002994}
2995
2996
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002997thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002998ProcessGDBRemote::AsyncThread (void *arg)
2999{
3000 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
3001
Greg Clayton5160ce52013-03-27 23:08:40 +00003002 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003003 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003004 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003005
3006 Listener listener ("ProcessGDBRemote::AsyncThread");
3007 EventSP event_sp;
3008 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
3009 eBroadcastBitAsyncThreadShouldExit;
3010
3011 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
3012 {
Greg Clayton71337622011-02-24 22:24:29 +00003013 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
3014
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003015 bool done = false;
3016 while (!done)
3017 {
3018 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003019 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003020 if (listener.WaitForEvent (NULL, event_sp))
3021 {
3022 const uint32_t event_type = event_sp->GetType();
Greg Clayton71337622011-02-24 22:24:29 +00003023 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003024 {
Greg Clayton71337622011-02-24 22:24:29 +00003025 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003026 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 +00003027
Greg Clayton71337622011-02-24 22:24:29 +00003028 switch (event_type)
3029 {
3030 case eBroadcastBitAsyncContinue:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003031 {
Greg Clayton71337622011-02-24 22:24:29 +00003032 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003033
Greg Clayton71337622011-02-24 22:24:29 +00003034 if (continue_packet)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003035 {
Greg Clayton71337622011-02-24 22:24:29 +00003036 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
3037 const size_t continue_cstr_len = continue_packet->GetByteSize ();
3038 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003039 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003040
Greg Clayton71337622011-02-24 22:24:29 +00003041 if (::strstr (continue_cstr, "vAttach") == NULL)
3042 process->SetPrivateState(eStateRunning);
3043 StringExtractorGDBRemote response;
3044 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003045
Greg Clayton0772ded2012-05-16 02:48:06 +00003046 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
3047 // The thread ID list might be contained within the "response", or the stop reply packet that
3048 // caused the stop. So clear it now before we give the stop reply packet to the process
3049 // using the process->SetLastStopPacket()...
3050 process->ClearThreadIDList ();
3051
Greg Clayton71337622011-02-24 22:24:29 +00003052 switch (stop_state)
3053 {
3054 case eStateStopped:
3055 case eStateCrashed:
3056 case eStateSuspended:
Greg Clayton09c3e3d2011-12-06 04:51:14 +00003057 process->SetLastStopPacket (response);
Greg Clayton71337622011-02-24 22:24:29 +00003058 process->SetPrivateState (stop_state);
3059 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003060
Greg Clayton71337622011-02-24 22:24:29 +00003061 case eStateExited:
Jason Molendaa3329782014-03-29 18:54:20 +00003062 {
Greg Clayton09c3e3d2011-12-06 04:51:14 +00003063 process->SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00003064 process->ClearThreadIDList();
Greg Clayton71337622011-02-24 22:24:29 +00003065 response.SetFilePos(1);
Jason Molendaa3329782014-03-29 18:54:20 +00003066
3067 int exit_status = response.GetHexU8();
3068 const char *desc_cstr = NULL;
3069 StringExtractor extractor;
3070 std::string desc_string;
3071 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';')
3072 {
3073 std::string desc_token;
3074 while (response.GetNameColonValue (desc_token, desc_string))
3075 {
3076 if (desc_token == "description")
3077 {
3078 extractor.GetStringRef().swap(desc_string);
3079 extractor.SetFilePos(0);
3080 extractor.GetHexByteString (desc_string);
3081 desc_cstr = desc_string.c_str();
3082 }
3083 }
3084 }
3085 process->SetExitStatus(exit_status, desc_cstr);
Greg Clayton71337622011-02-24 22:24:29 +00003086 done = true;
3087 break;
Jason Molendaa3329782014-03-29 18:54:20 +00003088 }
Greg Clayton71337622011-02-24 22:24:29 +00003089 case eStateInvalid:
3090 process->SetExitStatus(-1, "lost connection");
3091 break;
3092
3093 default:
3094 process->SetPrivateState (stop_state);
3095 break;
3096 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003097 }
3098 }
Greg Clayton71337622011-02-24 22:24:29 +00003099 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003100
Greg Clayton71337622011-02-24 22:24:29 +00003101 case eBroadcastBitAsyncThreadShouldExit:
3102 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003103 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Clayton71337622011-02-24 22:24:29 +00003104 done = true;
3105 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003106
Greg Clayton71337622011-02-24 22:24:29 +00003107 default:
3108 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003109 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 +00003110 done = true;
3111 break;
3112 }
3113 }
3114 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
3115 {
3116 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
3117 {
3118 process->SetExitStatus (-1, "lost connection");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003119 done = true;
Greg Clayton71337622011-02-24 22:24:29 +00003120 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003121 }
3122 }
3123 else
3124 {
3125 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003126 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 +00003127 done = true;
3128 }
3129 }
3130 }
3131
3132 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003133 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003134
Zachary Turner39de3112014-09-09 20:54:56 +00003135 process->m_async_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003136 return NULL;
3137}
3138
Greg Claytone996fd32011-03-08 22:40:15 +00003139//uint32_t
3140//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3141//{
3142// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
3143// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
3144// if (m_local_debugserver)
3145// {
3146// return Host::ListProcessesMatchingName (name, matches, pids);
3147// }
3148// else
3149// {
3150// // FIXME: Implement talking to the remote debugserver.
3151// return 0;
3152// }
3153//
3154//}
3155//
Jim Ingham1c823b42011-01-22 01:33:44 +00003156bool
3157ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
3158 lldb_private::StoppointCallbackContext *context,
3159 lldb::user_id_t break_id,
3160 lldb::user_id_t break_loc_id)
3161{
3162 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3163 // run so I can stop it if that's what I want to do.
Greg Clayton5160ce52013-03-27 23:08:40 +00003164 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00003165 if (log)
3166 log->Printf("Hit New Thread Notification breakpoint.");
3167 return false;
3168}
3169
3170
3171bool
3172ProcessGDBRemote::StartNoticingNewThreads()
3173{
Greg Clayton5160ce52013-03-27 23:08:40 +00003174 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00003175 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003176 {
Greg Clayton4116e932012-05-15 02:33:01 +00003177 if (log && log->GetVerbose())
3178 log->Printf("Enabled noticing new thread breakpoint.");
3179 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003180 }
Greg Clayton4116e932012-05-15 02:33:01 +00003181 else
Jim Ingham1c823b42011-01-22 01:33:44 +00003182 {
Greg Clayton4116e932012-05-15 02:33:01 +00003183 PlatformSP platform_sp (m_target.GetPlatform());
3184 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003185 {
Greg Clayton4116e932012-05-15 02:33:01 +00003186 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3187 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003188 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00003189 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00003190 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3191 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003192 }
3193 else
3194 {
3195 if (log)
3196 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00003197 }
3198 }
3199 }
Greg Clayton4116e932012-05-15 02:33:01 +00003200 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00003201}
3202
3203bool
3204ProcessGDBRemote::StopNoticingNewThreads()
3205{
Greg Clayton5160ce52013-03-27 23:08:40 +00003206 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00003207 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00003208 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00003209
3210 if (m_thread_create_bp_sp)
3211 m_thread_create_bp_sp->SetEnabled(false);
3212
Jim Ingham1c823b42011-01-22 01:33:44 +00003213 return true;
3214}
3215
Jason Molenda5e8534e2012-10-03 01:29:34 +00003216lldb_private::DynamicLoader *
3217ProcessGDBRemote::GetDynamicLoader ()
3218{
3219 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00003220 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00003221 return m_dyld_ap.get();
3222}
Jim Ingham1c823b42011-01-22 01:33:44 +00003223
Jason Molendaa3329782014-03-29 18:54:20 +00003224Error
3225ProcessGDBRemote::SendEventData(const char *data)
3226{
3227 int return_value;
3228 bool was_supported;
3229
3230 Error error;
3231
3232 return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported);
3233 if (return_value != 0)
3234 {
3235 if (!was_supported)
3236 error.SetErrorString("Sending events is not supported for this process.");
3237 else
3238 error.SetErrorStringWithFormat("Error sending event data: %d.", return_value);
3239 }
3240 return error;
3241}
3242
Steve Pucci03904ac2014-03-04 23:18:46 +00003243const DataBufferSP
3244ProcessGDBRemote::GetAuxvData()
3245{
3246 DataBufferSP buf;
3247 if (m_gdb_comm.GetQXferAuxvReadSupported())
3248 {
3249 std::string response_string;
3250 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success)
3251 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length()));
3252 }
3253 return buf;
3254}
3255
Jason Molenda705b1802014-06-13 02:37:02 +00003256StructuredData::ObjectSP
3257ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid)
3258{
3259 StructuredData::ObjectSP object_sp;
3260
3261 if (m_gdb_comm.GetThreadExtendedInfoSupported())
3262 {
3263 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3264 SystemRuntime *runtime = GetSystemRuntime();
3265 if (runtime)
3266 {
3267 runtime->AddThreadExtendedInfoPacketHints (args_dict);
3268 }
3269 args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid);
3270
3271 StreamString packet;
3272 packet << "jThreadExtendedInfo:";
3273 args_dict->Dump (packet);
3274
3275 // FIXME the final character of a JSON dictionary, '}', is the escape
3276 // character in gdb-remote binary mode. lldb currently doesn't escape
3277 // these characters in its packet output -- so we add the quoted version
3278 // of the } character here manually in case we talk to a debugserver which
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003279 // un-escapes the characters at packet read time.
Jason Molenda705b1802014-06-13 02:37:02 +00003280 packet << (char) (0x7d ^ 0x20);
3281
3282 StringExtractorGDBRemote response;
3283 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
3284 {
3285 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
3286 if (response_type == StringExtractorGDBRemote::eResponse)
3287 {
3288 if (!response.Empty())
3289 {
3290 // The packet has already had the 0x7d xor quoting stripped out at the
3291 // GDBRemoteCommunication packet receive level.
3292 object_sp = StructuredData::ParseJSON (response.GetStringRef());
3293 }
3294 }
3295 }
3296 }
3297 return object_sp;
3298}
3299
Jason Molenda6076bf42014-05-06 04:34:52 +00003300// Establish the largest memory read/write payloads we should use.
3301// If the remote stub has a max packet size, stay under that size.
3302//
3303// If the remote stub's max packet size is crazy large, use a
3304// reasonable largeish default.
3305//
3306// If the remote stub doesn't advertise a max packet size, use a
3307// conservative default.
3308
3309void
3310ProcessGDBRemote::GetMaxMemorySize()
3311{
3312 const uint64_t reasonable_largeish_default = 128 * 1024;
3313 const uint64_t conservative_default = 512;
3314
3315 if (m_max_memory_size == 0)
3316 {
3317 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
3318 if (stub_max_size != UINT64_MAX && stub_max_size != 0)
3319 {
3320 // Save the stub's claimed maximum packet size
3321 m_remote_stub_max_memory_size = stub_max_size;
3322
3323 // Even if the stub says it can support ginormous packets,
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003324 // don't exceed our reasonable largeish default packet size.
Jason Molenda6076bf42014-05-06 04:34:52 +00003325 if (stub_max_size > reasonable_largeish_default)
3326 {
3327 stub_max_size = reasonable_largeish_default;
3328 }
3329
3330 m_max_memory_size = stub_max_size;
3331 }
3332 else
3333 {
3334 m_max_memory_size = conservative_default;
3335 }
3336 }
3337}
3338
3339void
3340ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max)
3341{
3342 if (user_specified_max != 0)
3343 {
3344 GetMaxMemorySize ();
3345
3346 if (m_remote_stub_max_memory_size != 0)
3347 {
3348 if (m_remote_stub_max_memory_size < user_specified_max)
3349 {
3350 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a packet size too big, go as big
3351 // as the remote stub says we can go.
3352 }
3353 else
3354 {
3355 m_max_memory_size = user_specified_max; // user's packet size is good
3356 }
3357 }
3358 else
3359 {
3360 m_max_memory_size = user_specified_max; // user's packet size is probably fine
3361 }
3362 }
3363}
3364
Greg Clayton02686b82012-10-15 22:42:16 +00003365class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00003366{
3367private:
3368
3369public:
Greg Clayton02686b82012-10-15 22:42:16 +00003370 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00003371 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00003372 "process plugin packet history",
3373 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00003374 NULL)
3375 {
3376 }
3377
Greg Clayton02686b82012-10-15 22:42:16 +00003378 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton998255b2012-10-13 02:07:45 +00003379 {
3380 }
3381
3382 bool
3383 DoExecute (Args& command, CommandReturnObject &result)
3384 {
Greg Clayton02686b82012-10-15 22:42:16 +00003385 const size_t argc = command.GetArgumentCount();
3386 if (argc == 0)
3387 {
3388 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3389 if (process)
3390 {
3391 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
3392 result.SetStatus (eReturnStatusSuccessFinishResult);
3393 return true;
3394 }
3395 }
3396 else
3397 {
3398 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
3399 }
3400 result.SetStatus (eReturnStatusFailed);
3401 return false;
3402 }
3403};
3404
Jason Molenda6076bf42014-05-06 04:34:52 +00003405class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed
3406{
3407private:
3408
3409public:
3410 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) :
3411 CommandObjectParsed (interpreter,
3412 "process plugin packet xfer-size",
3413 "Maximum size that lldb will try to read/write one one chunk.",
3414 NULL)
3415 {
3416 }
3417
3418 ~CommandObjectProcessGDBRemotePacketXferSize ()
3419 {
3420 }
3421
3422 bool
3423 DoExecute (Args& command, CommandReturnObject &result)
3424 {
3425 const size_t argc = command.GetArgumentCount();
3426 if (argc == 0)
3427 {
3428 result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str());
3429 result.SetStatus (eReturnStatusFailed);
3430 return false;
3431 }
3432
3433 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3434 if (process)
3435 {
3436 const char *packet_size = command.GetArgumentAtIndex(0);
3437 errno = 0;
3438 uint64_t user_specified_max = strtoul (packet_size, NULL, 10);
3439 if (errno == 0 && user_specified_max != 0)
3440 {
3441 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max);
3442 result.SetStatus (eReturnStatusSuccessFinishResult);
3443 return true;
3444 }
3445 }
3446 result.SetStatus (eReturnStatusFailed);
3447 return false;
3448 }
3449};
3450
3451
Greg Clayton02686b82012-10-15 22:42:16 +00003452class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
3453{
3454private:
3455
3456public:
3457 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
3458 CommandObjectParsed (interpreter,
3459 "process plugin packet send",
3460 "Send a custom packet through the GDB remote protocol and print the answer. "
3461 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
3462 NULL)
3463 {
3464 }
3465
3466 ~CommandObjectProcessGDBRemotePacketSend ()
3467 {
3468 }
3469
3470 bool
3471 DoExecute (Args& command, CommandReturnObject &result)
3472 {
3473 const size_t argc = command.GetArgumentCount();
3474 if (argc == 0)
3475 {
3476 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
3477 result.SetStatus (eReturnStatusFailed);
3478 return false;
3479 }
3480
3481 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3482 if (process)
3483 {
Han Ming Ong84145852012-11-26 20:42:03 +00003484 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00003485 {
Han Ming Ong84145852012-11-26 20:42:03 +00003486 const char *packet_cstr = command.GetArgumentAtIndex(0);
3487 bool send_async = true;
3488 StringExtractorGDBRemote response;
3489 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3490 result.SetStatus (eReturnStatusSuccessFinishResult);
3491 Stream &output_strm = result.GetOutputStream();
3492 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00003493 std::string &response_str = response.GetStringRef();
3494
Han Ming Ong399289e2013-06-21 19:56:59 +00003495 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00003496 {
3497 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
3498 }
3499
Han Ming Ong84145852012-11-26 20:42:03 +00003500 if (response_str.empty())
3501 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3502 else
3503 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00003504 }
Greg Clayton02686b82012-10-15 22:42:16 +00003505 }
Greg Clayton998255b2012-10-13 02:07:45 +00003506 return true;
3507 }
3508};
3509
Greg Claytonba4a0a52013-02-01 23:03:47 +00003510class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
3511{
3512private:
3513
3514public:
3515 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
3516 CommandObjectRaw (interpreter,
3517 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00003518 "Send a qRcmd packet through the GDB remote protocol and print the response."
3519 "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 +00003520 NULL)
3521 {
3522 }
3523
3524 ~CommandObjectProcessGDBRemotePacketMonitor ()
3525 {
3526 }
3527
3528 bool
3529 DoExecute (const char *command, CommandReturnObject &result)
3530 {
3531 if (command == NULL || command[0] == '\0')
3532 {
3533 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
3534 result.SetStatus (eReturnStatusFailed);
3535 return false;
3536 }
3537
3538 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3539 if (process)
3540 {
3541 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00003542 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00003543 packet.PutBytesAsRawHex8(command, strlen(command));
3544 const char *packet_cstr = packet.GetString().c_str();
3545
3546 bool send_async = true;
3547 StringExtractorGDBRemote response;
3548 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3549 result.SetStatus (eReturnStatusSuccessFinishResult);
3550 Stream &output_strm = result.GetOutputStream();
3551 output_strm.Printf (" packet: %s\n", packet_cstr);
3552 const std::string &response_str = response.GetStringRef();
3553
3554 if (response_str.empty())
3555 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3556 else
3557 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
3558 }
3559 return true;
3560 }
3561};
3562
Greg Clayton02686b82012-10-15 22:42:16 +00003563class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
3564{
3565private:
3566
3567public:
3568 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
3569 CommandObjectMultiword (interpreter,
3570 "process plugin packet",
3571 "Commands that deal with GDB remote packets.",
3572 NULL)
3573 {
3574 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
3575 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00003576 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Jason Molenda6076bf42014-05-06 04:34:52 +00003577 LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00003578 }
3579
3580 ~CommandObjectProcessGDBRemotePacket ()
3581 {
3582 }
3583};
Greg Clayton998255b2012-10-13 02:07:45 +00003584
3585class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
3586{
3587public:
3588 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
3589 CommandObjectMultiword (interpreter,
3590 "process plugin",
3591 "A set of commands for operating on a ProcessGDBRemote process.",
3592 "process plugin <subcommand> [<subcommand-options>]")
3593 {
3594 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
3595 }
3596
3597 ~CommandObjectMultiwordProcessGDBRemote ()
3598 {
3599 }
3600};
3601
Greg Clayton998255b2012-10-13 02:07:45 +00003602CommandObject *
3603ProcessGDBRemote::GetPluginCommandObject()
3604{
3605 if (!m_command_sp)
3606 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
3607 return m_command_sp.get();
3608}