blob: 0f5f890379966fe3f0b3d8b212d70d51350a5d5e [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"
Greg Claytonef8180a2013-10-15 00:14:28 +000052#include "lldb/Interpreter/PythonDataObjects.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000053#include "lldb/Symbol/ObjectFile.h"
54#include "lldb/Target/DynamicLoader.h"
55#include "lldb/Target/Target.h"
56#include "lldb/Target/TargetList.h"
Greg Clayton2a48f522011-05-14 01:50:35 +000057#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molendaa34a0c62010-06-09 21:28:42 +000058#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000059
60// Project includes
61#include "lldb/Host/Host.h"
Peter Collingbourne99f9aa02011-06-03 20:40:38 +000062#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Jason Molendac42d2432012-07-25 03:40:06 +000063#include "Plugins/Process/Utility/StopInfoMachException.h"
Jim Ingham43c555d2012-07-04 00:35:43 +000064#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
Greg Claytonc982c762010-07-09 20:39:50 +000065#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000066#include "GDBRemoteRegisterContext.h"
67#include "ProcessGDBRemote.h"
68#include "ProcessGDBRemoteLog.h"
69#include "ThreadGDBRemote.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000070
Jason Molenda5e8534e2012-10-03 01:29:34 +000071
Greg Claytonc1422c12012-04-09 22:46:21 +000072namespace lldb
73{
74 // Provide a function that can easily dump the packet history if we know a
75 // ProcessGDBRemote * value (which we can get from logs or from debugging).
76 // We need the function in the lldb namespace so it makes it into the final
77 // executable since the LLDB shared library only exports stuff in the lldb
78 // namespace. This allows you to attach with a debugger and call this
79 // function and get the packet history dumped to a file.
80 void
81 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
82 {
Greg Claytond451c1a2012-04-13 21:24:18 +000083 lldb_private::StreamFile strm;
84 lldb_private::Error error (strm.GetFile().Open(path, lldb_private::File::eOpenOptionWrite | lldb_private::File::eOpenOptionCanCreate));
85 if (error.Success())
86 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
Greg Claytonc1422c12012-04-09 22:46:21 +000087 }
Filipe Cabecinhasc34f7762012-05-23 16:27:09 +000088}
Chris Lattner30fdc8d2010-06-08 16:52:24 +000089
Chris Lattner30fdc8d2010-06-08 16:52:24 +000090#define DEBUGSERVER_BASENAME "debugserver"
91using namespace lldb;
92using namespace lldb_private;
93
Greg Clayton7f982402013-07-15 22:54:20 +000094
95namespace {
96
97 static PropertyDefinition
98 g_properties[] =
99 {
100 { "packet-timeout" , OptionValue::eTypeUInt64 , true , 1, NULL, NULL, "Specify the default packet timeout in seconds." },
Greg Claytonef8180a2013-10-15 00:14:28 +0000101 { "target-definition-file" , OptionValue::eTypeFileSpec , true, 0 , NULL, NULL, "The file that provides the description for remote target registers." },
Greg Clayton7f982402013-07-15 22:54:20 +0000102 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
103 };
104
105 enum
106 {
Greg Claytonef8180a2013-10-15 00:14:28 +0000107 ePropertyPacketTimeout,
108 ePropertyTargetDefinitionFile
Greg Clayton7f982402013-07-15 22:54:20 +0000109 };
110
111 class PluginProperties : public Properties
112 {
113 public:
114
115 static ConstString
116 GetSettingName ()
117 {
118 return ProcessGDBRemote::GetPluginNameStatic();
119 }
120
121 PluginProperties() :
122 Properties ()
123 {
124 m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
125 m_collection_sp->Initialize(g_properties);
126 }
127
128 virtual
129 ~PluginProperties()
130 {
131 }
132
133 uint64_t
134 GetPacketTimeout()
135 {
136 const uint32_t idx = ePropertyPacketTimeout;
137 return m_collection_sp->GetPropertyAtIndexAsUInt64(NULL, idx, g_properties[idx].default_uint_value);
138 }
Greg Claytonef8180a2013-10-15 00:14:28 +0000139 FileSpec
140 GetTargetDefinitionFile () const
141 {
142 const uint32_t idx = ePropertyTargetDefinitionFile;
143 return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
144 }
Greg Clayton7f982402013-07-15 22:54:20 +0000145 };
146
147 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
148
149 static const ProcessKDPPropertiesSP &
150 GetGlobalPluginProperties()
151 {
152 static ProcessKDPPropertiesSP g_settings_sp;
153 if (!g_settings_sp)
154 g_settings_sp.reset (new PluginProperties ());
155 return g_settings_sp;
156 }
157
158} // anonymous namespace end
159
Jim Ingham7572fa72011-03-29 21:45:47 +0000160static bool rand_initialized = false;
161
Sean Callanan224f6f52012-07-19 18:07:36 +0000162// TODO Randomly assigning a port is unsafe. We should get an unused
163// ephemeral port from the kernel and make sure we reserve it before passing
164// it to debugserver.
165
166#if defined (__APPLE__)
167#define LOW_PORT (IPPORT_RESERVED)
168#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
169#else
170#define LOW_PORT (1024u)
171#define HIGH_PORT (49151u)
172#endif
173
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000174static inline uint16_t
175get_random_port ()
176{
Jim Ingham7572fa72011-03-29 21:45:47 +0000177 if (!rand_initialized)
178 {
Stephen Wilsondc916862011-03-30 00:12:40 +0000179 time_t seed = time(NULL);
180
Jim Ingham7572fa72011-03-29 21:45:47 +0000181 rand_initialized = true;
Stephen Wilsondc916862011-03-30 00:12:40 +0000182 srand(seed);
Jim Ingham7572fa72011-03-29 21:45:47 +0000183 }
Sean Callanan224f6f52012-07-19 18:07:36 +0000184 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000185}
186
187
Greg Clayton57abc5d2013-05-10 21:47:16 +0000188lldb_private::ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000189ProcessGDBRemote::GetPluginNameStatic()
190{
Greg Clayton57abc5d2013-05-10 21:47:16 +0000191 static ConstString g_name("gdb-remote");
192 return g_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000193}
194
195const char *
196ProcessGDBRemote::GetPluginDescriptionStatic()
197{
198 return "GDB Remote protocol based debugging plug-in.";
199}
200
201void
202ProcessGDBRemote::Terminate()
203{
204 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
205}
206
207
Greg Claytonc3776bf2012-02-09 06:16:32 +0000208lldb::ProcessSP
209ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000210{
Greg Claytonc3776bf2012-02-09 06:16:32 +0000211 lldb::ProcessSP process_sp;
212 if (crash_file_path == NULL)
213 process_sp.reset (new ProcessGDBRemote (target, listener));
214 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000215}
216
217bool
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000218ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000219{
Greg Clayton596ed242011-10-21 21:41:45 +0000220 if (plugin_specified_by_name)
221 return true;
222
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000223 // For now we are just making sure the file exists for a given module
Greg Claytonaa149cb2011-08-11 02:48:45 +0000224 Module *exe_module = target.GetExecutableModulePointer();
225 if (exe_module)
Greg Claytonc3776bf2012-02-09 06:16:32 +0000226 {
227 ObjectFile *exe_objfile = exe_module->GetObjectFile();
228 // We can't debug core files...
229 switch (exe_objfile->GetType())
230 {
231 case ObjectFile::eTypeInvalid:
232 case ObjectFile::eTypeCoreFile:
233 case ObjectFile::eTypeDebugInfo:
234 case ObjectFile::eTypeObjectFile:
235 case ObjectFile::eTypeSharedLibrary:
236 case ObjectFile::eTypeStubLibrary:
237 return false;
238 case ObjectFile::eTypeExecutable:
239 case ObjectFile::eTypeDynamicLinker:
240 case ObjectFile::eTypeUnknown:
241 break;
242 }
Greg Claytonaa149cb2011-08-11 02:48:45 +0000243 return exe_module->GetFileSpec().Exists();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000244 }
Jim Ingham5aee1622010-08-09 23:31:02 +0000245 // However, if there is no executable module, we return true since we might be preparing to attach.
246 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000247}
248
249//----------------------------------------------------------------------
250// ProcessGDBRemote constructor
251//----------------------------------------------------------------------
252ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
253 Process (target, listener),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000254 m_flags (0),
Greg Clayton8b82f082011-04-12 05:54:46 +0000255 m_gdb_comm(false),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000256 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Claytonc982c762010-07-09 20:39:50 +0000257 m_last_stop_packet (),
Greg Clayton09c3e3d2011-12-06 04:51:14 +0000258 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000259 m_register_info (),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000260 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000261 m_async_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham455fa5c2012-11-01 01:15:33 +0000262 m_async_thread_state(eAsyncThreadNotStarted),
263 m_async_thread_state_mutex(Mutex::eMutexTypeRecursive),
Greg Clayton9e920902012-04-10 02:25:43 +0000264 m_thread_ids (),
Greg Clayton71fc2a32011-02-12 06:28:37 +0000265 m_continue_c_tids (),
266 m_continue_C_tids (),
267 m_continue_s_tids (),
268 m_continue_S_tids (),
Greg Claytonc982c762010-07-09 20:39:50 +0000269 m_max_memory_size (512),
Greg Clayton4116e932012-05-15 02:33:01 +0000270 m_addr_to_mmap_size (),
271 m_thread_create_bp_sp (),
Jim Ingham43c555d2012-07-04 00:35:43 +0000272 m_waiting_for_attach (false),
Jason Molenda5e8534e2012-10-03 01:29:34 +0000273 m_destroy_tried_resuming (false),
Greg Clayton998255b2012-10-13 02:07:45 +0000274 m_command_sp ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000275{
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000276 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
277 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Inghamb1e2e842012-04-12 18:49:31 +0000278 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Greg Clayton7f982402013-07-15 22:54:20 +0000279 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
280 if (timeout_seconds > 0)
281 m_gdb_comm.SetPacketTimeout(timeout_seconds);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000282}
283
284//----------------------------------------------------------------------
285// Destructor
286//----------------------------------------------------------------------
287ProcessGDBRemote::~ProcessGDBRemote()
288{
289 // m_mach_process.UnregisterNotificationCallbacks (this);
290 Clear();
Greg Clayton1ed54f52011-10-01 00:45:15 +0000291 // We need to call finalize on the process before destroying ourselves
292 // to make sure all of the broadcaster cleanup goes as planned. If we
293 // destruct this class, then Process::~Process() might have problems
294 // trying to fully destroy the broadcaster.
295 Finalize();
Jim Ingham455fa5c2012-11-01 01:15:33 +0000296
297 // The general Finalize is going to try to destroy the process and that SHOULD
298 // shut down the async thread. However, if we don't kill it it will get stranded and
299 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
300 StopAsyncThread();
301 KillDebugserverProcess();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000302}
303
304//----------------------------------------------------------------------
305// PluginInterface
306//----------------------------------------------------------------------
Greg Clayton57abc5d2013-05-10 21:47:16 +0000307ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000308ProcessGDBRemote::GetPluginName()
309{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000310 return GetPluginNameStatic();
311}
312
313uint32_t
314ProcessGDBRemote::GetPluginVersion()
315{
316 return 1;
317}
318
Greg Claytonef8180a2013-10-15 00:14:28 +0000319bool
320ProcessGDBRemote::ParsePythonTargetDefinition(const FileSpec &target_definition_fspec)
321{
322 ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
323 Error error;
324 lldb::ScriptInterpreterObjectSP module_object_sp (interpreter->LoadPluginModule(target_definition_fspec, error));
325 if (module_object_sp)
326 {
327 lldb::ScriptInterpreterObjectSP target_definition_sp (interpreter->GetDynamicSettings(module_object_sp,
328 &GetTarget(),
329 "gdb-server-target-definition",
330 error));
331
332 PythonDictionary target_dict(target_definition_sp);
333
334 if (target_dict)
335 {
Greg Clayton312bcbe2013-10-17 01:10:23 +0000336 PythonDictionary host_info_dict (target_dict.GetItemForKey("host-info"));
337 if (host_info_dict)
338 {
339 ArchSpec host_arch (host_info_dict.GetItemForKeyAsString(PythonString("triple")));
340
341 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture()))
342 {
343 GetTarget().SetArchitecture(host_arch);
344 }
345
346 }
347 if (m_register_info.SetRegisterInfo (target_dict, GetTarget().GetArchitecture().GetByteOrder()) > 0)
Greg Claytonef8180a2013-10-15 00:14:28 +0000348 {
349 return true;
350 }
351 }
352 }
353 return false;
354}
355
356
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000357void
Greg Clayton513c26c2011-01-29 07:10:55 +0000358ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000359{
Greg Clayton513c26c2011-01-29 07:10:55 +0000360 if (!force && m_register_info.GetNumRegisters() > 0)
361 return;
362
363 char packet[128];
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000364 m_register_info.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000365 uint32_t reg_offset = 0;
366 uint32_t reg_num = 0;
Greg Clayton23f59502012-07-17 03:23:13 +0000367 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Greg Clayton576d8832011-03-22 04:00:09 +0000368 response_type == StringExtractorGDBRemote::eResponse;
369 ++reg_num)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000370 {
Greg Clayton513c26c2011-01-29 07:10:55 +0000371 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
Andy Gibbsa297a972013-06-19 19:04:53 +0000372 assert (packet_len < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000373 StringExtractorGDBRemote response;
Greg Claytonc574ede2011-03-10 02:26:48 +0000374 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000375 {
Greg Clayton576d8832011-03-22 04:00:09 +0000376 response_type = response.GetResponseType();
377 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000378 {
379 std::string name;
380 std::string value;
381 ConstString reg_name;
382 ConstString alt_name;
383 ConstString set_name;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000384 std::vector<uint32_t> value_regs;
385 std::vector<uint32_t> invalidate_regs;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000386 RegisterInfo reg_info = { NULL, // Name
387 NULL, // Alt name
388 0, // byte size
389 reg_offset, // offset
390 eEncodingUint, // encoding
391 eFormatHex, // formate
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000392 {
393 LLDB_INVALID_REGNUM, // GCC reg num
394 LLDB_INVALID_REGNUM, // DWARF reg num
395 LLDB_INVALID_REGNUM, // generic reg num
Jason Molendafbcb7f22010-09-10 07:49:16 +0000396 reg_num, // GDB reg num
397 reg_num // native register number
Greg Clayton435d85a2012-02-29 19:27:27 +0000398 },
399 NULL,
400 NULL
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000401 };
402
403 while (response.GetNameColonValue(name, value))
404 {
405 if (name.compare("name") == 0)
406 {
407 reg_name.SetCString(value.c_str());
408 }
409 else if (name.compare("alt-name") == 0)
410 {
411 alt_name.SetCString(value.c_str());
412 }
413 else if (name.compare("bitsize") == 0)
414 {
415 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
416 }
417 else if (name.compare("offset") == 0)
418 {
419 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda743e86a2010-06-11 23:44:18 +0000420 if (reg_offset != offset)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000421 {
422 reg_offset = offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000423 }
424 }
425 else if (name.compare("encoding") == 0)
426 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000427 const Encoding encoding = Args::StringToEncoding (value.c_str());
428 if (encoding != eEncodingInvalid)
429 reg_info.encoding = encoding;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000430 }
431 else if (name.compare("format") == 0)
432 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000433 Format format = eFormatInvalid;
434 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
435 reg_info.format = format;
436 else if (value.compare("binary") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000437 reg_info.format = eFormatBinary;
438 else if (value.compare("decimal") == 0)
439 reg_info.format = eFormatDecimal;
440 else if (value.compare("hex") == 0)
441 reg_info.format = eFormatHex;
442 else if (value.compare("float") == 0)
443 reg_info.format = eFormatFloat;
444 else if (value.compare("vector-sint8") == 0)
445 reg_info.format = eFormatVectorOfSInt8;
446 else if (value.compare("vector-uint8") == 0)
447 reg_info.format = eFormatVectorOfUInt8;
448 else if (value.compare("vector-sint16") == 0)
449 reg_info.format = eFormatVectorOfSInt16;
450 else if (value.compare("vector-uint16") == 0)
451 reg_info.format = eFormatVectorOfUInt16;
452 else if (value.compare("vector-sint32") == 0)
453 reg_info.format = eFormatVectorOfSInt32;
454 else if (value.compare("vector-uint32") == 0)
455 reg_info.format = eFormatVectorOfUInt32;
456 else if (value.compare("vector-float32") == 0)
457 reg_info.format = eFormatVectorOfFloat32;
458 else if (value.compare("vector-uint128") == 0)
459 reg_info.format = eFormatVectorOfUInt128;
460 }
461 else if (name.compare("set") == 0)
462 {
463 set_name.SetCString(value.c_str());
464 }
465 else if (name.compare("gcc") == 0)
466 {
467 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
468 }
469 else if (name.compare("dwarf") == 0)
470 {
471 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
472 }
473 else if (name.compare("generic") == 0)
474 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000475 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000476 }
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000477 else if (name.compare("container-regs") == 0)
478 {
479 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
480 value_pair.second = value;
481 do
482 {
483 value_pair = value_pair.second.split(',');
484 if (!value_pair.first.empty())
485 {
Greg Clayton0ba20242013-01-21 23:32:42 +0000486 uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
487 if (reg != LLDB_INVALID_REGNUM)
488 value_regs.push_back (reg);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000489 }
490 } while (!value_pair.second.empty());
491 }
492 else if (name.compare("invalidate-regs") == 0)
493 {
494 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
495 value_pair.second = value;
496 do
497 {
498 value_pair = value_pair.second.split(',');
499 if (!value_pair.first.empty())
500 {
Greg Clayton0ba20242013-01-21 23:32:42 +0000501 uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
502 if (reg != LLDB_INVALID_REGNUM)
503 invalidate_regs.push_back (reg);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000504 }
505 } while (!value_pair.second.empty());
506 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000507 }
508
Jason Molenda743e86a2010-06-11 23:44:18 +0000509 reg_info.byte_offset = reg_offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000510 assert (reg_info.byte_size != 0);
511 reg_offset += reg_info.byte_size;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000512 if (!value_regs.empty())
513 {
514 value_regs.push_back(LLDB_INVALID_REGNUM);
515 reg_info.value_regs = value_regs.data();
516 }
517 if (!invalidate_regs.empty())
518 {
519 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
520 reg_info.invalidate_regs = invalidate_regs.data();
521 }
522
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000523 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
524 }
525 }
526 else
527 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000528 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000529 }
530 }
531
Greg Claytonef8180a2013-10-15 00:14:28 +0000532 if (reg_num == 0)
533 {
534 FileSpec target_definition_fspec = GetGlobalPluginProperties()->GetTargetDefinitionFile ();
Greg Clayton312bcbe2013-10-17 01:10:23 +0000535
536 if (target_definition_fspec)
Greg Claytonef8180a2013-10-15 00:14:28 +0000537 {
Greg Clayton312bcbe2013-10-17 01:10:23 +0000538 // See if we can get register definitions from a python file
539 if (ParsePythonTargetDefinition (target_definition_fspec))
540 return;
Greg Claytonef8180a2013-10-15 00:14:28 +0000541 }
542 }
543
Johnny Chen2fa9de12012-05-14 18:44:23 +0000544 // We didn't get anything if the accumulated reg_num is zero. See if we are
545 // debugging ARM and fill with a hard coded register set until we can get an
546 // updated debugserver down on the devices.
547 // On the other hand, if the accumulated reg_num is positive, see if we can
548 // add composite registers to the existing primordial ones.
549 bool from_scratch = (reg_num == 0);
550
551 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000552 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
553 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
554
555 // Use the process' architecture instead of the host arch, if available
556 ArchSpec remote_arch;
557 if (remote_process_arch.IsValid ())
558 remote_arch = remote_process_arch;
559 else
560 remote_arch = remote_host_arch;
561
Johnny Chen2fa9de12012-05-14 18:44:23 +0000562 if (!target_arch.IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000563 {
Johnny Chen2fa9de12012-05-14 18:44:23 +0000564 if (remote_arch.IsValid()
565 && remote_arch.GetMachine() == llvm::Triple::arm
566 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
567 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000568 }
Johnny Chen2fa9de12012-05-14 18:44:23 +0000569 else if (target_arch.GetMachine() == llvm::Triple::arm)
570 {
571 m_register_info.HardcodeARMRegisters(from_scratch);
572 }
573
574 // At this point, we can finalize our register info.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000575 m_register_info.Finalize ();
576}
577
578Error
579ProcessGDBRemote::WillLaunch (Module* module)
580{
581 return WillLaunchOrAttach ();
582}
583
584Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000585ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000586{
587 return WillLaunchOrAttach ();
588}
589
590Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000591ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000592{
593 return WillLaunchOrAttach ();
594}
595
596Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000597ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +0000598{
599 Error error (WillLaunchOrAttach ());
600
601 if (error.Fail())
602 return error;
603
Greg Clayton2289fa42011-04-30 01:09:13 +0000604 error = ConnectToDebugserver (remote_url);
Greg Claytonb766a732011-02-04 01:58:07 +0000605
606 if (error.Fail())
607 return error;
608 StartAsyncThread ();
609
Greg Claytonc574ede2011-03-10 02:26:48 +0000610 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonb766a732011-02-04 01:58:07 +0000611 if (pid == LLDB_INVALID_PROCESS_ID)
612 {
613 // We don't have a valid process ID, so note that we are connected
614 // and could now request to launch or attach, or get remote process
615 // listings...
616 SetPrivateState (eStateConnected);
617 }
618 else
619 {
620 // We have a valid process
621 SetID (pid);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000622 GetThreadList();
Greg Claytondd0e5a52011-06-02 22:22:38 +0000623 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytonb766a732011-02-04 01:58:07 +0000624 {
Carlo Kok74389122013-10-14 07:09:13 +0000625 if (!m_target.GetArchitecture().IsValid()) { // Make sure we have an architecture
626 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
627 }
628
629
Greg Claytondd0e5a52011-06-02 22:22:38 +0000630 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytonb766a732011-02-04 01:58:07 +0000631 if (state == eStateStopped)
632 {
633 SetPrivateState (state);
634 }
635 else
Daniel Malead01b2952012-11-29 21:49:15 +0000636 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 +0000637 }
638 else
Daniel Malead01b2952012-11-29 21:49:15 +0000639 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 +0000640 }
Jason Molenda16d127c2012-05-03 22:37:30 +0000641
642 if (error.Success()
643 && !GetTarget().GetArchitecture().IsValid()
644 && m_gdb_comm.GetHostArchitecture().IsValid())
645 {
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000646 // Prefer the *process'* architecture over that of the *host*, if available.
647 if (m_gdb_comm.GetProcessArchitecture().IsValid())
648 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
649 else
650 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molenda16d127c2012-05-03 22:37:30 +0000651 }
652
Greg Claytonb766a732011-02-04 01:58:07 +0000653 return error;
654}
655
656Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000657ProcessGDBRemote::WillLaunchOrAttach ()
658{
659 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000660 m_stdio_communication.Clear ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000661 return error;
662}
663
664//----------------------------------------------------------------------
665// Process Control
666//----------------------------------------------------------------------
667Error
Greg Clayton982c9762011-11-03 21:22:33 +0000668ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000669{
Greg Clayton4957bf62010-09-30 21:49:03 +0000670 Error error;
Greg Clayton982c9762011-11-03 21:22:33 +0000671
672 uint32_t launch_flags = launch_info.GetFlags().Get();
673 const char *stdin_path = NULL;
674 const char *stdout_path = NULL;
675 const char *stderr_path = NULL;
676 const char *working_dir = launch_info.GetWorkingDirectory();
677
678 const ProcessLaunchInfo::FileAction *file_action;
679 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
680 if (file_action)
681 {
682 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
683 stdin_path = file_action->GetPath();
684 }
685 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
686 if (file_action)
687 {
688 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
689 stdout_path = file_action->GetPath();
690 }
691 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
692 if (file_action)
693 {
694 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
695 stderr_path = file_action->GetPath();
696 }
697
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000698 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
699 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
700 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton5160ce52013-03-27 23:08:40 +0000701 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000702
Greg Clayton982c9762011-11-03 21:22:33 +0000703 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000704 if (object_file)
705 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000706 char host_port[128];
707 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytonb766a732011-02-04 01:58:07 +0000708 char connect_url[128];
709 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000710
Greg Clayton71337622011-02-24 22:24:29 +0000711 // Make sure we aren't already connected?
712 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000713 {
Han Ming Ong84647042012-02-25 01:07:38 +0000714 error = StartDebugserverProcess (host_port, launch_info);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000715 if (error.Fail())
Greg Claytonc235ac72011-08-09 05:20:29 +0000716 {
Johnny Chen4c1e9202011-08-09 18:56:45 +0000717 if (log)
718 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000719 return error;
Greg Claytonc235ac72011-08-09 05:20:29 +0000720 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000721
Greg Claytonb766a732011-02-04 01:58:07 +0000722 error = ConnectToDebugserver (connect_url);
Greg Clayton71337622011-02-24 22:24:29 +0000723 }
724
725 if (error.Success())
726 {
727 lldb_utility::PseudoTerminal pty;
728 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000729
730 // If the debugserver is local and we aren't disabling STDIO, lets use
731 // a pseudo terminal to instead of relying on the 'O' packets for stdio
732 // since 'O' packets can really slow down debugging if the inferior
733 // does a lot of output.
Greg Claytonf58c2692011-06-24 22:32:10 +0000734 PlatformSP platform_sp (m_target.GetPlatform());
735 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Clayton71337622011-02-24 22:24:29 +0000736 {
737 const char *slave_name = NULL;
738 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000739 {
Greg Clayton71337622011-02-24 22:24:29 +0000740 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
741 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000742 }
Greg Clayton71337622011-02-24 22:24:29 +0000743 if (stdin_path == NULL)
744 stdin_path = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000745
Greg Clayton71337622011-02-24 22:24:29 +0000746 if (stdout_path == NULL)
747 stdout_path = slave_name;
748
749 if (stderr_path == NULL)
750 stderr_path = slave_name;
751 }
752
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000753 // Set STDIN to /dev/null if we want STDIO disabled or if either
754 // STDOUT or STDERR have been set to something and STDIN hasn't
755 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000756 stdin_path = "/dev/null";
757
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000758 // Set STDOUT to /dev/null if we want STDIO disabled or if either
759 // STDIN or STDERR have been set to something and STDOUT hasn't
760 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000761 stdout_path = "/dev/null";
762
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000763 // Set STDERR to /dev/null if we want STDIO disabled or if either
764 // STDIN or STDOUT have been set to something and STDERR hasn't
765 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000766 stderr_path = "/dev/null";
767
768 if (stdin_path)
769 m_gdb_comm.SetSTDIN (stdin_path);
770 if (stdout_path)
771 m_gdb_comm.SetSTDOUT (stdout_path);
772 if (stderr_path)
773 m_gdb_comm.SetSTDERR (stderr_path);
774
775 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
776
Greg Claytonc4103b32011-05-08 04:53:50 +0000777 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Clayton71337622011-02-24 22:24:29 +0000778
779 if (working_dir && working_dir[0])
780 {
781 m_gdb_comm.SetWorkingDir (working_dir);
782 }
783
784 // Send the environment and the program + arguments after we connect
Greg Clayton982c9762011-11-03 21:22:33 +0000785 const Args &environment = launch_info.GetEnvironmentEntries();
786 if (environment.GetArgumentCount())
Greg Clayton71337622011-02-24 22:24:29 +0000787 {
Greg Clayton982c9762011-11-03 21:22:33 +0000788 size_t num_environment_entries = environment.GetArgumentCount();
789 for (size_t i=0; i<num_environment_entries; ++i)
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000790 {
Greg Clayton982c9762011-11-03 21:22:33 +0000791 const char *env_entry = environment.GetArgumentAtIndex(i);
792 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Clayton71337622011-02-24 22:24:29 +0000793 break;
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000794 }
Greg Clayton71337622011-02-24 22:24:29 +0000795 }
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000796
Greg Claytonc574ede2011-03-10 02:26:48 +0000797 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Clayton982c9762011-11-03 21:22:33 +0000798 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info.GetArguments().GetConstArgumentVector());
Greg Clayton71337622011-02-24 22:24:29 +0000799 if (arg_packet_err == 0)
800 {
801 std::string error_str;
Greg Claytonc574ede2011-03-10 02:26:48 +0000802 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000803 {
Greg Claytonc574ede2011-03-10 02:26:48 +0000804 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000805 }
806 else
807 {
Greg Clayton71337622011-02-24 22:24:29 +0000808 error.SetErrorString (error_str.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000809 }
Greg Clayton71337622011-02-24 22:24:29 +0000810 }
811 else
812 {
Greg Clayton86edbf42011-10-26 00:56:27 +0000813 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Clayton71337622011-02-24 22:24:29 +0000814 }
Greg Clayton8b45bee2011-08-10 22:05:39 +0000815
816 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000817
Greg Clayton71337622011-02-24 22:24:29 +0000818 if (GetID() == LLDB_INVALID_PROCESS_ID)
819 {
Johnny Chen4c1e9202011-08-09 18:56:45 +0000820 if (log)
821 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton71337622011-02-24 22:24:29 +0000822 KillDebugserverProcess ();
823 return error;
824 }
825
Greg Claytondd0e5a52011-06-02 22:22:38 +0000826 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Clayton71337622011-02-24 22:24:29 +0000827 {
Carlo Kok74389122013-10-14 07:09:13 +0000828 if (!m_target.GetArchitecture().IsValid()) { // Make sure we have an architecture
829 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
830 }
831
Greg Claytondd0e5a52011-06-02 22:22:38 +0000832 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Clayton71337622011-02-24 22:24:29 +0000833
834 if (!disable_stdio)
835 {
836 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Claytonee95ed52011-11-17 22:14:31 +0000837 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Clayton71337622011-02-24 22:24:29 +0000838 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000839 }
840 }
Greg Claytonc235ac72011-08-09 05:20:29 +0000841 else
842 {
Johnny Chen4c1e9202011-08-09 18:56:45 +0000843 if (log)
844 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytonc235ac72011-08-09 05:20:29 +0000845 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000846 }
847 else
848 {
849 // Set our user ID to an invalid process ID.
850 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton982c9762011-11-03 21:22:33 +0000851 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
852 exe_module->GetFileSpec().GetFilename().AsCString(),
853 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000854 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000855 return error;
Greg Clayton4957bf62010-09-30 21:49:03 +0000856
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000857}
858
859
860Error
Greg Claytonb766a732011-02-04 01:58:07 +0000861ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000862{
863 Error error;
864 // Sleep and wait a bit for debugserver to start to listen...
Greg Clayton7b0992d2013-04-18 22:45:39 +0000865 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000866 if (conn_ap.get())
867 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000868 const uint32_t max_retry_count = 50;
869 uint32_t retry_count = 0;
870 while (!m_gdb_comm.IsConnected())
871 {
Greg Claytonb766a732011-02-04 01:58:07 +0000872 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000873 {
874 m_gdb_comm.SetConnection (conn_ap.release());
875 break;
876 }
Jim Ingham4e5c8212013-06-07 22:09:53 +0000877 else if (error.WasInterrupted())
878 {
879 // If we were interrupted, don't keep retrying.
880 break;
881 }
882
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000883 retry_count++;
Jim Ingham4e5c8212013-06-07 22:09:53 +0000884
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000885 if (retry_count >= max_retry_count)
886 break;
887
888 usleep (100000);
889 }
890 }
891
892 if (!m_gdb_comm.IsConnected())
893 {
894 if (error.Success())
895 error.SetErrorString("not connected to remote gdb server");
896 return error;
897 }
898
Greg Clayton32e0a752011-03-30 18:16:51 +0000899 // We always seem to be able to open a connection to a local port
900 // so we need to make sure we can then send data to it. If we can't
901 // then we aren't actually connected to anything, so try and do the
902 // handshake with the remote GDB server and make sure that goes
903 // alright.
904 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000905 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000906 m_gdb_comm.Disconnect();
907 if (error.Success())
908 error.SetErrorString("not connected to remote gdb server");
909 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000910 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000911 m_gdb_comm.ResetDiscoverableSettings();
912 m_gdb_comm.QueryNoAckModeSupported ();
913 m_gdb_comm.GetThreadSuffixSupported ();
Greg Clayton44633992012-04-10 03:22:03 +0000914 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +0000915 m_gdb_comm.GetHostInfo ();
916 m_gdb_comm.GetVContSupported ('c');
Jim Inghamcd16df92012-07-20 21:37:13 +0000917 m_gdb_comm.GetVAttachOrWaitSupported();
Jim Ingham03afad82012-07-02 05:40:07 +0000918
919 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
920 for (size_t idx = 0; idx < num_cmds; idx++)
921 {
922 StringExtractorGDBRemote response;
Jim Ingham03afad82012-07-02 05:40:07 +0000923 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
924 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000925 return error;
926}
927
928void
929ProcessGDBRemote::DidLaunchOrAttach ()
930{
Greg Clayton5160ce52013-03-27 23:08:40 +0000931 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +0000932 if (log)
933 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton93d3c8332011-02-16 04:46:07 +0000934 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000935 {
Greg Clayton513c26c2011-01-29 07:10:55 +0000936 BuildDynamicRegisterInfo (false);
Greg Clayton3af9ea52010-11-18 05:57:03 +0000937
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000938 // See if the GDB server supports the qHostInfo information
Greg Clayton0d0c12a2011-02-09 03:09:55 +0000939
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000940 ArchSpec gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
941
942 // See if the GDB server supports the qProcessInfo packet, if so
943 // prefer that over the Host information as it will be more specific
944 // to our process.
945
946 if (m_gdb_comm.GetProcessArchitecture().IsValid())
947 gdb_remote_arch = m_gdb_comm.GetProcessArchitecture();
948
Greg Claytond314e812011-03-23 00:09:55 +0000949 if (gdb_remote_arch.IsValid())
Greg Clayton0d0c12a2011-02-09 03:09:55 +0000950 {
Greg Claytond314e812011-03-23 00:09:55 +0000951 ArchSpec &target_arch = GetTarget().GetArchitecture();
952
953 if (target_arch.IsValid())
954 {
955 // If the remote host is ARM and we have apple as the vendor, then
956 // ARM executables and shared libraries can have mixed ARM architectures.
957 // You can have an armv6 executable, and if the host is armv7, then the
958 // system will load the best possible architecture for all shared libraries
959 // it has, so we really need to take the remote host architecture as our
960 // defacto architecture in this case.
961
962 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
963 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
964 {
965 target_arch = gdb_remote_arch;
966 }
967 else
968 {
969 // Fill in what is missing in the triple
970 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
971 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton70b57652011-05-15 01:25:55 +0000972 if (target_triple.getVendorName().size() == 0)
973 {
Greg Claytond314e812011-03-23 00:09:55 +0000974 target_triple.setVendor (remote_triple.getVendor());
975
Greg Clayton70b57652011-05-15 01:25:55 +0000976 if (target_triple.getOSName().size() == 0)
977 {
978 target_triple.setOS (remote_triple.getOS());
Greg Claytond314e812011-03-23 00:09:55 +0000979
Greg Clayton70b57652011-05-15 01:25:55 +0000980 if (target_triple.getEnvironmentName().size() == 0)
981 target_triple.setEnvironment (remote_triple.getEnvironment());
982 }
983 }
Greg Claytond314e812011-03-23 00:09:55 +0000984 }
985 }
986 else
987 {
988 // The target doesn't have a valid architecture yet, set it from
989 // the architecture we got from the remote GDB server
990 target_arch = gdb_remote_arch;
991 }
Greg Clayton0d0c12a2011-02-09 03:09:55 +0000992 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000993 }
994}
995
996void
997ProcessGDBRemote::DidLaunch ()
998{
999 DidLaunchOrAttach ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001000}
1001
1002Error
Greg Claytonc982c762010-07-09 20:39:50 +00001003ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001004{
Han Ming Ong84647042012-02-25 01:07:38 +00001005 ProcessAttachInfo attach_info;
1006 return DoAttachToProcessWithID(attach_pid, attach_info);
1007}
1008
1009Error
1010ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1011{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001012 Error error;
1013 // Clear out and clean up from any current state
1014 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001015 if (attach_pid != LLDB_INVALID_PROCESS_ID)
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);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001024
Han Ming Ong84647042012-02-25 01:07:38 +00001025 error = StartDebugserverProcess (host_port, attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001026
1027 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001028 {
Greg Clayton71337622011-02-24 22:24:29 +00001029 const char *error_string = error.AsCString();
1030 if (error_string == NULL)
1031 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1032
1033 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001034 }
Greg Clayton71337622011-02-24 22:24:29 +00001035 else
1036 {
1037 error = ConnectToDebugserver (connect_url);
1038 }
1039 }
1040
1041 if (error.Success())
1042 {
1043 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001044 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Greg Clayton3b608422011-11-19 02:11:30 +00001045 SetID (attach_pid);
Greg Clayton71337622011-02-24 22:24:29 +00001046 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001047 }
1048 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001049 return error;
1050}
1051
1052size_t
1053ProcessGDBRemote::AttachInputReaderCallback
1054(
1055 void *baton,
1056 InputReader *reader,
1057 lldb::InputReaderAction notification,
1058 const char *bytes,
1059 size_t bytes_len
1060)
1061{
1062 if (notification == eInputReaderGotToken)
1063 {
1064 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
1065 if (gdb_process->m_waiting_for_attach)
1066 gdb_process->m_waiting_for_attach = false;
1067 reader->SetIsDone(true);
1068 return 1;
1069 }
1070 return 0;
1071}
1072
1073Error
Han Ming Ong84647042012-02-25 01:07:38 +00001074ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001075{
1076 Error error;
1077 // Clear out and clean up from any current state
1078 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001079
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001080 if (process_name && process_name[0])
1081 {
Greg Clayton71337622011-02-24 22:24:29 +00001082 // Make sure we aren't already connected?
1083 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001084 {
Greg Clayton71337622011-02-24 22:24:29 +00001085 char host_port[128];
1086 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
1087 char connect_url[128];
1088 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
1089
Han Ming Ong84647042012-02-25 01:07:38 +00001090 error = StartDebugserverProcess (host_port, attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001091 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001092 {
Greg Clayton71337622011-02-24 22:24:29 +00001093 const char *error_string = error.AsCString();
1094 if (error_string == NULL)
1095 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001096
Greg Clayton71337622011-02-24 22:24:29 +00001097 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001098 }
Greg Clayton71337622011-02-24 22:24:29 +00001099 else
1100 {
1101 error = ConnectToDebugserver (connect_url);
1102 }
1103 }
1104
1105 if (error.Success())
1106 {
1107 StreamString packet;
1108
1109 if (wait_for_launch)
Jim Inghamcd16df92012-07-20 21:37:13 +00001110 {
1111 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1112 {
1113 packet.PutCString ("vAttachWait");
1114 }
1115 else
1116 {
1117 if (attach_info.GetIgnoreExisting())
1118 packet.PutCString("vAttachWait");
1119 else
1120 packet.PutCString ("vAttachOrWait");
1121 }
1122 }
Greg Clayton71337622011-02-24 22:24:29 +00001123 else
1124 packet.PutCString("vAttachName");
1125 packet.PutChar(';');
1126 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1127
1128 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1129
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001130 }
1131 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001132 return error;
1133}
1134
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001135
1136void
1137ProcessGDBRemote::DidAttach ()
1138{
Greg Claytonb766a732011-02-04 01:58:07 +00001139 DidLaunchOrAttach ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001140}
1141
Greg Clayton90ba8112012-12-05 00:16:59 +00001142
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001143Error
1144ProcessGDBRemote::WillResume ()
1145{
Greg Clayton71fc2a32011-02-12 06:28:37 +00001146 m_continue_c_tids.clear();
1147 m_continue_C_tids.clear();
1148 m_continue_s_tids.clear();
1149 m_continue_S_tids.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001150 return Error();
1151}
1152
1153Error
1154ProcessGDBRemote::DoResume ()
1155{
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001156 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001157 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001158 if (log)
1159 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytone5219662010-12-03 06:02:24 +00001160
1161 Listener listener ("gdb-remote.resume-packet-sent");
1162 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1163 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00001164 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1165
Greg Claytond1d06e42013-04-20 00:27:58 +00001166 const size_t num_threads = GetThreadList().GetSize();
1167
Greg Clayton71fc2a32011-02-12 06:28:37 +00001168 StreamString continue_packet;
1169 bool continue_packet_error = false;
1170 if (m_gdb_comm.HasAnyVContSupport ())
1171 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001172 if (m_continue_c_tids.size() == num_threads)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001173 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001174 // All threads are continuing, just send a "c" packet
1175 continue_packet.PutCString ("c");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001176 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001177 else
1178 {
1179 continue_packet.PutCString ("vCont");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001180
Greg Claytond1d06e42013-04-20 00:27:58 +00001181 if (!m_continue_c_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001182 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001183 if (m_gdb_comm.GetVContSupported ('c'))
1184 {
1185 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)
1186 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1187 }
1188 else
1189 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001190 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001191
1192 if (!continue_packet_error && !m_continue_C_tids.empty())
1193 {
1194 if (m_gdb_comm.GetVContSupported ('C'))
1195 {
1196 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)
1197 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1198 }
1199 else
1200 continue_packet_error = true;
1201 }
Greg Claytone5219662010-12-03 06:02:24 +00001202
Greg Claytond1d06e42013-04-20 00:27:58 +00001203 if (!continue_packet_error && !m_continue_s_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001204 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001205 if (m_gdb_comm.GetVContSupported ('s'))
1206 {
1207 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)
1208 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1209 }
1210 else
1211 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001212 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001213
1214 if (!continue_packet_error && !m_continue_S_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001215 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001216 if (m_gdb_comm.GetVContSupported ('S'))
1217 {
1218 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)
1219 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1220 }
1221 else
1222 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001223 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001224
1225 if (continue_packet_error)
1226 continue_packet.GetString().clear();
Greg Clayton71fc2a32011-02-12 06:28:37 +00001227 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001228 }
1229 else
1230 continue_packet_error = true;
1231
1232 if (continue_packet_error)
1233 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001234 // Either no vCont support, or we tried to use part of the vCont
1235 // packet that wasn't supported by the remote GDB server.
1236 // We need to try and make a simple packet that can do our continue
Greg Clayton71fc2a32011-02-12 06:28:37 +00001237 const size_t num_continue_c_tids = m_continue_c_tids.size();
1238 const size_t num_continue_C_tids = m_continue_C_tids.size();
1239 const size_t num_continue_s_tids = m_continue_s_tids.size();
1240 const size_t num_continue_S_tids = m_continue_S_tids.size();
1241 if (num_continue_c_tids > 0)
1242 {
1243 if (num_continue_c_tids == num_threads)
1244 {
1245 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001246 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001247 continue_packet.PutChar ('c');
1248 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001249 }
1250 else if (num_continue_c_tids == 1 &&
1251 num_continue_C_tids == 0 &&
1252 num_continue_s_tids == 0 &&
1253 num_continue_S_tids == 0 )
1254 {
1255 // Only one thread is continuing
Greg Clayton8b82f082011-04-12 05:54:46 +00001256 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001257 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001258 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001259 }
1260 }
1261
Greg Clayton0c74e782011-06-24 03:21:43 +00001262 if (continue_packet_error && num_continue_C_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001263 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001264 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1265 num_continue_C_tids > 0 &&
1266 num_continue_s_tids == 0 &&
1267 num_continue_S_tids == 0 )
Greg Clayton71fc2a32011-02-12 06:28:37 +00001268 {
1269 const int continue_signo = m_continue_C_tids.front().second;
Greg Clayton0c74e782011-06-24 03:21:43 +00001270 // Only one thread is continuing
Greg Clayton71fc2a32011-02-12 06:28:37 +00001271 if (num_continue_C_tids > 1)
1272 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001273 // More that one thread with a signal, yet we don't have
1274 // vCont support and we are being asked to resume each
1275 // thread with a signal, we need to make sure they are
1276 // all the same signal, or we can't issue the continue
1277 // accurately with the current support...
1278 if (num_continue_C_tids > 1)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001279 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001280 continue_packet_error = false;
1281 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1282 {
1283 if (m_continue_C_tids[i].second != continue_signo)
1284 continue_packet_error = true;
1285 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001286 }
Greg Clayton0c74e782011-06-24 03:21:43 +00001287 if (!continue_packet_error)
1288 m_gdb_comm.SetCurrentThreadForRun (-1);
1289 }
1290 else
1291 {
1292 // Set the continue thread ID
1293 continue_packet_error = false;
1294 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001295 }
1296 if (!continue_packet_error)
1297 {
1298 // Add threads continuing with the same signo...
Greg Clayton71fc2a32011-02-12 06:28:37 +00001299 continue_packet.Printf("C%2.2x", continue_signo);
1300 }
1301 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001302 }
1303
Greg Clayton0c74e782011-06-24 03:21:43 +00001304 if (continue_packet_error && num_continue_s_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001305 {
1306 if (num_continue_s_tids == num_threads)
1307 {
1308 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001309 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001310 continue_packet.PutChar ('s');
1311 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001312 }
1313 else if (num_continue_c_tids == 0 &&
1314 num_continue_C_tids == 0 &&
1315 num_continue_s_tids == 1 &&
1316 num_continue_S_tids == 0 )
1317 {
1318 // Only one thread is stepping
Greg Clayton8b82f082011-04-12 05:54:46 +00001319 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001320 continue_packet.PutChar ('s');
Greg Clayton0c74e782011-06-24 03:21:43 +00001321 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001322 }
1323 }
1324
1325 if (!continue_packet_error && num_continue_S_tids > 0)
1326 {
1327 if (num_continue_S_tids == num_threads)
1328 {
1329 const int step_signo = m_continue_S_tids.front().second;
1330 // Are all threads trying to step with the same signal?
Greg Clayton0c74e782011-06-24 03:21:43 +00001331 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001332 if (num_continue_S_tids > 1)
1333 {
1334 for (size_t i=1; i<num_threads; ++i)
1335 {
1336 if (m_continue_S_tids[i].second != step_signo)
1337 continue_packet_error = true;
1338 }
1339 }
1340 if (!continue_packet_error)
1341 {
1342 // Add threads stepping with the same signo...
Greg Clayton8b82f082011-04-12 05:54:46 +00001343 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001344 continue_packet.Printf("S%2.2x", step_signo);
1345 }
1346 }
1347 else if (num_continue_c_tids == 0 &&
1348 num_continue_C_tids == 0 &&
1349 num_continue_s_tids == 0 &&
1350 num_continue_S_tids == 1 )
1351 {
1352 // Only one thread is stepping with signal
Greg Clayton8b82f082011-04-12 05:54:46 +00001353 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001354 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Clayton0c74e782011-06-24 03:21:43 +00001355 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001356 }
1357 }
1358 }
1359
1360 if (continue_packet_error)
1361 {
1362 error.SetErrorString ("can't make continue packet for this resume");
1363 }
1364 else
1365 {
1366 EventSP event_sp;
1367 TimeValue timeout;
1368 timeout = TimeValue::Now();
1369 timeout.OffsetWithSeconds (5);
Jim Inghamb1e2e842012-04-12 18:49:31 +00001370 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1371 {
1372 error.SetErrorString ("Trying to resume but the async thread is dead.");
1373 if (log)
1374 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1375 return error;
1376 }
1377
Greg Clayton71fc2a32011-02-12 06:28:37 +00001378 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1379
1380 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Inghamb1e2e842012-04-12 18:49:31 +00001381 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001382 error.SetErrorString("Resume timed out.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00001383 if (log)
1384 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1385 }
1386 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1387 {
1388 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1389 if (log)
1390 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1391 return error;
1392 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001393 }
Greg Claytone5219662010-12-03 06:02:24 +00001394 }
1395
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001396 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001397}
1398
Greg Clayton9e920902012-04-10 02:25:43 +00001399void
1400ProcessGDBRemote::ClearThreadIDList ()
1401{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001402 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001403 m_thread_ids.clear();
1404}
1405
1406bool
1407ProcessGDBRemote::UpdateThreadIDList ()
1408{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001409 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001410 bool sequence_mutex_unavailable = false;
1411 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1412 if (sequence_mutex_unavailable)
1413 {
Greg Clayton9e920902012-04-10 02:25:43 +00001414 return false; // We just didn't get the list
1415 }
1416 return true;
1417}
1418
Greg Clayton9fc13552012-04-10 00:18:59 +00001419bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001420ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001421{
1422 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +00001423 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Clayton73b472d2010-10-27 03:32:59 +00001424 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +00001425 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton9e920902012-04-10 02:25:43 +00001426
1427 size_t num_thread_ids = m_thread_ids.size();
1428 // The "m_thread_ids" thread ID list should always be updated after each stop
1429 // reply packet, but in case it isn't, update it here.
1430 if (num_thread_ids == 0)
1431 {
1432 if (!UpdateThreadIDList ())
1433 return false;
1434 num_thread_ids = m_thread_ids.size();
1435 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001436
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001437 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001438 if (num_thread_ids > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001439 {
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001440 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001441 {
Greg Clayton9e920902012-04-10 02:25:43 +00001442 tid_t tid = m_thread_ids[i];
Greg Clayton160c9d82013-05-01 21:54:04 +00001443 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001444 if (!thread_sp)
Jim Inghamdee1bc92013-06-22 00:27:45 +00001445 {
Jim Ingham4f465cf2012-10-10 18:32:14 +00001446 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001447 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1448 log->Printf(
1449 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1450 __FUNCTION__,
1451 thread_sp.get(),
1452 thread_sp->GetID());
1453 }
1454 else
1455 {
1456 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1457 log->Printf(
1458 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
1459 __FUNCTION__,
1460 thread_sp.get(),
1461 thread_sp->GetID());
1462 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001463 new_thread_list.AddThread(thread_sp);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001464 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001465 }
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001466
1467 // Whatever that is left in old_thread_list_copy are not
1468 // present in new_thread_list. Remove non-existent threads from internal id table.
1469 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1470 for (size_t i=0; i<old_num_thread_ids; i++)
1471 {
1472 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1473 if (old_thread_sp)
1474 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001475 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001476 m_thread_id_to_index_id_map.erase(old_thread_id);
1477 }
1478 }
1479
Greg Clayton9fc13552012-04-10 00:18:59 +00001480 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001481}
1482
1483
1484StateType
1485ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1486{
Greg Claytondd0e5a52011-06-02 22:22:38 +00001487 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001488 const char stop_type = stop_packet.GetChar();
1489 switch (stop_type)
1490 {
1491 case 'T':
1492 case 'S':
1493 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00001494 // This is a bit of a hack, but is is required. If we did exec, we
1495 // need to clear our thread lists and also know to rebuild our dynamic
1496 // register info before we lookup and threads and populate the expedited
1497 // register values so we need to know this right away so we can cleanup
1498 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00001499 const uint32_t stop_id = GetStopID();
1500 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00001501 {
1502 // Our first stop, make sure we have a process ID, and also make
1503 // sure we know about our registers
1504 if (GetID() == LLDB_INVALID_PROCESS_ID)
1505 {
Greg Claytonc574ede2011-03-10 02:26:48 +00001506 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00001507 if (pid != LLDB_INVALID_PROCESS_ID)
1508 SetID (pid);
1509 }
1510 BuildDynamicRegisterInfo (true);
1511 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001512 // Stop with signal and thread info
1513 const uint8_t signo = stop_packet.GetHexU8();
1514 std::string name;
1515 std::string value;
1516 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00001517 std::string reason;
1518 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001519 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00001520 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001521 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001522 ThreadSP thread_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001523 ThreadGDBRemote *gdb_thread = NULL;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001524
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001525 while (stop_packet.GetNameColonValue(name, value))
1526 {
1527 if (name.compare("metype") == 0)
1528 {
1529 // exception type in big endian hex
1530 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1531 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001532 else if (name.compare("medata") == 0)
1533 {
1534 // exception data in big endian hex
1535 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1536 }
1537 else if (name.compare("thread") == 0)
1538 {
1539 // thread in big endian hex
Greg Clayton9e920902012-04-10 02:25:43 +00001540 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001541 // m_thread_list_real does have its own mutex, but we need to
1542 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1543 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1544 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1545 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
Greg Clayton160c9d82013-05-01 21:54:04 +00001546
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001547 if (!thread_sp)
Greg Claytond1d06e42013-04-20 00:27:58 +00001548 {
Greg Claytone576ab22011-02-15 00:19:15 +00001549 // Create the thread if we need to
Jim Ingham4f465cf2012-10-10 18:32:14 +00001550 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001551 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
1552 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1553 log->Printf ("ProcessGDBRemote::%s Adding new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1554 __FUNCTION__,
1555 thread_sp.get(),
1556 thread_sp->GetID());
1557
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001558 m_thread_list_real.AddThread(thread_sp);
Greg Claytone576ab22011-02-15 00:19:15 +00001559 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001560 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1561
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001562 }
Greg Clayton9e920902012-04-10 02:25:43 +00001563 else if (name.compare("threads") == 0)
1564 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001565 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001566 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00001567 // A comma separated list of all threads in the current
1568 // process that includes the thread for this stop reply
1569 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00001570 size_t comma_pos;
1571 lldb::tid_t tid;
1572 while ((comma_pos = value.find(',')) != std::string::npos)
1573 {
1574 value[comma_pos] = '\0';
1575 // thread in big endian hex
1576 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1577 if (tid != LLDB_INVALID_THREAD_ID)
1578 m_thread_ids.push_back (tid);
1579 value.erase(0, comma_pos + 1);
1580
1581 }
1582 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1583 if (tid != LLDB_INVALID_THREAD_ID)
1584 m_thread_ids.push_back (tid);
1585 }
Greg Claytonde9d0492011-01-08 03:17:57 +00001586 else if (name.compare("hexname") == 0)
1587 {
1588 StringExtractor name_extractor;
1589 // Swap "value" over into "name_extractor"
1590 name_extractor.GetStringRef().swap(value);
1591 // Now convert the HEX bytes into a string value
1592 name_extractor.GetHexByteString (value);
1593 thread_name.swap (value);
1594 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001595 else if (name.compare("name") == 0)
1596 {
1597 thread_name.swap (value);
1598 }
Greg Clayton6f35f5c2010-09-09 06:32:46 +00001599 else if (name.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001600 {
1601 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1602 }
Greg Claytona658fd22011-06-04 01:26:29 +00001603 else if (name.compare("reason") == 0)
1604 {
1605 reason.swap(value);
1606 }
1607 else if (name.compare("description") == 0)
1608 {
1609 StringExtractor desc_extractor;
1610 // Swap "value" over into "name_extractor"
1611 desc_extractor.GetStringRef().swap(value);
1612 // Now convert the HEX bytes into a string value
1613 desc_extractor.GetHexByteString (thread_name);
1614 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001615 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1616 {
1617 // We have a register number that contains an expedited
1618 // register value. Lets supply this register to our thread
1619 // so it won't have to go and read it.
Greg Clayton160c9d82013-05-01 21:54:04 +00001620 if (gdb_thread)
Greg Clayton3e06bd92011-01-09 21:07:35 +00001621 {
1622 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1623
1624 if (reg != UINT32_MAX)
1625 {
1626 StringExtractor reg_value_extractor;
1627 // Swap "value" over into "reg_value_extractor"
1628 reg_value_extractor.GetStringRef().swap(value);
Greg Clayton160c9d82013-05-01 21:54:04 +00001629 if (!gdb_thread->PrivateSetRegisterValue (reg, reg_value_extractor))
Greg Claytone576ab22011-02-15 00:19:15 +00001630 {
1631 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1632 name.c_str(),
1633 reg,
1634 reg,
1635 reg_value_extractor.GetStringRef().c_str(),
1636 stop_packet.GetStringRef().c_str());
1637 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001638 }
1639 }
1640 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001641 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001642
1643 if (thread_sp)
1644 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001645 // Clear the stop info just in case we don't set it to anything
1646 thread_sp->SetStopInfo (StopInfoSP());
1647
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001648 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Inghamdd2fe7a2011-01-28 02:23:12 +00001649 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001650 if (exc_type != 0)
1651 {
Greg Clayton1a65ae12011-01-25 23:55:37 +00001652 const size_t exc_data_size = exc_data.size();
Greg Claytonf4b47e12010-08-04 01:40:35 +00001653
Greg Clayton160c9d82013-05-01 21:54:04 +00001654 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1655 exc_type,
1656 exc_data_size,
1657 exc_data_size >= 1 ? exc_data[0] : 0,
1658 exc_data_size >= 2 ? exc_data[1] : 0,
1659 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001660 }
Greg Claytona658fd22011-06-04 01:26:29 +00001661 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001662 {
Greg Claytona658fd22011-06-04 01:26:29 +00001663 bool handled = false;
Greg Clayton8cda7f02013-05-21 21:55:59 +00001664 bool did_exec = false;
Greg Claytona658fd22011-06-04 01:26:29 +00001665 if (!reason.empty())
1666 {
1667 if (reason.compare("trace") == 0)
1668 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001669 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Greg Claytona658fd22011-06-04 01:26:29 +00001670 handled = true;
1671 }
1672 else if (reason.compare("breakpoint") == 0)
1673 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001674 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1675 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Claytona658fd22011-06-04 01:26:29 +00001676 if (bp_site_sp)
1677 {
1678 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1679 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1680 // 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 +00001681 handled = true;
Greg Clayton160c9d82013-05-01 21:54:04 +00001682 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00001683 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001684 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00001685 }
1686 else
1687 {
1688 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001689 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00001690 }
1691 }
1692
Greg Claytona658fd22011-06-04 01:26:29 +00001693 }
1694 else if (reason.compare("trap") == 0)
1695 {
1696 // Let the trap just use the standard signal stop reason below...
1697 }
1698 else if (reason.compare("watchpoint") == 0)
1699 {
1700 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1701 // TODO: locate the watchpoint somehow...
Greg Clayton160c9d82013-05-01 21:54:04 +00001702 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
Greg Claytona658fd22011-06-04 01:26:29 +00001703 handled = true;
1704 }
1705 else if (reason.compare("exception") == 0)
1706 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001707 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00001708 handled = true;
1709 }
Greg Clayton15fc2be2013-05-21 01:00:52 +00001710 else if (reason.compare("exec") == 0)
1711 {
Greg Clayton8cda7f02013-05-21 21:55:59 +00001712 did_exec = true;
Greg Clayton15fc2be2013-05-21 01:00:52 +00001713 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
1714 handled = true;
1715 }
Greg Claytona658fd22011-06-04 01:26:29 +00001716 }
1717
Greg Clayton15fc2be2013-05-21 01:00:52 +00001718 if (signo && did_exec == false)
Greg Claytona658fd22011-06-04 01:26:29 +00001719 {
1720 if (signo == SIGTRAP)
1721 {
1722 // Currently we are going to assume SIGTRAP means we are either
1723 // hitting a breakpoint or hardware single stepping.
Jim Ingham54cc6e42012-07-11 21:41:19 +00001724 handled = true;
Greg Clayton160c9d82013-05-01 21:54:04 +00001725 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1726 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Jim Ingham54cc6e42012-07-11 21:41:19 +00001727
Greg Claytona658fd22011-06-04 01:26:29 +00001728 if (bp_site_sp)
1729 {
1730 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1731 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1732 // 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 +00001733 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00001734 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001735 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00001736 }
1737 else
1738 {
1739 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001740 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00001741 }
1742 }
Jim Ingham54cc6e42012-07-11 21:41:19 +00001743 else
Greg Claytona658fd22011-06-04 01:26:29 +00001744 {
Jim Ingham4dc613b2012-10-27 02:52:04 +00001745 // If we were stepping then assume the stop was the result of the trace. If we were
1746 // not stepping then report the SIGTRAP.
1747 // FIXME: We are still missing the case where we single step over a trap instruction.
Greg Clayton160c9d82013-05-01 21:54:04 +00001748 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1749 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Jim Ingham4dc613b2012-10-27 02:52:04 +00001750 else
Greg Clayton160c9d82013-05-01 21:54:04 +00001751 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo));
Greg Claytona658fd22011-06-04 01:26:29 +00001752 }
1753 }
1754 if (!handled)
Greg Clayton160c9d82013-05-01 21:54:04 +00001755 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Jason Molenda8214b012013-04-25 01:33:46 +00001756 }
Greg Claytona658fd22011-06-04 01:26:29 +00001757
1758 if (!description.empty())
1759 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001760 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
Greg Claytona658fd22011-06-04 01:26:29 +00001761 if (stop_info_sp)
1762 {
1763 stop_info_sp->SetDescription (description.c_str());
Greg Clayton3418c852011-08-10 02:10:13 +00001764 }
Greg Claytona658fd22011-06-04 01:26:29 +00001765 else
1766 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001767 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00001768 }
1769 }
1770 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001771 }
1772 return eStateStopped;
1773 }
1774 break;
1775
1776 case 'W':
1777 // process exited
1778 return eStateExited;
1779
1780 default:
1781 break;
1782 }
1783 return eStateInvalid;
1784}
1785
1786void
1787ProcessGDBRemote::RefreshStateAfterStop ()
1788{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001789 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001790 m_thread_ids.clear();
1791 // Set the thread stop info. It might have a "threads" key whose value is
1792 // a list of all thread IDs in the current process, so m_thread_ids might
1793 // get set.
1794 SetThreadStopInfo (m_last_stop_packet);
1795 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1796 if (m_thread_ids.empty())
1797 {
1798 // No, we need to fetch the thread list manually
1799 UpdateThreadIDList();
1800 }
1801
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001802 // Let all threads recover from stopping and do any clean up based
1803 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001804 m_thread_list_real.RefreshStateAfterStop();
Greg Clayton9e920902012-04-10 02:25:43 +00001805
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001806}
1807
1808Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001809ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001810{
1811 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001812
Greg Clayton6ed95942011-01-22 07:12:45 +00001813 bool timed_out = false;
1814 Mutex::Locker locker;
Greg Clayton513c26c2011-01-29 07:10:55 +00001815
1816 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00001817 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001818 // We are being asked to halt during an attach. We need to just close
1819 // our file handle and debugserver will go away, and we can be done...
1820 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00001821 }
Greg Clayton513c26c2011-01-29 07:10:55 +00001822 else
1823 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001824 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton513c26c2011-01-29 07:10:55 +00001825 {
1826 if (timed_out)
1827 error.SetErrorString("timed out sending interrupt packet");
1828 else
1829 error.SetErrorString("unknown error sending interrupt packet");
1830 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001831
1832 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton513c26c2011-01-29 07:10:55 +00001833 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001834 return error;
1835}
1836
1837Error
Jim Inghamacff8952013-05-02 00:27:30 +00001838ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00001839{
1840 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001841 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00001842 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00001843 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
1844
Greg Clayton594e5ed2010-09-27 21:07:38 +00001845 DisableAllBreakpointSites ();
1846
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001847 m_thread_list.DiscardThreadPlans();
Greg Clayton594e5ed2010-09-27 21:07:38 +00001848
Jim Inghamacff8952013-05-02 00:27:30 +00001849 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001850 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00001851 {
Jim Inghamacff8952013-05-02 00:27:30 +00001852 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001853 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1854 else
Jim Inghamacff8952013-05-02 00:27:30 +00001855 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00001856 }
Jim Inghamacff8952013-05-02 00:27:30 +00001857
1858 if (!error.Success())
1859 return error;
1860
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001861 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00001862 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001863
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001864 SetPrivateState (eStateDetached);
1865 ResumePrivateStateThread();
1866
1867 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00001868 return error;
1869}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001870
Jim Ingham43c555d2012-07-04 00:35:43 +00001871
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001872Error
1873ProcessGDBRemote::DoDestroy ()
1874{
1875 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001876 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001877 if (log)
1878 log->Printf ("ProcessGDBRemote::DoDestroy()");
1879
Jim Ingham43c555d2012-07-04 00:35:43 +00001880 // There is a bug in older iOS debugservers where they don't shut down the process
1881 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
1882 // this can cause problems with restarting. So we check to see if any of our threads are stopped
1883 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
1884 // destroy it again.
1885 //
1886 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
1887 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
1888 // the debugservers with this bug are equal. There really should be a better way to test this!
1889 //
1890 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
1891 // get called here to destroy again and we're still at a breakpoint or exception, then we should
1892 // just do the straight-forward kill.
1893 //
1894 // And of course, if we weren't able to stop the process by the time we get here, it isn't
1895 // necessary (or helpful) to do any of this.
1896
1897 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
1898 {
1899 PlatformSP platform_sp = GetTarget().GetPlatform();
1900
1901 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
1902 if (platform_sp
1903 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00001904 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00001905 {
1906 if (m_destroy_tried_resuming)
1907 {
1908 if (log)
1909 log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again.");
1910 }
1911 else
1912 {
1913 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
1914 // but we really need it to happen here and it doesn't matter if we do it twice.
1915 m_thread_list.DiscardThreadPlans();
1916 DisableAllBreakpointSites();
1917
1918 bool stop_looks_like_crash = false;
1919 ThreadList &threads = GetThreadList();
1920
1921 {
Jim Ingham45350372012-09-11 00:08:52 +00001922 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00001923
1924 size_t num_threads = threads.GetSize();
1925 for (size_t i = 0; i < num_threads; i++)
1926 {
1927 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00001928 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00001929 StopReason reason = eStopReasonInvalid;
1930 if (stop_info_sp)
1931 reason = stop_info_sp->GetStopReason();
1932 if (reason == eStopReasonBreakpoint
1933 || reason == eStopReasonException)
1934 {
1935 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00001936 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
1937 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00001938 stop_info_sp->GetDescription());
1939 stop_looks_like_crash = true;
1940 break;
1941 }
1942 }
1943 }
1944
1945 if (stop_looks_like_crash)
1946 {
1947 if (log)
1948 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
1949 m_destroy_tried_resuming = true;
1950
1951 // If we are going to run again before killing, it would be good to suspend all the threads
1952 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
1953 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
1954 // have to run the risk of letting those threads proceed a bit.
1955
1956 {
Jim Ingham45350372012-09-11 00:08:52 +00001957 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00001958
1959 size_t num_threads = threads.GetSize();
1960 for (size_t i = 0; i < num_threads; i++)
1961 {
1962 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00001963 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00001964 StopReason reason = eStopReasonInvalid;
1965 if (stop_info_sp)
1966 reason = stop_info_sp->GetStopReason();
1967 if (reason != eStopReasonBreakpoint
1968 && reason != eStopReasonException)
1969 {
1970 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00001971 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
1972 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00001973 thread_sp->SetResumeState(eStateSuspended);
1974 }
1975 }
1976 }
1977 Resume ();
1978 return Destroy();
1979 }
1980 }
1981 }
1982 }
1983
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001984 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00001985 int exit_status = SIGABRT;
1986 std::string exit_string;
1987
Greg Clayton6ed95942011-01-22 07:12:45 +00001988 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001989 {
Jim Inghamaab78372011-10-28 01:11:35 +00001990 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00001991 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001992
1993 StringExtractorGDBRemote response;
1994 bool send_async = true;
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00001995 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3);
1996
Greg Claytonc574ede2011-03-10 02:26:48 +00001997 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton513c26c2011-01-29 07:10:55 +00001998 {
1999 char packet_cmd = response.GetChar(0);
2000
2001 if (packet_cmd == 'W' || packet_cmd == 'X')
2002 {
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002003 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002004 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00002005 exit_status = response.GetHexU8();
2006 }
2007 else
2008 {
2009 if (log)
2010 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2011 exit_string.assign("got unexpected response to k packet: ");
2012 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00002013 }
2014 }
2015 else
2016 {
Jim Inghambabfc382012-06-06 00:32:39 +00002017 if (log)
2018 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2019 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00002020 }
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002021
2022 m_gdb_comm.SetPacketTimeout(old_packet_timeout);
Greg Clayton6779606a2011-01-22 23:43:18 +00002023 }
Jim Inghambabfc382012-06-06 00:32:39 +00002024 else
2025 {
2026 if (log)
2027 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
Jim Inghamcfc09352012-07-27 23:57:19 +00002028 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00002029 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002030 }
Jim Inghambabfc382012-06-06 00:32:39 +00002031 else
2032 {
2033 // If we missed setting the exit status on the way out, do it here.
2034 // NB set exit status can be called multiple times, the first one sets the status.
2035 exit_string.assign("destroying when not connected to debugserver");
2036 }
2037
2038 SetExitStatus(exit_status, exit_string.c_str());
2039
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002040 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002041 KillDebugserverProcess ();
2042 return error;
2043}
2044
Greg Clayton8cda7f02013-05-21 21:55:59 +00002045void
2046ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2047{
2048 lldb_private::Mutex::Locker locker (m_last_stop_packet_mutex);
2049 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2050 if (did_exec)
2051 {
2052 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2053 if (log)
2054 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2055
2056 m_thread_list_real.Clear();
2057 m_thread_list.Clear();
2058 BuildDynamicRegisterInfo (true);
2059 m_gdb_comm.ResetDiscoverableSettings();
2060 }
2061 m_last_stop_packet = response;
2062}
2063
2064
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002065//------------------------------------------------------------------
2066// Process Queries
2067//------------------------------------------------------------------
2068
2069bool
2070ProcessGDBRemote::IsAlive ()
2071{
Greg Clayton10177aa2010-12-08 05:08:21 +00002072 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002073}
2074
2075addr_t
2076ProcessGDBRemote::GetImageInfoAddress()
2077{
Jason Molenda6ba6d3d2013-01-30 04:39:32 +00002078 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002079}
2080
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002081//------------------------------------------------------------------
2082// Process Memory
2083//------------------------------------------------------------------
2084size_t
2085ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2086{
2087 if (size > m_max_memory_size)
2088 {
2089 // Keep memory read sizes down to a sane limit. This function will be
2090 // called multiple times in order to complete the task by
2091 // lldb_private::Process so it is ok to do this.
2092 size = m_max_memory_size;
2093 }
2094
2095 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002096 const int packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
Andy Gibbsa297a972013-06-19 19:04:53 +00002097 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002098 StringExtractorGDBRemote response;
Greg Claytonc574ede2011-03-10 02:26:48 +00002099 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002100 {
Greg Clayton576d8832011-03-22 04:00:09 +00002101 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002102 {
2103 error.Clear();
2104 return response.GetHexBytes(buf, size, '\xdd');
2105 }
Greg Clayton576d8832011-03-22 04:00:09 +00002106 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002107 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002108 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002109 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002110 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002111 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002112 }
2113 else
2114 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002115 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002116 }
2117 return 0;
2118}
2119
2120size_t
2121ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2122{
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002123 if (size > m_max_memory_size)
2124 {
2125 // Keep memory read sizes down to a sane limit. This function will be
2126 // called multiple times in order to complete the task by
2127 // lldb_private::Process so it is ok to do this.
2128 size = m_max_memory_size;
2129 }
2130
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002131 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00002132 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Clayton7fb56d02011-02-01 01:31:41 +00002133 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002134 StringExtractorGDBRemote response;
Greg Claytonc574ede2011-03-10 02:26:48 +00002135 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002136 {
Greg Clayton576d8832011-03-22 04:00:09 +00002137 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002138 {
2139 error.Clear();
2140 return size;
2141 }
Greg Clayton576d8832011-03-22 04:00:09 +00002142 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002143 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002144 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002145 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002146 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002147 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 +00002148 }
2149 else
2150 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002151 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002152 }
2153 return 0;
2154}
2155
2156lldb::addr_t
2157ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2158{
Greg Clayton2a48f522011-05-14 01:50:35 +00002159 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2160
Greg Clayton70b57652011-05-15 01:25:55 +00002161 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton2a48f522011-05-14 01:50:35 +00002162 switch (supported)
2163 {
2164 case eLazyBoolCalculate:
2165 case eLazyBoolYes:
2166 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2167 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2168 return allocated_addr;
2169
2170 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002171 // Call mmap() to create memory in the inferior..
2172 unsigned prot = 0;
2173 if (permissions & lldb::ePermissionsReadable)
2174 prot |= eMmapProtRead;
2175 if (permissions & lldb::ePermissionsWritable)
2176 prot |= eMmapProtWrite;
2177 if (permissions & lldb::ePermissionsExecutable)
2178 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00002179
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002180 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2181 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2182 m_addr_to_mmap_size[allocated_addr] = size;
2183 else
2184 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton2a48f522011-05-14 01:50:35 +00002185 break;
2186 }
2187
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002188 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00002189 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002190 else
2191 error.Clear();
2192 return allocated_addr;
2193}
2194
2195Error
Greg Clayton46fb5582011-11-18 07:03:08 +00002196ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2197 MemoryRegionInfo &region_info)
2198{
2199
2200 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2201 return error;
2202}
2203
2204Error
Johnny Chen64637202012-05-23 21:09:52 +00002205ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2206{
2207
2208 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2209 return error;
2210}
2211
2212Error
Enrico Granataf04a2192012-07-13 23:18:48 +00002213ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2214{
2215 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2216 return error;
2217}
2218
2219Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002220ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2221{
2222 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00002223 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2224
2225 switch (supported)
2226 {
2227 case eLazyBoolCalculate:
2228 // We should never be deallocating memory without allocating memory
2229 // first so we should never get eLazyBoolCalculate
2230 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2231 break;
2232
2233 case eLazyBoolYes:
2234 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00002235 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002236 break;
2237
2238 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002239 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00002240 {
2241 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002242 if (pos != m_addr_to_mmap_size.end() &&
2243 InferiorCallMunmap(this, addr, pos->second))
2244 m_addr_to_mmap_size.erase (pos);
2245 else
Daniel Malead01b2952012-11-29 21:49:15 +00002246 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002247 }
2248 break;
2249 }
2250
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002251 return error;
2252}
2253
2254
2255//------------------------------------------------------------------
2256// Process STDIO
2257//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002258size_t
2259ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2260{
2261 if (m_stdio_communication.IsConnected())
2262 {
2263 ConnectionStatus status;
2264 m_stdio_communication.Write(src, src_len, status, NULL);
2265 }
2266 return 0;
2267}
2268
2269Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002270ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002271{
2272 Error error;
2273 assert (bp_site != NULL);
2274
Greg Clayton5160ce52013-03-27 23:08:40 +00002275 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002276 user_id_t site_id = bp_site->GetID();
2277 const addr_t addr = bp_site->GetLoadAddress();
2278 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002279 log->Printf ("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002280
2281 if (bp_site->IsEnabled())
2282 {
2283 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002284 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 +00002285 return error;
2286 }
2287 else
2288 {
2289 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2290
Greg Claytoneb023e72013-10-11 19:48:25 +00002291 if (bp_site->HardwareRequired())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002292 {
2293 // Try and set hardware breakpoint, and if that fails, fall through
2294 // and set a software breakpoint?
Greg Clayton8b82f082011-04-12 05:54:46 +00002295 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002296 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002297 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002298 {
2299 bp_site->SetEnabled(true);
Greg Clayton8b82f082011-04-12 05:54:46 +00002300 bp_site->SetType (BreakpointSite::eHardware);
Greg Claytoneb023e72013-10-11 19:48:25 +00002301 }
2302 else
2303 {
2304 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002305 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002306 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002307 else
2308 {
2309 error.SetErrorString("hardware breakpoints are not supported");
2310 }
2311 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002312 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002313 else if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002314 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002315 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
2316 {
2317 bp_site->SetEnabled(true);
2318 bp_site->SetType (BreakpointSite::eExternal);
2319 return error;
2320 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002321 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002322
2323 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002324 }
2325
2326 if (log)
2327 {
2328 const char *err_string = error.AsCString();
Jim Ingham299c0c12013-02-15 02:06:30 +00002329 log->Printf ("ProcessGDBRemote::EnableBreakpointSite () error for breakpoint at 0x%8.8" PRIx64 ": %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002330 bp_site->GetLoadAddress(),
2331 err_string ? err_string : "NULL");
2332 }
2333 // We shouldn't reach here on a successful breakpoint enable...
2334 if (error.Success())
2335 error.SetErrorToGenericError();
2336 return error;
2337}
2338
2339Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002340ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002341{
2342 Error error;
2343 assert (bp_site != NULL);
2344 addr_t addr = bp_site->GetLoadAddress();
2345 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00002346 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002347 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002348 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002349
2350 if (bp_site->IsEnabled())
2351 {
2352 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2353
Greg Clayton8b82f082011-04-12 05:54:46 +00002354 BreakpointSite::Type bp_type = bp_site->GetType();
2355 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002356 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002357 case BreakpointSite::eSoftware:
2358 error = DisableSoftwareBreakpoint (bp_site);
2359 break;
2360
2361 case BreakpointSite::eHardware:
2362 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2363 error.SetErrorToGenericError();
2364 break;
2365
2366 case BreakpointSite::eExternal:
2367 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2368 error.SetErrorToGenericError();
2369 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002370 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002371 if (error.Success())
2372 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002373 }
2374 else
2375 {
2376 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002377 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 +00002378 return error;
2379 }
2380
2381 if (error.Success())
2382 error.SetErrorToGenericError();
2383 return error;
2384}
2385
Johnny Chen11309a32011-09-06 22:38:36 +00002386// Pre-requisite: wp != NULL.
2387static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00002388GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00002389{
2390 assert(wp);
2391 bool watch_read = wp->WatchpointRead();
2392 bool watch_write = wp->WatchpointWrite();
2393
2394 // watch_read and watch_write cannot both be false.
2395 assert(watch_read || watch_write);
2396 if (watch_read && watch_write)
2397 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00002398 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00002399 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00002400 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00002401 return eWatchpointWrite;
2402}
2403
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002404Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002405ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002406{
2407 Error error;
2408 if (wp)
2409 {
2410 user_id_t watchID = wp->GetID();
2411 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00002412 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002413 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002414 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002415 if (wp->IsEnabled())
2416 {
2417 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002418 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 +00002419 return error;
2420 }
Johnny Chen11309a32011-09-06 22:38:36 +00002421
2422 GDBStoppointType type = GetGDBStoppointType(wp);
2423 // Pass down an appropriate z/Z packet...
2424 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002425 {
Johnny Chen11309a32011-09-06 22:38:36 +00002426 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2427 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002428 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002429 return error;
2430 }
2431 else
2432 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002433 }
Johnny Chen11309a32011-09-06 22:38:36 +00002434 else
2435 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002436 }
2437 else
2438 {
Johnny Chen01a67862011-10-14 00:42:25 +00002439 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002440 }
2441 if (error.Success())
2442 error.SetErrorToGenericError();
2443 return error;
2444}
2445
2446Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002447ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002448{
2449 Error error;
2450 if (wp)
2451 {
2452 user_id_t watchID = wp->GetID();
2453
Greg Clayton5160ce52013-03-27 23:08:40 +00002454 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002455
2456 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00002457
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002458 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002459 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002460
Johnny Chen11309a32011-09-06 22:38:36 +00002461 if (!wp->IsEnabled())
2462 {
2463 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002464 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 +00002465 // See also 'class WatchpointSentry' within StopInfo.cpp.
2466 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2467 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00002468 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002469 return error;
2470 }
2471
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002472 if (wp->IsHardware())
2473 {
Johnny Chen11309a32011-09-06 22:38:36 +00002474 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002475 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00002476 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2477 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002478 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002479 return error;
2480 }
2481 else
2482 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002483 }
2484 // TODO: clear software watchpoints if we implement them
2485 }
2486 else
2487 {
Johnny Chen01a67862011-10-14 00:42:25 +00002488 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002489 }
2490 if (error.Success())
2491 error.SetErrorToGenericError();
2492 return error;
2493}
2494
2495void
2496ProcessGDBRemote::Clear()
2497{
2498 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002499 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002500 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002501}
2502
2503Error
2504ProcessGDBRemote::DoSignal (int signo)
2505{
2506 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002507 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002508 if (log)
2509 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2510
2511 if (!m_gdb_comm.SendAsyncSignal (signo))
2512 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2513 return error;
2514}
2515
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002516Error
Han Ming Ong84647042012-02-25 01:07:38 +00002517ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)
2518{
2519 ProcessLaunchInfo launch_info;
2520 return StartDebugserverProcess(debugserver_url, launch_info);
2521}
2522
2523Error
2524ProcessGDBRemote::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 +00002525{
2526 Error error;
2527 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2528 {
2529 // If we locate debugserver, keep that located version around
2530 static FileSpec g_debugserver_file_spec;
2531
Han Ming Ong84647042012-02-25 01:07:38 +00002532 ProcessLaunchInfo debugserver_launch_info;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002533 char debugserver_path[PATH_MAX];
Han Ming Ong84647042012-02-25 01:07:38 +00002534 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002535
2536 // Always check to see if we have an environment override for the path
2537 // to the debugserver to use and use it if we do.
2538 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2539 if (env_debugserver_path)
Greg Clayton274060b2010-10-20 20:54:39 +00002540 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002541 else
2542 debugserver_file_spec = g_debugserver_file_spec;
2543 bool debugserver_exists = debugserver_file_spec.Exists();
2544 if (!debugserver_exists)
2545 {
2546 // The debugserver binary is in the LLDB.framework/Resources
2547 // directory.
Greg Claytondd36def2010-10-17 22:03:32 +00002548 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002549 {
Greg Claytondd36def2010-10-17 22:03:32 +00002550 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002551 debugserver_exists = debugserver_file_spec.Exists();
Greg Claytondd36def2010-10-17 22:03:32 +00002552 if (debugserver_exists)
2553 {
2554 g_debugserver_file_spec = debugserver_file_spec;
2555 }
2556 else
2557 {
2558 g_debugserver_file_spec.Clear();
2559 debugserver_file_spec.Clear();
2560 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002561 }
2562 }
2563
2564 if (debugserver_exists)
2565 {
2566 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2567
2568 m_stdio_communication.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002569
Greg Clayton5160ce52013-03-27 23:08:40 +00002570 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002571
Han Ming Ong84647042012-02-25 01:07:38 +00002572 Args &debugserver_args = debugserver_launch_info.GetArguments();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002573 char arg_cstr[PATH_MAX];
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002574
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002575 // Start args with "debugserver /file/path -r --"
2576 debugserver_args.AppendArgument(debugserver_path);
2577 debugserver_args.AppendArgument(debugserver_url);
Greg Claytondd36def2010-10-17 22:03:32 +00002578 // use native registers, not the GDB registers
2579 debugserver_args.AppendArgument("--native-regs");
2580 // make debugserver run in its own session so signals generated by
2581 // special terminal key sequences (^C) don't affect debugserver
2582 debugserver_args.AppendArgument("--setsid");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002583
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002584 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2585 if (env_debugserver_log_file)
2586 {
2587 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2588 debugserver_args.AppendArgument(arg_cstr);
2589 }
2590
2591 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2592 if (env_debugserver_log_flags)
2593 {
2594 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2595 debugserver_args.AppendArgument(arg_cstr);
2596 }
Jim Inghama0cc6b22012-10-03 22:31:30 +00002597// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
2598// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002599
Greg Clayton8b82f082011-04-12 05:54:46 +00002600 // We currently send down all arguments, attach pids, or attach
2601 // process names in dedicated GDB server packets, so we don't need
2602 // to pass them as arguments. This is currently because of all the
2603 // things we need to setup prior to launching: the environment,
2604 // current working dir, file actions, etc.
2605#if 0
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002606 // Now append the program arguments
Greg Clayton71337622011-02-24 22:24:29 +00002607 if (inferior_argv)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002608 {
Greg Clayton71337622011-02-24 22:24:29 +00002609 // Terminate the debugserver args so we can now append the inferior args
2610 debugserver_args.AppendArgument("--");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002611
Greg Clayton71337622011-02-24 22:24:29 +00002612 for (int i = 0; inferior_argv[i] != NULL; ++i)
2613 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002614 }
2615 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2616 {
2617 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2618 debugserver_args.AppendArgument (arg_cstr);
2619 }
2620 else if (attach_name && attach_name[0])
2621 {
2622 if (wait_for_launch)
2623 debugserver_args.AppendArgument ("--waitfor");
2624 else
2625 debugserver_args.AppendArgument ("--attach");
2626 debugserver_args.AppendArgument (attach_name);
2627 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002628#endif
Greg Clayton8b82f082011-04-12 05:54:46 +00002629
2630 ProcessLaunchInfo::FileAction file_action;
2631
2632 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2633 // to "/dev/null" if we run into any problems.
2634 file_action.Close (STDIN_FILENO);
Han Ming Ong84647042012-02-25 01:07:38 +00002635 debugserver_launch_info.AppendFileAction (file_action);
Greg Clayton8b82f082011-04-12 05:54:46 +00002636 file_action.Close (STDOUT_FILENO);
Han Ming Ong84647042012-02-25 01:07:38 +00002637 debugserver_launch_info.AppendFileAction (file_action);
Greg Clayton8b82f082011-04-12 05:54:46 +00002638 file_action.Close (STDERR_FILENO);
Han Ming Ong84647042012-02-25 01:07:38 +00002639 debugserver_launch_info.AppendFileAction (file_action);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002640
2641 if (log)
2642 {
2643 StreamString strm;
2644 debugserver_args.Dump (&strm);
2645 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2646 }
2647
Han Ming Ong84647042012-02-25 01:07:38 +00002648 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2649 debugserver_launch_info.SetUserID(process_info.GetUserID());
Greg Claytone4e45922011-11-16 05:37:56 +00002650
Han Ming Ong84647042012-02-25 01:07:38 +00002651 error = Host::LaunchProcess(debugserver_launch_info);
Greg Clayton0b42ac32010-07-02 01:29:13 +00002652
Greg Clayton8b82f082011-04-12 05:54:46 +00002653 if (error.Success ())
Han Ming Ong84647042012-02-25 01:07:38 +00002654 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Greg Clayton8b82f082011-04-12 05:54:46 +00002655 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002656 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2657
2658 if (error.Fail() || log)
Greg Clayton5160ce52013-03-27 23:08:40 +00002659 error.PutToLog(log, "Host::LaunchProcess (launch_info) => pid=%" PRIu64 ", path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002660 }
2661 else
2662 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002663 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002664 }
2665
2666 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2667 StartAsyncThread ();
2668 }
2669 return error;
2670}
2671
2672bool
2673ProcessGDBRemote::MonitorDebugserverProcess
2674(
2675 void *callback_baton,
2676 lldb::pid_t debugserver_pid,
Greg Claytone4e45922011-11-16 05:37:56 +00002677 bool exited, // True if the process did exit
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002678 int signo, // Zero for no signal
2679 int exit_status // Exit value of process if signal is zero
2680)
2681{
Greg Claytone4e45922011-11-16 05:37:56 +00002682 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2683 // and might not exist anymore, so we need to carefully try to get the
2684 // target for this process first since we have a race condition when
2685 // we are done running between getting the notice that the inferior
2686 // process has died and the debugserver that was debugging this process.
2687 // In our test suite, we are also continually running process after
2688 // process, so we must be very careful to make sure:
2689 // 1 - process object hasn't been deleted already
2690 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002691
2692 // "debugserver_pid" argument passed in is the process ID for
2693 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00002694 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002695
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002696 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton6779606a2011-01-22 23:43:18 +00002697
Greg Claytone4e45922011-11-16 05:37:56 +00002698 // Get a shared pointer to the target that has a matching process pointer.
2699 // This target could be gone, or the target could already have a new process
2700 // object inside of it
2701 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2702
Greg Clayton6779606a2011-01-22 23:43:18 +00002703 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002704 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 +00002705
Greg Claytone4e45922011-11-16 05:37:56 +00002706 if (target_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002707 {
Greg Claytone4e45922011-11-16 05:37:56 +00002708 // We found a process in a target that matches, but another thread
2709 // might be in the process of launching a new process that will
2710 // soon replace it, so get a shared pointer to the process so we
2711 // can keep it alive.
2712 ProcessSP process_sp (target_sp->GetProcessSP());
2713 // Now we have a shared pointer to the process that can't go away on us
2714 // so we now make sure it was the same as the one passed in, and also make
2715 // sure that our previous "process *" didn't get deleted and have a new
2716 // "process *" created in its place with the same pointer. To verify this
2717 // we make sure the process has our debugserver process ID. If we pass all
2718 // of these tests, then we are sure that this process is the one we were
2719 // looking for.
2720 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002721 {
Greg Claytone4e45922011-11-16 05:37:56 +00002722 // Sleep for a half a second to make sure our inferior process has
2723 // time to set its exit status before we set it incorrectly when
2724 // both the debugserver and the inferior process shut down.
2725 usleep (500000);
2726 // If our process hasn't yet exited, debugserver might have died.
2727 // If the process did exit, the we are reaping it.
2728 const StateType state = process->GetState();
2729
2730 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2731 state != eStateInvalid &&
2732 state != eStateUnloaded &&
2733 state != eStateExited &&
2734 state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002735 {
Greg Claytone4e45922011-11-16 05:37:56 +00002736 char error_str[1024];
2737 if (signo)
2738 {
2739 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2740 if (signal_cstr)
2741 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2742 else
2743 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2744 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002745 else
Greg Claytone4e45922011-11-16 05:37:56 +00002746 {
2747 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2748 }
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002749
Greg Claytone4e45922011-11-16 05:37:56 +00002750 process->SetExitStatus (-1, error_str);
2751 }
2752 // Debugserver has exited we need to let our ProcessGDBRemote
2753 // know that it no longer has a debugserver instance
2754 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002755 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002756 }
2757 return true;
2758}
2759
2760void
2761ProcessGDBRemote::KillDebugserverProcess ()
2762{
2763 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2764 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002765 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002766 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2767 }
2768}
2769
2770void
2771ProcessGDBRemote::Initialize()
2772{
2773 static bool g_initialized = false;
2774
2775 if (g_initialized == false)
2776 {
2777 g_initialized = true;
2778 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2779 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00002780 CreateInstance,
2781 DebuggerInitialize);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002782
2783 Log::Callbacks log_callbacks = {
2784 ProcessGDBRemoteLog::DisableLog,
2785 ProcessGDBRemoteLog::EnableLog,
2786 ProcessGDBRemoteLog::ListLogCategories
2787 };
2788
2789 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2790 }
2791}
2792
Greg Clayton7f982402013-07-15 22:54:20 +00002793void
2794ProcessGDBRemote::DebuggerInitialize (lldb_private::Debugger &debugger)
2795{
2796 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
2797 {
2798 const bool is_global_setting = true;
2799 PluginManager::CreateSettingForProcessPlugin (debugger,
2800 GetGlobalPluginProperties()->GetValueProperties(),
2801 ConstString ("Properties for the gdb-remote process plug-in."),
2802 is_global_setting);
2803 }
2804}
2805
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002806bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002807ProcessGDBRemote::StartAsyncThread ()
2808{
Greg Clayton5160ce52013-03-27 23:08:40 +00002809 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002810
2811 if (log)
2812 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Ingham455fa5c2012-11-01 01:15:33 +00002813
2814 Mutex::Locker start_locker(m_async_thread_state_mutex);
2815 if (m_async_thread_state == eAsyncThreadNotStarted)
2816 {
2817 // Create a thread that watches our internal state and controls which
2818 // events make it to clients (into the DCProcess event queue).
2819 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2820 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2821 {
2822 m_async_thread_state = eAsyncThreadRunning;
2823 return true;
2824 }
2825 else
2826 return false;
2827 }
2828 else
2829 {
2830 // Somebody tried to start the async thread while it was either being started or stopped. If the former, and
2831 // it started up successfully, then say all's well. Otherwise it is an error, since we aren't going to restart it.
2832 if (log)
2833 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
2834 if (m_async_thread_state == eAsyncThreadRunning)
2835 return true;
2836 else
2837 return false;
2838 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002839}
2840
2841void
2842ProcessGDBRemote::StopAsyncThread ()
2843{
Greg Clayton5160ce52013-03-27 23:08:40 +00002844 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002845
2846 if (log)
2847 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2848
Jim Ingham455fa5c2012-11-01 01:15:33 +00002849 Mutex::Locker start_locker(m_async_thread_state_mutex);
2850 if (m_async_thread_state == eAsyncThreadRunning)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002851 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00002852 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2853
2854 // This will shut down the async thread.
2855 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
2856
2857 // Stop the stdio thread
2858 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2859 {
2860 Host::ThreadJoin (m_async_thread, NULL, NULL);
2861 }
2862 m_async_thread_state = eAsyncThreadDone;
2863 }
2864 else
2865 {
2866 if (log)
2867 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002868 }
2869}
2870
2871
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002872thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002873ProcessGDBRemote::AsyncThread (void *arg)
2874{
2875 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2876
Greg Clayton5160ce52013-03-27 23:08:40 +00002877 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002878 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002879 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002880
2881 Listener listener ("ProcessGDBRemote::AsyncThread");
2882 EventSP event_sp;
2883 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2884 eBroadcastBitAsyncThreadShouldExit;
2885
2886 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2887 {
Greg Clayton71337622011-02-24 22:24:29 +00002888 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2889
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002890 bool done = false;
2891 while (!done)
2892 {
2893 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002894 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002895 if (listener.WaitForEvent (NULL, event_sp))
2896 {
2897 const uint32_t event_type = event_sp->GetType();
Greg Clayton71337622011-02-24 22:24:29 +00002898 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002899 {
Greg Clayton71337622011-02-24 22:24:29 +00002900 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002901 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 +00002902
Greg Clayton71337622011-02-24 22:24:29 +00002903 switch (event_type)
2904 {
2905 case eBroadcastBitAsyncContinue:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002906 {
Greg Clayton71337622011-02-24 22:24:29 +00002907 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002908
Greg Clayton71337622011-02-24 22:24:29 +00002909 if (continue_packet)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002910 {
Greg Clayton71337622011-02-24 22:24:29 +00002911 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2912 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2913 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002914 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002915
Greg Clayton71337622011-02-24 22:24:29 +00002916 if (::strstr (continue_cstr, "vAttach") == NULL)
2917 process->SetPrivateState(eStateRunning);
2918 StringExtractorGDBRemote response;
2919 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002920
Greg Clayton0772ded2012-05-16 02:48:06 +00002921 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
2922 // The thread ID list might be contained within the "response", or the stop reply packet that
2923 // caused the stop. So clear it now before we give the stop reply packet to the process
2924 // using the process->SetLastStopPacket()...
2925 process->ClearThreadIDList ();
2926
Greg Clayton71337622011-02-24 22:24:29 +00002927 switch (stop_state)
2928 {
2929 case eStateStopped:
2930 case eStateCrashed:
2931 case eStateSuspended:
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002932 process->SetLastStopPacket (response);
Greg Clayton71337622011-02-24 22:24:29 +00002933 process->SetPrivateState (stop_state);
2934 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002935
Greg Clayton71337622011-02-24 22:24:29 +00002936 case eStateExited:
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002937 process->SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002938 process->ClearThreadIDList();
Greg Clayton71337622011-02-24 22:24:29 +00002939 response.SetFilePos(1);
2940 process->SetExitStatus(response.GetHexU8(), NULL);
2941 done = true;
2942 break;
2943
2944 case eStateInvalid:
2945 process->SetExitStatus(-1, "lost connection");
2946 break;
2947
2948 default:
2949 process->SetPrivateState (stop_state);
2950 break;
2951 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002952 }
2953 }
Greg Clayton71337622011-02-24 22:24:29 +00002954 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002955
Greg Clayton71337622011-02-24 22:24:29 +00002956 case eBroadcastBitAsyncThreadShouldExit:
2957 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002958 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Clayton71337622011-02-24 22:24:29 +00002959 done = true;
2960 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002961
Greg Clayton71337622011-02-24 22:24:29 +00002962 default:
2963 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002964 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 +00002965 done = true;
2966 break;
2967 }
2968 }
2969 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2970 {
2971 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2972 {
2973 process->SetExitStatus (-1, "lost connection");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002974 done = true;
Greg Clayton71337622011-02-24 22:24:29 +00002975 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002976 }
2977 }
2978 else
2979 {
2980 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002981 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002982 done = true;
2983 }
2984 }
2985 }
2986
2987 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002988 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002989
2990 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2991 return NULL;
2992}
2993
Greg Claytone996fd32011-03-08 22:40:15 +00002994//uint32_t
2995//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2996//{
2997// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2998// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2999// if (m_local_debugserver)
3000// {
3001// return Host::ListProcessesMatchingName (name, matches, pids);
3002// }
3003// else
3004// {
3005// // FIXME: Implement talking to the remote debugserver.
3006// return 0;
3007// }
3008//
3009//}
3010//
Jim Ingham1c823b42011-01-22 01:33:44 +00003011bool
3012ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
3013 lldb_private::StoppointCallbackContext *context,
3014 lldb::user_id_t break_id,
3015 lldb::user_id_t break_loc_id)
3016{
3017 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3018 // run so I can stop it if that's what I want to do.
Greg Clayton5160ce52013-03-27 23:08:40 +00003019 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00003020 if (log)
3021 log->Printf("Hit New Thread Notification breakpoint.");
3022 return false;
3023}
3024
3025
3026bool
3027ProcessGDBRemote::StartNoticingNewThreads()
3028{
Greg Clayton5160ce52013-03-27 23:08:40 +00003029 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00003030 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003031 {
Greg Clayton4116e932012-05-15 02:33:01 +00003032 if (log && log->GetVerbose())
3033 log->Printf("Enabled noticing new thread breakpoint.");
3034 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003035 }
Greg Clayton4116e932012-05-15 02:33:01 +00003036 else
Jim Ingham1c823b42011-01-22 01:33:44 +00003037 {
Greg Clayton4116e932012-05-15 02:33:01 +00003038 PlatformSP platform_sp (m_target.GetPlatform());
3039 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003040 {
Greg Clayton4116e932012-05-15 02:33:01 +00003041 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3042 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003043 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00003044 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00003045 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3046 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003047 }
3048 else
3049 {
3050 if (log)
3051 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00003052 }
3053 }
3054 }
Greg Clayton4116e932012-05-15 02:33:01 +00003055 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00003056}
3057
3058bool
3059ProcessGDBRemote::StopNoticingNewThreads()
3060{
Greg Clayton5160ce52013-03-27 23:08:40 +00003061 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00003062 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00003063 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00003064
3065 if (m_thread_create_bp_sp)
3066 m_thread_create_bp_sp->SetEnabled(false);
3067
Jim Ingham1c823b42011-01-22 01:33:44 +00003068 return true;
3069}
3070
Jason Molenda5e8534e2012-10-03 01:29:34 +00003071lldb_private::DynamicLoader *
3072ProcessGDBRemote::GetDynamicLoader ()
3073{
3074 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00003075 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00003076 return m_dyld_ap.get();
3077}
Jim Ingham1c823b42011-01-22 01:33:44 +00003078
Greg Clayton998255b2012-10-13 02:07:45 +00003079
Greg Clayton02686b82012-10-15 22:42:16 +00003080class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00003081{
3082private:
3083
3084public:
Greg Clayton02686b82012-10-15 22:42:16 +00003085 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00003086 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00003087 "process plugin packet history",
3088 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00003089 NULL)
3090 {
3091 }
3092
Greg Clayton02686b82012-10-15 22:42:16 +00003093 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton998255b2012-10-13 02:07:45 +00003094 {
3095 }
3096
3097 bool
3098 DoExecute (Args& command, CommandReturnObject &result)
3099 {
Greg Clayton02686b82012-10-15 22:42:16 +00003100 const size_t argc = command.GetArgumentCount();
3101 if (argc == 0)
3102 {
3103 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3104 if (process)
3105 {
3106 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
3107 result.SetStatus (eReturnStatusSuccessFinishResult);
3108 return true;
3109 }
3110 }
3111 else
3112 {
3113 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
3114 }
3115 result.SetStatus (eReturnStatusFailed);
3116 return false;
3117 }
3118};
3119
3120class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
3121{
3122private:
3123
3124public:
3125 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
3126 CommandObjectParsed (interpreter,
3127 "process plugin packet send",
3128 "Send a custom packet through the GDB remote protocol and print the answer. "
3129 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
3130 NULL)
3131 {
3132 }
3133
3134 ~CommandObjectProcessGDBRemotePacketSend ()
3135 {
3136 }
3137
3138 bool
3139 DoExecute (Args& command, CommandReturnObject &result)
3140 {
3141 const size_t argc = command.GetArgumentCount();
3142 if (argc == 0)
3143 {
3144 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
3145 result.SetStatus (eReturnStatusFailed);
3146 return false;
3147 }
3148
3149 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3150 if (process)
3151 {
Han Ming Ong84145852012-11-26 20:42:03 +00003152 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00003153 {
Han Ming Ong84145852012-11-26 20:42:03 +00003154 const char *packet_cstr = command.GetArgumentAtIndex(0);
3155 bool send_async = true;
3156 StringExtractorGDBRemote response;
3157 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3158 result.SetStatus (eReturnStatusSuccessFinishResult);
3159 Stream &output_strm = result.GetOutputStream();
3160 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00003161 std::string &response_str = response.GetStringRef();
3162
Han Ming Ong399289e2013-06-21 19:56:59 +00003163 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00003164 {
3165 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
3166 }
3167
Han Ming Ong84145852012-11-26 20:42:03 +00003168 if (response_str.empty())
3169 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3170 else
3171 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00003172 }
Greg Clayton02686b82012-10-15 22:42:16 +00003173 }
Greg Clayton998255b2012-10-13 02:07:45 +00003174 return true;
3175 }
3176};
3177
Greg Claytonba4a0a52013-02-01 23:03:47 +00003178class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
3179{
3180private:
3181
3182public:
3183 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
3184 CommandObjectRaw (interpreter,
3185 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00003186 "Send a qRcmd packet through the GDB remote protocol and print the response."
3187 "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 +00003188 NULL)
3189 {
3190 }
3191
3192 ~CommandObjectProcessGDBRemotePacketMonitor ()
3193 {
3194 }
3195
3196 bool
3197 DoExecute (const char *command, CommandReturnObject &result)
3198 {
3199 if (command == NULL || command[0] == '\0')
3200 {
3201 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
3202 result.SetStatus (eReturnStatusFailed);
3203 return false;
3204 }
3205
3206 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3207 if (process)
3208 {
3209 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00003210 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00003211 packet.PutBytesAsRawHex8(command, strlen(command));
3212 const char *packet_cstr = packet.GetString().c_str();
3213
3214 bool send_async = true;
3215 StringExtractorGDBRemote response;
3216 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3217 result.SetStatus (eReturnStatusSuccessFinishResult);
3218 Stream &output_strm = result.GetOutputStream();
3219 output_strm.Printf (" packet: %s\n", packet_cstr);
3220 const std::string &response_str = response.GetStringRef();
3221
3222 if (response_str.empty())
3223 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3224 else
3225 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
3226 }
3227 return true;
3228 }
3229};
3230
Greg Clayton02686b82012-10-15 22:42:16 +00003231class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
3232{
3233private:
3234
3235public:
3236 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
3237 CommandObjectMultiword (interpreter,
3238 "process plugin packet",
3239 "Commands that deal with GDB remote packets.",
3240 NULL)
3241 {
3242 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
3243 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00003244 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00003245 }
3246
3247 ~CommandObjectProcessGDBRemotePacket ()
3248 {
3249 }
3250};
Greg Clayton998255b2012-10-13 02:07:45 +00003251
3252class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
3253{
3254public:
3255 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
3256 CommandObjectMultiword (interpreter,
3257 "process plugin",
3258 "A set of commands for operating on a ProcessGDBRemote process.",
3259 "process plugin <subcommand> [<subcommand-options>]")
3260 {
3261 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
3262 }
3263
3264 ~CommandObjectMultiwordProcessGDBRemote ()
3265 {
3266 }
3267};
3268
Greg Clayton998255b2012-10-13 02:07:45 +00003269CommandObject *
3270ProcessGDBRemote::GetPluginCommandObject()
3271{
3272 if (!m_command_sp)
3273 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
3274 return m_command_sp.get();
3275}