blob: 0cb2e144d86f62ddfe18a98f6c4f7f29c2c22748 [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
17#include <spawn.h>
Sean Callanan224f6f52012-07-19 18:07:36 +000018#include <netinet/in.h>
Greg Clayton2a48f522011-05-14 01:50:35 +000019#include <sys/mman.h> // for mmap
Virgile Bellob2f1fb22013-08-23 12:44:05 +000020#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000021#include <sys/stat.h>
Greg Clayton2a48f522011-05-14 01:50:35 +000022#include <sys/types.h>
Stephen Wilsondc916862011-03-30 00:12:40 +000023#include <time.h>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000024
25// C++ Includes
26#include <algorithm>
27#include <map>
28
29// Other libraries and framework includes
30
Johnny Chen01a67862011-10-14 00:42:25 +000031#include "lldb/Breakpoint/Watchpoint.h"
Jim Ingham40af72e2010-06-15 19:49:27 +000032#include "lldb/Interpreter/Args.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000033#include "lldb/Core/ArchSpec.h"
34#include "lldb/Core/Debugger.h"
35#include "lldb/Core/ConnectionFileDescriptor.h"
Greg Clayton53239f02011-02-08 05:05:52 +000036#include "lldb/Host/FileSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000037#include "lldb/Core/Module.h"
Greg Clayton1f746072012-08-29 21:13:06 +000038#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000039#include "lldb/Core/PluginManager.h"
40#include "lldb/Core/State.h"
Greg Claytond451c1a2012-04-13 21:24:18 +000041#include "lldb/Core/StreamFile.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000042#include "lldb/Core/StreamString.h"
43#include "lldb/Core/Timer.h"
Greg Clayton70b57652011-05-15 01:25:55 +000044#include "lldb/Core/Value.h"
Jason Molendad1fae142012-09-29 08:03:33 +000045#include "lldb/Host/Symbols.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000046#include "lldb/Host/TimeValue.h"
Greg Clayton02686b82012-10-15 22:42:16 +000047#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton1d19a2f2012-10-19 22:22:57 +000048#include "lldb/Interpreter/CommandObject.h"
49#include "lldb/Interpreter/CommandObjectMultiword.h"
Greg Clayton02686b82012-10-15 22:42:16 +000050#include "lldb/Interpreter/CommandReturnObject.h"
Joerg Sonnenbergere77b0422013-10-20 17:36:05 +000051#ifndef LLDB_DISABLE_PYTHON
Greg Claytonef8180a2013-10-15 00:14:28 +000052#include "lldb/Interpreter/PythonDataObjects.h"
Joerg Sonnenbergere77b0422013-10-20 17:36:05 +000053#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000054#include "lldb/Symbol/ObjectFile.h"
55#include "lldb/Target/DynamicLoader.h"
56#include "lldb/Target/Target.h"
57#include "lldb/Target/TargetList.h"
Greg Clayton2a48f522011-05-14 01:50:35 +000058#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molenda705b1802014-06-13 02:37:02 +000059#include "lldb/Target/SystemRuntime.h"
Jason Molendaa34a0c62010-06-09 21:28:42 +000060#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000061
62// Project includes
63#include "lldb/Host/Host.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000064#include "Plugins/Process/Utility/FreeBSDSignals.h"
Peter Collingbourne99f9aa02011-06-03 20:40:38 +000065#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000066#include "Plugins/Process/Utility/LinuxSignals.h"
Jason Molendac42d2432012-07-25 03:40:06 +000067#include "Plugins/Process/Utility/StopInfoMachException.h"
Jim Ingham43c555d2012-07-04 00:35:43 +000068#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
Greg Claytonc982c762010-07-09 20:39:50 +000069#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000070#include "GDBRemoteRegisterContext.h"
71#include "ProcessGDBRemote.h"
72#include "ProcessGDBRemoteLog.h"
73#include "ThreadGDBRemote.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000074
Jason Molenda5e8534e2012-10-03 01:29:34 +000075
Greg Claytonc1422c12012-04-09 22:46:21 +000076namespace lldb
77{
78 // Provide a function that can easily dump the packet history if we know a
79 // ProcessGDBRemote * value (which we can get from logs or from debugging).
80 // We need the function in the lldb namespace so it makes it into the final
81 // executable since the LLDB shared library only exports stuff in the lldb
82 // namespace. This allows you to attach with a debugger and call this
83 // function and get the packet history dumped to a file.
84 void
85 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
86 {
Greg Claytond451c1a2012-04-13 21:24:18 +000087 lldb_private::StreamFile strm;
88 lldb_private::Error error (strm.GetFile().Open(path, lldb_private::File::eOpenOptionWrite | lldb_private::File::eOpenOptionCanCreate));
89 if (error.Success())
90 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
Greg Claytonc1422c12012-04-09 22:46:21 +000091 }
Filipe Cabecinhasc34f7762012-05-23 16:27:09 +000092}
Chris Lattner30fdc8d2010-06-08 16:52:24 +000093
Chris Lattner30fdc8d2010-06-08 16:52:24 +000094#define DEBUGSERVER_BASENAME "debugserver"
95using namespace lldb;
96using namespace lldb_private;
97
Greg Clayton7f982402013-07-15 22:54:20 +000098
99namespace {
Steve Pucci5ec012d2014-01-16 22:18:14 +0000100
Greg Clayton7f982402013-07-15 22:54:20 +0000101 static PropertyDefinition
102 g_properties[] =
103 {
104 { "packet-timeout" , OptionValue::eTypeUInt64 , true , 1, NULL, NULL, "Specify the default packet timeout in seconds." },
Greg Claytonef8180a2013-10-15 00:14:28 +0000105 { "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 +0000106 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
107 };
108
109 enum
110 {
Greg Claytonef8180a2013-10-15 00:14:28 +0000111 ePropertyPacketTimeout,
112 ePropertyTargetDefinitionFile
Greg Clayton7f982402013-07-15 22:54:20 +0000113 };
114
115 class PluginProperties : public Properties
116 {
117 public:
118
119 static ConstString
120 GetSettingName ()
121 {
122 return ProcessGDBRemote::GetPluginNameStatic();
123 }
124
125 PluginProperties() :
126 Properties ()
127 {
128 m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
129 m_collection_sp->Initialize(g_properties);
130 }
131
132 virtual
133 ~PluginProperties()
134 {
135 }
136
137 uint64_t
138 GetPacketTimeout()
139 {
140 const uint32_t idx = ePropertyPacketTimeout;
141 return m_collection_sp->GetPropertyAtIndexAsUInt64(NULL, idx, g_properties[idx].default_uint_value);
142 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000143
144 bool
145 SetPacketTimeout(uint64_t timeout)
146 {
147 const uint32_t idx = ePropertyPacketTimeout;
148 return m_collection_sp->SetPropertyAtIndexAsUInt64(NULL, idx, timeout);
149 }
150
Greg Claytonef8180a2013-10-15 00:14:28 +0000151 FileSpec
152 GetTargetDefinitionFile () const
153 {
154 const uint32_t idx = ePropertyTargetDefinitionFile;
155 return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
156 }
Greg Clayton7f982402013-07-15 22:54:20 +0000157 };
158
159 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
160
161 static const ProcessKDPPropertiesSP &
162 GetGlobalPluginProperties()
163 {
164 static ProcessKDPPropertiesSP g_settings_sp;
165 if (!g_settings_sp)
166 g_settings_sp.reset (new PluginProperties ());
167 return g_settings_sp;
168 }
169
170} // anonymous namespace end
171
Greg Claytonfda4fab2014-01-10 22:24:11 +0000172// TODO Randomly assigning a port is unsafe. We should get an unused
173// ephemeral port from the kernel and make sure we reserve it before passing
174// it to debugserver.
175
176#if defined (__APPLE__)
177#define LOW_PORT (IPPORT_RESERVED)
178#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
179#else
180#define LOW_PORT (1024u)
181#define HIGH_PORT (49151u)
182#endif
183
Todd Fiala013434e2014-07-09 01:29:05 +0000184#if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000185static bool rand_initialized = false;
186
Greg Claytonfda4fab2014-01-10 22:24:11 +0000187static inline uint16_t
188get_random_port ()
189{
190 if (!rand_initialized)
191 {
192 time_t seed = time(NULL);
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000193
Greg Claytonfda4fab2014-01-10 22:24:11 +0000194 rand_initialized = true;
195 srand(seed);
196 }
197 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
198}
Saleem Abdulrasoola68f7b62014-03-20 06:08:36 +0000199#endif
Greg Claytonfda4fab2014-01-10 22:24:11 +0000200
Greg Clayton57abc5d2013-05-10 21:47:16 +0000201lldb_private::ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000202ProcessGDBRemote::GetPluginNameStatic()
203{
Greg Clayton57abc5d2013-05-10 21:47:16 +0000204 static ConstString g_name("gdb-remote");
205 return g_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000206}
207
208const char *
209ProcessGDBRemote::GetPluginDescriptionStatic()
210{
211 return "GDB Remote protocol based debugging plug-in.";
212}
213
214void
215ProcessGDBRemote::Terminate()
216{
217 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
218}
219
220
Greg Claytonc3776bf2012-02-09 06:16:32 +0000221lldb::ProcessSP
222ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000223{
Greg Claytonc3776bf2012-02-09 06:16:32 +0000224 lldb::ProcessSP process_sp;
225 if (crash_file_path == NULL)
226 process_sp.reset (new ProcessGDBRemote (target, listener));
227 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000228}
229
230bool
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000231ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000232{
Greg Clayton596ed242011-10-21 21:41:45 +0000233 if (plugin_specified_by_name)
234 return true;
235
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000236 // For now we are just making sure the file exists for a given module
Greg Claytonaa149cb2011-08-11 02:48:45 +0000237 Module *exe_module = target.GetExecutableModulePointer();
238 if (exe_module)
Greg Claytonc3776bf2012-02-09 06:16:32 +0000239 {
240 ObjectFile *exe_objfile = exe_module->GetObjectFile();
241 // We can't debug core files...
242 switch (exe_objfile->GetType())
243 {
244 case ObjectFile::eTypeInvalid:
245 case ObjectFile::eTypeCoreFile:
246 case ObjectFile::eTypeDebugInfo:
247 case ObjectFile::eTypeObjectFile:
248 case ObjectFile::eTypeSharedLibrary:
249 case ObjectFile::eTypeStubLibrary:
Greg Clayton23f8c952014-03-24 23:10:19 +0000250 case ObjectFile::eTypeJIT:
Greg Claytonc3776bf2012-02-09 06:16:32 +0000251 return false;
252 case ObjectFile::eTypeExecutable:
253 case ObjectFile::eTypeDynamicLinker:
254 case ObjectFile::eTypeUnknown:
255 break;
256 }
Greg Claytonaa149cb2011-08-11 02:48:45 +0000257 return exe_module->GetFileSpec().Exists();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000258 }
Jim Ingham5aee1622010-08-09 23:31:02 +0000259 // However, if there is no executable module, we return true since we might be preparing to attach.
260 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000261}
262
263//----------------------------------------------------------------------
264// ProcessGDBRemote constructor
265//----------------------------------------------------------------------
266ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
267 Process (target, listener),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000268 m_flags (0),
Greg Clayton8b82f082011-04-12 05:54:46 +0000269 m_gdb_comm(false),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000270 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Claytonc982c762010-07-09 20:39:50 +0000271 m_last_stop_packet (),
Greg Clayton09c3e3d2011-12-06 04:51:14 +0000272 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000273 m_register_info (),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000274 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000275 m_async_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham455fa5c2012-11-01 01:15:33 +0000276 m_async_thread_state(eAsyncThreadNotStarted),
277 m_async_thread_state_mutex(Mutex::eMutexTypeRecursive),
Greg Clayton9e920902012-04-10 02:25:43 +0000278 m_thread_ids (),
Greg Clayton71fc2a32011-02-12 06:28:37 +0000279 m_continue_c_tids (),
280 m_continue_C_tids (),
281 m_continue_s_tids (),
282 m_continue_S_tids (),
Jason Molenda6076bf42014-05-06 04:34:52 +0000283 m_max_memory_size (0),
284 m_remote_stub_max_memory_size (0),
Greg Clayton4116e932012-05-15 02:33:01 +0000285 m_addr_to_mmap_size (),
286 m_thread_create_bp_sp (),
Jim Ingham43c555d2012-07-04 00:35:43 +0000287 m_waiting_for_attach (false),
Jason Molenda5e8534e2012-10-03 01:29:34 +0000288 m_destroy_tried_resuming (false),
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000289 m_command_sp (),
Todd Fialaaf245d12014-06-30 21:05:18 +0000290 m_breakpoint_pc_offset (0),
291 m_unix_signals_sp (new UnixSignals ())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000292{
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000293 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
294 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Inghamb1e2e842012-04-12 18:49:31 +0000295 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Greg Clayton7f982402013-07-15 22:54:20 +0000296 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
297 if (timeout_seconds > 0)
298 m_gdb_comm.SetPacketTimeout(timeout_seconds);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000299}
300
301//----------------------------------------------------------------------
302// Destructor
303//----------------------------------------------------------------------
304ProcessGDBRemote::~ProcessGDBRemote()
305{
306 // m_mach_process.UnregisterNotificationCallbacks (this);
307 Clear();
Greg Clayton1ed54f52011-10-01 00:45:15 +0000308 // We need to call finalize on the process before destroying ourselves
309 // to make sure all of the broadcaster cleanup goes as planned. If we
310 // destruct this class, then Process::~Process() might have problems
311 // trying to fully destroy the broadcaster.
312 Finalize();
Jim Ingham455fa5c2012-11-01 01:15:33 +0000313
314 // The general Finalize is going to try to destroy the process and that SHOULD
315 // shut down the async thread. However, if we don't kill it it will get stranded and
316 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
317 StopAsyncThread();
318 KillDebugserverProcess();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000319}
320
321//----------------------------------------------------------------------
322// PluginInterface
323//----------------------------------------------------------------------
Greg Clayton57abc5d2013-05-10 21:47:16 +0000324ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000325ProcessGDBRemote::GetPluginName()
326{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000327 return GetPluginNameStatic();
328}
329
330uint32_t
331ProcessGDBRemote::GetPluginVersion()
332{
333 return 1;
334}
335
Greg Claytonef8180a2013-10-15 00:14:28 +0000336bool
337ProcessGDBRemote::ParsePythonTargetDefinition(const FileSpec &target_definition_fspec)
338{
Joerg Sonnenbergere77b0422013-10-20 17:36:05 +0000339#ifndef LLDB_DISABLE_PYTHON
Greg Claytonef8180a2013-10-15 00:14:28 +0000340 ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
341 Error error;
342 lldb::ScriptInterpreterObjectSP module_object_sp (interpreter->LoadPluginModule(target_definition_fspec, error));
343 if (module_object_sp)
344 {
345 lldb::ScriptInterpreterObjectSP target_definition_sp (interpreter->GetDynamicSettings(module_object_sp,
346 &GetTarget(),
347 "gdb-server-target-definition",
348 error));
349
350 PythonDictionary target_dict(target_definition_sp);
351
352 if (target_dict)
353 {
Greg Clayton312bcbe2013-10-17 01:10:23 +0000354 PythonDictionary host_info_dict (target_dict.GetItemForKey("host-info"));
355 if (host_info_dict)
356 {
357 ArchSpec host_arch (host_info_dict.GetItemForKeyAsString(PythonString("triple")));
358
359 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture()))
360 {
361 GetTarget().SetArchitecture(host_arch);
362 }
363
364 }
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000365 m_breakpoint_pc_offset = target_dict.GetItemForKeyAsInteger("breakpoint-pc-offset", 0);
366
Greg Clayton312bcbe2013-10-17 01:10:23 +0000367 if (m_register_info.SetRegisterInfo (target_dict, GetTarget().GetArchitecture().GetByteOrder()) > 0)
Greg Claytonef8180a2013-10-15 00:14:28 +0000368 {
369 return true;
370 }
371 }
372 }
Joerg Sonnenbergere77b0422013-10-20 17:36:05 +0000373#endif
Greg Claytonef8180a2013-10-15 00:14:28 +0000374 return false;
375}
376
377
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000378void
Greg Clayton513c26c2011-01-29 07:10:55 +0000379ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000380{
Greg Clayton513c26c2011-01-29 07:10:55 +0000381 if (!force && m_register_info.GetNumRegisters() > 0)
382 return;
383
384 char packet[128];
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000385 m_register_info.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000386 uint32_t reg_offset = 0;
387 uint32_t reg_num = 0;
Greg Clayton23f59502012-07-17 03:23:13 +0000388 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Greg Clayton576d8832011-03-22 04:00:09 +0000389 response_type == StringExtractorGDBRemote::eResponse;
390 ++reg_num)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000391 {
Greg Clayton513c26c2011-01-29 07:10:55 +0000392 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
Andy Gibbsa297a972013-06-19 19:04:53 +0000393 assert (packet_len < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000394 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000395 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000396 {
Greg Clayton576d8832011-03-22 04:00:09 +0000397 response_type = response.GetResponseType();
398 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000399 {
400 std::string name;
401 std::string value;
402 ConstString reg_name;
403 ConstString alt_name;
404 ConstString set_name;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000405 std::vector<uint32_t> value_regs;
406 std::vector<uint32_t> invalidate_regs;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000407 RegisterInfo reg_info = { NULL, // Name
408 NULL, // Alt name
409 0, // byte size
410 reg_offset, // offset
411 eEncodingUint, // encoding
412 eFormatHex, // formate
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000413 {
414 LLDB_INVALID_REGNUM, // GCC reg num
415 LLDB_INVALID_REGNUM, // DWARF reg num
416 LLDB_INVALID_REGNUM, // generic reg num
Jason Molendafbcb7f22010-09-10 07:49:16 +0000417 reg_num, // GDB reg num
418 reg_num // native register number
Greg Clayton435d85a2012-02-29 19:27:27 +0000419 },
420 NULL,
421 NULL
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000422 };
423
424 while (response.GetNameColonValue(name, value))
425 {
426 if (name.compare("name") == 0)
427 {
428 reg_name.SetCString(value.c_str());
429 }
430 else if (name.compare("alt-name") == 0)
431 {
432 alt_name.SetCString(value.c_str());
433 }
434 else if (name.compare("bitsize") == 0)
435 {
436 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
437 }
438 else if (name.compare("offset") == 0)
439 {
440 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda743e86a2010-06-11 23:44:18 +0000441 if (reg_offset != offset)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000442 {
443 reg_offset = offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000444 }
445 }
446 else if (name.compare("encoding") == 0)
447 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000448 const Encoding encoding = Args::StringToEncoding (value.c_str());
449 if (encoding != eEncodingInvalid)
450 reg_info.encoding = encoding;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000451 }
452 else if (name.compare("format") == 0)
453 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000454 Format format = eFormatInvalid;
455 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
456 reg_info.format = format;
457 else if (value.compare("binary") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000458 reg_info.format = eFormatBinary;
459 else if (value.compare("decimal") == 0)
460 reg_info.format = eFormatDecimal;
461 else if (value.compare("hex") == 0)
462 reg_info.format = eFormatHex;
463 else if (value.compare("float") == 0)
464 reg_info.format = eFormatFloat;
465 else if (value.compare("vector-sint8") == 0)
466 reg_info.format = eFormatVectorOfSInt8;
467 else if (value.compare("vector-uint8") == 0)
468 reg_info.format = eFormatVectorOfUInt8;
469 else if (value.compare("vector-sint16") == 0)
470 reg_info.format = eFormatVectorOfSInt16;
471 else if (value.compare("vector-uint16") == 0)
472 reg_info.format = eFormatVectorOfUInt16;
473 else if (value.compare("vector-sint32") == 0)
474 reg_info.format = eFormatVectorOfSInt32;
475 else if (value.compare("vector-uint32") == 0)
476 reg_info.format = eFormatVectorOfUInt32;
477 else if (value.compare("vector-float32") == 0)
478 reg_info.format = eFormatVectorOfFloat32;
479 else if (value.compare("vector-uint128") == 0)
480 reg_info.format = eFormatVectorOfUInt128;
481 }
482 else if (name.compare("set") == 0)
483 {
484 set_name.SetCString(value.c_str());
485 }
486 else if (name.compare("gcc") == 0)
487 {
488 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
489 }
490 else if (name.compare("dwarf") == 0)
491 {
492 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
493 }
494 else if (name.compare("generic") == 0)
495 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000496 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000497 }
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000498 else if (name.compare("container-regs") == 0)
499 {
500 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
501 value_pair.second = value;
502 do
503 {
504 value_pair = value_pair.second.split(',');
505 if (!value_pair.first.empty())
506 {
Greg Clayton0ba20242013-01-21 23:32:42 +0000507 uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
508 if (reg != LLDB_INVALID_REGNUM)
509 value_regs.push_back (reg);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000510 }
511 } while (!value_pair.second.empty());
512 }
513 else if (name.compare("invalidate-regs") == 0)
514 {
515 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
516 value_pair.second = value;
517 do
518 {
519 value_pair = value_pair.second.split(',');
520 if (!value_pair.first.empty())
521 {
Greg Clayton0ba20242013-01-21 23:32:42 +0000522 uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
523 if (reg != LLDB_INVALID_REGNUM)
524 invalidate_regs.push_back (reg);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000525 }
526 } while (!value_pair.second.empty());
527 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000528 }
529
Jason Molenda743e86a2010-06-11 23:44:18 +0000530 reg_info.byte_offset = reg_offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000531 assert (reg_info.byte_size != 0);
532 reg_offset += reg_info.byte_size;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000533 if (!value_regs.empty())
534 {
535 value_regs.push_back(LLDB_INVALID_REGNUM);
536 reg_info.value_regs = value_regs.data();
537 }
538 if (!invalidate_regs.empty())
539 {
540 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
541 reg_info.invalidate_regs = invalidate_regs.data();
542 }
543
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000544 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
545 }
Todd Fiala1a634402014-01-08 07:52:40 +0000546 else
547 {
548 break; // ensure exit before reg_num is incremented
549 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000550 }
551 else
552 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000553 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000554 }
555 }
556
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000557 // Check if qHostInfo specified a specific packet timeout for this connection.
558 // If so then lets update our setting so the user knows what the timeout is
559 // and can see it.
560 const uint32_t host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
561 if (host_packet_timeout)
562 {
563 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout);
564 }
565
566
Greg Claytonef8180a2013-10-15 00:14:28 +0000567 if (reg_num == 0)
568 {
569 FileSpec target_definition_fspec = GetGlobalPluginProperties()->GetTargetDefinitionFile ();
Greg Clayton312bcbe2013-10-17 01:10:23 +0000570
571 if (target_definition_fspec)
Greg Claytonef8180a2013-10-15 00:14:28 +0000572 {
Greg Clayton312bcbe2013-10-17 01:10:23 +0000573 // See if we can get register definitions from a python file
574 if (ParsePythonTargetDefinition (target_definition_fspec))
575 return;
Greg Claytonef8180a2013-10-15 00:14:28 +0000576 }
577 }
578
Johnny Chen2fa9de12012-05-14 18:44:23 +0000579 // We didn't get anything if the accumulated reg_num is zero. See if we are
580 // debugging ARM and fill with a hard coded register set until we can get an
581 // updated debugserver down on the devices.
582 // On the other hand, if the accumulated reg_num is positive, see if we can
583 // add composite registers to the existing primordial ones.
584 bool from_scratch = (reg_num == 0);
585
586 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000587 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
588 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
589
590 // Use the process' architecture instead of the host arch, if available
591 ArchSpec remote_arch;
592 if (remote_process_arch.IsValid ())
593 remote_arch = remote_process_arch;
594 else
595 remote_arch = remote_host_arch;
596
Johnny Chen2fa9de12012-05-14 18:44:23 +0000597 if (!target_arch.IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000598 {
Johnny Chen2fa9de12012-05-14 18:44:23 +0000599 if (remote_arch.IsValid()
600 && remote_arch.GetMachine() == llvm::Triple::arm
601 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
602 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000603 }
Johnny Chen2fa9de12012-05-14 18:44:23 +0000604 else if (target_arch.GetMachine() == llvm::Triple::arm)
605 {
606 m_register_info.HardcodeARMRegisters(from_scratch);
607 }
608
609 // At this point, we can finalize our register info.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000610 m_register_info.Finalize ();
611}
612
613Error
614ProcessGDBRemote::WillLaunch (Module* module)
615{
616 return WillLaunchOrAttach ();
617}
618
619Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000620ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000621{
622 return WillLaunchOrAttach ();
623}
624
625Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000626ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000627{
628 return WillLaunchOrAttach ();
629}
630
631Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000632ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +0000633{
Todd Fialaaf245d12014-06-30 21:05:18 +0000634 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Claytonb766a732011-02-04 01:58:07 +0000635 Error error (WillLaunchOrAttach ());
636
637 if (error.Fail())
638 return error;
639
Greg Clayton2289fa42011-04-30 01:09:13 +0000640 error = ConnectToDebugserver (remote_url);
Greg Claytonb766a732011-02-04 01:58:07 +0000641
642 if (error.Fail())
643 return error;
644 StartAsyncThread ();
645
Greg Claytonc574ede2011-03-10 02:26:48 +0000646 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonb766a732011-02-04 01:58:07 +0000647 if (pid == LLDB_INVALID_PROCESS_ID)
648 {
649 // We don't have a valid process ID, so note that we are connected
650 // and could now request to launch or attach, or get remote process
651 // listings...
652 SetPrivateState (eStateConnected);
653 }
654 else
655 {
656 // We have a valid process
657 SetID (pid);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000658 GetThreadList();
Greg Clayton3dedae12013-12-06 21:45:27 +0000659 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false) == GDBRemoteCommunication::PacketResult::Success)
Greg Claytonb766a732011-02-04 01:58:07 +0000660 {
Jason Molendac62bd7b2013-12-21 05:20:36 +0000661 if (!m_target.GetArchitecture().IsValid())
662 {
663 if (m_gdb_comm.GetProcessArchitecture().IsValid())
664 {
665 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
666 }
667 else
668 {
669 m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
670 }
Carlo Kok74389122013-10-14 07:09:13 +0000671 }
672
Greg Claytondd0e5a52011-06-02 22:22:38 +0000673 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytonb766a732011-02-04 01:58:07 +0000674 if (state == eStateStopped)
675 {
676 SetPrivateState (state);
677 }
678 else
Daniel Malead01b2952012-11-29 21:49:15 +0000679 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 +0000680 }
681 else
Daniel Malead01b2952012-11-29 21:49:15 +0000682 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 +0000683 }
Jason Molenda16d127c2012-05-03 22:37:30 +0000684
Todd Fialaaf245d12014-06-30 21:05:18 +0000685 if (log)
686 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");
687
688
689 if (error.Success()
Jason Molenda16d127c2012-05-03 22:37:30 +0000690 && !GetTarget().GetArchitecture().IsValid()
691 && m_gdb_comm.GetHostArchitecture().IsValid())
692 {
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000693 // Prefer the *process'* architecture over that of the *host*, if available.
694 if (m_gdb_comm.GetProcessArchitecture().IsValid())
695 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
696 else
697 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molenda16d127c2012-05-03 22:37:30 +0000698 }
699
Todd Fialaaf245d12014-06-30 21:05:18 +0000700 if (log)
701 log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": normalized target architecture triple: %s", __FUNCTION__, GetID (), GetTarget ().GetArchitecture ().GetTriple ().getTriple ().c_str ());
702
703 // Set the Unix signals properly for the target.
704 // FIXME Add a gdb-remote packet to discover dynamically.
705 if (error.Success ())
706 {
707 const ArchSpec arch_spec = GetTarget ().GetArchitecture ();
708 if (arch_spec.IsValid ())
709 {
710 if (log)
711 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 ());
712
713 switch (arch_spec.GetTriple ().getOS ())
714 {
715 case llvm::Triple::Linux:
716 m_unix_signals_sp.reset (new process_linux::LinuxSignals ());
717 if (log)
718 log->Printf ("ProcessGDBRemote::%s using Linux unix signals type for pid %" PRIu64, __FUNCTION__, GetID ());
719 break;
720 case llvm::Triple::OpenBSD:
721 case llvm::Triple::FreeBSD:
722 case llvm::Triple::NetBSD:
723 m_unix_signals_sp.reset (new FreeBSDSignals ());
724 if (log)
725 log->Printf ("ProcessGDBRemote::%s using *BSD unix signals type for pid %" PRIu64, __FUNCTION__, GetID ());
726 break;
727 default:
728 m_unix_signals_sp.reset (new UnixSignals ());
729 if (log)
730 log->Printf ("ProcessGDBRemote::%s using generic unix signals type for pid %" PRIu64, __FUNCTION__, GetID ());
731 break;
732 }
733 }
734 }
735
Greg Claytonb766a732011-02-04 01:58:07 +0000736 return error;
737}
738
739Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000740ProcessGDBRemote::WillLaunchOrAttach ()
741{
742 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000743 m_stdio_communication.Clear ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000744 return error;
745}
746
747//----------------------------------------------------------------------
748// Process Control
749//----------------------------------------------------------------------
750Error
Jean-Daniel Dupas7782de92013-12-09 22:52:50 +0000751ProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000752{
Greg Clayton4957bf62010-09-30 21:49:03 +0000753 Error error;
Greg Clayton982c9762011-11-03 21:22:33 +0000754
755 uint32_t launch_flags = launch_info.GetFlags().Get();
756 const char *stdin_path = NULL;
757 const char *stdout_path = NULL;
758 const char *stderr_path = NULL;
759 const char *working_dir = launch_info.GetWorkingDirectory();
760
Zachary Turner696b5282014-08-14 16:01:25 +0000761 const FileAction *file_action;
Greg Clayton982c9762011-11-03 21:22:33 +0000762 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
763 if (file_action)
764 {
Zachary Turner696b5282014-08-14 16:01:25 +0000765 if (file_action->GetAction () == FileAction::eFileActionOpen)
Greg Clayton982c9762011-11-03 21:22:33 +0000766 stdin_path = file_action->GetPath();
767 }
768 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
769 if (file_action)
770 {
Zachary Turner696b5282014-08-14 16:01:25 +0000771 if (file_action->GetAction () == FileAction::eFileActionOpen)
Greg Clayton982c9762011-11-03 21:22:33 +0000772 stdout_path = file_action->GetPath();
773 }
774 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
775 if (file_action)
776 {
Zachary Turner696b5282014-08-14 16:01:25 +0000777 if (file_action->GetAction () == FileAction::eFileActionOpen)
Greg Clayton982c9762011-11-03 21:22:33 +0000778 stderr_path = file_action->GetPath();
779 }
780
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000781 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
782 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
783 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton5160ce52013-03-27 23:08:40 +0000784 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000785
Greg Clayton982c9762011-11-03 21:22:33 +0000786 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000787 if (object_file)
788 {
Greg Clayton71337622011-02-24 22:24:29 +0000789 // Make sure we aren't already connected?
790 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000791 {
Greg Clayton91a9b2472013-12-04 19:19:12 +0000792 error = LaunchAndConnectToDebugserver (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000793 }
794
795 if (error.Success())
796 {
797 lldb_utility::PseudoTerminal pty;
798 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000799
800 // If the debugserver is local and we aren't disabling STDIO, lets use
801 // a pseudo terminal to instead of relying on the 'O' packets for stdio
802 // since 'O' packets can really slow down debugging if the inferior
803 // does a lot of output.
Greg Claytonf58c2692011-06-24 22:32:10 +0000804 PlatformSP platform_sp (m_target.GetPlatform());
805 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Clayton71337622011-02-24 22:24:29 +0000806 {
807 const char *slave_name = NULL;
808 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000809 {
Greg Clayton71337622011-02-24 22:24:29 +0000810 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
811 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000812 }
Greg Clayton71337622011-02-24 22:24:29 +0000813 if (stdin_path == NULL)
814 stdin_path = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000815
Greg Clayton71337622011-02-24 22:24:29 +0000816 if (stdout_path == NULL)
817 stdout_path = slave_name;
818
819 if (stderr_path == NULL)
820 stderr_path = slave_name;
821 }
822
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000823 // Set STDIN to /dev/null if we want STDIO disabled or if either
824 // STDOUT or STDERR have been set to something and STDIN hasn't
825 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000826 stdin_path = "/dev/null";
827
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000828 // Set STDOUT to /dev/null if we want STDIO disabled or if either
829 // STDIN or STDERR have been set to something and STDOUT hasn't
830 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000831 stdout_path = "/dev/null";
832
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000833 // Set STDERR to /dev/null if we want STDIO disabled or if either
834 // STDIN or STDOUT have been set to something and STDERR hasn't
835 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000836 stderr_path = "/dev/null";
837
838 if (stdin_path)
839 m_gdb_comm.SetSTDIN (stdin_path);
840 if (stdout_path)
841 m_gdb_comm.SetSTDOUT (stdout_path);
842 if (stderr_path)
843 m_gdb_comm.SetSTDERR (stderr_path);
844
845 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
Jim Ingham106d0282014-06-25 02:32:56 +0000846 m_gdb_comm.SetDetachOnError (launch_flags & eLaunchFlagDetachOnError);
Greg Clayton71337622011-02-24 22:24:29 +0000847
Greg Claytonc4103b32011-05-08 04:53:50 +0000848 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Clayton71337622011-02-24 22:24:29 +0000849
Jason Molendaa3329782014-03-29 18:54:20 +0000850 const char * launch_event_data = launch_info.GetLaunchEventData();
851 if (launch_event_data != NULL && *launch_event_data != '\0')
852 m_gdb_comm.SendLaunchEventDataPacket (launch_event_data);
853
Greg Clayton71337622011-02-24 22:24:29 +0000854 if (working_dir && working_dir[0])
855 {
856 m_gdb_comm.SetWorkingDir (working_dir);
857 }
858
859 // Send the environment and the program + arguments after we connect
Greg Clayton982c9762011-11-03 21:22:33 +0000860 const Args &environment = launch_info.GetEnvironmentEntries();
861 if (environment.GetArgumentCount())
Greg Clayton71337622011-02-24 22:24:29 +0000862 {
Greg Clayton982c9762011-11-03 21:22:33 +0000863 size_t num_environment_entries = environment.GetArgumentCount();
864 for (size_t i=0; i<num_environment_entries; ++i)
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000865 {
Greg Clayton982c9762011-11-03 21:22:33 +0000866 const char *env_entry = environment.GetArgumentAtIndex(i);
867 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Clayton71337622011-02-24 22:24:29 +0000868 break;
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000869 }
Greg Clayton71337622011-02-24 22:24:29 +0000870 }
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000871
Greg Claytonc574ede2011-03-10 02:26:48 +0000872 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Claytonfbb76342013-11-20 21:07:01 +0000873 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000874 if (arg_packet_err == 0)
875 {
876 std::string error_str;
Greg Claytonc574ede2011-03-10 02:26:48 +0000877 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000878 {
Greg Claytonc574ede2011-03-10 02:26:48 +0000879 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000880 }
881 else
882 {
Greg Clayton71337622011-02-24 22:24:29 +0000883 error.SetErrorString (error_str.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000884 }
Greg Clayton71337622011-02-24 22:24:29 +0000885 }
886 else
887 {
Greg Clayton86edbf42011-10-26 00:56:27 +0000888 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Clayton71337622011-02-24 22:24:29 +0000889 }
Greg Clayton8b45bee2011-08-10 22:05:39 +0000890
891 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000892
Greg Clayton71337622011-02-24 22:24:29 +0000893 if (GetID() == LLDB_INVALID_PROCESS_ID)
894 {
Johnny Chen4c1e9202011-08-09 18:56:45 +0000895 if (log)
896 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton71337622011-02-24 22:24:29 +0000897 KillDebugserverProcess ();
898 return error;
899 }
900
Greg Clayton3dedae12013-12-06 21:45:27 +0000901 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton71337622011-02-24 22:24:29 +0000902 {
Jason Molendac62bd7b2013-12-21 05:20:36 +0000903 if (!m_target.GetArchitecture().IsValid())
904 {
905 if (m_gdb_comm.GetProcessArchitecture().IsValid())
906 {
907 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
908 }
909 else
910 {
911 m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
912 }
Carlo Kok74389122013-10-14 07:09:13 +0000913 }
914
Greg Claytondd0e5a52011-06-02 22:22:38 +0000915 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Clayton71337622011-02-24 22:24:29 +0000916
917 if (!disable_stdio)
918 {
919 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Claytonee95ed52011-11-17 22:14:31 +0000920 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Clayton71337622011-02-24 22:24:29 +0000921 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000922 }
923 }
Greg Claytonc235ac72011-08-09 05:20:29 +0000924 else
925 {
Johnny Chen4c1e9202011-08-09 18:56:45 +0000926 if (log)
927 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytonc235ac72011-08-09 05:20:29 +0000928 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000929 }
930 else
931 {
932 // Set our user ID to an invalid process ID.
933 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton982c9762011-11-03 21:22:33 +0000934 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
935 exe_module->GetFileSpec().GetFilename().AsCString(),
936 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000937 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000938 return error;
Greg Clayton4957bf62010-09-30 21:49:03 +0000939
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000940}
941
942
943Error
Greg Claytonb766a732011-02-04 01:58:07 +0000944ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000945{
946 Error error;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000947 // Only connect if we have a valid connect URL
948
949 if (connect_url && connect_url[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000950 {
Greg Clayton00fe87b2013-12-05 22:58:22 +0000951 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
952 if (conn_ap.get())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000953 {
Greg Clayton00fe87b2013-12-05 22:58:22 +0000954 const uint32_t max_retry_count = 50;
955 uint32_t retry_count = 0;
956 while (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000957 {
Greg Clayton00fe87b2013-12-05 22:58:22 +0000958 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
959 {
960 m_gdb_comm.SetConnection (conn_ap.release());
961 break;
962 }
963 else if (error.WasInterrupted())
964 {
965 // If we were interrupted, don't keep retrying.
966 break;
967 }
968
969 retry_count++;
970
971 if (retry_count >= max_retry_count)
972 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000973
Greg Clayton00fe87b2013-12-05 22:58:22 +0000974 usleep (100000);
975 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000976 }
977 }
978
979 if (!m_gdb_comm.IsConnected())
980 {
981 if (error.Success())
982 error.SetErrorString("not connected to remote gdb server");
983 return error;
984 }
985
Greg Clayton32e0a752011-03-30 18:16:51 +0000986 // We always seem to be able to open a connection to a local port
987 // so we need to make sure we can then send data to it. If we can't
988 // then we aren't actually connected to anything, so try and do the
989 // handshake with the remote GDB server and make sure that goes
990 // alright.
Greg Claytonfb909312013-11-23 01:58:15 +0000991 if (!m_gdb_comm.HandshakeWithServer (&error))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000992 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000993 m_gdb_comm.Disconnect();
994 if (error.Success())
995 error.SetErrorString("not connected to remote gdb server");
996 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000997 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000998 m_gdb_comm.GetThreadSuffixSupported ();
Greg Clayton44633992012-04-10 03:22:03 +0000999 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +00001000 m_gdb_comm.GetHostInfo ();
1001 m_gdb_comm.GetVContSupported ('c');
Jim Inghamcd16df92012-07-20 21:37:13 +00001002 m_gdb_comm.GetVAttachOrWaitSupported();
Jim Ingham03afad82012-07-02 05:40:07 +00001003
1004 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1005 for (size_t idx = 0; idx < num_cmds; idx++)
1006 {
1007 StringExtractorGDBRemote response;
Jim Ingham03afad82012-07-02 05:40:07 +00001008 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1009 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001010 return error;
1011}
1012
1013void
Jim Inghambb006ce2014-08-02 00:33:35 +00001014ProcessGDBRemote::DidLaunchOrAttach (ArchSpec& process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001015{
Greg Clayton5160ce52013-03-27 23:08:40 +00001016 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001017 if (log)
1018 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton93d3c8332011-02-16 04:46:07 +00001019 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001020 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001021 BuildDynamicRegisterInfo (false);
Greg Clayton3af9ea52010-11-18 05:57:03 +00001022
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001023 // See if the GDB server supports the qHostInfo information
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001024
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001025
1026 // See if the GDB server supports the qProcessInfo packet, if so
1027 // prefer that over the Host information as it will be more specific
1028 // to our process.
1029
1030 if (m_gdb_comm.GetProcessArchitecture().IsValid())
Jim Inghambb006ce2014-08-02 00:33:35 +00001031 process_arch = m_gdb_comm.GetProcessArchitecture();
1032 else
1033 process_arch = m_gdb_comm.GetHostArchitecture();
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001034
Jim Inghambb006ce2014-08-02 00:33:35 +00001035 if (process_arch.IsValid())
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001036 {
Greg Claytond314e812011-03-23 00:09:55 +00001037 ArchSpec &target_arch = GetTarget().GetArchitecture();
1038
1039 if (target_arch.IsValid())
1040 {
1041 // If the remote host is ARM and we have apple as the vendor, then
1042 // ARM executables and shared libraries can have mixed ARM architectures.
1043 // You can have an armv6 executable, and if the host is armv7, then the
1044 // system will load the best possible architecture for all shared libraries
1045 // it has, so we really need to take the remote host architecture as our
1046 // defacto architecture in this case.
1047
Jim Inghambb006ce2014-08-02 00:33:35 +00001048 if (process_arch.GetMachine() == llvm::Triple::arm &&
1049 process_arch.GetTriple().getVendor() == llvm::Triple::Apple)
Greg Claytond314e812011-03-23 00:09:55 +00001050 {
Jason Molenda921c01b2014-08-03 21:42:52 +00001051 GetTarget().SetArchitecture (process_arch);
Greg Claytond314e812011-03-23 00:09:55 +00001052 }
1053 else
1054 {
1055 // Fill in what is missing in the triple
Jim Inghambb006ce2014-08-02 00:33:35 +00001056 const llvm::Triple &remote_triple = process_arch.GetTriple();
Greg Claytond314e812011-03-23 00:09:55 +00001057 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton70b57652011-05-15 01:25:55 +00001058 if (target_triple.getVendorName().size() == 0)
1059 {
Greg Claytond314e812011-03-23 00:09:55 +00001060 target_triple.setVendor (remote_triple.getVendor());
1061
Greg Clayton70b57652011-05-15 01:25:55 +00001062 if (target_triple.getOSName().size() == 0)
1063 {
1064 target_triple.setOS (remote_triple.getOS());
Greg Claytond314e812011-03-23 00:09:55 +00001065
Greg Clayton70b57652011-05-15 01:25:55 +00001066 if (target_triple.getEnvironmentName().size() == 0)
1067 target_triple.setEnvironment (remote_triple.getEnvironment());
1068 }
1069 }
Greg Claytond314e812011-03-23 00:09:55 +00001070 }
1071 }
1072 else
1073 {
1074 // The target doesn't have a valid architecture yet, set it from
1075 // the architecture we got from the remote GDB server
Jason Molenda921c01b2014-08-03 21:42:52 +00001076 GetTarget().SetArchitecture (process_arch);
Greg Claytond314e812011-03-23 00:09:55 +00001077 }
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001078 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001079 }
1080}
1081
1082void
1083ProcessGDBRemote::DidLaunch ()
1084{
Jim Inghambb006ce2014-08-02 00:33:35 +00001085 ArchSpec process_arch;
1086 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001087}
1088
Todd Fialaaf245d12014-06-30 21:05:18 +00001089UnixSignals&
1090ProcessGDBRemote::GetUnixSignals ()
1091{
1092 assert (m_unix_signals_sp && "m_unix_signals_sp is null");
1093 return *m_unix_signals_sp;
1094}
1095
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001096Error
Greg Claytonc982c762010-07-09 20:39:50 +00001097ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001098{
Han Ming Ong84647042012-02-25 01:07:38 +00001099 ProcessAttachInfo attach_info;
1100 return DoAttachToProcessWithID(attach_pid, attach_info);
1101}
1102
1103Error
1104ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1105{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001106 Error error;
1107 // Clear out and clean up from any current state
1108 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001109 if (attach_pid != LLDB_INVALID_PROCESS_ID)
1110 {
Greg Clayton71337622011-02-24 22:24:29 +00001111 // Make sure we aren't already connected?
1112 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001113 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001114 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001115
1116 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001117 {
Greg Clayton71337622011-02-24 22:24:29 +00001118 const char *error_string = error.AsCString();
1119 if (error_string == NULL)
1120 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1121
1122 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001123 }
Greg Clayton71337622011-02-24 22:24:29 +00001124 }
1125
1126 if (error.Success())
1127 {
Jim Ingham106d0282014-06-25 02:32:56 +00001128 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1129
Greg Clayton71337622011-02-24 22:24:29 +00001130 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001131 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Greg Clayton3b608422011-11-19 02:11:30 +00001132 SetID (attach_pid);
Greg Clayton71337622011-02-24 22:24:29 +00001133 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001134 }
1135 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001136 return error;
1137}
1138
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001139Error
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001140ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001141{
1142 Error error;
1143 // Clear out and clean up from any current state
1144 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001145
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001146 if (process_name && process_name[0])
1147 {
Greg Clayton71337622011-02-24 22:24:29 +00001148 // Make sure we aren't already connected?
1149 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001150 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001151 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001152
Greg Clayton71337622011-02-24 22:24:29 +00001153 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001154 {
Greg Clayton71337622011-02-24 22:24:29 +00001155 const char *error_string = error.AsCString();
1156 if (error_string == NULL)
1157 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001158
Greg Clayton71337622011-02-24 22:24:29 +00001159 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001160 }
Greg Clayton71337622011-02-24 22:24:29 +00001161 }
1162
1163 if (error.Success())
1164 {
1165 StreamString packet;
1166
Jim Ingham106d0282014-06-25 02:32:56 +00001167 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1168
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001169 if (attach_info.GetWaitForLaunch())
Jim Inghamcd16df92012-07-20 21:37:13 +00001170 {
1171 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1172 {
1173 packet.PutCString ("vAttachWait");
1174 }
1175 else
1176 {
1177 if (attach_info.GetIgnoreExisting())
1178 packet.PutCString("vAttachWait");
1179 else
1180 packet.PutCString ("vAttachOrWait");
1181 }
1182 }
Greg Clayton71337622011-02-24 22:24:29 +00001183 else
1184 packet.PutCString("vAttachName");
1185 packet.PutChar(';');
1186 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1187
1188 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1189
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001190 }
1191 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001192 return error;
1193}
1194
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001195
Greg Claytonfbb76342013-11-20 21:07:01 +00001196bool
1197ProcessGDBRemote::SetExitStatus (int exit_status, const char *cstr)
1198{
1199 m_gdb_comm.Disconnect();
1200 return Process::SetExitStatus (exit_status, cstr);
1201}
1202
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001203void
Jim Inghambb006ce2014-08-02 00:33:35 +00001204ProcessGDBRemote::DidAttach (ArchSpec &process_arch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001205{
Jim Inghambb006ce2014-08-02 00:33:35 +00001206 // If you can figure out what the architecture is, fill it in here.
1207 process_arch.Clear();
1208 DidLaunchOrAttach (process_arch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001209}
1210
Greg Clayton90ba8112012-12-05 00:16:59 +00001211
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001212Error
1213ProcessGDBRemote::WillResume ()
1214{
Greg Clayton71fc2a32011-02-12 06:28:37 +00001215 m_continue_c_tids.clear();
1216 m_continue_C_tids.clear();
1217 m_continue_s_tids.clear();
1218 m_continue_S_tids.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001219 return Error();
1220}
1221
1222Error
1223ProcessGDBRemote::DoResume ()
1224{
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001225 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001226 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001227 if (log)
1228 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytone5219662010-12-03 06:02:24 +00001229
1230 Listener listener ("gdb-remote.resume-packet-sent");
1231 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1232 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00001233 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1234
Greg Claytond1d06e42013-04-20 00:27:58 +00001235 const size_t num_threads = GetThreadList().GetSize();
1236
Greg Clayton71fc2a32011-02-12 06:28:37 +00001237 StreamString continue_packet;
1238 bool continue_packet_error = false;
1239 if (m_gdb_comm.HasAnyVContSupport ())
1240 {
Greg Claytone98008c2014-02-13 23:34:38 +00001241 if (m_continue_c_tids.size() == num_threads ||
1242 (m_continue_c_tids.empty() &&
1243 m_continue_C_tids.empty() &&
1244 m_continue_s_tids.empty() &&
1245 m_continue_S_tids.empty()))
Greg Clayton71fc2a32011-02-12 06:28:37 +00001246 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001247 // All threads are continuing, just send a "c" packet
1248 continue_packet.PutCString ("c");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001249 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001250 else
1251 {
1252 continue_packet.PutCString ("vCont");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001253
Greg Claytond1d06e42013-04-20 00:27:58 +00001254 if (!m_continue_c_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001255 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001256 if (m_gdb_comm.GetVContSupported ('c'))
1257 {
1258 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)
1259 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1260 }
1261 else
1262 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001263 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001264
1265 if (!continue_packet_error && !m_continue_C_tids.empty())
1266 {
1267 if (m_gdb_comm.GetVContSupported ('C'))
1268 {
1269 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)
1270 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1271 }
1272 else
1273 continue_packet_error = true;
1274 }
Greg Claytone5219662010-12-03 06:02:24 +00001275
Greg Claytond1d06e42013-04-20 00:27:58 +00001276 if (!continue_packet_error && !m_continue_s_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001277 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001278 if (m_gdb_comm.GetVContSupported ('s'))
1279 {
1280 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)
1281 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1282 }
1283 else
1284 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001285 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001286
1287 if (!continue_packet_error && !m_continue_S_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001288 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001289 if (m_gdb_comm.GetVContSupported ('S'))
1290 {
1291 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)
1292 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1293 }
1294 else
1295 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001296 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001297
1298 if (continue_packet_error)
1299 continue_packet.GetString().clear();
Greg Clayton71fc2a32011-02-12 06:28:37 +00001300 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001301 }
1302 else
1303 continue_packet_error = true;
1304
1305 if (continue_packet_error)
1306 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001307 // Either no vCont support, or we tried to use part of the vCont
1308 // packet that wasn't supported by the remote GDB server.
1309 // We need to try and make a simple packet that can do our continue
Greg Clayton71fc2a32011-02-12 06:28:37 +00001310 const size_t num_continue_c_tids = m_continue_c_tids.size();
1311 const size_t num_continue_C_tids = m_continue_C_tids.size();
1312 const size_t num_continue_s_tids = m_continue_s_tids.size();
1313 const size_t num_continue_S_tids = m_continue_S_tids.size();
1314 if (num_continue_c_tids > 0)
1315 {
1316 if (num_continue_c_tids == num_threads)
1317 {
1318 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001319 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001320 continue_packet.PutChar ('c');
1321 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001322 }
1323 else if (num_continue_c_tids == 1 &&
1324 num_continue_C_tids == 0 &&
1325 num_continue_s_tids == 0 &&
1326 num_continue_S_tids == 0 )
1327 {
1328 // Only one thread is continuing
Greg Clayton8b82f082011-04-12 05:54:46 +00001329 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001330 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001331 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001332 }
1333 }
1334
Greg Clayton0c74e782011-06-24 03:21:43 +00001335 if (continue_packet_error && num_continue_C_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001336 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001337 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1338 num_continue_C_tids > 0 &&
1339 num_continue_s_tids == 0 &&
1340 num_continue_S_tids == 0 )
Greg Clayton71fc2a32011-02-12 06:28:37 +00001341 {
1342 const int continue_signo = m_continue_C_tids.front().second;
Greg Clayton0c74e782011-06-24 03:21:43 +00001343 // Only one thread is continuing
Greg Clayton71fc2a32011-02-12 06:28:37 +00001344 if (num_continue_C_tids > 1)
1345 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001346 // More that one thread with a signal, yet we don't have
1347 // vCont support and we are being asked to resume each
1348 // thread with a signal, we need to make sure they are
1349 // all the same signal, or we can't issue the continue
1350 // accurately with the current support...
1351 if (num_continue_C_tids > 1)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001352 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001353 continue_packet_error = false;
1354 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1355 {
1356 if (m_continue_C_tids[i].second != continue_signo)
1357 continue_packet_error = true;
1358 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001359 }
Greg Clayton0c74e782011-06-24 03:21:43 +00001360 if (!continue_packet_error)
1361 m_gdb_comm.SetCurrentThreadForRun (-1);
1362 }
1363 else
1364 {
1365 // Set the continue thread ID
1366 continue_packet_error = false;
1367 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001368 }
1369 if (!continue_packet_error)
1370 {
1371 // Add threads continuing with the same signo...
Greg Clayton71fc2a32011-02-12 06:28:37 +00001372 continue_packet.Printf("C%2.2x", continue_signo);
1373 }
1374 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001375 }
1376
Greg Clayton0c74e782011-06-24 03:21:43 +00001377 if (continue_packet_error && num_continue_s_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001378 {
1379 if (num_continue_s_tids == num_threads)
1380 {
1381 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001382 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001383 continue_packet.PutChar ('s');
1384 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001385 }
1386 else if (num_continue_c_tids == 0 &&
1387 num_continue_C_tids == 0 &&
1388 num_continue_s_tids == 1 &&
1389 num_continue_S_tids == 0 )
1390 {
1391 // Only one thread is stepping
Greg Clayton8b82f082011-04-12 05:54:46 +00001392 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001393 continue_packet.PutChar ('s');
Greg Clayton0c74e782011-06-24 03:21:43 +00001394 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001395 }
1396 }
1397
1398 if (!continue_packet_error && num_continue_S_tids > 0)
1399 {
1400 if (num_continue_S_tids == num_threads)
1401 {
1402 const int step_signo = m_continue_S_tids.front().second;
1403 // Are all threads trying to step with the same signal?
Greg Clayton0c74e782011-06-24 03:21:43 +00001404 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001405 if (num_continue_S_tids > 1)
1406 {
1407 for (size_t i=1; i<num_threads; ++i)
1408 {
1409 if (m_continue_S_tids[i].second != step_signo)
1410 continue_packet_error = true;
1411 }
1412 }
1413 if (!continue_packet_error)
1414 {
1415 // Add threads stepping with the same signo...
Greg Clayton8b82f082011-04-12 05:54:46 +00001416 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001417 continue_packet.Printf("S%2.2x", step_signo);
1418 }
1419 }
1420 else if (num_continue_c_tids == 0 &&
1421 num_continue_C_tids == 0 &&
1422 num_continue_s_tids == 0 &&
1423 num_continue_S_tids == 1 )
1424 {
1425 // Only one thread is stepping with signal
Greg Clayton8b82f082011-04-12 05:54:46 +00001426 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001427 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Clayton0c74e782011-06-24 03:21:43 +00001428 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001429 }
1430 }
1431 }
1432
1433 if (continue_packet_error)
1434 {
1435 error.SetErrorString ("can't make continue packet for this resume");
1436 }
1437 else
1438 {
1439 EventSP event_sp;
1440 TimeValue timeout;
1441 timeout = TimeValue::Now();
1442 timeout.OffsetWithSeconds (5);
Jim Inghamb1e2e842012-04-12 18:49:31 +00001443 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1444 {
1445 error.SetErrorString ("Trying to resume but the async thread is dead.");
1446 if (log)
1447 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1448 return error;
1449 }
1450
Greg Clayton71fc2a32011-02-12 06:28:37 +00001451 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1452
1453 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Inghamb1e2e842012-04-12 18:49:31 +00001454 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001455 error.SetErrorString("Resume timed out.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00001456 if (log)
1457 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1458 }
1459 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1460 {
1461 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1462 if (log)
1463 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1464 return error;
1465 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001466 }
Greg Claytone5219662010-12-03 06:02:24 +00001467 }
1468
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001469 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001470}
1471
Greg Clayton9e920902012-04-10 02:25:43 +00001472void
1473ProcessGDBRemote::ClearThreadIDList ()
1474{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001475 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001476 m_thread_ids.clear();
1477}
1478
1479bool
1480ProcessGDBRemote::UpdateThreadIDList ()
1481{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001482 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001483 bool sequence_mutex_unavailable = false;
1484 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1485 if (sequence_mutex_unavailable)
1486 {
Greg Clayton9e920902012-04-10 02:25:43 +00001487 return false; // We just didn't get the list
1488 }
1489 return true;
1490}
1491
Greg Clayton9fc13552012-04-10 00:18:59 +00001492bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001493ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001494{
1495 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +00001496 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Clayton73b472d2010-10-27 03:32:59 +00001497 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +00001498 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton9e920902012-04-10 02:25:43 +00001499
1500 size_t num_thread_ids = m_thread_ids.size();
1501 // The "m_thread_ids" thread ID list should always be updated after each stop
1502 // reply packet, but in case it isn't, update it here.
1503 if (num_thread_ids == 0)
1504 {
1505 if (!UpdateThreadIDList ())
1506 return false;
1507 num_thread_ids = m_thread_ids.size();
1508 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001509
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001510 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001511 if (num_thread_ids > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001512 {
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001513 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001514 {
Greg Clayton9e920902012-04-10 02:25:43 +00001515 tid_t tid = m_thread_ids[i];
Greg Clayton160c9d82013-05-01 21:54:04 +00001516 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001517 if (!thread_sp)
Jim Inghamdee1bc92013-06-22 00:27:45 +00001518 {
Jim Ingham4f465cf2012-10-10 18:32:14 +00001519 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001520 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1521 log->Printf(
1522 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001523 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001524 thread_sp->GetID());
1525 }
1526 else
1527 {
1528 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1529 log->Printf(
1530 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001531 __FUNCTION__, static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001532 thread_sp->GetID());
1533 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001534 new_thread_list.AddThread(thread_sp);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001535 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001536 }
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001537
1538 // Whatever that is left in old_thread_list_copy are not
1539 // present in new_thread_list. Remove non-existent threads from internal id table.
1540 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1541 for (size_t i=0; i<old_num_thread_ids; i++)
1542 {
1543 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1544 if (old_thread_sp)
1545 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001546 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001547 m_thread_id_to_index_id_map.erase(old_thread_id);
1548 }
1549 }
1550
Greg Clayton9fc13552012-04-10 00:18:59 +00001551 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001552}
1553
1554
1555StateType
1556ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1557{
Greg Claytondd0e5a52011-06-02 22:22:38 +00001558 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001559 const char stop_type = stop_packet.GetChar();
1560 switch (stop_type)
1561 {
1562 case 'T':
1563 case 'S':
1564 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00001565 // This is a bit of a hack, but is is required. If we did exec, we
1566 // need to clear our thread lists and also know to rebuild our dynamic
1567 // register info before we lookup and threads and populate the expedited
1568 // register values so we need to know this right away so we can cleanup
1569 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00001570 const uint32_t stop_id = GetStopID();
1571 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00001572 {
1573 // Our first stop, make sure we have a process ID, and also make
1574 // sure we know about our registers
1575 if (GetID() == LLDB_INVALID_PROCESS_ID)
1576 {
Greg Claytonc574ede2011-03-10 02:26:48 +00001577 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00001578 if (pid != LLDB_INVALID_PROCESS_ID)
1579 SetID (pid);
1580 }
1581 BuildDynamicRegisterInfo (true);
1582 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001583 // Stop with signal and thread info
1584 const uint8_t signo = stop_packet.GetHexU8();
1585 std::string name;
1586 std::string value;
1587 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00001588 std::string reason;
1589 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001590 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00001591 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001592 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001593 ThreadSP thread_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001594 ThreadGDBRemote *gdb_thread = NULL;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001595
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001596 while (stop_packet.GetNameColonValue(name, value))
1597 {
1598 if (name.compare("metype") == 0)
1599 {
1600 // exception type in big endian hex
1601 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1602 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001603 else if (name.compare("medata") == 0)
1604 {
1605 // exception data in big endian hex
1606 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1607 }
1608 else if (name.compare("thread") == 0)
1609 {
1610 // thread in big endian hex
Greg Clayton9e920902012-04-10 02:25:43 +00001611 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001612 // m_thread_list_real does have its own mutex, but we need to
1613 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1614 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1615 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1616 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
Greg Clayton160c9d82013-05-01 21:54:04 +00001617
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001618 if (!thread_sp)
Greg Claytond1d06e42013-04-20 00:27:58 +00001619 {
Greg Claytone576ab22011-02-15 00:19:15 +00001620 // Create the thread if we need to
Jim Ingham4f465cf2012-10-10 18:32:14 +00001621 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001622 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
1623 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1624 log->Printf ("ProcessGDBRemote::%s Adding new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1625 __FUNCTION__,
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001626 static_cast<void*>(thread_sp.get()),
Jim Inghamdee1bc92013-06-22 00:27:45 +00001627 thread_sp->GetID());
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001628
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001629 m_thread_list_real.AddThread(thread_sp);
Greg Claytone576ab22011-02-15 00:19:15 +00001630 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001631 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1632
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001633 }
Greg Clayton9e920902012-04-10 02:25:43 +00001634 else if (name.compare("threads") == 0)
1635 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001636 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001637 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00001638 // A comma separated list of all threads in the current
1639 // process that includes the thread for this stop reply
1640 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00001641 size_t comma_pos;
1642 lldb::tid_t tid;
1643 while ((comma_pos = value.find(',')) != std::string::npos)
1644 {
1645 value[comma_pos] = '\0';
1646 // thread in big endian hex
1647 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1648 if (tid != LLDB_INVALID_THREAD_ID)
1649 m_thread_ids.push_back (tid);
1650 value.erase(0, comma_pos + 1);
Greg Clayton9e920902012-04-10 02:25:43 +00001651 }
1652 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1653 if (tid != LLDB_INVALID_THREAD_ID)
1654 m_thread_ids.push_back (tid);
1655 }
Greg Claytonde9d0492011-01-08 03:17:57 +00001656 else if (name.compare("hexname") == 0)
1657 {
1658 StringExtractor name_extractor;
1659 // Swap "value" over into "name_extractor"
1660 name_extractor.GetStringRef().swap(value);
1661 // Now convert the HEX bytes into a string value
1662 name_extractor.GetHexByteString (value);
1663 thread_name.swap (value);
1664 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001665 else if (name.compare("name") == 0)
1666 {
1667 thread_name.swap (value);
1668 }
Greg Clayton6f35f5c2010-09-09 06:32:46 +00001669 else if (name.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001670 {
1671 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1672 }
Greg Claytona658fd22011-06-04 01:26:29 +00001673 else if (name.compare("reason") == 0)
1674 {
1675 reason.swap(value);
1676 }
1677 else if (name.compare("description") == 0)
1678 {
1679 StringExtractor desc_extractor;
1680 // Swap "value" over into "name_extractor"
1681 desc_extractor.GetStringRef().swap(value);
1682 // Now convert the HEX bytes into a string value
1683 desc_extractor.GetHexByteString (thread_name);
1684 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001685 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1686 {
1687 // We have a register number that contains an expedited
1688 // register value. Lets supply this register to our thread
1689 // so it won't have to go and read it.
Greg Clayton160c9d82013-05-01 21:54:04 +00001690 if (gdb_thread)
Greg Clayton3e06bd92011-01-09 21:07:35 +00001691 {
1692 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1693
1694 if (reg != UINT32_MAX)
1695 {
1696 StringExtractor reg_value_extractor;
1697 // Swap "value" over into "reg_value_extractor"
1698 reg_value_extractor.GetStringRef().swap(value);
Greg Clayton160c9d82013-05-01 21:54:04 +00001699 if (!gdb_thread->PrivateSetRegisterValue (reg, reg_value_extractor))
Greg Claytone576ab22011-02-15 00:19:15 +00001700 {
1701 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1702 name.c_str(),
1703 reg,
1704 reg,
1705 reg_value_extractor.GetStringRef().c_str(),
1706 stop_packet.GetStringRef().c_str());
1707 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001708 }
1709 }
1710 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001711 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001712
Hafiz Abid Qadeer673b4a32014-02-20 10:23:20 +00001713 // If the response is old style 'S' packet which does not provide us with thread information
1714 // then update the thread list and choose the first one.
1715 if (!thread_sp)
1716 {
1717 UpdateThreadIDList ();
1718
1719 if (!m_thread_ids.empty ())
1720 {
1721 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1722 thread_sp = m_thread_list_real.FindThreadByProtocolID (m_thread_ids.front (), false);
1723 if (thread_sp)
1724 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get ());
1725 }
1726 }
1727
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001728 if (thread_sp)
1729 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001730 // Clear the stop info just in case we don't set it to anything
1731 thread_sp->SetStopInfo (StopInfoSP());
1732
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001733 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Inghamdd2fe7a2011-01-28 02:23:12 +00001734 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001735 if (exc_type != 0)
1736 {
Greg Clayton1a65ae12011-01-25 23:55:37 +00001737 const size_t exc_data_size = exc_data.size();
Greg Claytonf4b47e12010-08-04 01:40:35 +00001738
Greg Clayton160c9d82013-05-01 21:54:04 +00001739 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1740 exc_type,
1741 exc_data_size,
1742 exc_data_size >= 1 ? exc_data[0] : 0,
1743 exc_data_size >= 2 ? exc_data[1] : 0,
1744 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001745 }
Greg Claytona658fd22011-06-04 01:26:29 +00001746 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001747 {
Greg Claytona658fd22011-06-04 01:26:29 +00001748 bool handled = false;
Greg Clayton8cda7f02013-05-21 21:55:59 +00001749 bool did_exec = false;
Greg Claytona658fd22011-06-04 01:26:29 +00001750 if (!reason.empty())
1751 {
1752 if (reason.compare("trace") == 0)
1753 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001754 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Greg Claytona658fd22011-06-04 01:26:29 +00001755 handled = true;
1756 }
1757 else if (reason.compare("breakpoint") == 0)
1758 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001759 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1760 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Claytona658fd22011-06-04 01:26:29 +00001761 if (bp_site_sp)
1762 {
1763 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1764 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1765 // 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 +00001766 handled = true;
Greg Clayton160c9d82013-05-01 21:54:04 +00001767 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00001768 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001769 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00001770 }
1771 else
1772 {
1773 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001774 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00001775 }
1776 }
Greg Claytona658fd22011-06-04 01:26:29 +00001777 }
1778 else if (reason.compare("trap") == 0)
1779 {
1780 // Let the trap just use the standard signal stop reason below...
1781 }
1782 else if (reason.compare("watchpoint") == 0)
1783 {
1784 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1785 // TODO: locate the watchpoint somehow...
Greg Clayton160c9d82013-05-01 21:54:04 +00001786 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
Greg Claytona658fd22011-06-04 01:26:29 +00001787 handled = true;
1788 }
1789 else if (reason.compare("exception") == 0)
1790 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001791 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00001792 handled = true;
1793 }
Greg Clayton15fc2be2013-05-21 01:00:52 +00001794 else if (reason.compare("exec") == 0)
1795 {
Greg Clayton8cda7f02013-05-21 21:55:59 +00001796 did_exec = true;
Greg Clayton15fc2be2013-05-21 01:00:52 +00001797 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
1798 handled = true;
1799 }
Greg Claytona658fd22011-06-04 01:26:29 +00001800 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001801
Jim Ingham40083a42014-02-24 19:49:46 +00001802 if (!handled && signo && did_exec == false)
Greg Claytona658fd22011-06-04 01:26:29 +00001803 {
1804 if (signo == SIGTRAP)
1805 {
1806 // Currently we are going to assume SIGTRAP means we are either
1807 // hitting a breakpoint or hardware single stepping.
Jim Ingham54cc6e42012-07-11 21:41:19 +00001808 handled = true;
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +00001809 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
Greg Clayton160c9d82013-05-01 21:54:04 +00001810 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001811
Greg Claytona658fd22011-06-04 01:26:29 +00001812 if (bp_site_sp)
1813 {
1814 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1815 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1816 // 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 +00001817 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00001818 {
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +00001819 if(m_breakpoint_pc_offset != 0)
1820 thread_sp->GetRegisterContext()->SetPC(pc);
Greg Clayton160c9d82013-05-01 21:54:04 +00001821 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00001822 }
1823 else
1824 {
1825 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001826 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00001827 }
1828 }
Jim Ingham54cc6e42012-07-11 21:41:19 +00001829 else
Greg Claytona658fd22011-06-04 01:26:29 +00001830 {
Jim Ingham4dc613b2012-10-27 02:52:04 +00001831 // If we were stepping then assume the stop was the result of the trace. If we were
1832 // not stepping then report the SIGTRAP.
1833 // FIXME: We are still missing the case where we single step over a trap instruction.
Greg Clayton160c9d82013-05-01 21:54:04 +00001834 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1835 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Jim Ingham4dc613b2012-10-27 02:52:04 +00001836 else
Greg Clayton160c9d82013-05-01 21:54:04 +00001837 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo));
Greg Claytona658fd22011-06-04 01:26:29 +00001838 }
1839 }
1840 if (!handled)
Greg Clayton160c9d82013-05-01 21:54:04 +00001841 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Jason Molenda8214b012013-04-25 01:33:46 +00001842 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001843
Greg Claytona658fd22011-06-04 01:26:29 +00001844 if (!description.empty())
1845 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001846 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
Greg Claytona658fd22011-06-04 01:26:29 +00001847 if (stop_info_sp)
1848 {
1849 stop_info_sp->SetDescription (description.c_str());
Greg Clayton3418c852011-08-10 02:10:13 +00001850 }
Greg Claytona658fd22011-06-04 01:26:29 +00001851 else
1852 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001853 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00001854 }
1855 }
1856 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001857 }
1858 return eStateStopped;
1859 }
1860 break;
1861
1862 case 'W':
Todd Fialaff6131a2014-05-19 04:57:23 +00001863 case 'X':
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001864 // process exited
1865 return eStateExited;
1866
1867 default:
1868 break;
1869 }
1870 return eStateInvalid;
1871}
1872
1873void
1874ProcessGDBRemote::RefreshStateAfterStop ()
1875{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001876 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001877 m_thread_ids.clear();
1878 // Set the thread stop info. It might have a "threads" key whose value is
1879 // a list of all thread IDs in the current process, so m_thread_ids might
1880 // get set.
1881 SetThreadStopInfo (m_last_stop_packet);
1882 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1883 if (m_thread_ids.empty())
1884 {
1885 // No, we need to fetch the thread list manually
1886 UpdateThreadIDList();
1887 }
1888
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001889 // Let all threads recover from stopping and do any clean up based
1890 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001891 m_thread_list_real.RefreshStateAfterStop();
Greg Clayton9e920902012-04-10 02:25:43 +00001892
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001893}
1894
1895Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001896ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001897{
1898 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001899
Greg Clayton6ed95942011-01-22 07:12:45 +00001900 bool timed_out = false;
1901 Mutex::Locker locker;
Greg Clayton513c26c2011-01-29 07:10:55 +00001902
1903 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00001904 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001905 // We are being asked to halt during an attach. We need to just close
1906 // our file handle and debugserver will go away, and we can be done...
1907 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00001908 }
Greg Clayton513c26c2011-01-29 07:10:55 +00001909 else
1910 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001911 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton513c26c2011-01-29 07:10:55 +00001912 {
1913 if (timed_out)
1914 error.SetErrorString("timed out sending interrupt packet");
1915 else
1916 error.SetErrorString("unknown error sending interrupt packet");
1917 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001918
1919 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton513c26c2011-01-29 07:10:55 +00001920 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001921 return error;
1922}
1923
1924Error
Jim Inghamacff8952013-05-02 00:27:30 +00001925ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00001926{
1927 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001928 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00001929 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00001930 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
1931
Jim Inghamacff8952013-05-02 00:27:30 +00001932 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001933 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00001934 {
Jim Inghamacff8952013-05-02 00:27:30 +00001935 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001936 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1937 else
Jim Inghamacff8952013-05-02 00:27:30 +00001938 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00001939 }
Jim Inghamacff8952013-05-02 00:27:30 +00001940
1941 if (!error.Success())
1942 return error;
1943
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001944 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00001945 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001946
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001947 SetPrivateState (eStateDetached);
1948 ResumePrivateStateThread();
1949
1950 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00001951 return error;
1952}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001953
Jim Ingham43c555d2012-07-04 00:35:43 +00001954
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001955Error
1956ProcessGDBRemote::DoDestroy ()
1957{
1958 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001959 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001960 if (log)
1961 log->Printf ("ProcessGDBRemote::DoDestroy()");
1962
Jim Ingham43c555d2012-07-04 00:35:43 +00001963 // There is a bug in older iOS debugservers where they don't shut down the process
1964 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
1965 // this can cause problems with restarting. So we check to see if any of our threads are stopped
1966 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
1967 // destroy it again.
1968 //
1969 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
1970 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
1971 // the debugservers with this bug are equal. There really should be a better way to test this!
1972 //
1973 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
1974 // get called here to destroy again and we're still at a breakpoint or exception, then we should
1975 // just do the straight-forward kill.
1976 //
1977 // And of course, if we weren't able to stop the process by the time we get here, it isn't
1978 // necessary (or helpful) to do any of this.
1979
1980 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
1981 {
1982 PlatformSP platform_sp = GetTarget().GetPlatform();
1983
1984 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
1985 if (platform_sp
1986 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00001987 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00001988 {
1989 if (m_destroy_tried_resuming)
1990 {
1991 if (log)
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001992 log->PutCString ("ProcessGDBRemote::DoDestroy() - Tried resuming to destroy once already, not doing it again.");
Jim Ingham43c555d2012-07-04 00:35:43 +00001993 }
1994 else
1995 {
1996 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
1997 // but we really need it to happen here and it doesn't matter if we do it twice.
1998 m_thread_list.DiscardThreadPlans();
1999 DisableAllBreakpointSites();
2000
2001 bool stop_looks_like_crash = false;
2002 ThreadList &threads = GetThreadList();
2003
2004 {
Jim Ingham45350372012-09-11 00:08:52 +00002005 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002006
2007 size_t num_threads = threads.GetSize();
2008 for (size_t i = 0; i < num_threads; i++)
2009 {
2010 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002011 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002012 StopReason reason = eStopReasonInvalid;
2013 if (stop_info_sp)
2014 reason = stop_info_sp->GetStopReason();
2015 if (reason == eStopReasonBreakpoint
2016 || reason == eStopReasonException)
2017 {
2018 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002019 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
2020 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00002021 stop_info_sp->GetDescription());
2022 stop_looks_like_crash = true;
2023 break;
2024 }
2025 }
2026 }
2027
2028 if (stop_looks_like_crash)
2029 {
2030 if (log)
2031 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
2032 m_destroy_tried_resuming = true;
2033
2034 // If we are going to run again before killing, it would be good to suspend all the threads
2035 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
2036 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
2037 // have to run the risk of letting those threads proceed a bit.
2038
2039 {
Jim Ingham45350372012-09-11 00:08:52 +00002040 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00002041
2042 size_t num_threads = threads.GetSize();
2043 for (size_t i = 0; i < num_threads; i++)
2044 {
2045 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00002046 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00002047 StopReason reason = eStopReasonInvalid;
2048 if (stop_info_sp)
2049 reason = stop_info_sp->GetStopReason();
2050 if (reason != eStopReasonBreakpoint
2051 && reason != eStopReasonException)
2052 {
2053 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002054 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
2055 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00002056 thread_sp->SetResumeState(eStateSuspended);
2057 }
2058 }
2059 }
2060 Resume ();
2061 return Destroy();
2062 }
2063 }
2064 }
2065 }
2066
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002067 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00002068 int exit_status = SIGABRT;
2069 std::string exit_string;
2070
Greg Clayton6ed95942011-01-22 07:12:45 +00002071 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002072 {
Jim Inghamaab78372011-10-28 01:11:35 +00002073 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00002074 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002075
2076 StringExtractorGDBRemote response;
2077 bool send_async = true;
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002078 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3);
2079
Greg Clayton3dedae12013-12-06 21:45:27 +00002080 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton513c26c2011-01-29 07:10:55 +00002081 {
2082 char packet_cmd = response.GetChar(0);
2083
2084 if (packet_cmd == 'W' || packet_cmd == 'X')
2085 {
Jim Inghameac0aa42014-02-21 22:36:11 +00002086#if defined(__APPLE__)
Jim Ingham9d67cc52014-02-21 22:35:29 +00002087 // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off
2088 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill
2089 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns
2090 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap
2091 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of
2092 // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2093 // Anyway, so call waitpid here to finally reap it.
2094 PlatformSP platform_sp(GetTarget().GetPlatform());
2095 if (platform_sp && platform_sp->IsHost())
2096 {
2097 int status;
2098 ::pid_t reap_pid;
2099 reap_pid = waitpid (GetID(), &status, WNOHANG);
2100 if (log)
2101 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2102 }
2103#endif
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002104 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002105 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00002106 exit_status = response.GetHexU8();
2107 }
2108 else
2109 {
2110 if (log)
2111 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2112 exit_string.assign("got unexpected response to k packet: ");
2113 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00002114 }
2115 }
2116 else
2117 {
Jim Inghambabfc382012-06-06 00:32:39 +00002118 if (log)
2119 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2120 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00002121 }
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002122
2123 m_gdb_comm.SetPacketTimeout(old_packet_timeout);
Greg Clayton6779606a2011-01-22 23:43:18 +00002124 }
Jim Inghambabfc382012-06-06 00:32:39 +00002125 else
2126 {
2127 if (log)
Ed Masteb3a53332014-03-17 17:05:22 +00002128 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching");
Jim Inghamcfc09352012-07-27 23:57:19 +00002129 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00002130 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002131 }
Jim Inghambabfc382012-06-06 00:32:39 +00002132 else
2133 {
2134 // If we missed setting the exit status on the way out, do it here.
2135 // NB set exit status can be called multiple times, the first one sets the status.
2136 exit_string.assign("destroying when not connected to debugserver");
2137 }
2138
2139 SetExitStatus(exit_status, exit_string.c_str());
2140
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002141 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002142 KillDebugserverProcess ();
2143 return error;
2144}
2145
Greg Clayton8cda7f02013-05-21 21:55:59 +00002146void
2147ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2148{
2149 lldb_private::Mutex::Locker locker (m_last_stop_packet_mutex);
2150 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2151 if (did_exec)
2152 {
2153 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2154 if (log)
2155 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2156
2157 m_thread_list_real.Clear();
2158 m_thread_list.Clear();
2159 BuildDynamicRegisterInfo (true);
2160 m_gdb_comm.ResetDiscoverableSettings();
2161 }
2162 m_last_stop_packet = response;
2163}
2164
2165
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002166//------------------------------------------------------------------
2167// Process Queries
2168//------------------------------------------------------------------
2169
2170bool
2171ProcessGDBRemote::IsAlive ()
2172{
Greg Clayton10177aa2010-12-08 05:08:21 +00002173 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002174}
2175
2176addr_t
2177ProcessGDBRemote::GetImageInfoAddress()
2178{
Jason Molenda6ba6d3d2013-01-30 04:39:32 +00002179 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002180}
2181
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002182//------------------------------------------------------------------
2183// Process Memory
2184//------------------------------------------------------------------
2185size_t
2186ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2187{
Jason Molenda6076bf42014-05-06 04:34:52 +00002188 GetMaxMemorySize ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002189 if (size > m_max_memory_size)
2190 {
2191 // Keep memory read sizes down to a sane limit. This function will be
2192 // called multiple times in order to complete the task by
2193 // lldb_private::Process so it is ok to do this.
2194 size = m_max_memory_size;
2195 }
2196
2197 char packet[64];
Jason Molenda6076bf42014-05-06 04:34:52 +00002198 int packet_len;
2199 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2200 if (binary_memory_read)
2201 {
2202 packet_len = ::snprintf (packet, sizeof(packet), "x0x%" PRIx64 ",0x%" PRIx64, (uint64_t)addr, (uint64_t)size);
2203 }
2204 else
2205 {
2206 packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
2207 }
Andy Gibbsa297a972013-06-19 19:04:53 +00002208 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002209 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002210 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002211 {
Greg Clayton576d8832011-03-22 04:00:09 +00002212 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002213 {
2214 error.Clear();
Jason Molenda6076bf42014-05-06 04:34:52 +00002215 if (binary_memory_read)
2216 {
2217 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any
2218 // 0x7d character escaping that was present in the packet
2219
2220 size_t data_received_size = response.GetBytesLeft();
2221 if (data_received_size > size)
2222 {
2223 // Don't write past the end of BUF if the remote debug server gave us too
2224 // much data for some reason.
2225 data_received_size = size;
2226 }
2227 memcpy (buf, response.GetStringRef().data(), data_received_size);
2228 return data_received_size;
2229 }
2230 else
2231 {
2232 return response.GetHexBytes(buf, size, '\xdd');
2233 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002234 }
Greg Clayton576d8832011-03-22 04:00:09 +00002235 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002236 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002237 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002238 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002239 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002240 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002241 }
2242 else
2243 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002244 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002245 }
2246 return 0;
2247}
2248
2249size_t
2250ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2251{
Jason Molenda6076bf42014-05-06 04:34:52 +00002252 GetMaxMemorySize ();
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002253 if (size > m_max_memory_size)
2254 {
2255 // Keep memory read sizes down to a sane limit. This function will be
2256 // called multiple times in order to complete the task by
2257 // lldb_private::Process so it is ok to do this.
2258 size = m_max_memory_size;
2259 }
2260
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002261 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00002262 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Clayton7fb56d02011-02-01 01:31:41 +00002263 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002264 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002265 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002266 {
Greg Clayton576d8832011-03-22 04:00:09 +00002267 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002268 {
2269 error.Clear();
2270 return size;
2271 }
Greg Clayton576d8832011-03-22 04:00:09 +00002272 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002273 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002274 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002275 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002276 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002277 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 +00002278 }
2279 else
2280 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002281 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002282 }
2283 return 0;
2284}
2285
2286lldb::addr_t
2287ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2288{
Todd Fialaaf245d12014-06-30 21:05:18 +00002289 lldb_private::Log *log (lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_EXPRESSIONS));
Greg Clayton2a48f522011-05-14 01:50:35 +00002290 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2291
Greg Clayton70b57652011-05-15 01:25:55 +00002292 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton2a48f522011-05-14 01:50:35 +00002293 switch (supported)
2294 {
2295 case eLazyBoolCalculate:
2296 case eLazyBoolYes:
2297 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2298 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2299 return allocated_addr;
2300
2301 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002302 // Call mmap() to create memory in the inferior..
2303 unsigned prot = 0;
2304 if (permissions & lldb::ePermissionsReadable)
2305 prot |= eMmapProtRead;
2306 if (permissions & lldb::ePermissionsWritable)
2307 prot |= eMmapProtWrite;
2308 if (permissions & lldb::ePermissionsExecutable)
2309 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00002310
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002311 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2312 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2313 m_addr_to_mmap_size[allocated_addr] = size;
2314 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002315 {
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002316 allocated_addr = LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00002317 if (log)
2318 log->Printf ("ProcessGDBRemote::%s no direct stub support for memory allocation, and InferiorCallMmap also failed - is stub missing register context save/restore capability?", __FUNCTION__);
2319 }
Greg Clayton2a48f522011-05-14 01:50:35 +00002320 break;
2321 }
2322
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002323 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00002324 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002325 else
2326 error.Clear();
2327 return allocated_addr;
2328}
2329
2330Error
Greg Clayton46fb5582011-11-18 07:03:08 +00002331ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2332 MemoryRegionInfo &region_info)
2333{
2334
2335 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2336 return error;
2337}
2338
2339Error
Johnny Chen64637202012-05-23 21:09:52 +00002340ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2341{
2342
2343 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2344 return error;
2345}
2346
2347Error
Enrico Granataf04a2192012-07-13 23:18:48 +00002348ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2349{
2350 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2351 return error;
2352}
2353
2354Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002355ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2356{
2357 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00002358 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2359
2360 switch (supported)
2361 {
2362 case eLazyBoolCalculate:
2363 // We should never be deallocating memory without allocating memory
2364 // first so we should never get eLazyBoolCalculate
2365 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2366 break;
2367
2368 case eLazyBoolYes:
2369 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00002370 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002371 break;
2372
2373 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002374 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00002375 {
2376 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002377 if (pos != m_addr_to_mmap_size.end() &&
2378 InferiorCallMunmap(this, addr, pos->second))
2379 m_addr_to_mmap_size.erase (pos);
2380 else
Daniel Malead01b2952012-11-29 21:49:15 +00002381 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002382 }
2383 break;
2384 }
2385
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002386 return error;
2387}
2388
2389
2390//------------------------------------------------------------------
2391// Process STDIO
2392//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002393size_t
2394ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2395{
2396 if (m_stdio_communication.IsConnected())
2397 {
2398 ConnectionStatus status;
2399 m_stdio_communication.Write(src, src_len, status, NULL);
2400 }
2401 return 0;
2402}
2403
2404Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002405ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002406{
2407 Error error;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002408 assert(bp_site != NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002409
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002410 // Get logging info
2411 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002412 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002413
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002414 // Get the breakpoint address
2415 const addr_t addr = bp_site->GetLoadAddress();
2416
2417 // Log that a breakpoint was requested
2418 if (log)
2419 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
2420
2421 // Breakpoint already exists and is enabled
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002422 if (bp_site->IsEnabled())
2423 {
2424 if (log)
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002425 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 +00002426 return error;
2427 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002428
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002429 // Get the software breakpoint trap opcode size
2430 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2431
2432 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
2433 // is supported by the remote stub. These are set to true by default, and later set to false
2434 // only after we receive an unimplemented response when sending a breakpoint packet. This means
2435 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
2436 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
2437 // indicates if the user specifically asked for hardware breakpoints. If true then we will
2438 // skip over software breakpoints.
2439 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
2440 {
2441 // Try to send off a software breakpoint packet ($Z0)
2442 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002443 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002444 // The breakpoint was placed successfully
2445 bp_site->SetEnabled(true);
2446 bp_site->SetType(BreakpointSite::eExternal);
Greg Claytoneb023e72013-10-11 19:48:25 +00002447 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002448 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002449
2450 // SendGDBStoppointTypePacket() will return an error if it was unable to set this
2451 // breakpoint. We need to differentiate between a error specific to placing this breakpoint
2452 // or if we have learned that this breakpoint type is unsupported. To do this, we
2453 // must test the support boolean for this breakpoint type to see if it now indicates that
2454 // this breakpoint type is unsupported. If they are still supported then we should return
2455 // with the error code. If they are now unsupported, then we would like to fall through
2456 // and try another form of breakpoint.
2457 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
2458 return error;
2459
2460 // We reach here when software breakpoints have been found to be unsupported. For future
2461 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
2462 // known not to be supported.
2463 if (log)
2464 log->Printf("Software breakpoints are unsupported");
2465
2466 // So we will fall through and try a hardware breakpoint
2467 }
2468
2469 // The process of setting a hardware breakpoint is much the same as above. We check the
2470 // supported boolean for this breakpoint type, and if it is thought to be supported then we
2471 // will try to set this breakpoint with a hardware breakpoint.
2472 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
2473 {
2474 // Try to send off a hardware breakpoint packet ($Z1)
2475 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002476 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002477 // The breakpoint was placed successfully
2478 bp_site->SetEnabled(true);
2479 bp_site->SetType(BreakpointSite::eHardware);
2480 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002481 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002482
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002483 // Check if the error was something other then an unsupported breakpoint type
2484 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
2485 {
2486 // Unable to set this hardware breakpoint
2487 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
2488 return error;
2489 }
2490
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002491 // We will reach here when the stub gives an unsupported response to a hardware breakpoint
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002492 if (log)
2493 log->Printf("Hardware breakpoints are unsupported");
2494
2495 // Finally we will falling through to a #trap style breakpoint
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002496 }
2497
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002498 // Don't fall through when hardware breakpoints were specifically requested
2499 if (bp_site->HardwareRequired())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002500 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002501 error.SetErrorString("hardware breakpoints are not supported");
2502 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002503 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002504
2505 // As a last resort we want to place a manual breakpoint. An instruction
2506 // is placed into the process memory using memory write packets.
2507 return EnableSoftwareBreakpoint(bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002508}
2509
2510Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002511ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002512{
2513 Error error;
2514 assert (bp_site != NULL);
2515 addr_t addr = bp_site->GetLoadAddress();
2516 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00002517 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002518 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002519 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002520
2521 if (bp_site->IsEnabled())
2522 {
2523 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2524
Greg Clayton8b82f082011-04-12 05:54:46 +00002525 BreakpointSite::Type bp_type = bp_site->GetType();
2526 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002527 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002528 case BreakpointSite::eSoftware:
2529 error = DisableSoftwareBreakpoint (bp_site);
2530 break;
2531
2532 case BreakpointSite::eHardware:
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002533 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00002534 error.SetErrorToGenericError();
2535 break;
2536
2537 case BreakpointSite::eExternal:
Jim Inghama04ef752014-03-07 11:18:02 +00002538 {
2539 GDBStoppointType stoppoint_type;
2540 if (bp_site->IsHardware())
2541 stoppoint_type = eBreakpointHardware;
2542 else
2543 stoppoint_type = eBreakpointSoftware;
2544
2545 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00002546 error.SetErrorToGenericError();
Jim Inghama04ef752014-03-07 11:18:02 +00002547 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002548 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002549 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002550 if (error.Success())
2551 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002552 }
2553 else
2554 {
2555 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002556 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 +00002557 return error;
2558 }
2559
2560 if (error.Success())
2561 error.SetErrorToGenericError();
2562 return error;
2563}
2564
Johnny Chen11309a32011-09-06 22:38:36 +00002565// Pre-requisite: wp != NULL.
2566static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00002567GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00002568{
2569 assert(wp);
2570 bool watch_read = wp->WatchpointRead();
2571 bool watch_write = wp->WatchpointWrite();
2572
2573 // watch_read and watch_write cannot both be false.
2574 assert(watch_read || watch_write);
2575 if (watch_read && watch_write)
2576 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00002577 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00002578 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00002579 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00002580 return eWatchpointWrite;
2581}
2582
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002583Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002584ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002585{
2586 Error error;
2587 if (wp)
2588 {
2589 user_id_t watchID = wp->GetID();
2590 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00002591 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002592 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002593 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002594 if (wp->IsEnabled())
2595 {
2596 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002597 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 +00002598 return error;
2599 }
Johnny Chen11309a32011-09-06 22:38:36 +00002600
2601 GDBStoppointType type = GetGDBStoppointType(wp);
2602 // Pass down an appropriate z/Z packet...
2603 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002604 {
Johnny Chen11309a32011-09-06 22:38:36 +00002605 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2606 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002607 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002608 return error;
2609 }
2610 else
2611 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002612 }
Johnny Chen11309a32011-09-06 22:38:36 +00002613 else
2614 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002615 }
2616 else
2617 {
Johnny Chen01a67862011-10-14 00:42:25 +00002618 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002619 }
2620 if (error.Success())
2621 error.SetErrorToGenericError();
2622 return error;
2623}
2624
2625Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002626ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002627{
2628 Error error;
2629 if (wp)
2630 {
2631 user_id_t watchID = wp->GetID();
2632
Greg Clayton5160ce52013-03-27 23:08:40 +00002633 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002634
2635 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00002636
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002637 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002638 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002639
Johnny Chen11309a32011-09-06 22:38:36 +00002640 if (!wp->IsEnabled())
2641 {
2642 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002643 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 +00002644 // See also 'class WatchpointSentry' within StopInfo.cpp.
2645 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2646 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00002647 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002648 return error;
2649 }
2650
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002651 if (wp->IsHardware())
2652 {
Johnny Chen11309a32011-09-06 22:38:36 +00002653 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002654 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00002655 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2656 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002657 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002658 return error;
2659 }
2660 else
2661 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002662 }
2663 // TODO: clear software watchpoints if we implement them
2664 }
2665 else
2666 {
Johnny Chen01a67862011-10-14 00:42:25 +00002667 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002668 }
2669 if (error.Success())
2670 error.SetErrorToGenericError();
2671 return error;
2672}
2673
2674void
2675ProcessGDBRemote::Clear()
2676{
2677 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002678 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002679 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002680}
2681
2682Error
2683ProcessGDBRemote::DoSignal (int signo)
2684{
2685 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002686 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002687 if (log)
2688 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2689
2690 if (!m_gdb_comm.SendAsyncSignal (signo))
2691 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2692 return error;
2693}
2694
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002695Error
Greg Clayton91a9b2472013-12-04 19:19:12 +00002696ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002697{
2698 Error error;
2699 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2700 {
2701 // If we locate debugserver, keep that located version around
2702 static FileSpec g_debugserver_file_spec;
2703
Han Ming Ong84647042012-02-25 01:07:38 +00002704 ProcessLaunchInfo debugserver_launch_info;
Greg Clayton91a9b2472013-12-04 19:19:12 +00002705 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2706 debugserver_launch_info.SetUserID(process_info.GetUserID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002707
Todd Fiala013434e2014-07-09 01:29:05 +00002708#if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__) || defined (__aarch64__))
Greg Claytonfda4fab2014-01-10 22:24:11 +00002709 // On iOS, still do a local connection using a random port
Greg Clayton16810922014-02-27 19:38:18 +00002710 const char *hostname = "127.0.0.1";
Greg Claytonfda4fab2014-01-10 22:24:11 +00002711 uint16_t port = get_random_port ();
2712#else
2713 // Set hostname being NULL to do the reverse connect where debugserver
2714 // will bind to port zero and it will communicate back to us the port
2715 // that we will connect to
2716 const char *hostname = NULL;
2717 uint16_t port = 0;
2718#endif
2719
2720 error = m_gdb_comm.StartDebugserverProcess (hostname,
2721 port,
Greg Clayton00fe87b2013-12-05 22:58:22 +00002722 debugserver_launch_info,
2723 port);
Greg Clayton91a9b2472013-12-04 19:19:12 +00002724
2725 if (error.Success ())
2726 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002727 else
Greg Clayton91a9b2472013-12-04 19:19:12 +00002728 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002729
2730 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2731 StartAsyncThread ();
Greg Clayton91a9b2472013-12-04 19:19:12 +00002732
2733 if (error.Fail())
2734 {
2735 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
2736
2737 if (log)
2738 log->Printf("failed to start debugserver process: %s", error.AsCString());
2739 return error;
2740 }
2741
Greg Clayton00fe87b2013-12-05 22:58:22 +00002742 if (m_gdb_comm.IsConnected())
2743 {
2744 // Finish the connection process by doing the handshake without connecting (send NULL URL)
2745 ConnectToDebugserver (NULL);
2746 }
2747 else
2748 {
Greg Claytonfda4fab2014-01-10 22:24:11 +00002749 StreamString connect_url;
2750 connect_url.Printf("connect://%s:%u", hostname, port);
2751 error = ConnectToDebugserver (connect_url.GetString().c_str());
Greg Clayton00fe87b2013-12-05 22:58:22 +00002752 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00002753
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002754 }
2755 return error;
2756}
2757
2758bool
2759ProcessGDBRemote::MonitorDebugserverProcess
2760(
2761 void *callback_baton,
2762 lldb::pid_t debugserver_pid,
Greg Claytone4e45922011-11-16 05:37:56 +00002763 bool exited, // True if the process did exit
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002764 int signo, // Zero for no signal
2765 int exit_status // Exit value of process if signal is zero
2766)
2767{
Greg Claytone4e45922011-11-16 05:37:56 +00002768 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2769 // and might not exist anymore, so we need to carefully try to get the
2770 // target for this process first since we have a race condition when
2771 // we are done running between getting the notice that the inferior
2772 // process has died and the debugserver that was debugging this process.
2773 // In our test suite, we are also continually running process after
2774 // process, so we must be very careful to make sure:
2775 // 1 - process object hasn't been deleted already
2776 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002777
2778 // "debugserver_pid" argument passed in is the process ID for
2779 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00002780 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002781
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002782 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton6779606a2011-01-22 23:43:18 +00002783
Greg Claytone4e45922011-11-16 05:37:56 +00002784 // Get a shared pointer to the target that has a matching process pointer.
2785 // This target could be gone, or the target could already have a new process
2786 // object inside of it
2787 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2788
Greg Clayton6779606a2011-01-22 23:43:18 +00002789 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002790 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 +00002791
Greg Claytone4e45922011-11-16 05:37:56 +00002792 if (target_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002793 {
Greg Claytone4e45922011-11-16 05:37:56 +00002794 // We found a process in a target that matches, but another thread
2795 // might be in the process of launching a new process that will
2796 // soon replace it, so get a shared pointer to the process so we
2797 // can keep it alive.
2798 ProcessSP process_sp (target_sp->GetProcessSP());
2799 // Now we have a shared pointer to the process that can't go away on us
2800 // so we now make sure it was the same as the one passed in, and also make
2801 // sure that our previous "process *" didn't get deleted and have a new
2802 // "process *" created in its place with the same pointer. To verify this
2803 // we make sure the process has our debugserver process ID. If we pass all
2804 // of these tests, then we are sure that this process is the one we were
2805 // looking for.
2806 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002807 {
Greg Claytone4e45922011-11-16 05:37:56 +00002808 // Sleep for a half a second to make sure our inferior process has
2809 // time to set its exit status before we set it incorrectly when
2810 // both the debugserver and the inferior process shut down.
2811 usleep (500000);
2812 // If our process hasn't yet exited, debugserver might have died.
2813 // If the process did exit, the we are reaping it.
2814 const StateType state = process->GetState();
2815
2816 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2817 state != eStateInvalid &&
2818 state != eStateUnloaded &&
2819 state != eStateExited &&
2820 state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002821 {
Greg Claytone4e45922011-11-16 05:37:56 +00002822 char error_str[1024];
2823 if (signo)
2824 {
2825 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2826 if (signal_cstr)
2827 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2828 else
2829 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2830 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002831 else
Greg Claytone4e45922011-11-16 05:37:56 +00002832 {
2833 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2834 }
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002835
Greg Claytone4e45922011-11-16 05:37:56 +00002836 process->SetExitStatus (-1, error_str);
2837 }
2838 // Debugserver has exited we need to let our ProcessGDBRemote
2839 // know that it no longer has a debugserver instance
2840 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002841 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002842 }
2843 return true;
2844}
2845
2846void
2847ProcessGDBRemote::KillDebugserverProcess ()
2848{
Greg Claytonfbb76342013-11-20 21:07:01 +00002849 m_gdb_comm.Disconnect();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002850 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2851 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002852 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002853 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2854 }
2855}
2856
2857void
2858ProcessGDBRemote::Initialize()
2859{
2860 static bool g_initialized = false;
2861
2862 if (g_initialized == false)
2863 {
2864 g_initialized = true;
2865 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2866 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00002867 CreateInstance,
2868 DebuggerInitialize);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002869
2870 Log::Callbacks log_callbacks = {
2871 ProcessGDBRemoteLog::DisableLog,
2872 ProcessGDBRemoteLog::EnableLog,
2873 ProcessGDBRemoteLog::ListLogCategories
2874 };
2875
2876 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2877 }
2878}
2879
Greg Clayton7f982402013-07-15 22:54:20 +00002880void
2881ProcessGDBRemote::DebuggerInitialize (lldb_private::Debugger &debugger)
2882{
2883 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
2884 {
2885 const bool is_global_setting = true;
2886 PluginManager::CreateSettingForProcessPlugin (debugger,
2887 GetGlobalPluginProperties()->GetValueProperties(),
2888 ConstString ("Properties for the gdb-remote process plug-in."),
2889 is_global_setting);
2890 }
2891}
2892
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002893bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002894ProcessGDBRemote::StartAsyncThread ()
2895{
Greg Clayton5160ce52013-03-27 23:08:40 +00002896 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002897
2898 if (log)
2899 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Ingham455fa5c2012-11-01 01:15:33 +00002900
2901 Mutex::Locker start_locker(m_async_thread_state_mutex);
2902 if (m_async_thread_state == eAsyncThreadNotStarted)
2903 {
2904 // Create a thread that watches our internal state and controls which
2905 // events make it to clients (into the DCProcess event queue).
2906 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2907 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2908 {
2909 m_async_thread_state = eAsyncThreadRunning;
2910 return true;
2911 }
2912 else
2913 return false;
2914 }
2915 else
2916 {
2917 // Somebody tried to start the async thread while it was either being started or stopped. If the former, and
2918 // it started up successfully, then say all's well. Otherwise it is an error, since we aren't going to restart it.
2919 if (log)
2920 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
2921 if (m_async_thread_state == eAsyncThreadRunning)
2922 return true;
2923 else
2924 return false;
2925 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002926}
2927
2928void
2929ProcessGDBRemote::StopAsyncThread ()
2930{
Greg Clayton5160ce52013-03-27 23:08:40 +00002931 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002932
2933 if (log)
2934 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2935
Jim Ingham455fa5c2012-11-01 01:15:33 +00002936 Mutex::Locker start_locker(m_async_thread_state_mutex);
2937 if (m_async_thread_state == eAsyncThreadRunning)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002938 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00002939 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2940
2941 // This will shut down the async thread.
2942 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
2943
2944 // Stop the stdio thread
2945 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2946 {
2947 Host::ThreadJoin (m_async_thread, NULL, NULL);
2948 }
2949 m_async_thread_state = eAsyncThreadDone;
2950 }
2951 else
2952 {
2953 if (log)
2954 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002955 }
2956}
2957
2958
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002959thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002960ProcessGDBRemote::AsyncThread (void *arg)
2961{
2962 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2963
Greg Clayton5160ce52013-03-27 23:08:40 +00002964 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002965 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002966 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002967
2968 Listener listener ("ProcessGDBRemote::AsyncThread");
2969 EventSP event_sp;
2970 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2971 eBroadcastBitAsyncThreadShouldExit;
2972
2973 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2974 {
Greg Clayton71337622011-02-24 22:24:29 +00002975 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2976
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002977 bool done = false;
2978 while (!done)
2979 {
2980 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002981 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002982 if (listener.WaitForEvent (NULL, event_sp))
2983 {
2984 const uint32_t event_type = event_sp->GetType();
Greg Clayton71337622011-02-24 22:24:29 +00002985 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002986 {
Greg Clayton71337622011-02-24 22:24:29 +00002987 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002988 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 +00002989
Greg Clayton71337622011-02-24 22:24:29 +00002990 switch (event_type)
2991 {
2992 case eBroadcastBitAsyncContinue:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002993 {
Greg Clayton71337622011-02-24 22:24:29 +00002994 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002995
Greg Clayton71337622011-02-24 22:24:29 +00002996 if (continue_packet)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002997 {
Greg Clayton71337622011-02-24 22:24:29 +00002998 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2999 const size_t continue_cstr_len = continue_packet->GetByteSize ();
3000 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003001 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003002
Greg Clayton71337622011-02-24 22:24:29 +00003003 if (::strstr (continue_cstr, "vAttach") == NULL)
3004 process->SetPrivateState(eStateRunning);
3005 StringExtractorGDBRemote response;
3006 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003007
Greg Clayton0772ded2012-05-16 02:48:06 +00003008 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
3009 // The thread ID list might be contained within the "response", or the stop reply packet that
3010 // caused the stop. So clear it now before we give the stop reply packet to the process
3011 // using the process->SetLastStopPacket()...
3012 process->ClearThreadIDList ();
3013
Greg Clayton71337622011-02-24 22:24:29 +00003014 switch (stop_state)
3015 {
3016 case eStateStopped:
3017 case eStateCrashed:
3018 case eStateSuspended:
Greg Clayton09c3e3d2011-12-06 04:51:14 +00003019 process->SetLastStopPacket (response);
Greg Clayton71337622011-02-24 22:24:29 +00003020 process->SetPrivateState (stop_state);
3021 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003022
Greg Clayton71337622011-02-24 22:24:29 +00003023 case eStateExited:
Jason Molendaa3329782014-03-29 18:54:20 +00003024 {
Greg Clayton09c3e3d2011-12-06 04:51:14 +00003025 process->SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00003026 process->ClearThreadIDList();
Greg Clayton71337622011-02-24 22:24:29 +00003027 response.SetFilePos(1);
Jason Molendaa3329782014-03-29 18:54:20 +00003028
3029 int exit_status = response.GetHexU8();
3030 const char *desc_cstr = NULL;
3031 StringExtractor extractor;
3032 std::string desc_string;
3033 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';')
3034 {
3035 std::string desc_token;
3036 while (response.GetNameColonValue (desc_token, desc_string))
3037 {
3038 if (desc_token == "description")
3039 {
3040 extractor.GetStringRef().swap(desc_string);
3041 extractor.SetFilePos(0);
3042 extractor.GetHexByteString (desc_string);
3043 desc_cstr = desc_string.c_str();
3044 }
3045 }
3046 }
3047 process->SetExitStatus(exit_status, desc_cstr);
Greg Clayton71337622011-02-24 22:24:29 +00003048 done = true;
3049 break;
Jason Molendaa3329782014-03-29 18:54:20 +00003050 }
Greg Clayton71337622011-02-24 22:24:29 +00003051 case eStateInvalid:
3052 process->SetExitStatus(-1, "lost connection");
3053 break;
3054
3055 default:
3056 process->SetPrivateState (stop_state);
3057 break;
3058 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003059 }
3060 }
Greg Clayton71337622011-02-24 22:24:29 +00003061 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003062
Greg Clayton71337622011-02-24 22:24:29 +00003063 case eBroadcastBitAsyncThreadShouldExit:
3064 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003065 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Clayton71337622011-02-24 22:24:29 +00003066 done = true;
3067 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003068
Greg Clayton71337622011-02-24 22:24:29 +00003069 default:
3070 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003071 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 +00003072 done = true;
3073 break;
3074 }
3075 }
3076 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
3077 {
3078 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
3079 {
3080 process->SetExitStatus (-1, "lost connection");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003081 done = true;
Greg Clayton71337622011-02-24 22:24:29 +00003082 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003083 }
3084 }
3085 else
3086 {
3087 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003088 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 +00003089 done = true;
3090 }
3091 }
3092 }
3093
3094 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003095 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003096
3097 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
3098 return NULL;
3099}
3100
Greg Claytone996fd32011-03-08 22:40:15 +00003101//uint32_t
3102//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3103//{
3104// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
3105// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
3106// if (m_local_debugserver)
3107// {
3108// return Host::ListProcessesMatchingName (name, matches, pids);
3109// }
3110// else
3111// {
3112// // FIXME: Implement talking to the remote debugserver.
3113// return 0;
3114// }
3115//
3116//}
3117//
Jim Ingham1c823b42011-01-22 01:33:44 +00003118bool
3119ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
3120 lldb_private::StoppointCallbackContext *context,
3121 lldb::user_id_t break_id,
3122 lldb::user_id_t break_loc_id)
3123{
3124 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3125 // run so I can stop it if that's what I want to do.
Greg Clayton5160ce52013-03-27 23:08:40 +00003126 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00003127 if (log)
3128 log->Printf("Hit New Thread Notification breakpoint.");
3129 return false;
3130}
3131
3132
3133bool
3134ProcessGDBRemote::StartNoticingNewThreads()
3135{
Greg Clayton5160ce52013-03-27 23:08:40 +00003136 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00003137 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003138 {
Greg Clayton4116e932012-05-15 02:33:01 +00003139 if (log && log->GetVerbose())
3140 log->Printf("Enabled noticing new thread breakpoint.");
3141 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003142 }
Greg Clayton4116e932012-05-15 02:33:01 +00003143 else
Jim Ingham1c823b42011-01-22 01:33:44 +00003144 {
Greg Clayton4116e932012-05-15 02:33:01 +00003145 PlatformSP platform_sp (m_target.GetPlatform());
3146 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003147 {
Greg Clayton4116e932012-05-15 02:33:01 +00003148 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3149 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003150 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00003151 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00003152 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3153 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003154 }
3155 else
3156 {
3157 if (log)
3158 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00003159 }
3160 }
3161 }
Greg Clayton4116e932012-05-15 02:33:01 +00003162 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00003163}
3164
3165bool
3166ProcessGDBRemote::StopNoticingNewThreads()
3167{
Greg Clayton5160ce52013-03-27 23:08:40 +00003168 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00003169 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00003170 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00003171
3172 if (m_thread_create_bp_sp)
3173 m_thread_create_bp_sp->SetEnabled(false);
3174
Jim Ingham1c823b42011-01-22 01:33:44 +00003175 return true;
3176}
3177
Jason Molenda5e8534e2012-10-03 01:29:34 +00003178lldb_private::DynamicLoader *
3179ProcessGDBRemote::GetDynamicLoader ()
3180{
3181 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00003182 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00003183 return m_dyld_ap.get();
3184}
Jim Ingham1c823b42011-01-22 01:33:44 +00003185
Jason Molendaa3329782014-03-29 18:54:20 +00003186Error
3187ProcessGDBRemote::SendEventData(const char *data)
3188{
3189 int return_value;
3190 bool was_supported;
3191
3192 Error error;
3193
3194 return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported);
3195 if (return_value != 0)
3196 {
3197 if (!was_supported)
3198 error.SetErrorString("Sending events is not supported for this process.");
3199 else
3200 error.SetErrorStringWithFormat("Error sending event data: %d.", return_value);
3201 }
3202 return error;
3203}
3204
Steve Pucci03904ac2014-03-04 23:18:46 +00003205const DataBufferSP
3206ProcessGDBRemote::GetAuxvData()
3207{
3208 DataBufferSP buf;
3209 if (m_gdb_comm.GetQXferAuxvReadSupported())
3210 {
3211 std::string response_string;
3212 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success)
3213 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length()));
3214 }
3215 return buf;
3216}
3217
Jason Molenda705b1802014-06-13 02:37:02 +00003218StructuredData::ObjectSP
3219ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid)
3220{
3221 StructuredData::ObjectSP object_sp;
3222
3223 if (m_gdb_comm.GetThreadExtendedInfoSupported())
3224 {
3225 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3226 SystemRuntime *runtime = GetSystemRuntime();
3227 if (runtime)
3228 {
3229 runtime->AddThreadExtendedInfoPacketHints (args_dict);
3230 }
3231 args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid);
3232
3233 StreamString packet;
3234 packet << "jThreadExtendedInfo:";
3235 args_dict->Dump (packet);
3236
3237 // FIXME the final character of a JSON dictionary, '}', is the escape
3238 // character in gdb-remote binary mode. lldb currently doesn't escape
3239 // these characters in its packet output -- so we add the quoted version
3240 // of the } character here manually in case we talk to a debugserver which
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003241 // un-escapes the characters at packet read time.
Jason Molenda705b1802014-06-13 02:37:02 +00003242 packet << (char) (0x7d ^ 0x20);
3243
3244 StringExtractorGDBRemote response;
3245 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
3246 {
3247 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
3248 if (response_type == StringExtractorGDBRemote::eResponse)
3249 {
3250 if (!response.Empty())
3251 {
3252 // The packet has already had the 0x7d xor quoting stripped out at the
3253 // GDBRemoteCommunication packet receive level.
3254 object_sp = StructuredData::ParseJSON (response.GetStringRef());
3255 }
3256 }
3257 }
3258 }
3259 return object_sp;
3260}
3261
Jason Molenda6076bf42014-05-06 04:34:52 +00003262// Establish the largest memory read/write payloads we should use.
3263// If the remote stub has a max packet size, stay under that size.
3264//
3265// If the remote stub's max packet size is crazy large, use a
3266// reasonable largeish default.
3267//
3268// If the remote stub doesn't advertise a max packet size, use a
3269// conservative default.
3270
3271void
3272ProcessGDBRemote::GetMaxMemorySize()
3273{
3274 const uint64_t reasonable_largeish_default = 128 * 1024;
3275 const uint64_t conservative_default = 512;
3276
3277 if (m_max_memory_size == 0)
3278 {
3279 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
3280 if (stub_max_size != UINT64_MAX && stub_max_size != 0)
3281 {
3282 // Save the stub's claimed maximum packet size
3283 m_remote_stub_max_memory_size = stub_max_size;
3284
3285 // Even if the stub says it can support ginormous packets,
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003286 // don't exceed our reasonable largeish default packet size.
Jason Molenda6076bf42014-05-06 04:34:52 +00003287 if (stub_max_size > reasonable_largeish_default)
3288 {
3289 stub_max_size = reasonable_largeish_default;
3290 }
3291
3292 m_max_memory_size = stub_max_size;
3293 }
3294 else
3295 {
3296 m_max_memory_size = conservative_default;
3297 }
3298 }
3299}
3300
3301void
3302ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max)
3303{
3304 if (user_specified_max != 0)
3305 {
3306 GetMaxMemorySize ();
3307
3308 if (m_remote_stub_max_memory_size != 0)
3309 {
3310 if (m_remote_stub_max_memory_size < user_specified_max)
3311 {
3312 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a packet size too big, go as big
3313 // as the remote stub says we can go.
3314 }
3315 else
3316 {
3317 m_max_memory_size = user_specified_max; // user's packet size is good
3318 }
3319 }
3320 else
3321 {
3322 m_max_memory_size = user_specified_max; // user's packet size is probably fine
3323 }
3324 }
3325}
3326
Greg Clayton02686b82012-10-15 22:42:16 +00003327class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00003328{
3329private:
3330
3331public:
Greg Clayton02686b82012-10-15 22:42:16 +00003332 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00003333 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00003334 "process plugin packet history",
3335 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00003336 NULL)
3337 {
3338 }
3339
Greg Clayton02686b82012-10-15 22:42:16 +00003340 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton998255b2012-10-13 02:07:45 +00003341 {
3342 }
3343
3344 bool
3345 DoExecute (Args& command, CommandReturnObject &result)
3346 {
Greg Clayton02686b82012-10-15 22:42:16 +00003347 const size_t argc = command.GetArgumentCount();
3348 if (argc == 0)
3349 {
3350 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3351 if (process)
3352 {
3353 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
3354 result.SetStatus (eReturnStatusSuccessFinishResult);
3355 return true;
3356 }
3357 }
3358 else
3359 {
3360 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
3361 }
3362 result.SetStatus (eReturnStatusFailed);
3363 return false;
3364 }
3365};
3366
Jason Molenda6076bf42014-05-06 04:34:52 +00003367class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed
3368{
3369private:
3370
3371public:
3372 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) :
3373 CommandObjectParsed (interpreter,
3374 "process plugin packet xfer-size",
3375 "Maximum size that lldb will try to read/write one one chunk.",
3376 NULL)
3377 {
3378 }
3379
3380 ~CommandObjectProcessGDBRemotePacketXferSize ()
3381 {
3382 }
3383
3384 bool
3385 DoExecute (Args& command, CommandReturnObject &result)
3386 {
3387 const size_t argc = command.GetArgumentCount();
3388 if (argc == 0)
3389 {
3390 result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str());
3391 result.SetStatus (eReturnStatusFailed);
3392 return false;
3393 }
3394
3395 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3396 if (process)
3397 {
3398 const char *packet_size = command.GetArgumentAtIndex(0);
3399 errno = 0;
3400 uint64_t user_specified_max = strtoul (packet_size, NULL, 10);
3401 if (errno == 0 && user_specified_max != 0)
3402 {
3403 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max);
3404 result.SetStatus (eReturnStatusSuccessFinishResult);
3405 return true;
3406 }
3407 }
3408 result.SetStatus (eReturnStatusFailed);
3409 return false;
3410 }
3411};
3412
3413
Greg Clayton02686b82012-10-15 22:42:16 +00003414class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
3415{
3416private:
3417
3418public:
3419 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
3420 CommandObjectParsed (interpreter,
3421 "process plugin packet send",
3422 "Send a custom packet through the GDB remote protocol and print the answer. "
3423 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
3424 NULL)
3425 {
3426 }
3427
3428 ~CommandObjectProcessGDBRemotePacketSend ()
3429 {
3430 }
3431
3432 bool
3433 DoExecute (Args& command, CommandReturnObject &result)
3434 {
3435 const size_t argc = command.GetArgumentCount();
3436 if (argc == 0)
3437 {
3438 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
3439 result.SetStatus (eReturnStatusFailed);
3440 return false;
3441 }
3442
3443 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3444 if (process)
3445 {
Han Ming Ong84145852012-11-26 20:42:03 +00003446 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00003447 {
Han Ming Ong84145852012-11-26 20:42:03 +00003448 const char *packet_cstr = command.GetArgumentAtIndex(0);
3449 bool send_async = true;
3450 StringExtractorGDBRemote response;
3451 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3452 result.SetStatus (eReturnStatusSuccessFinishResult);
3453 Stream &output_strm = result.GetOutputStream();
3454 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00003455 std::string &response_str = response.GetStringRef();
3456
Han Ming Ong399289e2013-06-21 19:56:59 +00003457 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00003458 {
3459 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
3460 }
3461
Han Ming Ong84145852012-11-26 20:42:03 +00003462 if (response_str.empty())
3463 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3464 else
3465 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00003466 }
Greg Clayton02686b82012-10-15 22:42:16 +00003467 }
Greg Clayton998255b2012-10-13 02:07:45 +00003468 return true;
3469 }
3470};
3471
Greg Claytonba4a0a52013-02-01 23:03:47 +00003472class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
3473{
3474private:
3475
3476public:
3477 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
3478 CommandObjectRaw (interpreter,
3479 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00003480 "Send a qRcmd packet through the GDB remote protocol and print the response."
3481 "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 +00003482 NULL)
3483 {
3484 }
3485
3486 ~CommandObjectProcessGDBRemotePacketMonitor ()
3487 {
3488 }
3489
3490 bool
3491 DoExecute (const char *command, CommandReturnObject &result)
3492 {
3493 if (command == NULL || command[0] == '\0')
3494 {
3495 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
3496 result.SetStatus (eReturnStatusFailed);
3497 return false;
3498 }
3499
3500 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3501 if (process)
3502 {
3503 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00003504 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00003505 packet.PutBytesAsRawHex8(command, strlen(command));
3506 const char *packet_cstr = packet.GetString().c_str();
3507
3508 bool send_async = true;
3509 StringExtractorGDBRemote response;
3510 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3511 result.SetStatus (eReturnStatusSuccessFinishResult);
3512 Stream &output_strm = result.GetOutputStream();
3513 output_strm.Printf (" packet: %s\n", packet_cstr);
3514 const std::string &response_str = response.GetStringRef();
3515
3516 if (response_str.empty())
3517 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3518 else
3519 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
3520 }
3521 return true;
3522 }
3523};
3524
Greg Clayton02686b82012-10-15 22:42:16 +00003525class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
3526{
3527private:
3528
3529public:
3530 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
3531 CommandObjectMultiword (interpreter,
3532 "process plugin packet",
3533 "Commands that deal with GDB remote packets.",
3534 NULL)
3535 {
3536 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
3537 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00003538 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Jason Molenda6076bf42014-05-06 04:34:52 +00003539 LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00003540 }
3541
3542 ~CommandObjectProcessGDBRemotePacket ()
3543 {
3544 }
3545};
Greg Clayton998255b2012-10-13 02:07:45 +00003546
3547class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
3548{
3549public:
3550 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
3551 CommandObjectMultiword (interpreter,
3552 "process plugin",
3553 "A set of commands for operating on a ProcessGDBRemote process.",
3554 "process plugin <subcommand> [<subcommand-options>]")
3555 {
3556 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
3557 }
3558
3559 ~CommandObjectMultiwordProcessGDBRemote ()
3560 {
3561 }
3562};
3563
Greg Clayton998255b2012-10-13 02:07:45 +00003564CommandObject *
3565ProcessGDBRemote::GetPluginCommandObject()
3566{
3567 if (!m_command_sp)
3568 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
3569 return m_command_sp.get();
3570}