blob: 4a3bd041524c06cf5f52d5c6ea4809e80cc45bf5 [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/InputReader.h"
38#include "lldb/Core/Module.h"
Greg Clayton1f746072012-08-29 21:13:06 +000039#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000040#include "lldb/Core/PluginManager.h"
41#include "lldb/Core/State.h"
Greg Claytond451c1a2012-04-13 21:24:18 +000042#include "lldb/Core/StreamFile.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000043#include "lldb/Core/StreamString.h"
44#include "lldb/Core/Timer.h"
Greg Clayton70b57652011-05-15 01:25:55 +000045#include "lldb/Core/Value.h"
Jason Molendad1fae142012-09-29 08:03:33 +000046#include "lldb/Host/Symbols.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000047#include "lldb/Host/TimeValue.h"
Greg Clayton02686b82012-10-15 22:42:16 +000048#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton1d19a2f2012-10-19 22:22:57 +000049#include "lldb/Interpreter/CommandObject.h"
50#include "lldb/Interpreter/CommandObjectMultiword.h"
Greg Clayton02686b82012-10-15 22:42:16 +000051#include "lldb/Interpreter/CommandReturnObject.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000052#include "lldb/Symbol/ObjectFile.h"
53#include "lldb/Target/DynamicLoader.h"
54#include "lldb/Target/Target.h"
55#include "lldb/Target/TargetList.h"
Greg Clayton2a48f522011-05-14 01:50:35 +000056#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molendaa34a0c62010-06-09 21:28:42 +000057#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000058
59// Project includes
60#include "lldb/Host/Host.h"
Peter Collingbourne99f9aa02011-06-03 20:40:38 +000061#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Jason Molendac42d2432012-07-25 03:40:06 +000062#include "Plugins/Process/Utility/StopInfoMachException.h"
Jim Ingham43c555d2012-07-04 00:35:43 +000063#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
Greg Claytonc982c762010-07-09 20:39:50 +000064#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000065#include "GDBRemoteRegisterContext.h"
66#include "ProcessGDBRemote.h"
67#include "ProcessGDBRemoteLog.h"
68#include "ThreadGDBRemote.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000069
Jason Molenda5e8534e2012-10-03 01:29:34 +000070
Greg Claytonc1422c12012-04-09 22:46:21 +000071namespace lldb
72{
73 // Provide a function that can easily dump the packet history if we know a
74 // ProcessGDBRemote * value (which we can get from logs or from debugging).
75 // We need the function in the lldb namespace so it makes it into the final
76 // executable since the LLDB shared library only exports stuff in the lldb
77 // namespace. This allows you to attach with a debugger and call this
78 // function and get the packet history dumped to a file.
79 void
80 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
81 {
Greg Claytond451c1a2012-04-13 21:24:18 +000082 lldb_private::StreamFile strm;
83 lldb_private::Error error (strm.GetFile().Open(path, lldb_private::File::eOpenOptionWrite | lldb_private::File::eOpenOptionCanCreate));
84 if (error.Success())
85 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
Greg Claytonc1422c12012-04-09 22:46:21 +000086 }
Filipe Cabecinhasc34f7762012-05-23 16:27:09 +000087}
Chris Lattner30fdc8d2010-06-08 16:52:24 +000088
Chris Lattner30fdc8d2010-06-08 16:52:24 +000089#define DEBUGSERVER_BASENAME "debugserver"
90using namespace lldb;
91using namespace lldb_private;
92
Greg Clayton7f982402013-07-15 22:54:20 +000093
94namespace {
95
96 static PropertyDefinition
97 g_properties[] =
98 {
99 { "packet-timeout" , OptionValue::eTypeUInt64 , true , 1, NULL, NULL, "Specify the default packet timeout in seconds." },
100 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
101 };
102
103 enum
104 {
105 ePropertyPacketTimeout
106 };
107
108 class PluginProperties : public Properties
109 {
110 public:
111
112 static ConstString
113 GetSettingName ()
114 {
115 return ProcessGDBRemote::GetPluginNameStatic();
116 }
117
118 PluginProperties() :
119 Properties ()
120 {
121 m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
122 m_collection_sp->Initialize(g_properties);
123 }
124
125 virtual
126 ~PluginProperties()
127 {
128 }
129
130 uint64_t
131 GetPacketTimeout()
132 {
133 const uint32_t idx = ePropertyPacketTimeout;
134 return m_collection_sp->GetPropertyAtIndexAsUInt64(NULL, idx, g_properties[idx].default_uint_value);
135 }
136 };
137
138 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
139
140 static const ProcessKDPPropertiesSP &
141 GetGlobalPluginProperties()
142 {
143 static ProcessKDPPropertiesSP g_settings_sp;
144 if (!g_settings_sp)
145 g_settings_sp.reset (new PluginProperties ());
146 return g_settings_sp;
147 }
148
149} // anonymous namespace end
150
Jim Ingham7572fa72011-03-29 21:45:47 +0000151static bool rand_initialized = false;
152
Sean Callanan224f6f52012-07-19 18:07:36 +0000153// TODO Randomly assigning a port is unsafe. We should get an unused
154// ephemeral port from the kernel and make sure we reserve it before passing
155// it to debugserver.
156
157#if defined (__APPLE__)
158#define LOW_PORT (IPPORT_RESERVED)
159#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
160#else
161#define LOW_PORT (1024u)
162#define HIGH_PORT (49151u)
163#endif
164
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000165static inline uint16_t
166get_random_port ()
167{
Jim Ingham7572fa72011-03-29 21:45:47 +0000168 if (!rand_initialized)
169 {
Stephen Wilsondc916862011-03-30 00:12:40 +0000170 time_t seed = time(NULL);
171
Jim Ingham7572fa72011-03-29 21:45:47 +0000172 rand_initialized = true;
Stephen Wilsondc916862011-03-30 00:12:40 +0000173 srand(seed);
Jim Ingham7572fa72011-03-29 21:45:47 +0000174 }
Sean Callanan224f6f52012-07-19 18:07:36 +0000175 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000176}
177
178
Greg Clayton57abc5d2013-05-10 21:47:16 +0000179lldb_private::ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000180ProcessGDBRemote::GetPluginNameStatic()
181{
Greg Clayton57abc5d2013-05-10 21:47:16 +0000182 static ConstString g_name("gdb-remote");
183 return g_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000184}
185
186const char *
187ProcessGDBRemote::GetPluginDescriptionStatic()
188{
189 return "GDB Remote protocol based debugging plug-in.";
190}
191
192void
193ProcessGDBRemote::Terminate()
194{
195 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
196}
197
198
Greg Claytonc3776bf2012-02-09 06:16:32 +0000199lldb::ProcessSP
200ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000201{
Greg Claytonc3776bf2012-02-09 06:16:32 +0000202 lldb::ProcessSP process_sp;
203 if (crash_file_path == NULL)
204 process_sp.reset (new ProcessGDBRemote (target, listener));
205 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000206}
207
208bool
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000209ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000210{
Greg Clayton596ed242011-10-21 21:41:45 +0000211 if (plugin_specified_by_name)
212 return true;
213
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000214 // For now we are just making sure the file exists for a given module
Greg Claytonaa149cb2011-08-11 02:48:45 +0000215 Module *exe_module = target.GetExecutableModulePointer();
216 if (exe_module)
Greg Claytonc3776bf2012-02-09 06:16:32 +0000217 {
218 ObjectFile *exe_objfile = exe_module->GetObjectFile();
219 // We can't debug core files...
220 switch (exe_objfile->GetType())
221 {
222 case ObjectFile::eTypeInvalid:
223 case ObjectFile::eTypeCoreFile:
224 case ObjectFile::eTypeDebugInfo:
225 case ObjectFile::eTypeObjectFile:
226 case ObjectFile::eTypeSharedLibrary:
227 case ObjectFile::eTypeStubLibrary:
228 return false;
229 case ObjectFile::eTypeExecutable:
230 case ObjectFile::eTypeDynamicLinker:
231 case ObjectFile::eTypeUnknown:
232 break;
233 }
Greg Claytonaa149cb2011-08-11 02:48:45 +0000234 return exe_module->GetFileSpec().Exists();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000235 }
Jim Ingham5aee1622010-08-09 23:31:02 +0000236 // However, if there is no executable module, we return true since we might be preparing to attach.
237 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000238}
239
240//----------------------------------------------------------------------
241// ProcessGDBRemote constructor
242//----------------------------------------------------------------------
243ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
244 Process (target, listener),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000245 m_flags (0),
Greg Clayton8b82f082011-04-12 05:54:46 +0000246 m_gdb_comm(false),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000247 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Claytonc982c762010-07-09 20:39:50 +0000248 m_last_stop_packet (),
Greg Clayton09c3e3d2011-12-06 04:51:14 +0000249 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000250 m_register_info (),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000251 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000252 m_async_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham455fa5c2012-11-01 01:15:33 +0000253 m_async_thread_state(eAsyncThreadNotStarted),
254 m_async_thread_state_mutex(Mutex::eMutexTypeRecursive),
Greg Clayton9e920902012-04-10 02:25:43 +0000255 m_thread_ids (),
Greg Clayton71fc2a32011-02-12 06:28:37 +0000256 m_continue_c_tids (),
257 m_continue_C_tids (),
258 m_continue_s_tids (),
259 m_continue_S_tids (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000260 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Claytonc982c762010-07-09 20:39:50 +0000261 m_max_memory_size (512),
Greg Clayton4116e932012-05-15 02:33:01 +0000262 m_addr_to_mmap_size (),
263 m_thread_create_bp_sp (),
Jim Ingham43c555d2012-07-04 00:35:43 +0000264 m_waiting_for_attach (false),
Jason Molenda5e8534e2012-10-03 01:29:34 +0000265 m_destroy_tried_resuming (false),
Greg Clayton998255b2012-10-13 02:07:45 +0000266 m_command_sp ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000267{
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000268 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
269 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Inghamb1e2e842012-04-12 18:49:31 +0000270 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Greg Clayton7f982402013-07-15 22:54:20 +0000271 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
272 if (timeout_seconds > 0)
273 m_gdb_comm.SetPacketTimeout(timeout_seconds);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000274}
275
276//----------------------------------------------------------------------
277// Destructor
278//----------------------------------------------------------------------
279ProcessGDBRemote::~ProcessGDBRemote()
280{
281 // m_mach_process.UnregisterNotificationCallbacks (this);
282 Clear();
Greg Clayton1ed54f52011-10-01 00:45:15 +0000283 // We need to call finalize on the process before destroying ourselves
284 // to make sure all of the broadcaster cleanup goes as planned. If we
285 // destruct this class, then Process::~Process() might have problems
286 // trying to fully destroy the broadcaster.
287 Finalize();
Jim Ingham455fa5c2012-11-01 01:15:33 +0000288
289 // The general Finalize is going to try to destroy the process and that SHOULD
290 // shut down the async thread. However, if we don't kill it it will get stranded and
291 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
292 StopAsyncThread();
293 KillDebugserverProcess();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000294}
295
296//----------------------------------------------------------------------
297// PluginInterface
298//----------------------------------------------------------------------
Greg Clayton57abc5d2013-05-10 21:47:16 +0000299ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000300ProcessGDBRemote::GetPluginName()
301{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000302 return GetPluginNameStatic();
303}
304
305uint32_t
306ProcessGDBRemote::GetPluginVersion()
307{
308 return 1;
309}
310
311void
Greg Clayton513c26c2011-01-29 07:10:55 +0000312ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000313{
Greg Clayton513c26c2011-01-29 07:10:55 +0000314 if (!force && m_register_info.GetNumRegisters() > 0)
315 return;
316
317 char packet[128];
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000318 m_register_info.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000319 uint32_t reg_offset = 0;
320 uint32_t reg_num = 0;
Greg Clayton23f59502012-07-17 03:23:13 +0000321 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Greg Clayton576d8832011-03-22 04:00:09 +0000322 response_type == StringExtractorGDBRemote::eResponse;
323 ++reg_num)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000324 {
Greg Clayton513c26c2011-01-29 07:10:55 +0000325 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
Andy Gibbsa297a972013-06-19 19:04:53 +0000326 assert (packet_len < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000327 StringExtractorGDBRemote response;
Greg Claytonc574ede2011-03-10 02:26:48 +0000328 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000329 {
Greg Clayton576d8832011-03-22 04:00:09 +0000330 response_type = response.GetResponseType();
331 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000332 {
333 std::string name;
334 std::string value;
335 ConstString reg_name;
336 ConstString alt_name;
337 ConstString set_name;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000338 std::vector<uint32_t> value_regs;
339 std::vector<uint32_t> invalidate_regs;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000340 RegisterInfo reg_info = { NULL, // Name
341 NULL, // Alt name
342 0, // byte size
343 reg_offset, // offset
344 eEncodingUint, // encoding
345 eFormatHex, // formate
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000346 {
347 LLDB_INVALID_REGNUM, // GCC reg num
348 LLDB_INVALID_REGNUM, // DWARF reg num
349 LLDB_INVALID_REGNUM, // generic reg num
Jason Molendafbcb7f22010-09-10 07:49:16 +0000350 reg_num, // GDB reg num
351 reg_num // native register number
Greg Clayton435d85a2012-02-29 19:27:27 +0000352 },
353 NULL,
354 NULL
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000355 };
356
357 while (response.GetNameColonValue(name, value))
358 {
359 if (name.compare("name") == 0)
360 {
361 reg_name.SetCString(value.c_str());
362 }
363 else if (name.compare("alt-name") == 0)
364 {
365 alt_name.SetCString(value.c_str());
366 }
367 else if (name.compare("bitsize") == 0)
368 {
369 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
370 }
371 else if (name.compare("offset") == 0)
372 {
373 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda743e86a2010-06-11 23:44:18 +0000374 if (reg_offset != offset)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000375 {
376 reg_offset = offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000377 }
378 }
379 else if (name.compare("encoding") == 0)
380 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000381 const Encoding encoding = Args::StringToEncoding (value.c_str());
382 if (encoding != eEncodingInvalid)
383 reg_info.encoding = encoding;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000384 }
385 else if (name.compare("format") == 0)
386 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000387 Format format = eFormatInvalid;
388 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
389 reg_info.format = format;
390 else if (value.compare("binary") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000391 reg_info.format = eFormatBinary;
392 else if (value.compare("decimal") == 0)
393 reg_info.format = eFormatDecimal;
394 else if (value.compare("hex") == 0)
395 reg_info.format = eFormatHex;
396 else if (value.compare("float") == 0)
397 reg_info.format = eFormatFloat;
398 else if (value.compare("vector-sint8") == 0)
399 reg_info.format = eFormatVectorOfSInt8;
400 else if (value.compare("vector-uint8") == 0)
401 reg_info.format = eFormatVectorOfUInt8;
402 else if (value.compare("vector-sint16") == 0)
403 reg_info.format = eFormatVectorOfSInt16;
404 else if (value.compare("vector-uint16") == 0)
405 reg_info.format = eFormatVectorOfUInt16;
406 else if (value.compare("vector-sint32") == 0)
407 reg_info.format = eFormatVectorOfSInt32;
408 else if (value.compare("vector-uint32") == 0)
409 reg_info.format = eFormatVectorOfUInt32;
410 else if (value.compare("vector-float32") == 0)
411 reg_info.format = eFormatVectorOfFloat32;
412 else if (value.compare("vector-uint128") == 0)
413 reg_info.format = eFormatVectorOfUInt128;
414 }
415 else if (name.compare("set") == 0)
416 {
417 set_name.SetCString(value.c_str());
418 }
419 else if (name.compare("gcc") == 0)
420 {
421 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
422 }
423 else if (name.compare("dwarf") == 0)
424 {
425 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
426 }
427 else if (name.compare("generic") == 0)
428 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000429 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000430 }
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000431 else if (name.compare("container-regs") == 0)
432 {
433 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
434 value_pair.second = value;
435 do
436 {
437 value_pair = value_pair.second.split(',');
438 if (!value_pair.first.empty())
439 {
Greg Clayton0ba20242013-01-21 23:32:42 +0000440 uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
441 if (reg != LLDB_INVALID_REGNUM)
442 value_regs.push_back (reg);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000443 }
444 } while (!value_pair.second.empty());
445 }
446 else if (name.compare("invalidate-regs") == 0)
447 {
448 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
449 value_pair.second = value;
450 do
451 {
452 value_pair = value_pair.second.split(',');
453 if (!value_pair.first.empty())
454 {
Greg Clayton0ba20242013-01-21 23:32:42 +0000455 uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
456 if (reg != LLDB_INVALID_REGNUM)
457 invalidate_regs.push_back (reg);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000458 }
459 } while (!value_pair.second.empty());
460 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000461 }
462
Jason Molenda743e86a2010-06-11 23:44:18 +0000463 reg_info.byte_offset = reg_offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000464 assert (reg_info.byte_size != 0);
465 reg_offset += reg_info.byte_size;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000466 if (!value_regs.empty())
467 {
468 value_regs.push_back(LLDB_INVALID_REGNUM);
469 reg_info.value_regs = value_regs.data();
470 }
471 if (!invalidate_regs.empty())
472 {
473 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
474 reg_info.invalidate_regs = invalidate_regs.data();
475 }
476
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000477 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
478 }
479 }
480 else
481 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000482 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000483 }
484 }
485
Johnny Chen2fa9de12012-05-14 18:44:23 +0000486 // We didn't get anything if the accumulated reg_num is zero. See if we are
487 // debugging ARM and fill with a hard coded register set until we can get an
488 // updated debugserver down on the devices.
489 // On the other hand, if the accumulated reg_num is positive, see if we can
490 // add composite registers to the existing primordial ones.
491 bool from_scratch = (reg_num == 0);
492
493 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000494 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
495 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
496
497 // Use the process' architecture instead of the host arch, if available
498 ArchSpec remote_arch;
499 if (remote_process_arch.IsValid ())
500 remote_arch = remote_process_arch;
501 else
502 remote_arch = remote_host_arch;
503
Johnny Chen2fa9de12012-05-14 18:44:23 +0000504 if (!target_arch.IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000505 {
Johnny Chen2fa9de12012-05-14 18:44:23 +0000506 if (remote_arch.IsValid()
507 && remote_arch.GetMachine() == llvm::Triple::arm
508 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
509 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000510 }
Johnny Chen2fa9de12012-05-14 18:44:23 +0000511 else if (target_arch.GetMachine() == llvm::Triple::arm)
512 {
513 m_register_info.HardcodeARMRegisters(from_scratch);
514 }
515
516 // At this point, we can finalize our register info.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000517 m_register_info.Finalize ();
518}
519
520Error
521ProcessGDBRemote::WillLaunch (Module* module)
522{
523 return WillLaunchOrAttach ();
524}
525
526Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000527ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000528{
529 return WillLaunchOrAttach ();
530}
531
532Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000533ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000534{
535 return WillLaunchOrAttach ();
536}
537
538Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000539ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +0000540{
541 Error error (WillLaunchOrAttach ());
542
543 if (error.Fail())
544 return error;
545
Greg Clayton2289fa42011-04-30 01:09:13 +0000546 error = ConnectToDebugserver (remote_url);
Greg Claytonb766a732011-02-04 01:58:07 +0000547
548 if (error.Fail())
549 return error;
550 StartAsyncThread ();
551
Greg Claytonc574ede2011-03-10 02:26:48 +0000552 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonb766a732011-02-04 01:58:07 +0000553 if (pid == LLDB_INVALID_PROCESS_ID)
554 {
555 // We don't have a valid process ID, so note that we are connected
556 // and could now request to launch or attach, or get remote process
557 // listings...
558 SetPrivateState (eStateConnected);
559 }
560 else
561 {
562 // We have a valid process
563 SetID (pid);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000564 GetThreadList();
Greg Claytondd0e5a52011-06-02 22:22:38 +0000565 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytonb766a732011-02-04 01:58:07 +0000566 {
Greg Claytondd0e5a52011-06-02 22:22:38 +0000567 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytonb766a732011-02-04 01:58:07 +0000568 if (state == eStateStopped)
569 {
570 SetPrivateState (state);
571 }
572 else
Daniel Malead01b2952012-11-29 21:49:15 +0000573 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 +0000574 }
575 else
Daniel Malead01b2952012-11-29 21:49:15 +0000576 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 +0000577 }
Jason Molenda16d127c2012-05-03 22:37:30 +0000578
579 if (error.Success()
580 && !GetTarget().GetArchitecture().IsValid()
581 && m_gdb_comm.GetHostArchitecture().IsValid())
582 {
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000583 // Prefer the *process'* architecture over that of the *host*, if available.
584 if (m_gdb_comm.GetProcessArchitecture().IsValid())
585 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
586 else
587 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molenda16d127c2012-05-03 22:37:30 +0000588 }
589
Greg Claytonb766a732011-02-04 01:58:07 +0000590 return error;
591}
592
593Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000594ProcessGDBRemote::WillLaunchOrAttach ()
595{
596 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000597 m_stdio_communication.Clear ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000598 return error;
599}
600
601//----------------------------------------------------------------------
602// Process Control
603//----------------------------------------------------------------------
604Error
Greg Clayton982c9762011-11-03 21:22:33 +0000605ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000606{
Greg Clayton4957bf62010-09-30 21:49:03 +0000607 Error error;
Greg Clayton982c9762011-11-03 21:22:33 +0000608
609 uint32_t launch_flags = launch_info.GetFlags().Get();
610 const char *stdin_path = NULL;
611 const char *stdout_path = NULL;
612 const char *stderr_path = NULL;
613 const char *working_dir = launch_info.GetWorkingDirectory();
614
615 const ProcessLaunchInfo::FileAction *file_action;
616 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
617 if (file_action)
618 {
619 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
620 stdin_path = file_action->GetPath();
621 }
622 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
623 if (file_action)
624 {
625 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
626 stdout_path = file_action->GetPath();
627 }
628 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
629 if (file_action)
630 {
631 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
632 stderr_path = file_action->GetPath();
633 }
634
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000635 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
636 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
637 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton5160ce52013-03-27 23:08:40 +0000638 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000639
Greg Clayton982c9762011-11-03 21:22:33 +0000640 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000641 if (object_file)
642 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000643 char host_port[128];
644 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytonb766a732011-02-04 01:58:07 +0000645 char connect_url[128];
646 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000647
Greg Clayton71337622011-02-24 22:24:29 +0000648 // Make sure we aren't already connected?
649 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000650 {
Han Ming Ong84647042012-02-25 01:07:38 +0000651 error = StartDebugserverProcess (host_port, launch_info);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000652 if (error.Fail())
Greg Claytonc235ac72011-08-09 05:20:29 +0000653 {
Johnny Chen4c1e9202011-08-09 18:56:45 +0000654 if (log)
655 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000656 return error;
Greg Claytonc235ac72011-08-09 05:20:29 +0000657 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000658
Greg Claytonb766a732011-02-04 01:58:07 +0000659 error = ConnectToDebugserver (connect_url);
Greg Clayton71337622011-02-24 22:24:29 +0000660 }
661
662 if (error.Success())
663 {
664 lldb_utility::PseudoTerminal pty;
665 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000666
667 // If the debugserver is local and we aren't disabling STDIO, lets use
668 // a pseudo terminal to instead of relying on the 'O' packets for stdio
669 // since 'O' packets can really slow down debugging if the inferior
670 // does a lot of output.
Greg Claytonf58c2692011-06-24 22:32:10 +0000671 PlatformSP platform_sp (m_target.GetPlatform());
672 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Clayton71337622011-02-24 22:24:29 +0000673 {
674 const char *slave_name = NULL;
675 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000676 {
Greg Clayton71337622011-02-24 22:24:29 +0000677 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
678 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000679 }
Greg Clayton71337622011-02-24 22:24:29 +0000680 if (stdin_path == NULL)
681 stdin_path = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000682
Greg Clayton71337622011-02-24 22:24:29 +0000683 if (stdout_path == NULL)
684 stdout_path = slave_name;
685
686 if (stderr_path == NULL)
687 stderr_path = slave_name;
688 }
689
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000690 // Set STDIN to /dev/null if we want STDIO disabled or if either
691 // STDOUT or STDERR have been set to something and STDIN hasn't
692 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000693 stdin_path = "/dev/null";
694
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000695 // Set STDOUT to /dev/null if we want STDIO disabled or if either
696 // STDIN or STDERR have been set to something and STDOUT hasn't
697 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000698 stdout_path = "/dev/null";
699
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000700 // Set STDERR to /dev/null if we want STDIO disabled or if either
701 // STDIN or STDOUT have been set to something and STDERR hasn't
702 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000703 stderr_path = "/dev/null";
704
705 if (stdin_path)
706 m_gdb_comm.SetSTDIN (stdin_path);
707 if (stdout_path)
708 m_gdb_comm.SetSTDOUT (stdout_path);
709 if (stderr_path)
710 m_gdb_comm.SetSTDERR (stderr_path);
711
712 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
713
Greg Claytonc4103b32011-05-08 04:53:50 +0000714 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Clayton71337622011-02-24 22:24:29 +0000715
716 if (working_dir && working_dir[0])
717 {
718 m_gdb_comm.SetWorkingDir (working_dir);
719 }
720
721 // Send the environment and the program + arguments after we connect
Greg Clayton982c9762011-11-03 21:22:33 +0000722 const Args &environment = launch_info.GetEnvironmentEntries();
723 if (environment.GetArgumentCount())
Greg Clayton71337622011-02-24 22:24:29 +0000724 {
Greg Clayton982c9762011-11-03 21:22:33 +0000725 size_t num_environment_entries = environment.GetArgumentCount();
726 for (size_t i=0; i<num_environment_entries; ++i)
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000727 {
Greg Clayton982c9762011-11-03 21:22:33 +0000728 const char *env_entry = environment.GetArgumentAtIndex(i);
729 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Clayton71337622011-02-24 22:24:29 +0000730 break;
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000731 }
Greg Clayton71337622011-02-24 22:24:29 +0000732 }
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000733
Greg Claytonc574ede2011-03-10 02:26:48 +0000734 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Clayton982c9762011-11-03 21:22:33 +0000735 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info.GetArguments().GetConstArgumentVector());
Greg Clayton71337622011-02-24 22:24:29 +0000736 if (arg_packet_err == 0)
737 {
738 std::string error_str;
Greg Claytonc574ede2011-03-10 02:26:48 +0000739 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000740 {
Greg Claytonc574ede2011-03-10 02:26:48 +0000741 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000742 }
743 else
744 {
Greg Clayton71337622011-02-24 22:24:29 +0000745 error.SetErrorString (error_str.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000746 }
Greg Clayton71337622011-02-24 22:24:29 +0000747 }
748 else
749 {
Greg Clayton86edbf42011-10-26 00:56:27 +0000750 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Clayton71337622011-02-24 22:24:29 +0000751 }
Greg Clayton8b45bee2011-08-10 22:05:39 +0000752
753 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000754
Greg Clayton71337622011-02-24 22:24:29 +0000755 if (GetID() == LLDB_INVALID_PROCESS_ID)
756 {
Johnny Chen4c1e9202011-08-09 18:56:45 +0000757 if (log)
758 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton71337622011-02-24 22:24:29 +0000759 KillDebugserverProcess ();
760 return error;
761 }
762
Greg Claytondd0e5a52011-06-02 22:22:38 +0000763 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Clayton71337622011-02-24 22:24:29 +0000764 {
Greg Claytondd0e5a52011-06-02 22:22:38 +0000765 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Clayton71337622011-02-24 22:24:29 +0000766
767 if (!disable_stdio)
768 {
769 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Claytonee95ed52011-11-17 22:14:31 +0000770 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Clayton71337622011-02-24 22:24:29 +0000771 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000772 }
773 }
Greg Claytonc235ac72011-08-09 05:20:29 +0000774 else
775 {
Johnny Chen4c1e9202011-08-09 18:56:45 +0000776 if (log)
777 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytonc235ac72011-08-09 05:20:29 +0000778 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000779 }
780 else
781 {
782 // Set our user ID to an invalid process ID.
783 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton982c9762011-11-03 21:22:33 +0000784 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
785 exe_module->GetFileSpec().GetFilename().AsCString(),
786 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000787 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000788 return error;
Greg Clayton4957bf62010-09-30 21:49:03 +0000789
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000790}
791
792
793Error
Greg Claytonb766a732011-02-04 01:58:07 +0000794ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000795{
796 Error error;
797 // Sleep and wait a bit for debugserver to start to listen...
Greg Clayton7b0992d2013-04-18 22:45:39 +0000798 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000799 if (conn_ap.get())
800 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000801 const uint32_t max_retry_count = 50;
802 uint32_t retry_count = 0;
803 while (!m_gdb_comm.IsConnected())
804 {
Greg Claytonb766a732011-02-04 01:58:07 +0000805 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000806 {
807 m_gdb_comm.SetConnection (conn_ap.release());
808 break;
809 }
Jim Ingham4e5c8212013-06-07 22:09:53 +0000810 else if (error.WasInterrupted())
811 {
812 // If we were interrupted, don't keep retrying.
813 break;
814 }
815
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000816 retry_count++;
Jim Ingham4e5c8212013-06-07 22:09:53 +0000817
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000818 if (retry_count >= max_retry_count)
819 break;
820
821 usleep (100000);
822 }
823 }
824
825 if (!m_gdb_comm.IsConnected())
826 {
827 if (error.Success())
828 error.SetErrorString("not connected to remote gdb server");
829 return error;
830 }
831
Greg Clayton32e0a752011-03-30 18:16:51 +0000832 // We always seem to be able to open a connection to a local port
833 // so we need to make sure we can then send data to it. If we can't
834 // then we aren't actually connected to anything, so try and do the
835 // handshake with the remote GDB server and make sure that goes
836 // alright.
837 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000838 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000839 m_gdb_comm.Disconnect();
840 if (error.Success())
841 error.SetErrorString("not connected to remote gdb server");
842 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000843 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000844 m_gdb_comm.ResetDiscoverableSettings();
845 m_gdb_comm.QueryNoAckModeSupported ();
846 m_gdb_comm.GetThreadSuffixSupported ();
Greg Clayton44633992012-04-10 03:22:03 +0000847 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +0000848 m_gdb_comm.GetHostInfo ();
849 m_gdb_comm.GetVContSupported ('c');
Jim Inghamcd16df92012-07-20 21:37:13 +0000850 m_gdb_comm.GetVAttachOrWaitSupported();
Jim Ingham03afad82012-07-02 05:40:07 +0000851
852 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
853 for (size_t idx = 0; idx < num_cmds; idx++)
854 {
855 StringExtractorGDBRemote response;
Jim Ingham03afad82012-07-02 05:40:07 +0000856 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
857 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000858 return error;
859}
860
861void
862ProcessGDBRemote::DidLaunchOrAttach ()
863{
Greg Clayton5160ce52013-03-27 23:08:40 +0000864 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +0000865 if (log)
866 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton93d3c8332011-02-16 04:46:07 +0000867 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000868 {
869 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
870
Greg Clayton513c26c2011-01-29 07:10:55 +0000871 BuildDynamicRegisterInfo (false);
Greg Clayton3af9ea52010-11-18 05:57:03 +0000872
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000873 // See if the GDB server supports the qHostInfo information
Greg Clayton0d0c12a2011-02-09 03:09:55 +0000874
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000875 ArchSpec gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
876
877 // See if the GDB server supports the qProcessInfo packet, if so
878 // prefer that over the Host information as it will be more specific
879 // to our process.
880
881 if (m_gdb_comm.GetProcessArchitecture().IsValid())
882 gdb_remote_arch = m_gdb_comm.GetProcessArchitecture();
883
Greg Claytond314e812011-03-23 00:09:55 +0000884 if (gdb_remote_arch.IsValid())
Greg Clayton0d0c12a2011-02-09 03:09:55 +0000885 {
Greg Claytond314e812011-03-23 00:09:55 +0000886 ArchSpec &target_arch = GetTarget().GetArchitecture();
887
888 if (target_arch.IsValid())
889 {
890 // If the remote host is ARM and we have apple as the vendor, then
891 // ARM executables and shared libraries can have mixed ARM architectures.
892 // You can have an armv6 executable, and if the host is armv7, then the
893 // system will load the best possible architecture for all shared libraries
894 // it has, so we really need to take the remote host architecture as our
895 // defacto architecture in this case.
896
897 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
898 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
899 {
900 target_arch = gdb_remote_arch;
901 }
902 else
903 {
904 // Fill in what is missing in the triple
905 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
906 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton70b57652011-05-15 01:25:55 +0000907 if (target_triple.getVendorName().size() == 0)
908 {
Greg Claytond314e812011-03-23 00:09:55 +0000909 target_triple.setVendor (remote_triple.getVendor());
910
Greg Clayton70b57652011-05-15 01:25:55 +0000911 if (target_triple.getOSName().size() == 0)
912 {
913 target_triple.setOS (remote_triple.getOS());
Greg Claytond314e812011-03-23 00:09:55 +0000914
Greg Clayton70b57652011-05-15 01:25:55 +0000915 if (target_triple.getEnvironmentName().size() == 0)
916 target_triple.setEnvironment (remote_triple.getEnvironment());
917 }
918 }
Greg Claytond314e812011-03-23 00:09:55 +0000919 }
920 }
921 else
922 {
923 // The target doesn't have a valid architecture yet, set it from
924 // the architecture we got from the remote GDB server
925 target_arch = gdb_remote_arch;
926 }
Greg Clayton0d0c12a2011-02-09 03:09:55 +0000927 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000928 }
929}
930
931void
932ProcessGDBRemote::DidLaunch ()
933{
934 DidLaunchOrAttach ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000935}
936
937Error
Greg Claytonc982c762010-07-09 20:39:50 +0000938ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000939{
Han Ming Ong84647042012-02-25 01:07:38 +0000940 ProcessAttachInfo attach_info;
941 return DoAttachToProcessWithID(attach_pid, attach_info);
942}
943
944Error
945ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
946{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000947 Error error;
948 // Clear out and clean up from any current state
949 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000950 if (attach_pid != LLDB_INVALID_PROCESS_ID)
951 {
Greg Clayton71337622011-02-24 22:24:29 +0000952 // Make sure we aren't already connected?
953 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000954 {
Greg Clayton71337622011-02-24 22:24:29 +0000955 char host_port[128];
956 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
957 char connect_url[128];
958 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000959
Han Ming Ong84647042012-02-25 01:07:38 +0000960 error = StartDebugserverProcess (host_port, attach_info);
Greg Clayton71337622011-02-24 22:24:29 +0000961
962 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000963 {
Greg Clayton71337622011-02-24 22:24:29 +0000964 const char *error_string = error.AsCString();
965 if (error_string == NULL)
966 error_string = "unable to launch " DEBUGSERVER_BASENAME;
967
968 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000969 }
Greg Clayton71337622011-02-24 22:24:29 +0000970 else
971 {
972 error = ConnectToDebugserver (connect_url);
973 }
974 }
975
976 if (error.Success())
977 {
978 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +0000979 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Greg Clayton3b608422011-11-19 02:11:30 +0000980 SetID (attach_pid);
Greg Clayton71337622011-02-24 22:24:29 +0000981 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000982 }
983 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000984 return error;
985}
986
987size_t
988ProcessGDBRemote::AttachInputReaderCallback
989(
990 void *baton,
991 InputReader *reader,
992 lldb::InputReaderAction notification,
993 const char *bytes,
994 size_t bytes_len
995)
996{
997 if (notification == eInputReaderGotToken)
998 {
999 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
1000 if (gdb_process->m_waiting_for_attach)
1001 gdb_process->m_waiting_for_attach = false;
1002 reader->SetIsDone(true);
1003 return 1;
1004 }
1005 return 0;
1006}
1007
1008Error
Han Ming Ong84647042012-02-25 01:07:38 +00001009ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001010{
1011 Error error;
1012 // Clear out and clean up from any current state
1013 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001014
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001015 if (process_name && process_name[0])
1016 {
Greg Clayton71337622011-02-24 22:24:29 +00001017 // Make sure we aren't already connected?
1018 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001019 {
Greg Clayton71337622011-02-24 22:24:29 +00001020 char host_port[128];
1021 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
1022 char connect_url[128];
1023 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
1024
Han Ming Ong84647042012-02-25 01:07:38 +00001025 error = StartDebugserverProcess (host_port, attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001026 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001027 {
Greg Clayton71337622011-02-24 22:24:29 +00001028 const char *error_string = error.AsCString();
1029 if (error_string == NULL)
1030 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001031
Greg Clayton71337622011-02-24 22:24:29 +00001032 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001033 }
Greg Clayton71337622011-02-24 22:24:29 +00001034 else
1035 {
1036 error = ConnectToDebugserver (connect_url);
1037 }
1038 }
1039
1040 if (error.Success())
1041 {
1042 StreamString packet;
1043
1044 if (wait_for_launch)
Jim Inghamcd16df92012-07-20 21:37:13 +00001045 {
1046 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1047 {
1048 packet.PutCString ("vAttachWait");
1049 }
1050 else
1051 {
1052 if (attach_info.GetIgnoreExisting())
1053 packet.PutCString("vAttachWait");
1054 else
1055 packet.PutCString ("vAttachOrWait");
1056 }
1057 }
Greg Clayton71337622011-02-24 22:24:29 +00001058 else
1059 packet.PutCString("vAttachName");
1060 packet.PutChar(';');
1061 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1062
1063 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1064
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001065 }
1066 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001067 return error;
1068}
1069
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001070
1071void
1072ProcessGDBRemote::DidAttach ()
1073{
Greg Claytonb766a732011-02-04 01:58:07 +00001074 DidLaunchOrAttach ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001075}
1076
Greg Clayton90ba8112012-12-05 00:16:59 +00001077
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001078Error
1079ProcessGDBRemote::WillResume ()
1080{
Greg Clayton71fc2a32011-02-12 06:28:37 +00001081 m_continue_c_tids.clear();
1082 m_continue_C_tids.clear();
1083 m_continue_s_tids.clear();
1084 m_continue_S_tids.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001085 return Error();
1086}
1087
1088Error
1089ProcessGDBRemote::DoResume ()
1090{
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001091 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001092 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001093 if (log)
1094 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytone5219662010-12-03 06:02:24 +00001095
1096 Listener listener ("gdb-remote.resume-packet-sent");
1097 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1098 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00001099 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1100
Greg Claytond1d06e42013-04-20 00:27:58 +00001101 const size_t num_threads = GetThreadList().GetSize();
1102
Greg Clayton71fc2a32011-02-12 06:28:37 +00001103 StreamString continue_packet;
1104 bool continue_packet_error = false;
1105 if (m_gdb_comm.HasAnyVContSupport ())
1106 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001107 if (m_continue_c_tids.size() == num_threads)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001108 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001109 // All threads are continuing, just send a "c" packet
1110 continue_packet.PutCString ("c");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001111 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001112 else
1113 {
1114 continue_packet.PutCString ("vCont");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001115
Greg Claytond1d06e42013-04-20 00:27:58 +00001116 if (!m_continue_c_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001117 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001118 if (m_gdb_comm.GetVContSupported ('c'))
1119 {
1120 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)
1121 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1122 }
1123 else
1124 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001125 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001126
1127 if (!continue_packet_error && !m_continue_C_tids.empty())
1128 {
1129 if (m_gdb_comm.GetVContSupported ('C'))
1130 {
1131 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)
1132 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1133 }
1134 else
1135 continue_packet_error = true;
1136 }
Greg Claytone5219662010-12-03 06:02:24 +00001137
Greg Claytond1d06e42013-04-20 00:27:58 +00001138 if (!continue_packet_error && !m_continue_s_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001139 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001140 if (m_gdb_comm.GetVContSupported ('s'))
1141 {
1142 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)
1143 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1144 }
1145 else
1146 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001147 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001148
1149 if (!continue_packet_error && !m_continue_S_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001150 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001151 if (m_gdb_comm.GetVContSupported ('S'))
1152 {
1153 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)
1154 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1155 }
1156 else
1157 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001158 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001159
1160 if (continue_packet_error)
1161 continue_packet.GetString().clear();
Greg Clayton71fc2a32011-02-12 06:28:37 +00001162 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001163 }
1164 else
1165 continue_packet_error = true;
1166
1167 if (continue_packet_error)
1168 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001169 // Either no vCont support, or we tried to use part of the vCont
1170 // packet that wasn't supported by the remote GDB server.
1171 // We need to try and make a simple packet that can do our continue
Greg Clayton71fc2a32011-02-12 06:28:37 +00001172 const size_t num_continue_c_tids = m_continue_c_tids.size();
1173 const size_t num_continue_C_tids = m_continue_C_tids.size();
1174 const size_t num_continue_s_tids = m_continue_s_tids.size();
1175 const size_t num_continue_S_tids = m_continue_S_tids.size();
1176 if (num_continue_c_tids > 0)
1177 {
1178 if (num_continue_c_tids == num_threads)
1179 {
1180 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001181 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001182 continue_packet.PutChar ('c');
1183 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001184 }
1185 else if (num_continue_c_tids == 1 &&
1186 num_continue_C_tids == 0 &&
1187 num_continue_s_tids == 0 &&
1188 num_continue_S_tids == 0 )
1189 {
1190 // Only one thread is continuing
Greg Clayton8b82f082011-04-12 05:54:46 +00001191 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001192 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001193 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001194 }
1195 }
1196
Greg Clayton0c74e782011-06-24 03:21:43 +00001197 if (continue_packet_error && num_continue_C_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001198 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001199 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1200 num_continue_C_tids > 0 &&
1201 num_continue_s_tids == 0 &&
1202 num_continue_S_tids == 0 )
Greg Clayton71fc2a32011-02-12 06:28:37 +00001203 {
1204 const int continue_signo = m_continue_C_tids.front().second;
Greg Clayton0c74e782011-06-24 03:21:43 +00001205 // Only one thread is continuing
Greg Clayton71fc2a32011-02-12 06:28:37 +00001206 if (num_continue_C_tids > 1)
1207 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001208 // More that one thread with a signal, yet we don't have
1209 // vCont support and we are being asked to resume each
1210 // thread with a signal, we need to make sure they are
1211 // all the same signal, or we can't issue the continue
1212 // accurately with the current support...
1213 if (num_continue_C_tids > 1)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001214 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001215 continue_packet_error = false;
1216 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1217 {
1218 if (m_continue_C_tids[i].second != continue_signo)
1219 continue_packet_error = true;
1220 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001221 }
Greg Clayton0c74e782011-06-24 03:21:43 +00001222 if (!continue_packet_error)
1223 m_gdb_comm.SetCurrentThreadForRun (-1);
1224 }
1225 else
1226 {
1227 // Set the continue thread ID
1228 continue_packet_error = false;
1229 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001230 }
1231 if (!continue_packet_error)
1232 {
1233 // Add threads continuing with the same signo...
Greg Clayton71fc2a32011-02-12 06:28:37 +00001234 continue_packet.Printf("C%2.2x", continue_signo);
1235 }
1236 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001237 }
1238
Greg Clayton0c74e782011-06-24 03:21:43 +00001239 if (continue_packet_error && num_continue_s_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001240 {
1241 if (num_continue_s_tids == num_threads)
1242 {
1243 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001244 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001245 continue_packet.PutChar ('s');
1246 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001247 }
1248 else if (num_continue_c_tids == 0 &&
1249 num_continue_C_tids == 0 &&
1250 num_continue_s_tids == 1 &&
1251 num_continue_S_tids == 0 )
1252 {
1253 // Only one thread is stepping
Greg Clayton8b82f082011-04-12 05:54:46 +00001254 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001255 continue_packet.PutChar ('s');
Greg Clayton0c74e782011-06-24 03:21:43 +00001256 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001257 }
1258 }
1259
1260 if (!continue_packet_error && num_continue_S_tids > 0)
1261 {
1262 if (num_continue_S_tids == num_threads)
1263 {
1264 const int step_signo = m_continue_S_tids.front().second;
1265 // Are all threads trying to step with the same signal?
Greg Clayton0c74e782011-06-24 03:21:43 +00001266 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001267 if (num_continue_S_tids > 1)
1268 {
1269 for (size_t i=1; i<num_threads; ++i)
1270 {
1271 if (m_continue_S_tids[i].second != step_signo)
1272 continue_packet_error = true;
1273 }
1274 }
1275 if (!continue_packet_error)
1276 {
1277 // Add threads stepping with the same signo...
Greg Clayton8b82f082011-04-12 05:54:46 +00001278 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001279 continue_packet.Printf("S%2.2x", step_signo);
1280 }
1281 }
1282 else if (num_continue_c_tids == 0 &&
1283 num_continue_C_tids == 0 &&
1284 num_continue_s_tids == 0 &&
1285 num_continue_S_tids == 1 )
1286 {
1287 // Only one thread is stepping with signal
Greg Clayton8b82f082011-04-12 05:54:46 +00001288 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001289 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Clayton0c74e782011-06-24 03:21:43 +00001290 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001291 }
1292 }
1293 }
1294
1295 if (continue_packet_error)
1296 {
1297 error.SetErrorString ("can't make continue packet for this resume");
1298 }
1299 else
1300 {
1301 EventSP event_sp;
1302 TimeValue timeout;
1303 timeout = TimeValue::Now();
1304 timeout.OffsetWithSeconds (5);
Jim Inghamb1e2e842012-04-12 18:49:31 +00001305 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1306 {
1307 error.SetErrorString ("Trying to resume but the async thread is dead.");
1308 if (log)
1309 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1310 return error;
1311 }
1312
Greg Clayton71fc2a32011-02-12 06:28:37 +00001313 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1314
1315 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Inghamb1e2e842012-04-12 18:49:31 +00001316 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001317 error.SetErrorString("Resume timed out.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00001318 if (log)
1319 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1320 }
1321 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1322 {
1323 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1324 if (log)
1325 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1326 return error;
1327 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001328 }
Greg Claytone5219662010-12-03 06:02:24 +00001329 }
1330
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001331 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001332}
1333
Greg Clayton9e920902012-04-10 02:25:43 +00001334void
1335ProcessGDBRemote::ClearThreadIDList ()
1336{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001337 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001338 m_thread_ids.clear();
1339}
1340
1341bool
1342ProcessGDBRemote::UpdateThreadIDList ()
1343{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001344 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001345 bool sequence_mutex_unavailable = false;
1346 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1347 if (sequence_mutex_unavailable)
1348 {
Greg Clayton9e920902012-04-10 02:25:43 +00001349 return false; // We just didn't get the list
1350 }
1351 return true;
1352}
1353
Greg Clayton9fc13552012-04-10 00:18:59 +00001354bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001355ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001356{
1357 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +00001358 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Clayton73b472d2010-10-27 03:32:59 +00001359 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +00001360 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton9e920902012-04-10 02:25:43 +00001361
1362 size_t num_thread_ids = m_thread_ids.size();
1363 // The "m_thread_ids" thread ID list should always be updated after each stop
1364 // reply packet, but in case it isn't, update it here.
1365 if (num_thread_ids == 0)
1366 {
1367 if (!UpdateThreadIDList ())
1368 return false;
1369 num_thread_ids = m_thread_ids.size();
1370 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001371
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001372 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001373 if (num_thread_ids > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001374 {
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001375 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001376 {
Greg Clayton9e920902012-04-10 02:25:43 +00001377 tid_t tid = m_thread_ids[i];
Greg Clayton160c9d82013-05-01 21:54:04 +00001378 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001379 if (!thread_sp)
Jim Inghamdee1bc92013-06-22 00:27:45 +00001380 {
Jim Ingham4f465cf2012-10-10 18:32:14 +00001381 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001382 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1383 log->Printf(
1384 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1385 __FUNCTION__,
1386 thread_sp.get(),
1387 thread_sp->GetID());
1388 }
1389 else
1390 {
1391 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1392 log->Printf(
1393 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
1394 __FUNCTION__,
1395 thread_sp.get(),
1396 thread_sp->GetID());
1397 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001398 new_thread_list.AddThread(thread_sp);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001399 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001400 }
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001401
1402 // Whatever that is left in old_thread_list_copy are not
1403 // present in new_thread_list. Remove non-existent threads from internal id table.
1404 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1405 for (size_t i=0; i<old_num_thread_ids; i++)
1406 {
1407 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1408 if (old_thread_sp)
1409 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001410 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001411 m_thread_id_to_index_id_map.erase(old_thread_id);
1412 }
1413 }
1414
Greg Clayton9fc13552012-04-10 00:18:59 +00001415 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001416}
1417
1418
1419StateType
1420ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1421{
Greg Claytondd0e5a52011-06-02 22:22:38 +00001422 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001423 const char stop_type = stop_packet.GetChar();
1424 switch (stop_type)
1425 {
1426 case 'T':
1427 case 'S':
1428 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00001429 // This is a bit of a hack, but is is required. If we did exec, we
1430 // need to clear our thread lists and also know to rebuild our dynamic
1431 // register info before we lookup and threads and populate the expedited
1432 // register values so we need to know this right away so we can cleanup
1433 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00001434 const uint32_t stop_id = GetStopID();
1435 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00001436 {
1437 // Our first stop, make sure we have a process ID, and also make
1438 // sure we know about our registers
1439 if (GetID() == LLDB_INVALID_PROCESS_ID)
1440 {
Greg Claytonc574ede2011-03-10 02:26:48 +00001441 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00001442 if (pid != LLDB_INVALID_PROCESS_ID)
1443 SetID (pid);
1444 }
1445 BuildDynamicRegisterInfo (true);
1446 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001447 // Stop with signal and thread info
1448 const uint8_t signo = stop_packet.GetHexU8();
1449 std::string name;
1450 std::string value;
1451 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00001452 std::string reason;
1453 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001454 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00001455 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001456 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001457 ThreadSP thread_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001458 ThreadGDBRemote *gdb_thread = NULL;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001459
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001460 while (stop_packet.GetNameColonValue(name, value))
1461 {
1462 if (name.compare("metype") == 0)
1463 {
1464 // exception type in big endian hex
1465 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1466 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001467 else if (name.compare("medata") == 0)
1468 {
1469 // exception data in big endian hex
1470 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1471 }
1472 else if (name.compare("thread") == 0)
1473 {
1474 // thread in big endian hex
Greg Clayton9e920902012-04-10 02:25:43 +00001475 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001476 // m_thread_list_real does have its own mutex, but we need to
1477 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1478 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1479 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1480 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
Greg Clayton160c9d82013-05-01 21:54:04 +00001481
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001482 if (!thread_sp)
Greg Claytond1d06e42013-04-20 00:27:58 +00001483 {
Greg Claytone576ab22011-02-15 00:19:15 +00001484 // Create the thread if we need to
Jim Ingham4f465cf2012-10-10 18:32:14 +00001485 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001486 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
1487 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1488 log->Printf ("ProcessGDBRemote::%s Adding new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1489 __FUNCTION__,
1490 thread_sp.get(),
1491 thread_sp->GetID());
1492
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001493 m_thread_list_real.AddThread(thread_sp);
Greg Claytone576ab22011-02-15 00:19:15 +00001494 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001495 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1496
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001497 }
Greg Clayton9e920902012-04-10 02:25:43 +00001498 else if (name.compare("threads") == 0)
1499 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001500 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001501 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00001502 // A comma separated list of all threads in the current
1503 // process that includes the thread for this stop reply
1504 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00001505 size_t comma_pos;
1506 lldb::tid_t tid;
1507 while ((comma_pos = value.find(',')) != std::string::npos)
1508 {
1509 value[comma_pos] = '\0';
1510 // thread in big endian hex
1511 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1512 if (tid != LLDB_INVALID_THREAD_ID)
1513 m_thread_ids.push_back (tid);
1514 value.erase(0, comma_pos + 1);
1515
1516 }
1517 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1518 if (tid != LLDB_INVALID_THREAD_ID)
1519 m_thread_ids.push_back (tid);
1520 }
Greg Claytonde9d0492011-01-08 03:17:57 +00001521 else if (name.compare("hexname") == 0)
1522 {
1523 StringExtractor name_extractor;
1524 // Swap "value" over into "name_extractor"
1525 name_extractor.GetStringRef().swap(value);
1526 // Now convert the HEX bytes into a string value
1527 name_extractor.GetHexByteString (value);
1528 thread_name.swap (value);
1529 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001530 else if (name.compare("name") == 0)
1531 {
1532 thread_name.swap (value);
1533 }
Greg Clayton6f35f5c2010-09-09 06:32:46 +00001534 else if (name.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001535 {
1536 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1537 }
Greg Claytona658fd22011-06-04 01:26:29 +00001538 else if (name.compare("reason") == 0)
1539 {
1540 reason.swap(value);
1541 }
1542 else if (name.compare("description") == 0)
1543 {
1544 StringExtractor desc_extractor;
1545 // Swap "value" over into "name_extractor"
1546 desc_extractor.GetStringRef().swap(value);
1547 // Now convert the HEX bytes into a string value
1548 desc_extractor.GetHexByteString (thread_name);
1549 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001550 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1551 {
1552 // We have a register number that contains an expedited
1553 // register value. Lets supply this register to our thread
1554 // so it won't have to go and read it.
Greg Clayton160c9d82013-05-01 21:54:04 +00001555 if (gdb_thread)
Greg Clayton3e06bd92011-01-09 21:07:35 +00001556 {
1557 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1558
1559 if (reg != UINT32_MAX)
1560 {
1561 StringExtractor reg_value_extractor;
1562 // Swap "value" over into "reg_value_extractor"
1563 reg_value_extractor.GetStringRef().swap(value);
Greg Clayton160c9d82013-05-01 21:54:04 +00001564 if (!gdb_thread->PrivateSetRegisterValue (reg, reg_value_extractor))
Greg Claytone576ab22011-02-15 00:19:15 +00001565 {
1566 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1567 name.c_str(),
1568 reg,
1569 reg,
1570 reg_value_extractor.GetStringRef().c_str(),
1571 stop_packet.GetStringRef().c_str());
1572 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001573 }
1574 }
1575 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001576 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001577
1578 if (thread_sp)
1579 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001580 // Clear the stop info just in case we don't set it to anything
1581 thread_sp->SetStopInfo (StopInfoSP());
1582
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001583 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Inghamdd2fe7a2011-01-28 02:23:12 +00001584 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001585 if (exc_type != 0)
1586 {
Greg Clayton1a65ae12011-01-25 23:55:37 +00001587 const size_t exc_data_size = exc_data.size();
Greg Claytonf4b47e12010-08-04 01:40:35 +00001588
Greg Clayton160c9d82013-05-01 21:54:04 +00001589 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1590 exc_type,
1591 exc_data_size,
1592 exc_data_size >= 1 ? exc_data[0] : 0,
1593 exc_data_size >= 2 ? exc_data[1] : 0,
1594 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001595 }
Greg Claytona658fd22011-06-04 01:26:29 +00001596 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001597 {
Greg Claytona658fd22011-06-04 01:26:29 +00001598 bool handled = false;
Greg Clayton8cda7f02013-05-21 21:55:59 +00001599 bool did_exec = false;
Greg Claytona658fd22011-06-04 01:26:29 +00001600 if (!reason.empty())
1601 {
1602 if (reason.compare("trace") == 0)
1603 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001604 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Greg Claytona658fd22011-06-04 01:26:29 +00001605 handled = true;
1606 }
1607 else if (reason.compare("breakpoint") == 0)
1608 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001609 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1610 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Claytona658fd22011-06-04 01:26:29 +00001611 if (bp_site_sp)
1612 {
1613 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1614 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1615 // 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 +00001616 handled = true;
Greg Clayton160c9d82013-05-01 21:54:04 +00001617 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00001618 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001619 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00001620 }
1621 else
1622 {
1623 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001624 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00001625 }
1626 }
1627
Greg Claytona658fd22011-06-04 01:26:29 +00001628 }
1629 else if (reason.compare("trap") == 0)
1630 {
1631 // Let the trap just use the standard signal stop reason below...
1632 }
1633 else if (reason.compare("watchpoint") == 0)
1634 {
1635 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1636 // TODO: locate the watchpoint somehow...
Greg Clayton160c9d82013-05-01 21:54:04 +00001637 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
Greg Claytona658fd22011-06-04 01:26:29 +00001638 handled = true;
1639 }
1640 else if (reason.compare("exception") == 0)
1641 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001642 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00001643 handled = true;
1644 }
Greg Clayton15fc2be2013-05-21 01:00:52 +00001645 else if (reason.compare("exec") == 0)
1646 {
Greg Clayton8cda7f02013-05-21 21:55:59 +00001647 did_exec = true;
Greg Clayton15fc2be2013-05-21 01:00:52 +00001648 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
1649 handled = true;
1650 }
Greg Claytona658fd22011-06-04 01:26:29 +00001651 }
1652
Greg Clayton15fc2be2013-05-21 01:00:52 +00001653 if (signo && did_exec == false)
Greg Claytona658fd22011-06-04 01:26:29 +00001654 {
1655 if (signo == SIGTRAP)
1656 {
1657 // Currently we are going to assume SIGTRAP means we are either
1658 // hitting a breakpoint or hardware single stepping.
Jim Ingham54cc6e42012-07-11 21:41:19 +00001659 handled = true;
Greg Clayton160c9d82013-05-01 21:54:04 +00001660 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1661 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Jim Ingham54cc6e42012-07-11 21:41:19 +00001662
Greg Claytona658fd22011-06-04 01:26:29 +00001663 if (bp_site_sp)
1664 {
1665 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1666 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1667 // 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 +00001668 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00001669 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001670 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00001671 }
1672 else
1673 {
1674 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001675 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00001676 }
1677 }
Jim Ingham54cc6e42012-07-11 21:41:19 +00001678 else
Greg Claytona658fd22011-06-04 01:26:29 +00001679 {
Jim Ingham4dc613b2012-10-27 02:52:04 +00001680 // If we were stepping then assume the stop was the result of the trace. If we were
1681 // not stepping then report the SIGTRAP.
1682 // FIXME: We are still missing the case where we single step over a trap instruction.
Greg Clayton160c9d82013-05-01 21:54:04 +00001683 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1684 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Jim Ingham4dc613b2012-10-27 02:52:04 +00001685 else
Greg Clayton160c9d82013-05-01 21:54:04 +00001686 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo));
Greg Claytona658fd22011-06-04 01:26:29 +00001687 }
1688 }
1689 if (!handled)
Greg Clayton160c9d82013-05-01 21:54:04 +00001690 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Jason Molenda8214b012013-04-25 01:33:46 +00001691 }
Greg Claytona658fd22011-06-04 01:26:29 +00001692
1693 if (!description.empty())
1694 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001695 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
Greg Claytona658fd22011-06-04 01:26:29 +00001696 if (stop_info_sp)
1697 {
1698 stop_info_sp->SetDescription (description.c_str());
Greg Clayton3418c852011-08-10 02:10:13 +00001699 }
Greg Claytona658fd22011-06-04 01:26:29 +00001700 else
1701 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001702 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00001703 }
1704 }
1705 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001706 }
1707 return eStateStopped;
1708 }
1709 break;
1710
1711 case 'W':
1712 // process exited
1713 return eStateExited;
1714
1715 default:
1716 break;
1717 }
1718 return eStateInvalid;
1719}
1720
1721void
1722ProcessGDBRemote::RefreshStateAfterStop ()
1723{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001724 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001725 m_thread_ids.clear();
1726 // Set the thread stop info. It might have a "threads" key whose value is
1727 // a list of all thread IDs in the current process, so m_thread_ids might
1728 // get set.
1729 SetThreadStopInfo (m_last_stop_packet);
1730 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1731 if (m_thread_ids.empty())
1732 {
1733 // No, we need to fetch the thread list manually
1734 UpdateThreadIDList();
1735 }
1736
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001737 // Let all threads recover from stopping and do any clean up based
1738 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001739 m_thread_list_real.RefreshStateAfterStop();
Greg Clayton9e920902012-04-10 02:25:43 +00001740
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001741}
1742
1743Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001744ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001745{
1746 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001747
Greg Clayton6ed95942011-01-22 07:12:45 +00001748 bool timed_out = false;
1749 Mutex::Locker locker;
Greg Clayton513c26c2011-01-29 07:10:55 +00001750
1751 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00001752 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001753 // We are being asked to halt during an attach. We need to just close
1754 // our file handle and debugserver will go away, and we can be done...
1755 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00001756 }
Greg Clayton513c26c2011-01-29 07:10:55 +00001757 else
1758 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001759 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton513c26c2011-01-29 07:10:55 +00001760 {
1761 if (timed_out)
1762 error.SetErrorString("timed out sending interrupt packet");
1763 else
1764 error.SetErrorString("unknown error sending interrupt packet");
1765 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001766
1767 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton513c26c2011-01-29 07:10:55 +00001768 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001769 return error;
1770}
1771
1772Error
Jim Inghamacff8952013-05-02 00:27:30 +00001773ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00001774{
1775 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001776 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00001777 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00001778 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
1779
Greg Clayton594e5ed2010-09-27 21:07:38 +00001780 DisableAllBreakpointSites ();
1781
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001782 m_thread_list.DiscardThreadPlans();
Greg Clayton594e5ed2010-09-27 21:07:38 +00001783
Jim Inghamacff8952013-05-02 00:27:30 +00001784 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001785 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00001786 {
Jim Inghamacff8952013-05-02 00:27:30 +00001787 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001788 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1789 else
Jim Inghamacff8952013-05-02 00:27:30 +00001790 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00001791 }
Jim Inghamacff8952013-05-02 00:27:30 +00001792
1793 if (!error.Success())
1794 return error;
1795
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001796 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00001797 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001798
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001799 SetPrivateState (eStateDetached);
1800 ResumePrivateStateThread();
1801
1802 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00001803 return error;
1804}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001805
Jim Ingham43c555d2012-07-04 00:35:43 +00001806
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001807Error
1808ProcessGDBRemote::DoDestroy ()
1809{
1810 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001811 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001812 if (log)
1813 log->Printf ("ProcessGDBRemote::DoDestroy()");
1814
Jim Ingham43c555d2012-07-04 00:35:43 +00001815 // There is a bug in older iOS debugservers where they don't shut down the process
1816 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
1817 // this can cause problems with restarting. So we check to see if any of our threads are stopped
1818 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
1819 // destroy it again.
1820 //
1821 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
1822 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
1823 // the debugservers with this bug are equal. There really should be a better way to test this!
1824 //
1825 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
1826 // get called here to destroy again and we're still at a breakpoint or exception, then we should
1827 // just do the straight-forward kill.
1828 //
1829 // And of course, if we weren't able to stop the process by the time we get here, it isn't
1830 // necessary (or helpful) to do any of this.
1831
1832 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
1833 {
1834 PlatformSP platform_sp = GetTarget().GetPlatform();
1835
1836 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
1837 if (platform_sp
1838 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00001839 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00001840 {
1841 if (m_destroy_tried_resuming)
1842 {
1843 if (log)
1844 log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again.");
1845 }
1846 else
1847 {
1848 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
1849 // but we really need it to happen here and it doesn't matter if we do it twice.
1850 m_thread_list.DiscardThreadPlans();
1851 DisableAllBreakpointSites();
1852
1853 bool stop_looks_like_crash = false;
1854 ThreadList &threads = GetThreadList();
1855
1856 {
Jim Ingham45350372012-09-11 00:08:52 +00001857 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00001858
1859 size_t num_threads = threads.GetSize();
1860 for (size_t i = 0; i < num_threads; i++)
1861 {
1862 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00001863 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00001864 StopReason reason = eStopReasonInvalid;
1865 if (stop_info_sp)
1866 reason = stop_info_sp->GetStopReason();
1867 if (reason == eStopReasonBreakpoint
1868 || reason == eStopReasonException)
1869 {
1870 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00001871 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
1872 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00001873 stop_info_sp->GetDescription());
1874 stop_looks_like_crash = true;
1875 break;
1876 }
1877 }
1878 }
1879
1880 if (stop_looks_like_crash)
1881 {
1882 if (log)
1883 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
1884 m_destroy_tried_resuming = true;
1885
1886 // If we are going to run again before killing, it would be good to suspend all the threads
1887 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
1888 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
1889 // have to run the risk of letting those threads proceed a bit.
1890
1891 {
Jim Ingham45350372012-09-11 00:08:52 +00001892 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00001893
1894 size_t num_threads = threads.GetSize();
1895 for (size_t i = 0; i < num_threads; i++)
1896 {
1897 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00001898 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00001899 StopReason reason = eStopReasonInvalid;
1900 if (stop_info_sp)
1901 reason = stop_info_sp->GetStopReason();
1902 if (reason != eStopReasonBreakpoint
1903 && reason != eStopReasonException)
1904 {
1905 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00001906 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
1907 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00001908 thread_sp->SetResumeState(eStateSuspended);
1909 }
1910 }
1911 }
1912 Resume ();
1913 return Destroy();
1914 }
1915 }
1916 }
1917 }
1918
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001919 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00001920 int exit_status = SIGABRT;
1921 std::string exit_string;
1922
Greg Clayton6ed95942011-01-22 07:12:45 +00001923 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001924 {
Jim Inghamaab78372011-10-28 01:11:35 +00001925 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00001926 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001927
1928 StringExtractorGDBRemote response;
1929 bool send_async = true;
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00001930 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3);
1931
Greg Claytonc574ede2011-03-10 02:26:48 +00001932 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton513c26c2011-01-29 07:10:55 +00001933 {
1934 char packet_cmd = response.GetChar(0);
1935
1936 if (packet_cmd == 'W' || packet_cmd == 'X')
1937 {
Greg Clayton09c3e3d2011-12-06 04:51:14 +00001938 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00001939 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00001940 exit_status = response.GetHexU8();
1941 }
1942 else
1943 {
1944 if (log)
1945 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
1946 exit_string.assign("got unexpected response to k packet: ");
1947 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00001948 }
1949 }
1950 else
1951 {
Jim Inghambabfc382012-06-06 00:32:39 +00001952 if (log)
1953 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
1954 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00001955 }
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00001956
1957 m_gdb_comm.SetPacketTimeout(old_packet_timeout);
Greg Clayton6779606a2011-01-22 23:43:18 +00001958 }
Jim Inghambabfc382012-06-06 00:32:39 +00001959 else
1960 {
1961 if (log)
1962 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
Jim Inghamcfc09352012-07-27 23:57:19 +00001963 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00001964 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001965 }
Jim Inghambabfc382012-06-06 00:32:39 +00001966 else
1967 {
1968 // If we missed setting the exit status on the way out, do it here.
1969 // NB set exit status can be called multiple times, the first one sets the status.
1970 exit_string.assign("destroying when not connected to debugserver");
1971 }
1972
1973 SetExitStatus(exit_status, exit_string.c_str());
1974
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001975 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001976 KillDebugserverProcess ();
1977 return error;
1978}
1979
Greg Clayton8cda7f02013-05-21 21:55:59 +00001980void
1981ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
1982{
1983 lldb_private::Mutex::Locker locker (m_last_stop_packet_mutex);
1984 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
1985 if (did_exec)
1986 {
1987 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1988 if (log)
1989 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
1990
1991 m_thread_list_real.Clear();
1992 m_thread_list.Clear();
1993 BuildDynamicRegisterInfo (true);
1994 m_gdb_comm.ResetDiscoverableSettings();
1995 }
1996 m_last_stop_packet = response;
1997}
1998
1999
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002000//------------------------------------------------------------------
2001// Process Queries
2002//------------------------------------------------------------------
2003
2004bool
2005ProcessGDBRemote::IsAlive ()
2006{
Greg Clayton10177aa2010-12-08 05:08:21 +00002007 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002008}
2009
2010addr_t
2011ProcessGDBRemote::GetImageInfoAddress()
2012{
Jason Molenda6ba6d3d2013-01-30 04:39:32 +00002013 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002014}
2015
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002016//------------------------------------------------------------------
2017// Process Memory
2018//------------------------------------------------------------------
2019size_t
2020ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2021{
2022 if (size > m_max_memory_size)
2023 {
2024 // Keep memory read sizes down to a sane limit. This function will be
2025 // called multiple times in order to complete the task by
2026 // lldb_private::Process so it is ok to do this.
2027 size = m_max_memory_size;
2028 }
2029
2030 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002031 const int packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
Andy Gibbsa297a972013-06-19 19:04:53 +00002032 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002033 StringExtractorGDBRemote response;
Greg Claytonc574ede2011-03-10 02:26:48 +00002034 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002035 {
Greg Clayton576d8832011-03-22 04:00:09 +00002036 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002037 {
2038 error.Clear();
2039 return response.GetHexBytes(buf, size, '\xdd');
2040 }
Greg Clayton576d8832011-03-22 04:00:09 +00002041 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002042 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002043 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002044 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002045 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002046 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002047 }
2048 else
2049 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002050 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002051 }
2052 return 0;
2053}
2054
2055size_t
2056ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2057{
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002058 if (size > m_max_memory_size)
2059 {
2060 // Keep memory read sizes down to a sane limit. This function will be
2061 // called multiple times in order to complete the task by
2062 // lldb_private::Process so it is ok to do this.
2063 size = m_max_memory_size;
2064 }
2065
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002066 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00002067 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Clayton7fb56d02011-02-01 01:31:41 +00002068 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002069 StringExtractorGDBRemote response;
Greg Claytonc574ede2011-03-10 02:26:48 +00002070 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002071 {
Greg Clayton576d8832011-03-22 04:00:09 +00002072 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002073 {
2074 error.Clear();
2075 return size;
2076 }
Greg Clayton576d8832011-03-22 04:00:09 +00002077 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002078 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002079 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002080 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002081 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002082 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 +00002083 }
2084 else
2085 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002086 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002087 }
2088 return 0;
2089}
2090
2091lldb::addr_t
2092ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2093{
Greg Clayton2a48f522011-05-14 01:50:35 +00002094 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2095
Greg Clayton70b57652011-05-15 01:25:55 +00002096 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton2a48f522011-05-14 01:50:35 +00002097 switch (supported)
2098 {
2099 case eLazyBoolCalculate:
2100 case eLazyBoolYes:
2101 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2102 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2103 return allocated_addr;
2104
2105 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002106 // Call mmap() to create memory in the inferior..
2107 unsigned prot = 0;
2108 if (permissions & lldb::ePermissionsReadable)
2109 prot |= eMmapProtRead;
2110 if (permissions & lldb::ePermissionsWritable)
2111 prot |= eMmapProtWrite;
2112 if (permissions & lldb::ePermissionsExecutable)
2113 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00002114
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002115 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2116 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2117 m_addr_to_mmap_size[allocated_addr] = size;
2118 else
2119 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton2a48f522011-05-14 01:50:35 +00002120 break;
2121 }
2122
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002123 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00002124 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002125 else
2126 error.Clear();
2127 return allocated_addr;
2128}
2129
2130Error
Greg Clayton46fb5582011-11-18 07:03:08 +00002131ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2132 MemoryRegionInfo &region_info)
2133{
2134
2135 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2136 return error;
2137}
2138
2139Error
Johnny Chen64637202012-05-23 21:09:52 +00002140ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2141{
2142
2143 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2144 return error;
2145}
2146
2147Error
Enrico Granataf04a2192012-07-13 23:18:48 +00002148ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2149{
2150 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2151 return error;
2152}
2153
2154Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002155ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2156{
2157 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00002158 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2159
2160 switch (supported)
2161 {
2162 case eLazyBoolCalculate:
2163 // We should never be deallocating memory without allocating memory
2164 // first so we should never get eLazyBoolCalculate
2165 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2166 break;
2167
2168 case eLazyBoolYes:
2169 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00002170 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002171 break;
2172
2173 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002174 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00002175 {
2176 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002177 if (pos != m_addr_to_mmap_size.end() &&
2178 InferiorCallMunmap(this, addr, pos->second))
2179 m_addr_to_mmap_size.erase (pos);
2180 else
Daniel Malead01b2952012-11-29 21:49:15 +00002181 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002182 }
2183 break;
2184 }
2185
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002186 return error;
2187}
2188
2189
2190//------------------------------------------------------------------
2191// Process STDIO
2192//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002193size_t
2194ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2195{
2196 if (m_stdio_communication.IsConnected())
2197 {
2198 ConnectionStatus status;
2199 m_stdio_communication.Write(src, src_len, status, NULL);
2200 }
2201 return 0;
2202}
2203
2204Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002205ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002206{
2207 Error error;
2208 assert (bp_site != NULL);
2209
Greg Clayton5160ce52013-03-27 23:08:40 +00002210 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002211 user_id_t site_id = bp_site->GetID();
2212 const addr_t addr = bp_site->GetLoadAddress();
2213 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002214 log->Printf ("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002215
2216 if (bp_site->IsEnabled())
2217 {
2218 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002219 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 +00002220 return error;
2221 }
2222 else
2223 {
2224 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2225
2226 if (bp_site->HardwarePreferred())
2227 {
2228 // Try and set hardware breakpoint, and if that fails, fall through
2229 // and set a software breakpoint?
Greg Clayton8b82f082011-04-12 05:54:46 +00002230 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002231 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002232 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002233 {
2234 bp_site->SetEnabled(true);
Greg Clayton8b82f082011-04-12 05:54:46 +00002235 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002236 return error;
2237 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002238 }
2239 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002240
2241 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002242 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002243 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
2244 {
2245 bp_site->SetEnabled(true);
2246 bp_site->SetType (BreakpointSite::eExternal);
2247 return error;
2248 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002249 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002250
2251 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002252 }
2253
2254 if (log)
2255 {
2256 const char *err_string = error.AsCString();
Jim Ingham299c0c12013-02-15 02:06:30 +00002257 log->Printf ("ProcessGDBRemote::EnableBreakpointSite () error for breakpoint at 0x%8.8" PRIx64 ": %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002258 bp_site->GetLoadAddress(),
2259 err_string ? err_string : "NULL");
2260 }
2261 // We shouldn't reach here on a successful breakpoint enable...
2262 if (error.Success())
2263 error.SetErrorToGenericError();
2264 return error;
2265}
2266
2267Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002268ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002269{
2270 Error error;
2271 assert (bp_site != NULL);
2272 addr_t addr = bp_site->GetLoadAddress();
2273 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00002274 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002275 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002276 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002277
2278 if (bp_site->IsEnabled())
2279 {
2280 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2281
Greg Clayton8b82f082011-04-12 05:54:46 +00002282 BreakpointSite::Type bp_type = bp_site->GetType();
2283 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002284 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002285 case BreakpointSite::eSoftware:
2286 error = DisableSoftwareBreakpoint (bp_site);
2287 break;
2288
2289 case BreakpointSite::eHardware:
2290 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2291 error.SetErrorToGenericError();
2292 break;
2293
2294 case BreakpointSite::eExternal:
2295 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2296 error.SetErrorToGenericError();
2297 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002298 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002299 if (error.Success())
2300 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002301 }
2302 else
2303 {
2304 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002305 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 +00002306 return error;
2307 }
2308
2309 if (error.Success())
2310 error.SetErrorToGenericError();
2311 return error;
2312}
2313
Johnny Chen11309a32011-09-06 22:38:36 +00002314// Pre-requisite: wp != NULL.
2315static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00002316GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00002317{
2318 assert(wp);
2319 bool watch_read = wp->WatchpointRead();
2320 bool watch_write = wp->WatchpointWrite();
2321
2322 // watch_read and watch_write cannot both be false.
2323 assert(watch_read || watch_write);
2324 if (watch_read && watch_write)
2325 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00002326 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00002327 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00002328 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00002329 return eWatchpointWrite;
2330}
2331
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002332Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002333ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002334{
2335 Error error;
2336 if (wp)
2337 {
2338 user_id_t watchID = wp->GetID();
2339 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00002340 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002341 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002342 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002343 if (wp->IsEnabled())
2344 {
2345 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002346 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 +00002347 return error;
2348 }
Johnny Chen11309a32011-09-06 22:38:36 +00002349
2350 GDBStoppointType type = GetGDBStoppointType(wp);
2351 // Pass down an appropriate z/Z packet...
2352 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002353 {
Johnny Chen11309a32011-09-06 22:38:36 +00002354 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2355 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002356 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002357 return error;
2358 }
2359 else
2360 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002361 }
Johnny Chen11309a32011-09-06 22:38:36 +00002362 else
2363 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002364 }
2365 else
2366 {
Johnny Chen01a67862011-10-14 00:42:25 +00002367 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002368 }
2369 if (error.Success())
2370 error.SetErrorToGenericError();
2371 return error;
2372}
2373
2374Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002375ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002376{
2377 Error error;
2378 if (wp)
2379 {
2380 user_id_t watchID = wp->GetID();
2381
Greg Clayton5160ce52013-03-27 23:08:40 +00002382 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002383
2384 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00002385
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002386 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002387 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002388
Johnny Chen11309a32011-09-06 22:38:36 +00002389 if (!wp->IsEnabled())
2390 {
2391 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002392 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 +00002393 // See also 'class WatchpointSentry' within StopInfo.cpp.
2394 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2395 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00002396 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002397 return error;
2398 }
2399
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002400 if (wp->IsHardware())
2401 {
Johnny Chen11309a32011-09-06 22:38:36 +00002402 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002403 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00002404 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2405 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002406 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002407 return error;
2408 }
2409 else
2410 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002411 }
2412 // TODO: clear software watchpoints if we implement them
2413 }
2414 else
2415 {
Johnny Chen01a67862011-10-14 00:42:25 +00002416 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002417 }
2418 if (error.Success())
2419 error.SetErrorToGenericError();
2420 return error;
2421}
2422
2423void
2424ProcessGDBRemote::Clear()
2425{
2426 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002427 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002428 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002429}
2430
2431Error
2432ProcessGDBRemote::DoSignal (int signo)
2433{
2434 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002435 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002436 if (log)
2437 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2438
2439 if (!m_gdb_comm.SendAsyncSignal (signo))
2440 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2441 return error;
2442}
2443
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002444Error
Han Ming Ong84647042012-02-25 01:07:38 +00002445ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)
2446{
2447 ProcessLaunchInfo launch_info;
2448 return StartDebugserverProcess(debugserver_url, launch_info);
2449}
2450
2451Error
2452ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url, const ProcessInfo &process_info) // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002453{
2454 Error error;
2455 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2456 {
2457 // If we locate debugserver, keep that located version around
2458 static FileSpec g_debugserver_file_spec;
2459
Han Ming Ong84647042012-02-25 01:07:38 +00002460 ProcessLaunchInfo debugserver_launch_info;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002461 char debugserver_path[PATH_MAX];
Han Ming Ong84647042012-02-25 01:07:38 +00002462 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002463
2464 // Always check to see if we have an environment override for the path
2465 // to the debugserver to use and use it if we do.
2466 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2467 if (env_debugserver_path)
Greg Clayton274060b2010-10-20 20:54:39 +00002468 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002469 else
2470 debugserver_file_spec = g_debugserver_file_spec;
2471 bool debugserver_exists = debugserver_file_spec.Exists();
2472 if (!debugserver_exists)
2473 {
2474 // The debugserver binary is in the LLDB.framework/Resources
2475 // directory.
Greg Claytondd36def2010-10-17 22:03:32 +00002476 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002477 {
Greg Claytondd36def2010-10-17 22:03:32 +00002478 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002479 debugserver_exists = debugserver_file_spec.Exists();
Greg Claytondd36def2010-10-17 22:03:32 +00002480 if (debugserver_exists)
2481 {
2482 g_debugserver_file_spec = debugserver_file_spec;
2483 }
2484 else
2485 {
2486 g_debugserver_file_spec.Clear();
2487 debugserver_file_spec.Clear();
2488 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002489 }
2490 }
2491
2492 if (debugserver_exists)
2493 {
2494 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2495
2496 m_stdio_communication.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002497
Greg Clayton5160ce52013-03-27 23:08:40 +00002498 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002499
Han Ming Ong84647042012-02-25 01:07:38 +00002500 Args &debugserver_args = debugserver_launch_info.GetArguments();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002501 char arg_cstr[PATH_MAX];
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002502
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002503 // Start args with "debugserver /file/path -r --"
2504 debugserver_args.AppendArgument(debugserver_path);
2505 debugserver_args.AppendArgument(debugserver_url);
Greg Claytondd36def2010-10-17 22:03:32 +00002506 // use native registers, not the GDB registers
2507 debugserver_args.AppendArgument("--native-regs");
2508 // make debugserver run in its own session so signals generated by
2509 // special terminal key sequences (^C) don't affect debugserver
2510 debugserver_args.AppendArgument("--setsid");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002511
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002512 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2513 if (env_debugserver_log_file)
2514 {
2515 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2516 debugserver_args.AppendArgument(arg_cstr);
2517 }
2518
2519 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2520 if (env_debugserver_log_flags)
2521 {
2522 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2523 debugserver_args.AppendArgument(arg_cstr);
2524 }
Jim Inghama0cc6b22012-10-03 22:31:30 +00002525// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
2526// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002527
Greg Clayton8b82f082011-04-12 05:54:46 +00002528 // We currently send down all arguments, attach pids, or attach
2529 // process names in dedicated GDB server packets, so we don't need
2530 // to pass them as arguments. This is currently because of all the
2531 // things we need to setup prior to launching: the environment,
2532 // current working dir, file actions, etc.
2533#if 0
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002534 // Now append the program arguments
Greg Clayton71337622011-02-24 22:24:29 +00002535 if (inferior_argv)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002536 {
Greg Clayton71337622011-02-24 22:24:29 +00002537 // Terminate the debugserver args so we can now append the inferior args
2538 debugserver_args.AppendArgument("--");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002539
Greg Clayton71337622011-02-24 22:24:29 +00002540 for (int i = 0; inferior_argv[i] != NULL; ++i)
2541 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002542 }
2543 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2544 {
2545 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2546 debugserver_args.AppendArgument (arg_cstr);
2547 }
2548 else if (attach_name && attach_name[0])
2549 {
2550 if (wait_for_launch)
2551 debugserver_args.AppendArgument ("--waitfor");
2552 else
2553 debugserver_args.AppendArgument ("--attach");
2554 debugserver_args.AppendArgument (attach_name);
2555 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002556#endif
Greg Clayton8b82f082011-04-12 05:54:46 +00002557
2558 ProcessLaunchInfo::FileAction file_action;
2559
2560 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2561 // to "/dev/null" if we run into any problems.
2562 file_action.Close (STDIN_FILENO);
Han Ming Ong84647042012-02-25 01:07:38 +00002563 debugserver_launch_info.AppendFileAction (file_action);
Greg Clayton8b82f082011-04-12 05:54:46 +00002564 file_action.Close (STDOUT_FILENO);
Han Ming Ong84647042012-02-25 01:07:38 +00002565 debugserver_launch_info.AppendFileAction (file_action);
Greg Clayton8b82f082011-04-12 05:54:46 +00002566 file_action.Close (STDERR_FILENO);
Han Ming Ong84647042012-02-25 01:07:38 +00002567 debugserver_launch_info.AppendFileAction (file_action);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002568
2569 if (log)
2570 {
2571 StreamString strm;
2572 debugserver_args.Dump (&strm);
2573 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2574 }
2575
Han Ming Ong84647042012-02-25 01:07:38 +00002576 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2577 debugserver_launch_info.SetUserID(process_info.GetUserID());
Greg Claytone4e45922011-11-16 05:37:56 +00002578
Han Ming Ong84647042012-02-25 01:07:38 +00002579 error = Host::LaunchProcess(debugserver_launch_info);
Greg Clayton0b42ac32010-07-02 01:29:13 +00002580
Greg Clayton8b82f082011-04-12 05:54:46 +00002581 if (error.Success ())
Han Ming Ong84647042012-02-25 01:07:38 +00002582 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Greg Clayton8b82f082011-04-12 05:54:46 +00002583 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002584 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2585
2586 if (error.Fail() || log)
Greg Clayton5160ce52013-03-27 23:08:40 +00002587 error.PutToLog(log, "Host::LaunchProcess (launch_info) => pid=%" PRIu64 ", path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002588 }
2589 else
2590 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002591 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002592 }
2593
2594 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2595 StartAsyncThread ();
2596 }
2597 return error;
2598}
2599
2600bool
2601ProcessGDBRemote::MonitorDebugserverProcess
2602(
2603 void *callback_baton,
2604 lldb::pid_t debugserver_pid,
Greg Claytone4e45922011-11-16 05:37:56 +00002605 bool exited, // True if the process did exit
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002606 int signo, // Zero for no signal
2607 int exit_status // Exit value of process if signal is zero
2608)
2609{
Greg Claytone4e45922011-11-16 05:37:56 +00002610 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2611 // and might not exist anymore, so we need to carefully try to get the
2612 // target for this process first since we have a race condition when
2613 // we are done running between getting the notice that the inferior
2614 // process has died and the debugserver that was debugging this process.
2615 // In our test suite, we are also continually running process after
2616 // process, so we must be very careful to make sure:
2617 // 1 - process object hasn't been deleted already
2618 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002619
2620 // "debugserver_pid" argument passed in is the process ID for
2621 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00002622 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002623
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002624 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton6779606a2011-01-22 23:43:18 +00002625
Greg Claytone4e45922011-11-16 05:37:56 +00002626 // Get a shared pointer to the target that has a matching process pointer.
2627 // This target could be gone, or the target could already have a new process
2628 // object inside of it
2629 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2630
Greg Clayton6779606a2011-01-22 23:43:18 +00002631 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002632 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 +00002633
Greg Claytone4e45922011-11-16 05:37:56 +00002634 if (target_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002635 {
Greg Claytone4e45922011-11-16 05:37:56 +00002636 // We found a process in a target that matches, but another thread
2637 // might be in the process of launching a new process that will
2638 // soon replace it, so get a shared pointer to the process so we
2639 // can keep it alive.
2640 ProcessSP process_sp (target_sp->GetProcessSP());
2641 // Now we have a shared pointer to the process that can't go away on us
2642 // so we now make sure it was the same as the one passed in, and also make
2643 // sure that our previous "process *" didn't get deleted and have a new
2644 // "process *" created in its place with the same pointer. To verify this
2645 // we make sure the process has our debugserver process ID. If we pass all
2646 // of these tests, then we are sure that this process is the one we were
2647 // looking for.
2648 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002649 {
Greg Claytone4e45922011-11-16 05:37:56 +00002650 // Sleep for a half a second to make sure our inferior process has
2651 // time to set its exit status before we set it incorrectly when
2652 // both the debugserver and the inferior process shut down.
2653 usleep (500000);
2654 // If our process hasn't yet exited, debugserver might have died.
2655 // If the process did exit, the we are reaping it.
2656 const StateType state = process->GetState();
2657
2658 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2659 state != eStateInvalid &&
2660 state != eStateUnloaded &&
2661 state != eStateExited &&
2662 state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002663 {
Greg Claytone4e45922011-11-16 05:37:56 +00002664 char error_str[1024];
2665 if (signo)
2666 {
2667 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2668 if (signal_cstr)
2669 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2670 else
2671 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2672 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002673 else
Greg Claytone4e45922011-11-16 05:37:56 +00002674 {
2675 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2676 }
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002677
Greg Claytone4e45922011-11-16 05:37:56 +00002678 process->SetExitStatus (-1, error_str);
2679 }
2680 // Debugserver has exited we need to let our ProcessGDBRemote
2681 // know that it no longer has a debugserver instance
2682 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002683 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002684 }
2685 return true;
2686}
2687
2688void
2689ProcessGDBRemote::KillDebugserverProcess ()
2690{
2691 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2692 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002693 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002694 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2695 }
2696}
2697
2698void
2699ProcessGDBRemote::Initialize()
2700{
2701 static bool g_initialized = false;
2702
2703 if (g_initialized == false)
2704 {
2705 g_initialized = true;
2706 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2707 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00002708 CreateInstance,
2709 DebuggerInitialize);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002710
2711 Log::Callbacks log_callbacks = {
2712 ProcessGDBRemoteLog::DisableLog,
2713 ProcessGDBRemoteLog::EnableLog,
2714 ProcessGDBRemoteLog::ListLogCategories
2715 };
2716
2717 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2718 }
2719}
2720
Greg Clayton7f982402013-07-15 22:54:20 +00002721void
2722ProcessGDBRemote::DebuggerInitialize (lldb_private::Debugger &debugger)
2723{
2724 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
2725 {
2726 const bool is_global_setting = true;
2727 PluginManager::CreateSettingForProcessPlugin (debugger,
2728 GetGlobalPluginProperties()->GetValueProperties(),
2729 ConstString ("Properties for the gdb-remote process plug-in."),
2730 is_global_setting);
2731 }
2732}
2733
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002734bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002735ProcessGDBRemote::StartAsyncThread ()
2736{
Greg Clayton5160ce52013-03-27 23:08:40 +00002737 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002738
2739 if (log)
2740 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Ingham455fa5c2012-11-01 01:15:33 +00002741
2742 Mutex::Locker start_locker(m_async_thread_state_mutex);
2743 if (m_async_thread_state == eAsyncThreadNotStarted)
2744 {
2745 // Create a thread that watches our internal state and controls which
2746 // events make it to clients (into the DCProcess event queue).
2747 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2748 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2749 {
2750 m_async_thread_state = eAsyncThreadRunning;
2751 return true;
2752 }
2753 else
2754 return false;
2755 }
2756 else
2757 {
2758 // Somebody tried to start the async thread while it was either being started or stopped. If the former, and
2759 // it started up successfully, then say all's well. Otherwise it is an error, since we aren't going to restart it.
2760 if (log)
2761 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
2762 if (m_async_thread_state == eAsyncThreadRunning)
2763 return true;
2764 else
2765 return false;
2766 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002767}
2768
2769void
2770ProcessGDBRemote::StopAsyncThread ()
2771{
Greg Clayton5160ce52013-03-27 23:08:40 +00002772 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002773
2774 if (log)
2775 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2776
Jim Ingham455fa5c2012-11-01 01:15:33 +00002777 Mutex::Locker start_locker(m_async_thread_state_mutex);
2778 if (m_async_thread_state == eAsyncThreadRunning)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002779 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00002780 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2781
2782 // This will shut down the async thread.
2783 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
2784
2785 // Stop the stdio thread
2786 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2787 {
2788 Host::ThreadJoin (m_async_thread, NULL, NULL);
2789 }
2790 m_async_thread_state = eAsyncThreadDone;
2791 }
2792 else
2793 {
2794 if (log)
2795 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002796 }
2797}
2798
2799
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002800thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002801ProcessGDBRemote::AsyncThread (void *arg)
2802{
2803 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2804
Greg Clayton5160ce52013-03-27 23:08:40 +00002805 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002806 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002807 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002808
2809 Listener listener ("ProcessGDBRemote::AsyncThread");
2810 EventSP event_sp;
2811 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2812 eBroadcastBitAsyncThreadShouldExit;
2813
2814 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2815 {
Greg Clayton71337622011-02-24 22:24:29 +00002816 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2817
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002818 bool done = false;
2819 while (!done)
2820 {
2821 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002822 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002823 if (listener.WaitForEvent (NULL, event_sp))
2824 {
2825 const uint32_t event_type = event_sp->GetType();
Greg Clayton71337622011-02-24 22:24:29 +00002826 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002827 {
Greg Clayton71337622011-02-24 22:24:29 +00002828 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002829 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 +00002830
Greg Clayton71337622011-02-24 22:24:29 +00002831 switch (event_type)
2832 {
2833 case eBroadcastBitAsyncContinue:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002834 {
Greg Clayton71337622011-02-24 22:24:29 +00002835 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002836
Greg Clayton71337622011-02-24 22:24:29 +00002837 if (continue_packet)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002838 {
Greg Clayton71337622011-02-24 22:24:29 +00002839 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2840 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2841 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002842 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002843
Greg Clayton71337622011-02-24 22:24:29 +00002844 if (::strstr (continue_cstr, "vAttach") == NULL)
2845 process->SetPrivateState(eStateRunning);
2846 StringExtractorGDBRemote response;
2847 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002848
Greg Clayton0772ded2012-05-16 02:48:06 +00002849 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
2850 // The thread ID list might be contained within the "response", or the stop reply packet that
2851 // caused the stop. So clear it now before we give the stop reply packet to the process
2852 // using the process->SetLastStopPacket()...
2853 process->ClearThreadIDList ();
2854
Greg Clayton71337622011-02-24 22:24:29 +00002855 switch (stop_state)
2856 {
2857 case eStateStopped:
2858 case eStateCrashed:
2859 case eStateSuspended:
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002860 process->SetLastStopPacket (response);
Greg Clayton71337622011-02-24 22:24:29 +00002861 process->SetPrivateState (stop_state);
2862 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002863
Greg Clayton71337622011-02-24 22:24:29 +00002864 case eStateExited:
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002865 process->SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002866 process->ClearThreadIDList();
Greg Clayton71337622011-02-24 22:24:29 +00002867 response.SetFilePos(1);
2868 process->SetExitStatus(response.GetHexU8(), NULL);
2869 done = true;
2870 break;
2871
2872 case eStateInvalid:
2873 process->SetExitStatus(-1, "lost connection");
2874 break;
2875
2876 default:
2877 process->SetPrivateState (stop_state);
2878 break;
2879 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002880 }
2881 }
Greg Clayton71337622011-02-24 22:24:29 +00002882 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002883
Greg Clayton71337622011-02-24 22:24:29 +00002884 case eBroadcastBitAsyncThreadShouldExit:
2885 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002886 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Clayton71337622011-02-24 22:24:29 +00002887 done = true;
2888 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002889
Greg Clayton71337622011-02-24 22:24:29 +00002890 default:
2891 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002892 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 +00002893 done = true;
2894 break;
2895 }
2896 }
2897 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2898 {
2899 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2900 {
2901 process->SetExitStatus (-1, "lost connection");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002902 done = true;
Greg Clayton71337622011-02-24 22:24:29 +00002903 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002904 }
2905 }
2906 else
2907 {
2908 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002909 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 +00002910 done = true;
2911 }
2912 }
2913 }
2914
2915 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002916 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002917
2918 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2919 return NULL;
2920}
2921
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002922const char *
2923ProcessGDBRemote::GetDispatchQueueNameForThread
2924(
2925 addr_t thread_dispatch_qaddr,
2926 std::string &dispatch_queue_name
2927)
2928{
2929 dispatch_queue_name.clear();
2930 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2931 {
2932 // Cache the dispatch_queue_offsets_addr value so we don't always have
2933 // to look it up
2934 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2935 {
Greg Clayton897f96a2010-10-12 17:33:06 +00002936 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2937 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Claytonb9a01b32012-02-26 05:51:37 +00002938 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false));
2939 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec));
Greg Clayton897f96a2010-10-12 17:33:06 +00002940 if (module_sp)
2941 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2942
2943 if (dispatch_queue_offsets_symbol == NULL)
2944 {
Greg Claytonb9a01b32012-02-26 05:51:37 +00002945 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false));
2946 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_module_spec);
Greg Clayton897f96a2010-10-12 17:33:06 +00002947 if (module_sp)
2948 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2949 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002950 if (dispatch_queue_offsets_symbol)
Greg Claytone7612132012-03-07 21:03:09 +00002951 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002952
2953 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2954 return NULL;
2955 }
2956
2957 uint8_t memory_buffer[8];
Greg Clayton514487e2011-02-15 21:59:32 +00002958 DataExtractor data (memory_buffer,
2959 sizeof(memory_buffer),
2960 m_target.GetArchitecture().GetByteOrder(),
2961 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002962
2963 // Excerpt from src/queue_private.h
2964 struct dispatch_queue_offsets_s
2965 {
2966 uint16_t dqo_version;
Jason Molendae424a9b2012-11-10 06:54:30 +00002967 uint16_t dqo_label; // in version 1-3, offset to string; in version 4+, offset to a pointer to a string
2968 uint16_t dqo_label_size; // in version 1-3, length of string; in version 4+, size of a (void*) in this process
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002969 } dispatch_queue_offsets;
2970
2971
2972 Error error;
2973 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2974 {
Greg Claytonc7bece562013-01-25 18:06:21 +00002975 lldb::offset_t data_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002976 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2977 {
2978 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2979 {
2980 data_offset = 0;
2981 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
Jason Molendae424a9b2012-11-10 06:54:30 +00002982 if (dispatch_queue_offsets.dqo_version >= 4)
2983 {
2984 // libdispatch versions 4+, pointer to dispatch name is in the
2985 // queue structure.
2986 lldb::addr_t pointer_to_label_address = queue_addr + dispatch_queue_offsets.dqo_label;
2987 if (ReadMemory (pointer_to_label_address, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2988 {
2989 data_offset = 0;
2990 lldb::addr_t label_addr = data.GetAddress(&data_offset);
2991 ReadCStringFromMemory (label_addr, dispatch_queue_name, error);
2992 }
2993 }
2994 else
2995 {
2996 // libdispatch versions 1-3, dispatch name is a fixed width char array
2997 // in the queue structure.
2998 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2999 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
3000 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
3001 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
3002 dispatch_queue_name.erase (bytes_read);
3003 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003004 }
3005 }
3006 }
3007 }
3008 if (dispatch_queue_name.empty())
3009 return NULL;
3010 return dispatch_queue_name.c_str();
3011}
3012
Greg Claytone996fd32011-03-08 22:40:15 +00003013//uint32_t
3014//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3015//{
3016// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
3017// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
3018// if (m_local_debugserver)
3019// {
3020// return Host::ListProcessesMatchingName (name, matches, pids);
3021// }
3022// else
3023// {
3024// // FIXME: Implement talking to the remote debugserver.
3025// return 0;
3026// }
3027//
3028//}
3029//
Jim Ingham1c823b42011-01-22 01:33:44 +00003030bool
3031ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
3032 lldb_private::StoppointCallbackContext *context,
3033 lldb::user_id_t break_id,
3034 lldb::user_id_t break_loc_id)
3035{
3036 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3037 // run so I can stop it if that's what I want to do.
Greg Clayton5160ce52013-03-27 23:08:40 +00003038 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00003039 if (log)
3040 log->Printf("Hit New Thread Notification breakpoint.");
3041 return false;
3042}
3043
3044
3045bool
3046ProcessGDBRemote::StartNoticingNewThreads()
3047{
Greg Clayton5160ce52013-03-27 23:08:40 +00003048 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00003049 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003050 {
Greg Clayton4116e932012-05-15 02:33:01 +00003051 if (log && log->GetVerbose())
3052 log->Printf("Enabled noticing new thread breakpoint.");
3053 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003054 }
Greg Clayton4116e932012-05-15 02:33:01 +00003055 else
Jim Ingham1c823b42011-01-22 01:33:44 +00003056 {
Greg Clayton4116e932012-05-15 02:33:01 +00003057 PlatformSP platform_sp (m_target.GetPlatform());
3058 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003059 {
Greg Clayton4116e932012-05-15 02:33:01 +00003060 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3061 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003062 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00003063 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00003064 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3065 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003066 }
3067 else
3068 {
3069 if (log)
3070 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00003071 }
3072 }
3073 }
Greg Clayton4116e932012-05-15 02:33:01 +00003074 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00003075}
3076
3077bool
3078ProcessGDBRemote::StopNoticingNewThreads()
3079{
Greg Clayton5160ce52013-03-27 23:08:40 +00003080 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00003081 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00003082 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00003083
3084 if (m_thread_create_bp_sp)
3085 m_thread_create_bp_sp->SetEnabled(false);
3086
Jim Ingham1c823b42011-01-22 01:33:44 +00003087 return true;
3088}
3089
Jason Molenda5e8534e2012-10-03 01:29:34 +00003090lldb_private::DynamicLoader *
3091ProcessGDBRemote::GetDynamicLoader ()
3092{
3093 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00003094 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00003095 return m_dyld_ap.get();
3096}
Jim Ingham1c823b42011-01-22 01:33:44 +00003097
Greg Clayton998255b2012-10-13 02:07:45 +00003098
Greg Clayton02686b82012-10-15 22:42:16 +00003099class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00003100{
3101private:
3102
3103public:
Greg Clayton02686b82012-10-15 22:42:16 +00003104 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00003105 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00003106 "process plugin packet history",
3107 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00003108 NULL)
3109 {
3110 }
3111
Greg Clayton02686b82012-10-15 22:42:16 +00003112 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton998255b2012-10-13 02:07:45 +00003113 {
3114 }
3115
3116 bool
3117 DoExecute (Args& command, CommandReturnObject &result)
3118 {
Greg Clayton02686b82012-10-15 22:42:16 +00003119 const size_t argc = command.GetArgumentCount();
3120 if (argc == 0)
3121 {
3122 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3123 if (process)
3124 {
3125 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
3126 result.SetStatus (eReturnStatusSuccessFinishResult);
3127 return true;
3128 }
3129 }
3130 else
3131 {
3132 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
3133 }
3134 result.SetStatus (eReturnStatusFailed);
3135 return false;
3136 }
3137};
3138
3139class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
3140{
3141private:
3142
3143public:
3144 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
3145 CommandObjectParsed (interpreter,
3146 "process plugin packet send",
3147 "Send a custom packet through the GDB remote protocol and print the answer. "
3148 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
3149 NULL)
3150 {
3151 }
3152
3153 ~CommandObjectProcessGDBRemotePacketSend ()
3154 {
3155 }
3156
3157 bool
3158 DoExecute (Args& command, CommandReturnObject &result)
3159 {
3160 const size_t argc = command.GetArgumentCount();
3161 if (argc == 0)
3162 {
3163 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
3164 result.SetStatus (eReturnStatusFailed);
3165 return false;
3166 }
3167
3168 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3169 if (process)
3170 {
Han Ming Ong84145852012-11-26 20:42:03 +00003171 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00003172 {
Han Ming Ong84145852012-11-26 20:42:03 +00003173 const char *packet_cstr = command.GetArgumentAtIndex(0);
3174 bool send_async = true;
3175 StringExtractorGDBRemote response;
3176 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3177 result.SetStatus (eReturnStatusSuccessFinishResult);
3178 Stream &output_strm = result.GetOutputStream();
3179 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00003180 std::string &response_str = response.GetStringRef();
3181
Han Ming Ong399289e2013-06-21 19:56:59 +00003182 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00003183 {
3184 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
3185 }
3186
Han Ming Ong84145852012-11-26 20:42:03 +00003187 if (response_str.empty())
3188 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3189 else
3190 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00003191 }
Greg Clayton02686b82012-10-15 22:42:16 +00003192 }
Greg Clayton998255b2012-10-13 02:07:45 +00003193 return true;
3194 }
3195};
3196
Greg Claytonba4a0a52013-02-01 23:03:47 +00003197class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
3198{
3199private:
3200
3201public:
3202 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
3203 CommandObjectRaw (interpreter,
3204 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00003205 "Send a qRcmd packet through the GDB remote protocol and print the response."
3206 "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 +00003207 NULL)
3208 {
3209 }
3210
3211 ~CommandObjectProcessGDBRemotePacketMonitor ()
3212 {
3213 }
3214
3215 bool
3216 DoExecute (const char *command, CommandReturnObject &result)
3217 {
3218 if (command == NULL || command[0] == '\0')
3219 {
3220 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
3221 result.SetStatus (eReturnStatusFailed);
3222 return false;
3223 }
3224
3225 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3226 if (process)
3227 {
3228 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00003229 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00003230 packet.PutBytesAsRawHex8(command, strlen(command));
3231 const char *packet_cstr = packet.GetString().c_str();
3232
3233 bool send_async = true;
3234 StringExtractorGDBRemote response;
3235 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3236 result.SetStatus (eReturnStatusSuccessFinishResult);
3237 Stream &output_strm = result.GetOutputStream();
3238 output_strm.Printf (" packet: %s\n", packet_cstr);
3239 const std::string &response_str = response.GetStringRef();
3240
3241 if (response_str.empty())
3242 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3243 else
3244 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
3245 }
3246 return true;
3247 }
3248};
3249
Greg Clayton02686b82012-10-15 22:42:16 +00003250class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
3251{
3252private:
3253
3254public:
3255 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
3256 CommandObjectMultiword (interpreter,
3257 "process plugin packet",
3258 "Commands that deal with GDB remote packets.",
3259 NULL)
3260 {
3261 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
3262 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00003263 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00003264 }
3265
3266 ~CommandObjectProcessGDBRemotePacket ()
3267 {
3268 }
3269};
Greg Clayton998255b2012-10-13 02:07:45 +00003270
3271class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
3272{
3273public:
3274 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
3275 CommandObjectMultiword (interpreter,
3276 "process plugin",
3277 "A set of commands for operating on a ProcessGDBRemote process.",
3278 "process plugin <subcommand> [<subcommand-options>]")
3279 {
3280 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
3281 }
3282
3283 ~CommandObjectMultiwordProcessGDBRemote ()
3284 {
3285 }
3286};
3287
Greg Clayton998255b2012-10-13 02:07:45 +00003288CommandObject *
3289ProcessGDBRemote::GetPluginCommandObject()
3290{
3291 if (!m_command_sp)
3292 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
3293 return m_command_sp.get();
3294}