blob: 67dcfad5cf7529cdb4b9327da27a4381b69f1064 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- ProcessGDBRemote.cpp ------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Daniel Malea93a64302012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
Virgile Bellob2f1fb22013-08-23 12:44:05 +000011#include "lldb/Host/Config.h"
Daniel Malea93a64302012-12-05 00:20:57 +000012
Chris Lattner30fdc8d2010-06-08 16:52:24 +000013// C Includes
14#include <errno.h>
Stephen Wilsona78867b2011-03-25 18:16:28 +000015#include <stdlib.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000016#ifndef LLDB_DISABLE_POSIX
Sean Callanan224f6f52012-07-19 18:07:36 +000017#include <netinet/in.h>
Greg Clayton2a48f522011-05-14 01:50:35 +000018#include <sys/mman.h> // for mmap
Virgile Bellob2f1fb22013-08-23 12:44:05 +000019#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include <sys/stat.h>
Greg Clayton2a48f522011-05-14 01:50:35 +000021#include <sys/types.h>
Stephen Wilsondc916862011-03-30 00:12:40 +000022#include <time.h>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000023
24// C++ Includes
25#include <algorithm>
26#include <map>
27
28// Other libraries and framework includes
29
Johnny Chen01a67862011-10-14 00:42:25 +000030#include "lldb/Breakpoint/Watchpoint.h"
Jim Ingham40af72e2010-06-15 19:49:27 +000031#include "lldb/Interpreter/Args.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000032#include "lldb/Core/ArchSpec.h"
33#include "lldb/Core/Debugger.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000034#include "lldb/Host/ConnectionFileDescriptor.h"
Greg Clayton53239f02011-02-08 05:05:52 +000035#include "lldb/Host/FileSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000036#include "lldb/Core/Module.h"
Greg Clayton1f746072012-08-29 21:13:06 +000037#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000038#include "lldb/Core/PluginManager.h"
39#include "lldb/Core/State.h"
Greg Claytond451c1a2012-04-13 21:24:18 +000040#include "lldb/Core/StreamFile.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000041#include "lldb/Core/StreamString.h"
42#include "lldb/Core/Timer.h"
Greg Clayton70b57652011-05-15 01:25:55 +000043#include "lldb/Core/Value.h"
Zachary Turner39de3112014-09-09 20:54:56 +000044#include "lldb/Host/HostThread.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000045#include "lldb/Host/StringConvert.h"
Jason Molendad1fae142012-09-29 08:03:33 +000046#include "lldb/Host/Symbols.h"
Zachary Turner39de3112014-09-09 20:54:56 +000047#include "lldb/Host/ThreadLauncher.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000048#include "lldb/Host/TimeValue.h"
Greg Clayton02686b82012-10-15 22:42:16 +000049#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton1d19a2f2012-10-19 22:22:57 +000050#include "lldb/Interpreter/CommandObject.h"
51#include "lldb/Interpreter/CommandObjectMultiword.h"
Greg Clayton02686b82012-10-15 22:42:16 +000052#include "lldb/Interpreter/CommandReturnObject.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000053#include "lldb/Interpreter/OptionValueProperties.h"
54#include "lldb/Interpreter/Property.h"
Joerg Sonnenbergere77b0422013-10-20 17:36:05 +000055#ifndef LLDB_DISABLE_PYTHON
Greg Claytonef8180a2013-10-15 00:14:28 +000056#include "lldb/Interpreter/PythonDataObjects.h"
Joerg Sonnenbergere77b0422013-10-20 17:36:05 +000057#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000058#include "lldb/Symbol/ObjectFile.h"
59#include "lldb/Target/DynamicLoader.h"
60#include "lldb/Target/Target.h"
61#include "lldb/Target/TargetList.h"
Greg Clayton2a48f522011-05-14 01:50:35 +000062#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molenda705b1802014-06-13 02:37:02 +000063#include "lldb/Target/SystemRuntime.h"
Jason Molendaa34a0c62010-06-09 21:28:42 +000064#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000065
66// Project includes
67#include "lldb/Host/Host.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000068#include "Plugins/Process/Utility/FreeBSDSignals.h"
Peter Collingbourne99f9aa02011-06-03 20:40:38 +000069#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000070#include "Plugins/Process/Utility/LinuxSignals.h"
Jason Molendac42d2432012-07-25 03:40:06 +000071#include "Plugins/Process/Utility/StopInfoMachException.h"
Jim Ingham43c555d2012-07-04 00:35:43 +000072#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
Greg Claytonc982c762010-07-09 20:39:50 +000073#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000074#include "GDBRemoteRegisterContext.h"
75#include "ProcessGDBRemote.h"
76#include "ProcessGDBRemoteLog.h"
77#include "ThreadGDBRemote.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000078
Jason Molenda5e8534e2012-10-03 01:29:34 +000079
Greg Claytonc1422c12012-04-09 22:46:21 +000080namespace lldb
81{
82 // Provide a function that can easily dump the packet history if we know a
83 // ProcessGDBRemote * value (which we can get from logs or from debugging).
84 // We need the function in the lldb namespace so it makes it into the final
85 // executable since the LLDB shared library only exports stuff in the lldb
86 // namespace. This allows you to attach with a debugger and call this
87 // function and get the packet history dumped to a file.
88 void
89 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
90 {
Greg Claytond451c1a2012-04-13 21:24:18 +000091 lldb_private::StreamFile strm;
92 lldb_private::Error error (strm.GetFile().Open(path, lldb_private::File::eOpenOptionWrite | lldb_private::File::eOpenOptionCanCreate));
93 if (error.Success())
94 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
Greg Claytonc1422c12012-04-09 22:46:21 +000095 }
Filipe Cabecinhasc34f7762012-05-23 16:27:09 +000096}
Chris Lattner30fdc8d2010-06-08 16:52:24 +000097
Chris Lattner30fdc8d2010-06-08 16:52:24 +000098#define DEBUGSERVER_BASENAME "debugserver"
99using namespace lldb;
100using namespace lldb_private;
101
Greg Clayton7f982402013-07-15 22:54:20 +0000102
103namespace {
Steve Pucci5ec012d2014-01-16 22:18:14 +0000104
Greg Clayton7f982402013-07-15 22:54:20 +0000105 static PropertyDefinition
106 g_properties[] =
107 {
108 { "packet-timeout" , OptionValue::eTypeUInt64 , true , 1, NULL, NULL, "Specify the default packet timeout in seconds." },
Greg Claytonef8180a2013-10-15 00:14:28 +0000109 { "target-definition-file" , OptionValue::eTypeFileSpec , true, 0 , NULL, NULL, "The file that provides the description for remote target registers." },
Greg Clayton7f982402013-07-15 22:54:20 +0000110 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
111 };
112
113 enum
114 {
Greg Claytonef8180a2013-10-15 00:14:28 +0000115 ePropertyPacketTimeout,
116 ePropertyTargetDefinitionFile
Greg Clayton7f982402013-07-15 22:54:20 +0000117 };
118
119 class PluginProperties : public Properties
120 {
121 public:
122
123 static ConstString
124 GetSettingName ()
125 {
126 return ProcessGDBRemote::GetPluginNameStatic();
127 }
128
129 PluginProperties() :
130 Properties ()
131 {
132 m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
133 m_collection_sp->Initialize(g_properties);
134 }
135
136 virtual
137 ~PluginProperties()
138 {
139 }
140
141 uint64_t
142 GetPacketTimeout()
143 {
144 const uint32_t idx = ePropertyPacketTimeout;
145 return m_collection_sp->GetPropertyAtIndexAsUInt64(NULL, idx, g_properties[idx].default_uint_value);
146 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000147
148 bool
149 SetPacketTimeout(uint64_t timeout)
150 {
151 const uint32_t idx = ePropertyPacketTimeout;
152 return m_collection_sp->SetPropertyAtIndexAsUInt64(NULL, idx, timeout);
153 }
154
Greg Claytonef8180a2013-10-15 00:14:28 +0000155 FileSpec
156 GetTargetDefinitionFile () const
157 {
158 const uint32_t idx = ePropertyTargetDefinitionFile;
159 return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
160 }
Greg Clayton7f982402013-07-15 22:54:20 +0000161 };
162
163 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
164
165 static const ProcessKDPPropertiesSP &
166 GetGlobalPluginProperties()
167 {
168 static ProcessKDPPropertiesSP g_settings_sp;
169 if (!g_settings_sp)
170 g_settings_sp.reset (new PluginProperties ());
171 return g_settings_sp;
172 }
173
174} // anonymous namespace end
175
Greg Claytonfda4fab2014-01-10 22:24:11 +0000176// TODO Randomly assigning a port is unsafe. We should get an unused
177// ephemeral port from the kernel and make sure we reserve it before passing
178// it to debugserver.
179
180#if defined (__APPLE__)
181#define LOW_PORT (IPPORT_RESERVED)
182#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
183#else
184#define LOW_PORT (1024u)
185#define HIGH_PORT (49151u)
186#endif
187
Todd Fiala013434e2014-07-09 01:29:05 +0000188#if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000189static bool rand_initialized = false;
190
Greg Claytonfda4fab2014-01-10 22:24:11 +0000191static inline uint16_t
192get_random_port ()
193{
194 if (!rand_initialized)
195 {
196 time_t seed = time(NULL);
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000197
Greg Claytonfda4fab2014-01-10 22:24:11 +0000198 rand_initialized = true;
199 srand(seed);
200 }
201 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
202}
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000203#endif
Greg Claytonfda4fab2014-01-10 22:24:11 +0000204
Greg Clayton57abc5d2013-05-10 21:47:16 +0000205lldb_private::ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000206ProcessGDBRemote::GetPluginNameStatic()
207{
Greg Clayton57abc5d2013-05-10 21:47:16 +0000208 static ConstString g_name("gdb-remote");
209 return g_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000210}
211
212const char *
213ProcessGDBRemote::GetPluginDescriptionStatic()
214{
215 return "GDB Remote protocol based debugging plug-in.";
216}
217
218void
219ProcessGDBRemote::Terminate()
220{
221 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
222}
223
224
Greg Claytonc3776bf2012-02-09 06:16:32 +0000225lldb::ProcessSP
226ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000227{
Greg Claytonc3776bf2012-02-09 06:16:32 +0000228 lldb::ProcessSP process_sp;
229 if (crash_file_path == NULL)
230 process_sp.reset (new ProcessGDBRemote (target, listener));
231 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000232}
233
234bool
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000235ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000236{
Greg Clayton596ed242011-10-21 21:41:45 +0000237 if (plugin_specified_by_name)
238 return true;
239
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000240 // For now we are just making sure the file exists for a given module
Greg Claytonaa149cb2011-08-11 02:48:45 +0000241 Module *exe_module = target.GetExecutableModulePointer();
242 if (exe_module)
Greg Claytonc3776bf2012-02-09 06:16:32 +0000243 {
244 ObjectFile *exe_objfile = exe_module->GetObjectFile();
245 // We can't debug core files...
246 switch (exe_objfile->GetType())
247 {
248 case ObjectFile::eTypeInvalid:
249 case ObjectFile::eTypeCoreFile:
250 case ObjectFile::eTypeDebugInfo:
251 case ObjectFile::eTypeObjectFile:
252 case ObjectFile::eTypeSharedLibrary:
253 case ObjectFile::eTypeStubLibrary:
Greg Clayton23f8c952014-03-24 23:10:19 +0000254 case ObjectFile::eTypeJIT:
Greg Claytonc3776bf2012-02-09 06:16:32 +0000255 return false;
256 case ObjectFile::eTypeExecutable:
257 case ObjectFile::eTypeDynamicLinker:
258 case ObjectFile::eTypeUnknown:
259 break;
260 }
Greg Claytonaa149cb2011-08-11 02:48:45 +0000261 return exe_module->GetFileSpec().Exists();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000262 }
Jim Ingham5aee1622010-08-09 23:31:02 +0000263 // However, if there is no executable module, we return true since we might be preparing to attach.
264 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000265}
266
267//----------------------------------------------------------------------
268// ProcessGDBRemote constructor
269//----------------------------------------------------------------------
270ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
271 Process (target, listener),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000272 m_flags (0),
Tamas Berghammere13c2732015-02-11 10:29:30 +0000273 m_gdb_comm (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000274 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Claytonc982c762010-07-09 20:39:50 +0000275 m_last_stop_packet (),
Greg Clayton09c3e3d2011-12-06 04:51:14 +0000276 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000277 m_register_info (),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000278 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
Jim Ingham455fa5c2012-11-01 01:15:33 +0000279 m_async_thread_state_mutex(Mutex::eMutexTypeRecursive),
Greg Clayton9e920902012-04-10 02:25:43 +0000280 m_thread_ids (),
Greg Clayton71fc2a32011-02-12 06:28:37 +0000281 m_continue_c_tids (),
282 m_continue_C_tids (),
283 m_continue_s_tids (),
284 m_continue_S_tids (),
Jason Molenda6076bf42014-05-06 04:34:52 +0000285 m_max_memory_size (0),
286 m_remote_stub_max_memory_size (0),
Greg Clayton4116e932012-05-15 02:33:01 +0000287 m_addr_to_mmap_size (),
288 m_thread_create_bp_sp (),
Jim Ingham43c555d2012-07-04 00:35:43 +0000289 m_waiting_for_attach (false),
Jason Molenda5e8534e2012-10-03 01:29:34 +0000290 m_destroy_tried_resuming (false),
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000291 m_command_sp (),
Todd Fiala4ceced32014-08-29 17:35:57 +0000292 m_breakpoint_pc_offset (0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000293{
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000294 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
295 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Inghamb1e2e842012-04-12 18:49:31 +0000296 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Greg Clayton7f982402013-07-15 22:54:20 +0000297 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
298 if (timeout_seconds > 0)
299 m_gdb_comm.SetPacketTimeout(timeout_seconds);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000300}
301
302//----------------------------------------------------------------------
303// Destructor
304//----------------------------------------------------------------------
305ProcessGDBRemote::~ProcessGDBRemote()
306{
307 // m_mach_process.UnregisterNotificationCallbacks (this);
308 Clear();
Greg Clayton1ed54f52011-10-01 00:45:15 +0000309 // We need to call finalize on the process before destroying ourselves
310 // to make sure all of the broadcaster cleanup goes as planned. If we
311 // destruct this class, then Process::~Process() might have problems
312 // trying to fully destroy the broadcaster.
313 Finalize();
Jim Ingham455fa5c2012-11-01 01:15:33 +0000314
315 // The general Finalize is going to try to destroy the process and that SHOULD
316 // shut down the async thread. However, if we don't kill it it will get stranded and
317 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
318 StopAsyncThread();
319 KillDebugserverProcess();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000320}
321
322//----------------------------------------------------------------------
323// PluginInterface
324//----------------------------------------------------------------------
Greg Clayton57abc5d2013-05-10 21:47:16 +0000325ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000326ProcessGDBRemote::GetPluginName()
327{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000328 return GetPluginNameStatic();
329}
330
331uint32_t
332ProcessGDBRemote::GetPluginVersion()
333{
334 return 1;
335}
336
Greg Claytonef8180a2013-10-15 00:14:28 +0000337bool
338ProcessGDBRemote::ParsePythonTargetDefinition(const FileSpec &target_definition_fspec)
339{
Joerg Sonnenbergere77b0422013-10-20 17:36:05 +0000340#ifndef LLDB_DISABLE_PYTHON
Greg Claytonef8180a2013-10-15 00:14:28 +0000341 ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
342 Error error;
343 lldb::ScriptInterpreterObjectSP module_object_sp (interpreter->LoadPluginModule(target_definition_fspec, error));
344 if (module_object_sp)
345 {
346 lldb::ScriptInterpreterObjectSP target_definition_sp (interpreter->GetDynamicSettings(module_object_sp,
347 &GetTarget(),
348 "gdb-server-target-definition",
349 error));
350
351 PythonDictionary target_dict(target_definition_sp);
352
353 if (target_dict)
354 {
Greg Clayton312bcbe2013-10-17 01:10:23 +0000355 PythonDictionary host_info_dict (target_dict.GetItemForKey("host-info"));
356 if (host_info_dict)
357 {
358 ArchSpec host_arch (host_info_dict.GetItemForKeyAsString(PythonString("triple")));
359
360 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture()))
361 {
362 GetTarget().SetArchitecture(host_arch);
363 }
364
365 }
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000366 m_breakpoint_pc_offset = target_dict.GetItemForKeyAsInteger("breakpoint-pc-offset", 0);
367
Greg Clayton312bcbe2013-10-17 01:10:23 +0000368 if (m_register_info.SetRegisterInfo (target_dict, GetTarget().GetArchitecture().GetByteOrder()) > 0)
Greg Claytonef8180a2013-10-15 00:14:28 +0000369 {
370 return true;
371 }
372 }
373 }
Joerg Sonnenbergere77b0422013-10-20 17:36:05 +0000374#endif
Greg Claytonef8180a2013-10-15 00:14:28 +0000375 return false;
376}
377
378
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000379void
Greg Clayton513c26c2011-01-29 07:10:55 +0000380ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000381{
Greg Clayton513c26c2011-01-29 07:10:55 +0000382 if (!force && m_register_info.GetNumRegisters() > 0)
383 return;
384
385 char packet[128];
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000386 m_register_info.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000387 uint32_t reg_offset = 0;
388 uint32_t reg_num = 0;
Greg Clayton23f59502012-07-17 03:23:13 +0000389 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Greg Clayton576d8832011-03-22 04:00:09 +0000390 response_type == StringExtractorGDBRemote::eResponse;
391 ++reg_num)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000392 {
Greg Clayton513c26c2011-01-29 07:10:55 +0000393 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
Andy Gibbsa297a972013-06-19 19:04:53 +0000394 assert (packet_len < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000395 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000396 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000397 {
Greg Clayton576d8832011-03-22 04:00:09 +0000398 response_type = response.GetResponseType();
399 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000400 {
401 std::string name;
402 std::string value;
403 ConstString reg_name;
404 ConstString alt_name;
405 ConstString set_name;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000406 std::vector<uint32_t> value_regs;
407 std::vector<uint32_t> invalidate_regs;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000408 RegisterInfo reg_info = { NULL, // Name
409 NULL, // Alt name
410 0, // byte size
411 reg_offset, // offset
412 eEncodingUint, // encoding
413 eFormatHex, // formate
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000414 {
415 LLDB_INVALID_REGNUM, // GCC reg num
416 LLDB_INVALID_REGNUM, // DWARF reg num
417 LLDB_INVALID_REGNUM, // generic reg num
Jason Molendafbcb7f22010-09-10 07:49:16 +0000418 reg_num, // GDB reg num
419 reg_num // native register number
Greg Clayton435d85a2012-02-29 19:27:27 +0000420 },
421 NULL,
422 NULL
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000423 };
424
425 while (response.GetNameColonValue(name, value))
426 {
427 if (name.compare("name") == 0)
428 {
429 reg_name.SetCString(value.c_str());
430 }
431 else if (name.compare("alt-name") == 0)
432 {
433 alt_name.SetCString(value.c_str());
434 }
435 else if (name.compare("bitsize") == 0)
436 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000437 reg_info.byte_size = StringConvert::ToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000438 }
439 else if (name.compare("offset") == 0)
440 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000441 uint32_t offset = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda743e86a2010-06-11 23:44:18 +0000442 if (reg_offset != offset)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000443 {
444 reg_offset = offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000445 }
446 }
447 else if (name.compare("encoding") == 0)
448 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000449 const Encoding encoding = Args::StringToEncoding (value.c_str());
450 if (encoding != eEncodingInvalid)
451 reg_info.encoding = encoding;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000452 }
453 else if (name.compare("format") == 0)
454 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000455 Format format = eFormatInvalid;
456 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
457 reg_info.format = format;
458 else if (value.compare("binary") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000459 reg_info.format = eFormatBinary;
460 else if (value.compare("decimal") == 0)
461 reg_info.format = eFormatDecimal;
462 else if (value.compare("hex") == 0)
463 reg_info.format = eFormatHex;
464 else if (value.compare("float") == 0)
465 reg_info.format = eFormatFloat;
466 else if (value.compare("vector-sint8") == 0)
467 reg_info.format = eFormatVectorOfSInt8;
468 else if (value.compare("vector-uint8") == 0)
469 reg_info.format = eFormatVectorOfUInt8;
470 else if (value.compare("vector-sint16") == 0)
471 reg_info.format = eFormatVectorOfSInt16;
472 else if (value.compare("vector-uint16") == 0)
473 reg_info.format = eFormatVectorOfUInt16;
474 else if (value.compare("vector-sint32") == 0)
475 reg_info.format = eFormatVectorOfSInt32;
476 else if (value.compare("vector-uint32") == 0)
477 reg_info.format = eFormatVectorOfUInt32;
478 else if (value.compare("vector-float32") == 0)
479 reg_info.format = eFormatVectorOfFloat32;
480 else if (value.compare("vector-uint128") == 0)
481 reg_info.format = eFormatVectorOfUInt128;
482 }
483 else if (name.compare("set") == 0)
484 {
485 set_name.SetCString(value.c_str());
486 }
487 else if (name.compare("gcc") == 0)
488 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000489 reg_info.kinds[eRegisterKindGCC] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000490 }
491 else if (name.compare("dwarf") == 0)
492 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000493 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000494 }
495 else if (name.compare("generic") == 0)
496 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000497 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000498 }
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000499 else if (name.compare("container-regs") == 0)
500 {
501 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
502 value_pair.second = value;
503 do
504 {
505 value_pair = value_pair.second.split(',');
506 if (!value_pair.first.empty())
507 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000508 uint32_t reg = StringConvert::ToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
Greg Clayton0ba20242013-01-21 23:32:42 +0000509 if (reg != LLDB_INVALID_REGNUM)
510 value_regs.push_back (reg);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000511 }
512 } while (!value_pair.second.empty());
513 }
514 else if (name.compare("invalidate-regs") == 0)
515 {
516 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
517 value_pair.second = value;
518 do
519 {
520 value_pair = value_pair.second.split(',');
521 if (!value_pair.first.empty())
522 {
Vince Harron5275aaa2015-01-15 20:08:35 +0000523 uint32_t reg = StringConvert::ToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
Greg Clayton0ba20242013-01-21 23:32:42 +0000524 if (reg != LLDB_INVALID_REGNUM)
525 invalidate_regs.push_back (reg);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000526 }
527 } while (!value_pair.second.empty());
528 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000529 }
530
Jason Molenda743e86a2010-06-11 23:44:18 +0000531 reg_info.byte_offset = reg_offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000532 assert (reg_info.byte_size != 0);
533 reg_offset += reg_info.byte_size;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000534 if (!value_regs.empty())
535 {
536 value_regs.push_back(LLDB_INVALID_REGNUM);
537 reg_info.value_regs = value_regs.data();
538 }
539 if (!invalidate_regs.empty())
540 {
541 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
542 reg_info.invalidate_regs = invalidate_regs.data();
543 }
544
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000545 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
546 }
Todd Fiala1a634402014-01-08 07:52:40 +0000547 else
548 {
549 break; // ensure exit before reg_num is incremented
550 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000551 }
552 else
553 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000554 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000555 }
556 }
557
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000558 // Check if qHostInfo specified a specific packet timeout for this connection.
559 // If so then lets update our setting so the user knows what the timeout is
560 // and can see it.
561 const uint32_t host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
562 if (host_packet_timeout)
563 {
564 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout);
565 }
566
567
Greg Claytonef8180a2013-10-15 00:14:28 +0000568 if (reg_num == 0)
569 {
570 FileSpec target_definition_fspec = GetGlobalPluginProperties()->GetTargetDefinitionFile ();
Greg Clayton312bcbe2013-10-17 01:10:23 +0000571
572 if (target_definition_fspec)
Greg Claytonef8180a2013-10-15 00:14:28 +0000573 {
Greg Clayton312bcbe2013-10-17 01:10:23 +0000574 // See if we can get register definitions from a python file
575 if (ParsePythonTargetDefinition (target_definition_fspec))
576 return;
Greg Claytonef8180a2013-10-15 00:14:28 +0000577 }
578 }
579
Johnny Chen2fa9de12012-05-14 18:44:23 +0000580 // We didn't get anything if the accumulated reg_num is zero. See if we are
581 // debugging ARM and fill with a hard coded register set until we can get an
582 // updated debugserver down on the devices.
583 // On the other hand, if the accumulated reg_num is positive, see if we can
584 // add composite registers to the existing primordial ones.
585 bool from_scratch = (reg_num == 0);
586
587 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000588 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
589 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
590
591 // Use the process' architecture instead of the host arch, if available
592 ArchSpec remote_arch;
593 if (remote_process_arch.IsValid ())
594 remote_arch = remote_process_arch;
595 else
596 remote_arch = remote_host_arch;
597
Johnny Chen2fa9de12012-05-14 18:44:23 +0000598 if (!target_arch.IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000599 {
Johnny Chen2fa9de12012-05-14 18:44:23 +0000600 if (remote_arch.IsValid()
601 && remote_arch.GetMachine() == llvm::Triple::arm
602 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
603 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000604 }
Johnny Chen2fa9de12012-05-14 18:44:23 +0000605 else if (target_arch.GetMachine() == llvm::Triple::arm)
606 {
607 m_register_info.HardcodeARMRegisters(from_scratch);
608 }
609
610 // At this point, we can finalize our register info.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000611 m_register_info.Finalize ();
612}
613
614Error
615ProcessGDBRemote::WillLaunch (Module* module)
616{
617 return WillLaunchOrAttach ();
618}
619
620Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000621ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000622{
623 return WillLaunchOrAttach ();
624}
625
626Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000627ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000628{
629 return WillLaunchOrAttach ();
630}
631
632Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000633ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +0000634{
Todd Fialaaf245d12014-06-30 21:05:18 +0000635 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Claytonb766a732011-02-04 01:58:07 +0000636 Error error (WillLaunchOrAttach ());
637
638 if (error.Fail())
639 return error;
640
Greg Clayton2289fa42011-04-30 01:09:13 +0000641 error = ConnectToDebugserver (remote_url);
Greg Claytonb766a732011-02-04 01:58:07 +0000642
643 if (error.Fail())
644 return error;
645 StartAsyncThread ();
646
Greg Claytonc574ede2011-03-10 02:26:48 +0000647 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonb766a732011-02-04 01:58:07 +0000648 if (pid == LLDB_INVALID_PROCESS_ID)
649 {
650 // We don't have a valid process ID, so note that we are connected
651 // and could now request to launch or attach, or get remote process
652 // listings...
653 SetPrivateState (eStateConnected);
654 }
655 else
656 {
657 // We have a valid process
658 SetID (pid);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000659 GetThreadList();
Greg Clayton3dedae12013-12-06 21:45:27 +0000660 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false) == GDBRemoteCommunication::PacketResult::Success)
Greg Claytonb766a732011-02-04 01:58:07 +0000661 {
Jason Molendac62bd7b2013-12-21 05:20:36 +0000662 if (!m_target.GetArchitecture().IsValid())
663 {
664 if (m_gdb_comm.GetProcessArchitecture().IsValid())
665 {
666 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
667 }
668 else
669 {
670 m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
671 }
Carlo Kok74389122013-10-14 07:09:13 +0000672 }
673
Greg Claytondd0e5a52011-06-02 22:22:38 +0000674 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytonb766a732011-02-04 01:58:07 +0000675 if (state == eStateStopped)
676 {
677 SetPrivateState (state);
678 }
679 else
Daniel Malead01b2952012-11-29 21:49:15 +0000680 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 +0000681 }
682 else
Daniel Malead01b2952012-11-29 21:49:15 +0000683 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 +0000684 }
Jason Molenda16d127c2012-05-03 22:37:30 +0000685
Todd Fialaaf245d12014-06-30 21:05:18 +0000686 if (log)
687 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");
688
689
690 if (error.Success()
Jason Molenda16d127c2012-05-03 22:37:30 +0000691 && !GetTarget().GetArchitecture().IsValid()
692 && m_gdb_comm.GetHostArchitecture().IsValid())
693 {
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000694 // Prefer the *process'* architecture over that of the *host*, if available.
695 if (m_gdb_comm.GetProcessArchitecture().IsValid())
696 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
697 else
698 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molenda16d127c2012-05-03 22:37:30 +0000699 }
700
Todd Fialaaf245d12014-06-30 21:05:18 +0000701 if (log)
702 log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": normalized target architecture triple: %s", __FUNCTION__, GetID (), GetTarget ().GetArchitecture ().GetTriple ().getTriple ().c_str ());
703
704 // Set the Unix signals properly for the target.
705 // FIXME Add a gdb-remote packet to discover dynamically.
706 if (error.Success ())
707 {
Tamas Berghammerac839822015-03-04 11:34:10 +0000708 const ArchSpec arch_spec = m_gdb_comm.GetHostArchitecture();
Todd Fialaaf245d12014-06-30 21:05:18 +0000709 if (arch_spec.IsValid ())
710 {
711 if (log)
712 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 ());
713
714 switch (arch_spec.GetTriple ().getOS ())
715 {
716 case llvm::Triple::Linux:
Todd Fiala4ceced32014-08-29 17:35:57 +0000717 SetUnixSignals (UnixSignalsSP (new process_linux::LinuxSignals ()));
Todd Fialaaf245d12014-06-30 21:05:18 +0000718 if (log)
719 log->Printf ("ProcessGDBRemote::%s using Linux unix signals type for pid %" PRIu64, __FUNCTION__, GetID ());
720 break;
721 case llvm::Triple::OpenBSD:
722 case llvm::Triple::FreeBSD:
723 case llvm::Triple::NetBSD:
Todd Fiala4ceced32014-08-29 17:35:57 +0000724 SetUnixSignals (UnixSignalsSP (new FreeBSDSignals ()));
Todd Fialaaf245d12014-06-30 21:05:18 +0000725 if (log)
726 log->Printf ("ProcessGDBRemote::%s using *BSD unix signals type for pid %" PRIu64, __FUNCTION__, GetID ());
727 break;
728 default:
Todd Fiala4ceced32014-08-29 17:35:57 +0000729 SetUnixSignals (UnixSignalsSP (new UnixSignals ()));
Todd Fialaaf245d12014-06-30 21:05:18 +0000730 if (log)
731 log->Printf ("ProcessGDBRemote::%s using generic unix signals type for pid %" PRIu64, __FUNCTION__, GetID ());
732 break;
733 }
734 }
735 }
736
Greg Claytonb766a732011-02-04 01:58:07 +0000737 return error;
738}
739
740Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000741ProcessGDBRemote::WillLaunchOrAttach ()
742{
743 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000744 m_stdio_communication.Clear ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000745 return error;
746}
747
748//----------------------------------------------------------------------
749// Process Control
750//----------------------------------------------------------------------
751Error
Jean-Daniel Dupas7782de92013-12-09 22:52:50 +0000752ProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000753{
Todd Fiala75f47c32014-10-11 21:42:09 +0000754 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton4957bf62010-09-30 21:49:03 +0000755 Error error;
Greg Clayton982c9762011-11-03 21:22:33 +0000756
Todd Fiala75f47c32014-10-11 21:42:09 +0000757 if (log)
758 log->Printf ("ProcessGDBRemote::%s() entered", __FUNCTION__);
759
Greg Clayton982c9762011-11-03 21:22:33 +0000760 uint32_t launch_flags = launch_info.GetFlags().Get();
761 const char *stdin_path = NULL;
762 const char *stdout_path = NULL;
763 const char *stderr_path = NULL;
764 const char *working_dir = launch_info.GetWorkingDirectory();
765
Zachary Turner696b5282014-08-14 16:01:25 +0000766 const FileAction *file_action;
Greg Clayton982c9762011-11-03 21:22:33 +0000767 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
768 if (file_action)
769 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000770 if (file_action->GetAction() == FileAction::eFileActionOpen)
Greg Clayton982c9762011-11-03 21:22:33 +0000771 stdin_path = file_action->GetPath();
772 }
773 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
774 if (file_action)
775 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000776 if (file_action->GetAction() == FileAction::eFileActionOpen)
Greg Clayton982c9762011-11-03 21:22:33 +0000777 stdout_path = file_action->GetPath();
778 }
779 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
780 if (file_action)
781 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000782 if (file_action->GetAction() == FileAction::eFileActionOpen)
Greg Clayton982c9762011-11-03 21:22:33 +0000783 stderr_path = file_action->GetPath();
784 }
785
Todd Fiala75f47c32014-10-11 21:42:09 +0000786 if (log)
787 {
788 if (stdin_path || stdout_path || stderr_path)
Vince Harron4a8abd32015-02-13 19:15:24 +0000789 log->Printf ("ProcessGDBRemote::%s provided with STDIO paths via launch_info: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000790 __FUNCTION__,
791 stdin_path ? stdin_path : "<null>",
792 stdout_path ? stdout_path : "<null>",
793 stderr_path ? stderr_path : "<null>");
794 else
795 log->Printf ("ProcessGDBRemote::%s no STDIO paths given via launch_info", __FUNCTION__);
796 }
797
Vince Harrondf3f00f2015-02-10 21:09:04 +0000798 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
799 if (stdin_path || disable_stdio)
800 {
801 // the inferior will be reading stdin from the specified file
802 // or stdio is completely disabled
803 m_stdin_forward = false;
804 }
805 else
806 {
807 m_stdin_forward = true;
808 }
809
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000810 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
811 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
812 // ::LogSetLogFile ("/dev/stdout");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000813
Greg Clayton982c9762011-11-03 21:22:33 +0000814 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000815 if (object_file)
816 {
Greg Clayton71337622011-02-24 22:24:29 +0000817 // Make sure we aren't already connected?
818 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000819 {
Greg Clayton91a9b2472013-12-04 19:19:12 +0000820 error = LaunchAndConnectToDebugserver (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000821 }
822
823 if (error.Success())
824 {
825 lldb_utility::PseudoTerminal pty;
826 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000827
Greg Claytonf58c2692011-06-24 22:32:10 +0000828 PlatformSP platform_sp (m_target.GetPlatform());
Vince Harrondf3f00f2015-02-10 21:09:04 +0000829 if (disable_stdio)
Greg Clayton71337622011-02-24 22:24:29 +0000830 {
Vince Harrondf3f00f2015-02-10 21:09:04 +0000831 // set to /dev/null unless redirected to a file above
832 if (!stdin_path)
833 stdin_path = "/dev/null";
834 if (!stdout_path)
835 stdout_path = "/dev/null";
836 if (!stderr_path)
837 stderr_path = "/dev/null";
838 }
839 else if (platform_sp && platform_sp->IsHost())
840 {
841 // If the debugserver is local and we aren't disabling STDIO, lets use
842 // a pseudo terminal to instead of relying on the 'O' packets for stdio
843 // since 'O' packets can really slow down debugging if the inferior
844 // does a lot of output.
Greg Clayton71337622011-02-24 22:24:29 +0000845 const char *slave_name = NULL;
846 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000847 {
Greg Clayton71337622011-02-24 22:24:29 +0000848 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
849 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000850 }
Greg Clayton71337622011-02-24 22:24:29 +0000851 if (stdin_path == NULL)
852 stdin_path = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000853
Greg Clayton71337622011-02-24 22:24:29 +0000854 if (stdout_path == NULL)
855 stdout_path = slave_name;
856
857 if (stderr_path == NULL)
858 stderr_path = slave_name;
Todd Fiala75f47c32014-10-11 21:42:09 +0000859
860 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +0000861 log->Printf ("ProcessGDBRemote::%s adjusted STDIO paths for local platform (IsHost() is true) using slave: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000862 __FUNCTION__,
863 stdin_path ? stdin_path : "<null>",
864 stdout_path ? stdout_path : "<null>",
865 stderr_path ? stderr_path : "<null>");
Greg Clayton71337622011-02-24 22:24:29 +0000866 }
867
Todd Fiala75f47c32014-10-11 21:42:09 +0000868 if (log)
Vince Harron4a8abd32015-02-13 19:15:24 +0000869 log->Printf ("ProcessGDBRemote::%s final STDIO paths after all adjustments: stdin=%s, stdout=%s, stderr=%s",
Todd Fiala75f47c32014-10-11 21:42:09 +0000870 __FUNCTION__,
871 stdin_path ? stdin_path : "<null>",
872 stdout_path ? stdout_path : "<null>",
873 stderr_path ? stderr_path : "<null>");
874
875 if (stdin_path)
Greg Clayton71337622011-02-24 22:24:29 +0000876 m_gdb_comm.SetSTDIN (stdin_path);
877 if (stdout_path)
878 m_gdb_comm.SetSTDOUT (stdout_path);
879 if (stderr_path)
880 m_gdb_comm.SetSTDERR (stderr_path);
881
882 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
Jim Ingham106d0282014-06-25 02:32:56 +0000883 m_gdb_comm.SetDetachOnError (launch_flags & eLaunchFlagDetachOnError);
Greg Clayton71337622011-02-24 22:24:29 +0000884
Greg Claytonc4103b32011-05-08 04:53:50 +0000885 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Clayton71337622011-02-24 22:24:29 +0000886
Jason Molendaa3329782014-03-29 18:54:20 +0000887 const char * launch_event_data = launch_info.GetLaunchEventData();
888 if (launch_event_data != NULL && *launch_event_data != '\0')
889 m_gdb_comm.SendLaunchEventDataPacket (launch_event_data);
890
Greg Clayton71337622011-02-24 22:24:29 +0000891 if (working_dir && working_dir[0])
892 {
893 m_gdb_comm.SetWorkingDir (working_dir);
894 }
895
896 // Send the environment and the program + arguments after we connect
Greg Clayton982c9762011-11-03 21:22:33 +0000897 const Args &environment = launch_info.GetEnvironmentEntries();
898 if (environment.GetArgumentCount())
Greg Clayton71337622011-02-24 22:24:29 +0000899 {
Greg Clayton982c9762011-11-03 21:22:33 +0000900 size_t num_environment_entries = environment.GetArgumentCount();
901 for (size_t i=0; i<num_environment_entries; ++i)
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000902 {
Greg Clayton982c9762011-11-03 21:22:33 +0000903 const char *env_entry = environment.GetArgumentAtIndex(i);
904 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Clayton71337622011-02-24 22:24:29 +0000905 break;
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000906 }
Greg Clayton71337622011-02-24 22:24:29 +0000907 }
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000908
Greg Clayton71337622011-02-24 22:24:29 +0000909 {
Tamas Berghammer912800c2015-02-24 10:23:39 +0000910 // Scope for the scoped timeout object
911 GDBRemoteCommunication::ScopedTimeout timeout (m_gdb_comm, 10);
912
913 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
914 if (arg_packet_err == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000915 {
Tamas Berghammer912800c2015-02-24 10:23:39 +0000916 std::string error_str;
917 if (m_gdb_comm.GetLaunchSuccess (error_str))
918 {
919 SetID (m_gdb_comm.GetCurrentProcessID ());
920 }
921 else
922 {
923 error.SetErrorString (error_str.c_str());
924 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000925 }
926 else
927 {
Tamas Berghammer912800c2015-02-24 10:23:39 +0000928 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000929 }
Greg Clayton71337622011-02-24 22:24:29 +0000930 }
Tamas Berghammer912800c2015-02-24 10:23:39 +0000931
Greg Clayton71337622011-02-24 22:24:29 +0000932 if (GetID() == LLDB_INVALID_PROCESS_ID)
933 {
Johnny Chen4c1e9202011-08-09 18:56:45 +0000934 if (log)
935 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton71337622011-02-24 22:24:29 +0000936 KillDebugserverProcess ();
937 return error;
938 }
939
Greg Clayton3dedae12013-12-06 21:45:27 +0000940 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton71337622011-02-24 22:24:29 +0000941 {
Jason Molendac62bd7b2013-12-21 05:20:36 +0000942 if (!m_target.GetArchitecture().IsValid())
943 {
944 if (m_gdb_comm.GetProcessArchitecture().IsValid())
945 {
946 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
947 }
948 else
949 {
950 m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
951 }
Carlo Kok74389122013-10-14 07:09:13 +0000952 }
953
Greg Claytondd0e5a52011-06-02 22:22:38 +0000954 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Clayton71337622011-02-24 22:24:29 +0000955
956 if (!disable_stdio)
957 {
958 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Claytonee95ed52011-11-17 22:14:31 +0000959 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Clayton71337622011-02-24 22:24:29 +0000960 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000961 }
962 }
Greg Claytonc235ac72011-08-09 05:20:29 +0000963 else
964 {
Johnny Chen4c1e9202011-08-09 18:56:45 +0000965 if (log)
966 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytonc235ac72011-08-09 05:20:29 +0000967 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000968 }
969 else
970 {
971 // Set our user ID to an invalid process ID.
972 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton982c9762011-11-03 21:22:33 +0000973 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
974 exe_module->GetFileSpec().GetFilename().AsCString(),
975 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000976 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000977 return error;
Greg Clayton4957bf62010-09-30 21:49:03 +0000978
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000979}
980
981
982Error
Greg Claytonb766a732011-02-04 01:58:07 +0000983ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000984{
985 Error error;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000986 // Only connect if we have a valid connect URL
Vince Harron1b5a74e2015-01-21 22:42:49 +0000987 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton00fe87b2013-12-05 22:58:22 +0000988
989 if (connect_url && connect_url[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000990 {
Vince Harron1b5a74e2015-01-21 22:42:49 +0000991 if (log)
992 log->Printf("ProcessGDBRemote::%s Connecting to %s", __FUNCTION__, connect_url);
Greg Clayton00fe87b2013-12-05 22:58:22 +0000993 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
994 if (conn_ap.get())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000995 {
Greg Clayton00fe87b2013-12-05 22:58:22 +0000996 const uint32_t max_retry_count = 50;
997 uint32_t retry_count = 0;
998 while (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000999 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001000 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
1001 {
1002 m_gdb_comm.SetConnection (conn_ap.release());
1003 break;
1004 }
1005 else if (error.WasInterrupted())
1006 {
1007 // If we were interrupted, don't keep retrying.
1008 break;
1009 }
1010
1011 retry_count++;
1012
1013 if (retry_count >= max_retry_count)
1014 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001015
Greg Clayton00fe87b2013-12-05 22:58:22 +00001016 usleep (100000);
1017 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001018 }
1019 }
1020
1021 if (!m_gdb_comm.IsConnected())
1022 {
1023 if (error.Success())
1024 error.SetErrorString("not connected to remote gdb server");
1025 return error;
1026 }
1027
Greg Clayton32e0a752011-03-30 18:16:51 +00001028 // We always seem to be able to open a connection to a local port
1029 // so we need to make sure we can then send data to it. If we can't
1030 // then we aren't actually connected to anything, so try and do the
1031 // handshake with the remote GDB server and make sure that goes
1032 // alright.
Greg Claytonfb909312013-11-23 01:58:15 +00001033 if (!m_gdb_comm.HandshakeWithServer (&error))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001034 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001035 m_gdb_comm.Disconnect();
1036 if (error.Success())
1037 error.SetErrorString("not connected to remote gdb server");
1038 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001039 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001040 m_gdb_comm.GetThreadSuffixSupported ();
Greg Clayton44633992012-04-10 03:22:03 +00001041 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001042 m_gdb_comm.GetHostInfo ();
1043 m_gdb_comm.GetVContSupported ('c');
Jim Inghamcd16df92012-07-20 21:37:13 +00001044 m_gdb_comm.GetVAttachOrWaitSupported();
Jim Ingham03afad82012-07-02 05:40:07 +00001045
1046 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1047 for (size_t idx = 0; idx < num_cmds; idx++)
1048 {
1049 StringExtractorGDBRemote response;
Jim Ingham03afad82012-07-02 05:40:07 +00001050 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1051 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001052 return error;
1053}
1054
1055void
Jim Inghambb006ce2014-08-02 00:33:35 +00001056ProcessGDBRemote::DidLaunchOrAttach (ArchSpec& process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001057{
Greg Clayton5160ce52013-03-27 23:08:40 +00001058 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001059 if (log)
1060 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton93d3c8332011-02-16 04:46:07 +00001061 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001062 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001063 BuildDynamicRegisterInfo (false);
Greg Clayton3af9ea52010-11-18 05:57:03 +00001064
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001065 // See if the GDB server supports the qHostInfo information
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001066
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001067
1068 // See if the GDB server supports the qProcessInfo packet, if so
1069 // prefer that over the Host information as it will be more specific
1070 // to our process.
1071
Todd Fiala75f47c32014-10-11 21:42:09 +00001072 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1073 if (remote_process_arch.IsValid())
1074 {
1075 process_arch = remote_process_arch;
1076 if (log)
1077 log->Printf ("ProcessGDBRemote::%s gdb-remote had process architecture, using %s %s",
1078 __FUNCTION__,
1079 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1080 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1081 }
Jim Inghambb006ce2014-08-02 00:33:35 +00001082 else
Todd Fiala75f47c32014-10-11 21:42:09 +00001083 {
Jim Inghambb006ce2014-08-02 00:33:35 +00001084 process_arch = m_gdb_comm.GetHostArchitecture();
Todd Fiala75f47c32014-10-11 21:42:09 +00001085 if (log)
1086 log->Printf ("ProcessGDBRemote::%s gdb-remote did not have process architecture, using gdb-remote host architecture %s %s",
1087 __FUNCTION__,
1088 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1089 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1090 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001091
Jim Inghambb006ce2014-08-02 00:33:35 +00001092 if (process_arch.IsValid())
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001093 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001094 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Greg Claytond314e812011-03-23 00:09:55 +00001095 if (target_arch.IsValid())
1096 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001097 if (log)
1098 log->Printf ("ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1099 __FUNCTION__,
1100 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1101 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
1102
1103 // If the remote host is ARM and we have apple as the vendor, then
Greg Claytond314e812011-03-23 00:09:55 +00001104 // ARM executables and shared libraries can have mixed ARM architectures.
1105 // You can have an armv6 executable, and if the host is armv7, then the
1106 // system will load the best possible architecture for all shared libraries
1107 // it has, so we really need to take the remote host architecture as our
1108 // defacto architecture in this case.
1109
Jim Inghambb006ce2014-08-02 00:33:35 +00001110 if (process_arch.GetMachine() == llvm::Triple::arm &&
1111 process_arch.GetTriple().getVendor() == llvm::Triple::Apple)
Greg Claytond314e812011-03-23 00:09:55 +00001112 {
Jason Molenda921c01b2014-08-03 21:42:52 +00001113 GetTarget().SetArchitecture (process_arch);
Todd Fiala75f47c32014-10-11 21:42:09 +00001114 if (log)
1115 log->Printf ("ProcessGDBRemote::%s remote process is ARM/Apple, setting target arch to %s %s",
1116 __FUNCTION__,
1117 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1118 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001119 }
1120 else
1121 {
1122 // Fill in what is missing in the triple
Jim Inghambb006ce2014-08-02 00:33:35 +00001123 const llvm::Triple &remote_triple = process_arch.GetTriple();
Tamas Berghammere724af12015-03-13 10:32:37 +00001124 llvm::Triple new_target_triple = target_arch.GetTriple();
1125 if (new_target_triple.getVendorName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001126 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001127 new_target_triple.setVendor (remote_triple.getVendor());
Greg Claytond314e812011-03-23 00:09:55 +00001128
Tamas Berghammere724af12015-03-13 10:32:37 +00001129 if (new_target_triple.getOSName().size() == 0)
Greg Clayton70b57652011-05-15 01:25:55 +00001130 {
Tamas Berghammere724af12015-03-13 10:32:37 +00001131 new_target_triple.setOS (remote_triple.getOS());
Greg Claytond314e812011-03-23 00:09:55 +00001132
Tamas Berghammere724af12015-03-13 10:32:37 +00001133 if (new_target_triple.getEnvironmentName().size() == 0)
1134 new_target_triple.setEnvironment (remote_triple.getEnvironment());
Greg Clayton70b57652011-05-15 01:25:55 +00001135 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001136
Tamas Berghammere724af12015-03-13 10:32:37 +00001137 ArchSpec new_target_arch = target_arch;
1138 new_target_arch.SetTriple(new_target_triple);
1139 GetTarget().SetArchitecture(new_target_arch);
1140 }
Greg Claytond314e812011-03-23 00:09:55 +00001141 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001142
1143 if (log)
1144 log->Printf ("ProcessGDBRemote::%s final target arch after adjustments for remote architecture: %s %s",
1145 __FUNCTION__,
1146 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1147 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
Greg Claytond314e812011-03-23 00:09:55 +00001148 }
1149 else
1150 {
1151 // The target doesn't have a valid architecture yet, set it from
1152 // the architecture we got from the remote GDB server
Jason Molenda921c01b2014-08-03 21:42:52 +00001153 GetTarget().SetArchitecture (process_arch);
Greg Claytond314e812011-03-23 00:09:55 +00001154 }
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001155 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001156 }
1157}
1158
1159void
1160ProcessGDBRemote::DidLaunch ()
1161{
Jim Inghambb006ce2014-08-02 00:33:35 +00001162 ArchSpec process_arch;
1163 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001164}
1165
1166Error
Greg Claytonc982c762010-07-09 20:39:50 +00001167ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001168{
Han Ming Ong84647042012-02-25 01:07:38 +00001169 ProcessAttachInfo attach_info;
1170 return DoAttachToProcessWithID(attach_pid, attach_info);
1171}
1172
1173Error
1174ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1175{
Todd Fiala75f47c32014-10-11 21:42:09 +00001176 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001177 Error error;
Todd Fiala75f47c32014-10-11 21:42:09 +00001178
1179 if (log)
1180 log->Printf ("ProcessGDBRemote::%s()", __FUNCTION__);
1181
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001182 // Clear out and clean up from any current state
1183 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001184 if (attach_pid != LLDB_INVALID_PROCESS_ID)
1185 {
Greg Clayton71337622011-02-24 22:24:29 +00001186 // Make sure we aren't already connected?
1187 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001188 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001189 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001190
1191 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001192 {
Greg Clayton71337622011-02-24 22:24:29 +00001193 const char *error_string = error.AsCString();
1194 if (error_string == NULL)
1195 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1196
1197 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001198 }
Greg Clayton71337622011-02-24 22:24:29 +00001199 }
1200
1201 if (error.Success())
1202 {
Jim Ingham106d0282014-06-25 02:32:56 +00001203 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
Todd Fiala75f47c32014-10-11 21:42:09 +00001204
Greg Clayton71337622011-02-24 22:24:29 +00001205 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001206 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Greg Clayton3b608422011-11-19 02:11:30 +00001207 SetID (attach_pid);
Greg Clayton71337622011-02-24 22:24:29 +00001208 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001209 }
1210 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001211
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001212 return error;
1213}
1214
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001215Error
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001216ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001217{
1218 Error error;
1219 // Clear out and clean up from any current state
1220 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001221
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001222 if (process_name && process_name[0])
1223 {
Greg Clayton71337622011-02-24 22:24:29 +00001224 // Make sure we aren't already connected?
1225 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001226 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001227 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001228
Greg Clayton71337622011-02-24 22:24:29 +00001229 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001230 {
Greg Clayton71337622011-02-24 22:24:29 +00001231 const char *error_string = error.AsCString();
1232 if (error_string == NULL)
1233 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001234
Greg Clayton71337622011-02-24 22:24:29 +00001235 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001236 }
Greg Clayton71337622011-02-24 22:24:29 +00001237 }
1238
1239 if (error.Success())
1240 {
1241 StreamString packet;
1242
Jim Ingham106d0282014-06-25 02:32:56 +00001243 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1244
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001245 if (attach_info.GetWaitForLaunch())
Jim Inghamcd16df92012-07-20 21:37:13 +00001246 {
1247 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1248 {
1249 packet.PutCString ("vAttachWait");
1250 }
1251 else
1252 {
1253 if (attach_info.GetIgnoreExisting())
1254 packet.PutCString("vAttachWait");
1255 else
1256 packet.PutCString ("vAttachOrWait");
1257 }
1258 }
Greg Clayton71337622011-02-24 22:24:29 +00001259 else
1260 packet.PutCString("vAttachName");
1261 packet.PutChar(';');
1262 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1263
1264 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1265
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001266 }
1267 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001268 return error;
1269}
1270
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001271
Greg Claytonfbb76342013-11-20 21:07:01 +00001272bool
1273ProcessGDBRemote::SetExitStatus (int exit_status, const char *cstr)
1274{
1275 m_gdb_comm.Disconnect();
1276 return Process::SetExitStatus (exit_status, cstr);
1277}
1278
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001279void
Jim Inghambb006ce2014-08-02 00:33:35 +00001280ProcessGDBRemote::DidAttach (ArchSpec &process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001281{
Jim Inghambb006ce2014-08-02 00:33:35 +00001282 // If you can figure out what the architecture is, fill it in here.
1283 process_arch.Clear();
1284 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001285}
1286
Greg Clayton90ba8112012-12-05 00:16:59 +00001287
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001288Error
1289ProcessGDBRemote::WillResume ()
1290{
Greg Clayton71fc2a32011-02-12 06:28:37 +00001291 m_continue_c_tids.clear();
1292 m_continue_C_tids.clear();
1293 m_continue_s_tids.clear();
1294 m_continue_S_tids.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001295 return Error();
1296}
1297
1298Error
1299ProcessGDBRemote::DoResume ()
1300{
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001301 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001302 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001303 if (log)
1304 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytone5219662010-12-03 06:02:24 +00001305
1306 Listener listener ("gdb-remote.resume-packet-sent");
1307 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1308 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00001309 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1310
Greg Claytond1d06e42013-04-20 00:27:58 +00001311 const size_t num_threads = GetThreadList().GetSize();
1312
Greg Clayton71fc2a32011-02-12 06:28:37 +00001313 StreamString continue_packet;
1314 bool continue_packet_error = false;
1315 if (m_gdb_comm.HasAnyVContSupport ())
1316 {
Greg Claytone98008c2014-02-13 23:34:38 +00001317 if (m_continue_c_tids.size() == num_threads ||
1318 (m_continue_c_tids.empty() &&
1319 m_continue_C_tids.empty() &&
1320 m_continue_s_tids.empty() &&
1321 m_continue_S_tids.empty()))
Greg Clayton71fc2a32011-02-12 06:28:37 +00001322 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001323 // All threads are continuing, just send a "c" packet
1324 continue_packet.PutCString ("c");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001325 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001326 else
1327 {
1328 continue_packet.PutCString ("vCont");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001329
Greg Claytond1d06e42013-04-20 00:27:58 +00001330 if (!m_continue_c_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001331 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001332 if (m_gdb_comm.GetVContSupported ('c'))
1333 {
1334 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)
1335 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1336 }
1337 else
1338 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001339 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001340
1341 if (!continue_packet_error && !m_continue_C_tids.empty())
1342 {
1343 if (m_gdb_comm.GetVContSupported ('C'))
1344 {
1345 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)
1346 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1347 }
1348 else
1349 continue_packet_error = true;
1350 }
Greg Claytone5219662010-12-03 06:02:24 +00001351
Greg Claytond1d06e42013-04-20 00:27:58 +00001352 if (!continue_packet_error && !m_continue_s_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001353 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001354 if (m_gdb_comm.GetVContSupported ('s'))
1355 {
1356 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)
1357 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1358 }
1359 else
1360 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001361 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001362
1363 if (!continue_packet_error && !m_continue_S_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001364 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001365 if (m_gdb_comm.GetVContSupported ('S'))
1366 {
1367 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)
1368 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1369 }
1370 else
1371 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001372 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001373
1374 if (continue_packet_error)
1375 continue_packet.GetString().clear();
Greg Clayton71fc2a32011-02-12 06:28:37 +00001376 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001377 }
1378 else
1379 continue_packet_error = true;
1380
1381 if (continue_packet_error)
1382 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001383 // Either no vCont support, or we tried to use part of the vCont
1384 // packet that wasn't supported by the remote GDB server.
1385 // We need to try and make a simple packet that can do our continue
Greg Clayton71fc2a32011-02-12 06:28:37 +00001386 const size_t num_continue_c_tids = m_continue_c_tids.size();
1387 const size_t num_continue_C_tids = m_continue_C_tids.size();
1388 const size_t num_continue_s_tids = m_continue_s_tids.size();
1389 const size_t num_continue_S_tids = m_continue_S_tids.size();
1390 if (num_continue_c_tids > 0)
1391 {
1392 if (num_continue_c_tids == num_threads)
1393 {
1394 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001395 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001396 continue_packet.PutChar ('c');
1397 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001398 }
1399 else if (num_continue_c_tids == 1 &&
1400 num_continue_C_tids == 0 &&
1401 num_continue_s_tids == 0 &&
1402 num_continue_S_tids == 0 )
1403 {
1404 // Only one thread is continuing
Greg Clayton8b82f082011-04-12 05:54:46 +00001405 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001406 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001407 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001408 }
1409 }
1410
Greg Clayton0c74e782011-06-24 03:21:43 +00001411 if (continue_packet_error && num_continue_C_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001412 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001413 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1414 num_continue_C_tids > 0 &&
1415 num_continue_s_tids == 0 &&
1416 num_continue_S_tids == 0 )
Greg Clayton71fc2a32011-02-12 06:28:37 +00001417 {
1418 const int continue_signo = m_continue_C_tids.front().second;
Greg Clayton0c74e782011-06-24 03:21:43 +00001419 // Only one thread is continuing
Greg Clayton71fc2a32011-02-12 06:28:37 +00001420 if (num_continue_C_tids > 1)
1421 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001422 // More that one thread with a signal, yet we don't have
1423 // vCont support and we are being asked to resume each
1424 // thread with a signal, we need to make sure they are
1425 // all the same signal, or we can't issue the continue
1426 // accurately with the current support...
1427 if (num_continue_C_tids > 1)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001428 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001429 continue_packet_error = false;
1430 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1431 {
1432 if (m_continue_C_tids[i].second != continue_signo)
1433 continue_packet_error = true;
1434 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001435 }
Greg Clayton0c74e782011-06-24 03:21:43 +00001436 if (!continue_packet_error)
1437 m_gdb_comm.SetCurrentThreadForRun (-1);
1438 }
1439 else
1440 {
1441 // Set the continue thread ID
1442 continue_packet_error = false;
1443 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001444 }
1445 if (!continue_packet_error)
1446 {
1447 // Add threads continuing with the same signo...
Greg Clayton71fc2a32011-02-12 06:28:37 +00001448 continue_packet.Printf("C%2.2x", continue_signo);
1449 }
1450 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001451 }
1452
Greg Clayton0c74e782011-06-24 03:21:43 +00001453 if (continue_packet_error && num_continue_s_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001454 {
1455 if (num_continue_s_tids == num_threads)
1456 {
1457 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001458 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001459 continue_packet.PutChar ('s');
1460 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001461 }
1462 else if (num_continue_c_tids == 0 &&
1463 num_continue_C_tids == 0 &&
1464 num_continue_s_tids == 1 &&
1465 num_continue_S_tids == 0 )
1466 {
1467 // Only one thread is stepping
Greg Clayton8b82f082011-04-12 05:54:46 +00001468 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001469 continue_packet.PutChar ('s');
Greg Clayton0c74e782011-06-24 03:21:43 +00001470 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001471 }
1472 }
1473
1474 if (!continue_packet_error && num_continue_S_tids > 0)
1475 {
1476 if (num_continue_S_tids == num_threads)
1477 {
1478 const int step_signo = m_continue_S_tids.front().second;
1479 // Are all threads trying to step with the same signal?
Greg Clayton0c74e782011-06-24 03:21:43 +00001480 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001481 if (num_continue_S_tids > 1)
1482 {
1483 for (size_t i=1; i<num_threads; ++i)
1484 {
1485 if (m_continue_S_tids[i].second != step_signo)
1486 continue_packet_error = true;
1487 }
1488 }
1489 if (!continue_packet_error)
1490 {
1491 // Add threads stepping with the same signo...
Greg Clayton8b82f082011-04-12 05:54:46 +00001492 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001493 continue_packet.Printf("S%2.2x", step_signo);
1494 }
1495 }
1496 else if (num_continue_c_tids == 0 &&
1497 num_continue_C_tids == 0 &&
1498 num_continue_s_tids == 0 &&
1499 num_continue_S_tids == 1 )
1500 {
1501 // Only one thread is stepping with signal
Greg Clayton8b82f082011-04-12 05:54:46 +00001502 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001503 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Clayton0c74e782011-06-24 03:21:43 +00001504 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001505 }
1506 }
1507 }
1508
1509 if (continue_packet_error)
1510 {
1511 error.SetErrorString ("can't make continue packet for this resume");
1512 }
1513 else
1514 {
1515 EventSP event_sp;
1516 TimeValue timeout;
1517 timeout = TimeValue::Now();
1518 timeout.OffsetWithSeconds (5);
Zachary Turneracee96a2014-09-23 18:32:09 +00001519 if (!m_async_thread.IsJoinable())
Jim Inghamb1e2e842012-04-12 18:49:31 +00001520 {
1521 error.SetErrorString ("Trying to resume but the async thread is dead.");
1522 if (log)
1523 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1524 return error;
1525 }
1526
Greg Clayton71fc2a32011-02-12 06:28:37 +00001527 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1528
1529 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Inghamb1e2e842012-04-12 18:49:31 +00001530 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001531 error.SetErrorString("Resume timed out.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00001532 if (log)
1533 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1534 }
1535 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1536 {
1537 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1538 if (log)
1539 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1540 return error;
1541 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001542 }
Greg Claytone5219662010-12-03 06:02:24 +00001543 }
1544
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001545 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001546}
1547
Greg Clayton9e920902012-04-10 02:25:43 +00001548void
1549ProcessGDBRemote::ClearThreadIDList ()
1550{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001551 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001552 m_thread_ids.clear();
1553}
1554
1555bool
1556ProcessGDBRemote::UpdateThreadIDList ()
1557{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001558 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001559 bool sequence_mutex_unavailable = false;
1560 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1561 if (sequence_mutex_unavailable)
1562 {
Greg Clayton9e920902012-04-10 02:25:43 +00001563 return false; // We just didn't get the list
1564 }
1565 return true;
1566}
1567
Greg Clayton9fc13552012-04-10 00:18:59 +00001568bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001569ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001570{
1571 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +00001572 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Clayton73b472d2010-10-27 03:32:59 +00001573 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +00001574 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton9e920902012-04-10 02:25:43 +00001575
1576 size_t num_thread_ids = m_thread_ids.size();
1577 // The "m_thread_ids" thread ID list should always be updated after each stop
1578 // reply packet, but in case it isn't, update it here.
1579 if (num_thread_ids == 0)
1580 {
1581 if (!UpdateThreadIDList ())
1582 return false;
1583 num_thread_ids = m_thread_ids.size();
1584 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001585
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001586 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001587 if (num_thread_ids > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001588 {
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001589 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001590 {
Greg Clayton9e920902012-04-10 02:25:43 +00001591 tid_t tid = m_thread_ids[i];
Greg Clayton160c9d82013-05-01 21:54:04 +00001592 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001593 if (!thread_sp)
Jim Inghamdee1bc92013-06-22 00:27:45 +00001594 {
Jim Ingham4f465cf2012-10-10 18:32:14 +00001595 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001596 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1597 log->Printf(
1598 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001599 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001600 thread_sp->GetID());
1601 }
1602 else
1603 {
1604 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1605 log->Printf(
1606 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001607 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001608 thread_sp->GetID());
1609 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001610 new_thread_list.AddThread(thread_sp);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001611 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001612 }
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001613
1614 // Whatever that is left in old_thread_list_copy are not
1615 // present in new_thread_list. Remove non-existent threads from internal id table.
1616 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1617 for (size_t i=0; i<old_num_thread_ids; i++)
1618 {
1619 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1620 if (old_thread_sp)
1621 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001622 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001623 m_thread_id_to_index_id_map.erase(old_thread_id);
1624 }
1625 }
1626
Greg Clayton9fc13552012-04-10 00:18:59 +00001627 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001628}
1629
1630
1631StateType
1632ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1633{
Greg Claytondd0e5a52011-06-02 22:22:38 +00001634 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001635 const char stop_type = stop_packet.GetChar();
1636 switch (stop_type)
1637 {
1638 case 'T':
1639 case 'S':
1640 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00001641 // This is a bit of a hack, but is is required. If we did exec, we
1642 // need to clear our thread lists and also know to rebuild our dynamic
1643 // register info before we lookup and threads and populate the expedited
1644 // register values so we need to know this right away so we can cleanup
1645 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00001646 const uint32_t stop_id = GetStopID();
1647 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00001648 {
1649 // Our first stop, make sure we have a process ID, and also make
1650 // sure we know about our registers
1651 if (GetID() == LLDB_INVALID_PROCESS_ID)
1652 {
Greg Claytonc574ede2011-03-10 02:26:48 +00001653 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00001654 if (pid != LLDB_INVALID_PROCESS_ID)
1655 SetID (pid);
1656 }
1657 BuildDynamicRegisterInfo (true);
1658 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001659 // Stop with signal and thread info
1660 const uint8_t signo = stop_packet.GetHexU8();
1661 std::string name;
1662 std::string value;
1663 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00001664 std::string reason;
1665 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001666 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00001667 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001668 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001669 ThreadSP thread_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001670 ThreadGDBRemote *gdb_thread = NULL;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001671
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001672 while (stop_packet.GetNameColonValue(name, value))
1673 {
1674 if (name.compare("metype") == 0)
1675 {
1676 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001677 exc_type = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001678 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001679 else if (name.compare("medata") == 0)
1680 {
1681 // exception data in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001682 exc_data.push_back(StringConvert::ToUInt64 (value.c_str(), 0, 16));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001683 }
1684 else if (name.compare("thread") == 0)
1685 {
1686 // thread in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001687 lldb::tid_t tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001688 // m_thread_list_real does have its own mutex, but we need to
1689 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1690 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1691 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1692 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
Greg Clayton160c9d82013-05-01 21:54:04 +00001693
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001694 if (!thread_sp)
Greg Claytond1d06e42013-04-20 00:27:58 +00001695 {
Greg Claytone576ab22011-02-15 00:19:15 +00001696 // Create the thread if we need to
Jim Ingham4f465cf2012-10-10 18:32:14 +00001697 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001698 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
1699 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1700 log->Printf ("ProcessGDBRemote::%s Adding new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1701 __FUNCTION__,
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001702 static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001703 thread_sp->GetID());
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001704
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001705 m_thread_list_real.AddThread(thread_sp);
Greg Claytone576ab22011-02-15 00:19:15 +00001706 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001707 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1708
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001709 }
Greg Clayton9e920902012-04-10 02:25:43 +00001710 else if (name.compare("threads") == 0)
1711 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001712 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001713 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00001714 // A comma separated list of all threads in the current
1715 // process that includes the thread for this stop reply
1716 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00001717 size_t comma_pos;
1718 lldb::tid_t tid;
1719 while ((comma_pos = value.find(',')) != std::string::npos)
1720 {
1721 value[comma_pos] = '\0';
1722 // thread in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001723 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00001724 if (tid != LLDB_INVALID_THREAD_ID)
1725 m_thread_ids.push_back (tid);
1726 value.erase(0, comma_pos + 1);
Greg Clayton9e920902012-04-10 02:25:43 +00001727 }
Vince Harron5275aaa2015-01-15 20:08:35 +00001728 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Clayton9e920902012-04-10 02:25:43 +00001729 if (tid != LLDB_INVALID_THREAD_ID)
1730 m_thread_ids.push_back (tid);
1731 }
Greg Claytonde9d0492011-01-08 03:17:57 +00001732 else if (name.compare("hexname") == 0)
1733 {
1734 StringExtractor name_extractor;
1735 // Swap "value" over into "name_extractor"
1736 name_extractor.GetStringRef().swap(value);
1737 // Now convert the HEX bytes into a string value
1738 name_extractor.GetHexByteString (value);
1739 thread_name.swap (value);
1740 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001741 else if (name.compare("name") == 0)
1742 {
1743 thread_name.swap (value);
1744 }
Greg Clayton6f35f5c2010-09-09 06:32:46 +00001745 else if (name.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001746 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001747 thread_dispatch_qaddr = StringConvert::ToUInt64 (value.c_str(), 0, 16);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001748 }
Greg Claytona658fd22011-06-04 01:26:29 +00001749 else if (name.compare("reason") == 0)
1750 {
1751 reason.swap(value);
1752 }
1753 else if (name.compare("description") == 0)
1754 {
1755 StringExtractor desc_extractor;
1756 // Swap "value" over into "name_extractor"
1757 desc_extractor.GetStringRef().swap(value);
1758 // Now convert the HEX bytes into a string value
Chaoren Lin28e57422015-02-03 01:51:25 +00001759 desc_extractor.GetHexByteString (value);
1760 description.swap(value);
Greg Claytona658fd22011-06-04 01:26:29 +00001761 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001762 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1763 {
1764 // We have a register number that contains an expedited
1765 // register value. Lets supply this register to our thread
1766 // so it won't have to go and read it.
Greg Clayton160c9d82013-05-01 21:54:04 +00001767 if (gdb_thread)
Greg Clayton3e06bd92011-01-09 21:07:35 +00001768 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001769 uint32_t reg = StringConvert::ToUInt32 (name.c_str(), UINT32_MAX, 16);
Greg Clayton3e06bd92011-01-09 21:07:35 +00001770
1771 if (reg != UINT32_MAX)
1772 {
1773 StringExtractor reg_value_extractor;
1774 // Swap "value" over into "reg_value_extractor"
1775 reg_value_extractor.GetStringRef().swap(value);
Greg Clayton160c9d82013-05-01 21:54:04 +00001776 if (!gdb_thread->PrivateSetRegisterValue (reg, reg_value_extractor))
Greg Claytone576ab22011-02-15 00:19:15 +00001777 {
1778 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1779 name.c_str(),
1780 reg,
1781 reg,
1782 reg_value_extractor.GetStringRef().c_str(),
1783 stop_packet.GetStringRef().c_str());
1784 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001785 }
1786 }
1787 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001788 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001789
Hafiz Abid Qadeer673b4a32014-02-20 10:23:20 +00001790 // If the response is old style 'S' packet which does not provide us with thread information
1791 // then update the thread list and choose the first one.
1792 if (!thread_sp)
1793 {
1794 UpdateThreadIDList ();
1795
1796 if (!m_thread_ids.empty ())
1797 {
1798 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1799 thread_sp = m_thread_list_real.FindThreadByProtocolID (m_thread_ids.front (), false);
1800 if (thread_sp)
1801 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get ());
1802 }
1803 }
1804
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001805 if (thread_sp)
1806 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001807 // Clear the stop info just in case we don't set it to anything
1808 thread_sp->SetStopInfo (StopInfoSP());
1809
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001810 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Inghamdd2fe7a2011-01-28 02:23:12 +00001811 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001812 if (exc_type != 0)
1813 {
Greg Clayton1a65ae12011-01-25 23:55:37 +00001814 const size_t exc_data_size = exc_data.size();
Greg Claytonf4b47e12010-08-04 01:40:35 +00001815
Greg Clayton160c9d82013-05-01 21:54:04 +00001816 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1817 exc_type,
1818 exc_data_size,
1819 exc_data_size >= 1 ? exc_data[0] : 0,
1820 exc_data_size >= 2 ? exc_data[1] : 0,
1821 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001822 }
Greg Claytona658fd22011-06-04 01:26:29 +00001823 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001824 {
Greg Claytona658fd22011-06-04 01:26:29 +00001825 bool handled = false;
Greg Clayton8cda7f02013-05-21 21:55:59 +00001826 bool did_exec = false;
Greg Claytona658fd22011-06-04 01:26:29 +00001827 if (!reason.empty())
1828 {
1829 if (reason.compare("trace") == 0)
1830 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001831 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Greg Claytona658fd22011-06-04 01:26:29 +00001832 handled = true;
1833 }
1834 else if (reason.compare("breakpoint") == 0)
1835 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001836 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1837 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Claytona658fd22011-06-04 01:26:29 +00001838 if (bp_site_sp)
1839 {
1840 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1841 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1842 // 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 +00001843 handled = true;
Greg Clayton160c9d82013-05-01 21:54:04 +00001844 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00001845 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001846 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00001847 }
1848 else
1849 {
1850 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001851 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00001852 }
1853 }
Greg Claytona658fd22011-06-04 01:26:29 +00001854 }
1855 else if (reason.compare("trap") == 0)
1856 {
1857 // Let the trap just use the standard signal stop reason below...
1858 }
1859 else if (reason.compare("watchpoint") == 0)
1860 {
Chaoren Lin18fe6402015-02-03 01:51:47 +00001861 StringExtractor desc_extractor(description.c_str());
1862 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1863 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
1864 watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
1865 if (wp_addr != LLDB_INVALID_ADDRESS)
1866 {
1867 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
1868 if (wp_sp)
1869 {
1870 wp_sp->SetHardwareIndex(wp_index);
1871 watch_id = wp_sp->GetID();
1872 }
1873 }
1874 if (watch_id == LLDB_INVALID_WATCH_ID)
1875 {
1876 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_WATCHPOINTS));
1877 if (log) log->Printf ("failed to find watchpoint");
1878 }
Greg Clayton160c9d82013-05-01 21:54:04 +00001879 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
Greg Claytona658fd22011-06-04 01:26:29 +00001880 handled = true;
1881 }
1882 else if (reason.compare("exception") == 0)
1883 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001884 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00001885 handled = true;
1886 }
Greg Clayton15fc2be2013-05-21 01:00:52 +00001887 else if (reason.compare("exec") == 0)
1888 {
Greg Clayton8cda7f02013-05-21 21:55:59 +00001889 did_exec = true;
Greg Clayton15fc2be2013-05-21 01:00:52 +00001890 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
1891 handled = true;
1892 }
Greg Claytona658fd22011-06-04 01:26:29 +00001893 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001894
Jim Ingham40083a42014-02-24 19:49:46 +00001895 if (!handled && signo && did_exec == false)
Greg Claytona658fd22011-06-04 01:26:29 +00001896 {
1897 if (signo == SIGTRAP)
1898 {
1899 // Currently we are going to assume SIGTRAP means we are either
1900 // hitting a breakpoint or hardware single stepping.
Jim Ingham54cc6e42012-07-11 21:41:19 +00001901 handled = true;
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +00001902 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
Greg Clayton160c9d82013-05-01 21:54:04 +00001903 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001904
Greg Claytona658fd22011-06-04 01:26:29 +00001905 if (bp_site_sp)
1906 {
1907 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1908 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1909 // 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 +00001910 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00001911 {
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +00001912 if(m_breakpoint_pc_offset != 0)
1913 thread_sp->GetRegisterContext()->SetPC(pc);
Greg Clayton160c9d82013-05-01 21:54:04 +00001914 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00001915 }
1916 else
1917 {
1918 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001919 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00001920 }
1921 }
Jim Ingham54cc6e42012-07-11 21:41:19 +00001922 else
Greg Claytona658fd22011-06-04 01:26:29 +00001923 {
Jim Ingham4dc613b2012-10-27 02:52:04 +00001924 // If we were stepping then assume the stop was the result of the trace. If we were
1925 // not stepping then report the SIGTRAP.
1926 // FIXME: We are still missing the case where we single step over a trap instruction.
Greg Clayton160c9d82013-05-01 21:54:04 +00001927 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1928 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Jim Ingham4dc613b2012-10-27 02:52:04 +00001929 else
Greg Clayton160c9d82013-05-01 21:54:04 +00001930 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo));
Greg Claytona658fd22011-06-04 01:26:29 +00001931 }
1932 }
1933 if (!handled)
Greg Clayton160c9d82013-05-01 21:54:04 +00001934 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Jason Molenda8214b012013-04-25 01:33:46 +00001935 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001936
Greg Claytona658fd22011-06-04 01:26:29 +00001937 if (!description.empty())
1938 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001939 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
Greg Claytona658fd22011-06-04 01:26:29 +00001940 if (stop_info_sp)
1941 {
1942 stop_info_sp->SetDescription (description.c_str());
Greg Clayton3418c852011-08-10 02:10:13 +00001943 }
Greg Claytona658fd22011-06-04 01:26:29 +00001944 else
1945 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001946 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00001947 }
1948 }
1949 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001950 }
1951 return eStateStopped;
1952 }
1953 break;
1954
1955 case 'W':
Todd Fialaff6131a2014-05-19 04:57:23 +00001956 case 'X':
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001957 // process exited
1958 return eStateExited;
1959
1960 default:
1961 break;
1962 }
1963 return eStateInvalid;
1964}
1965
1966void
1967ProcessGDBRemote::RefreshStateAfterStop ()
1968{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001969 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001970 m_thread_ids.clear();
1971 // Set the thread stop info. It might have a "threads" key whose value is
1972 // a list of all thread IDs in the current process, so m_thread_ids might
1973 // get set.
1974 SetThreadStopInfo (m_last_stop_packet);
1975 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1976 if (m_thread_ids.empty())
1977 {
1978 // No, we need to fetch the thread list manually
1979 UpdateThreadIDList();
1980 }
1981
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001982 // Let all threads recover from stopping and do any clean up based
1983 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001984 m_thread_list_real.RefreshStateAfterStop();
Greg Clayton9e920902012-04-10 02:25:43 +00001985
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001986}
1987
1988Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001989ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001990{
1991 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001992
Greg Clayton6ed95942011-01-22 07:12:45 +00001993 bool timed_out = false;
1994 Mutex::Locker locker;
Greg Clayton513c26c2011-01-29 07:10:55 +00001995
1996 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00001997 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001998 // We are being asked to halt during an attach. We need to just close
1999 // our file handle and debugserver will go away, and we can be done...
2000 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00002001 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002002 else
2003 {
Greg Clayton2687cd12012-03-29 01:55:41 +00002004 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton513c26c2011-01-29 07:10:55 +00002005 {
2006 if (timed_out)
2007 error.SetErrorString("timed out sending interrupt packet");
2008 else
2009 error.SetErrorString("unknown error sending interrupt packet");
2010 }
Greg Clayton2687cd12012-03-29 01:55:41 +00002011
2012 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton513c26c2011-01-29 07:10:55 +00002013 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002014 return error;
2015}
2016
2017Error
Jim Inghamacff8952013-05-02 00:27:30 +00002018ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002019{
2020 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002021 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00002022 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00002023 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2024
Jim Inghamacff8952013-05-02 00:27:30 +00002025 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002026 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00002027 {
Jim Inghamacff8952013-05-02 00:27:30 +00002028 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002029 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
2030 else
Jim Inghamacff8952013-05-02 00:27:30 +00002031 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00002032 }
Jim Inghamacff8952013-05-02 00:27:30 +00002033
2034 if (!error.Success())
2035 return error;
2036
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002037 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00002038 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002039
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002040 SetPrivateState (eStateDetached);
2041 ResumePrivateStateThread();
2042
2043 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00002044 return error;
2045}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002046
Jim Ingham43c555d2012-07-04 00:35:43 +00002047
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002048Error
2049ProcessGDBRemote::DoDestroy ()
2050{
2051 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002052 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002053 if (log)
2054 log->Printf ("ProcessGDBRemote::DoDestroy()");
2055
Jim Ingham43c555d2012-07-04 00:35:43 +00002056 // There is a bug in older iOS debugservers where they don't shut down the process
2057 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
2058 // this can cause problems with restarting. So we check to see if any of our threads are stopped
2059 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
2060 // destroy it again.
2061 //
2062 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
2063 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
2064 // the debugservers with this bug are equal. There really should be a better way to test this!
2065 //
2066 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
2067 // get called here to destroy again and we're still at a breakpoint or exception, then we should
2068 // just do the straight-forward kill.
2069 //
2070 // And of course, if we weren't able to stop the process by the time we get here, it isn't
2071 // necessary (or helpful) to do any of this.
2072
2073 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
2074 {
2075 PlatformSP platform_sp = GetTarget().GetPlatform();
2076
2077 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2078 if (platform_sp
2079 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00002080 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00002081 {
2082 if (m_destroy_tried_resuming)
2083 {
2084 if (log)
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002085 log->PutCString ("ProcessGDBRemote::DoDestroy() - Tried resuming to destroy once already, not doing it again.");
Jim Ingham43c555d2012-07-04 00:35:43 +00002086 }
2087 else
2088 {
2089 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
2090 // but we really need it to happen here and it doesn't matter if we do it twice.
2091 m_thread_list.DiscardThreadPlans();
2092 DisableAllBreakpointSites();
2093
2094 bool stop_looks_like_crash = false;
2095 ThreadList &threads = GetThreadList();
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() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
2113 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00002114 stop_info_sp->GetDescription());
2115 stop_looks_like_crash = true;
2116 break;
2117 }
2118 }
2119 }
2120
2121 if (stop_looks_like_crash)
2122 {
2123 if (log)
2124 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
2125 m_destroy_tried_resuming = true;
2126
2127 // If we are going to run again before killing, it would be good to suspend all the threads
2128 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
2129 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
2130 // have to run the risk of letting those threads proceed a bit.
2131
2132 {
Jim Ingham45350372012-09-11 00:08:52 +00002133 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002134
2135 size_t num_threads = threads.GetSize();
2136 for (size_t i = 0; i < num_threads; i++)
2137 {
2138 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002139 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002140 StopReason reason = eStopReasonInvalid;
2141 if (stop_info_sp)
2142 reason = stop_info_sp->GetStopReason();
2143 if (reason != eStopReasonBreakpoint
2144 && reason != eStopReasonException)
2145 {
2146 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002147 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
2148 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00002149 thread_sp->SetResumeState(eStateSuspended);
2150 }
2151 }
2152 }
2153 Resume ();
2154 return Destroy();
2155 }
2156 }
2157 }
2158 }
2159
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002160 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00002161 int exit_status = SIGABRT;
2162 std::string exit_string;
2163
Greg Clayton6ed95942011-01-22 07:12:45 +00002164 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002165 {
Jim Inghamaab78372011-10-28 01:11:35 +00002166 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00002167 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002168 StringExtractorGDBRemote response;
2169 bool send_async = true;
Tamas Berghammer912800c2015-02-24 10:23:39 +00002170 GDBRemoteCommunication::ScopedTimeout (m_gdb_comm, 3);
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002171
Greg Clayton3dedae12013-12-06 21:45:27 +00002172 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton513c26c2011-01-29 07:10:55 +00002173 {
2174 char packet_cmd = response.GetChar(0);
2175
2176 if (packet_cmd == 'W' || packet_cmd == 'X')
2177 {
Jim Inghameac0aa42014-02-21 22:36:11 +00002178#if defined(__APPLE__)
Jim Ingham9d67cc52014-02-21 22:35:29 +00002179 // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off
2180 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill
2181 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns
2182 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap
2183 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of
2184 // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2185 // Anyway, so call waitpid here to finally reap it.
2186 PlatformSP platform_sp(GetTarget().GetPlatform());
2187 if (platform_sp && platform_sp->IsHost())
2188 {
2189 int status;
2190 ::pid_t reap_pid;
2191 reap_pid = waitpid (GetID(), &status, WNOHANG);
2192 if (log)
2193 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2194 }
2195#endif
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002196 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002197 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00002198 exit_status = response.GetHexU8();
2199 }
2200 else
2201 {
2202 if (log)
2203 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2204 exit_string.assign("got unexpected response to k packet: ");
2205 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00002206 }
2207 }
2208 else
2209 {
Jim Inghambabfc382012-06-06 00:32:39 +00002210 if (log)
2211 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2212 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00002213 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002214 }
Jim Inghambabfc382012-06-06 00:32:39 +00002215 else
2216 {
2217 if (log)
Ed Masteb3a53332014-03-17 17:05:22 +00002218 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching");
Jim Inghamcfc09352012-07-27 23:57:19 +00002219 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00002220 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002221 }
Jim Inghambabfc382012-06-06 00:32:39 +00002222 else
2223 {
2224 // If we missed setting the exit status on the way out, do it here.
2225 // NB set exit status can be called multiple times, the first one sets the status.
2226 exit_string.assign("destroying when not connected to debugserver");
2227 }
2228
2229 SetExitStatus(exit_status, exit_string.c_str());
2230
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002231 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002232 KillDebugserverProcess ();
2233 return error;
2234}
2235
Greg Clayton8cda7f02013-05-21 21:55:59 +00002236void
2237ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2238{
2239 lldb_private::Mutex::Locker locker (m_last_stop_packet_mutex);
2240 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2241 if (did_exec)
2242 {
2243 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2244 if (log)
2245 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2246
2247 m_thread_list_real.Clear();
2248 m_thread_list.Clear();
2249 BuildDynamicRegisterInfo (true);
2250 m_gdb_comm.ResetDiscoverableSettings();
2251 }
2252 m_last_stop_packet = response;
2253}
2254
2255
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002256//------------------------------------------------------------------
2257// Process Queries
2258//------------------------------------------------------------------
2259
2260bool
2261ProcessGDBRemote::IsAlive ()
2262{
Greg Clayton10177aa2010-12-08 05:08:21 +00002263 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002264}
2265
2266addr_t
2267ProcessGDBRemote::GetImageInfoAddress()
2268{
Jason Molenda6ba6d3d2013-01-30 04:39:32 +00002269 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002270}
2271
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002272//------------------------------------------------------------------
2273// Process Memory
2274//------------------------------------------------------------------
2275size_t
2276ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2277{
Jason Molenda6076bf42014-05-06 04:34:52 +00002278 GetMaxMemorySize ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002279 if (size > m_max_memory_size)
2280 {
2281 // Keep memory read sizes down to a sane limit. This function will be
2282 // called multiple times in order to complete the task by
2283 // lldb_private::Process so it is ok to do this.
2284 size = m_max_memory_size;
2285 }
2286
2287 char packet[64];
Jason Molenda6076bf42014-05-06 04:34:52 +00002288 int packet_len;
2289 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2290 if (binary_memory_read)
2291 {
2292 packet_len = ::snprintf (packet, sizeof(packet), "x0x%" PRIx64 ",0x%" PRIx64, (uint64_t)addr, (uint64_t)size);
2293 }
2294 else
2295 {
2296 packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
2297 }
Andy Gibbsa297a972013-06-19 19:04:53 +00002298 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002299 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002300 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002301 {
Greg Clayton576d8832011-03-22 04:00:09 +00002302 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002303 {
2304 error.Clear();
Jason Molenda6076bf42014-05-06 04:34:52 +00002305 if (binary_memory_read)
2306 {
2307 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any
2308 // 0x7d character escaping that was present in the packet
2309
2310 size_t data_received_size = response.GetBytesLeft();
2311 if (data_received_size > size)
2312 {
2313 // Don't write past the end of BUF if the remote debug server gave us too
2314 // much data for some reason.
2315 data_received_size = size;
2316 }
2317 memcpy (buf, response.GetStringRef().data(), data_received_size);
2318 return data_received_size;
2319 }
2320 else
2321 {
2322 return response.GetHexBytes(buf, size, '\xdd');
2323 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002324 }
Greg Clayton576d8832011-03-22 04:00:09 +00002325 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002326 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002327 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002328 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002329 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002330 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002331 }
2332 else
2333 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002334 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002335 }
2336 return 0;
2337}
2338
2339size_t
2340ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2341{
Jason Molenda6076bf42014-05-06 04:34:52 +00002342 GetMaxMemorySize ();
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002343 if (size > m_max_memory_size)
2344 {
2345 // Keep memory read sizes down to a sane limit. This function will be
2346 // called multiple times in order to complete the task by
2347 // lldb_private::Process so it is ok to do this.
2348 size = m_max_memory_size;
2349 }
2350
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002351 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00002352 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Clayton7fb56d02011-02-01 01:31:41 +00002353 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002354 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002355 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002356 {
Greg Clayton576d8832011-03-22 04:00:09 +00002357 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002358 {
2359 error.Clear();
2360 return size;
2361 }
Greg Clayton576d8832011-03-22 04:00:09 +00002362 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002363 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002364 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002365 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002366 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002367 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 +00002368 }
2369 else
2370 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002371 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002372 }
2373 return 0;
2374}
2375
2376lldb::addr_t
2377ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2378{
Todd Fialaaf245d12014-06-30 21:05:18 +00002379 lldb_private::Log *log (lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_EXPRESSIONS));
Greg Clayton2a48f522011-05-14 01:50:35 +00002380 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2381
Greg Clayton70b57652011-05-15 01:25:55 +00002382 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton2a48f522011-05-14 01:50:35 +00002383 switch (supported)
2384 {
2385 case eLazyBoolCalculate:
2386 case eLazyBoolYes:
2387 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2388 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2389 return allocated_addr;
2390
2391 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002392 // Call mmap() to create memory in the inferior..
2393 unsigned prot = 0;
2394 if (permissions & lldb::ePermissionsReadable)
2395 prot |= eMmapProtRead;
2396 if (permissions & lldb::ePermissionsWritable)
2397 prot |= eMmapProtWrite;
2398 if (permissions & lldb::ePermissionsExecutable)
2399 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00002400
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002401 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2402 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2403 m_addr_to_mmap_size[allocated_addr] = size;
2404 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002405 {
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002406 allocated_addr = LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00002407 if (log)
2408 log->Printf ("ProcessGDBRemote::%s no direct stub support for memory allocation, and InferiorCallMmap also failed - is stub missing register context save/restore capability?", __FUNCTION__);
2409 }
Greg Clayton2a48f522011-05-14 01:50:35 +00002410 break;
2411 }
2412
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002413 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00002414 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002415 else
2416 error.Clear();
2417 return allocated_addr;
2418}
2419
2420Error
Greg Clayton46fb5582011-11-18 07:03:08 +00002421ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2422 MemoryRegionInfo &region_info)
2423{
2424
2425 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2426 return error;
2427}
2428
2429Error
Johnny Chen64637202012-05-23 21:09:52 +00002430ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2431{
2432
2433 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2434 return error;
2435}
2436
2437Error
Enrico Granataf04a2192012-07-13 23:18:48 +00002438ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2439{
2440 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2441 return error;
2442}
2443
2444Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002445ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2446{
2447 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00002448 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2449
2450 switch (supported)
2451 {
2452 case eLazyBoolCalculate:
2453 // We should never be deallocating memory without allocating memory
2454 // first so we should never get eLazyBoolCalculate
2455 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2456 break;
2457
2458 case eLazyBoolYes:
2459 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00002460 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002461 break;
2462
2463 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002464 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00002465 {
2466 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002467 if (pos != m_addr_to_mmap_size.end() &&
2468 InferiorCallMunmap(this, addr, pos->second))
2469 m_addr_to_mmap_size.erase (pos);
2470 else
Daniel Malead01b2952012-11-29 21:49:15 +00002471 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002472 }
2473 break;
2474 }
2475
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002476 return error;
2477}
2478
2479
2480//------------------------------------------------------------------
2481// Process STDIO
2482//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002483size_t
2484ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2485{
2486 if (m_stdio_communication.IsConnected())
2487 {
2488 ConnectionStatus status;
2489 m_stdio_communication.Write(src, src_len, status, NULL);
2490 }
Vince Harrondf3f00f2015-02-10 21:09:04 +00002491 else if (m_stdin_forward)
Vince Harrone0be4252015-02-06 18:32:57 +00002492 {
2493 m_gdb_comm.SendStdinNotification(src, src_len);
2494 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002495 return 0;
2496}
2497
2498Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002499ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002500{
2501 Error error;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002502 assert(bp_site != NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002503
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002504 // Get logging info
2505 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002506 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002507
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002508 // Get the breakpoint address
2509 const addr_t addr = bp_site->GetLoadAddress();
2510
2511 // Log that a breakpoint was requested
2512 if (log)
2513 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
2514
2515 // Breakpoint already exists and is enabled
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002516 if (bp_site->IsEnabled())
2517 {
2518 if (log)
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002519 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 +00002520 return error;
2521 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002522
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002523 // Get the software breakpoint trap opcode size
2524 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2525
2526 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
2527 // is supported by the remote stub. These are set to true by default, and later set to false
2528 // only after we receive an unimplemented response when sending a breakpoint packet. This means
2529 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
2530 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
2531 // indicates if the user specifically asked for hardware breakpoints. If true then we will
2532 // skip over software breakpoints.
2533 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
2534 {
2535 // Try to send off a software breakpoint packet ($Z0)
2536 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002537 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002538 // The breakpoint was placed successfully
2539 bp_site->SetEnabled(true);
2540 bp_site->SetType(BreakpointSite::eExternal);
Greg Claytoneb023e72013-10-11 19:48:25 +00002541 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002542 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002543
2544 // SendGDBStoppointTypePacket() will return an error if it was unable to set this
2545 // breakpoint. We need to differentiate between a error specific to placing this breakpoint
2546 // or if we have learned that this breakpoint type is unsupported. To do this, we
2547 // must test the support boolean for this breakpoint type to see if it now indicates that
2548 // this breakpoint type is unsupported. If they are still supported then we should return
2549 // with the error code. If they are now unsupported, then we would like to fall through
2550 // and try another form of breakpoint.
2551 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
2552 return error;
2553
2554 // We reach here when software breakpoints have been found to be unsupported. For future
2555 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
2556 // known not to be supported.
2557 if (log)
2558 log->Printf("Software breakpoints are unsupported");
2559
2560 // So we will fall through and try a hardware breakpoint
2561 }
2562
2563 // The process of setting a hardware breakpoint is much the same as above. We check the
2564 // supported boolean for this breakpoint type, and if it is thought to be supported then we
2565 // will try to set this breakpoint with a hardware breakpoint.
2566 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
2567 {
2568 // Try to send off a hardware breakpoint packet ($Z1)
2569 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002570 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002571 // The breakpoint was placed successfully
2572 bp_site->SetEnabled(true);
2573 bp_site->SetType(BreakpointSite::eHardware);
2574 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002575 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002576
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002577 // Check if the error was something other then an unsupported breakpoint type
2578 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
2579 {
2580 // Unable to set this hardware breakpoint
2581 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
2582 return error;
2583 }
2584
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002585 // We will reach here when the stub gives an unsupported response to a hardware breakpoint
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002586 if (log)
2587 log->Printf("Hardware breakpoints are unsupported");
2588
2589 // Finally we will falling through to a #trap style breakpoint
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002590 }
2591
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002592 // Don't fall through when hardware breakpoints were specifically requested
2593 if (bp_site->HardwareRequired())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002594 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002595 error.SetErrorString("hardware breakpoints are not supported");
2596 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002597 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002598
2599 // As a last resort we want to place a manual breakpoint. An instruction
2600 // is placed into the process memory using memory write packets.
2601 return EnableSoftwareBreakpoint(bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002602}
2603
2604Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002605ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002606{
2607 Error error;
2608 assert (bp_site != NULL);
2609 addr_t addr = bp_site->GetLoadAddress();
2610 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00002611 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002612 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002613 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002614
2615 if (bp_site->IsEnabled())
2616 {
2617 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2618
Greg Clayton8b82f082011-04-12 05:54:46 +00002619 BreakpointSite::Type bp_type = bp_site->GetType();
2620 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002621 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002622 case BreakpointSite::eSoftware:
2623 error = DisableSoftwareBreakpoint (bp_site);
2624 break;
2625
2626 case BreakpointSite::eHardware:
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002627 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00002628 error.SetErrorToGenericError();
2629 break;
2630
2631 case BreakpointSite::eExternal:
Jim Inghama04ef752014-03-07 11:18:02 +00002632 {
2633 GDBStoppointType stoppoint_type;
2634 if (bp_site->IsHardware())
2635 stoppoint_type = eBreakpointHardware;
2636 else
2637 stoppoint_type = eBreakpointSoftware;
2638
2639 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00002640 error.SetErrorToGenericError();
Jim Inghama04ef752014-03-07 11:18:02 +00002641 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002642 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002643 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002644 if (error.Success())
2645 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002646 }
2647 else
2648 {
2649 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002650 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 +00002651 return error;
2652 }
2653
2654 if (error.Success())
2655 error.SetErrorToGenericError();
2656 return error;
2657}
2658
Johnny Chen11309a32011-09-06 22:38:36 +00002659// Pre-requisite: wp != NULL.
2660static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00002661GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00002662{
2663 assert(wp);
2664 bool watch_read = wp->WatchpointRead();
2665 bool watch_write = wp->WatchpointWrite();
2666
2667 // watch_read and watch_write cannot both be false.
2668 assert(watch_read || watch_write);
2669 if (watch_read && watch_write)
2670 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00002671 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00002672 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00002673 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00002674 return eWatchpointWrite;
2675}
2676
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002677Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002678ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002679{
2680 Error error;
2681 if (wp)
2682 {
2683 user_id_t watchID = wp->GetID();
2684 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00002685 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002686 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002687 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002688 if (wp->IsEnabled())
2689 {
2690 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002691 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 +00002692 return error;
2693 }
Johnny Chen11309a32011-09-06 22:38:36 +00002694
2695 GDBStoppointType type = GetGDBStoppointType(wp);
2696 // Pass down an appropriate z/Z packet...
2697 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002698 {
Johnny Chen11309a32011-09-06 22:38:36 +00002699 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2700 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002701 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002702 return error;
2703 }
2704 else
2705 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002706 }
Johnny Chen11309a32011-09-06 22:38:36 +00002707 else
2708 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002709 }
2710 else
2711 {
Johnny Chen01a67862011-10-14 00:42:25 +00002712 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002713 }
2714 if (error.Success())
2715 error.SetErrorToGenericError();
2716 return error;
2717}
2718
2719Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002720ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002721{
2722 Error error;
2723 if (wp)
2724 {
2725 user_id_t watchID = wp->GetID();
2726
Greg Clayton5160ce52013-03-27 23:08:40 +00002727 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002728
2729 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00002730
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002731 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002732 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002733
Johnny Chen11309a32011-09-06 22:38:36 +00002734 if (!wp->IsEnabled())
2735 {
2736 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002737 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 +00002738 // See also 'class WatchpointSentry' within StopInfo.cpp.
2739 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2740 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00002741 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002742 return error;
2743 }
2744
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002745 if (wp->IsHardware())
2746 {
Johnny Chen11309a32011-09-06 22:38:36 +00002747 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002748 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00002749 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2750 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002751 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002752 return error;
2753 }
2754 else
2755 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002756 }
2757 // TODO: clear software watchpoints if we implement them
2758 }
2759 else
2760 {
Johnny Chen01a67862011-10-14 00:42:25 +00002761 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002762 }
2763 if (error.Success())
2764 error.SetErrorToGenericError();
2765 return error;
2766}
2767
2768void
2769ProcessGDBRemote::Clear()
2770{
2771 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002772 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002773 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002774}
2775
2776Error
2777ProcessGDBRemote::DoSignal (int signo)
2778{
2779 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002780 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002781 if (log)
2782 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2783
2784 if (!m_gdb_comm.SendAsyncSignal (signo))
2785 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2786 return error;
2787}
2788
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002789Error
Greg Clayton91a9b2472013-12-04 19:19:12 +00002790ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002791{
2792 Error error;
2793 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2794 {
2795 // If we locate debugserver, keep that located version around
2796 static FileSpec g_debugserver_file_spec;
2797
Han Ming Ong84647042012-02-25 01:07:38 +00002798 ProcessLaunchInfo debugserver_launch_info;
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00002799 // Make debugserver run in its own session so signals generated by
2800 // special terminal key sequences (^C) don't affect debugserver.
2801 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
2802
Greg Clayton91a9b2472013-12-04 19:19:12 +00002803 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2804 debugserver_launch_info.SetUserID(process_info.GetUserID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002805
Todd Fiala013434e2014-07-09 01:29:05 +00002806#if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__) || defined (__aarch64__))
Greg Claytonfda4fab2014-01-10 22:24:11 +00002807 // On iOS, still do a local connection using a random port
Greg Clayton16810922014-02-27 19:38:18 +00002808 const char *hostname = "127.0.0.1";
Greg Claytonfda4fab2014-01-10 22:24:11 +00002809 uint16_t port = get_random_port ();
2810#else
2811 // Set hostname being NULL to do the reverse connect where debugserver
2812 // will bind to port zero and it will communicate back to us the port
2813 // that we will connect to
2814 const char *hostname = NULL;
2815 uint16_t port = 0;
2816#endif
2817
2818 error = m_gdb_comm.StartDebugserverProcess (hostname,
2819 port,
Greg Clayton00fe87b2013-12-05 22:58:22 +00002820 debugserver_launch_info,
2821 port);
Greg Clayton91a9b2472013-12-04 19:19:12 +00002822
2823 if (error.Success ())
2824 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002825 else
Greg Clayton91a9b2472013-12-04 19:19:12 +00002826 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002827
2828 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2829 StartAsyncThread ();
Greg Clayton91a9b2472013-12-04 19:19:12 +00002830
2831 if (error.Fail())
2832 {
2833 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
2834
2835 if (log)
2836 log->Printf("failed to start debugserver process: %s", error.AsCString());
2837 return error;
2838 }
2839
Greg Clayton00fe87b2013-12-05 22:58:22 +00002840 if (m_gdb_comm.IsConnected())
2841 {
2842 // Finish the connection process by doing the handshake without connecting (send NULL URL)
2843 ConnectToDebugserver (NULL);
2844 }
2845 else
2846 {
Greg Claytonfda4fab2014-01-10 22:24:11 +00002847 StreamString connect_url;
2848 connect_url.Printf("connect://%s:%u", hostname, port);
2849 error = ConnectToDebugserver (connect_url.GetString().c_str());
Greg Clayton00fe87b2013-12-05 22:58:22 +00002850 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00002851
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002852 }
2853 return error;
2854}
2855
2856bool
2857ProcessGDBRemote::MonitorDebugserverProcess
2858(
2859 void *callback_baton,
2860 lldb::pid_t debugserver_pid,
Greg Claytone4e45922011-11-16 05:37:56 +00002861 bool exited, // True if the process did exit
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002862 int signo, // Zero for no signal
2863 int exit_status // Exit value of process if signal is zero
2864)
2865{
Greg Claytone4e45922011-11-16 05:37:56 +00002866 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2867 // and might not exist anymore, so we need to carefully try to get the
2868 // target for this process first since we have a race condition when
2869 // we are done running between getting the notice that the inferior
2870 // process has died and the debugserver that was debugging this process.
2871 // In our test suite, we are also continually running process after
2872 // process, so we must be very careful to make sure:
2873 // 1 - process object hasn't been deleted already
2874 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002875
2876 // "debugserver_pid" argument passed in is the process ID for
2877 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00002878 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002879
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002880 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton6779606a2011-01-22 23:43:18 +00002881
Greg Claytone4e45922011-11-16 05:37:56 +00002882 // Get a shared pointer to the target that has a matching process pointer.
2883 // This target could be gone, or the target could already have a new process
2884 // object inside of it
2885 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2886
Greg Clayton6779606a2011-01-22 23:43:18 +00002887 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002888 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 +00002889
Greg Claytone4e45922011-11-16 05:37:56 +00002890 if (target_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002891 {
Greg Claytone4e45922011-11-16 05:37:56 +00002892 // We found a process in a target that matches, but another thread
2893 // might be in the process of launching a new process that will
2894 // soon replace it, so get a shared pointer to the process so we
2895 // can keep it alive.
2896 ProcessSP process_sp (target_sp->GetProcessSP());
2897 // Now we have a shared pointer to the process that can't go away on us
2898 // so we now make sure it was the same as the one passed in, and also make
2899 // sure that our previous "process *" didn't get deleted and have a new
2900 // "process *" created in its place with the same pointer. To verify this
2901 // we make sure the process has our debugserver process ID. If we pass all
2902 // of these tests, then we are sure that this process is the one we were
2903 // looking for.
2904 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002905 {
Greg Claytone4e45922011-11-16 05:37:56 +00002906 // Sleep for a half a second to make sure our inferior process has
2907 // time to set its exit status before we set it incorrectly when
2908 // both the debugserver and the inferior process shut down.
2909 usleep (500000);
2910 // If our process hasn't yet exited, debugserver might have died.
2911 // If the process did exit, the we are reaping it.
2912 const StateType state = process->GetState();
2913
2914 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2915 state != eStateInvalid &&
2916 state != eStateUnloaded &&
2917 state != eStateExited &&
2918 state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002919 {
Greg Claytone4e45922011-11-16 05:37:56 +00002920 char error_str[1024];
2921 if (signo)
2922 {
2923 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2924 if (signal_cstr)
2925 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2926 else
2927 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2928 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002929 else
Greg Claytone4e45922011-11-16 05:37:56 +00002930 {
2931 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2932 }
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002933
Greg Claytone4e45922011-11-16 05:37:56 +00002934 process->SetExitStatus (-1, error_str);
2935 }
2936 // Debugserver has exited we need to let our ProcessGDBRemote
2937 // know that it no longer has a debugserver instance
2938 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002939 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002940 }
2941 return true;
2942}
2943
2944void
2945ProcessGDBRemote::KillDebugserverProcess ()
2946{
Greg Claytonfbb76342013-11-20 21:07:01 +00002947 m_gdb_comm.Disconnect();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002948 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2949 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002950 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002951 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2952 }
2953}
2954
2955void
2956ProcessGDBRemote::Initialize()
2957{
2958 static bool g_initialized = false;
2959
2960 if (g_initialized == false)
2961 {
2962 g_initialized = true;
2963 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2964 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00002965 CreateInstance,
2966 DebuggerInitialize);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002967 }
2968}
2969
Greg Clayton7f982402013-07-15 22:54:20 +00002970void
2971ProcessGDBRemote::DebuggerInitialize (lldb_private::Debugger &debugger)
2972{
2973 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
2974 {
2975 const bool is_global_setting = true;
2976 PluginManager::CreateSettingForProcessPlugin (debugger,
2977 GetGlobalPluginProperties()->GetValueProperties(),
2978 ConstString ("Properties for the gdb-remote process plug-in."),
2979 is_global_setting);
2980 }
2981}
2982
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002983bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002984ProcessGDBRemote::StartAsyncThread ()
2985{
Greg Clayton5160ce52013-03-27 23:08:40 +00002986 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002987
2988 if (log)
2989 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Ingham455fa5c2012-11-01 01:15:33 +00002990
2991 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00002992 if (!m_async_thread.IsJoinable())
Jim Ingham455fa5c2012-11-01 01:15:33 +00002993 {
2994 // Create a thread that watches our internal state and controls which
2995 // events make it to clients (into the DCProcess event queue).
Zachary Turner39de3112014-09-09 20:54:56 +00002996
2997 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Jim Ingham455fa5c2012-11-01 01:15:33 +00002998 }
Zachary Turneracee96a2014-09-23 18:32:09 +00002999 else if (log)
3000 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was already running.", __FUNCTION__);
Zachary Turner39de3112014-09-09 20:54:56 +00003001
Zachary Turneracee96a2014-09-23 18:32:09 +00003002 return m_async_thread.IsJoinable();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003003}
3004
3005void
3006ProcessGDBRemote::StopAsyncThread ()
3007{
Greg Clayton5160ce52013-03-27 23:08:40 +00003008 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003009
3010 if (log)
3011 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
3012
Jim Ingham455fa5c2012-11-01 01:15:33 +00003013 Mutex::Locker start_locker(m_async_thread_state_mutex);
Zachary Turneracee96a2014-09-23 18:32:09 +00003014 if (m_async_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003015 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00003016 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
3017
3018 // This will shut down the async thread.
3019 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3020
3021 // Stop the stdio thread
Zachary Turner39de3112014-09-09 20:54:56 +00003022 m_async_thread.Join(nullptr);
Pavel Labatha55a9532015-03-11 09:53:42 +00003023 m_async_thread.Reset();
Jim Ingham455fa5c2012-11-01 01:15:33 +00003024 }
Zachary Turneracee96a2014-09-23 18:32:09 +00003025 else if (log)
3026 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003027}
3028
3029
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003030thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003031ProcessGDBRemote::AsyncThread (void *arg)
3032{
3033 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
3034
Greg Clayton5160ce52013-03-27 23:08:40 +00003035 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003036 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003037 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003038
3039 Listener listener ("ProcessGDBRemote::AsyncThread");
3040 EventSP event_sp;
3041 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
3042 eBroadcastBitAsyncThreadShouldExit;
3043
3044 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
3045 {
Greg Clayton71337622011-02-24 22:24:29 +00003046 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
3047
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003048 bool done = false;
3049 while (!done)
3050 {
3051 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003052 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003053 if (listener.WaitForEvent (NULL, event_sp))
3054 {
3055 const uint32_t event_type = event_sp->GetType();
Greg Clayton71337622011-02-24 22:24:29 +00003056 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003057 {
Greg Clayton71337622011-02-24 22:24:29 +00003058 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003059 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 +00003060
Greg Clayton71337622011-02-24 22:24:29 +00003061 switch (event_type)
3062 {
3063 case eBroadcastBitAsyncContinue:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003064 {
Greg Clayton71337622011-02-24 22:24:29 +00003065 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003066
Greg Clayton71337622011-02-24 22:24:29 +00003067 if (continue_packet)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003068 {
Greg Clayton71337622011-02-24 22:24:29 +00003069 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
3070 const size_t continue_cstr_len = continue_packet->GetByteSize ();
3071 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003072 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003073
Greg Clayton71337622011-02-24 22:24:29 +00003074 if (::strstr (continue_cstr, "vAttach") == NULL)
3075 process->SetPrivateState(eStateRunning);
3076 StringExtractorGDBRemote response;
3077 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003078
Greg Clayton0772ded2012-05-16 02:48:06 +00003079 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
3080 // The thread ID list might be contained within the "response", or the stop reply packet that
3081 // caused the stop. So clear it now before we give the stop reply packet to the process
3082 // using the process->SetLastStopPacket()...
3083 process->ClearThreadIDList ();
3084
Greg Clayton71337622011-02-24 22:24:29 +00003085 switch (stop_state)
3086 {
3087 case eStateStopped:
3088 case eStateCrashed:
3089 case eStateSuspended:
Greg Clayton09c3e3d2011-12-06 04:51:14 +00003090 process->SetLastStopPacket (response);
Greg Clayton71337622011-02-24 22:24:29 +00003091 process->SetPrivateState (stop_state);
3092 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003093
Greg Clayton71337622011-02-24 22:24:29 +00003094 case eStateExited:
Jason Molendaa3329782014-03-29 18:54:20 +00003095 {
Greg Clayton09c3e3d2011-12-06 04:51:14 +00003096 process->SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00003097 process->ClearThreadIDList();
Greg Clayton71337622011-02-24 22:24:29 +00003098 response.SetFilePos(1);
Jason Molendaa3329782014-03-29 18:54:20 +00003099
3100 int exit_status = response.GetHexU8();
3101 const char *desc_cstr = NULL;
3102 StringExtractor extractor;
3103 std::string desc_string;
3104 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';')
3105 {
3106 std::string desc_token;
3107 while (response.GetNameColonValue (desc_token, desc_string))
3108 {
3109 if (desc_token == "description")
3110 {
3111 extractor.GetStringRef().swap(desc_string);
3112 extractor.SetFilePos(0);
3113 extractor.GetHexByteString (desc_string);
3114 desc_cstr = desc_string.c_str();
3115 }
3116 }
3117 }
3118 process->SetExitStatus(exit_status, desc_cstr);
Greg Clayton71337622011-02-24 22:24:29 +00003119 done = true;
3120 break;
Jason Molendaa3329782014-03-29 18:54:20 +00003121 }
Greg Clayton71337622011-02-24 22:24:29 +00003122 case eStateInvalid:
3123 process->SetExitStatus(-1, "lost connection");
3124 break;
3125
3126 default:
3127 process->SetPrivateState (stop_state);
3128 break;
3129 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003130 }
3131 }
Greg Clayton71337622011-02-24 22:24:29 +00003132 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003133
Greg Clayton71337622011-02-24 22:24:29 +00003134 case eBroadcastBitAsyncThreadShouldExit:
3135 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003136 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Clayton71337622011-02-24 22:24:29 +00003137 done = true;
3138 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003139
Greg Clayton71337622011-02-24 22:24:29 +00003140 default:
3141 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003142 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 +00003143 done = true;
3144 break;
3145 }
3146 }
3147 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
3148 {
3149 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
3150 {
3151 process->SetExitStatus (-1, "lost connection");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003152 done = true;
Greg Clayton71337622011-02-24 22:24:29 +00003153 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003154 }
3155 }
3156 else
3157 {
3158 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003159 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 +00003160 done = true;
3161 }
3162 }
3163 }
3164
3165 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003166 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003167
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003168 return NULL;
3169}
3170
Greg Claytone996fd32011-03-08 22:40:15 +00003171//uint32_t
3172//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3173//{
3174// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
3175// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
3176// if (m_local_debugserver)
3177// {
3178// return Host::ListProcessesMatchingName (name, matches, pids);
3179// }
3180// else
3181// {
3182// // FIXME: Implement talking to the remote debugserver.
3183// return 0;
3184// }
3185//
3186//}
3187//
Jim Ingham1c823b42011-01-22 01:33:44 +00003188bool
3189ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
3190 lldb_private::StoppointCallbackContext *context,
3191 lldb::user_id_t break_id,
3192 lldb::user_id_t break_loc_id)
3193{
3194 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3195 // run so I can stop it if that's what I want to do.
Greg Clayton5160ce52013-03-27 23:08:40 +00003196 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00003197 if (log)
3198 log->Printf("Hit New Thread Notification breakpoint.");
3199 return false;
3200}
3201
3202
3203bool
3204ProcessGDBRemote::StartNoticingNewThreads()
3205{
Greg Clayton5160ce52013-03-27 23:08:40 +00003206 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00003207 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003208 {
Greg Clayton4116e932012-05-15 02:33:01 +00003209 if (log && log->GetVerbose())
3210 log->Printf("Enabled noticing new thread breakpoint.");
3211 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003212 }
Greg Clayton4116e932012-05-15 02:33:01 +00003213 else
Jim Ingham1c823b42011-01-22 01:33:44 +00003214 {
Greg Clayton4116e932012-05-15 02:33:01 +00003215 PlatformSP platform_sp (m_target.GetPlatform());
3216 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003217 {
Greg Clayton4116e932012-05-15 02:33:01 +00003218 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3219 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003220 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00003221 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00003222 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3223 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003224 }
3225 else
3226 {
3227 if (log)
3228 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00003229 }
3230 }
3231 }
Greg Clayton4116e932012-05-15 02:33:01 +00003232 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00003233}
3234
3235bool
3236ProcessGDBRemote::StopNoticingNewThreads()
3237{
Greg Clayton5160ce52013-03-27 23:08:40 +00003238 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00003239 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00003240 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00003241
3242 if (m_thread_create_bp_sp)
3243 m_thread_create_bp_sp->SetEnabled(false);
3244
Jim Ingham1c823b42011-01-22 01:33:44 +00003245 return true;
3246}
3247
Jason Molenda5e8534e2012-10-03 01:29:34 +00003248lldb_private::DynamicLoader *
3249ProcessGDBRemote::GetDynamicLoader ()
3250{
3251 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00003252 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00003253 return m_dyld_ap.get();
3254}
Jim Ingham1c823b42011-01-22 01:33:44 +00003255
Jason Molendaa3329782014-03-29 18:54:20 +00003256Error
3257ProcessGDBRemote::SendEventData(const char *data)
3258{
3259 int return_value;
3260 bool was_supported;
3261
3262 Error error;
3263
3264 return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported);
3265 if (return_value != 0)
3266 {
3267 if (!was_supported)
3268 error.SetErrorString("Sending events is not supported for this process.");
3269 else
3270 error.SetErrorStringWithFormat("Error sending event data: %d.", return_value);
3271 }
3272 return error;
3273}
3274
Steve Pucci03904ac2014-03-04 23:18:46 +00003275const DataBufferSP
3276ProcessGDBRemote::GetAuxvData()
3277{
3278 DataBufferSP buf;
3279 if (m_gdb_comm.GetQXferAuxvReadSupported())
3280 {
3281 std::string response_string;
3282 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success)
3283 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length()));
3284 }
3285 return buf;
3286}
3287
Jason Molenda705b1802014-06-13 02:37:02 +00003288StructuredData::ObjectSP
3289ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid)
3290{
3291 StructuredData::ObjectSP object_sp;
3292
3293 if (m_gdb_comm.GetThreadExtendedInfoSupported())
3294 {
3295 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3296 SystemRuntime *runtime = GetSystemRuntime();
3297 if (runtime)
3298 {
3299 runtime->AddThreadExtendedInfoPacketHints (args_dict);
3300 }
3301 args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid);
3302
3303 StreamString packet;
3304 packet << "jThreadExtendedInfo:";
3305 args_dict->Dump (packet);
3306
3307 // FIXME the final character of a JSON dictionary, '}', is the escape
3308 // character in gdb-remote binary mode. lldb currently doesn't escape
3309 // these characters in its packet output -- so we add the quoted version
3310 // of the } character here manually in case we talk to a debugserver which
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003311 // un-escapes the characters at packet read time.
Jason Molenda705b1802014-06-13 02:37:02 +00003312 packet << (char) (0x7d ^ 0x20);
3313
3314 StringExtractorGDBRemote response;
3315 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
3316 {
3317 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
3318 if (response_type == StringExtractorGDBRemote::eResponse)
3319 {
3320 if (!response.Empty())
3321 {
3322 // The packet has already had the 0x7d xor quoting stripped out at the
3323 // GDBRemoteCommunication packet receive level.
3324 object_sp = StructuredData::ParseJSON (response.GetStringRef());
3325 }
3326 }
3327 }
3328 }
3329 return object_sp;
3330}
3331
Jason Molenda6076bf42014-05-06 04:34:52 +00003332// Establish the largest memory read/write payloads we should use.
3333// If the remote stub has a max packet size, stay under that size.
3334//
3335// If the remote stub's max packet size is crazy large, use a
3336// reasonable largeish default.
3337//
3338// If the remote stub doesn't advertise a max packet size, use a
3339// conservative default.
3340
3341void
3342ProcessGDBRemote::GetMaxMemorySize()
3343{
3344 const uint64_t reasonable_largeish_default = 128 * 1024;
3345 const uint64_t conservative_default = 512;
3346
3347 if (m_max_memory_size == 0)
3348 {
3349 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
3350 if (stub_max_size != UINT64_MAX && stub_max_size != 0)
3351 {
3352 // Save the stub's claimed maximum packet size
3353 m_remote_stub_max_memory_size = stub_max_size;
3354
3355 // Even if the stub says it can support ginormous packets,
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003356 // don't exceed our reasonable largeish default packet size.
Jason Molenda6076bf42014-05-06 04:34:52 +00003357 if (stub_max_size > reasonable_largeish_default)
3358 {
3359 stub_max_size = reasonable_largeish_default;
3360 }
3361
3362 m_max_memory_size = stub_max_size;
3363 }
3364 else
3365 {
3366 m_max_memory_size = conservative_default;
3367 }
3368 }
3369}
3370
3371void
3372ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max)
3373{
3374 if (user_specified_max != 0)
3375 {
3376 GetMaxMemorySize ();
3377
3378 if (m_remote_stub_max_memory_size != 0)
3379 {
3380 if (m_remote_stub_max_memory_size < user_specified_max)
3381 {
3382 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a packet size too big, go as big
3383 // as the remote stub says we can go.
3384 }
3385 else
3386 {
3387 m_max_memory_size = user_specified_max; // user's packet size is good
3388 }
3389 }
3390 else
3391 {
3392 m_max_memory_size = user_specified_max; // user's packet size is probably fine
3393 }
3394 }
3395}
3396
Greg Clayton02686b82012-10-15 22:42:16 +00003397class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00003398{
3399private:
3400
3401public:
Greg Clayton02686b82012-10-15 22:42:16 +00003402 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00003403 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00003404 "process plugin packet history",
3405 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00003406 NULL)
3407 {
3408 }
3409
Greg Clayton02686b82012-10-15 22:42:16 +00003410 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton998255b2012-10-13 02:07:45 +00003411 {
3412 }
3413
3414 bool
3415 DoExecute (Args& command, CommandReturnObject &result)
3416 {
Greg Clayton02686b82012-10-15 22:42:16 +00003417 const size_t argc = command.GetArgumentCount();
3418 if (argc == 0)
3419 {
3420 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3421 if (process)
3422 {
3423 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
3424 result.SetStatus (eReturnStatusSuccessFinishResult);
3425 return true;
3426 }
3427 }
3428 else
3429 {
3430 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
3431 }
3432 result.SetStatus (eReturnStatusFailed);
3433 return false;
3434 }
3435};
3436
Jason Molenda6076bf42014-05-06 04:34:52 +00003437class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed
3438{
3439private:
3440
3441public:
3442 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) :
3443 CommandObjectParsed (interpreter,
3444 "process plugin packet xfer-size",
3445 "Maximum size that lldb will try to read/write one one chunk.",
3446 NULL)
3447 {
3448 }
3449
3450 ~CommandObjectProcessGDBRemotePacketXferSize ()
3451 {
3452 }
3453
3454 bool
3455 DoExecute (Args& command, CommandReturnObject &result)
3456 {
3457 const size_t argc = command.GetArgumentCount();
3458 if (argc == 0)
3459 {
3460 result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str());
3461 result.SetStatus (eReturnStatusFailed);
3462 return false;
3463 }
3464
3465 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3466 if (process)
3467 {
3468 const char *packet_size = command.GetArgumentAtIndex(0);
3469 errno = 0;
3470 uint64_t user_specified_max = strtoul (packet_size, NULL, 10);
3471 if (errno == 0 && user_specified_max != 0)
3472 {
3473 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max);
3474 result.SetStatus (eReturnStatusSuccessFinishResult);
3475 return true;
3476 }
3477 }
3478 result.SetStatus (eReturnStatusFailed);
3479 return false;
3480 }
3481};
3482
3483
Greg Clayton02686b82012-10-15 22:42:16 +00003484class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
3485{
3486private:
3487
3488public:
3489 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
3490 CommandObjectParsed (interpreter,
3491 "process plugin packet send",
3492 "Send a custom packet through the GDB remote protocol and print the answer. "
3493 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
3494 NULL)
3495 {
3496 }
3497
3498 ~CommandObjectProcessGDBRemotePacketSend ()
3499 {
3500 }
3501
3502 bool
3503 DoExecute (Args& command, CommandReturnObject &result)
3504 {
3505 const size_t argc = command.GetArgumentCount();
3506 if (argc == 0)
3507 {
3508 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
3509 result.SetStatus (eReturnStatusFailed);
3510 return false;
3511 }
3512
3513 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3514 if (process)
3515 {
Han Ming Ong84145852012-11-26 20:42:03 +00003516 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00003517 {
Han Ming Ong84145852012-11-26 20:42:03 +00003518 const char *packet_cstr = command.GetArgumentAtIndex(0);
3519 bool send_async = true;
3520 StringExtractorGDBRemote response;
3521 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3522 result.SetStatus (eReturnStatusSuccessFinishResult);
3523 Stream &output_strm = result.GetOutputStream();
3524 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00003525 std::string &response_str = response.GetStringRef();
3526
Han Ming Ong399289e2013-06-21 19:56:59 +00003527 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00003528 {
3529 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
3530 }
3531
Han Ming Ong84145852012-11-26 20:42:03 +00003532 if (response_str.empty())
3533 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3534 else
3535 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00003536 }
Greg Clayton02686b82012-10-15 22:42:16 +00003537 }
Greg Clayton998255b2012-10-13 02:07:45 +00003538 return true;
3539 }
3540};
3541
Greg Claytonba4a0a52013-02-01 23:03:47 +00003542class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
3543{
3544private:
3545
3546public:
3547 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
3548 CommandObjectRaw (interpreter,
3549 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00003550 "Send a qRcmd packet through the GDB remote protocol and print the response."
3551 "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 +00003552 NULL)
3553 {
3554 }
3555
3556 ~CommandObjectProcessGDBRemotePacketMonitor ()
3557 {
3558 }
3559
3560 bool
3561 DoExecute (const char *command, CommandReturnObject &result)
3562 {
3563 if (command == NULL || command[0] == '\0')
3564 {
3565 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
3566 result.SetStatus (eReturnStatusFailed);
3567 return false;
3568 }
3569
3570 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3571 if (process)
3572 {
3573 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00003574 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00003575 packet.PutBytesAsRawHex8(command, strlen(command));
3576 const char *packet_cstr = packet.GetString().c_str();
3577
3578 bool send_async = true;
3579 StringExtractorGDBRemote response;
3580 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3581 result.SetStatus (eReturnStatusSuccessFinishResult);
3582 Stream &output_strm = result.GetOutputStream();
3583 output_strm.Printf (" packet: %s\n", packet_cstr);
3584 const std::string &response_str = response.GetStringRef();
3585
3586 if (response_str.empty())
3587 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3588 else
3589 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
3590 }
3591 return true;
3592 }
3593};
3594
Greg Clayton02686b82012-10-15 22:42:16 +00003595class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
3596{
3597private:
3598
3599public:
3600 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
3601 CommandObjectMultiword (interpreter,
3602 "process plugin packet",
3603 "Commands that deal with GDB remote packets.",
3604 NULL)
3605 {
3606 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
3607 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00003608 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Jason Molenda6076bf42014-05-06 04:34:52 +00003609 LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00003610 }
3611
3612 ~CommandObjectProcessGDBRemotePacket ()
3613 {
3614 }
3615};
Greg Clayton998255b2012-10-13 02:07:45 +00003616
3617class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
3618{
3619public:
3620 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
3621 CommandObjectMultiword (interpreter,
3622 "process plugin",
3623 "A set of commands for operating on a ProcessGDBRemote process.",
3624 "process plugin <subcommand> [<subcommand-options>]")
3625 {
3626 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
3627 }
3628
3629 ~CommandObjectMultiwordProcessGDBRemote ()
3630 {
3631 }
3632};
3633
Greg Clayton998255b2012-10-13 02:07:45 +00003634CommandObject *
3635ProcessGDBRemote::GetPluginCommandObject()
3636{
3637 if (!m_command_sp)
3638 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
3639 return m_command_sp.get();
3640}