blob: 604906e2a8504872d7f8c367ce5266e546cda502 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- ProcessGDBRemote.cpp ------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Daniel Malea93a64302012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
Virgile Bellob2f1fb22013-08-23 12:44:05 +000011#include "lldb/Host/Config.h"
Daniel Malea93a64302012-12-05 00:20:57 +000012
Chris Lattner30fdc8d2010-06-08 16:52:24 +000013// C Includes
14#include <errno.h>
Stephen Wilsona78867b2011-03-25 18:16:28 +000015#include <stdlib.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000016#ifndef LLDB_DISABLE_POSIX
17#include <spawn.h>
Sean Callanan224f6f52012-07-19 18:07:36 +000018#include <netinet/in.h>
Greg Clayton2a48f522011-05-14 01:50:35 +000019#include <sys/mman.h> // for mmap
Virgile Bellob2f1fb22013-08-23 12:44:05 +000020#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000021#include <sys/stat.h>
Greg Clayton2a48f522011-05-14 01:50:35 +000022#include <sys/types.h>
Stephen Wilsondc916862011-03-30 00:12:40 +000023#include <time.h>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000024
25// C++ Includes
26#include <algorithm>
27#include <map>
28
29// Other libraries and framework includes
30
Johnny Chen01a67862011-10-14 00:42:25 +000031#include "lldb/Breakpoint/Watchpoint.h"
Jim Ingham40af72e2010-06-15 19:49:27 +000032#include "lldb/Interpreter/Args.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000033#include "lldb/Core/ArchSpec.h"
34#include "lldb/Core/Debugger.h"
35#include "lldb/Core/ConnectionFileDescriptor.h"
Greg Clayton53239f02011-02-08 05:05:52 +000036#include "lldb/Host/FileSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000037#include "lldb/Core/Module.h"
Greg Clayton1f746072012-08-29 21:13:06 +000038#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000039#include "lldb/Core/PluginManager.h"
40#include "lldb/Core/State.h"
Greg Claytond451c1a2012-04-13 21:24:18 +000041#include "lldb/Core/StreamFile.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000042#include "lldb/Core/StreamString.h"
43#include "lldb/Core/Timer.h"
Greg Clayton70b57652011-05-15 01:25:55 +000044#include "lldb/Core/Value.h"
Jason Molendad1fae142012-09-29 08:03:33 +000045#include "lldb/Host/Symbols.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000046#include "lldb/Host/TimeValue.h"
Greg Clayton02686b82012-10-15 22:42:16 +000047#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton1d19a2f2012-10-19 22:22:57 +000048#include "lldb/Interpreter/CommandObject.h"
49#include "lldb/Interpreter/CommandObjectMultiword.h"
Greg Clayton02686b82012-10-15 22:42:16 +000050#include "lldb/Interpreter/CommandReturnObject.h"
Joerg Sonnenbergere77b0422013-10-20 17:36:05 +000051#ifndef LLDB_DISABLE_PYTHON
Greg Claytonef8180a2013-10-15 00:14:28 +000052#include "lldb/Interpreter/PythonDataObjects.h"
Joerg Sonnenbergere77b0422013-10-20 17:36:05 +000053#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000054#include "lldb/Symbol/ObjectFile.h"
55#include "lldb/Target/DynamicLoader.h"
56#include "lldb/Target/Target.h"
57#include "lldb/Target/TargetList.h"
Greg Clayton2a48f522011-05-14 01:50:35 +000058#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molendaa34a0c62010-06-09 21:28:42 +000059#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000060
61// Project includes
62#include "lldb/Host/Host.h"
Peter Collingbourne99f9aa02011-06-03 20:40:38 +000063#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Jason Molendac42d2432012-07-25 03:40:06 +000064#include "Plugins/Process/Utility/StopInfoMachException.h"
Jim Ingham43c555d2012-07-04 00:35:43 +000065#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
Greg Claytonc982c762010-07-09 20:39:50 +000066#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000067#include "GDBRemoteRegisterContext.h"
68#include "ProcessGDBRemote.h"
69#include "ProcessGDBRemoteLog.h"
70#include "ThreadGDBRemote.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000071
Jason Molenda5e8534e2012-10-03 01:29:34 +000072
Greg Claytonc1422c12012-04-09 22:46:21 +000073namespace lldb
74{
75 // Provide a function that can easily dump the packet history if we know a
76 // ProcessGDBRemote * value (which we can get from logs or from debugging).
77 // We need the function in the lldb namespace so it makes it into the final
78 // executable since the LLDB shared library only exports stuff in the lldb
79 // namespace. This allows you to attach with a debugger and call this
80 // function and get the packet history dumped to a file.
81 void
82 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
83 {
Greg Claytond451c1a2012-04-13 21:24:18 +000084 lldb_private::StreamFile strm;
85 lldb_private::Error error (strm.GetFile().Open(path, lldb_private::File::eOpenOptionWrite | lldb_private::File::eOpenOptionCanCreate));
86 if (error.Success())
87 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
Greg Claytonc1422c12012-04-09 22:46:21 +000088 }
Filipe Cabecinhasc34f7762012-05-23 16:27:09 +000089}
Chris Lattner30fdc8d2010-06-08 16:52:24 +000090
Chris Lattner30fdc8d2010-06-08 16:52:24 +000091#define DEBUGSERVER_BASENAME "debugserver"
92using namespace lldb;
93using namespace lldb_private;
94
Greg Clayton7f982402013-07-15 22:54:20 +000095
96namespace {
Steve Pucci5ec012d2014-01-16 22:18:14 +000097
Greg Clayton7f982402013-07-15 22:54:20 +000098 static PropertyDefinition
99 g_properties[] =
100 {
101 { "packet-timeout" , OptionValue::eTypeUInt64 , true , 1, NULL, NULL, "Specify the default packet timeout in seconds." },
Greg Claytonef8180a2013-10-15 00:14:28 +0000102 { "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 +0000103 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
104 };
105
106 enum
107 {
Greg Claytonef8180a2013-10-15 00:14:28 +0000108 ePropertyPacketTimeout,
109 ePropertyTargetDefinitionFile
Greg Clayton7f982402013-07-15 22:54:20 +0000110 };
111
112 class PluginProperties : public Properties
113 {
114 public:
115
116 static ConstString
117 GetSettingName ()
118 {
119 return ProcessGDBRemote::GetPluginNameStatic();
120 }
121
122 PluginProperties() :
123 Properties ()
124 {
125 m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
126 m_collection_sp->Initialize(g_properties);
127 }
128
129 virtual
130 ~PluginProperties()
131 {
132 }
133
134 uint64_t
135 GetPacketTimeout()
136 {
137 const uint32_t idx = ePropertyPacketTimeout;
138 return m_collection_sp->GetPropertyAtIndexAsUInt64(NULL, idx, g_properties[idx].default_uint_value);
139 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000140
141 bool
142 SetPacketTimeout(uint64_t timeout)
143 {
144 const uint32_t idx = ePropertyPacketTimeout;
145 return m_collection_sp->SetPropertyAtIndexAsUInt64(NULL, idx, timeout);
146 }
147
Greg Claytonef8180a2013-10-15 00:14:28 +0000148 FileSpec
149 GetTargetDefinitionFile () const
150 {
151 const uint32_t idx = ePropertyTargetDefinitionFile;
152 return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
153 }
Greg Clayton7f982402013-07-15 22:54:20 +0000154 };
155
156 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
157
158 static const ProcessKDPPropertiesSP &
159 GetGlobalPluginProperties()
160 {
161 static ProcessKDPPropertiesSP g_settings_sp;
162 if (!g_settings_sp)
163 g_settings_sp.reset (new PluginProperties ());
164 return g_settings_sp;
165 }
166
167} // anonymous namespace end
168
Greg Claytonfda4fab2014-01-10 22:24:11 +0000169static bool rand_initialized = false;
170
171// TODO Randomly assigning a port is unsafe. We should get an unused
172// ephemeral port from the kernel and make sure we reserve it before passing
173// it to debugserver.
174
175#if defined (__APPLE__)
176#define LOW_PORT (IPPORT_RESERVED)
177#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
178#else
179#define LOW_PORT (1024u)
180#define HIGH_PORT (49151u)
181#endif
182
183static inline uint16_t
184get_random_port ()
185{
186 if (!rand_initialized)
187 {
188 time_t seed = time(NULL);
189
190 rand_initialized = true;
191 srand(seed);
192 }
193 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
194}
195
196
Greg Clayton57abc5d2013-05-10 21:47:16 +0000197lldb_private::ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000198ProcessGDBRemote::GetPluginNameStatic()
199{
Greg Clayton57abc5d2013-05-10 21:47:16 +0000200 static ConstString g_name("gdb-remote");
201 return g_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000202}
203
204const char *
205ProcessGDBRemote::GetPluginDescriptionStatic()
206{
207 return "GDB Remote protocol based debugging plug-in.";
208}
209
210void
211ProcessGDBRemote::Terminate()
212{
213 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
214}
215
216
Greg Claytonc3776bf2012-02-09 06:16:32 +0000217lldb::ProcessSP
218ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000219{
Greg Claytonc3776bf2012-02-09 06:16:32 +0000220 lldb::ProcessSP process_sp;
221 if (crash_file_path == NULL)
222 process_sp.reset (new ProcessGDBRemote (target, listener));
223 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000224}
225
226bool
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000227ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000228{
Greg Clayton596ed242011-10-21 21:41:45 +0000229 if (plugin_specified_by_name)
230 return true;
231
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000232 // For now we are just making sure the file exists for a given module
Greg Claytonaa149cb2011-08-11 02:48:45 +0000233 Module *exe_module = target.GetExecutableModulePointer();
234 if (exe_module)
Greg Claytonc3776bf2012-02-09 06:16:32 +0000235 {
236 ObjectFile *exe_objfile = exe_module->GetObjectFile();
237 // We can't debug core files...
238 switch (exe_objfile->GetType())
239 {
240 case ObjectFile::eTypeInvalid:
241 case ObjectFile::eTypeCoreFile:
242 case ObjectFile::eTypeDebugInfo:
243 case ObjectFile::eTypeObjectFile:
244 case ObjectFile::eTypeSharedLibrary:
245 case ObjectFile::eTypeStubLibrary:
246 return false;
247 case ObjectFile::eTypeExecutable:
248 case ObjectFile::eTypeDynamicLinker:
249 case ObjectFile::eTypeUnknown:
250 break;
251 }
Greg Claytonaa149cb2011-08-11 02:48:45 +0000252 return exe_module->GetFileSpec().Exists();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000253 }
Jim Ingham5aee1622010-08-09 23:31:02 +0000254 // However, if there is no executable module, we return true since we might be preparing to attach.
255 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000256}
257
258//----------------------------------------------------------------------
259// ProcessGDBRemote constructor
260//----------------------------------------------------------------------
261ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
262 Process (target, listener),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000263 m_flags (0),
Greg Clayton8b82f082011-04-12 05:54:46 +0000264 m_gdb_comm(false),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000265 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Claytonc982c762010-07-09 20:39:50 +0000266 m_last_stop_packet (),
Greg Clayton09c3e3d2011-12-06 04:51:14 +0000267 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000268 m_register_info (),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000269 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000270 m_async_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham455fa5c2012-11-01 01:15:33 +0000271 m_async_thread_state(eAsyncThreadNotStarted),
272 m_async_thread_state_mutex(Mutex::eMutexTypeRecursive),
Greg Clayton9e920902012-04-10 02:25:43 +0000273 m_thread_ids (),
Greg Clayton71fc2a32011-02-12 06:28:37 +0000274 m_continue_c_tids (),
275 m_continue_C_tids (),
276 m_continue_s_tids (),
277 m_continue_S_tids (),
Greg Claytonc982c762010-07-09 20:39:50 +0000278 m_max_memory_size (512),
Greg Clayton4116e932012-05-15 02:33:01 +0000279 m_addr_to_mmap_size (),
280 m_thread_create_bp_sp (),
Jim Ingham43c555d2012-07-04 00:35:43 +0000281 m_waiting_for_attach (false),
Jason Molenda5e8534e2012-10-03 01:29:34 +0000282 m_destroy_tried_resuming (false),
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000283 m_command_sp (),
284 m_breakpoint_pc_offset (0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000285{
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000286 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
287 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Inghamb1e2e842012-04-12 18:49:31 +0000288 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Greg Clayton7f982402013-07-15 22:54:20 +0000289 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
290 if (timeout_seconds > 0)
291 m_gdb_comm.SetPacketTimeout(timeout_seconds);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000292}
293
294//----------------------------------------------------------------------
295// Destructor
296//----------------------------------------------------------------------
297ProcessGDBRemote::~ProcessGDBRemote()
298{
299 // m_mach_process.UnregisterNotificationCallbacks (this);
300 Clear();
Greg Clayton1ed54f52011-10-01 00:45:15 +0000301 // We need to call finalize on the process before destroying ourselves
302 // to make sure all of the broadcaster cleanup goes as planned. If we
303 // destruct this class, then Process::~Process() might have problems
304 // trying to fully destroy the broadcaster.
305 Finalize();
Jim Ingham455fa5c2012-11-01 01:15:33 +0000306
307 // The general Finalize is going to try to destroy the process and that SHOULD
308 // shut down the async thread. However, if we don't kill it it will get stranded and
309 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
310 StopAsyncThread();
311 KillDebugserverProcess();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000312}
313
314//----------------------------------------------------------------------
315// PluginInterface
316//----------------------------------------------------------------------
Greg Clayton57abc5d2013-05-10 21:47:16 +0000317ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000318ProcessGDBRemote::GetPluginName()
319{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000320 return GetPluginNameStatic();
321}
322
323uint32_t
324ProcessGDBRemote::GetPluginVersion()
325{
326 return 1;
327}
328
Greg Claytonef8180a2013-10-15 00:14:28 +0000329bool
330ProcessGDBRemote::ParsePythonTargetDefinition(const FileSpec &target_definition_fspec)
331{
Joerg Sonnenbergere77b0422013-10-20 17:36:05 +0000332#ifndef LLDB_DISABLE_PYTHON
Greg Claytonef8180a2013-10-15 00:14:28 +0000333 ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
334 Error error;
335 lldb::ScriptInterpreterObjectSP module_object_sp (interpreter->LoadPluginModule(target_definition_fspec, error));
336 if (module_object_sp)
337 {
338 lldb::ScriptInterpreterObjectSP target_definition_sp (interpreter->GetDynamicSettings(module_object_sp,
339 &GetTarget(),
340 "gdb-server-target-definition",
341 error));
342
343 PythonDictionary target_dict(target_definition_sp);
344
345 if (target_dict)
346 {
Greg Clayton312bcbe2013-10-17 01:10:23 +0000347 PythonDictionary host_info_dict (target_dict.GetItemForKey("host-info"));
348 if (host_info_dict)
349 {
350 ArchSpec host_arch (host_info_dict.GetItemForKeyAsString(PythonString("triple")));
351
352 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture()))
353 {
354 GetTarget().SetArchitecture(host_arch);
355 }
356
357 }
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000358 m_breakpoint_pc_offset = target_dict.GetItemForKeyAsInteger("breakpoint-pc-offset", 0);
359
Greg Clayton312bcbe2013-10-17 01:10:23 +0000360 if (m_register_info.SetRegisterInfo (target_dict, GetTarget().GetArchitecture().GetByteOrder()) > 0)
Greg Claytonef8180a2013-10-15 00:14:28 +0000361 {
362 return true;
363 }
364 }
365 }
Joerg Sonnenbergere77b0422013-10-20 17:36:05 +0000366#endif
Greg Claytonef8180a2013-10-15 00:14:28 +0000367 return false;
368}
369
370
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000371void
Greg Clayton513c26c2011-01-29 07:10:55 +0000372ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000373{
Greg Clayton513c26c2011-01-29 07:10:55 +0000374 if (!force && m_register_info.GetNumRegisters() > 0)
375 return;
376
377 char packet[128];
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000378 m_register_info.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000379 uint32_t reg_offset = 0;
380 uint32_t reg_num = 0;
Greg Clayton23f59502012-07-17 03:23:13 +0000381 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Greg Clayton576d8832011-03-22 04:00:09 +0000382 response_type == StringExtractorGDBRemote::eResponse;
383 ++reg_num)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000384 {
Greg Clayton513c26c2011-01-29 07:10:55 +0000385 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
Andy Gibbsa297a972013-06-19 19:04:53 +0000386 assert (packet_len < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000387 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000388 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000389 {
Greg Clayton576d8832011-03-22 04:00:09 +0000390 response_type = response.GetResponseType();
391 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000392 {
393 std::string name;
394 std::string value;
395 ConstString reg_name;
396 ConstString alt_name;
397 ConstString set_name;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000398 std::vector<uint32_t> value_regs;
399 std::vector<uint32_t> invalidate_regs;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000400 RegisterInfo reg_info = { NULL, // Name
401 NULL, // Alt name
402 0, // byte size
403 reg_offset, // offset
404 eEncodingUint, // encoding
405 eFormatHex, // formate
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000406 {
407 LLDB_INVALID_REGNUM, // GCC reg num
408 LLDB_INVALID_REGNUM, // DWARF reg num
409 LLDB_INVALID_REGNUM, // generic reg num
Jason Molendafbcb7f22010-09-10 07:49:16 +0000410 reg_num, // GDB reg num
411 reg_num // native register number
Greg Clayton435d85a2012-02-29 19:27:27 +0000412 },
413 NULL,
414 NULL
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000415 };
416
417 while (response.GetNameColonValue(name, value))
418 {
419 if (name.compare("name") == 0)
420 {
421 reg_name.SetCString(value.c_str());
422 }
423 else if (name.compare("alt-name") == 0)
424 {
425 alt_name.SetCString(value.c_str());
426 }
427 else if (name.compare("bitsize") == 0)
428 {
429 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
430 }
431 else if (name.compare("offset") == 0)
432 {
433 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda743e86a2010-06-11 23:44:18 +0000434 if (reg_offset != offset)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000435 {
436 reg_offset = offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000437 }
438 }
439 else if (name.compare("encoding") == 0)
440 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000441 const Encoding encoding = Args::StringToEncoding (value.c_str());
442 if (encoding != eEncodingInvalid)
443 reg_info.encoding = encoding;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000444 }
445 else if (name.compare("format") == 0)
446 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000447 Format format = eFormatInvalid;
448 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
449 reg_info.format = format;
450 else if (value.compare("binary") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000451 reg_info.format = eFormatBinary;
452 else if (value.compare("decimal") == 0)
453 reg_info.format = eFormatDecimal;
454 else if (value.compare("hex") == 0)
455 reg_info.format = eFormatHex;
456 else if (value.compare("float") == 0)
457 reg_info.format = eFormatFloat;
458 else if (value.compare("vector-sint8") == 0)
459 reg_info.format = eFormatVectorOfSInt8;
460 else if (value.compare("vector-uint8") == 0)
461 reg_info.format = eFormatVectorOfUInt8;
462 else if (value.compare("vector-sint16") == 0)
463 reg_info.format = eFormatVectorOfSInt16;
464 else if (value.compare("vector-uint16") == 0)
465 reg_info.format = eFormatVectorOfUInt16;
466 else if (value.compare("vector-sint32") == 0)
467 reg_info.format = eFormatVectorOfSInt32;
468 else if (value.compare("vector-uint32") == 0)
469 reg_info.format = eFormatVectorOfUInt32;
470 else if (value.compare("vector-float32") == 0)
471 reg_info.format = eFormatVectorOfFloat32;
472 else if (value.compare("vector-uint128") == 0)
473 reg_info.format = eFormatVectorOfUInt128;
474 }
475 else if (name.compare("set") == 0)
476 {
477 set_name.SetCString(value.c_str());
478 }
479 else if (name.compare("gcc") == 0)
480 {
481 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
482 }
483 else if (name.compare("dwarf") == 0)
484 {
485 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
486 }
487 else if (name.compare("generic") == 0)
488 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000489 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000490 }
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000491 else if (name.compare("container-regs") == 0)
492 {
493 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
494 value_pair.second = value;
495 do
496 {
497 value_pair = value_pair.second.split(',');
498 if (!value_pair.first.empty())
499 {
Greg Clayton0ba20242013-01-21 23:32:42 +0000500 uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
501 if (reg != LLDB_INVALID_REGNUM)
502 value_regs.push_back (reg);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000503 }
504 } while (!value_pair.second.empty());
505 }
506 else if (name.compare("invalidate-regs") == 0)
507 {
508 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
509 value_pair.second = value;
510 do
511 {
512 value_pair = value_pair.second.split(',');
513 if (!value_pair.first.empty())
514 {
Greg Clayton0ba20242013-01-21 23:32:42 +0000515 uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
516 if (reg != LLDB_INVALID_REGNUM)
517 invalidate_regs.push_back (reg);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000518 }
519 } while (!value_pair.second.empty());
520 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000521 }
522
Jason Molenda743e86a2010-06-11 23:44:18 +0000523 reg_info.byte_offset = reg_offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000524 assert (reg_info.byte_size != 0);
525 reg_offset += reg_info.byte_size;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000526 if (!value_regs.empty())
527 {
528 value_regs.push_back(LLDB_INVALID_REGNUM);
529 reg_info.value_regs = value_regs.data();
530 }
531 if (!invalidate_regs.empty())
532 {
533 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
534 reg_info.invalidate_regs = invalidate_regs.data();
535 }
536
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000537 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
538 }
Todd Fiala1a634402014-01-08 07:52:40 +0000539 else
540 {
541 break; // ensure exit before reg_num is incremented
542 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000543 }
544 else
545 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000546 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000547 }
548 }
549
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000550 // Check if qHostInfo specified a specific packet timeout for this connection.
551 // If so then lets update our setting so the user knows what the timeout is
552 // and can see it.
553 const uint32_t host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
554 if (host_packet_timeout)
555 {
556 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout);
557 }
558
559
Greg Claytonef8180a2013-10-15 00:14:28 +0000560 if (reg_num == 0)
561 {
562 FileSpec target_definition_fspec = GetGlobalPluginProperties()->GetTargetDefinitionFile ();
Greg Clayton312bcbe2013-10-17 01:10:23 +0000563
564 if (target_definition_fspec)
Greg Claytonef8180a2013-10-15 00:14:28 +0000565 {
Greg Clayton312bcbe2013-10-17 01:10:23 +0000566 // See if we can get register definitions from a python file
567 if (ParsePythonTargetDefinition (target_definition_fspec))
568 return;
Greg Claytonef8180a2013-10-15 00:14:28 +0000569 }
570 }
571
Johnny Chen2fa9de12012-05-14 18:44:23 +0000572 // We didn't get anything if the accumulated reg_num is zero. See if we are
573 // debugging ARM and fill with a hard coded register set until we can get an
574 // updated debugserver down on the devices.
575 // On the other hand, if the accumulated reg_num is positive, see if we can
576 // add composite registers to the existing primordial ones.
577 bool from_scratch = (reg_num == 0);
578
579 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000580 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
581 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
582
583 // Use the process' architecture instead of the host arch, if available
584 ArchSpec remote_arch;
585 if (remote_process_arch.IsValid ())
586 remote_arch = remote_process_arch;
587 else
588 remote_arch = remote_host_arch;
589
Johnny Chen2fa9de12012-05-14 18:44:23 +0000590 if (!target_arch.IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000591 {
Johnny Chen2fa9de12012-05-14 18:44:23 +0000592 if (remote_arch.IsValid()
593 && remote_arch.GetMachine() == llvm::Triple::arm
594 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
595 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000596 }
Johnny Chen2fa9de12012-05-14 18:44:23 +0000597 else if (target_arch.GetMachine() == llvm::Triple::arm)
598 {
599 m_register_info.HardcodeARMRegisters(from_scratch);
600 }
601
602 // At this point, we can finalize our register info.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000603 m_register_info.Finalize ();
604}
605
606Error
607ProcessGDBRemote::WillLaunch (Module* module)
608{
609 return WillLaunchOrAttach ();
610}
611
612Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000613ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000614{
615 return WillLaunchOrAttach ();
616}
617
618Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000619ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000620{
621 return WillLaunchOrAttach ();
622}
623
624Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000625ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +0000626{
627 Error error (WillLaunchOrAttach ());
628
629 if (error.Fail())
630 return error;
631
Greg Clayton2289fa42011-04-30 01:09:13 +0000632 error = ConnectToDebugserver (remote_url);
Greg Claytonb766a732011-02-04 01:58:07 +0000633
634 if (error.Fail())
635 return error;
636 StartAsyncThread ();
637
Greg Claytonc574ede2011-03-10 02:26:48 +0000638 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonb766a732011-02-04 01:58:07 +0000639 if (pid == LLDB_INVALID_PROCESS_ID)
640 {
641 // We don't have a valid process ID, so note that we are connected
642 // and could now request to launch or attach, or get remote process
643 // listings...
644 SetPrivateState (eStateConnected);
645 }
646 else
647 {
648 // We have a valid process
649 SetID (pid);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000650 GetThreadList();
Greg Clayton3dedae12013-12-06 21:45:27 +0000651 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false) == GDBRemoteCommunication::PacketResult::Success)
Greg Claytonb766a732011-02-04 01:58:07 +0000652 {
Jason Molendac62bd7b2013-12-21 05:20:36 +0000653 if (!m_target.GetArchitecture().IsValid())
654 {
655 if (m_gdb_comm.GetProcessArchitecture().IsValid())
656 {
657 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
658 }
659 else
660 {
661 m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
662 }
Carlo Kok74389122013-10-14 07:09:13 +0000663 }
664
Greg Claytondd0e5a52011-06-02 22:22:38 +0000665 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytonb766a732011-02-04 01:58:07 +0000666 if (state == eStateStopped)
667 {
668 SetPrivateState (state);
669 }
670 else
Daniel Malead01b2952012-11-29 21:49:15 +0000671 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 +0000672 }
673 else
Daniel Malead01b2952012-11-29 21:49:15 +0000674 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 +0000675 }
Jason Molenda16d127c2012-05-03 22:37:30 +0000676
677 if (error.Success()
678 && !GetTarget().GetArchitecture().IsValid()
679 && m_gdb_comm.GetHostArchitecture().IsValid())
680 {
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000681 // Prefer the *process'* architecture over that of the *host*, if available.
682 if (m_gdb_comm.GetProcessArchitecture().IsValid())
683 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
684 else
685 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molenda16d127c2012-05-03 22:37:30 +0000686 }
687
Greg Claytonb766a732011-02-04 01:58:07 +0000688 return error;
689}
690
691Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000692ProcessGDBRemote::WillLaunchOrAttach ()
693{
694 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000695 m_stdio_communication.Clear ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000696 return error;
697}
698
699//----------------------------------------------------------------------
700// Process Control
701//----------------------------------------------------------------------
702Error
Jean-Daniel Dupas7782de92013-12-09 22:52:50 +0000703ProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000704{
Greg Clayton4957bf62010-09-30 21:49:03 +0000705 Error error;
Greg Clayton982c9762011-11-03 21:22:33 +0000706
707 uint32_t launch_flags = launch_info.GetFlags().Get();
708 const char *stdin_path = NULL;
709 const char *stdout_path = NULL;
710 const char *stderr_path = NULL;
711 const char *working_dir = launch_info.GetWorkingDirectory();
712
713 const ProcessLaunchInfo::FileAction *file_action;
714 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
715 if (file_action)
716 {
717 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
718 stdin_path = file_action->GetPath();
719 }
720 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
721 if (file_action)
722 {
723 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
724 stdout_path = file_action->GetPath();
725 }
726 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
727 if (file_action)
728 {
729 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
730 stderr_path = file_action->GetPath();
731 }
732
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000733 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
734 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
735 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton5160ce52013-03-27 23:08:40 +0000736 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000737
Greg Clayton982c9762011-11-03 21:22:33 +0000738 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000739 if (object_file)
740 {
Greg Clayton71337622011-02-24 22:24:29 +0000741 // Make sure we aren't already connected?
742 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000743 {
Greg Clayton91a9b2472013-12-04 19:19:12 +0000744 error = LaunchAndConnectToDebugserver (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000745 }
746
747 if (error.Success())
748 {
749 lldb_utility::PseudoTerminal pty;
750 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000751
752 // If the debugserver is local and we aren't disabling STDIO, lets use
753 // a pseudo terminal to instead of relying on the 'O' packets for stdio
754 // since 'O' packets can really slow down debugging if the inferior
755 // does a lot of output.
Greg Claytonf58c2692011-06-24 22:32:10 +0000756 PlatformSP platform_sp (m_target.GetPlatform());
757 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Clayton71337622011-02-24 22:24:29 +0000758 {
759 const char *slave_name = NULL;
760 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000761 {
Greg Clayton71337622011-02-24 22:24:29 +0000762 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
763 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000764 }
Greg Clayton71337622011-02-24 22:24:29 +0000765 if (stdin_path == NULL)
766 stdin_path = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000767
Greg Clayton71337622011-02-24 22:24:29 +0000768 if (stdout_path == NULL)
769 stdout_path = slave_name;
770
771 if (stderr_path == NULL)
772 stderr_path = slave_name;
773 }
774
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000775 // Set STDIN to /dev/null if we want STDIO disabled or if either
776 // STDOUT or STDERR have been set to something and STDIN hasn't
777 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000778 stdin_path = "/dev/null";
779
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000780 // Set STDOUT to /dev/null if we want STDIO disabled or if either
781 // STDIN or STDERR have been set to something and STDOUT hasn't
782 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000783 stdout_path = "/dev/null";
784
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000785 // Set STDERR to /dev/null if we want STDIO disabled or if either
786 // STDIN or STDOUT have been set to something and STDERR hasn't
787 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000788 stderr_path = "/dev/null";
789
790 if (stdin_path)
791 m_gdb_comm.SetSTDIN (stdin_path);
792 if (stdout_path)
793 m_gdb_comm.SetSTDOUT (stdout_path);
794 if (stderr_path)
795 m_gdb_comm.SetSTDERR (stderr_path);
796
797 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
798
Greg Claytonc4103b32011-05-08 04:53:50 +0000799 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Clayton71337622011-02-24 22:24:29 +0000800
801 if (working_dir && working_dir[0])
802 {
803 m_gdb_comm.SetWorkingDir (working_dir);
804 }
805
806 // Send the environment and the program + arguments after we connect
Greg Clayton982c9762011-11-03 21:22:33 +0000807 const Args &environment = launch_info.GetEnvironmentEntries();
808 if (environment.GetArgumentCount())
Greg Clayton71337622011-02-24 22:24:29 +0000809 {
Greg Clayton982c9762011-11-03 21:22:33 +0000810 size_t num_environment_entries = environment.GetArgumentCount();
811 for (size_t i=0; i<num_environment_entries; ++i)
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000812 {
Greg Clayton982c9762011-11-03 21:22:33 +0000813 const char *env_entry = environment.GetArgumentAtIndex(i);
814 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Clayton71337622011-02-24 22:24:29 +0000815 break;
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000816 }
Greg Clayton71337622011-02-24 22:24:29 +0000817 }
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000818
Greg Claytonc574ede2011-03-10 02:26:48 +0000819 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Claytonfbb76342013-11-20 21:07:01 +0000820 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000821 if (arg_packet_err == 0)
822 {
823 std::string error_str;
Greg Claytonc574ede2011-03-10 02:26:48 +0000824 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000825 {
Greg Claytonc574ede2011-03-10 02:26:48 +0000826 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000827 }
828 else
829 {
Greg Clayton71337622011-02-24 22:24:29 +0000830 error.SetErrorString (error_str.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000831 }
Greg Clayton71337622011-02-24 22:24:29 +0000832 }
833 else
834 {
Greg Clayton86edbf42011-10-26 00:56:27 +0000835 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Clayton71337622011-02-24 22:24:29 +0000836 }
Greg Clayton8b45bee2011-08-10 22:05:39 +0000837
838 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000839
Greg Clayton71337622011-02-24 22:24:29 +0000840 if (GetID() == LLDB_INVALID_PROCESS_ID)
841 {
Johnny Chen4c1e9202011-08-09 18:56:45 +0000842 if (log)
843 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton71337622011-02-24 22:24:29 +0000844 KillDebugserverProcess ();
845 return error;
846 }
847
Greg Clayton3dedae12013-12-06 21:45:27 +0000848 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton71337622011-02-24 22:24:29 +0000849 {
Jason Molendac62bd7b2013-12-21 05:20:36 +0000850 if (!m_target.GetArchitecture().IsValid())
851 {
852 if (m_gdb_comm.GetProcessArchitecture().IsValid())
853 {
854 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
855 }
856 else
857 {
858 m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
859 }
Carlo Kok74389122013-10-14 07:09:13 +0000860 }
861
Greg Claytondd0e5a52011-06-02 22:22:38 +0000862 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Clayton71337622011-02-24 22:24:29 +0000863
864 if (!disable_stdio)
865 {
866 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Claytonee95ed52011-11-17 22:14:31 +0000867 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Clayton71337622011-02-24 22:24:29 +0000868 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000869 }
870 }
Greg Claytonc235ac72011-08-09 05:20:29 +0000871 else
872 {
Johnny Chen4c1e9202011-08-09 18:56:45 +0000873 if (log)
874 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytonc235ac72011-08-09 05:20:29 +0000875 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000876 }
877 else
878 {
879 // Set our user ID to an invalid process ID.
880 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton982c9762011-11-03 21:22:33 +0000881 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
882 exe_module->GetFileSpec().GetFilename().AsCString(),
883 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000884 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000885 return error;
Greg Clayton4957bf62010-09-30 21:49:03 +0000886
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000887}
888
889
890Error
Greg Claytonb766a732011-02-04 01:58:07 +0000891ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000892{
893 Error error;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000894 // Only connect if we have a valid connect URL
895
896 if (connect_url && connect_url[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000897 {
Greg Clayton00fe87b2013-12-05 22:58:22 +0000898 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
899 if (conn_ap.get())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000900 {
Greg Clayton00fe87b2013-12-05 22:58:22 +0000901 const uint32_t max_retry_count = 50;
902 uint32_t retry_count = 0;
903 while (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000904 {
Greg Clayton00fe87b2013-12-05 22:58:22 +0000905 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
906 {
907 m_gdb_comm.SetConnection (conn_ap.release());
908 break;
909 }
910 else if (error.WasInterrupted())
911 {
912 // If we were interrupted, don't keep retrying.
913 break;
914 }
915
916 retry_count++;
917
918 if (retry_count >= max_retry_count)
919 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000920
Greg Clayton00fe87b2013-12-05 22:58:22 +0000921 usleep (100000);
922 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000923 }
924 }
925
926 if (!m_gdb_comm.IsConnected())
927 {
928 if (error.Success())
929 error.SetErrorString("not connected to remote gdb server");
930 return error;
931 }
932
Greg Clayton32e0a752011-03-30 18:16:51 +0000933 // We always seem to be able to open a connection to a local port
934 // so we need to make sure we can then send data to it. If we can't
935 // then we aren't actually connected to anything, so try and do the
936 // handshake with the remote GDB server and make sure that goes
937 // alright.
Greg Claytonfb909312013-11-23 01:58:15 +0000938 if (!m_gdb_comm.HandshakeWithServer (&error))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000939 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000940 m_gdb_comm.Disconnect();
941 if (error.Success())
942 error.SetErrorString("not connected to remote gdb server");
943 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000944 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000945 m_gdb_comm.GetThreadSuffixSupported ();
Greg Clayton44633992012-04-10 03:22:03 +0000946 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +0000947 m_gdb_comm.GetHostInfo ();
948 m_gdb_comm.GetVContSupported ('c');
Jim Inghamcd16df92012-07-20 21:37:13 +0000949 m_gdb_comm.GetVAttachOrWaitSupported();
Jim Ingham03afad82012-07-02 05:40:07 +0000950
951 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
952 for (size_t idx = 0; idx < num_cmds; idx++)
953 {
954 StringExtractorGDBRemote response;
Jim Ingham03afad82012-07-02 05:40:07 +0000955 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
956 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000957 return error;
958}
959
960void
961ProcessGDBRemote::DidLaunchOrAttach ()
962{
Greg Clayton5160ce52013-03-27 23:08:40 +0000963 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +0000964 if (log)
965 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton93d3c8332011-02-16 04:46:07 +0000966 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000967 {
Greg Clayton513c26c2011-01-29 07:10:55 +0000968 BuildDynamicRegisterInfo (false);
Greg Clayton3af9ea52010-11-18 05:57:03 +0000969
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000970 // See if the GDB server supports the qHostInfo information
Greg Clayton0d0c12a2011-02-09 03:09:55 +0000971
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000972 ArchSpec gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
973
974 // See if the GDB server supports the qProcessInfo packet, if so
975 // prefer that over the Host information as it will be more specific
976 // to our process.
977
978 if (m_gdb_comm.GetProcessArchitecture().IsValid())
979 gdb_remote_arch = m_gdb_comm.GetProcessArchitecture();
980
Greg Claytond314e812011-03-23 00:09:55 +0000981 if (gdb_remote_arch.IsValid())
Greg Clayton0d0c12a2011-02-09 03:09:55 +0000982 {
Greg Claytond314e812011-03-23 00:09:55 +0000983 ArchSpec &target_arch = GetTarget().GetArchitecture();
984
985 if (target_arch.IsValid())
986 {
987 // If the remote host is ARM and we have apple as the vendor, then
988 // ARM executables and shared libraries can have mixed ARM architectures.
989 // You can have an armv6 executable, and if the host is armv7, then the
990 // system will load the best possible architecture for all shared libraries
991 // it has, so we really need to take the remote host architecture as our
992 // defacto architecture in this case.
993
994 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
995 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
996 {
997 target_arch = gdb_remote_arch;
998 }
999 else
1000 {
1001 // Fill in what is missing in the triple
1002 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
1003 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton70b57652011-05-15 01:25:55 +00001004 if (target_triple.getVendorName().size() == 0)
1005 {
Greg Claytond314e812011-03-23 00:09:55 +00001006 target_triple.setVendor (remote_triple.getVendor());
1007
Greg Clayton70b57652011-05-15 01:25:55 +00001008 if (target_triple.getOSName().size() == 0)
1009 {
1010 target_triple.setOS (remote_triple.getOS());
Greg Claytond314e812011-03-23 00:09:55 +00001011
Greg Clayton70b57652011-05-15 01:25:55 +00001012 if (target_triple.getEnvironmentName().size() == 0)
1013 target_triple.setEnvironment (remote_triple.getEnvironment());
1014 }
1015 }
Greg Claytond314e812011-03-23 00:09:55 +00001016 }
1017 }
1018 else
1019 {
1020 // The target doesn't have a valid architecture yet, set it from
1021 // the architecture we got from the remote GDB server
1022 target_arch = gdb_remote_arch;
1023 }
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001024 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001025 }
1026}
1027
1028void
1029ProcessGDBRemote::DidLaunch ()
1030{
1031 DidLaunchOrAttach ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001032}
1033
1034Error
Greg Claytonc982c762010-07-09 20:39:50 +00001035ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001036{
Han Ming Ong84647042012-02-25 01:07:38 +00001037 ProcessAttachInfo attach_info;
1038 return DoAttachToProcessWithID(attach_pid, attach_info);
1039}
1040
1041Error
1042ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1043{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001044 Error error;
1045 // Clear out and clean up from any current state
1046 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001047 if (attach_pid != LLDB_INVALID_PROCESS_ID)
1048 {
Greg Clayton71337622011-02-24 22:24:29 +00001049 // Make sure we aren't already connected?
1050 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001051 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001052 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001053
1054 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001055 {
Greg Clayton71337622011-02-24 22:24:29 +00001056 const char *error_string = error.AsCString();
1057 if (error_string == NULL)
1058 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1059
1060 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001061 }
Greg Clayton71337622011-02-24 22:24:29 +00001062 }
1063
1064 if (error.Success())
1065 {
1066 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001067 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Greg Clayton3b608422011-11-19 02:11:30 +00001068 SetID (attach_pid);
Greg Clayton71337622011-02-24 22:24:29 +00001069 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001070 }
1071 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001072 return error;
1073}
1074
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001075Error
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001076ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001077{
1078 Error error;
1079 // Clear out and clean up from any current state
1080 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001081
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001082 if (process_name && process_name[0])
1083 {
Greg Clayton71337622011-02-24 22:24:29 +00001084 // Make sure we aren't already connected?
1085 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001086 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001087 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001088
Greg Clayton71337622011-02-24 22:24:29 +00001089 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001090 {
Greg Clayton71337622011-02-24 22:24:29 +00001091 const char *error_string = error.AsCString();
1092 if (error_string == NULL)
1093 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001094
Greg Clayton71337622011-02-24 22:24:29 +00001095 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001096 }
Greg Clayton71337622011-02-24 22:24:29 +00001097 }
1098
1099 if (error.Success())
1100 {
1101 StreamString packet;
1102
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001103 if (attach_info.GetWaitForLaunch())
Jim Inghamcd16df92012-07-20 21:37:13 +00001104 {
1105 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1106 {
1107 packet.PutCString ("vAttachWait");
1108 }
1109 else
1110 {
1111 if (attach_info.GetIgnoreExisting())
1112 packet.PutCString("vAttachWait");
1113 else
1114 packet.PutCString ("vAttachOrWait");
1115 }
1116 }
Greg Clayton71337622011-02-24 22:24:29 +00001117 else
1118 packet.PutCString("vAttachName");
1119 packet.PutChar(';');
1120 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1121
1122 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1123
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001124 }
1125 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001126 return error;
1127}
1128
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001129
Greg Claytonfbb76342013-11-20 21:07:01 +00001130bool
1131ProcessGDBRemote::SetExitStatus (int exit_status, const char *cstr)
1132{
1133 m_gdb_comm.Disconnect();
1134 return Process::SetExitStatus (exit_status, cstr);
1135}
1136
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001137void
1138ProcessGDBRemote::DidAttach ()
1139{
Greg Claytonb766a732011-02-04 01:58:07 +00001140 DidLaunchOrAttach ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001141}
1142
Greg Clayton90ba8112012-12-05 00:16:59 +00001143
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001144Error
1145ProcessGDBRemote::WillResume ()
1146{
Greg Clayton71fc2a32011-02-12 06:28:37 +00001147 m_continue_c_tids.clear();
1148 m_continue_C_tids.clear();
1149 m_continue_s_tids.clear();
1150 m_continue_S_tids.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001151 return Error();
1152}
1153
1154Error
1155ProcessGDBRemote::DoResume ()
1156{
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001157 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001158 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001159 if (log)
1160 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytone5219662010-12-03 06:02:24 +00001161
1162 Listener listener ("gdb-remote.resume-packet-sent");
1163 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1164 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00001165 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1166
Greg Claytond1d06e42013-04-20 00:27:58 +00001167 const size_t num_threads = GetThreadList().GetSize();
1168
Greg Clayton71fc2a32011-02-12 06:28:37 +00001169 StreamString continue_packet;
1170 bool continue_packet_error = false;
1171 if (m_gdb_comm.HasAnyVContSupport ())
1172 {
Greg Claytone98008c2014-02-13 23:34:38 +00001173 if (m_continue_c_tids.size() == num_threads ||
1174 (m_continue_c_tids.empty() &&
1175 m_continue_C_tids.empty() &&
1176 m_continue_s_tids.empty() &&
1177 m_continue_S_tids.empty()))
Greg Clayton71fc2a32011-02-12 06:28:37 +00001178 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001179 // All threads are continuing, just send a "c" packet
1180 continue_packet.PutCString ("c");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001181 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001182 else
1183 {
1184 continue_packet.PutCString ("vCont");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001185
Greg Claytond1d06e42013-04-20 00:27:58 +00001186 if (!m_continue_c_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001187 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001188 if (m_gdb_comm.GetVContSupported ('c'))
1189 {
1190 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)
1191 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1192 }
1193 else
1194 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001195 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001196
1197 if (!continue_packet_error && !m_continue_C_tids.empty())
1198 {
1199 if (m_gdb_comm.GetVContSupported ('C'))
1200 {
1201 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)
1202 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1203 }
1204 else
1205 continue_packet_error = true;
1206 }
Greg Claytone5219662010-12-03 06:02:24 +00001207
Greg Claytond1d06e42013-04-20 00:27:58 +00001208 if (!continue_packet_error && !m_continue_s_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001209 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001210 if (m_gdb_comm.GetVContSupported ('s'))
1211 {
1212 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)
1213 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1214 }
1215 else
1216 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001217 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001218
1219 if (!continue_packet_error && !m_continue_S_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001220 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001221 if (m_gdb_comm.GetVContSupported ('S'))
1222 {
1223 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)
1224 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1225 }
1226 else
1227 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001228 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001229
1230 if (continue_packet_error)
1231 continue_packet.GetString().clear();
Greg Clayton71fc2a32011-02-12 06:28:37 +00001232 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001233 }
1234 else
1235 continue_packet_error = true;
1236
1237 if (continue_packet_error)
1238 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001239 // Either no vCont support, or we tried to use part of the vCont
1240 // packet that wasn't supported by the remote GDB server.
1241 // We need to try and make a simple packet that can do our continue
Greg Clayton71fc2a32011-02-12 06:28:37 +00001242 const size_t num_continue_c_tids = m_continue_c_tids.size();
1243 const size_t num_continue_C_tids = m_continue_C_tids.size();
1244 const size_t num_continue_s_tids = m_continue_s_tids.size();
1245 const size_t num_continue_S_tids = m_continue_S_tids.size();
1246 if (num_continue_c_tids > 0)
1247 {
1248 if (num_continue_c_tids == num_threads)
1249 {
1250 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001251 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001252 continue_packet.PutChar ('c');
1253 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001254 }
1255 else if (num_continue_c_tids == 1 &&
1256 num_continue_C_tids == 0 &&
1257 num_continue_s_tids == 0 &&
1258 num_continue_S_tids == 0 )
1259 {
1260 // Only one thread is continuing
Greg Clayton8b82f082011-04-12 05:54:46 +00001261 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001262 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001263 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001264 }
1265 }
1266
Greg Clayton0c74e782011-06-24 03:21:43 +00001267 if (continue_packet_error && num_continue_C_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001268 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001269 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1270 num_continue_C_tids > 0 &&
1271 num_continue_s_tids == 0 &&
1272 num_continue_S_tids == 0 )
Greg Clayton71fc2a32011-02-12 06:28:37 +00001273 {
1274 const int continue_signo = m_continue_C_tids.front().second;
Greg Clayton0c74e782011-06-24 03:21:43 +00001275 // Only one thread is continuing
Greg Clayton71fc2a32011-02-12 06:28:37 +00001276 if (num_continue_C_tids > 1)
1277 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001278 // More that one thread with a signal, yet we don't have
1279 // vCont support and we are being asked to resume each
1280 // thread with a signal, we need to make sure they are
1281 // all the same signal, or we can't issue the continue
1282 // accurately with the current support...
1283 if (num_continue_C_tids > 1)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001284 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001285 continue_packet_error = false;
1286 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1287 {
1288 if (m_continue_C_tids[i].second != continue_signo)
1289 continue_packet_error = true;
1290 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001291 }
Greg Clayton0c74e782011-06-24 03:21:43 +00001292 if (!continue_packet_error)
1293 m_gdb_comm.SetCurrentThreadForRun (-1);
1294 }
1295 else
1296 {
1297 // Set the continue thread ID
1298 continue_packet_error = false;
1299 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001300 }
1301 if (!continue_packet_error)
1302 {
1303 // Add threads continuing with the same signo...
Greg Clayton71fc2a32011-02-12 06:28:37 +00001304 continue_packet.Printf("C%2.2x", continue_signo);
1305 }
1306 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001307 }
1308
Greg Clayton0c74e782011-06-24 03:21:43 +00001309 if (continue_packet_error && num_continue_s_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001310 {
1311 if (num_continue_s_tids == num_threads)
1312 {
1313 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001314 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001315 continue_packet.PutChar ('s');
1316 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001317 }
1318 else if (num_continue_c_tids == 0 &&
1319 num_continue_C_tids == 0 &&
1320 num_continue_s_tids == 1 &&
1321 num_continue_S_tids == 0 )
1322 {
1323 // Only one thread is stepping
Greg Clayton8b82f082011-04-12 05:54:46 +00001324 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001325 continue_packet.PutChar ('s');
Greg Clayton0c74e782011-06-24 03:21:43 +00001326 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001327 }
1328 }
1329
1330 if (!continue_packet_error && num_continue_S_tids > 0)
1331 {
1332 if (num_continue_S_tids == num_threads)
1333 {
1334 const int step_signo = m_continue_S_tids.front().second;
1335 // Are all threads trying to step with the same signal?
Greg Clayton0c74e782011-06-24 03:21:43 +00001336 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001337 if (num_continue_S_tids > 1)
1338 {
1339 for (size_t i=1; i<num_threads; ++i)
1340 {
1341 if (m_continue_S_tids[i].second != step_signo)
1342 continue_packet_error = true;
1343 }
1344 }
1345 if (!continue_packet_error)
1346 {
1347 // Add threads stepping with the same signo...
Greg Clayton8b82f082011-04-12 05:54:46 +00001348 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001349 continue_packet.Printf("S%2.2x", step_signo);
1350 }
1351 }
1352 else if (num_continue_c_tids == 0 &&
1353 num_continue_C_tids == 0 &&
1354 num_continue_s_tids == 0 &&
1355 num_continue_S_tids == 1 )
1356 {
1357 // Only one thread is stepping with signal
Greg Clayton8b82f082011-04-12 05:54:46 +00001358 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001359 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Clayton0c74e782011-06-24 03:21:43 +00001360 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001361 }
1362 }
1363 }
1364
1365 if (continue_packet_error)
1366 {
1367 error.SetErrorString ("can't make continue packet for this resume");
1368 }
1369 else
1370 {
1371 EventSP event_sp;
1372 TimeValue timeout;
1373 timeout = TimeValue::Now();
1374 timeout.OffsetWithSeconds (5);
Jim Inghamb1e2e842012-04-12 18:49:31 +00001375 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1376 {
1377 error.SetErrorString ("Trying to resume but the async thread is dead.");
1378 if (log)
1379 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1380 return error;
1381 }
1382
Greg Clayton71fc2a32011-02-12 06:28:37 +00001383 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1384
1385 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Inghamb1e2e842012-04-12 18:49:31 +00001386 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001387 error.SetErrorString("Resume timed out.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00001388 if (log)
1389 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1390 }
1391 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1392 {
1393 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1394 if (log)
1395 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1396 return error;
1397 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001398 }
Greg Claytone5219662010-12-03 06:02:24 +00001399 }
1400
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001401 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001402}
1403
Greg Clayton9e920902012-04-10 02:25:43 +00001404void
1405ProcessGDBRemote::ClearThreadIDList ()
1406{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001407 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001408 m_thread_ids.clear();
1409}
1410
1411bool
1412ProcessGDBRemote::UpdateThreadIDList ()
1413{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001414 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001415 bool sequence_mutex_unavailable = false;
1416 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1417 if (sequence_mutex_unavailable)
1418 {
Greg Clayton9e920902012-04-10 02:25:43 +00001419 return false; // We just didn't get the list
1420 }
1421 return true;
1422}
1423
Greg Clayton9fc13552012-04-10 00:18:59 +00001424bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001425ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001426{
1427 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +00001428 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Clayton73b472d2010-10-27 03:32:59 +00001429 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +00001430 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton9e920902012-04-10 02:25:43 +00001431
1432 size_t num_thread_ids = m_thread_ids.size();
1433 // The "m_thread_ids" thread ID list should always be updated after each stop
1434 // reply packet, but in case it isn't, update it here.
1435 if (num_thread_ids == 0)
1436 {
1437 if (!UpdateThreadIDList ())
1438 return false;
1439 num_thread_ids = m_thread_ids.size();
1440 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001441
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001442 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001443 if (num_thread_ids > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001444 {
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001445 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001446 {
Greg Clayton9e920902012-04-10 02:25:43 +00001447 tid_t tid = m_thread_ids[i];
Greg Clayton160c9d82013-05-01 21:54:04 +00001448 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001449 if (!thread_sp)
Jim Inghamdee1bc92013-06-22 00:27:45 +00001450 {
Jim Ingham4f465cf2012-10-10 18:32:14 +00001451 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001452 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1453 log->Printf(
1454 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1455 __FUNCTION__,
1456 thread_sp.get(),
1457 thread_sp->GetID());
1458 }
1459 else
1460 {
1461 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1462 log->Printf(
1463 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
1464 __FUNCTION__,
1465 thread_sp.get(),
1466 thread_sp->GetID());
1467 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001468 new_thread_list.AddThread(thread_sp);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001469 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001470 }
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001471
1472 // Whatever that is left in old_thread_list_copy are not
1473 // present in new_thread_list. Remove non-existent threads from internal id table.
1474 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1475 for (size_t i=0; i<old_num_thread_ids; i++)
1476 {
1477 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1478 if (old_thread_sp)
1479 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001480 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001481 m_thread_id_to_index_id_map.erase(old_thread_id);
1482 }
1483 }
1484
Greg Clayton9fc13552012-04-10 00:18:59 +00001485 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001486}
1487
1488
1489StateType
1490ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1491{
Greg Claytondd0e5a52011-06-02 22:22:38 +00001492 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001493 const char stop_type = stop_packet.GetChar();
1494 switch (stop_type)
1495 {
1496 case 'T':
1497 case 'S':
1498 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00001499 // This is a bit of a hack, but is is required. If we did exec, we
1500 // need to clear our thread lists and also know to rebuild our dynamic
1501 // register info before we lookup and threads and populate the expedited
1502 // register values so we need to know this right away so we can cleanup
1503 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00001504 const uint32_t stop_id = GetStopID();
1505 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00001506 {
1507 // Our first stop, make sure we have a process ID, and also make
1508 // sure we know about our registers
1509 if (GetID() == LLDB_INVALID_PROCESS_ID)
1510 {
Greg Claytonc574ede2011-03-10 02:26:48 +00001511 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00001512 if (pid != LLDB_INVALID_PROCESS_ID)
1513 SetID (pid);
1514 }
1515 BuildDynamicRegisterInfo (true);
1516 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001517 // Stop with signal and thread info
1518 const uint8_t signo = stop_packet.GetHexU8();
1519 std::string name;
1520 std::string value;
1521 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00001522 std::string reason;
1523 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001524 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00001525 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001526 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001527 ThreadSP thread_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001528 ThreadGDBRemote *gdb_thread = NULL;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001529
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001530 while (stop_packet.GetNameColonValue(name, value))
1531 {
1532 if (name.compare("metype") == 0)
1533 {
1534 // exception type in big endian hex
1535 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1536 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001537 else if (name.compare("medata") == 0)
1538 {
1539 // exception data in big endian hex
1540 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1541 }
1542 else if (name.compare("thread") == 0)
1543 {
1544 // thread in big endian hex
Greg Clayton9e920902012-04-10 02:25:43 +00001545 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001546 // m_thread_list_real does have its own mutex, but we need to
1547 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1548 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1549 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1550 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
Greg Clayton160c9d82013-05-01 21:54:04 +00001551
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001552 if (!thread_sp)
Greg Claytond1d06e42013-04-20 00:27:58 +00001553 {
Greg Claytone576ab22011-02-15 00:19:15 +00001554 // Create the thread if we need to
Jim Ingham4f465cf2012-10-10 18:32:14 +00001555 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001556 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
1557 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1558 log->Printf ("ProcessGDBRemote::%s Adding new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1559 __FUNCTION__,
1560 thread_sp.get(),
1561 thread_sp->GetID());
1562
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001563 m_thread_list_real.AddThread(thread_sp);
Greg Claytone576ab22011-02-15 00:19:15 +00001564 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001565 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1566
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001567 }
Greg Clayton9e920902012-04-10 02:25:43 +00001568 else if (name.compare("threads") == 0)
1569 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001570 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001571 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00001572 // A comma separated list of all threads in the current
1573 // process that includes the thread for this stop reply
1574 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00001575 size_t comma_pos;
1576 lldb::tid_t tid;
1577 while ((comma_pos = value.find(',')) != std::string::npos)
1578 {
1579 value[comma_pos] = '\0';
1580 // thread in big endian hex
1581 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1582 if (tid != LLDB_INVALID_THREAD_ID)
1583 m_thread_ids.push_back (tid);
1584 value.erase(0, comma_pos + 1);
1585
1586 }
1587 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1588 if (tid != LLDB_INVALID_THREAD_ID)
1589 m_thread_ids.push_back (tid);
1590 }
Greg Claytonde9d0492011-01-08 03:17:57 +00001591 else if (name.compare("hexname") == 0)
1592 {
1593 StringExtractor name_extractor;
1594 // Swap "value" over into "name_extractor"
1595 name_extractor.GetStringRef().swap(value);
1596 // Now convert the HEX bytes into a string value
1597 name_extractor.GetHexByteString (value);
1598 thread_name.swap (value);
1599 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001600 else if (name.compare("name") == 0)
1601 {
1602 thread_name.swap (value);
1603 }
Greg Clayton6f35f5c2010-09-09 06:32:46 +00001604 else if (name.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001605 {
1606 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1607 }
Greg Claytona658fd22011-06-04 01:26:29 +00001608 else if (name.compare("reason") == 0)
1609 {
1610 reason.swap(value);
1611 }
1612 else if (name.compare("description") == 0)
1613 {
1614 StringExtractor desc_extractor;
1615 // Swap "value" over into "name_extractor"
1616 desc_extractor.GetStringRef().swap(value);
1617 // Now convert the HEX bytes into a string value
1618 desc_extractor.GetHexByteString (thread_name);
1619 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001620 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1621 {
1622 // We have a register number that contains an expedited
1623 // register value. Lets supply this register to our thread
1624 // so it won't have to go and read it.
Greg Clayton160c9d82013-05-01 21:54:04 +00001625 if (gdb_thread)
Greg Clayton3e06bd92011-01-09 21:07:35 +00001626 {
1627 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1628
1629 if (reg != UINT32_MAX)
1630 {
1631 StringExtractor reg_value_extractor;
1632 // Swap "value" over into "reg_value_extractor"
1633 reg_value_extractor.GetStringRef().swap(value);
Greg Clayton160c9d82013-05-01 21:54:04 +00001634 if (!gdb_thread->PrivateSetRegisterValue (reg, reg_value_extractor))
Greg Claytone576ab22011-02-15 00:19:15 +00001635 {
1636 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1637 name.c_str(),
1638 reg,
1639 reg,
1640 reg_value_extractor.GetStringRef().c_str(),
1641 stop_packet.GetStringRef().c_str());
1642 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001643 }
1644 }
1645 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001646 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001647
Hafiz Abid Qadeer673b4a32014-02-20 10:23:20 +00001648 // If the response is old style 'S' packet which does not provide us with thread information
1649 // then update the thread list and choose the first one.
1650 if (!thread_sp)
1651 {
1652 UpdateThreadIDList ();
1653
1654 if (!m_thread_ids.empty ())
1655 {
1656 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1657 thread_sp = m_thread_list_real.FindThreadByProtocolID (m_thread_ids.front (), false);
1658 if (thread_sp)
1659 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get ());
1660 }
1661 }
1662
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001663 if (thread_sp)
1664 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001665 // Clear the stop info just in case we don't set it to anything
1666 thread_sp->SetStopInfo (StopInfoSP());
1667
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001668 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Inghamdd2fe7a2011-01-28 02:23:12 +00001669 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001670 if (exc_type != 0)
1671 {
Greg Clayton1a65ae12011-01-25 23:55:37 +00001672 const size_t exc_data_size = exc_data.size();
Greg Claytonf4b47e12010-08-04 01:40:35 +00001673
Greg Clayton160c9d82013-05-01 21:54:04 +00001674 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1675 exc_type,
1676 exc_data_size,
1677 exc_data_size >= 1 ? exc_data[0] : 0,
1678 exc_data_size >= 2 ? exc_data[1] : 0,
1679 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001680 }
Greg Claytona658fd22011-06-04 01:26:29 +00001681 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001682 {
Greg Claytona658fd22011-06-04 01:26:29 +00001683 bool handled = false;
Greg Clayton8cda7f02013-05-21 21:55:59 +00001684 bool did_exec = false;
Greg Claytona658fd22011-06-04 01:26:29 +00001685 if (!reason.empty())
1686 {
1687 if (reason.compare("trace") == 0)
1688 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001689 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Greg Claytona658fd22011-06-04 01:26:29 +00001690 handled = true;
1691 }
1692 else if (reason.compare("breakpoint") == 0)
1693 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001694 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1695 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Claytona658fd22011-06-04 01:26:29 +00001696 if (bp_site_sp)
1697 {
1698 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1699 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1700 // 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 +00001701 handled = true;
Greg Clayton160c9d82013-05-01 21:54:04 +00001702 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00001703 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001704 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00001705 }
1706 else
1707 {
1708 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001709 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00001710 }
1711 }
1712
Greg Claytona658fd22011-06-04 01:26:29 +00001713 }
1714 else if (reason.compare("trap") == 0)
1715 {
1716 // Let the trap just use the standard signal stop reason below...
1717 }
1718 else if (reason.compare("watchpoint") == 0)
1719 {
1720 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1721 // TODO: locate the watchpoint somehow...
Greg Clayton160c9d82013-05-01 21:54:04 +00001722 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
Greg Claytona658fd22011-06-04 01:26:29 +00001723 handled = true;
1724 }
1725 else if (reason.compare("exception") == 0)
1726 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001727 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00001728 handled = true;
1729 }
Greg Clayton15fc2be2013-05-21 01:00:52 +00001730 else if (reason.compare("exec") == 0)
1731 {
Greg Clayton8cda7f02013-05-21 21:55:59 +00001732 did_exec = true;
Greg Clayton15fc2be2013-05-21 01:00:52 +00001733 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
1734 handled = true;
1735 }
Greg Claytona658fd22011-06-04 01:26:29 +00001736 }
1737
Jim Ingham40083a42014-02-24 19:49:46 +00001738 if (!handled && signo && did_exec == false)
Greg Claytona658fd22011-06-04 01:26:29 +00001739 {
1740 if (signo == SIGTRAP)
1741 {
1742 // Currently we are going to assume SIGTRAP means we are either
1743 // hitting a breakpoint or hardware single stepping.
Jim Ingham54cc6e42012-07-11 21:41:19 +00001744 handled = true;
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +00001745 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
Greg Clayton160c9d82013-05-01 21:54:04 +00001746 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Jim Ingham54cc6e42012-07-11 21:41:19 +00001747
Greg Claytona658fd22011-06-04 01:26:29 +00001748 if (bp_site_sp)
1749 {
1750 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1751 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1752 // 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 +00001753 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00001754 {
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +00001755 if(m_breakpoint_pc_offset != 0)
1756 thread_sp->GetRegisterContext()->SetPC(pc);
Greg Clayton160c9d82013-05-01 21:54:04 +00001757 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00001758 }
1759 else
1760 {
1761 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001762 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00001763 }
1764 }
Jim Ingham54cc6e42012-07-11 21:41:19 +00001765 else
Greg Claytona658fd22011-06-04 01:26:29 +00001766 {
Jim Ingham4dc613b2012-10-27 02:52:04 +00001767 // If we were stepping then assume the stop was the result of the trace. If we were
1768 // not stepping then report the SIGTRAP.
1769 // FIXME: We are still missing the case where we single step over a trap instruction.
Greg Clayton160c9d82013-05-01 21:54:04 +00001770 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1771 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Jim Ingham4dc613b2012-10-27 02:52:04 +00001772 else
Greg Clayton160c9d82013-05-01 21:54:04 +00001773 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo));
Greg Claytona658fd22011-06-04 01:26:29 +00001774 }
1775 }
1776 if (!handled)
Greg Clayton160c9d82013-05-01 21:54:04 +00001777 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Jason Molenda8214b012013-04-25 01:33:46 +00001778 }
Greg Claytona658fd22011-06-04 01:26:29 +00001779
1780 if (!description.empty())
1781 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001782 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
Greg Claytona658fd22011-06-04 01:26:29 +00001783 if (stop_info_sp)
1784 {
1785 stop_info_sp->SetDescription (description.c_str());
Greg Clayton3418c852011-08-10 02:10:13 +00001786 }
Greg Claytona658fd22011-06-04 01:26:29 +00001787 else
1788 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001789 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00001790 }
1791 }
1792 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001793 }
1794 return eStateStopped;
1795 }
1796 break;
1797
1798 case 'W':
1799 // process exited
1800 return eStateExited;
1801
1802 default:
1803 break;
1804 }
1805 return eStateInvalid;
1806}
1807
1808void
1809ProcessGDBRemote::RefreshStateAfterStop ()
1810{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001811 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001812 m_thread_ids.clear();
1813 // Set the thread stop info. It might have a "threads" key whose value is
1814 // a list of all thread IDs in the current process, so m_thread_ids might
1815 // get set.
1816 SetThreadStopInfo (m_last_stop_packet);
1817 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1818 if (m_thread_ids.empty())
1819 {
1820 // No, we need to fetch the thread list manually
1821 UpdateThreadIDList();
1822 }
1823
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001824 // Let all threads recover from stopping and do any clean up based
1825 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001826 m_thread_list_real.RefreshStateAfterStop();
Greg Clayton9e920902012-04-10 02:25:43 +00001827
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001828}
1829
1830Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001831ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001832{
1833 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001834
Greg Clayton6ed95942011-01-22 07:12:45 +00001835 bool timed_out = false;
1836 Mutex::Locker locker;
Greg Clayton513c26c2011-01-29 07:10:55 +00001837
1838 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00001839 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001840 // We are being asked to halt during an attach. We need to just close
1841 // our file handle and debugserver will go away, and we can be done...
1842 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00001843 }
Greg Clayton513c26c2011-01-29 07:10:55 +00001844 else
1845 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001846 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton513c26c2011-01-29 07:10:55 +00001847 {
1848 if (timed_out)
1849 error.SetErrorString("timed out sending interrupt packet");
1850 else
1851 error.SetErrorString("unknown error sending interrupt packet");
1852 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001853
1854 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton513c26c2011-01-29 07:10:55 +00001855 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001856 return error;
1857}
1858
1859Error
Jim Inghamacff8952013-05-02 00:27:30 +00001860ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00001861{
1862 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001863 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00001864 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00001865 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
1866
Greg Clayton594e5ed2010-09-27 21:07:38 +00001867 DisableAllBreakpointSites ();
1868
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001869 m_thread_list.DiscardThreadPlans();
Greg Clayton594e5ed2010-09-27 21:07:38 +00001870
Jim Inghamacff8952013-05-02 00:27:30 +00001871 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001872 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00001873 {
Jim Inghamacff8952013-05-02 00:27:30 +00001874 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001875 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1876 else
Jim Inghamacff8952013-05-02 00:27:30 +00001877 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00001878 }
Jim Inghamacff8952013-05-02 00:27:30 +00001879
1880 if (!error.Success())
1881 return error;
1882
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001883 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00001884 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001885
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001886 SetPrivateState (eStateDetached);
1887 ResumePrivateStateThread();
1888
1889 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00001890 return error;
1891}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001892
Jim Ingham43c555d2012-07-04 00:35:43 +00001893
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001894Error
1895ProcessGDBRemote::DoDestroy ()
1896{
1897 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001898 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001899 if (log)
1900 log->Printf ("ProcessGDBRemote::DoDestroy()");
1901
Jim Ingham43c555d2012-07-04 00:35:43 +00001902 // There is a bug in older iOS debugservers where they don't shut down the process
1903 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
1904 // this can cause problems with restarting. So we check to see if any of our threads are stopped
1905 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
1906 // destroy it again.
1907 //
1908 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
1909 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
1910 // the debugservers with this bug are equal. There really should be a better way to test this!
1911 //
1912 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
1913 // get called here to destroy again and we're still at a breakpoint or exception, then we should
1914 // just do the straight-forward kill.
1915 //
1916 // And of course, if we weren't able to stop the process by the time we get here, it isn't
1917 // necessary (or helpful) to do any of this.
1918
1919 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
1920 {
1921 PlatformSP platform_sp = GetTarget().GetPlatform();
1922
1923 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
1924 if (platform_sp
1925 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00001926 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00001927 {
1928 if (m_destroy_tried_resuming)
1929 {
1930 if (log)
1931 log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again.");
1932 }
1933 else
1934 {
1935 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
1936 // but we really need it to happen here and it doesn't matter if we do it twice.
1937 m_thread_list.DiscardThreadPlans();
1938 DisableAllBreakpointSites();
1939
1940 bool stop_looks_like_crash = false;
1941 ThreadList &threads = GetThreadList();
1942
1943 {
Jim Ingham45350372012-09-11 00:08:52 +00001944 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00001945
1946 size_t num_threads = threads.GetSize();
1947 for (size_t i = 0; i < num_threads; i++)
1948 {
1949 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00001950 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00001951 StopReason reason = eStopReasonInvalid;
1952 if (stop_info_sp)
1953 reason = stop_info_sp->GetStopReason();
1954 if (reason == eStopReasonBreakpoint
1955 || reason == eStopReasonException)
1956 {
1957 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00001958 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
1959 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00001960 stop_info_sp->GetDescription());
1961 stop_looks_like_crash = true;
1962 break;
1963 }
1964 }
1965 }
1966
1967 if (stop_looks_like_crash)
1968 {
1969 if (log)
1970 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
1971 m_destroy_tried_resuming = true;
1972
1973 // If we are going to run again before killing, it would be good to suspend all the threads
1974 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
1975 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
1976 // have to run the risk of letting those threads proceed a bit.
1977
1978 {
Jim Ingham45350372012-09-11 00:08:52 +00001979 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00001980
1981 size_t num_threads = threads.GetSize();
1982 for (size_t i = 0; i < num_threads; i++)
1983 {
1984 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00001985 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00001986 StopReason reason = eStopReasonInvalid;
1987 if (stop_info_sp)
1988 reason = stop_info_sp->GetStopReason();
1989 if (reason != eStopReasonBreakpoint
1990 && reason != eStopReasonException)
1991 {
1992 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00001993 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
1994 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00001995 thread_sp->SetResumeState(eStateSuspended);
1996 }
1997 }
1998 }
1999 Resume ();
2000 return Destroy();
2001 }
2002 }
2003 }
2004 }
2005
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002006 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00002007 int exit_status = SIGABRT;
2008 std::string exit_string;
2009
Greg Clayton6ed95942011-01-22 07:12:45 +00002010 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002011 {
Jim Inghamaab78372011-10-28 01:11:35 +00002012 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00002013 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002014
2015 StringExtractorGDBRemote response;
2016 bool send_async = true;
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002017 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3);
2018
Greg Clayton3dedae12013-12-06 21:45:27 +00002019 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton513c26c2011-01-29 07:10:55 +00002020 {
2021 char packet_cmd = response.GetChar(0);
2022
2023 if (packet_cmd == 'W' || packet_cmd == 'X')
2024 {
Jim Inghameac0aa42014-02-21 22:36:11 +00002025#if defined(__APPLE__)
Jim Ingham9d67cc52014-02-21 22:35:29 +00002026 // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off
2027 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill
2028 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns
2029 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap
2030 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of
2031 // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2032 // Anyway, so call waitpid here to finally reap it.
2033 PlatformSP platform_sp(GetTarget().GetPlatform());
2034 if (platform_sp && platform_sp->IsHost())
2035 {
2036 int status;
2037 ::pid_t reap_pid;
2038 reap_pid = waitpid (GetID(), &status, WNOHANG);
2039 if (log)
2040 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2041 }
2042#endif
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002043 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002044 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00002045 exit_status = response.GetHexU8();
2046 }
2047 else
2048 {
2049 if (log)
2050 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2051 exit_string.assign("got unexpected response to k packet: ");
2052 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00002053 }
2054 }
2055 else
2056 {
Jim Inghambabfc382012-06-06 00:32:39 +00002057 if (log)
2058 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2059 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00002060 }
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002061
2062 m_gdb_comm.SetPacketTimeout(old_packet_timeout);
Greg Clayton6779606a2011-01-22 23:43:18 +00002063 }
Jim Inghambabfc382012-06-06 00:32:39 +00002064 else
2065 {
2066 if (log)
2067 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
Jim Inghamcfc09352012-07-27 23:57:19 +00002068 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00002069 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002070 }
Jim Inghambabfc382012-06-06 00:32:39 +00002071 else
2072 {
2073 // If we missed setting the exit status on the way out, do it here.
2074 // NB set exit status can be called multiple times, the first one sets the status.
2075 exit_string.assign("destroying when not connected to debugserver");
2076 }
2077
2078 SetExitStatus(exit_status, exit_string.c_str());
2079
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002080 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002081 KillDebugserverProcess ();
2082 return error;
2083}
2084
Greg Clayton8cda7f02013-05-21 21:55:59 +00002085void
2086ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2087{
2088 lldb_private::Mutex::Locker locker (m_last_stop_packet_mutex);
2089 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2090 if (did_exec)
2091 {
2092 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2093 if (log)
2094 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2095
2096 m_thread_list_real.Clear();
2097 m_thread_list.Clear();
2098 BuildDynamicRegisterInfo (true);
2099 m_gdb_comm.ResetDiscoverableSettings();
2100 }
2101 m_last_stop_packet = response;
2102}
2103
2104
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002105//------------------------------------------------------------------
2106// Process Queries
2107//------------------------------------------------------------------
2108
2109bool
2110ProcessGDBRemote::IsAlive ()
2111{
Greg Clayton10177aa2010-12-08 05:08:21 +00002112 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002113}
2114
2115addr_t
2116ProcessGDBRemote::GetImageInfoAddress()
2117{
Jason Molenda6ba6d3d2013-01-30 04:39:32 +00002118 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002119}
2120
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002121//------------------------------------------------------------------
2122// Process Memory
2123//------------------------------------------------------------------
2124size_t
2125ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2126{
2127 if (size > m_max_memory_size)
2128 {
2129 // Keep memory read sizes down to a sane limit. This function will be
2130 // called multiple times in order to complete the task by
2131 // lldb_private::Process so it is ok to do this.
2132 size = m_max_memory_size;
2133 }
2134
2135 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002136 const int packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
Andy Gibbsa297a972013-06-19 19:04:53 +00002137 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002138 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002139 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002140 {
Greg Clayton576d8832011-03-22 04:00:09 +00002141 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002142 {
2143 error.Clear();
2144 return response.GetHexBytes(buf, size, '\xdd');
2145 }
Greg Clayton576d8832011-03-22 04:00:09 +00002146 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002147 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002148 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002149 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002150 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002151 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002152 }
2153 else
2154 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002155 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002156 }
2157 return 0;
2158}
2159
2160size_t
2161ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2162{
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002163 if (size > m_max_memory_size)
2164 {
2165 // Keep memory read sizes down to a sane limit. This function will be
2166 // called multiple times in order to complete the task by
2167 // lldb_private::Process so it is ok to do this.
2168 size = m_max_memory_size;
2169 }
2170
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002171 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00002172 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Clayton7fb56d02011-02-01 01:31:41 +00002173 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002174 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002175 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002176 {
Greg Clayton576d8832011-03-22 04:00:09 +00002177 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002178 {
2179 error.Clear();
2180 return size;
2181 }
Greg Clayton576d8832011-03-22 04:00:09 +00002182 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002183 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002184 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002185 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002186 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002187 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 +00002188 }
2189 else
2190 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002191 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002192 }
2193 return 0;
2194}
2195
2196lldb::addr_t
2197ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2198{
Greg Clayton2a48f522011-05-14 01:50:35 +00002199 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2200
Greg Clayton70b57652011-05-15 01:25:55 +00002201 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton2a48f522011-05-14 01:50:35 +00002202 switch (supported)
2203 {
2204 case eLazyBoolCalculate:
2205 case eLazyBoolYes:
2206 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2207 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2208 return allocated_addr;
2209
2210 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002211 // Call mmap() to create memory in the inferior..
2212 unsigned prot = 0;
2213 if (permissions & lldb::ePermissionsReadable)
2214 prot |= eMmapProtRead;
2215 if (permissions & lldb::ePermissionsWritable)
2216 prot |= eMmapProtWrite;
2217 if (permissions & lldb::ePermissionsExecutable)
2218 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00002219
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002220 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2221 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2222 m_addr_to_mmap_size[allocated_addr] = size;
2223 else
2224 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton2a48f522011-05-14 01:50:35 +00002225 break;
2226 }
2227
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002228 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00002229 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002230 else
2231 error.Clear();
2232 return allocated_addr;
2233}
2234
2235Error
Greg Clayton46fb5582011-11-18 07:03:08 +00002236ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2237 MemoryRegionInfo &region_info)
2238{
2239
2240 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2241 return error;
2242}
2243
2244Error
Johnny Chen64637202012-05-23 21:09:52 +00002245ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2246{
2247
2248 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2249 return error;
2250}
2251
2252Error
Enrico Granataf04a2192012-07-13 23:18:48 +00002253ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2254{
2255 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2256 return error;
2257}
2258
2259Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002260ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2261{
2262 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00002263 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2264
2265 switch (supported)
2266 {
2267 case eLazyBoolCalculate:
2268 // We should never be deallocating memory without allocating memory
2269 // first so we should never get eLazyBoolCalculate
2270 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2271 break;
2272
2273 case eLazyBoolYes:
2274 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00002275 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002276 break;
2277
2278 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002279 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00002280 {
2281 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002282 if (pos != m_addr_to_mmap_size.end() &&
2283 InferiorCallMunmap(this, addr, pos->second))
2284 m_addr_to_mmap_size.erase (pos);
2285 else
Daniel Malead01b2952012-11-29 21:49:15 +00002286 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002287 }
2288 break;
2289 }
2290
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002291 return error;
2292}
2293
2294
2295//------------------------------------------------------------------
2296// Process STDIO
2297//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002298size_t
2299ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2300{
2301 if (m_stdio_communication.IsConnected())
2302 {
2303 ConnectionStatus status;
2304 m_stdio_communication.Write(src, src_len, status, NULL);
2305 }
2306 return 0;
2307}
2308
2309Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002310ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002311{
2312 Error error;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002313 assert(bp_site != NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002314
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002315 // Get logging info
2316 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002317 user_id_t site_id = bp_site->GetID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002318
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002319 // Get the breakpoint address
2320 const addr_t addr = bp_site->GetLoadAddress();
2321
2322 // Log that a breakpoint was requested
2323 if (log)
2324 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
2325
2326 // Breakpoint already exists and is enabled
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002327 if (bp_site->IsEnabled())
2328 {
2329 if (log)
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002330 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 +00002331 return error;
2332 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002333
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002334 // Get the software breakpoint trap opcode size
2335 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2336
2337 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
2338 // is supported by the remote stub. These are set to true by default, and later set to false
2339 // only after we receive an unimplemented response when sending a breakpoint packet. This means
2340 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
2341 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
2342 // indicates if the user specifically asked for hardware breakpoints. If true then we will
2343 // skip over software breakpoints.
2344 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
2345 {
2346 // Try to send off a software breakpoint packet ($Z0)
2347 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002348 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002349 // The breakpoint was placed successfully
2350 bp_site->SetEnabled(true);
2351 bp_site->SetType(BreakpointSite::eExternal);
Greg Claytoneb023e72013-10-11 19:48:25 +00002352 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002353 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002354
2355 // SendGDBStoppointTypePacket() will return an error if it was unable to set this
2356 // breakpoint. We need to differentiate between a error specific to placing this breakpoint
2357 // or if we have learned that this breakpoint type is unsupported. To do this, we
2358 // must test the support boolean for this breakpoint type to see if it now indicates that
2359 // this breakpoint type is unsupported. If they are still supported then we should return
2360 // with the error code. If they are now unsupported, then we would like to fall through
2361 // and try another form of breakpoint.
2362 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
2363 return error;
2364
2365 // We reach here when software breakpoints have been found to be unsupported. For future
2366 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
2367 // known not to be supported.
2368 if (log)
2369 log->Printf("Software breakpoints are unsupported");
2370
2371 // So we will fall through and try a hardware breakpoint
2372 }
2373
2374 // The process of setting a hardware breakpoint is much the same as above. We check the
2375 // supported boolean for this breakpoint type, and if it is thought to be supported then we
2376 // will try to set this breakpoint with a hardware breakpoint.
2377 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
2378 {
2379 // Try to send off a hardware breakpoint packet ($Z1)
2380 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002381 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002382 // The breakpoint was placed successfully
2383 bp_site->SetEnabled(true);
2384 bp_site->SetType(BreakpointSite::eHardware);
2385 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002386 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002387
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002388 // Check if the error was something other then an unsupported breakpoint type
2389 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
2390 {
2391 // Unable to set this hardware breakpoint
2392 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
2393 return error;
2394 }
2395
2396 // We will reach here when the stub gives an unsported response to a hardware breakpoint
2397 if (log)
2398 log->Printf("Hardware breakpoints are unsupported");
2399
2400 // Finally we will falling through to a #trap style breakpoint
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002401 }
2402
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002403 // Don't fall through when hardware breakpoints were specifically requested
2404 if (bp_site->HardwareRequired())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002405 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002406 error.SetErrorString("hardware breakpoints are not supported");
2407 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002408 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002409
2410 // As a last resort we want to place a manual breakpoint. An instruction
2411 // is placed into the process memory using memory write packets.
2412 return EnableSoftwareBreakpoint(bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002413}
2414
2415Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002416ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002417{
2418 Error error;
2419 assert (bp_site != NULL);
2420 addr_t addr = bp_site->GetLoadAddress();
2421 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00002422 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002423 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002424 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002425
2426 if (bp_site->IsEnabled())
2427 {
2428 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2429
Greg Clayton8b82f082011-04-12 05:54:46 +00002430 BreakpointSite::Type bp_type = bp_site->GetType();
2431 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002432 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002433 case BreakpointSite::eSoftware:
2434 error = DisableSoftwareBreakpoint (bp_site);
2435 break;
2436
2437 case BreakpointSite::eHardware:
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002438 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
Greg Clayton8b82f082011-04-12 05:54:46 +00002439 error.SetErrorToGenericError();
2440 break;
2441
2442 case BreakpointSite::eExternal:
2443 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2444 error.SetErrorToGenericError();
2445 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002446 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002447 if (error.Success())
2448 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002449 }
2450 else
2451 {
2452 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002453 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 +00002454 return error;
2455 }
2456
2457 if (error.Success())
2458 error.SetErrorToGenericError();
2459 return error;
2460}
2461
Johnny Chen11309a32011-09-06 22:38:36 +00002462// Pre-requisite: wp != NULL.
2463static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00002464GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00002465{
2466 assert(wp);
2467 bool watch_read = wp->WatchpointRead();
2468 bool watch_write = wp->WatchpointWrite();
2469
2470 // watch_read and watch_write cannot both be false.
2471 assert(watch_read || watch_write);
2472 if (watch_read && watch_write)
2473 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00002474 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00002475 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00002476 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00002477 return eWatchpointWrite;
2478}
2479
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002480Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002481ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002482{
2483 Error error;
2484 if (wp)
2485 {
2486 user_id_t watchID = wp->GetID();
2487 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00002488 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002489 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002490 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002491 if (wp->IsEnabled())
2492 {
2493 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002494 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 +00002495 return error;
2496 }
Johnny Chen11309a32011-09-06 22:38:36 +00002497
2498 GDBStoppointType type = GetGDBStoppointType(wp);
2499 // Pass down an appropriate z/Z packet...
2500 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002501 {
Johnny Chen11309a32011-09-06 22:38:36 +00002502 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2503 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002504 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002505 return error;
2506 }
2507 else
2508 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002509 }
Johnny Chen11309a32011-09-06 22:38:36 +00002510 else
2511 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002512 }
2513 else
2514 {
Johnny Chen01a67862011-10-14 00:42:25 +00002515 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002516 }
2517 if (error.Success())
2518 error.SetErrorToGenericError();
2519 return error;
2520}
2521
2522Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002523ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002524{
2525 Error error;
2526 if (wp)
2527 {
2528 user_id_t watchID = wp->GetID();
2529
Greg Clayton5160ce52013-03-27 23:08:40 +00002530 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002531
2532 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00002533
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002534 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002535 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002536
Johnny Chen11309a32011-09-06 22:38:36 +00002537 if (!wp->IsEnabled())
2538 {
2539 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002540 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 +00002541 // See also 'class WatchpointSentry' within StopInfo.cpp.
2542 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2543 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00002544 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002545 return error;
2546 }
2547
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002548 if (wp->IsHardware())
2549 {
Johnny Chen11309a32011-09-06 22:38:36 +00002550 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002551 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00002552 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2553 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002554 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002555 return error;
2556 }
2557 else
2558 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002559 }
2560 // TODO: clear software watchpoints if we implement them
2561 }
2562 else
2563 {
Johnny Chen01a67862011-10-14 00:42:25 +00002564 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002565 }
2566 if (error.Success())
2567 error.SetErrorToGenericError();
2568 return error;
2569}
2570
2571void
2572ProcessGDBRemote::Clear()
2573{
2574 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002575 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002576 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002577}
2578
2579Error
2580ProcessGDBRemote::DoSignal (int signo)
2581{
2582 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002583 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002584 if (log)
2585 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2586
2587 if (!m_gdb_comm.SendAsyncSignal (signo))
2588 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2589 return error;
2590}
2591
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002592Error
Greg Clayton91a9b2472013-12-04 19:19:12 +00002593ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002594{
2595 Error error;
2596 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2597 {
2598 // If we locate debugserver, keep that located version around
2599 static FileSpec g_debugserver_file_spec;
2600
Han Ming Ong84647042012-02-25 01:07:38 +00002601 ProcessLaunchInfo debugserver_launch_info;
Greg Clayton91a9b2472013-12-04 19:19:12 +00002602 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2603 debugserver_launch_info.SetUserID(process_info.GetUserID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002604
Greg Claytonfda4fab2014-01-10 22:24:11 +00002605#if defined (__APPLE__) && defined (__arm__)
2606 // On iOS, still do a local connection using a random port
Greg Clayton16810922014-02-27 19:38:18 +00002607 const char *hostname = "127.0.0.1";
Greg Claytonfda4fab2014-01-10 22:24:11 +00002608 uint16_t port = get_random_port ();
2609#else
2610 // Set hostname being NULL to do the reverse connect where debugserver
2611 // will bind to port zero and it will communicate back to us the port
2612 // that we will connect to
2613 const char *hostname = NULL;
2614 uint16_t port = 0;
2615#endif
2616
2617 error = m_gdb_comm.StartDebugserverProcess (hostname,
2618 port,
Greg Clayton00fe87b2013-12-05 22:58:22 +00002619 debugserver_launch_info,
2620 port);
Greg Clayton91a9b2472013-12-04 19:19:12 +00002621
2622 if (error.Success ())
2623 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002624 else
Greg Clayton91a9b2472013-12-04 19:19:12 +00002625 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002626
2627 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2628 StartAsyncThread ();
Greg Clayton91a9b2472013-12-04 19:19:12 +00002629
2630 if (error.Fail())
2631 {
2632 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
2633
2634 if (log)
2635 log->Printf("failed to start debugserver process: %s", error.AsCString());
2636 return error;
2637 }
2638
Greg Clayton00fe87b2013-12-05 22:58:22 +00002639 if (m_gdb_comm.IsConnected())
2640 {
2641 // Finish the connection process by doing the handshake without connecting (send NULL URL)
2642 ConnectToDebugserver (NULL);
2643 }
2644 else
2645 {
Greg Claytonfda4fab2014-01-10 22:24:11 +00002646 StreamString connect_url;
2647 connect_url.Printf("connect://%s:%u", hostname, port);
2648 error = ConnectToDebugserver (connect_url.GetString().c_str());
Greg Clayton00fe87b2013-12-05 22:58:22 +00002649 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00002650
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002651 }
2652 return error;
2653}
2654
2655bool
2656ProcessGDBRemote::MonitorDebugserverProcess
2657(
2658 void *callback_baton,
2659 lldb::pid_t debugserver_pid,
Greg Claytone4e45922011-11-16 05:37:56 +00002660 bool exited, // True if the process did exit
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002661 int signo, // Zero for no signal
2662 int exit_status // Exit value of process if signal is zero
2663)
2664{
Greg Claytone4e45922011-11-16 05:37:56 +00002665 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2666 // and might not exist anymore, so we need to carefully try to get the
2667 // target for this process first since we have a race condition when
2668 // we are done running between getting the notice that the inferior
2669 // process has died and the debugserver that was debugging this process.
2670 // In our test suite, we are also continually running process after
2671 // process, so we must be very careful to make sure:
2672 // 1 - process object hasn't been deleted already
2673 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002674
2675 // "debugserver_pid" argument passed in is the process ID for
2676 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00002677 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002678
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002679 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton6779606a2011-01-22 23:43:18 +00002680
Greg Claytone4e45922011-11-16 05:37:56 +00002681 // Get a shared pointer to the target that has a matching process pointer.
2682 // This target could be gone, or the target could already have a new process
2683 // object inside of it
2684 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2685
Greg Clayton6779606a2011-01-22 23:43:18 +00002686 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002687 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 +00002688
Greg Claytone4e45922011-11-16 05:37:56 +00002689 if (target_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002690 {
Greg Claytone4e45922011-11-16 05:37:56 +00002691 // We found a process in a target that matches, but another thread
2692 // might be in the process of launching a new process that will
2693 // soon replace it, so get a shared pointer to the process so we
2694 // can keep it alive.
2695 ProcessSP process_sp (target_sp->GetProcessSP());
2696 // Now we have a shared pointer to the process that can't go away on us
2697 // so we now make sure it was the same as the one passed in, and also make
2698 // sure that our previous "process *" didn't get deleted and have a new
2699 // "process *" created in its place with the same pointer. To verify this
2700 // we make sure the process has our debugserver process ID. If we pass all
2701 // of these tests, then we are sure that this process is the one we were
2702 // looking for.
2703 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002704 {
Greg Claytone4e45922011-11-16 05:37:56 +00002705 // Sleep for a half a second to make sure our inferior process has
2706 // time to set its exit status before we set it incorrectly when
2707 // both the debugserver and the inferior process shut down.
2708 usleep (500000);
2709 // If our process hasn't yet exited, debugserver might have died.
2710 // If the process did exit, the we are reaping it.
2711 const StateType state = process->GetState();
2712
2713 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2714 state != eStateInvalid &&
2715 state != eStateUnloaded &&
2716 state != eStateExited &&
2717 state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002718 {
Greg Claytone4e45922011-11-16 05:37:56 +00002719 char error_str[1024];
2720 if (signo)
2721 {
2722 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2723 if (signal_cstr)
2724 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2725 else
2726 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2727 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002728 else
Greg Claytone4e45922011-11-16 05:37:56 +00002729 {
2730 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2731 }
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002732
Greg Claytone4e45922011-11-16 05:37:56 +00002733 process->SetExitStatus (-1, error_str);
2734 }
2735 // Debugserver has exited we need to let our ProcessGDBRemote
2736 // know that it no longer has a debugserver instance
2737 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002738 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002739 }
2740 return true;
2741}
2742
2743void
2744ProcessGDBRemote::KillDebugserverProcess ()
2745{
Greg Claytonfbb76342013-11-20 21:07:01 +00002746 m_gdb_comm.Disconnect();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002747 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2748 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002749 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002750 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2751 }
2752}
2753
2754void
2755ProcessGDBRemote::Initialize()
2756{
2757 static bool g_initialized = false;
2758
2759 if (g_initialized == false)
2760 {
2761 g_initialized = true;
2762 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2763 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00002764 CreateInstance,
2765 DebuggerInitialize);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002766
2767 Log::Callbacks log_callbacks = {
2768 ProcessGDBRemoteLog::DisableLog,
2769 ProcessGDBRemoteLog::EnableLog,
2770 ProcessGDBRemoteLog::ListLogCategories
2771 };
2772
2773 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2774 }
2775}
2776
Greg Clayton7f982402013-07-15 22:54:20 +00002777void
2778ProcessGDBRemote::DebuggerInitialize (lldb_private::Debugger &debugger)
2779{
2780 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
2781 {
2782 const bool is_global_setting = true;
2783 PluginManager::CreateSettingForProcessPlugin (debugger,
2784 GetGlobalPluginProperties()->GetValueProperties(),
2785 ConstString ("Properties for the gdb-remote process plug-in."),
2786 is_global_setting);
2787 }
2788}
2789
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002790bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002791ProcessGDBRemote::StartAsyncThread ()
2792{
Greg Clayton5160ce52013-03-27 23:08:40 +00002793 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002794
2795 if (log)
2796 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Ingham455fa5c2012-11-01 01:15:33 +00002797
2798 Mutex::Locker start_locker(m_async_thread_state_mutex);
2799 if (m_async_thread_state == eAsyncThreadNotStarted)
2800 {
2801 // Create a thread that watches our internal state and controls which
2802 // events make it to clients (into the DCProcess event queue).
2803 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2804 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2805 {
2806 m_async_thread_state = eAsyncThreadRunning;
2807 return true;
2808 }
2809 else
2810 return false;
2811 }
2812 else
2813 {
2814 // Somebody tried to start the async thread while it was either being started or stopped. If the former, and
2815 // it started up successfully, then say all's well. Otherwise it is an error, since we aren't going to restart it.
2816 if (log)
2817 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
2818 if (m_async_thread_state == eAsyncThreadRunning)
2819 return true;
2820 else
2821 return false;
2822 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002823}
2824
2825void
2826ProcessGDBRemote::StopAsyncThread ()
2827{
Greg Clayton5160ce52013-03-27 23:08:40 +00002828 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002829
2830 if (log)
2831 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2832
Jim Ingham455fa5c2012-11-01 01:15:33 +00002833 Mutex::Locker start_locker(m_async_thread_state_mutex);
2834 if (m_async_thread_state == eAsyncThreadRunning)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002835 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00002836 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2837
2838 // This will shut down the async thread.
2839 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
2840
2841 // Stop the stdio thread
2842 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2843 {
2844 Host::ThreadJoin (m_async_thread, NULL, NULL);
2845 }
2846 m_async_thread_state = eAsyncThreadDone;
2847 }
2848 else
2849 {
2850 if (log)
2851 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002852 }
2853}
2854
2855
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002856thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002857ProcessGDBRemote::AsyncThread (void *arg)
2858{
2859 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2860
Greg Clayton5160ce52013-03-27 23:08:40 +00002861 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002862 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002863 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002864
2865 Listener listener ("ProcessGDBRemote::AsyncThread");
2866 EventSP event_sp;
2867 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2868 eBroadcastBitAsyncThreadShouldExit;
2869
2870 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2871 {
Greg Clayton71337622011-02-24 22:24:29 +00002872 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2873
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002874 bool done = false;
2875 while (!done)
2876 {
2877 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002878 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002879 if (listener.WaitForEvent (NULL, event_sp))
2880 {
2881 const uint32_t event_type = event_sp->GetType();
Greg Clayton71337622011-02-24 22:24:29 +00002882 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002883 {
Greg Clayton71337622011-02-24 22:24:29 +00002884 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002885 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 +00002886
Greg Clayton71337622011-02-24 22:24:29 +00002887 switch (event_type)
2888 {
2889 case eBroadcastBitAsyncContinue:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002890 {
Greg Clayton71337622011-02-24 22:24:29 +00002891 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002892
Greg Clayton71337622011-02-24 22:24:29 +00002893 if (continue_packet)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002894 {
Greg Clayton71337622011-02-24 22:24:29 +00002895 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2896 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2897 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002898 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002899
Greg Clayton71337622011-02-24 22:24:29 +00002900 if (::strstr (continue_cstr, "vAttach") == NULL)
2901 process->SetPrivateState(eStateRunning);
2902 StringExtractorGDBRemote response;
2903 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002904
Greg Clayton0772ded2012-05-16 02:48:06 +00002905 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
2906 // The thread ID list might be contained within the "response", or the stop reply packet that
2907 // caused the stop. So clear it now before we give the stop reply packet to the process
2908 // using the process->SetLastStopPacket()...
2909 process->ClearThreadIDList ();
2910
Greg Clayton71337622011-02-24 22:24:29 +00002911 switch (stop_state)
2912 {
2913 case eStateStopped:
2914 case eStateCrashed:
2915 case eStateSuspended:
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002916 process->SetLastStopPacket (response);
Greg Clayton71337622011-02-24 22:24:29 +00002917 process->SetPrivateState (stop_state);
2918 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002919
Greg Clayton71337622011-02-24 22:24:29 +00002920 case eStateExited:
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002921 process->SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002922 process->ClearThreadIDList();
Greg Clayton71337622011-02-24 22:24:29 +00002923 response.SetFilePos(1);
2924 process->SetExitStatus(response.GetHexU8(), NULL);
2925 done = true;
2926 break;
2927
2928 case eStateInvalid:
2929 process->SetExitStatus(-1, "lost connection");
2930 break;
2931
2932 default:
2933 process->SetPrivateState (stop_state);
2934 break;
2935 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002936 }
2937 }
Greg Clayton71337622011-02-24 22:24:29 +00002938 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002939
Greg Clayton71337622011-02-24 22:24:29 +00002940 case eBroadcastBitAsyncThreadShouldExit:
2941 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002942 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Clayton71337622011-02-24 22:24:29 +00002943 done = true;
2944 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002945
Greg Clayton71337622011-02-24 22:24:29 +00002946 default:
2947 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002948 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 +00002949 done = true;
2950 break;
2951 }
2952 }
2953 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2954 {
2955 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2956 {
2957 process->SetExitStatus (-1, "lost connection");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002958 done = true;
Greg Clayton71337622011-02-24 22:24:29 +00002959 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002960 }
2961 }
2962 else
2963 {
2964 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002965 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 +00002966 done = true;
2967 }
2968 }
2969 }
2970
2971 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002972 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002973
2974 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2975 return NULL;
2976}
2977
Greg Claytone996fd32011-03-08 22:40:15 +00002978//uint32_t
2979//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2980//{
2981// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2982// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2983// if (m_local_debugserver)
2984// {
2985// return Host::ListProcessesMatchingName (name, matches, pids);
2986// }
2987// else
2988// {
2989// // FIXME: Implement talking to the remote debugserver.
2990// return 0;
2991// }
2992//
2993//}
2994//
Jim Ingham1c823b42011-01-22 01:33:44 +00002995bool
2996ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2997 lldb_private::StoppointCallbackContext *context,
2998 lldb::user_id_t break_id,
2999 lldb::user_id_t break_loc_id)
3000{
3001 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3002 // run so I can stop it if that's what I want to do.
Greg Clayton5160ce52013-03-27 23:08:40 +00003003 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00003004 if (log)
3005 log->Printf("Hit New Thread Notification breakpoint.");
3006 return false;
3007}
3008
3009
3010bool
3011ProcessGDBRemote::StartNoticingNewThreads()
3012{
Greg Clayton5160ce52013-03-27 23:08:40 +00003013 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00003014 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003015 {
Greg Clayton4116e932012-05-15 02:33:01 +00003016 if (log && log->GetVerbose())
3017 log->Printf("Enabled noticing new thread breakpoint.");
3018 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003019 }
Greg Clayton4116e932012-05-15 02:33:01 +00003020 else
Jim Ingham1c823b42011-01-22 01:33:44 +00003021 {
Greg Clayton4116e932012-05-15 02:33:01 +00003022 PlatformSP platform_sp (m_target.GetPlatform());
3023 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003024 {
Greg Clayton4116e932012-05-15 02:33:01 +00003025 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3026 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003027 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00003028 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00003029 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3030 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003031 }
3032 else
3033 {
3034 if (log)
3035 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00003036 }
3037 }
3038 }
Greg Clayton4116e932012-05-15 02:33:01 +00003039 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00003040}
3041
3042bool
3043ProcessGDBRemote::StopNoticingNewThreads()
3044{
Greg Clayton5160ce52013-03-27 23:08:40 +00003045 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00003046 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00003047 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00003048
3049 if (m_thread_create_bp_sp)
3050 m_thread_create_bp_sp->SetEnabled(false);
3051
Jim Ingham1c823b42011-01-22 01:33:44 +00003052 return true;
3053}
3054
Jason Molenda5e8534e2012-10-03 01:29:34 +00003055lldb_private::DynamicLoader *
3056ProcessGDBRemote::GetDynamicLoader ()
3057{
3058 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00003059 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00003060 return m_dyld_ap.get();
3061}
Jim Ingham1c823b42011-01-22 01:33:44 +00003062
Steve Pucci03904ac2014-03-04 23:18:46 +00003063const DataBufferSP
3064ProcessGDBRemote::GetAuxvData()
3065{
3066 DataBufferSP buf;
3067 if (m_gdb_comm.GetQXferAuxvReadSupported())
3068 {
3069 std::string response_string;
3070 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success)
3071 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length()));
3072 }
3073 return buf;
3074}
3075
Greg Clayton998255b2012-10-13 02:07:45 +00003076
Greg Clayton02686b82012-10-15 22:42:16 +00003077class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00003078{
3079private:
3080
3081public:
Greg Clayton02686b82012-10-15 22:42:16 +00003082 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00003083 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00003084 "process plugin packet history",
3085 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00003086 NULL)
3087 {
3088 }
3089
Greg Clayton02686b82012-10-15 22:42:16 +00003090 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton998255b2012-10-13 02:07:45 +00003091 {
3092 }
3093
3094 bool
3095 DoExecute (Args& command, CommandReturnObject &result)
3096 {
Greg Clayton02686b82012-10-15 22:42:16 +00003097 const size_t argc = command.GetArgumentCount();
3098 if (argc == 0)
3099 {
3100 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3101 if (process)
3102 {
3103 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
3104 result.SetStatus (eReturnStatusSuccessFinishResult);
3105 return true;
3106 }
3107 }
3108 else
3109 {
3110 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
3111 }
3112 result.SetStatus (eReturnStatusFailed);
3113 return false;
3114 }
3115};
3116
3117class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
3118{
3119private:
3120
3121public:
3122 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
3123 CommandObjectParsed (interpreter,
3124 "process plugin packet send",
3125 "Send a custom packet through the GDB remote protocol and print the answer. "
3126 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
3127 NULL)
3128 {
3129 }
3130
3131 ~CommandObjectProcessGDBRemotePacketSend ()
3132 {
3133 }
3134
3135 bool
3136 DoExecute (Args& command, CommandReturnObject &result)
3137 {
3138 const size_t argc = command.GetArgumentCount();
3139 if (argc == 0)
3140 {
3141 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
3142 result.SetStatus (eReturnStatusFailed);
3143 return false;
3144 }
3145
3146 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3147 if (process)
3148 {
Han Ming Ong84145852012-11-26 20:42:03 +00003149 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00003150 {
Han Ming Ong84145852012-11-26 20:42:03 +00003151 const char *packet_cstr = command.GetArgumentAtIndex(0);
3152 bool send_async = true;
3153 StringExtractorGDBRemote response;
3154 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3155 result.SetStatus (eReturnStatusSuccessFinishResult);
3156 Stream &output_strm = result.GetOutputStream();
3157 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00003158 std::string &response_str = response.GetStringRef();
3159
Han Ming Ong399289e2013-06-21 19:56:59 +00003160 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00003161 {
3162 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
3163 }
3164
Han Ming Ong84145852012-11-26 20:42:03 +00003165 if (response_str.empty())
3166 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3167 else
3168 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00003169 }
Greg Clayton02686b82012-10-15 22:42:16 +00003170 }
Greg Clayton998255b2012-10-13 02:07:45 +00003171 return true;
3172 }
3173};
3174
Greg Claytonba4a0a52013-02-01 23:03:47 +00003175class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
3176{
3177private:
3178
3179public:
3180 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
3181 CommandObjectRaw (interpreter,
3182 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00003183 "Send a qRcmd packet through the GDB remote protocol and print the response."
3184 "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 +00003185 NULL)
3186 {
3187 }
3188
3189 ~CommandObjectProcessGDBRemotePacketMonitor ()
3190 {
3191 }
3192
3193 bool
3194 DoExecute (const char *command, CommandReturnObject &result)
3195 {
3196 if (command == NULL || command[0] == '\0')
3197 {
3198 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
3199 result.SetStatus (eReturnStatusFailed);
3200 return false;
3201 }
3202
3203 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3204 if (process)
3205 {
3206 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00003207 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00003208 packet.PutBytesAsRawHex8(command, strlen(command));
3209 const char *packet_cstr = packet.GetString().c_str();
3210
3211 bool send_async = true;
3212 StringExtractorGDBRemote response;
3213 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3214 result.SetStatus (eReturnStatusSuccessFinishResult);
3215 Stream &output_strm = result.GetOutputStream();
3216 output_strm.Printf (" packet: %s\n", packet_cstr);
3217 const std::string &response_str = response.GetStringRef();
3218
3219 if (response_str.empty())
3220 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3221 else
3222 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
3223 }
3224 return true;
3225 }
3226};
3227
Greg Clayton02686b82012-10-15 22:42:16 +00003228class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
3229{
3230private:
3231
3232public:
3233 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
3234 CommandObjectMultiword (interpreter,
3235 "process plugin packet",
3236 "Commands that deal with GDB remote packets.",
3237 NULL)
3238 {
3239 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
3240 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00003241 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00003242 }
3243
3244 ~CommandObjectProcessGDBRemotePacket ()
3245 {
3246 }
3247};
Greg Clayton998255b2012-10-13 02:07:45 +00003248
3249class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
3250{
3251public:
3252 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
3253 CommandObjectMultiword (interpreter,
3254 "process plugin",
3255 "A set of commands for operating on a ProcessGDBRemote process.",
3256 "process plugin <subcommand> [<subcommand-options>]")
3257 {
3258 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
3259 }
3260
3261 ~CommandObjectMultiwordProcessGDBRemote ()
3262 {
3263 }
3264};
3265
Greg Clayton998255b2012-10-13 02:07:45 +00003266CommandObject *
3267ProcessGDBRemote::GetPluginCommandObject()
3268{
3269 if (!m_command_sp)
3270 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
3271 return m_command_sp.get();
3272}