blob: 20b1495177862d82cbb162ba3d1b62dce7e9b6b1 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- ProcessGDBRemote.cpp ------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Daniel Malea93a64302012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
Virgile Bellob2f1fb22013-08-23 12:44:05 +000011#include "lldb/Host/Config.h"
Daniel Malea93a64302012-12-05 00:20:57 +000012
Chris Lattner30fdc8d2010-06-08 16:52:24 +000013// C Includes
14#include <errno.h>
Stephen Wilsona78867b2011-03-25 18:16:28 +000015#include <stdlib.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000016#ifndef LLDB_DISABLE_POSIX
17#include <spawn.h>
Sean Callanan224f6f52012-07-19 18:07:36 +000018#include <netinet/in.h>
Greg Clayton2a48f522011-05-14 01:50:35 +000019#include <sys/mman.h> // for mmap
Virgile Bellob2f1fb22013-08-23 12:44:05 +000020#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000021#include <sys/stat.h>
Greg Clayton2a48f522011-05-14 01:50:35 +000022#include <sys/types.h>
Stephen Wilsondc916862011-03-30 00:12:40 +000023#include <time.h>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000024
25// C++ Includes
26#include <algorithm>
27#include <map>
28
29// Other libraries and framework includes
30
Johnny Chen01a67862011-10-14 00:42:25 +000031#include "lldb/Breakpoint/Watchpoint.h"
Jim Ingham40af72e2010-06-15 19:49:27 +000032#include "lldb/Interpreter/Args.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000033#include "lldb/Core/ArchSpec.h"
34#include "lldb/Core/Debugger.h"
35#include "lldb/Core/ConnectionFileDescriptor.h"
Greg Clayton53239f02011-02-08 05:05:52 +000036#include "lldb/Host/FileSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000037#include "lldb/Core/InputReader.h"
38#include "lldb/Core/Module.h"
Greg Clayton1f746072012-08-29 21:13:06 +000039#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000040#include "lldb/Core/PluginManager.h"
41#include "lldb/Core/State.h"
Greg Claytond451c1a2012-04-13 21:24:18 +000042#include "lldb/Core/StreamFile.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000043#include "lldb/Core/StreamString.h"
44#include "lldb/Core/Timer.h"
Greg Clayton70b57652011-05-15 01:25:55 +000045#include "lldb/Core/Value.h"
Jason Molendad1fae142012-09-29 08:03:33 +000046#include "lldb/Host/Symbols.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000047#include "lldb/Host/TimeValue.h"
Greg Clayton02686b82012-10-15 22:42:16 +000048#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton1d19a2f2012-10-19 22:22:57 +000049#include "lldb/Interpreter/CommandObject.h"
50#include "lldb/Interpreter/CommandObjectMultiword.h"
Greg Clayton02686b82012-10-15 22:42:16 +000051#include "lldb/Interpreter/CommandReturnObject.h"
Joerg Sonnenbergere77b0422013-10-20 17:36:05 +000052#ifndef LLDB_DISABLE_PYTHON
Greg Claytonef8180a2013-10-15 00:14:28 +000053#include "lldb/Interpreter/PythonDataObjects.h"
Joerg Sonnenbergere77b0422013-10-20 17:36:05 +000054#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000055#include "lldb/Symbol/ObjectFile.h"
56#include "lldb/Target/DynamicLoader.h"
57#include "lldb/Target/Target.h"
58#include "lldb/Target/TargetList.h"
Greg Clayton2a48f522011-05-14 01:50:35 +000059#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molendaa34a0c62010-06-09 21:28:42 +000060#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000061
62// Project includes
63#include "lldb/Host/Host.h"
Peter Collingbourne99f9aa02011-06-03 20:40:38 +000064#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Jason Molendac42d2432012-07-25 03:40:06 +000065#include "Plugins/Process/Utility/StopInfoMachException.h"
Jim Ingham43c555d2012-07-04 00:35:43 +000066#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
Greg Claytonc982c762010-07-09 20:39:50 +000067#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000068#include "GDBRemoteRegisterContext.h"
69#include "ProcessGDBRemote.h"
70#include "ProcessGDBRemoteLog.h"
71#include "ThreadGDBRemote.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000072
Jason Molenda5e8534e2012-10-03 01:29:34 +000073
Greg Claytonc1422c12012-04-09 22:46:21 +000074namespace lldb
75{
76 // Provide a function that can easily dump the packet history if we know a
77 // ProcessGDBRemote * value (which we can get from logs or from debugging).
78 // We need the function in the lldb namespace so it makes it into the final
79 // executable since the LLDB shared library only exports stuff in the lldb
80 // namespace. This allows you to attach with a debugger and call this
81 // function and get the packet history dumped to a file.
82 void
83 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
84 {
Greg Claytond451c1a2012-04-13 21:24:18 +000085 lldb_private::StreamFile strm;
86 lldb_private::Error error (strm.GetFile().Open(path, lldb_private::File::eOpenOptionWrite | lldb_private::File::eOpenOptionCanCreate));
87 if (error.Success())
88 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
Greg Claytonc1422c12012-04-09 22:46:21 +000089 }
Filipe Cabecinhasc34f7762012-05-23 16:27:09 +000090}
Chris Lattner30fdc8d2010-06-08 16:52:24 +000091
Chris Lattner30fdc8d2010-06-08 16:52:24 +000092#define DEBUGSERVER_BASENAME "debugserver"
93using namespace lldb;
94using namespace lldb_private;
95
Greg Clayton7f982402013-07-15 22:54:20 +000096
97namespace {
98
99 static PropertyDefinition
100 g_properties[] =
101 {
102 { "packet-timeout" , OptionValue::eTypeUInt64 , true , 1, NULL, NULL, "Specify the default packet timeout in seconds." },
Greg Claytonef8180a2013-10-15 00:14:28 +0000103 { "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 +0000104 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
105 };
106
107 enum
108 {
Greg Claytonef8180a2013-10-15 00:14:28 +0000109 ePropertyPacketTimeout,
110 ePropertyTargetDefinitionFile
Greg Clayton7f982402013-07-15 22:54:20 +0000111 };
112
113 class PluginProperties : public Properties
114 {
115 public:
116
117 static ConstString
118 GetSettingName ()
119 {
120 return ProcessGDBRemote::GetPluginNameStatic();
121 }
122
123 PluginProperties() :
124 Properties ()
125 {
126 m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
127 m_collection_sp->Initialize(g_properties);
128 }
129
130 virtual
131 ~PluginProperties()
132 {
133 }
134
135 uint64_t
136 GetPacketTimeout()
137 {
138 const uint32_t idx = ePropertyPacketTimeout;
139 return m_collection_sp->GetPropertyAtIndexAsUInt64(NULL, idx, g_properties[idx].default_uint_value);
140 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000141
142 bool
143 SetPacketTimeout(uint64_t timeout)
144 {
145 const uint32_t idx = ePropertyPacketTimeout;
146 return m_collection_sp->SetPropertyAtIndexAsUInt64(NULL, idx, timeout);
147 }
148
Greg Claytonef8180a2013-10-15 00:14:28 +0000149 FileSpec
150 GetTargetDefinitionFile () const
151 {
152 const uint32_t idx = ePropertyTargetDefinitionFile;
153 return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
154 }
Greg Clayton7f982402013-07-15 22:54:20 +0000155 };
156
157 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
158
159 static const ProcessKDPPropertiesSP &
160 GetGlobalPluginProperties()
161 {
162 static ProcessKDPPropertiesSP g_settings_sp;
163 if (!g_settings_sp)
164 g_settings_sp.reset (new PluginProperties ());
165 return g_settings_sp;
166 }
167
168} // anonymous namespace end
169
Greg Claytonfda4fab2014-01-10 22:24:11 +0000170static bool rand_initialized = false;
171
172// TODO Randomly assigning a port is unsafe. We should get an unused
173// ephemeral port from the kernel and make sure we reserve it before passing
174// it to debugserver.
175
176#if defined (__APPLE__)
177#define LOW_PORT (IPPORT_RESERVED)
178#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
179#else
180#define LOW_PORT (1024u)
181#define HIGH_PORT (49151u)
182#endif
183
184static inline uint16_t
185get_random_port ()
186{
187 if (!rand_initialized)
188 {
189 time_t seed = time(NULL);
190
191 rand_initialized = true;
192 srand(seed);
193 }
194 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
195}
196
197
Greg Clayton57abc5d2013-05-10 21:47:16 +0000198lldb_private::ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000199ProcessGDBRemote::GetPluginNameStatic()
200{
Greg Clayton57abc5d2013-05-10 21:47:16 +0000201 static ConstString g_name("gdb-remote");
202 return g_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000203}
204
205const char *
206ProcessGDBRemote::GetPluginDescriptionStatic()
207{
208 return "GDB Remote protocol based debugging plug-in.";
209}
210
211void
212ProcessGDBRemote::Terminate()
213{
214 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
215}
216
217
Greg Claytonc3776bf2012-02-09 06:16:32 +0000218lldb::ProcessSP
219ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000220{
Greg Claytonc3776bf2012-02-09 06:16:32 +0000221 lldb::ProcessSP process_sp;
222 if (crash_file_path == NULL)
223 process_sp.reset (new ProcessGDBRemote (target, listener));
224 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000225}
226
227bool
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000228ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000229{
Greg Clayton596ed242011-10-21 21:41:45 +0000230 if (plugin_specified_by_name)
231 return true;
232
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000233 // For now we are just making sure the file exists for a given module
Greg Claytonaa149cb2011-08-11 02:48:45 +0000234 Module *exe_module = target.GetExecutableModulePointer();
235 if (exe_module)
Greg Claytonc3776bf2012-02-09 06:16:32 +0000236 {
237 ObjectFile *exe_objfile = exe_module->GetObjectFile();
238 // We can't debug core files...
239 switch (exe_objfile->GetType())
240 {
241 case ObjectFile::eTypeInvalid:
242 case ObjectFile::eTypeCoreFile:
243 case ObjectFile::eTypeDebugInfo:
244 case ObjectFile::eTypeObjectFile:
245 case ObjectFile::eTypeSharedLibrary:
246 case ObjectFile::eTypeStubLibrary:
247 return false;
248 case ObjectFile::eTypeExecutable:
249 case ObjectFile::eTypeDynamicLinker:
250 case ObjectFile::eTypeUnknown:
251 break;
252 }
Greg Claytonaa149cb2011-08-11 02:48:45 +0000253 return exe_module->GetFileSpec().Exists();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000254 }
Jim Ingham5aee1622010-08-09 23:31:02 +0000255 // However, if there is no executable module, we return true since we might be preparing to attach.
256 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000257}
258
259//----------------------------------------------------------------------
260// ProcessGDBRemote constructor
261//----------------------------------------------------------------------
262ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
263 Process (target, listener),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000264 m_flags (0),
Greg Clayton8b82f082011-04-12 05:54:46 +0000265 m_gdb_comm(false),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000266 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Claytonc982c762010-07-09 20:39:50 +0000267 m_last_stop_packet (),
Greg Clayton09c3e3d2011-12-06 04:51:14 +0000268 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000269 m_register_info (),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000270 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000271 m_async_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham455fa5c2012-11-01 01:15:33 +0000272 m_async_thread_state(eAsyncThreadNotStarted),
273 m_async_thread_state_mutex(Mutex::eMutexTypeRecursive),
Greg Clayton9e920902012-04-10 02:25:43 +0000274 m_thread_ids (),
Greg Clayton71fc2a32011-02-12 06:28:37 +0000275 m_continue_c_tids (),
276 m_continue_C_tids (),
277 m_continue_s_tids (),
278 m_continue_S_tids (),
Greg Claytonc982c762010-07-09 20:39:50 +0000279 m_max_memory_size (512),
Greg Clayton4116e932012-05-15 02:33:01 +0000280 m_addr_to_mmap_size (),
281 m_thread_create_bp_sp (),
Jim Ingham43c555d2012-07-04 00:35:43 +0000282 m_waiting_for_attach (false),
Jason Molenda5e8534e2012-10-03 01:29:34 +0000283 m_destroy_tried_resuming (false),
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000284 m_command_sp (),
285 m_breakpoint_pc_offset (0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000286{
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000287 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
288 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Inghamb1e2e842012-04-12 18:49:31 +0000289 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Greg Clayton7f982402013-07-15 22:54:20 +0000290 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
291 if (timeout_seconds > 0)
292 m_gdb_comm.SetPacketTimeout(timeout_seconds);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000293}
294
295//----------------------------------------------------------------------
296// Destructor
297//----------------------------------------------------------------------
298ProcessGDBRemote::~ProcessGDBRemote()
299{
300 // m_mach_process.UnregisterNotificationCallbacks (this);
301 Clear();
Greg Clayton1ed54f52011-10-01 00:45:15 +0000302 // We need to call finalize on the process before destroying ourselves
303 // to make sure all of the broadcaster cleanup goes as planned. If we
304 // destruct this class, then Process::~Process() might have problems
305 // trying to fully destroy the broadcaster.
306 Finalize();
Jim Ingham455fa5c2012-11-01 01:15:33 +0000307
308 // The general Finalize is going to try to destroy the process and that SHOULD
309 // shut down the async thread. However, if we don't kill it it will get stranded and
310 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
311 StopAsyncThread();
312 KillDebugserverProcess();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000313}
314
315//----------------------------------------------------------------------
316// PluginInterface
317//----------------------------------------------------------------------
Greg Clayton57abc5d2013-05-10 21:47:16 +0000318ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000319ProcessGDBRemote::GetPluginName()
320{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000321 return GetPluginNameStatic();
322}
323
324uint32_t
325ProcessGDBRemote::GetPluginVersion()
326{
327 return 1;
328}
329
Greg Claytonef8180a2013-10-15 00:14:28 +0000330bool
331ProcessGDBRemote::ParsePythonTargetDefinition(const FileSpec &target_definition_fspec)
332{
Joerg Sonnenbergere77b0422013-10-20 17:36:05 +0000333#ifndef LLDB_DISABLE_PYTHON
Greg Claytonef8180a2013-10-15 00:14:28 +0000334 ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
335 Error error;
336 lldb::ScriptInterpreterObjectSP module_object_sp (interpreter->LoadPluginModule(target_definition_fspec, error));
337 if (module_object_sp)
338 {
339 lldb::ScriptInterpreterObjectSP target_definition_sp (interpreter->GetDynamicSettings(module_object_sp,
340 &GetTarget(),
341 "gdb-server-target-definition",
342 error));
343
344 PythonDictionary target_dict(target_definition_sp);
345
346 if (target_dict)
347 {
Greg Clayton312bcbe2013-10-17 01:10:23 +0000348 PythonDictionary host_info_dict (target_dict.GetItemForKey("host-info"));
349 if (host_info_dict)
350 {
351 ArchSpec host_arch (host_info_dict.GetItemForKeyAsString(PythonString("triple")));
352
353 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture()))
354 {
355 GetTarget().SetArchitecture(host_arch);
356 }
357
358 }
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000359 m_breakpoint_pc_offset = target_dict.GetItemForKeyAsInteger("breakpoint-pc-offset", 0);
360
Greg Clayton312bcbe2013-10-17 01:10:23 +0000361 if (m_register_info.SetRegisterInfo (target_dict, GetTarget().GetArchitecture().GetByteOrder()) > 0)
Greg Claytonef8180a2013-10-15 00:14:28 +0000362 {
363 return true;
364 }
365 }
366 }
Joerg Sonnenbergere77b0422013-10-20 17:36:05 +0000367#endif
Greg Claytonef8180a2013-10-15 00:14:28 +0000368 return false;
369}
370
371
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000372void
Greg Clayton513c26c2011-01-29 07:10:55 +0000373ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000374{
Greg Clayton513c26c2011-01-29 07:10:55 +0000375 if (!force && m_register_info.GetNumRegisters() > 0)
376 return;
377
378 char packet[128];
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000379 m_register_info.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000380 uint32_t reg_offset = 0;
381 uint32_t reg_num = 0;
Greg Clayton23f59502012-07-17 03:23:13 +0000382 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Greg Clayton576d8832011-03-22 04:00:09 +0000383 response_type == StringExtractorGDBRemote::eResponse;
384 ++reg_num)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000385 {
Greg Clayton513c26c2011-01-29 07:10:55 +0000386 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
Andy Gibbsa297a972013-06-19 19:04:53 +0000387 assert (packet_len < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000388 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000389 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000390 {
Greg Clayton576d8832011-03-22 04:00:09 +0000391 response_type = response.GetResponseType();
392 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000393 {
394 std::string name;
395 std::string value;
396 ConstString reg_name;
397 ConstString alt_name;
398 ConstString set_name;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000399 std::vector<uint32_t> value_regs;
400 std::vector<uint32_t> invalidate_regs;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000401 RegisterInfo reg_info = { NULL, // Name
402 NULL, // Alt name
403 0, // byte size
404 reg_offset, // offset
405 eEncodingUint, // encoding
406 eFormatHex, // formate
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000407 {
408 LLDB_INVALID_REGNUM, // GCC reg num
409 LLDB_INVALID_REGNUM, // DWARF reg num
410 LLDB_INVALID_REGNUM, // generic reg num
Jason Molendafbcb7f22010-09-10 07:49:16 +0000411 reg_num, // GDB reg num
412 reg_num // native register number
Greg Clayton435d85a2012-02-29 19:27:27 +0000413 },
414 NULL,
415 NULL
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000416 };
417
418 while (response.GetNameColonValue(name, value))
419 {
420 if (name.compare("name") == 0)
421 {
422 reg_name.SetCString(value.c_str());
423 }
424 else if (name.compare("alt-name") == 0)
425 {
426 alt_name.SetCString(value.c_str());
427 }
428 else if (name.compare("bitsize") == 0)
429 {
430 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
431 }
432 else if (name.compare("offset") == 0)
433 {
434 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda743e86a2010-06-11 23:44:18 +0000435 if (reg_offset != offset)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000436 {
437 reg_offset = offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000438 }
439 }
440 else if (name.compare("encoding") == 0)
441 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000442 const Encoding encoding = Args::StringToEncoding (value.c_str());
443 if (encoding != eEncodingInvalid)
444 reg_info.encoding = encoding;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000445 }
446 else if (name.compare("format") == 0)
447 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000448 Format format = eFormatInvalid;
449 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
450 reg_info.format = format;
451 else if (value.compare("binary") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000452 reg_info.format = eFormatBinary;
453 else if (value.compare("decimal") == 0)
454 reg_info.format = eFormatDecimal;
455 else if (value.compare("hex") == 0)
456 reg_info.format = eFormatHex;
457 else if (value.compare("float") == 0)
458 reg_info.format = eFormatFloat;
459 else if (value.compare("vector-sint8") == 0)
460 reg_info.format = eFormatVectorOfSInt8;
461 else if (value.compare("vector-uint8") == 0)
462 reg_info.format = eFormatVectorOfUInt8;
463 else if (value.compare("vector-sint16") == 0)
464 reg_info.format = eFormatVectorOfSInt16;
465 else if (value.compare("vector-uint16") == 0)
466 reg_info.format = eFormatVectorOfUInt16;
467 else if (value.compare("vector-sint32") == 0)
468 reg_info.format = eFormatVectorOfSInt32;
469 else if (value.compare("vector-uint32") == 0)
470 reg_info.format = eFormatVectorOfUInt32;
471 else if (value.compare("vector-float32") == 0)
472 reg_info.format = eFormatVectorOfFloat32;
473 else if (value.compare("vector-uint128") == 0)
474 reg_info.format = eFormatVectorOfUInt128;
475 }
476 else if (name.compare("set") == 0)
477 {
478 set_name.SetCString(value.c_str());
479 }
480 else if (name.compare("gcc") == 0)
481 {
482 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
483 }
484 else if (name.compare("dwarf") == 0)
485 {
486 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
487 }
488 else if (name.compare("generic") == 0)
489 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000490 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000491 }
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000492 else if (name.compare("container-regs") == 0)
493 {
494 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
495 value_pair.second = value;
496 do
497 {
498 value_pair = value_pair.second.split(',');
499 if (!value_pair.first.empty())
500 {
Greg Clayton0ba20242013-01-21 23:32:42 +0000501 uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
502 if (reg != LLDB_INVALID_REGNUM)
503 value_regs.push_back (reg);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000504 }
505 } while (!value_pair.second.empty());
506 }
507 else if (name.compare("invalidate-regs") == 0)
508 {
509 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
510 value_pair.second = value;
511 do
512 {
513 value_pair = value_pair.second.split(',');
514 if (!value_pair.first.empty())
515 {
Greg Clayton0ba20242013-01-21 23:32:42 +0000516 uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
517 if (reg != LLDB_INVALID_REGNUM)
518 invalidate_regs.push_back (reg);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000519 }
520 } while (!value_pair.second.empty());
521 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000522 }
523
Jason Molenda743e86a2010-06-11 23:44:18 +0000524 reg_info.byte_offset = reg_offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000525 assert (reg_info.byte_size != 0);
526 reg_offset += reg_info.byte_size;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000527 if (!value_regs.empty())
528 {
529 value_regs.push_back(LLDB_INVALID_REGNUM);
530 reg_info.value_regs = value_regs.data();
531 }
532 if (!invalidate_regs.empty())
533 {
534 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
535 reg_info.invalidate_regs = invalidate_regs.data();
536 }
537
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000538 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
539 }
Todd Fiala1a634402014-01-08 07:52:40 +0000540 else
541 {
542 break; // ensure exit before reg_num is incremented
543 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000544 }
545 else
546 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000547 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000548 }
549 }
550
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000551 // Check if qHostInfo specified a specific packet timeout for this connection.
552 // If so then lets update our setting so the user knows what the timeout is
553 // and can see it.
554 const uint32_t host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
555 if (host_packet_timeout)
556 {
557 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout);
558 }
559
560
Greg Claytonef8180a2013-10-15 00:14:28 +0000561 if (reg_num == 0)
562 {
563 FileSpec target_definition_fspec = GetGlobalPluginProperties()->GetTargetDefinitionFile ();
Greg Clayton312bcbe2013-10-17 01:10:23 +0000564
565 if (target_definition_fspec)
Greg Claytonef8180a2013-10-15 00:14:28 +0000566 {
Greg Clayton312bcbe2013-10-17 01:10:23 +0000567 // See if we can get register definitions from a python file
568 if (ParsePythonTargetDefinition (target_definition_fspec))
569 return;
Greg Claytonef8180a2013-10-15 00:14:28 +0000570 }
571 }
572
Johnny Chen2fa9de12012-05-14 18:44:23 +0000573 // We didn't get anything if the accumulated reg_num is zero. See if we are
574 // debugging ARM and fill with a hard coded register set until we can get an
575 // updated debugserver down on the devices.
576 // On the other hand, if the accumulated reg_num is positive, see if we can
577 // add composite registers to the existing primordial ones.
578 bool from_scratch = (reg_num == 0);
579
580 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000581 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
582 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
583
584 // Use the process' architecture instead of the host arch, if available
585 ArchSpec remote_arch;
586 if (remote_process_arch.IsValid ())
587 remote_arch = remote_process_arch;
588 else
589 remote_arch = remote_host_arch;
590
Johnny Chen2fa9de12012-05-14 18:44:23 +0000591 if (!target_arch.IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000592 {
Johnny Chen2fa9de12012-05-14 18:44:23 +0000593 if (remote_arch.IsValid()
594 && remote_arch.GetMachine() == llvm::Triple::arm
595 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
596 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000597 }
Johnny Chen2fa9de12012-05-14 18:44:23 +0000598 else if (target_arch.GetMachine() == llvm::Triple::arm)
599 {
600 m_register_info.HardcodeARMRegisters(from_scratch);
601 }
602
603 // At this point, we can finalize our register info.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000604 m_register_info.Finalize ();
605}
606
607Error
608ProcessGDBRemote::WillLaunch (Module* module)
609{
610 return WillLaunchOrAttach ();
611}
612
613Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000614ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000615{
616 return WillLaunchOrAttach ();
617}
618
619Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000620ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000621{
622 return WillLaunchOrAttach ();
623}
624
625Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000626ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +0000627{
628 Error error (WillLaunchOrAttach ());
629
630 if (error.Fail())
631 return error;
632
Greg Clayton2289fa42011-04-30 01:09:13 +0000633 error = ConnectToDebugserver (remote_url);
Greg Claytonb766a732011-02-04 01:58:07 +0000634
635 if (error.Fail())
636 return error;
637 StartAsyncThread ();
638
Greg Claytonc574ede2011-03-10 02:26:48 +0000639 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonb766a732011-02-04 01:58:07 +0000640 if (pid == LLDB_INVALID_PROCESS_ID)
641 {
642 // We don't have a valid process ID, so note that we are connected
643 // and could now request to launch or attach, or get remote process
644 // listings...
645 SetPrivateState (eStateConnected);
646 }
647 else
648 {
649 // We have a valid process
650 SetID (pid);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000651 GetThreadList();
Greg Clayton3dedae12013-12-06 21:45:27 +0000652 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false) == GDBRemoteCommunication::PacketResult::Success)
Greg Claytonb766a732011-02-04 01:58:07 +0000653 {
Jason Molendac62bd7b2013-12-21 05:20:36 +0000654 if (!m_target.GetArchitecture().IsValid())
655 {
656 if (m_gdb_comm.GetProcessArchitecture().IsValid())
657 {
658 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
659 }
660 else
661 {
662 m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
663 }
Carlo Kok74389122013-10-14 07:09:13 +0000664 }
665
Greg Claytondd0e5a52011-06-02 22:22:38 +0000666 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytonb766a732011-02-04 01:58:07 +0000667 if (state == eStateStopped)
668 {
669 SetPrivateState (state);
670 }
671 else
Daniel Malead01b2952012-11-29 21:49:15 +0000672 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 +0000673 }
674 else
Daniel Malead01b2952012-11-29 21:49:15 +0000675 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 +0000676 }
Jason Molenda16d127c2012-05-03 22:37:30 +0000677
678 if (error.Success()
679 && !GetTarget().GetArchitecture().IsValid()
680 && m_gdb_comm.GetHostArchitecture().IsValid())
681 {
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000682 // Prefer the *process'* architecture over that of the *host*, if available.
683 if (m_gdb_comm.GetProcessArchitecture().IsValid())
684 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
685 else
686 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molenda16d127c2012-05-03 22:37:30 +0000687 }
688
Greg Claytonb766a732011-02-04 01:58:07 +0000689 return error;
690}
691
692Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000693ProcessGDBRemote::WillLaunchOrAttach ()
694{
695 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000696 m_stdio_communication.Clear ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000697 return error;
698}
699
700//----------------------------------------------------------------------
701// Process Control
702//----------------------------------------------------------------------
703Error
Jean-Daniel Dupas7782de92013-12-09 22:52:50 +0000704ProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000705{
Greg Clayton4957bf62010-09-30 21:49:03 +0000706 Error error;
Greg Clayton982c9762011-11-03 21:22:33 +0000707
708 uint32_t launch_flags = launch_info.GetFlags().Get();
709 const char *stdin_path = NULL;
710 const char *stdout_path = NULL;
711 const char *stderr_path = NULL;
712 const char *working_dir = launch_info.GetWorkingDirectory();
713
714 const ProcessLaunchInfo::FileAction *file_action;
715 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
716 if (file_action)
717 {
718 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
719 stdin_path = file_action->GetPath();
720 }
721 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
722 if (file_action)
723 {
724 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
725 stdout_path = file_action->GetPath();
726 }
727 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
728 if (file_action)
729 {
730 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
731 stderr_path = file_action->GetPath();
732 }
733
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000734 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
735 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
736 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton5160ce52013-03-27 23:08:40 +0000737 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000738
Greg Clayton982c9762011-11-03 21:22:33 +0000739 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000740 if (object_file)
741 {
Greg Clayton71337622011-02-24 22:24:29 +0000742 // Make sure we aren't already connected?
743 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000744 {
Greg Clayton91a9b2472013-12-04 19:19:12 +0000745 error = LaunchAndConnectToDebugserver (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000746 }
747
748 if (error.Success())
749 {
750 lldb_utility::PseudoTerminal pty;
751 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000752
753 // If the debugserver is local and we aren't disabling STDIO, lets use
754 // a pseudo terminal to instead of relying on the 'O' packets for stdio
755 // since 'O' packets can really slow down debugging if the inferior
756 // does a lot of output.
Greg Claytonf58c2692011-06-24 22:32:10 +0000757 PlatformSP platform_sp (m_target.GetPlatform());
758 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Clayton71337622011-02-24 22:24:29 +0000759 {
760 const char *slave_name = NULL;
761 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000762 {
Greg Clayton71337622011-02-24 22:24:29 +0000763 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
764 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000765 }
Greg Clayton71337622011-02-24 22:24:29 +0000766 if (stdin_path == NULL)
767 stdin_path = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000768
Greg Clayton71337622011-02-24 22:24:29 +0000769 if (stdout_path == NULL)
770 stdout_path = slave_name;
771
772 if (stderr_path == NULL)
773 stderr_path = slave_name;
774 }
775
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000776 // Set STDIN to /dev/null if we want STDIO disabled or if either
777 // STDOUT or STDERR have been set to something and STDIN hasn't
778 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000779 stdin_path = "/dev/null";
780
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000781 // Set STDOUT to /dev/null if we want STDIO disabled or if either
782 // STDIN or STDERR have been set to something and STDOUT hasn't
783 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000784 stdout_path = "/dev/null";
785
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000786 // Set STDERR to /dev/null if we want STDIO disabled or if either
787 // STDIN or STDOUT have been set to something and STDERR hasn't
788 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000789 stderr_path = "/dev/null";
790
791 if (stdin_path)
792 m_gdb_comm.SetSTDIN (stdin_path);
793 if (stdout_path)
794 m_gdb_comm.SetSTDOUT (stdout_path);
795 if (stderr_path)
796 m_gdb_comm.SetSTDERR (stderr_path);
797
798 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
799
Greg Claytonc4103b32011-05-08 04:53:50 +0000800 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Clayton71337622011-02-24 22:24:29 +0000801
802 if (working_dir && working_dir[0])
803 {
804 m_gdb_comm.SetWorkingDir (working_dir);
805 }
806
807 // Send the environment and the program + arguments after we connect
Greg Clayton982c9762011-11-03 21:22:33 +0000808 const Args &environment = launch_info.GetEnvironmentEntries();
809 if (environment.GetArgumentCount())
Greg Clayton71337622011-02-24 22:24:29 +0000810 {
Greg Clayton982c9762011-11-03 21:22:33 +0000811 size_t num_environment_entries = environment.GetArgumentCount();
812 for (size_t i=0; i<num_environment_entries; ++i)
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000813 {
Greg Clayton982c9762011-11-03 21:22:33 +0000814 const char *env_entry = environment.GetArgumentAtIndex(i);
815 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Clayton71337622011-02-24 22:24:29 +0000816 break;
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000817 }
Greg Clayton71337622011-02-24 22:24:29 +0000818 }
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000819
Greg Claytonc574ede2011-03-10 02:26:48 +0000820 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Claytonfbb76342013-11-20 21:07:01 +0000821 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000822 if (arg_packet_err == 0)
823 {
824 std::string error_str;
Greg Claytonc574ede2011-03-10 02:26:48 +0000825 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000826 {
Greg Claytonc574ede2011-03-10 02:26:48 +0000827 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000828 }
829 else
830 {
Greg Clayton71337622011-02-24 22:24:29 +0000831 error.SetErrorString (error_str.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000832 }
Greg Clayton71337622011-02-24 22:24:29 +0000833 }
834 else
835 {
Greg Clayton86edbf42011-10-26 00:56:27 +0000836 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Clayton71337622011-02-24 22:24:29 +0000837 }
Greg Clayton8b45bee2011-08-10 22:05:39 +0000838
839 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000840
Greg Clayton71337622011-02-24 22:24:29 +0000841 if (GetID() == LLDB_INVALID_PROCESS_ID)
842 {
Johnny Chen4c1e9202011-08-09 18:56:45 +0000843 if (log)
844 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton71337622011-02-24 22:24:29 +0000845 KillDebugserverProcess ();
846 return error;
847 }
848
Greg Clayton3dedae12013-12-06 21:45:27 +0000849 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton71337622011-02-24 22:24:29 +0000850 {
Jason Molendac62bd7b2013-12-21 05:20:36 +0000851 if (!m_target.GetArchitecture().IsValid())
852 {
853 if (m_gdb_comm.GetProcessArchitecture().IsValid())
854 {
855 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
856 }
857 else
858 {
859 m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
860 }
Carlo Kok74389122013-10-14 07:09:13 +0000861 }
862
Greg Claytondd0e5a52011-06-02 22:22:38 +0000863 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Clayton71337622011-02-24 22:24:29 +0000864
865 if (!disable_stdio)
866 {
867 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Claytonee95ed52011-11-17 22:14:31 +0000868 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Clayton71337622011-02-24 22:24:29 +0000869 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000870 }
871 }
Greg Claytonc235ac72011-08-09 05:20:29 +0000872 else
873 {
Johnny Chen4c1e9202011-08-09 18:56:45 +0000874 if (log)
875 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytonc235ac72011-08-09 05:20:29 +0000876 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000877 }
878 else
879 {
880 // Set our user ID to an invalid process ID.
881 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton982c9762011-11-03 21:22:33 +0000882 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
883 exe_module->GetFileSpec().GetFilename().AsCString(),
884 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000885 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000886 return error;
Greg Clayton4957bf62010-09-30 21:49:03 +0000887
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000888}
889
890
891Error
Greg Claytonb766a732011-02-04 01:58:07 +0000892ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000893{
894 Error error;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000895 // Only connect if we have a valid connect URL
896
897 if (connect_url && connect_url[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000898 {
Greg Clayton00fe87b2013-12-05 22:58:22 +0000899 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
900 if (conn_ap.get())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000901 {
Greg Clayton00fe87b2013-12-05 22:58:22 +0000902 const uint32_t max_retry_count = 50;
903 uint32_t retry_count = 0;
904 while (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000905 {
Greg Clayton00fe87b2013-12-05 22:58:22 +0000906 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
907 {
908 m_gdb_comm.SetConnection (conn_ap.release());
909 break;
910 }
911 else if (error.WasInterrupted())
912 {
913 // If we were interrupted, don't keep retrying.
914 break;
915 }
916
917 retry_count++;
918
919 if (retry_count >= max_retry_count)
920 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000921
Greg Clayton00fe87b2013-12-05 22:58:22 +0000922 usleep (100000);
923 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000924 }
925 }
926
927 if (!m_gdb_comm.IsConnected())
928 {
929 if (error.Success())
930 error.SetErrorString("not connected to remote gdb server");
931 return error;
932 }
933
Greg Clayton32e0a752011-03-30 18:16:51 +0000934 // We always seem to be able to open a connection to a local port
935 // so we need to make sure we can then send data to it. If we can't
936 // then we aren't actually connected to anything, so try and do the
937 // handshake with the remote GDB server and make sure that goes
938 // alright.
Greg Claytonfb909312013-11-23 01:58:15 +0000939 if (!m_gdb_comm.HandshakeWithServer (&error))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000940 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000941 m_gdb_comm.Disconnect();
942 if (error.Success())
943 error.SetErrorString("not connected to remote gdb server");
944 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000945 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000946 m_gdb_comm.GetThreadSuffixSupported ();
Greg Clayton44633992012-04-10 03:22:03 +0000947 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +0000948 m_gdb_comm.GetHostInfo ();
949 m_gdb_comm.GetVContSupported ('c');
Jim Inghamcd16df92012-07-20 21:37:13 +0000950 m_gdb_comm.GetVAttachOrWaitSupported();
Jim Ingham03afad82012-07-02 05:40:07 +0000951
952 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
953 for (size_t idx = 0; idx < num_cmds; idx++)
954 {
955 StringExtractorGDBRemote response;
Jim Ingham03afad82012-07-02 05:40:07 +0000956 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
957 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000958 return error;
959}
960
961void
962ProcessGDBRemote::DidLaunchOrAttach ()
963{
Greg Clayton5160ce52013-03-27 23:08:40 +0000964 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +0000965 if (log)
966 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton93d3c8332011-02-16 04:46:07 +0000967 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000968 {
Greg Clayton513c26c2011-01-29 07:10:55 +0000969 BuildDynamicRegisterInfo (false);
Greg Clayton3af9ea52010-11-18 05:57:03 +0000970
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000971 // See if the GDB server supports the qHostInfo information
Greg Clayton0d0c12a2011-02-09 03:09:55 +0000972
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000973 ArchSpec gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
974
975 // See if the GDB server supports the qProcessInfo packet, if so
976 // prefer that over the Host information as it will be more specific
977 // to our process.
978
979 if (m_gdb_comm.GetProcessArchitecture().IsValid())
980 gdb_remote_arch = m_gdb_comm.GetProcessArchitecture();
981
Greg Claytond314e812011-03-23 00:09:55 +0000982 if (gdb_remote_arch.IsValid())
Greg Clayton0d0c12a2011-02-09 03:09:55 +0000983 {
Greg Claytond314e812011-03-23 00:09:55 +0000984 ArchSpec &target_arch = GetTarget().GetArchitecture();
985
986 if (target_arch.IsValid())
987 {
988 // If the remote host is ARM and we have apple as the vendor, then
989 // ARM executables and shared libraries can have mixed ARM architectures.
990 // You can have an armv6 executable, and if the host is armv7, then the
991 // system will load the best possible architecture for all shared libraries
992 // it has, so we really need to take the remote host architecture as our
993 // defacto architecture in this case.
994
995 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
996 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
997 {
998 target_arch = gdb_remote_arch;
999 }
1000 else
1001 {
1002 // Fill in what is missing in the triple
1003 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
1004 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton70b57652011-05-15 01:25:55 +00001005 if (target_triple.getVendorName().size() == 0)
1006 {
Greg Claytond314e812011-03-23 00:09:55 +00001007 target_triple.setVendor (remote_triple.getVendor());
1008
Greg Clayton70b57652011-05-15 01:25:55 +00001009 if (target_triple.getOSName().size() == 0)
1010 {
1011 target_triple.setOS (remote_triple.getOS());
Greg Claytond314e812011-03-23 00:09:55 +00001012
Greg Clayton70b57652011-05-15 01:25:55 +00001013 if (target_triple.getEnvironmentName().size() == 0)
1014 target_triple.setEnvironment (remote_triple.getEnvironment());
1015 }
1016 }
Greg Claytond314e812011-03-23 00:09:55 +00001017 }
1018 }
1019 else
1020 {
1021 // The target doesn't have a valid architecture yet, set it from
1022 // the architecture we got from the remote GDB server
1023 target_arch = gdb_remote_arch;
1024 }
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001025 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001026 }
1027}
1028
1029void
1030ProcessGDBRemote::DidLaunch ()
1031{
1032 DidLaunchOrAttach ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001033}
1034
1035Error
Greg Claytonc982c762010-07-09 20:39:50 +00001036ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001037{
Han Ming Ong84647042012-02-25 01:07:38 +00001038 ProcessAttachInfo attach_info;
1039 return DoAttachToProcessWithID(attach_pid, attach_info);
1040}
1041
1042Error
1043ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1044{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001045 Error error;
1046 // Clear out and clean up from any current state
1047 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001048 if (attach_pid != LLDB_INVALID_PROCESS_ID)
1049 {
Greg Clayton71337622011-02-24 22:24:29 +00001050 // Make sure we aren't already connected?
1051 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001052 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001053 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001054
1055 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001056 {
Greg Clayton71337622011-02-24 22:24:29 +00001057 const char *error_string = error.AsCString();
1058 if (error_string == NULL)
1059 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1060
1061 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001062 }
Greg Clayton71337622011-02-24 22:24:29 +00001063 }
1064
1065 if (error.Success())
1066 {
1067 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001068 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Greg Clayton3b608422011-11-19 02:11:30 +00001069 SetID (attach_pid);
Greg Clayton71337622011-02-24 22:24:29 +00001070 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001071 }
1072 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001073 return error;
1074}
1075
1076size_t
1077ProcessGDBRemote::AttachInputReaderCallback
1078(
1079 void *baton,
1080 InputReader *reader,
1081 lldb::InputReaderAction notification,
1082 const char *bytes,
1083 size_t bytes_len
1084)
1085{
1086 if (notification == eInputReaderGotToken)
1087 {
1088 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
1089 if (gdb_process->m_waiting_for_attach)
1090 gdb_process->m_waiting_for_attach = false;
1091 reader->SetIsDone(true);
1092 return 1;
1093 }
1094 return 0;
1095}
1096
1097Error
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001098ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001099{
1100 Error error;
1101 // Clear out and clean up from any current state
1102 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001103
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001104 if (process_name && process_name[0])
1105 {
Greg Clayton71337622011-02-24 22:24:29 +00001106 // Make sure we aren't already connected?
1107 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001108 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001109 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001110
Greg Clayton71337622011-02-24 22:24:29 +00001111 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001112 {
Greg Clayton71337622011-02-24 22:24:29 +00001113 const char *error_string = error.AsCString();
1114 if (error_string == NULL)
1115 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001116
Greg Clayton71337622011-02-24 22:24:29 +00001117 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001118 }
Greg Clayton71337622011-02-24 22:24:29 +00001119 }
1120
1121 if (error.Success())
1122 {
1123 StreamString packet;
1124
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00001125 if (attach_info.GetWaitForLaunch())
Jim Inghamcd16df92012-07-20 21:37:13 +00001126 {
1127 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1128 {
1129 packet.PutCString ("vAttachWait");
1130 }
1131 else
1132 {
1133 if (attach_info.GetIgnoreExisting())
1134 packet.PutCString("vAttachWait");
1135 else
1136 packet.PutCString ("vAttachOrWait");
1137 }
1138 }
Greg Clayton71337622011-02-24 22:24:29 +00001139 else
1140 packet.PutCString("vAttachName");
1141 packet.PutChar(';');
1142 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1143
1144 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1145
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001146 }
1147 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001148 return error;
1149}
1150
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001151
Greg Claytonfbb76342013-11-20 21:07:01 +00001152bool
1153ProcessGDBRemote::SetExitStatus (int exit_status, const char *cstr)
1154{
1155 m_gdb_comm.Disconnect();
1156 return Process::SetExitStatus (exit_status, cstr);
1157}
1158
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001159void
1160ProcessGDBRemote::DidAttach ()
1161{
Greg Claytonb766a732011-02-04 01:58:07 +00001162 DidLaunchOrAttach ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001163}
1164
Greg Clayton90ba8112012-12-05 00:16:59 +00001165
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001166Error
1167ProcessGDBRemote::WillResume ()
1168{
Greg Clayton71fc2a32011-02-12 06:28:37 +00001169 m_continue_c_tids.clear();
1170 m_continue_C_tids.clear();
1171 m_continue_s_tids.clear();
1172 m_continue_S_tids.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001173 return Error();
1174}
1175
1176Error
1177ProcessGDBRemote::DoResume ()
1178{
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001179 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001180 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001181 if (log)
1182 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytone5219662010-12-03 06:02:24 +00001183
1184 Listener listener ("gdb-remote.resume-packet-sent");
1185 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1186 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00001187 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1188
Greg Claytond1d06e42013-04-20 00:27:58 +00001189 const size_t num_threads = GetThreadList().GetSize();
1190
Greg Clayton71fc2a32011-02-12 06:28:37 +00001191 StreamString continue_packet;
1192 bool continue_packet_error = false;
1193 if (m_gdb_comm.HasAnyVContSupport ())
1194 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001195 if (m_continue_c_tids.size() == num_threads)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001196 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001197 // All threads are continuing, just send a "c" packet
1198 continue_packet.PutCString ("c");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001199 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001200 else
1201 {
1202 continue_packet.PutCString ("vCont");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001203
Greg Claytond1d06e42013-04-20 00:27:58 +00001204 if (!m_continue_c_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001205 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001206 if (m_gdb_comm.GetVContSupported ('c'))
1207 {
1208 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)
1209 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1210 }
1211 else
1212 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001213 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001214
1215 if (!continue_packet_error && !m_continue_C_tids.empty())
1216 {
1217 if (m_gdb_comm.GetVContSupported ('C'))
1218 {
1219 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)
1220 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1221 }
1222 else
1223 continue_packet_error = true;
1224 }
Greg Claytone5219662010-12-03 06:02:24 +00001225
Greg Claytond1d06e42013-04-20 00:27:58 +00001226 if (!continue_packet_error && !m_continue_s_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001227 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001228 if (m_gdb_comm.GetVContSupported ('s'))
1229 {
1230 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)
1231 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1232 }
1233 else
1234 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001235 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001236
1237 if (!continue_packet_error && !m_continue_S_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001238 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001239 if (m_gdb_comm.GetVContSupported ('S'))
1240 {
1241 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)
1242 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1243 }
1244 else
1245 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001246 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001247
1248 if (continue_packet_error)
1249 continue_packet.GetString().clear();
Greg Clayton71fc2a32011-02-12 06:28:37 +00001250 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001251 }
1252 else
1253 continue_packet_error = true;
1254
1255 if (continue_packet_error)
1256 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001257 // Either no vCont support, or we tried to use part of the vCont
1258 // packet that wasn't supported by the remote GDB server.
1259 // We need to try and make a simple packet that can do our continue
Greg Clayton71fc2a32011-02-12 06:28:37 +00001260 const size_t num_continue_c_tids = m_continue_c_tids.size();
1261 const size_t num_continue_C_tids = m_continue_C_tids.size();
1262 const size_t num_continue_s_tids = m_continue_s_tids.size();
1263 const size_t num_continue_S_tids = m_continue_S_tids.size();
1264 if (num_continue_c_tids > 0)
1265 {
1266 if (num_continue_c_tids == num_threads)
1267 {
1268 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001269 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001270 continue_packet.PutChar ('c');
1271 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001272 }
1273 else if (num_continue_c_tids == 1 &&
1274 num_continue_C_tids == 0 &&
1275 num_continue_s_tids == 0 &&
1276 num_continue_S_tids == 0 )
1277 {
1278 // Only one thread is continuing
Greg Clayton8b82f082011-04-12 05:54:46 +00001279 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001280 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001281 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001282 }
1283 }
1284
Greg Clayton0c74e782011-06-24 03:21:43 +00001285 if (continue_packet_error && num_continue_C_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001286 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001287 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1288 num_continue_C_tids > 0 &&
1289 num_continue_s_tids == 0 &&
1290 num_continue_S_tids == 0 )
Greg Clayton71fc2a32011-02-12 06:28:37 +00001291 {
1292 const int continue_signo = m_continue_C_tids.front().second;
Greg Clayton0c74e782011-06-24 03:21:43 +00001293 // Only one thread is continuing
Greg Clayton71fc2a32011-02-12 06:28:37 +00001294 if (num_continue_C_tids > 1)
1295 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001296 // More that one thread with a signal, yet we don't have
1297 // vCont support and we are being asked to resume each
1298 // thread with a signal, we need to make sure they are
1299 // all the same signal, or we can't issue the continue
1300 // accurately with the current support...
1301 if (num_continue_C_tids > 1)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001302 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001303 continue_packet_error = false;
1304 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1305 {
1306 if (m_continue_C_tids[i].second != continue_signo)
1307 continue_packet_error = true;
1308 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001309 }
Greg Clayton0c74e782011-06-24 03:21:43 +00001310 if (!continue_packet_error)
1311 m_gdb_comm.SetCurrentThreadForRun (-1);
1312 }
1313 else
1314 {
1315 // Set the continue thread ID
1316 continue_packet_error = false;
1317 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001318 }
1319 if (!continue_packet_error)
1320 {
1321 // Add threads continuing with the same signo...
Greg Clayton71fc2a32011-02-12 06:28:37 +00001322 continue_packet.Printf("C%2.2x", continue_signo);
1323 }
1324 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001325 }
1326
Greg Clayton0c74e782011-06-24 03:21:43 +00001327 if (continue_packet_error && num_continue_s_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001328 {
1329 if (num_continue_s_tids == num_threads)
1330 {
1331 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001332 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001333 continue_packet.PutChar ('s');
1334 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001335 }
1336 else if (num_continue_c_tids == 0 &&
1337 num_continue_C_tids == 0 &&
1338 num_continue_s_tids == 1 &&
1339 num_continue_S_tids == 0 )
1340 {
1341 // Only one thread is stepping
Greg Clayton8b82f082011-04-12 05:54:46 +00001342 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001343 continue_packet.PutChar ('s');
Greg Clayton0c74e782011-06-24 03:21:43 +00001344 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001345 }
1346 }
1347
1348 if (!continue_packet_error && num_continue_S_tids > 0)
1349 {
1350 if (num_continue_S_tids == num_threads)
1351 {
1352 const int step_signo = m_continue_S_tids.front().second;
1353 // Are all threads trying to step with the same signal?
Greg Clayton0c74e782011-06-24 03:21:43 +00001354 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001355 if (num_continue_S_tids > 1)
1356 {
1357 for (size_t i=1; i<num_threads; ++i)
1358 {
1359 if (m_continue_S_tids[i].second != step_signo)
1360 continue_packet_error = true;
1361 }
1362 }
1363 if (!continue_packet_error)
1364 {
1365 // Add threads stepping with the same signo...
Greg Clayton8b82f082011-04-12 05:54:46 +00001366 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001367 continue_packet.Printf("S%2.2x", step_signo);
1368 }
1369 }
1370 else if (num_continue_c_tids == 0 &&
1371 num_continue_C_tids == 0 &&
1372 num_continue_s_tids == 0 &&
1373 num_continue_S_tids == 1 )
1374 {
1375 // Only one thread is stepping with signal
Greg Clayton8b82f082011-04-12 05:54:46 +00001376 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001377 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Clayton0c74e782011-06-24 03:21:43 +00001378 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001379 }
1380 }
1381 }
1382
1383 if (continue_packet_error)
1384 {
1385 error.SetErrorString ("can't make continue packet for this resume");
1386 }
1387 else
1388 {
1389 EventSP event_sp;
1390 TimeValue timeout;
1391 timeout = TimeValue::Now();
1392 timeout.OffsetWithSeconds (5);
Jim Inghamb1e2e842012-04-12 18:49:31 +00001393 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1394 {
1395 error.SetErrorString ("Trying to resume but the async thread is dead.");
1396 if (log)
1397 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1398 return error;
1399 }
1400
Greg Clayton71fc2a32011-02-12 06:28:37 +00001401 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1402
1403 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Inghamb1e2e842012-04-12 18:49:31 +00001404 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001405 error.SetErrorString("Resume timed out.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00001406 if (log)
1407 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1408 }
1409 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1410 {
1411 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1412 if (log)
1413 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1414 return error;
1415 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001416 }
Greg Claytone5219662010-12-03 06:02:24 +00001417 }
1418
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001419 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001420}
1421
Greg Clayton9e920902012-04-10 02:25:43 +00001422void
1423ProcessGDBRemote::ClearThreadIDList ()
1424{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001425 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001426 m_thread_ids.clear();
1427}
1428
1429bool
1430ProcessGDBRemote::UpdateThreadIDList ()
1431{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001432 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001433 bool sequence_mutex_unavailable = false;
1434 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1435 if (sequence_mutex_unavailable)
1436 {
Greg Clayton9e920902012-04-10 02:25:43 +00001437 return false; // We just didn't get the list
1438 }
1439 return true;
1440}
1441
Greg Clayton9fc13552012-04-10 00:18:59 +00001442bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001443ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001444{
1445 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +00001446 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Clayton73b472d2010-10-27 03:32:59 +00001447 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +00001448 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton9e920902012-04-10 02:25:43 +00001449
1450 size_t num_thread_ids = m_thread_ids.size();
1451 // The "m_thread_ids" thread ID list should always be updated after each stop
1452 // reply packet, but in case it isn't, update it here.
1453 if (num_thread_ids == 0)
1454 {
1455 if (!UpdateThreadIDList ())
1456 return false;
1457 num_thread_ids = m_thread_ids.size();
1458 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001459
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001460 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001461 if (num_thread_ids > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001462 {
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001463 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001464 {
Greg Clayton9e920902012-04-10 02:25:43 +00001465 tid_t tid = m_thread_ids[i];
Greg Clayton160c9d82013-05-01 21:54:04 +00001466 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001467 if (!thread_sp)
Jim Inghamdee1bc92013-06-22 00:27:45 +00001468 {
Jim Ingham4f465cf2012-10-10 18:32:14 +00001469 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001470 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1471 log->Printf(
1472 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1473 __FUNCTION__,
1474 thread_sp.get(),
1475 thread_sp->GetID());
1476 }
1477 else
1478 {
1479 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1480 log->Printf(
1481 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
1482 __FUNCTION__,
1483 thread_sp.get(),
1484 thread_sp->GetID());
1485 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001486 new_thread_list.AddThread(thread_sp);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001487 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001488 }
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001489
1490 // Whatever that is left in old_thread_list_copy are not
1491 // present in new_thread_list. Remove non-existent threads from internal id table.
1492 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1493 for (size_t i=0; i<old_num_thread_ids; i++)
1494 {
1495 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1496 if (old_thread_sp)
1497 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001498 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001499 m_thread_id_to_index_id_map.erase(old_thread_id);
1500 }
1501 }
1502
Greg Clayton9fc13552012-04-10 00:18:59 +00001503 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001504}
1505
1506
1507StateType
1508ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1509{
Greg Claytondd0e5a52011-06-02 22:22:38 +00001510 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001511 const char stop_type = stop_packet.GetChar();
1512 switch (stop_type)
1513 {
1514 case 'T':
1515 case 'S':
1516 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00001517 // This is a bit of a hack, but is is required. If we did exec, we
1518 // need to clear our thread lists and also know to rebuild our dynamic
1519 // register info before we lookup and threads and populate the expedited
1520 // register values so we need to know this right away so we can cleanup
1521 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00001522 const uint32_t stop_id = GetStopID();
1523 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00001524 {
1525 // Our first stop, make sure we have a process ID, and also make
1526 // sure we know about our registers
1527 if (GetID() == LLDB_INVALID_PROCESS_ID)
1528 {
Greg Claytonc574ede2011-03-10 02:26:48 +00001529 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00001530 if (pid != LLDB_INVALID_PROCESS_ID)
1531 SetID (pid);
1532 }
1533 BuildDynamicRegisterInfo (true);
1534 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001535 // Stop with signal and thread info
1536 const uint8_t signo = stop_packet.GetHexU8();
1537 std::string name;
1538 std::string value;
1539 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00001540 std::string reason;
1541 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001542 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00001543 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001544 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001545 ThreadSP thread_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001546 ThreadGDBRemote *gdb_thread = NULL;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001547
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001548 while (stop_packet.GetNameColonValue(name, value))
1549 {
1550 if (name.compare("metype") == 0)
1551 {
1552 // exception type in big endian hex
1553 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1554 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001555 else if (name.compare("medata") == 0)
1556 {
1557 // exception data in big endian hex
1558 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1559 }
1560 else if (name.compare("thread") == 0)
1561 {
1562 // thread in big endian hex
Greg Clayton9e920902012-04-10 02:25:43 +00001563 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001564 // m_thread_list_real does have its own mutex, but we need to
1565 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1566 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1567 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1568 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
Greg Clayton160c9d82013-05-01 21:54:04 +00001569
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001570 if (!thread_sp)
Greg Claytond1d06e42013-04-20 00:27:58 +00001571 {
Greg Claytone576ab22011-02-15 00:19:15 +00001572 // Create the thread if we need to
Jim Ingham4f465cf2012-10-10 18:32:14 +00001573 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001574 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
1575 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1576 log->Printf ("ProcessGDBRemote::%s Adding new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1577 __FUNCTION__,
1578 thread_sp.get(),
1579 thread_sp->GetID());
1580
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001581 m_thread_list_real.AddThread(thread_sp);
Greg Claytone576ab22011-02-15 00:19:15 +00001582 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001583 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1584
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001585 }
Greg Clayton9e920902012-04-10 02:25:43 +00001586 else if (name.compare("threads") == 0)
1587 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001588 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001589 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00001590 // A comma separated list of all threads in the current
1591 // process that includes the thread for this stop reply
1592 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00001593 size_t comma_pos;
1594 lldb::tid_t tid;
1595 while ((comma_pos = value.find(',')) != std::string::npos)
1596 {
1597 value[comma_pos] = '\0';
1598 // thread in big endian hex
1599 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1600 if (tid != LLDB_INVALID_THREAD_ID)
1601 m_thread_ids.push_back (tid);
1602 value.erase(0, comma_pos + 1);
1603
1604 }
1605 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1606 if (tid != LLDB_INVALID_THREAD_ID)
1607 m_thread_ids.push_back (tid);
1608 }
Greg Claytonde9d0492011-01-08 03:17:57 +00001609 else if (name.compare("hexname") == 0)
1610 {
1611 StringExtractor name_extractor;
1612 // Swap "value" over into "name_extractor"
1613 name_extractor.GetStringRef().swap(value);
1614 // Now convert the HEX bytes into a string value
1615 name_extractor.GetHexByteString (value);
1616 thread_name.swap (value);
1617 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001618 else if (name.compare("name") == 0)
1619 {
1620 thread_name.swap (value);
1621 }
Greg Clayton6f35f5c2010-09-09 06:32:46 +00001622 else if (name.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001623 {
1624 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1625 }
Greg Claytona658fd22011-06-04 01:26:29 +00001626 else if (name.compare("reason") == 0)
1627 {
1628 reason.swap(value);
1629 }
1630 else if (name.compare("description") == 0)
1631 {
1632 StringExtractor desc_extractor;
1633 // Swap "value" over into "name_extractor"
1634 desc_extractor.GetStringRef().swap(value);
1635 // Now convert the HEX bytes into a string value
1636 desc_extractor.GetHexByteString (thread_name);
1637 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001638 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1639 {
1640 // We have a register number that contains an expedited
1641 // register value. Lets supply this register to our thread
1642 // so it won't have to go and read it.
Greg Clayton160c9d82013-05-01 21:54:04 +00001643 if (gdb_thread)
Greg Clayton3e06bd92011-01-09 21:07:35 +00001644 {
1645 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1646
1647 if (reg != UINT32_MAX)
1648 {
1649 StringExtractor reg_value_extractor;
1650 // Swap "value" over into "reg_value_extractor"
1651 reg_value_extractor.GetStringRef().swap(value);
Greg Clayton160c9d82013-05-01 21:54:04 +00001652 if (!gdb_thread->PrivateSetRegisterValue (reg, reg_value_extractor))
Greg Claytone576ab22011-02-15 00:19:15 +00001653 {
1654 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1655 name.c_str(),
1656 reg,
1657 reg,
1658 reg_value_extractor.GetStringRef().c_str(),
1659 stop_packet.GetStringRef().c_str());
1660 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001661 }
1662 }
1663 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001664 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001665
1666 if (thread_sp)
1667 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001668 // Clear the stop info just in case we don't set it to anything
1669 thread_sp->SetStopInfo (StopInfoSP());
1670
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001671 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Inghamdd2fe7a2011-01-28 02:23:12 +00001672 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001673 if (exc_type != 0)
1674 {
Greg Clayton1a65ae12011-01-25 23:55:37 +00001675 const size_t exc_data_size = exc_data.size();
Greg Claytonf4b47e12010-08-04 01:40:35 +00001676
Greg Clayton160c9d82013-05-01 21:54:04 +00001677 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1678 exc_type,
1679 exc_data_size,
1680 exc_data_size >= 1 ? exc_data[0] : 0,
1681 exc_data_size >= 2 ? exc_data[1] : 0,
1682 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001683 }
Greg Claytona658fd22011-06-04 01:26:29 +00001684 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001685 {
Greg Claytona658fd22011-06-04 01:26:29 +00001686 bool handled = false;
Greg Clayton8cda7f02013-05-21 21:55:59 +00001687 bool did_exec = false;
Greg Claytona658fd22011-06-04 01:26:29 +00001688 if (!reason.empty())
1689 {
1690 if (reason.compare("trace") == 0)
1691 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001692 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Greg Claytona658fd22011-06-04 01:26:29 +00001693 handled = true;
1694 }
1695 else if (reason.compare("breakpoint") == 0)
1696 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001697 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1698 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Claytona658fd22011-06-04 01:26:29 +00001699 if (bp_site_sp)
1700 {
1701 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1702 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1703 // 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 +00001704 handled = true;
Greg Clayton160c9d82013-05-01 21:54:04 +00001705 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00001706 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001707 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00001708 }
1709 else
1710 {
1711 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001712 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00001713 }
1714 }
1715
Greg Claytona658fd22011-06-04 01:26:29 +00001716 }
1717 else if (reason.compare("trap") == 0)
1718 {
1719 // Let the trap just use the standard signal stop reason below...
1720 }
1721 else if (reason.compare("watchpoint") == 0)
1722 {
1723 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1724 // TODO: locate the watchpoint somehow...
Greg Clayton160c9d82013-05-01 21:54:04 +00001725 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
Greg Claytona658fd22011-06-04 01:26:29 +00001726 handled = true;
1727 }
1728 else if (reason.compare("exception") == 0)
1729 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001730 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00001731 handled = true;
1732 }
Greg Clayton15fc2be2013-05-21 01:00:52 +00001733 else if (reason.compare("exec") == 0)
1734 {
Greg Clayton8cda7f02013-05-21 21:55:59 +00001735 did_exec = true;
Greg Clayton15fc2be2013-05-21 01:00:52 +00001736 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
1737 handled = true;
1738 }
Greg Claytona658fd22011-06-04 01:26:29 +00001739 }
1740
Greg Clayton15fc2be2013-05-21 01:00:52 +00001741 if (signo && did_exec == false)
Greg Claytona658fd22011-06-04 01:26:29 +00001742 {
1743 if (signo == SIGTRAP)
1744 {
1745 // Currently we are going to assume SIGTRAP means we are either
1746 // hitting a breakpoint or hardware single stepping.
Jim Ingham54cc6e42012-07-11 21:41:19 +00001747 handled = true;
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +00001748 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
Greg Clayton160c9d82013-05-01 21:54:04 +00001749 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Jim Ingham54cc6e42012-07-11 21:41:19 +00001750
Greg Claytona658fd22011-06-04 01:26:29 +00001751 if (bp_site_sp)
1752 {
1753 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1754 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1755 // 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 +00001756 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00001757 {
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +00001758 if(m_breakpoint_pc_offset != 0)
1759 thread_sp->GetRegisterContext()->SetPC(pc);
Greg Clayton160c9d82013-05-01 21:54:04 +00001760 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00001761 }
1762 else
1763 {
1764 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001765 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00001766 }
1767 }
Jim Ingham54cc6e42012-07-11 21:41:19 +00001768 else
Greg Claytona658fd22011-06-04 01:26:29 +00001769 {
Jim Ingham4dc613b2012-10-27 02:52:04 +00001770 // If we were stepping then assume the stop was the result of the trace. If we were
1771 // not stepping then report the SIGTRAP.
1772 // FIXME: We are still missing the case where we single step over a trap instruction.
Greg Clayton160c9d82013-05-01 21:54:04 +00001773 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1774 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Jim Ingham4dc613b2012-10-27 02:52:04 +00001775 else
Greg Clayton160c9d82013-05-01 21:54:04 +00001776 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo));
Greg Claytona658fd22011-06-04 01:26:29 +00001777 }
1778 }
1779 if (!handled)
Greg Clayton160c9d82013-05-01 21:54:04 +00001780 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Jason Molenda8214b012013-04-25 01:33:46 +00001781 }
Greg Claytona658fd22011-06-04 01:26:29 +00001782
1783 if (!description.empty())
1784 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001785 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
Greg Claytona658fd22011-06-04 01:26:29 +00001786 if (stop_info_sp)
1787 {
1788 stop_info_sp->SetDescription (description.c_str());
Greg Clayton3418c852011-08-10 02:10:13 +00001789 }
Greg Claytona658fd22011-06-04 01:26:29 +00001790 else
1791 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001792 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00001793 }
1794 }
1795 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001796 }
1797 return eStateStopped;
1798 }
1799 break;
1800
1801 case 'W':
1802 // process exited
1803 return eStateExited;
1804
1805 default:
1806 break;
1807 }
1808 return eStateInvalid;
1809}
1810
1811void
1812ProcessGDBRemote::RefreshStateAfterStop ()
1813{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001814 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001815 m_thread_ids.clear();
1816 // Set the thread stop info. It might have a "threads" key whose value is
1817 // a list of all thread IDs in the current process, so m_thread_ids might
1818 // get set.
1819 SetThreadStopInfo (m_last_stop_packet);
1820 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1821 if (m_thread_ids.empty())
1822 {
1823 // No, we need to fetch the thread list manually
1824 UpdateThreadIDList();
1825 }
1826
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001827 // Let all threads recover from stopping and do any clean up based
1828 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001829 m_thread_list_real.RefreshStateAfterStop();
Greg Clayton9e920902012-04-10 02:25:43 +00001830
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001831}
1832
1833Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001834ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001835{
1836 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001837
Greg Clayton6ed95942011-01-22 07:12:45 +00001838 bool timed_out = false;
1839 Mutex::Locker locker;
Greg Clayton513c26c2011-01-29 07:10:55 +00001840
1841 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00001842 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001843 // We are being asked to halt during an attach. We need to just close
1844 // our file handle and debugserver will go away, and we can be done...
1845 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00001846 }
Greg Clayton513c26c2011-01-29 07:10:55 +00001847 else
1848 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001849 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton513c26c2011-01-29 07:10:55 +00001850 {
1851 if (timed_out)
1852 error.SetErrorString("timed out sending interrupt packet");
1853 else
1854 error.SetErrorString("unknown error sending interrupt packet");
1855 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001856
1857 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton513c26c2011-01-29 07:10:55 +00001858 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001859 return error;
1860}
1861
1862Error
Jim Inghamacff8952013-05-02 00:27:30 +00001863ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00001864{
1865 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001866 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00001867 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00001868 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
1869
Greg Clayton594e5ed2010-09-27 21:07:38 +00001870 DisableAllBreakpointSites ();
1871
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001872 m_thread_list.DiscardThreadPlans();
Greg Clayton594e5ed2010-09-27 21:07:38 +00001873
Jim Inghamacff8952013-05-02 00:27:30 +00001874 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001875 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00001876 {
Jim Inghamacff8952013-05-02 00:27:30 +00001877 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001878 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1879 else
Jim Inghamacff8952013-05-02 00:27:30 +00001880 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00001881 }
Jim Inghamacff8952013-05-02 00:27:30 +00001882
1883 if (!error.Success())
1884 return error;
1885
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001886 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00001887 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001888
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001889 SetPrivateState (eStateDetached);
1890 ResumePrivateStateThread();
1891
1892 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00001893 return error;
1894}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001895
Jim Ingham43c555d2012-07-04 00:35:43 +00001896
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001897Error
1898ProcessGDBRemote::DoDestroy ()
1899{
1900 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001901 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001902 if (log)
1903 log->Printf ("ProcessGDBRemote::DoDestroy()");
1904
Jim Ingham43c555d2012-07-04 00:35:43 +00001905 // There is a bug in older iOS debugservers where they don't shut down the process
1906 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
1907 // this can cause problems with restarting. So we check to see if any of our threads are stopped
1908 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
1909 // destroy it again.
1910 //
1911 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
1912 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
1913 // the debugservers with this bug are equal. There really should be a better way to test this!
1914 //
1915 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
1916 // get called here to destroy again and we're still at a breakpoint or exception, then we should
1917 // just do the straight-forward kill.
1918 //
1919 // And of course, if we weren't able to stop the process by the time we get here, it isn't
1920 // necessary (or helpful) to do any of this.
1921
1922 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
1923 {
1924 PlatformSP platform_sp = GetTarget().GetPlatform();
1925
1926 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
1927 if (platform_sp
1928 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00001929 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00001930 {
1931 if (m_destroy_tried_resuming)
1932 {
1933 if (log)
1934 log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again.");
1935 }
1936 else
1937 {
1938 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
1939 // but we really need it to happen here and it doesn't matter if we do it twice.
1940 m_thread_list.DiscardThreadPlans();
1941 DisableAllBreakpointSites();
1942
1943 bool stop_looks_like_crash = false;
1944 ThreadList &threads = GetThreadList();
1945
1946 {
Jim Ingham45350372012-09-11 00:08:52 +00001947 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00001948
1949 size_t num_threads = threads.GetSize();
1950 for (size_t i = 0; i < num_threads; i++)
1951 {
1952 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00001953 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00001954 StopReason reason = eStopReasonInvalid;
1955 if (stop_info_sp)
1956 reason = stop_info_sp->GetStopReason();
1957 if (reason == eStopReasonBreakpoint
1958 || reason == eStopReasonException)
1959 {
1960 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00001961 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
1962 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00001963 stop_info_sp->GetDescription());
1964 stop_looks_like_crash = true;
1965 break;
1966 }
1967 }
1968 }
1969
1970 if (stop_looks_like_crash)
1971 {
1972 if (log)
1973 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
1974 m_destroy_tried_resuming = true;
1975
1976 // If we are going to run again before killing, it would be good to suspend all the threads
1977 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
1978 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
1979 // have to run the risk of letting those threads proceed a bit.
1980
1981 {
Jim Ingham45350372012-09-11 00:08:52 +00001982 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00001983
1984 size_t num_threads = threads.GetSize();
1985 for (size_t i = 0; i < num_threads; i++)
1986 {
1987 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00001988 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00001989 StopReason reason = eStopReasonInvalid;
1990 if (stop_info_sp)
1991 reason = stop_info_sp->GetStopReason();
1992 if (reason != eStopReasonBreakpoint
1993 && reason != eStopReasonException)
1994 {
1995 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00001996 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
1997 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00001998 thread_sp->SetResumeState(eStateSuspended);
1999 }
2000 }
2001 }
2002 Resume ();
2003 return Destroy();
2004 }
2005 }
2006 }
2007 }
2008
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002009 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00002010 int exit_status = SIGABRT;
2011 std::string exit_string;
2012
Greg Clayton6ed95942011-01-22 07:12:45 +00002013 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002014 {
Jim Inghamaab78372011-10-28 01:11:35 +00002015 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00002016 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002017
2018 StringExtractorGDBRemote response;
2019 bool send_async = true;
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002020 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3);
2021
Greg Clayton3dedae12013-12-06 21:45:27 +00002022 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton513c26c2011-01-29 07:10:55 +00002023 {
2024 char packet_cmd = response.GetChar(0);
2025
2026 if (packet_cmd == 'W' || packet_cmd == 'X')
2027 {
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002028 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002029 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00002030 exit_status = response.GetHexU8();
2031 }
2032 else
2033 {
2034 if (log)
2035 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2036 exit_string.assign("got unexpected response to k packet: ");
2037 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00002038 }
2039 }
2040 else
2041 {
Jim Inghambabfc382012-06-06 00:32:39 +00002042 if (log)
2043 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2044 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00002045 }
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002046
2047 m_gdb_comm.SetPacketTimeout(old_packet_timeout);
Greg Clayton6779606a2011-01-22 23:43:18 +00002048 }
Jim Inghambabfc382012-06-06 00:32:39 +00002049 else
2050 {
2051 if (log)
2052 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
Jim Inghamcfc09352012-07-27 23:57:19 +00002053 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00002054 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002055 }
Jim Inghambabfc382012-06-06 00:32:39 +00002056 else
2057 {
2058 // If we missed setting the exit status on the way out, do it here.
2059 // NB set exit status can be called multiple times, the first one sets the status.
2060 exit_string.assign("destroying when not connected to debugserver");
2061 }
2062
2063 SetExitStatus(exit_status, exit_string.c_str());
2064
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002065 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002066 KillDebugserverProcess ();
2067 return error;
2068}
2069
Greg Clayton8cda7f02013-05-21 21:55:59 +00002070void
2071ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2072{
2073 lldb_private::Mutex::Locker locker (m_last_stop_packet_mutex);
2074 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2075 if (did_exec)
2076 {
2077 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2078 if (log)
2079 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2080
2081 m_thread_list_real.Clear();
2082 m_thread_list.Clear();
2083 BuildDynamicRegisterInfo (true);
2084 m_gdb_comm.ResetDiscoverableSettings();
2085 }
2086 m_last_stop_packet = response;
2087}
2088
2089
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002090//------------------------------------------------------------------
2091// Process Queries
2092//------------------------------------------------------------------
2093
2094bool
2095ProcessGDBRemote::IsAlive ()
2096{
Greg Clayton10177aa2010-12-08 05:08:21 +00002097 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002098}
2099
2100addr_t
2101ProcessGDBRemote::GetImageInfoAddress()
2102{
Jason Molenda6ba6d3d2013-01-30 04:39:32 +00002103 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002104}
2105
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002106//------------------------------------------------------------------
2107// Process Memory
2108//------------------------------------------------------------------
2109size_t
2110ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2111{
2112 if (size > m_max_memory_size)
2113 {
2114 // Keep memory read sizes down to a sane limit. This function will be
2115 // called multiple times in order to complete the task by
2116 // lldb_private::Process so it is ok to do this.
2117 size = m_max_memory_size;
2118 }
2119
2120 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002121 const int packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
Andy Gibbsa297a972013-06-19 19:04:53 +00002122 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002123 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002124 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002125 {
Greg Clayton576d8832011-03-22 04:00:09 +00002126 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002127 {
2128 error.Clear();
2129 return response.GetHexBytes(buf, size, '\xdd');
2130 }
Greg Clayton576d8832011-03-22 04:00:09 +00002131 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002132 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002133 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002134 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002135 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002136 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002137 }
2138 else
2139 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002140 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002141 }
2142 return 0;
2143}
2144
2145size_t
2146ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2147{
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002148 if (size > m_max_memory_size)
2149 {
2150 // Keep memory read sizes down to a sane limit. This function will be
2151 // called multiple times in order to complete the task by
2152 // lldb_private::Process so it is ok to do this.
2153 size = m_max_memory_size;
2154 }
2155
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002156 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00002157 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Clayton7fb56d02011-02-01 01:31:41 +00002158 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002159 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002160 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002161 {
Greg Clayton576d8832011-03-22 04:00:09 +00002162 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002163 {
2164 error.Clear();
2165 return size;
2166 }
Greg Clayton576d8832011-03-22 04:00:09 +00002167 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002168 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002169 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002170 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002171 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002172 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 +00002173 }
2174 else
2175 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002176 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002177 }
2178 return 0;
2179}
2180
2181lldb::addr_t
2182ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2183{
Greg Clayton2a48f522011-05-14 01:50:35 +00002184 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2185
Greg Clayton70b57652011-05-15 01:25:55 +00002186 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton2a48f522011-05-14 01:50:35 +00002187 switch (supported)
2188 {
2189 case eLazyBoolCalculate:
2190 case eLazyBoolYes:
2191 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2192 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2193 return allocated_addr;
2194
2195 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002196 // Call mmap() to create memory in the inferior..
2197 unsigned prot = 0;
2198 if (permissions & lldb::ePermissionsReadable)
2199 prot |= eMmapProtRead;
2200 if (permissions & lldb::ePermissionsWritable)
2201 prot |= eMmapProtWrite;
2202 if (permissions & lldb::ePermissionsExecutable)
2203 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00002204
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002205 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2206 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2207 m_addr_to_mmap_size[allocated_addr] = size;
2208 else
2209 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton2a48f522011-05-14 01:50:35 +00002210 break;
2211 }
2212
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002213 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00002214 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002215 else
2216 error.Clear();
2217 return allocated_addr;
2218}
2219
2220Error
Greg Clayton46fb5582011-11-18 07:03:08 +00002221ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2222 MemoryRegionInfo &region_info)
2223{
2224
2225 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2226 return error;
2227}
2228
2229Error
Johnny Chen64637202012-05-23 21:09:52 +00002230ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2231{
2232
2233 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2234 return error;
2235}
2236
2237Error
Enrico Granataf04a2192012-07-13 23:18:48 +00002238ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2239{
2240 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2241 return error;
2242}
2243
2244Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002245ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2246{
2247 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00002248 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2249
2250 switch (supported)
2251 {
2252 case eLazyBoolCalculate:
2253 // We should never be deallocating memory without allocating memory
2254 // first so we should never get eLazyBoolCalculate
2255 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2256 break;
2257
2258 case eLazyBoolYes:
2259 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00002260 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002261 break;
2262
2263 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002264 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00002265 {
2266 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002267 if (pos != m_addr_to_mmap_size.end() &&
2268 InferiorCallMunmap(this, addr, pos->second))
2269 m_addr_to_mmap_size.erase (pos);
2270 else
Daniel Malead01b2952012-11-29 21:49:15 +00002271 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002272 }
2273 break;
2274 }
2275
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002276 return error;
2277}
2278
2279
2280//------------------------------------------------------------------
2281// Process STDIO
2282//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002283size_t
2284ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2285{
2286 if (m_stdio_communication.IsConnected())
2287 {
2288 ConnectionStatus status;
2289 m_stdio_communication.Write(src, src_len, status, NULL);
2290 }
2291 return 0;
2292}
2293
2294Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002295ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002296{
2297 Error error;
2298 assert (bp_site != NULL);
2299
Greg Clayton5160ce52013-03-27 23:08:40 +00002300 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002301 user_id_t site_id = bp_site->GetID();
2302 const addr_t addr = bp_site->GetLoadAddress();
2303 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002304 log->Printf ("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002305
2306 if (bp_site->IsEnabled())
2307 {
2308 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002309 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 +00002310 return error;
2311 }
2312 else
2313 {
2314 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2315
Greg Claytoneb023e72013-10-11 19:48:25 +00002316 if (bp_site->HardwareRequired())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002317 {
2318 // Try and set hardware breakpoint, and if that fails, fall through
2319 // and set a software breakpoint?
Greg Clayton8b82f082011-04-12 05:54:46 +00002320 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002321 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002322 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002323 {
2324 bp_site->SetEnabled(true);
Greg Clayton8b82f082011-04-12 05:54:46 +00002325 bp_site->SetType (BreakpointSite::eHardware);
Greg Claytoneb023e72013-10-11 19:48:25 +00002326 }
2327 else
2328 {
2329 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002330 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002331 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002332 else
2333 {
2334 error.SetErrorString("hardware breakpoints are not supported");
2335 }
2336 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002337 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002338 else if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002339 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002340 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
2341 {
2342 bp_site->SetEnabled(true);
2343 bp_site->SetType (BreakpointSite::eExternal);
2344 return error;
2345 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002346 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002347
2348 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002349 }
2350
2351 if (log)
2352 {
2353 const char *err_string = error.AsCString();
Jim Ingham299c0c12013-02-15 02:06:30 +00002354 log->Printf ("ProcessGDBRemote::EnableBreakpointSite () error for breakpoint at 0x%8.8" PRIx64 ": %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002355 bp_site->GetLoadAddress(),
2356 err_string ? err_string : "NULL");
2357 }
2358 // We shouldn't reach here on a successful breakpoint enable...
2359 if (error.Success())
2360 error.SetErrorToGenericError();
2361 return error;
2362}
2363
2364Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002365ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002366{
2367 Error error;
2368 assert (bp_site != NULL);
2369 addr_t addr = bp_site->GetLoadAddress();
2370 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00002371 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002372 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002373 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002374
2375 if (bp_site->IsEnabled())
2376 {
2377 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2378
Greg Clayton8b82f082011-04-12 05:54:46 +00002379 BreakpointSite::Type bp_type = bp_site->GetType();
2380 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002381 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002382 case BreakpointSite::eSoftware:
2383 error = DisableSoftwareBreakpoint (bp_site);
2384 break;
2385
2386 case BreakpointSite::eHardware:
2387 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2388 error.SetErrorToGenericError();
2389 break;
2390
2391 case BreakpointSite::eExternal:
2392 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2393 error.SetErrorToGenericError();
2394 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002395 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002396 if (error.Success())
2397 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002398 }
2399 else
2400 {
2401 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002402 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 +00002403 return error;
2404 }
2405
2406 if (error.Success())
2407 error.SetErrorToGenericError();
2408 return error;
2409}
2410
Johnny Chen11309a32011-09-06 22:38:36 +00002411// Pre-requisite: wp != NULL.
2412static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00002413GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00002414{
2415 assert(wp);
2416 bool watch_read = wp->WatchpointRead();
2417 bool watch_write = wp->WatchpointWrite();
2418
2419 // watch_read and watch_write cannot both be false.
2420 assert(watch_read || watch_write);
2421 if (watch_read && watch_write)
2422 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00002423 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00002424 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00002425 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00002426 return eWatchpointWrite;
2427}
2428
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002429Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002430ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002431{
2432 Error error;
2433 if (wp)
2434 {
2435 user_id_t watchID = wp->GetID();
2436 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00002437 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002438 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002439 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002440 if (wp->IsEnabled())
2441 {
2442 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002443 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 +00002444 return error;
2445 }
Johnny Chen11309a32011-09-06 22:38:36 +00002446
2447 GDBStoppointType type = GetGDBStoppointType(wp);
2448 // Pass down an appropriate z/Z packet...
2449 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002450 {
Johnny Chen11309a32011-09-06 22:38:36 +00002451 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2452 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002453 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002454 return error;
2455 }
2456 else
2457 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002458 }
Johnny Chen11309a32011-09-06 22:38:36 +00002459 else
2460 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002461 }
2462 else
2463 {
Johnny Chen01a67862011-10-14 00:42:25 +00002464 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002465 }
2466 if (error.Success())
2467 error.SetErrorToGenericError();
2468 return error;
2469}
2470
2471Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002472ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002473{
2474 Error error;
2475 if (wp)
2476 {
2477 user_id_t watchID = wp->GetID();
2478
Greg Clayton5160ce52013-03-27 23:08:40 +00002479 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002480
2481 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00002482
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002483 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002484 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002485
Johnny Chen11309a32011-09-06 22:38:36 +00002486 if (!wp->IsEnabled())
2487 {
2488 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002489 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 +00002490 // See also 'class WatchpointSentry' within StopInfo.cpp.
2491 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2492 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00002493 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002494 return error;
2495 }
2496
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002497 if (wp->IsHardware())
2498 {
Johnny Chen11309a32011-09-06 22:38:36 +00002499 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002500 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00002501 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2502 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002503 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002504 return error;
2505 }
2506 else
2507 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002508 }
2509 // TODO: clear software watchpoints if we implement them
2510 }
2511 else
2512 {
Johnny Chen01a67862011-10-14 00:42:25 +00002513 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002514 }
2515 if (error.Success())
2516 error.SetErrorToGenericError();
2517 return error;
2518}
2519
2520void
2521ProcessGDBRemote::Clear()
2522{
2523 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002524 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002525 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002526}
2527
2528Error
2529ProcessGDBRemote::DoSignal (int signo)
2530{
2531 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002532 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002533 if (log)
2534 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2535
2536 if (!m_gdb_comm.SendAsyncSignal (signo))
2537 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2538 return error;
2539}
2540
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002541Error
Greg Clayton91a9b2472013-12-04 19:19:12 +00002542ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002543{
2544 Error error;
2545 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2546 {
2547 // If we locate debugserver, keep that located version around
2548 static FileSpec g_debugserver_file_spec;
2549
Han Ming Ong84647042012-02-25 01:07:38 +00002550 ProcessLaunchInfo debugserver_launch_info;
Greg Clayton91a9b2472013-12-04 19:19:12 +00002551 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2552 debugserver_launch_info.SetUserID(process_info.GetUserID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002553
Greg Claytonfda4fab2014-01-10 22:24:11 +00002554#if defined (__APPLE__) && defined (__arm__)
2555 // On iOS, still do a local connection using a random port
2556 const char *hostname = "localhost";
2557 uint16_t port = get_random_port ();
2558#else
2559 // Set hostname being NULL to do the reverse connect where debugserver
2560 // will bind to port zero and it will communicate back to us the port
2561 // that we will connect to
2562 const char *hostname = NULL;
2563 uint16_t port = 0;
2564#endif
2565
2566 error = m_gdb_comm.StartDebugserverProcess (hostname,
2567 port,
Greg Clayton00fe87b2013-12-05 22:58:22 +00002568 debugserver_launch_info,
2569 port);
Greg Clayton91a9b2472013-12-04 19:19:12 +00002570
2571 if (error.Success ())
2572 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002573 else
Greg Clayton91a9b2472013-12-04 19:19:12 +00002574 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002575
2576 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2577 StartAsyncThread ();
Greg Clayton91a9b2472013-12-04 19:19:12 +00002578
2579 if (error.Fail())
2580 {
2581 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
2582
2583 if (log)
2584 log->Printf("failed to start debugserver process: %s", error.AsCString());
2585 return error;
2586 }
2587
Greg Clayton00fe87b2013-12-05 22:58:22 +00002588 if (m_gdb_comm.IsConnected())
2589 {
2590 // Finish the connection process by doing the handshake without connecting (send NULL URL)
2591 ConnectToDebugserver (NULL);
2592 }
2593 else
2594 {
Greg Claytonfda4fab2014-01-10 22:24:11 +00002595 StreamString connect_url;
2596 connect_url.Printf("connect://%s:%u", hostname, port);
2597 error = ConnectToDebugserver (connect_url.GetString().c_str());
Greg Clayton00fe87b2013-12-05 22:58:22 +00002598 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00002599
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002600 }
2601 return error;
2602}
2603
2604bool
2605ProcessGDBRemote::MonitorDebugserverProcess
2606(
2607 void *callback_baton,
2608 lldb::pid_t debugserver_pid,
Greg Claytone4e45922011-11-16 05:37:56 +00002609 bool exited, // True if the process did exit
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002610 int signo, // Zero for no signal
2611 int exit_status // Exit value of process if signal is zero
2612)
2613{
Greg Claytone4e45922011-11-16 05:37:56 +00002614 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2615 // and might not exist anymore, so we need to carefully try to get the
2616 // target for this process first since we have a race condition when
2617 // we are done running between getting the notice that the inferior
2618 // process has died and the debugserver that was debugging this process.
2619 // In our test suite, we are also continually running process after
2620 // process, so we must be very careful to make sure:
2621 // 1 - process object hasn't been deleted already
2622 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002623
2624 // "debugserver_pid" argument passed in is the process ID for
2625 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00002626 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002627
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002628 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton6779606a2011-01-22 23:43:18 +00002629
Greg Claytone4e45922011-11-16 05:37:56 +00002630 // Get a shared pointer to the target that has a matching process pointer.
2631 // This target could be gone, or the target could already have a new process
2632 // object inside of it
2633 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2634
Greg Clayton6779606a2011-01-22 23:43:18 +00002635 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002636 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 +00002637
Greg Claytone4e45922011-11-16 05:37:56 +00002638 if (target_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002639 {
Greg Claytone4e45922011-11-16 05:37:56 +00002640 // We found a process in a target that matches, but another thread
2641 // might be in the process of launching a new process that will
2642 // soon replace it, so get a shared pointer to the process so we
2643 // can keep it alive.
2644 ProcessSP process_sp (target_sp->GetProcessSP());
2645 // Now we have a shared pointer to the process that can't go away on us
2646 // so we now make sure it was the same as the one passed in, and also make
2647 // sure that our previous "process *" didn't get deleted and have a new
2648 // "process *" created in its place with the same pointer. To verify this
2649 // we make sure the process has our debugserver process ID. If we pass all
2650 // of these tests, then we are sure that this process is the one we were
2651 // looking for.
2652 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002653 {
Greg Claytone4e45922011-11-16 05:37:56 +00002654 // Sleep for a half a second to make sure our inferior process has
2655 // time to set its exit status before we set it incorrectly when
2656 // both the debugserver and the inferior process shut down.
2657 usleep (500000);
2658 // If our process hasn't yet exited, debugserver might have died.
2659 // If the process did exit, the we are reaping it.
2660 const StateType state = process->GetState();
2661
2662 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2663 state != eStateInvalid &&
2664 state != eStateUnloaded &&
2665 state != eStateExited &&
2666 state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002667 {
Greg Claytone4e45922011-11-16 05:37:56 +00002668 char error_str[1024];
2669 if (signo)
2670 {
2671 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2672 if (signal_cstr)
2673 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2674 else
2675 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2676 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002677 else
Greg Claytone4e45922011-11-16 05:37:56 +00002678 {
2679 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2680 }
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002681
Greg Claytone4e45922011-11-16 05:37:56 +00002682 process->SetExitStatus (-1, error_str);
2683 }
2684 // Debugserver has exited we need to let our ProcessGDBRemote
2685 // know that it no longer has a debugserver instance
2686 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002687 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002688 }
2689 return true;
2690}
2691
2692void
2693ProcessGDBRemote::KillDebugserverProcess ()
2694{
Greg Claytonfbb76342013-11-20 21:07:01 +00002695 m_gdb_comm.Disconnect();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002696 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2697 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002698 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002699 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2700 }
2701}
2702
2703void
2704ProcessGDBRemote::Initialize()
2705{
2706 static bool g_initialized = false;
2707
2708 if (g_initialized == false)
2709 {
2710 g_initialized = true;
2711 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2712 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00002713 CreateInstance,
2714 DebuggerInitialize);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002715
2716 Log::Callbacks log_callbacks = {
2717 ProcessGDBRemoteLog::DisableLog,
2718 ProcessGDBRemoteLog::EnableLog,
2719 ProcessGDBRemoteLog::ListLogCategories
2720 };
2721
2722 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2723 }
2724}
2725
Greg Clayton7f982402013-07-15 22:54:20 +00002726void
2727ProcessGDBRemote::DebuggerInitialize (lldb_private::Debugger &debugger)
2728{
2729 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
2730 {
2731 const bool is_global_setting = true;
2732 PluginManager::CreateSettingForProcessPlugin (debugger,
2733 GetGlobalPluginProperties()->GetValueProperties(),
2734 ConstString ("Properties for the gdb-remote process plug-in."),
2735 is_global_setting);
2736 }
2737}
2738
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002739bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002740ProcessGDBRemote::StartAsyncThread ()
2741{
Greg Clayton5160ce52013-03-27 23:08:40 +00002742 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002743
2744 if (log)
2745 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Ingham455fa5c2012-11-01 01:15:33 +00002746
2747 Mutex::Locker start_locker(m_async_thread_state_mutex);
2748 if (m_async_thread_state == eAsyncThreadNotStarted)
2749 {
2750 // Create a thread that watches our internal state and controls which
2751 // events make it to clients (into the DCProcess event queue).
2752 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2753 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2754 {
2755 m_async_thread_state = eAsyncThreadRunning;
2756 return true;
2757 }
2758 else
2759 return false;
2760 }
2761 else
2762 {
2763 // Somebody tried to start the async thread while it was either being started or stopped. If the former, and
2764 // it started up successfully, then say all's well. Otherwise it is an error, since we aren't going to restart it.
2765 if (log)
2766 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
2767 if (m_async_thread_state == eAsyncThreadRunning)
2768 return true;
2769 else
2770 return false;
2771 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002772}
2773
2774void
2775ProcessGDBRemote::StopAsyncThread ()
2776{
Greg Clayton5160ce52013-03-27 23:08:40 +00002777 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002778
2779 if (log)
2780 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2781
Jim Ingham455fa5c2012-11-01 01:15:33 +00002782 Mutex::Locker start_locker(m_async_thread_state_mutex);
2783 if (m_async_thread_state == eAsyncThreadRunning)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002784 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00002785 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2786
2787 // This will shut down the async thread.
2788 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
2789
2790 // Stop the stdio thread
2791 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2792 {
2793 Host::ThreadJoin (m_async_thread, NULL, NULL);
2794 }
2795 m_async_thread_state = eAsyncThreadDone;
2796 }
2797 else
2798 {
2799 if (log)
2800 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002801 }
2802}
2803
2804
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002805thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002806ProcessGDBRemote::AsyncThread (void *arg)
2807{
2808 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2809
Greg Clayton5160ce52013-03-27 23:08:40 +00002810 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002811 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002812 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002813
2814 Listener listener ("ProcessGDBRemote::AsyncThread");
2815 EventSP event_sp;
2816 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2817 eBroadcastBitAsyncThreadShouldExit;
2818
2819 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2820 {
Greg Clayton71337622011-02-24 22:24:29 +00002821 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2822
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002823 bool done = false;
2824 while (!done)
2825 {
2826 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002827 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002828 if (listener.WaitForEvent (NULL, event_sp))
2829 {
2830 const uint32_t event_type = event_sp->GetType();
Greg Clayton71337622011-02-24 22:24:29 +00002831 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002832 {
Greg Clayton71337622011-02-24 22:24:29 +00002833 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002834 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 +00002835
Greg Clayton71337622011-02-24 22:24:29 +00002836 switch (event_type)
2837 {
2838 case eBroadcastBitAsyncContinue:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002839 {
Greg Clayton71337622011-02-24 22:24:29 +00002840 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002841
Greg Clayton71337622011-02-24 22:24:29 +00002842 if (continue_packet)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002843 {
Greg Clayton71337622011-02-24 22:24:29 +00002844 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2845 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2846 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002847 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002848
Greg Clayton71337622011-02-24 22:24:29 +00002849 if (::strstr (continue_cstr, "vAttach") == NULL)
2850 process->SetPrivateState(eStateRunning);
2851 StringExtractorGDBRemote response;
2852 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002853
Greg Clayton0772ded2012-05-16 02:48:06 +00002854 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
2855 // The thread ID list might be contained within the "response", or the stop reply packet that
2856 // caused the stop. So clear it now before we give the stop reply packet to the process
2857 // using the process->SetLastStopPacket()...
2858 process->ClearThreadIDList ();
2859
Greg Clayton71337622011-02-24 22:24:29 +00002860 switch (stop_state)
2861 {
2862 case eStateStopped:
2863 case eStateCrashed:
2864 case eStateSuspended:
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002865 process->SetLastStopPacket (response);
Greg Clayton71337622011-02-24 22:24:29 +00002866 process->SetPrivateState (stop_state);
2867 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002868
Greg Clayton71337622011-02-24 22:24:29 +00002869 case eStateExited:
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002870 process->SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002871 process->ClearThreadIDList();
Greg Clayton71337622011-02-24 22:24:29 +00002872 response.SetFilePos(1);
2873 process->SetExitStatus(response.GetHexU8(), NULL);
2874 done = true;
2875 break;
2876
2877 case eStateInvalid:
2878 process->SetExitStatus(-1, "lost connection");
2879 break;
2880
2881 default:
2882 process->SetPrivateState (stop_state);
2883 break;
2884 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002885 }
2886 }
Greg Clayton71337622011-02-24 22:24:29 +00002887 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002888
Greg Clayton71337622011-02-24 22:24:29 +00002889 case eBroadcastBitAsyncThreadShouldExit:
2890 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002891 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Clayton71337622011-02-24 22:24:29 +00002892 done = true;
2893 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002894
Greg Clayton71337622011-02-24 22:24:29 +00002895 default:
2896 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002897 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 +00002898 done = true;
2899 break;
2900 }
2901 }
2902 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2903 {
2904 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2905 {
2906 process->SetExitStatus (-1, "lost connection");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002907 done = true;
Greg Clayton71337622011-02-24 22:24:29 +00002908 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002909 }
2910 }
2911 else
2912 {
2913 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002914 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 +00002915 done = true;
2916 }
2917 }
2918 }
2919
2920 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002921 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002922
2923 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2924 return NULL;
2925}
2926
Greg Claytone996fd32011-03-08 22:40:15 +00002927//uint32_t
2928//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2929//{
2930// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2931// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2932// if (m_local_debugserver)
2933// {
2934// return Host::ListProcessesMatchingName (name, matches, pids);
2935// }
2936// else
2937// {
2938// // FIXME: Implement talking to the remote debugserver.
2939// return 0;
2940// }
2941//
2942//}
2943//
Jim Ingham1c823b42011-01-22 01:33:44 +00002944bool
2945ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2946 lldb_private::StoppointCallbackContext *context,
2947 lldb::user_id_t break_id,
2948 lldb::user_id_t break_loc_id)
2949{
2950 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2951 // run so I can stop it if that's what I want to do.
Greg Clayton5160ce52013-03-27 23:08:40 +00002952 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00002953 if (log)
2954 log->Printf("Hit New Thread Notification breakpoint.");
2955 return false;
2956}
2957
2958
2959bool
2960ProcessGDBRemote::StartNoticingNewThreads()
2961{
Greg Clayton5160ce52013-03-27 23:08:40 +00002962 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00002963 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00002964 {
Greg Clayton4116e932012-05-15 02:33:01 +00002965 if (log && log->GetVerbose())
2966 log->Printf("Enabled noticing new thread breakpoint.");
2967 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00002968 }
Greg Clayton4116e932012-05-15 02:33:01 +00002969 else
Jim Ingham1c823b42011-01-22 01:33:44 +00002970 {
Greg Clayton4116e932012-05-15 02:33:01 +00002971 PlatformSP platform_sp (m_target.GetPlatform());
2972 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00002973 {
Greg Clayton4116e932012-05-15 02:33:01 +00002974 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
2975 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00002976 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00002977 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00002978 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
2979 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00002980 }
2981 else
2982 {
2983 if (log)
2984 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00002985 }
2986 }
2987 }
Greg Clayton4116e932012-05-15 02:33:01 +00002988 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00002989}
2990
2991bool
2992ProcessGDBRemote::StopNoticingNewThreads()
2993{
Greg Clayton5160ce52013-03-27 23:08:40 +00002994 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00002995 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00002996 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00002997
2998 if (m_thread_create_bp_sp)
2999 m_thread_create_bp_sp->SetEnabled(false);
3000
Jim Ingham1c823b42011-01-22 01:33:44 +00003001 return true;
3002}
3003
Jason Molenda5e8534e2012-10-03 01:29:34 +00003004lldb_private::DynamicLoader *
3005ProcessGDBRemote::GetDynamicLoader ()
3006{
3007 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00003008 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00003009 return m_dyld_ap.get();
3010}
Jim Ingham1c823b42011-01-22 01:33:44 +00003011
Greg Clayton998255b2012-10-13 02:07:45 +00003012
Greg Clayton02686b82012-10-15 22:42:16 +00003013class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00003014{
3015private:
3016
3017public:
Greg Clayton02686b82012-10-15 22:42:16 +00003018 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00003019 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00003020 "process plugin packet history",
3021 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00003022 NULL)
3023 {
3024 }
3025
Greg Clayton02686b82012-10-15 22:42:16 +00003026 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton998255b2012-10-13 02:07:45 +00003027 {
3028 }
3029
3030 bool
3031 DoExecute (Args& command, CommandReturnObject &result)
3032 {
Greg Clayton02686b82012-10-15 22:42:16 +00003033 const size_t argc = command.GetArgumentCount();
3034 if (argc == 0)
3035 {
3036 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3037 if (process)
3038 {
3039 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
3040 result.SetStatus (eReturnStatusSuccessFinishResult);
3041 return true;
3042 }
3043 }
3044 else
3045 {
3046 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
3047 }
3048 result.SetStatus (eReturnStatusFailed);
3049 return false;
3050 }
3051};
3052
3053class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
3054{
3055private:
3056
3057public:
3058 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
3059 CommandObjectParsed (interpreter,
3060 "process plugin packet send",
3061 "Send a custom packet through the GDB remote protocol and print the answer. "
3062 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
3063 NULL)
3064 {
3065 }
3066
3067 ~CommandObjectProcessGDBRemotePacketSend ()
3068 {
3069 }
3070
3071 bool
3072 DoExecute (Args& command, CommandReturnObject &result)
3073 {
3074 const size_t argc = command.GetArgumentCount();
3075 if (argc == 0)
3076 {
3077 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
3078 result.SetStatus (eReturnStatusFailed);
3079 return false;
3080 }
3081
3082 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3083 if (process)
3084 {
Han Ming Ong84145852012-11-26 20:42:03 +00003085 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00003086 {
Han Ming Ong84145852012-11-26 20:42:03 +00003087 const char *packet_cstr = command.GetArgumentAtIndex(0);
3088 bool send_async = true;
3089 StringExtractorGDBRemote response;
3090 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3091 result.SetStatus (eReturnStatusSuccessFinishResult);
3092 Stream &output_strm = result.GetOutputStream();
3093 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00003094 std::string &response_str = response.GetStringRef();
3095
Han Ming Ong399289e2013-06-21 19:56:59 +00003096 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00003097 {
3098 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
3099 }
3100
Han Ming Ong84145852012-11-26 20:42:03 +00003101 if (response_str.empty())
3102 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3103 else
3104 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00003105 }
Greg Clayton02686b82012-10-15 22:42:16 +00003106 }
Greg Clayton998255b2012-10-13 02:07:45 +00003107 return true;
3108 }
3109};
3110
Greg Claytonba4a0a52013-02-01 23:03:47 +00003111class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
3112{
3113private:
3114
3115public:
3116 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
3117 CommandObjectRaw (interpreter,
3118 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00003119 "Send a qRcmd packet through the GDB remote protocol and print the response."
3120 "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 +00003121 NULL)
3122 {
3123 }
3124
3125 ~CommandObjectProcessGDBRemotePacketMonitor ()
3126 {
3127 }
3128
3129 bool
3130 DoExecute (const char *command, CommandReturnObject &result)
3131 {
3132 if (command == NULL || command[0] == '\0')
3133 {
3134 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
3135 result.SetStatus (eReturnStatusFailed);
3136 return false;
3137 }
3138
3139 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3140 if (process)
3141 {
3142 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00003143 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00003144 packet.PutBytesAsRawHex8(command, strlen(command));
3145 const char *packet_cstr = packet.GetString().c_str();
3146
3147 bool send_async = true;
3148 StringExtractorGDBRemote response;
3149 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3150 result.SetStatus (eReturnStatusSuccessFinishResult);
3151 Stream &output_strm = result.GetOutputStream();
3152 output_strm.Printf (" packet: %s\n", packet_cstr);
3153 const std::string &response_str = response.GetStringRef();
3154
3155 if (response_str.empty())
3156 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3157 else
3158 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
3159 }
3160 return true;
3161 }
3162};
3163
Greg Clayton02686b82012-10-15 22:42:16 +00003164class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
3165{
3166private:
3167
3168public:
3169 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
3170 CommandObjectMultiword (interpreter,
3171 "process plugin packet",
3172 "Commands that deal with GDB remote packets.",
3173 NULL)
3174 {
3175 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
3176 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00003177 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00003178 }
3179
3180 ~CommandObjectProcessGDBRemotePacket ()
3181 {
3182 }
3183};
Greg Clayton998255b2012-10-13 02:07:45 +00003184
3185class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
3186{
3187public:
3188 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
3189 CommandObjectMultiword (interpreter,
3190 "process plugin",
3191 "A set of commands for operating on a ProcessGDBRemote process.",
3192 "process plugin <subcommand> [<subcommand-options>]")
3193 {
3194 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
3195 }
3196
3197 ~CommandObjectMultiwordProcessGDBRemote ()
3198 {
3199 }
3200};
3201
Greg Clayton998255b2012-10-13 02:07:45 +00003202CommandObject *
3203ProcessGDBRemote::GetPluginCommandObject()
3204{
3205 if (!m_command_sp)
3206 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
3207 return m_command_sp.get();
3208}