blob: 3754c366780ce9e3e42a58c7f18de5d6f7d48583 [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"
11
Chris Lattner30fdc8d2010-06-08 16:52:24 +000012// C Includes
13#include <errno.h>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000014#include <spawn.h>
Stephen Wilsona78867b2011-03-25 18:16:28 +000015#include <stdlib.h>
Sean Callanan224f6f52012-07-19 18:07:36 +000016#include <netinet/in.h>
Greg Clayton2a48f522011-05-14 01:50:35 +000017#include <sys/mman.h> // for mmap
Chris Lattner30fdc8d2010-06-08 16:52:24 +000018#include <sys/stat.h>
Greg Clayton2a48f522011-05-14 01:50:35 +000019#include <sys/types.h>
Stephen Wilsondc916862011-03-30 00:12:40 +000020#include <time.h>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000021
22// C++ Includes
23#include <algorithm>
24#include <map>
25
26// Other libraries and framework includes
27
Johnny Chen01a67862011-10-14 00:42:25 +000028#include "lldb/Breakpoint/Watchpoint.h"
Jim Ingham40af72e2010-06-15 19:49:27 +000029#include "lldb/Interpreter/Args.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000030#include "lldb/Core/ArchSpec.h"
31#include "lldb/Core/Debugger.h"
32#include "lldb/Core/ConnectionFileDescriptor.h"
Greg Clayton53239f02011-02-08 05:05:52 +000033#include "lldb/Host/FileSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000034#include "lldb/Core/InputReader.h"
35#include "lldb/Core/Module.h"
Greg Clayton1f746072012-08-29 21:13:06 +000036#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000037#include "lldb/Core/PluginManager.h"
38#include "lldb/Core/State.h"
Greg Claytond451c1a2012-04-13 21:24:18 +000039#include "lldb/Core/StreamFile.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000040#include "lldb/Core/StreamString.h"
41#include "lldb/Core/Timer.h"
Greg Clayton70b57652011-05-15 01:25:55 +000042#include "lldb/Core/Value.h"
Jason Molendad1fae142012-09-29 08:03:33 +000043#include "lldb/Host/Symbols.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000044#include "lldb/Host/TimeValue.h"
Greg Clayton02686b82012-10-15 22:42:16 +000045#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton1d19a2f2012-10-19 22:22:57 +000046#include "lldb/Interpreter/CommandObject.h"
47#include "lldb/Interpreter/CommandObjectMultiword.h"
Greg Clayton02686b82012-10-15 22:42:16 +000048#include "lldb/Interpreter/CommandReturnObject.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000049#include "lldb/Symbol/ObjectFile.h"
50#include "lldb/Target/DynamicLoader.h"
51#include "lldb/Target/Target.h"
52#include "lldb/Target/TargetList.h"
Greg Clayton2a48f522011-05-14 01:50:35 +000053#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molendaa34a0c62010-06-09 21:28:42 +000054#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000055
56// Project includes
57#include "lldb/Host/Host.h"
Peter Collingbourne99f9aa02011-06-03 20:40:38 +000058#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Jason Molendac42d2432012-07-25 03:40:06 +000059#include "Plugins/Process/Utility/StopInfoMachException.h"
Jim Ingham43c555d2012-07-04 00:35:43 +000060#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
Greg Claytonc982c762010-07-09 20:39:50 +000061#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000062#include "GDBRemoteRegisterContext.h"
63#include "ProcessGDBRemote.h"
64#include "ProcessGDBRemoteLog.h"
65#include "ThreadGDBRemote.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000066
Jason Molenda5e8534e2012-10-03 01:29:34 +000067
Greg Claytonc1422c12012-04-09 22:46:21 +000068namespace lldb
69{
70 // Provide a function that can easily dump the packet history if we know a
71 // ProcessGDBRemote * value (which we can get from logs or from debugging).
72 // We need the function in the lldb namespace so it makes it into the final
73 // executable since the LLDB shared library only exports stuff in the lldb
74 // namespace. This allows you to attach with a debugger and call this
75 // function and get the packet history dumped to a file.
76 void
77 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
78 {
Greg Claytond451c1a2012-04-13 21:24:18 +000079 lldb_private::StreamFile strm;
80 lldb_private::Error error (strm.GetFile().Open(path, lldb_private::File::eOpenOptionWrite | lldb_private::File::eOpenOptionCanCreate));
81 if (error.Success())
82 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
Greg Claytonc1422c12012-04-09 22:46:21 +000083 }
Filipe Cabecinhasc34f7762012-05-23 16:27:09 +000084}
Chris Lattner30fdc8d2010-06-08 16:52:24 +000085
Chris Lattner30fdc8d2010-06-08 16:52:24 +000086
87#define DEBUGSERVER_BASENAME "debugserver"
88using namespace lldb;
89using namespace lldb_private;
90
Jim Ingham7572fa72011-03-29 21:45:47 +000091static bool rand_initialized = false;
92
Sean Callanan224f6f52012-07-19 18:07:36 +000093// TODO Randomly assigning a port is unsafe. We should get an unused
94// ephemeral port from the kernel and make sure we reserve it before passing
95// it to debugserver.
96
97#if defined (__APPLE__)
98#define LOW_PORT (IPPORT_RESERVED)
99#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
100#else
101#define LOW_PORT (1024u)
102#define HIGH_PORT (49151u)
103#endif
104
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000105static inline uint16_t
106get_random_port ()
107{
Jim Ingham7572fa72011-03-29 21:45:47 +0000108 if (!rand_initialized)
109 {
Stephen Wilsondc916862011-03-30 00:12:40 +0000110 time_t seed = time(NULL);
111
Jim Ingham7572fa72011-03-29 21:45:47 +0000112 rand_initialized = true;
Stephen Wilsondc916862011-03-30 00:12:40 +0000113 srand(seed);
Jim Ingham7572fa72011-03-29 21:45:47 +0000114 }
Sean Callanan224f6f52012-07-19 18:07:36 +0000115 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000116}
117
118
Greg Clayton57abc5d2013-05-10 21:47:16 +0000119lldb_private::ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000120ProcessGDBRemote::GetPluginNameStatic()
121{
Greg Clayton57abc5d2013-05-10 21:47:16 +0000122 static ConstString g_name("gdb-remote");
123 return g_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000124}
125
126const char *
127ProcessGDBRemote::GetPluginDescriptionStatic()
128{
129 return "GDB Remote protocol based debugging plug-in.";
130}
131
132void
133ProcessGDBRemote::Terminate()
134{
135 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
136}
137
138
Greg Claytonc3776bf2012-02-09 06:16:32 +0000139lldb::ProcessSP
140ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000141{
Greg Claytonc3776bf2012-02-09 06:16:32 +0000142 lldb::ProcessSP process_sp;
143 if (crash_file_path == NULL)
144 process_sp.reset (new ProcessGDBRemote (target, listener));
145 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000146}
147
148bool
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000149ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000150{
Greg Clayton596ed242011-10-21 21:41:45 +0000151 if (plugin_specified_by_name)
152 return true;
153
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000154 // For now we are just making sure the file exists for a given module
Greg Claytonaa149cb2011-08-11 02:48:45 +0000155 Module *exe_module = target.GetExecutableModulePointer();
156 if (exe_module)
Greg Claytonc3776bf2012-02-09 06:16:32 +0000157 {
158 ObjectFile *exe_objfile = exe_module->GetObjectFile();
159 // We can't debug core files...
160 switch (exe_objfile->GetType())
161 {
162 case ObjectFile::eTypeInvalid:
163 case ObjectFile::eTypeCoreFile:
164 case ObjectFile::eTypeDebugInfo:
165 case ObjectFile::eTypeObjectFile:
166 case ObjectFile::eTypeSharedLibrary:
167 case ObjectFile::eTypeStubLibrary:
168 return false;
169 case ObjectFile::eTypeExecutable:
170 case ObjectFile::eTypeDynamicLinker:
171 case ObjectFile::eTypeUnknown:
172 break;
173 }
Greg Claytonaa149cb2011-08-11 02:48:45 +0000174 return exe_module->GetFileSpec().Exists();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000175 }
Jim Ingham5aee1622010-08-09 23:31:02 +0000176 // However, if there is no executable module, we return true since we might be preparing to attach.
177 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000178}
179
180//----------------------------------------------------------------------
181// ProcessGDBRemote constructor
182//----------------------------------------------------------------------
183ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
184 Process (target, listener),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000185 m_flags (0),
Greg Clayton8b82f082011-04-12 05:54:46 +0000186 m_gdb_comm(false),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000187 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Claytonc982c762010-07-09 20:39:50 +0000188 m_last_stop_packet (),
Greg Clayton09c3e3d2011-12-06 04:51:14 +0000189 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000190 m_register_info (),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000191 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000192 m_async_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham455fa5c2012-11-01 01:15:33 +0000193 m_async_thread_state(eAsyncThreadNotStarted),
194 m_async_thread_state_mutex(Mutex::eMutexTypeRecursive),
Greg Clayton9e920902012-04-10 02:25:43 +0000195 m_thread_ids (),
Greg Clayton71fc2a32011-02-12 06:28:37 +0000196 m_continue_c_tids (),
197 m_continue_C_tids (),
198 m_continue_s_tids (),
199 m_continue_S_tids (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000200 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Claytonc982c762010-07-09 20:39:50 +0000201 m_max_memory_size (512),
Greg Clayton4116e932012-05-15 02:33:01 +0000202 m_addr_to_mmap_size (),
203 m_thread_create_bp_sp (),
Jim Ingham43c555d2012-07-04 00:35:43 +0000204 m_waiting_for_attach (false),
Jason Molenda5e8534e2012-10-03 01:29:34 +0000205 m_destroy_tried_resuming (false),
Greg Clayton998255b2012-10-13 02:07:45 +0000206 m_command_sp ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000207{
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000208 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
209 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Inghamb1e2e842012-04-12 18:49:31 +0000210 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000211}
212
213//----------------------------------------------------------------------
214// Destructor
215//----------------------------------------------------------------------
216ProcessGDBRemote::~ProcessGDBRemote()
217{
218 // m_mach_process.UnregisterNotificationCallbacks (this);
219 Clear();
Greg Clayton1ed54f52011-10-01 00:45:15 +0000220 // We need to call finalize on the process before destroying ourselves
221 // to make sure all of the broadcaster cleanup goes as planned. If we
222 // destruct this class, then Process::~Process() might have problems
223 // trying to fully destroy the broadcaster.
224 Finalize();
Jim Ingham455fa5c2012-11-01 01:15:33 +0000225
226 // The general Finalize is going to try to destroy the process and that SHOULD
227 // shut down the async thread. However, if we don't kill it it will get stranded and
228 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
229 StopAsyncThread();
230 KillDebugserverProcess();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000231}
232
233//----------------------------------------------------------------------
234// PluginInterface
235//----------------------------------------------------------------------
Greg Clayton57abc5d2013-05-10 21:47:16 +0000236ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000237ProcessGDBRemote::GetPluginName()
238{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000239 return GetPluginNameStatic();
240}
241
242uint32_t
243ProcessGDBRemote::GetPluginVersion()
244{
245 return 1;
246}
247
248void
Greg Clayton513c26c2011-01-29 07:10:55 +0000249ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000250{
Greg Clayton513c26c2011-01-29 07:10:55 +0000251 if (!force && m_register_info.GetNumRegisters() > 0)
252 return;
253
254 char packet[128];
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000255 m_register_info.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000256 uint32_t reg_offset = 0;
257 uint32_t reg_num = 0;
Greg Clayton23f59502012-07-17 03:23:13 +0000258 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Greg Clayton576d8832011-03-22 04:00:09 +0000259 response_type == StringExtractorGDBRemote::eResponse;
260 ++reg_num)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000261 {
Greg Clayton513c26c2011-01-29 07:10:55 +0000262 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
Andy Gibbsa297a972013-06-19 19:04:53 +0000263 assert (packet_len < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000264 StringExtractorGDBRemote response;
Greg Claytonc574ede2011-03-10 02:26:48 +0000265 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000266 {
Greg Clayton576d8832011-03-22 04:00:09 +0000267 response_type = response.GetResponseType();
268 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000269 {
270 std::string name;
271 std::string value;
272 ConstString reg_name;
273 ConstString alt_name;
274 ConstString set_name;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000275 std::vector<uint32_t> value_regs;
276 std::vector<uint32_t> invalidate_regs;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000277 RegisterInfo reg_info = { NULL, // Name
278 NULL, // Alt name
279 0, // byte size
280 reg_offset, // offset
281 eEncodingUint, // encoding
282 eFormatHex, // formate
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000283 {
284 LLDB_INVALID_REGNUM, // GCC reg num
285 LLDB_INVALID_REGNUM, // DWARF reg num
286 LLDB_INVALID_REGNUM, // generic reg num
Jason Molendafbcb7f22010-09-10 07:49:16 +0000287 reg_num, // GDB reg num
288 reg_num // native register number
Greg Clayton435d85a2012-02-29 19:27:27 +0000289 },
290 NULL,
291 NULL
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000292 };
293
294 while (response.GetNameColonValue(name, value))
295 {
296 if (name.compare("name") == 0)
297 {
298 reg_name.SetCString(value.c_str());
299 }
300 else if (name.compare("alt-name") == 0)
301 {
302 alt_name.SetCString(value.c_str());
303 }
304 else if (name.compare("bitsize") == 0)
305 {
306 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
307 }
308 else if (name.compare("offset") == 0)
309 {
310 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda743e86a2010-06-11 23:44:18 +0000311 if (reg_offset != offset)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000312 {
313 reg_offset = offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000314 }
315 }
316 else if (name.compare("encoding") == 0)
317 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000318 const Encoding encoding = Args::StringToEncoding (value.c_str());
319 if (encoding != eEncodingInvalid)
320 reg_info.encoding = encoding;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000321 }
322 else if (name.compare("format") == 0)
323 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000324 Format format = eFormatInvalid;
325 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
326 reg_info.format = format;
327 else if (value.compare("binary") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000328 reg_info.format = eFormatBinary;
329 else if (value.compare("decimal") == 0)
330 reg_info.format = eFormatDecimal;
331 else if (value.compare("hex") == 0)
332 reg_info.format = eFormatHex;
333 else if (value.compare("float") == 0)
334 reg_info.format = eFormatFloat;
335 else if (value.compare("vector-sint8") == 0)
336 reg_info.format = eFormatVectorOfSInt8;
337 else if (value.compare("vector-uint8") == 0)
338 reg_info.format = eFormatVectorOfUInt8;
339 else if (value.compare("vector-sint16") == 0)
340 reg_info.format = eFormatVectorOfSInt16;
341 else if (value.compare("vector-uint16") == 0)
342 reg_info.format = eFormatVectorOfUInt16;
343 else if (value.compare("vector-sint32") == 0)
344 reg_info.format = eFormatVectorOfSInt32;
345 else if (value.compare("vector-uint32") == 0)
346 reg_info.format = eFormatVectorOfUInt32;
347 else if (value.compare("vector-float32") == 0)
348 reg_info.format = eFormatVectorOfFloat32;
349 else if (value.compare("vector-uint128") == 0)
350 reg_info.format = eFormatVectorOfUInt128;
351 }
352 else if (name.compare("set") == 0)
353 {
354 set_name.SetCString(value.c_str());
355 }
356 else if (name.compare("gcc") == 0)
357 {
358 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
359 }
360 else if (name.compare("dwarf") == 0)
361 {
362 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
363 }
364 else if (name.compare("generic") == 0)
365 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000366 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000367 }
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000368 else if (name.compare("container-regs") == 0)
369 {
370 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
371 value_pair.second = value;
372 do
373 {
374 value_pair = value_pair.second.split(',');
375 if (!value_pair.first.empty())
376 {
Greg Clayton0ba20242013-01-21 23:32:42 +0000377 uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
378 if (reg != LLDB_INVALID_REGNUM)
379 value_regs.push_back (reg);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000380 }
381 } while (!value_pair.second.empty());
382 }
383 else if (name.compare("invalidate-regs") == 0)
384 {
385 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
386 value_pair.second = value;
387 do
388 {
389 value_pair = value_pair.second.split(',');
390 if (!value_pair.first.empty())
391 {
Greg Clayton0ba20242013-01-21 23:32:42 +0000392 uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
393 if (reg != LLDB_INVALID_REGNUM)
394 invalidate_regs.push_back (reg);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000395 }
396 } while (!value_pair.second.empty());
397 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000398 }
399
Jason Molenda743e86a2010-06-11 23:44:18 +0000400 reg_info.byte_offset = reg_offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000401 assert (reg_info.byte_size != 0);
402 reg_offset += reg_info.byte_size;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000403 if (!value_regs.empty())
404 {
405 value_regs.push_back(LLDB_INVALID_REGNUM);
406 reg_info.value_regs = value_regs.data();
407 }
408 if (!invalidate_regs.empty())
409 {
410 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
411 reg_info.invalidate_regs = invalidate_regs.data();
412 }
413
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000414 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
415 }
416 }
417 else
418 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000419 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000420 }
421 }
422
Johnny Chen2fa9de12012-05-14 18:44:23 +0000423 // We didn't get anything if the accumulated reg_num is zero. See if we are
424 // debugging ARM and fill with a hard coded register set until we can get an
425 // updated debugserver down on the devices.
426 // On the other hand, if the accumulated reg_num is positive, see if we can
427 // add composite registers to the existing primordial ones.
428 bool from_scratch = (reg_num == 0);
429
430 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000431 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
432 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
433
434 // Use the process' architecture instead of the host arch, if available
435 ArchSpec remote_arch;
436 if (remote_process_arch.IsValid ())
437 remote_arch = remote_process_arch;
438 else
439 remote_arch = remote_host_arch;
440
Johnny Chen2fa9de12012-05-14 18:44:23 +0000441 if (!target_arch.IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000442 {
Johnny Chen2fa9de12012-05-14 18:44:23 +0000443 if (remote_arch.IsValid()
444 && remote_arch.GetMachine() == llvm::Triple::arm
445 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
446 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000447 }
Johnny Chen2fa9de12012-05-14 18:44:23 +0000448 else if (target_arch.GetMachine() == llvm::Triple::arm)
449 {
450 m_register_info.HardcodeARMRegisters(from_scratch);
451 }
452
453 // At this point, we can finalize our register info.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000454 m_register_info.Finalize ();
455}
456
457Error
458ProcessGDBRemote::WillLaunch (Module* module)
459{
460 return WillLaunchOrAttach ();
461}
462
463Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000464ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000465{
466 return WillLaunchOrAttach ();
467}
468
469Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000470ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000471{
472 return WillLaunchOrAttach ();
473}
474
475Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000476ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +0000477{
478 Error error (WillLaunchOrAttach ());
479
480 if (error.Fail())
481 return error;
482
Greg Clayton2289fa42011-04-30 01:09:13 +0000483 error = ConnectToDebugserver (remote_url);
Greg Claytonb766a732011-02-04 01:58:07 +0000484
485 if (error.Fail())
486 return error;
487 StartAsyncThread ();
488
Greg Claytonc574ede2011-03-10 02:26:48 +0000489 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonb766a732011-02-04 01:58:07 +0000490 if (pid == LLDB_INVALID_PROCESS_ID)
491 {
492 // We don't have a valid process ID, so note that we are connected
493 // and could now request to launch or attach, or get remote process
494 // listings...
495 SetPrivateState (eStateConnected);
496 }
497 else
498 {
499 // We have a valid process
500 SetID (pid);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000501 GetThreadList();
Greg Claytondd0e5a52011-06-02 22:22:38 +0000502 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytonb766a732011-02-04 01:58:07 +0000503 {
Greg Claytondd0e5a52011-06-02 22:22:38 +0000504 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytonb766a732011-02-04 01:58:07 +0000505 if (state == eStateStopped)
506 {
507 SetPrivateState (state);
508 }
509 else
Daniel Malead01b2952012-11-29 21:49:15 +0000510 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 +0000511 }
512 else
Daniel Malead01b2952012-11-29 21:49:15 +0000513 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 +0000514 }
Jason Molenda16d127c2012-05-03 22:37:30 +0000515
516 if (error.Success()
517 && !GetTarget().GetArchitecture().IsValid()
518 && m_gdb_comm.GetHostArchitecture().IsValid())
519 {
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000520 // Prefer the *process'* architecture over that of the *host*, if available.
521 if (m_gdb_comm.GetProcessArchitecture().IsValid())
522 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
523 else
524 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molenda16d127c2012-05-03 22:37:30 +0000525 }
526
Greg Claytonb766a732011-02-04 01:58:07 +0000527 return error;
528}
529
530Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000531ProcessGDBRemote::WillLaunchOrAttach ()
532{
533 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000534 m_stdio_communication.Clear ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000535 return error;
536}
537
538//----------------------------------------------------------------------
539// Process Control
540//----------------------------------------------------------------------
541Error
Greg Clayton982c9762011-11-03 21:22:33 +0000542ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000543{
Greg Clayton4957bf62010-09-30 21:49:03 +0000544 Error error;
Greg Clayton982c9762011-11-03 21:22:33 +0000545
546 uint32_t launch_flags = launch_info.GetFlags().Get();
547 const char *stdin_path = NULL;
548 const char *stdout_path = NULL;
549 const char *stderr_path = NULL;
550 const char *working_dir = launch_info.GetWorkingDirectory();
551
552 const ProcessLaunchInfo::FileAction *file_action;
553 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
554 if (file_action)
555 {
556 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
557 stdin_path = file_action->GetPath();
558 }
559 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
560 if (file_action)
561 {
562 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
563 stdout_path = file_action->GetPath();
564 }
565 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
566 if (file_action)
567 {
568 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
569 stderr_path = file_action->GetPath();
570 }
571
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000572 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
573 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
574 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton5160ce52013-03-27 23:08:40 +0000575 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000576
Greg Clayton982c9762011-11-03 21:22:33 +0000577 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000578 if (object_file)
579 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000580 char host_port[128];
581 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytonb766a732011-02-04 01:58:07 +0000582 char connect_url[128];
583 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000584
Greg Clayton71337622011-02-24 22:24:29 +0000585 // Make sure we aren't already connected?
586 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000587 {
Han Ming Ong84647042012-02-25 01:07:38 +0000588 error = StartDebugserverProcess (host_port, launch_info);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000589 if (error.Fail())
Greg Claytonc235ac72011-08-09 05:20:29 +0000590 {
Johnny Chen4c1e9202011-08-09 18:56:45 +0000591 if (log)
592 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000593 return error;
Greg Claytonc235ac72011-08-09 05:20:29 +0000594 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000595
Greg Claytonb766a732011-02-04 01:58:07 +0000596 error = ConnectToDebugserver (connect_url);
Greg Clayton71337622011-02-24 22:24:29 +0000597 }
598
599 if (error.Success())
600 {
601 lldb_utility::PseudoTerminal pty;
602 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000603
604 // If the debugserver is local and we aren't disabling STDIO, lets use
605 // a pseudo terminal to instead of relying on the 'O' packets for stdio
606 // since 'O' packets can really slow down debugging if the inferior
607 // does a lot of output.
Greg Claytonf58c2692011-06-24 22:32:10 +0000608 PlatformSP platform_sp (m_target.GetPlatform());
609 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Clayton71337622011-02-24 22:24:29 +0000610 {
611 const char *slave_name = NULL;
612 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000613 {
Greg Clayton71337622011-02-24 22:24:29 +0000614 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
615 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000616 }
Greg Clayton71337622011-02-24 22:24:29 +0000617 if (stdin_path == NULL)
618 stdin_path = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000619
Greg Clayton71337622011-02-24 22:24:29 +0000620 if (stdout_path == NULL)
621 stdout_path = slave_name;
622
623 if (stderr_path == NULL)
624 stderr_path = slave_name;
625 }
626
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000627 // Set STDIN to /dev/null if we want STDIO disabled or if either
628 // STDOUT or STDERR have been set to something and STDIN hasn't
629 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000630 stdin_path = "/dev/null";
631
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000632 // Set STDOUT to /dev/null if we want STDIO disabled or if either
633 // STDIN or STDERR have been set to something and STDOUT hasn't
634 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000635 stdout_path = "/dev/null";
636
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000637 // Set STDERR to /dev/null if we want STDIO disabled or if either
638 // STDIN or STDOUT have been set to something and STDERR hasn't
639 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000640 stderr_path = "/dev/null";
641
642 if (stdin_path)
643 m_gdb_comm.SetSTDIN (stdin_path);
644 if (stdout_path)
645 m_gdb_comm.SetSTDOUT (stdout_path);
646 if (stderr_path)
647 m_gdb_comm.SetSTDERR (stderr_path);
648
649 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
650
Greg Claytonc4103b32011-05-08 04:53:50 +0000651 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Clayton71337622011-02-24 22:24:29 +0000652
653 if (working_dir && working_dir[0])
654 {
655 m_gdb_comm.SetWorkingDir (working_dir);
656 }
657
658 // Send the environment and the program + arguments after we connect
Greg Clayton982c9762011-11-03 21:22:33 +0000659 const Args &environment = launch_info.GetEnvironmentEntries();
660 if (environment.GetArgumentCount())
Greg Clayton71337622011-02-24 22:24:29 +0000661 {
Greg Clayton982c9762011-11-03 21:22:33 +0000662 size_t num_environment_entries = environment.GetArgumentCount();
663 for (size_t i=0; i<num_environment_entries; ++i)
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000664 {
Greg Clayton982c9762011-11-03 21:22:33 +0000665 const char *env_entry = environment.GetArgumentAtIndex(i);
666 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Clayton71337622011-02-24 22:24:29 +0000667 break;
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000668 }
Greg Clayton71337622011-02-24 22:24:29 +0000669 }
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000670
Greg Claytonc574ede2011-03-10 02:26:48 +0000671 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Clayton982c9762011-11-03 21:22:33 +0000672 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info.GetArguments().GetConstArgumentVector());
Greg Clayton71337622011-02-24 22:24:29 +0000673 if (arg_packet_err == 0)
674 {
675 std::string error_str;
Greg Claytonc574ede2011-03-10 02:26:48 +0000676 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000677 {
Greg Claytonc574ede2011-03-10 02:26:48 +0000678 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000679 }
680 else
681 {
Greg Clayton71337622011-02-24 22:24:29 +0000682 error.SetErrorString (error_str.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000683 }
Greg Clayton71337622011-02-24 22:24:29 +0000684 }
685 else
686 {
Greg Clayton86edbf42011-10-26 00:56:27 +0000687 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Clayton71337622011-02-24 22:24:29 +0000688 }
Greg Clayton8b45bee2011-08-10 22:05:39 +0000689
690 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000691
Greg Clayton71337622011-02-24 22:24:29 +0000692 if (GetID() == LLDB_INVALID_PROCESS_ID)
693 {
Johnny Chen4c1e9202011-08-09 18:56:45 +0000694 if (log)
695 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton71337622011-02-24 22:24:29 +0000696 KillDebugserverProcess ();
697 return error;
698 }
699
Greg Claytondd0e5a52011-06-02 22:22:38 +0000700 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Clayton71337622011-02-24 22:24:29 +0000701 {
Greg Claytondd0e5a52011-06-02 22:22:38 +0000702 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Clayton71337622011-02-24 22:24:29 +0000703
704 if (!disable_stdio)
705 {
706 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Claytonee95ed52011-11-17 22:14:31 +0000707 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Clayton71337622011-02-24 22:24:29 +0000708 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000709 }
710 }
Greg Claytonc235ac72011-08-09 05:20:29 +0000711 else
712 {
Johnny Chen4c1e9202011-08-09 18:56:45 +0000713 if (log)
714 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytonc235ac72011-08-09 05:20:29 +0000715 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000716 }
717 else
718 {
719 // Set our user ID to an invalid process ID.
720 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton982c9762011-11-03 21:22:33 +0000721 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
722 exe_module->GetFileSpec().GetFilename().AsCString(),
723 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000724 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000725 return error;
Greg Clayton4957bf62010-09-30 21:49:03 +0000726
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000727}
728
729
730Error
Greg Claytonb766a732011-02-04 01:58:07 +0000731ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000732{
733 Error error;
734 // Sleep and wait a bit for debugserver to start to listen...
Greg Clayton7b0992d2013-04-18 22:45:39 +0000735 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000736 if (conn_ap.get())
737 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000738 const uint32_t max_retry_count = 50;
739 uint32_t retry_count = 0;
740 while (!m_gdb_comm.IsConnected())
741 {
Greg Claytonb766a732011-02-04 01:58:07 +0000742 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000743 {
744 m_gdb_comm.SetConnection (conn_ap.release());
745 break;
746 }
Jim Ingham4e5c8212013-06-07 22:09:53 +0000747 else if (error.WasInterrupted())
748 {
749 // If we were interrupted, don't keep retrying.
750 break;
751 }
752
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000753 retry_count++;
Jim Ingham4e5c8212013-06-07 22:09:53 +0000754
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000755 if (retry_count >= max_retry_count)
756 break;
757
758 usleep (100000);
759 }
760 }
761
762 if (!m_gdb_comm.IsConnected())
763 {
764 if (error.Success())
765 error.SetErrorString("not connected to remote gdb server");
766 return error;
767 }
768
Greg Clayton32e0a752011-03-30 18:16:51 +0000769 // We always seem to be able to open a connection to a local port
770 // so we need to make sure we can then send data to it. If we can't
771 // then we aren't actually connected to anything, so try and do the
772 // handshake with the remote GDB server and make sure that goes
773 // alright.
774 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000775 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000776 m_gdb_comm.Disconnect();
777 if (error.Success())
778 error.SetErrorString("not connected to remote gdb server");
779 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000780 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000781 m_gdb_comm.ResetDiscoverableSettings();
782 m_gdb_comm.QueryNoAckModeSupported ();
783 m_gdb_comm.GetThreadSuffixSupported ();
Greg Clayton44633992012-04-10 03:22:03 +0000784 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +0000785 m_gdb_comm.GetHostInfo ();
786 m_gdb_comm.GetVContSupported ('c');
Jim Inghamcd16df92012-07-20 21:37:13 +0000787 m_gdb_comm.GetVAttachOrWaitSupported();
Jim Ingham03afad82012-07-02 05:40:07 +0000788
789 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
790 for (size_t idx = 0; idx < num_cmds; idx++)
791 {
792 StringExtractorGDBRemote response;
Jim Ingham03afad82012-07-02 05:40:07 +0000793 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
794 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000795 return error;
796}
797
798void
799ProcessGDBRemote::DidLaunchOrAttach ()
800{
Greg Clayton5160ce52013-03-27 23:08:40 +0000801 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +0000802 if (log)
803 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton93d3c8332011-02-16 04:46:07 +0000804 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000805 {
806 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
807
Greg Clayton513c26c2011-01-29 07:10:55 +0000808 BuildDynamicRegisterInfo (false);
Greg Clayton3af9ea52010-11-18 05:57:03 +0000809
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000810 // See if the GDB server supports the qHostInfo information
Greg Clayton0d0c12a2011-02-09 03:09:55 +0000811
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000812 ArchSpec gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
813
814 // See if the GDB server supports the qProcessInfo packet, if so
815 // prefer that over the Host information as it will be more specific
816 // to our process.
817
818 if (m_gdb_comm.GetProcessArchitecture().IsValid())
819 gdb_remote_arch = m_gdb_comm.GetProcessArchitecture();
820
Greg Claytond314e812011-03-23 00:09:55 +0000821 if (gdb_remote_arch.IsValid())
Greg Clayton0d0c12a2011-02-09 03:09:55 +0000822 {
Greg Claytond314e812011-03-23 00:09:55 +0000823 ArchSpec &target_arch = GetTarget().GetArchitecture();
824
825 if (target_arch.IsValid())
826 {
827 // If the remote host is ARM and we have apple as the vendor, then
828 // ARM executables and shared libraries can have mixed ARM architectures.
829 // You can have an armv6 executable, and if the host is armv7, then the
830 // system will load the best possible architecture for all shared libraries
831 // it has, so we really need to take the remote host architecture as our
832 // defacto architecture in this case.
833
834 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
835 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
836 {
837 target_arch = gdb_remote_arch;
838 }
839 else
840 {
841 // Fill in what is missing in the triple
842 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
843 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton70b57652011-05-15 01:25:55 +0000844 if (target_triple.getVendorName().size() == 0)
845 {
Greg Claytond314e812011-03-23 00:09:55 +0000846 target_triple.setVendor (remote_triple.getVendor());
847
Greg Clayton70b57652011-05-15 01:25:55 +0000848 if (target_triple.getOSName().size() == 0)
849 {
850 target_triple.setOS (remote_triple.getOS());
Greg Claytond314e812011-03-23 00:09:55 +0000851
Greg Clayton70b57652011-05-15 01:25:55 +0000852 if (target_triple.getEnvironmentName().size() == 0)
853 target_triple.setEnvironment (remote_triple.getEnvironment());
854 }
855 }
Greg Claytond314e812011-03-23 00:09:55 +0000856 }
857 }
858 else
859 {
860 // The target doesn't have a valid architecture yet, set it from
861 // the architecture we got from the remote GDB server
862 target_arch = gdb_remote_arch;
863 }
Greg Clayton0d0c12a2011-02-09 03:09:55 +0000864 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000865 }
866}
867
868void
869ProcessGDBRemote::DidLaunch ()
870{
871 DidLaunchOrAttach ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000872}
873
874Error
Greg Claytonc982c762010-07-09 20:39:50 +0000875ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000876{
Han Ming Ong84647042012-02-25 01:07:38 +0000877 ProcessAttachInfo attach_info;
878 return DoAttachToProcessWithID(attach_pid, attach_info);
879}
880
881Error
882ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
883{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000884 Error error;
885 // Clear out and clean up from any current state
886 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000887 if (attach_pid != LLDB_INVALID_PROCESS_ID)
888 {
Greg Clayton71337622011-02-24 22:24:29 +0000889 // Make sure we aren't already connected?
890 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000891 {
Greg Clayton71337622011-02-24 22:24:29 +0000892 char host_port[128];
893 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
894 char connect_url[128];
895 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000896
Han Ming Ong84647042012-02-25 01:07:38 +0000897 error = StartDebugserverProcess (host_port, attach_info);
Greg Clayton71337622011-02-24 22:24:29 +0000898
899 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000900 {
Greg Clayton71337622011-02-24 22:24:29 +0000901 const char *error_string = error.AsCString();
902 if (error_string == NULL)
903 error_string = "unable to launch " DEBUGSERVER_BASENAME;
904
905 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000906 }
Greg Clayton71337622011-02-24 22:24:29 +0000907 else
908 {
909 error = ConnectToDebugserver (connect_url);
910 }
911 }
912
913 if (error.Success())
914 {
915 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +0000916 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Greg Clayton3b608422011-11-19 02:11:30 +0000917 SetID (attach_pid);
Greg Clayton71337622011-02-24 22:24:29 +0000918 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000919 }
920 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000921 return error;
922}
923
924size_t
925ProcessGDBRemote::AttachInputReaderCallback
926(
927 void *baton,
928 InputReader *reader,
929 lldb::InputReaderAction notification,
930 const char *bytes,
931 size_t bytes_len
932)
933{
934 if (notification == eInputReaderGotToken)
935 {
936 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
937 if (gdb_process->m_waiting_for_attach)
938 gdb_process->m_waiting_for_attach = false;
939 reader->SetIsDone(true);
940 return 1;
941 }
942 return 0;
943}
944
945Error
Han Ming Ong84647042012-02-25 01:07:38 +0000946ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000947{
948 Error error;
949 // Clear out and clean up from any current state
950 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000951
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000952 if (process_name && process_name[0])
953 {
Greg Clayton71337622011-02-24 22:24:29 +0000954 // Make sure we aren't already connected?
955 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000956 {
Greg Clayton71337622011-02-24 22:24:29 +0000957 char host_port[128];
958 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
959 char connect_url[128];
960 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
961
Han Ming Ong84647042012-02-25 01:07:38 +0000962 error = StartDebugserverProcess (host_port, attach_info);
Greg Clayton71337622011-02-24 22:24:29 +0000963 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000964 {
Greg Clayton71337622011-02-24 22:24:29 +0000965 const char *error_string = error.AsCString();
966 if (error_string == NULL)
967 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000968
Greg Clayton71337622011-02-24 22:24:29 +0000969 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000970 }
Greg Clayton71337622011-02-24 22:24:29 +0000971 else
972 {
973 error = ConnectToDebugserver (connect_url);
974 }
975 }
976
977 if (error.Success())
978 {
979 StreamString packet;
980
981 if (wait_for_launch)
Jim Inghamcd16df92012-07-20 21:37:13 +0000982 {
983 if (!m_gdb_comm.GetVAttachOrWaitSupported())
984 {
985 packet.PutCString ("vAttachWait");
986 }
987 else
988 {
989 if (attach_info.GetIgnoreExisting())
990 packet.PutCString("vAttachWait");
991 else
992 packet.PutCString ("vAttachOrWait");
993 }
994 }
Greg Clayton71337622011-02-24 22:24:29 +0000995 else
996 packet.PutCString("vAttachName");
997 packet.PutChar(';');
998 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
999
1000 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1001
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001002 }
1003 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001004 return error;
1005}
1006
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001007
1008void
1009ProcessGDBRemote::DidAttach ()
1010{
Greg Claytonb766a732011-02-04 01:58:07 +00001011 DidLaunchOrAttach ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001012}
1013
Greg Clayton90ba8112012-12-05 00:16:59 +00001014
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001015Error
1016ProcessGDBRemote::WillResume ()
1017{
Greg Clayton71fc2a32011-02-12 06:28:37 +00001018 m_continue_c_tids.clear();
1019 m_continue_C_tids.clear();
1020 m_continue_s_tids.clear();
1021 m_continue_S_tids.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001022 return Error();
1023}
1024
1025Error
1026ProcessGDBRemote::DoResume ()
1027{
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001028 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001029 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001030 if (log)
1031 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytone5219662010-12-03 06:02:24 +00001032
1033 Listener listener ("gdb-remote.resume-packet-sent");
1034 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1035 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00001036 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1037
Greg Claytond1d06e42013-04-20 00:27:58 +00001038 const size_t num_threads = GetThreadList().GetSize();
1039
Greg Clayton71fc2a32011-02-12 06:28:37 +00001040 StreamString continue_packet;
1041 bool continue_packet_error = false;
1042 if (m_gdb_comm.HasAnyVContSupport ())
1043 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001044 if (m_continue_c_tids.size() == num_threads)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001045 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001046 // All threads are continuing, just send a "c" packet
1047 continue_packet.PutCString ("c");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001048 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001049 else
1050 {
1051 continue_packet.PutCString ("vCont");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001052
Greg Claytond1d06e42013-04-20 00:27:58 +00001053 if (!m_continue_c_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001054 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001055 if (m_gdb_comm.GetVContSupported ('c'))
1056 {
1057 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)
1058 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1059 }
1060 else
1061 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001062 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001063
1064 if (!continue_packet_error && !m_continue_C_tids.empty())
1065 {
1066 if (m_gdb_comm.GetVContSupported ('C'))
1067 {
1068 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)
1069 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1070 }
1071 else
1072 continue_packet_error = true;
1073 }
Greg Claytone5219662010-12-03 06:02:24 +00001074
Greg Claytond1d06e42013-04-20 00:27:58 +00001075 if (!continue_packet_error && !m_continue_s_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001076 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001077 if (m_gdb_comm.GetVContSupported ('s'))
1078 {
1079 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)
1080 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1081 }
1082 else
1083 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001084 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001085
1086 if (!continue_packet_error && !m_continue_S_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001087 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001088 if (m_gdb_comm.GetVContSupported ('S'))
1089 {
1090 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)
1091 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1092 }
1093 else
1094 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001095 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001096
1097 if (continue_packet_error)
1098 continue_packet.GetString().clear();
Greg Clayton71fc2a32011-02-12 06:28:37 +00001099 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001100 }
1101 else
1102 continue_packet_error = true;
1103
1104 if (continue_packet_error)
1105 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001106 // Either no vCont support, or we tried to use part of the vCont
1107 // packet that wasn't supported by the remote GDB server.
1108 // We need to try and make a simple packet that can do our continue
Greg Clayton71fc2a32011-02-12 06:28:37 +00001109 const size_t num_continue_c_tids = m_continue_c_tids.size();
1110 const size_t num_continue_C_tids = m_continue_C_tids.size();
1111 const size_t num_continue_s_tids = m_continue_s_tids.size();
1112 const size_t num_continue_S_tids = m_continue_S_tids.size();
1113 if (num_continue_c_tids > 0)
1114 {
1115 if (num_continue_c_tids == num_threads)
1116 {
1117 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001118 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001119 continue_packet.PutChar ('c');
1120 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001121 }
1122 else if (num_continue_c_tids == 1 &&
1123 num_continue_C_tids == 0 &&
1124 num_continue_s_tids == 0 &&
1125 num_continue_S_tids == 0 )
1126 {
1127 // Only one thread is continuing
Greg Clayton8b82f082011-04-12 05:54:46 +00001128 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001129 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001130 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001131 }
1132 }
1133
Greg Clayton0c74e782011-06-24 03:21:43 +00001134 if (continue_packet_error && num_continue_C_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001135 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001136 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1137 num_continue_C_tids > 0 &&
1138 num_continue_s_tids == 0 &&
1139 num_continue_S_tids == 0 )
Greg Clayton71fc2a32011-02-12 06:28:37 +00001140 {
1141 const int continue_signo = m_continue_C_tids.front().second;
Greg Clayton0c74e782011-06-24 03:21:43 +00001142 // Only one thread is continuing
Greg Clayton71fc2a32011-02-12 06:28:37 +00001143 if (num_continue_C_tids > 1)
1144 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001145 // More that one thread with a signal, yet we don't have
1146 // vCont support and we are being asked to resume each
1147 // thread with a signal, we need to make sure they are
1148 // all the same signal, or we can't issue the continue
1149 // accurately with the current support...
1150 if (num_continue_C_tids > 1)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001151 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001152 continue_packet_error = false;
1153 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1154 {
1155 if (m_continue_C_tids[i].second != continue_signo)
1156 continue_packet_error = true;
1157 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001158 }
Greg Clayton0c74e782011-06-24 03:21:43 +00001159 if (!continue_packet_error)
1160 m_gdb_comm.SetCurrentThreadForRun (-1);
1161 }
1162 else
1163 {
1164 // Set the continue thread ID
1165 continue_packet_error = false;
1166 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001167 }
1168 if (!continue_packet_error)
1169 {
1170 // Add threads continuing with the same signo...
Greg Clayton71fc2a32011-02-12 06:28:37 +00001171 continue_packet.Printf("C%2.2x", continue_signo);
1172 }
1173 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001174 }
1175
Greg Clayton0c74e782011-06-24 03:21:43 +00001176 if (continue_packet_error && num_continue_s_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001177 {
1178 if (num_continue_s_tids == num_threads)
1179 {
1180 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001181 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001182 continue_packet.PutChar ('s');
1183 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001184 }
1185 else if (num_continue_c_tids == 0 &&
1186 num_continue_C_tids == 0 &&
1187 num_continue_s_tids == 1 &&
1188 num_continue_S_tids == 0 )
1189 {
1190 // Only one thread is stepping
Greg Clayton8b82f082011-04-12 05:54:46 +00001191 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001192 continue_packet.PutChar ('s');
Greg Clayton0c74e782011-06-24 03:21:43 +00001193 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001194 }
1195 }
1196
1197 if (!continue_packet_error && num_continue_S_tids > 0)
1198 {
1199 if (num_continue_S_tids == num_threads)
1200 {
1201 const int step_signo = m_continue_S_tids.front().second;
1202 // Are all threads trying to step with the same signal?
Greg Clayton0c74e782011-06-24 03:21:43 +00001203 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001204 if (num_continue_S_tids > 1)
1205 {
1206 for (size_t i=1; i<num_threads; ++i)
1207 {
1208 if (m_continue_S_tids[i].second != step_signo)
1209 continue_packet_error = true;
1210 }
1211 }
1212 if (!continue_packet_error)
1213 {
1214 // Add threads stepping with the same signo...
Greg Clayton8b82f082011-04-12 05:54:46 +00001215 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001216 continue_packet.Printf("S%2.2x", step_signo);
1217 }
1218 }
1219 else if (num_continue_c_tids == 0 &&
1220 num_continue_C_tids == 0 &&
1221 num_continue_s_tids == 0 &&
1222 num_continue_S_tids == 1 )
1223 {
1224 // Only one thread is stepping with signal
Greg Clayton8b82f082011-04-12 05:54:46 +00001225 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001226 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Clayton0c74e782011-06-24 03:21:43 +00001227 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001228 }
1229 }
1230 }
1231
1232 if (continue_packet_error)
1233 {
1234 error.SetErrorString ("can't make continue packet for this resume");
1235 }
1236 else
1237 {
1238 EventSP event_sp;
1239 TimeValue timeout;
1240 timeout = TimeValue::Now();
1241 timeout.OffsetWithSeconds (5);
Jim Inghamb1e2e842012-04-12 18:49:31 +00001242 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1243 {
1244 error.SetErrorString ("Trying to resume but the async thread is dead.");
1245 if (log)
1246 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1247 return error;
1248 }
1249
Greg Clayton71fc2a32011-02-12 06:28:37 +00001250 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1251
1252 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Inghamb1e2e842012-04-12 18:49:31 +00001253 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001254 error.SetErrorString("Resume timed out.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00001255 if (log)
1256 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1257 }
1258 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1259 {
1260 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1261 if (log)
1262 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1263 return error;
1264 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001265 }
Greg Claytone5219662010-12-03 06:02:24 +00001266 }
1267
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001268 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001269}
1270
Greg Clayton9e920902012-04-10 02:25:43 +00001271void
1272ProcessGDBRemote::ClearThreadIDList ()
1273{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001274 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001275 m_thread_ids.clear();
1276}
1277
1278bool
1279ProcessGDBRemote::UpdateThreadIDList ()
1280{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001281 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001282 bool sequence_mutex_unavailable = false;
1283 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1284 if (sequence_mutex_unavailable)
1285 {
Greg Clayton9e920902012-04-10 02:25:43 +00001286 return false; // We just didn't get the list
1287 }
1288 return true;
1289}
1290
Greg Clayton9fc13552012-04-10 00:18:59 +00001291bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001292ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001293{
1294 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +00001295 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Clayton73b472d2010-10-27 03:32:59 +00001296 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +00001297 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton9e920902012-04-10 02:25:43 +00001298
1299 size_t num_thread_ids = m_thread_ids.size();
1300 // The "m_thread_ids" thread ID list should always be updated after each stop
1301 // reply packet, but in case it isn't, update it here.
1302 if (num_thread_ids == 0)
1303 {
1304 if (!UpdateThreadIDList ())
1305 return false;
1306 num_thread_ids = m_thread_ids.size();
1307 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001308
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001309 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001310 if (num_thread_ids > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001311 {
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001312 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001313 {
Greg Clayton9e920902012-04-10 02:25:43 +00001314 tid_t tid = m_thread_ids[i];
Greg Clayton160c9d82013-05-01 21:54:04 +00001315 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001316 if (!thread_sp)
Jim Ingham4f465cf2012-10-10 18:32:14 +00001317 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001318 new_thread_list.AddThread(thread_sp);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001319 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001320 }
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001321
1322 // Whatever that is left in old_thread_list_copy are not
1323 // present in new_thread_list. Remove non-existent threads from internal id table.
1324 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1325 for (size_t i=0; i<old_num_thread_ids; i++)
1326 {
1327 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1328 if (old_thread_sp)
1329 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001330 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001331 m_thread_id_to_index_id_map.erase(old_thread_id);
1332 }
1333 }
1334
Greg Clayton9fc13552012-04-10 00:18:59 +00001335 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001336}
1337
1338
1339StateType
1340ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1341{
Greg Claytondd0e5a52011-06-02 22:22:38 +00001342 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001343 const char stop_type = stop_packet.GetChar();
1344 switch (stop_type)
1345 {
1346 case 'T':
1347 case 'S':
1348 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00001349 // This is a bit of a hack, but is is required. If we did exec, we
1350 // need to clear our thread lists and also know to rebuild our dynamic
1351 // register info before we lookup and threads and populate the expedited
1352 // register values so we need to know this right away so we can cleanup
1353 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00001354 const uint32_t stop_id = GetStopID();
1355 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00001356 {
1357 // Our first stop, make sure we have a process ID, and also make
1358 // sure we know about our registers
1359 if (GetID() == LLDB_INVALID_PROCESS_ID)
1360 {
Greg Claytonc574ede2011-03-10 02:26:48 +00001361 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00001362 if (pid != LLDB_INVALID_PROCESS_ID)
1363 SetID (pid);
1364 }
1365 BuildDynamicRegisterInfo (true);
1366 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001367 // Stop with signal and thread info
1368 const uint8_t signo = stop_packet.GetHexU8();
1369 std::string name;
1370 std::string value;
1371 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00001372 std::string reason;
1373 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001374 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00001375 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001376 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001377 ThreadSP thread_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001378 ThreadGDBRemote *gdb_thread = NULL;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001379
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001380 while (stop_packet.GetNameColonValue(name, value))
1381 {
1382 if (name.compare("metype") == 0)
1383 {
1384 // exception type in big endian hex
1385 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1386 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001387 else if (name.compare("medata") == 0)
1388 {
1389 // exception data in big endian hex
1390 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1391 }
1392 else if (name.compare("thread") == 0)
1393 {
1394 // thread in big endian hex
Greg Clayton9e920902012-04-10 02:25:43 +00001395 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001396 // m_thread_list_real does have its own mutex, but we need to
1397 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1398 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1399 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1400 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
Greg Clayton160c9d82013-05-01 21:54:04 +00001401
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001402 if (!thread_sp)
Greg Claytond1d06e42013-04-20 00:27:58 +00001403 {
Greg Claytone576ab22011-02-15 00:19:15 +00001404 // Create the thread if we need to
Jim Ingham4f465cf2012-10-10 18:32:14 +00001405 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001406 m_thread_list_real.AddThread(thread_sp);
Greg Claytone576ab22011-02-15 00:19:15 +00001407 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001408 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1409
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001410 }
Greg Clayton9e920902012-04-10 02:25:43 +00001411 else if (name.compare("threads") == 0)
1412 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001413 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001414 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00001415 // A comma separated list of all threads in the current
1416 // process that includes the thread for this stop reply
1417 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00001418 size_t comma_pos;
1419 lldb::tid_t tid;
1420 while ((comma_pos = value.find(',')) != std::string::npos)
1421 {
1422 value[comma_pos] = '\0';
1423 // thread in big endian hex
1424 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1425 if (tid != LLDB_INVALID_THREAD_ID)
1426 m_thread_ids.push_back (tid);
1427 value.erase(0, comma_pos + 1);
1428
1429 }
1430 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1431 if (tid != LLDB_INVALID_THREAD_ID)
1432 m_thread_ids.push_back (tid);
1433 }
Greg Claytonde9d0492011-01-08 03:17:57 +00001434 else if (name.compare("hexname") == 0)
1435 {
1436 StringExtractor name_extractor;
1437 // Swap "value" over into "name_extractor"
1438 name_extractor.GetStringRef().swap(value);
1439 // Now convert the HEX bytes into a string value
1440 name_extractor.GetHexByteString (value);
1441 thread_name.swap (value);
1442 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001443 else if (name.compare("name") == 0)
1444 {
1445 thread_name.swap (value);
1446 }
Greg Clayton6f35f5c2010-09-09 06:32:46 +00001447 else if (name.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001448 {
1449 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1450 }
Greg Claytona658fd22011-06-04 01:26:29 +00001451 else if (name.compare("reason") == 0)
1452 {
1453 reason.swap(value);
1454 }
1455 else if (name.compare("description") == 0)
1456 {
1457 StringExtractor desc_extractor;
1458 // Swap "value" over into "name_extractor"
1459 desc_extractor.GetStringRef().swap(value);
1460 // Now convert the HEX bytes into a string value
1461 desc_extractor.GetHexByteString (thread_name);
1462 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001463 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1464 {
1465 // We have a register number that contains an expedited
1466 // register value. Lets supply this register to our thread
1467 // so it won't have to go and read it.
Greg Clayton160c9d82013-05-01 21:54:04 +00001468 if (gdb_thread)
Greg Clayton3e06bd92011-01-09 21:07:35 +00001469 {
1470 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1471
1472 if (reg != UINT32_MAX)
1473 {
1474 StringExtractor reg_value_extractor;
1475 // Swap "value" over into "reg_value_extractor"
1476 reg_value_extractor.GetStringRef().swap(value);
Greg Clayton160c9d82013-05-01 21:54:04 +00001477 if (!gdb_thread->PrivateSetRegisterValue (reg, reg_value_extractor))
Greg Claytone576ab22011-02-15 00:19:15 +00001478 {
1479 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1480 name.c_str(),
1481 reg,
1482 reg,
1483 reg_value_extractor.GetStringRef().c_str(),
1484 stop_packet.GetStringRef().c_str());
1485 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001486 }
1487 }
1488 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001489 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001490
1491 if (thread_sp)
1492 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001493 // Clear the stop info just in case we don't set it to anything
1494 thread_sp->SetStopInfo (StopInfoSP());
1495
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001496 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Inghamdd2fe7a2011-01-28 02:23:12 +00001497 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001498 if (exc_type != 0)
1499 {
Greg Clayton1a65ae12011-01-25 23:55:37 +00001500 const size_t exc_data_size = exc_data.size();
Greg Claytonf4b47e12010-08-04 01:40:35 +00001501
Greg Clayton160c9d82013-05-01 21:54:04 +00001502 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1503 exc_type,
1504 exc_data_size,
1505 exc_data_size >= 1 ? exc_data[0] : 0,
1506 exc_data_size >= 2 ? exc_data[1] : 0,
1507 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001508 }
Greg Claytona658fd22011-06-04 01:26:29 +00001509 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001510 {
Greg Claytona658fd22011-06-04 01:26:29 +00001511 bool handled = false;
Greg Clayton8cda7f02013-05-21 21:55:59 +00001512 bool did_exec = false;
Greg Claytona658fd22011-06-04 01:26:29 +00001513 if (!reason.empty())
1514 {
1515 if (reason.compare("trace") == 0)
1516 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001517 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Greg Claytona658fd22011-06-04 01:26:29 +00001518 handled = true;
1519 }
1520 else if (reason.compare("breakpoint") == 0)
1521 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001522 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1523 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Claytona658fd22011-06-04 01:26:29 +00001524 if (bp_site_sp)
1525 {
1526 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1527 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1528 // 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 +00001529 handled = true;
Greg Clayton160c9d82013-05-01 21:54:04 +00001530 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00001531 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001532 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00001533 }
1534 else
1535 {
1536 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001537 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00001538 }
1539 }
1540
Greg Claytona658fd22011-06-04 01:26:29 +00001541 }
1542 else if (reason.compare("trap") == 0)
1543 {
1544 // Let the trap just use the standard signal stop reason below...
1545 }
1546 else if (reason.compare("watchpoint") == 0)
1547 {
1548 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1549 // TODO: locate the watchpoint somehow...
Greg Clayton160c9d82013-05-01 21:54:04 +00001550 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
Greg Claytona658fd22011-06-04 01:26:29 +00001551 handled = true;
1552 }
1553 else if (reason.compare("exception") == 0)
1554 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001555 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00001556 handled = true;
1557 }
Greg Clayton15fc2be2013-05-21 01:00:52 +00001558 else if (reason.compare("exec") == 0)
1559 {
Greg Clayton8cda7f02013-05-21 21:55:59 +00001560 did_exec = true;
Greg Clayton15fc2be2013-05-21 01:00:52 +00001561 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
1562 handled = true;
1563 }
Greg Claytona658fd22011-06-04 01:26:29 +00001564 }
1565
Greg Clayton15fc2be2013-05-21 01:00:52 +00001566 if (signo && did_exec == false)
Greg Claytona658fd22011-06-04 01:26:29 +00001567 {
1568 if (signo == SIGTRAP)
1569 {
1570 // Currently we are going to assume SIGTRAP means we are either
1571 // hitting a breakpoint or hardware single stepping.
Jim Ingham54cc6e42012-07-11 21:41:19 +00001572 handled = true;
Greg Clayton160c9d82013-05-01 21:54:04 +00001573 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1574 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Jim Ingham54cc6e42012-07-11 21:41:19 +00001575
Greg Claytona658fd22011-06-04 01:26:29 +00001576 if (bp_site_sp)
1577 {
1578 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1579 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1580 // 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 +00001581 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00001582 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001583 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00001584 }
1585 else
1586 {
1587 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001588 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00001589 }
1590 }
Jim Ingham54cc6e42012-07-11 21:41:19 +00001591 else
Greg Claytona658fd22011-06-04 01:26:29 +00001592 {
Jim Ingham4dc613b2012-10-27 02:52:04 +00001593 // If we were stepping then assume the stop was the result of the trace. If we were
1594 // not stepping then report the SIGTRAP.
1595 // FIXME: We are still missing the case where we single step over a trap instruction.
Greg Clayton160c9d82013-05-01 21:54:04 +00001596 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1597 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Jim Ingham4dc613b2012-10-27 02:52:04 +00001598 else
Greg Clayton160c9d82013-05-01 21:54:04 +00001599 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo));
Greg Claytona658fd22011-06-04 01:26:29 +00001600 }
1601 }
1602 if (!handled)
Greg Clayton160c9d82013-05-01 21:54:04 +00001603 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Jason Molenda8214b012013-04-25 01:33:46 +00001604 }
Greg Claytona658fd22011-06-04 01:26:29 +00001605
1606 if (!description.empty())
1607 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001608 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
Greg Claytona658fd22011-06-04 01:26:29 +00001609 if (stop_info_sp)
1610 {
1611 stop_info_sp->SetDescription (description.c_str());
Greg Clayton3418c852011-08-10 02:10:13 +00001612 }
Greg Claytona658fd22011-06-04 01:26:29 +00001613 else
1614 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001615 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00001616 }
1617 }
1618 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001619 }
1620 return eStateStopped;
1621 }
1622 break;
1623
1624 case 'W':
1625 // process exited
1626 return eStateExited;
1627
1628 default:
1629 break;
1630 }
1631 return eStateInvalid;
1632}
1633
1634void
1635ProcessGDBRemote::RefreshStateAfterStop ()
1636{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001637 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001638 m_thread_ids.clear();
1639 // Set the thread stop info. It might have a "threads" key whose value is
1640 // a list of all thread IDs in the current process, so m_thread_ids might
1641 // get set.
1642 SetThreadStopInfo (m_last_stop_packet);
1643 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1644 if (m_thread_ids.empty())
1645 {
1646 // No, we need to fetch the thread list manually
1647 UpdateThreadIDList();
1648 }
1649
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001650 // Let all threads recover from stopping and do any clean up based
1651 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001652 m_thread_list_real.RefreshStateAfterStop();
Greg Clayton9e920902012-04-10 02:25:43 +00001653
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001654}
1655
1656Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001657ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001658{
1659 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001660
Greg Clayton6ed95942011-01-22 07:12:45 +00001661 bool timed_out = false;
1662 Mutex::Locker locker;
Greg Clayton513c26c2011-01-29 07:10:55 +00001663
1664 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00001665 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001666 // We are being asked to halt during an attach. We need to just close
1667 // our file handle and debugserver will go away, and we can be done...
1668 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00001669 }
Greg Clayton513c26c2011-01-29 07:10:55 +00001670 else
1671 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001672 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton513c26c2011-01-29 07:10:55 +00001673 {
1674 if (timed_out)
1675 error.SetErrorString("timed out sending interrupt packet");
1676 else
1677 error.SetErrorString("unknown error sending interrupt packet");
1678 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001679
1680 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton513c26c2011-01-29 07:10:55 +00001681 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001682 return error;
1683}
1684
1685Error
Jim Inghamacff8952013-05-02 00:27:30 +00001686ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00001687{
1688 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001689 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00001690 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00001691 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
1692
Greg Clayton594e5ed2010-09-27 21:07:38 +00001693 DisableAllBreakpointSites ();
1694
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001695 m_thread_list.DiscardThreadPlans();
Greg Clayton594e5ed2010-09-27 21:07:38 +00001696
Jim Inghamacff8952013-05-02 00:27:30 +00001697 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001698 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00001699 {
Jim Inghamacff8952013-05-02 00:27:30 +00001700 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001701 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1702 else
Jim Inghamacff8952013-05-02 00:27:30 +00001703 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00001704 }
Jim Inghamacff8952013-05-02 00:27:30 +00001705
1706 if (!error.Success())
1707 return error;
1708
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001709 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00001710 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001711
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001712 SetPrivateState (eStateDetached);
1713 ResumePrivateStateThread();
1714
1715 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00001716 return error;
1717}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001718
Jim Ingham43c555d2012-07-04 00:35:43 +00001719
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001720Error
1721ProcessGDBRemote::DoDestroy ()
1722{
1723 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001724 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001725 if (log)
1726 log->Printf ("ProcessGDBRemote::DoDestroy()");
1727
Jim Ingham43c555d2012-07-04 00:35:43 +00001728 // There is a bug in older iOS debugservers where they don't shut down the process
1729 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
1730 // this can cause problems with restarting. So we check to see if any of our threads are stopped
1731 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
1732 // destroy it again.
1733 //
1734 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
1735 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
1736 // the debugservers with this bug are equal. There really should be a better way to test this!
1737 //
1738 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
1739 // get called here to destroy again and we're still at a breakpoint or exception, then we should
1740 // just do the straight-forward kill.
1741 //
1742 // And of course, if we weren't able to stop the process by the time we get here, it isn't
1743 // necessary (or helpful) to do any of this.
1744
1745 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
1746 {
1747 PlatformSP platform_sp = GetTarget().GetPlatform();
1748
1749 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
1750 if (platform_sp
1751 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00001752 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00001753 {
1754 if (m_destroy_tried_resuming)
1755 {
1756 if (log)
1757 log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again.");
1758 }
1759 else
1760 {
1761 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
1762 // but we really need it to happen here and it doesn't matter if we do it twice.
1763 m_thread_list.DiscardThreadPlans();
1764 DisableAllBreakpointSites();
1765
1766 bool stop_looks_like_crash = false;
1767 ThreadList &threads = GetThreadList();
1768
1769 {
Jim Ingham45350372012-09-11 00:08:52 +00001770 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00001771
1772 size_t num_threads = threads.GetSize();
1773 for (size_t i = 0; i < num_threads; i++)
1774 {
1775 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00001776 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00001777 StopReason reason = eStopReasonInvalid;
1778 if (stop_info_sp)
1779 reason = stop_info_sp->GetStopReason();
1780 if (reason == eStopReasonBreakpoint
1781 || reason == eStopReasonException)
1782 {
1783 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00001784 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
1785 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00001786 stop_info_sp->GetDescription());
1787 stop_looks_like_crash = true;
1788 break;
1789 }
1790 }
1791 }
1792
1793 if (stop_looks_like_crash)
1794 {
1795 if (log)
1796 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
1797 m_destroy_tried_resuming = true;
1798
1799 // If we are going to run again before killing, it would be good to suspend all the threads
1800 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
1801 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
1802 // have to run the risk of letting those threads proceed a bit.
1803
1804 {
Jim Ingham45350372012-09-11 00:08:52 +00001805 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00001806
1807 size_t num_threads = threads.GetSize();
1808 for (size_t i = 0; i < num_threads; i++)
1809 {
1810 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00001811 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00001812 StopReason reason = eStopReasonInvalid;
1813 if (stop_info_sp)
1814 reason = stop_info_sp->GetStopReason();
1815 if (reason != eStopReasonBreakpoint
1816 && reason != eStopReasonException)
1817 {
1818 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00001819 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
1820 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00001821 thread_sp->SetResumeState(eStateSuspended);
1822 }
1823 }
1824 }
1825 Resume ();
1826 return Destroy();
1827 }
1828 }
1829 }
1830 }
1831
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001832 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00001833 int exit_status = SIGABRT;
1834 std::string exit_string;
1835
Greg Clayton6ed95942011-01-22 07:12:45 +00001836 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001837 {
Jim Inghamaab78372011-10-28 01:11:35 +00001838 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00001839 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001840
1841 StringExtractorGDBRemote response;
1842 bool send_async = true;
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00001843 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3);
1844
Greg Claytonc574ede2011-03-10 02:26:48 +00001845 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton513c26c2011-01-29 07:10:55 +00001846 {
1847 char packet_cmd = response.GetChar(0);
1848
1849 if (packet_cmd == 'W' || packet_cmd == 'X')
1850 {
Greg Clayton09c3e3d2011-12-06 04:51:14 +00001851 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00001852 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00001853 exit_status = response.GetHexU8();
1854 }
1855 else
1856 {
1857 if (log)
1858 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
1859 exit_string.assign("got unexpected response to k packet: ");
1860 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00001861 }
1862 }
1863 else
1864 {
Jim Inghambabfc382012-06-06 00:32:39 +00001865 if (log)
1866 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
1867 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00001868 }
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00001869
1870 m_gdb_comm.SetPacketTimeout(old_packet_timeout);
Greg Clayton6779606a2011-01-22 23:43:18 +00001871 }
Jim Inghambabfc382012-06-06 00:32:39 +00001872 else
1873 {
1874 if (log)
1875 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
Jim Inghamcfc09352012-07-27 23:57:19 +00001876 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00001877 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001878 }
Jim Inghambabfc382012-06-06 00:32:39 +00001879 else
1880 {
1881 // If we missed setting the exit status on the way out, do it here.
1882 // NB set exit status can be called multiple times, the first one sets the status.
1883 exit_string.assign("destroying when not connected to debugserver");
1884 }
1885
1886 SetExitStatus(exit_status, exit_string.c_str());
1887
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001888 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001889 KillDebugserverProcess ();
1890 return error;
1891}
1892
Greg Clayton8cda7f02013-05-21 21:55:59 +00001893void
1894ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
1895{
1896 lldb_private::Mutex::Locker locker (m_last_stop_packet_mutex);
1897 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
1898 if (did_exec)
1899 {
1900 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1901 if (log)
1902 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
1903
1904 m_thread_list_real.Clear();
1905 m_thread_list.Clear();
1906 BuildDynamicRegisterInfo (true);
1907 m_gdb_comm.ResetDiscoverableSettings();
1908 }
1909 m_last_stop_packet = response;
1910}
1911
1912
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001913//------------------------------------------------------------------
1914// Process Queries
1915//------------------------------------------------------------------
1916
1917bool
1918ProcessGDBRemote::IsAlive ()
1919{
Greg Clayton10177aa2010-12-08 05:08:21 +00001920 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001921}
1922
1923addr_t
1924ProcessGDBRemote::GetImageInfoAddress()
1925{
Jason Molenda6ba6d3d2013-01-30 04:39:32 +00001926 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001927}
1928
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001929//------------------------------------------------------------------
1930// Process Memory
1931//------------------------------------------------------------------
1932size_t
1933ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1934{
1935 if (size > m_max_memory_size)
1936 {
1937 // Keep memory read sizes down to a sane limit. This function will be
1938 // called multiple times in order to complete the task by
1939 // lldb_private::Process so it is ok to do this.
1940 size = m_max_memory_size;
1941 }
1942
1943 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001944 const int packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
Andy Gibbsa297a972013-06-19 19:04:53 +00001945 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001946 StringExtractorGDBRemote response;
Greg Claytonc574ede2011-03-10 02:26:48 +00001947 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001948 {
Greg Clayton576d8832011-03-22 04:00:09 +00001949 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001950 {
1951 error.Clear();
1952 return response.GetHexBytes(buf, size, '\xdd');
1953 }
Greg Clayton576d8832011-03-22 04:00:09 +00001954 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00001955 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00001956 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00001957 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001958 else
Greg Clayton9944cd72012-09-19 01:46:31 +00001959 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001960 }
1961 else
1962 {
Jim Ingham35579dd2013-06-03 19:34:01 +00001963 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001964 }
1965 return 0;
1966}
1967
1968size_t
1969ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1970{
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00001971 if (size > m_max_memory_size)
1972 {
1973 // Keep memory read sizes down to a sane limit. This function will be
1974 // called multiple times in order to complete the task by
1975 // lldb_private::Process so it is ok to do this.
1976 size = m_max_memory_size;
1977 }
1978
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001979 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00001980 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Clayton7fb56d02011-02-01 01:31:41 +00001981 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001982 StringExtractorGDBRemote response;
Greg Claytonc574ede2011-03-10 02:26:48 +00001983 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001984 {
Greg Clayton576d8832011-03-22 04:00:09 +00001985 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001986 {
1987 error.Clear();
1988 return size;
1989 }
Greg Clayton576d8832011-03-22 04:00:09 +00001990 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00001991 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00001992 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00001993 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001994 else
Greg Clayton9944cd72012-09-19 01:46:31 +00001995 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 +00001996 }
1997 else
1998 {
Jim Ingham35579dd2013-06-03 19:34:01 +00001999 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002000 }
2001 return 0;
2002}
2003
2004lldb::addr_t
2005ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2006{
Greg Clayton2a48f522011-05-14 01:50:35 +00002007 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2008
Greg Clayton70b57652011-05-15 01:25:55 +00002009 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton2a48f522011-05-14 01:50:35 +00002010 switch (supported)
2011 {
2012 case eLazyBoolCalculate:
2013 case eLazyBoolYes:
2014 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2015 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2016 return allocated_addr;
2017
2018 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002019 // Call mmap() to create memory in the inferior..
2020 unsigned prot = 0;
2021 if (permissions & lldb::ePermissionsReadable)
2022 prot |= eMmapProtRead;
2023 if (permissions & lldb::ePermissionsWritable)
2024 prot |= eMmapProtWrite;
2025 if (permissions & lldb::ePermissionsExecutable)
2026 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00002027
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002028 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2029 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2030 m_addr_to_mmap_size[allocated_addr] = size;
2031 else
2032 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton2a48f522011-05-14 01:50:35 +00002033 break;
2034 }
2035
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002036 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00002037 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002038 else
2039 error.Clear();
2040 return allocated_addr;
2041}
2042
2043Error
Greg Clayton46fb5582011-11-18 07:03:08 +00002044ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2045 MemoryRegionInfo &region_info)
2046{
2047
2048 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2049 return error;
2050}
2051
2052Error
Johnny Chen64637202012-05-23 21:09:52 +00002053ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2054{
2055
2056 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2057 return error;
2058}
2059
2060Error
Enrico Granataf04a2192012-07-13 23:18:48 +00002061ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2062{
2063 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2064 return error;
2065}
2066
2067Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002068ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2069{
2070 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00002071 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2072
2073 switch (supported)
2074 {
2075 case eLazyBoolCalculate:
2076 // We should never be deallocating memory without allocating memory
2077 // first so we should never get eLazyBoolCalculate
2078 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2079 break;
2080
2081 case eLazyBoolYes:
2082 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00002083 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002084 break;
2085
2086 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002087 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00002088 {
2089 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002090 if (pos != m_addr_to_mmap_size.end() &&
2091 InferiorCallMunmap(this, addr, pos->second))
2092 m_addr_to_mmap_size.erase (pos);
2093 else
Daniel Malead01b2952012-11-29 21:49:15 +00002094 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002095 }
2096 break;
2097 }
2098
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002099 return error;
2100}
2101
2102
2103//------------------------------------------------------------------
2104// Process STDIO
2105//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002106size_t
2107ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2108{
2109 if (m_stdio_communication.IsConnected())
2110 {
2111 ConnectionStatus status;
2112 m_stdio_communication.Write(src, src_len, status, NULL);
2113 }
2114 return 0;
2115}
2116
2117Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002118ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002119{
2120 Error error;
2121 assert (bp_site != NULL);
2122
Greg Clayton5160ce52013-03-27 23:08:40 +00002123 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002124 user_id_t site_id = bp_site->GetID();
2125 const addr_t addr = bp_site->GetLoadAddress();
2126 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002127 log->Printf ("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002128
2129 if (bp_site->IsEnabled())
2130 {
2131 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002132 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 +00002133 return error;
2134 }
2135 else
2136 {
2137 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2138
2139 if (bp_site->HardwarePreferred())
2140 {
2141 // Try and set hardware breakpoint, and if that fails, fall through
2142 // and set a software breakpoint?
Greg Clayton8b82f082011-04-12 05:54:46 +00002143 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002144 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002145 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002146 {
2147 bp_site->SetEnabled(true);
Greg Clayton8b82f082011-04-12 05:54:46 +00002148 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002149 return error;
2150 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002151 }
2152 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002153
2154 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002155 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002156 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
2157 {
2158 bp_site->SetEnabled(true);
2159 bp_site->SetType (BreakpointSite::eExternal);
2160 return error;
2161 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002162 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002163
2164 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002165 }
2166
2167 if (log)
2168 {
2169 const char *err_string = error.AsCString();
Jim Ingham299c0c12013-02-15 02:06:30 +00002170 log->Printf ("ProcessGDBRemote::EnableBreakpointSite () error for breakpoint at 0x%8.8" PRIx64 ": %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002171 bp_site->GetLoadAddress(),
2172 err_string ? err_string : "NULL");
2173 }
2174 // We shouldn't reach here on a successful breakpoint enable...
2175 if (error.Success())
2176 error.SetErrorToGenericError();
2177 return error;
2178}
2179
2180Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002181ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002182{
2183 Error error;
2184 assert (bp_site != NULL);
2185 addr_t addr = bp_site->GetLoadAddress();
2186 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00002187 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002188 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002189 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002190
2191 if (bp_site->IsEnabled())
2192 {
2193 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2194
Greg Clayton8b82f082011-04-12 05:54:46 +00002195 BreakpointSite::Type bp_type = bp_site->GetType();
2196 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002197 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002198 case BreakpointSite::eSoftware:
2199 error = DisableSoftwareBreakpoint (bp_site);
2200 break;
2201
2202 case BreakpointSite::eHardware:
2203 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2204 error.SetErrorToGenericError();
2205 break;
2206
2207 case BreakpointSite::eExternal:
2208 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2209 error.SetErrorToGenericError();
2210 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002211 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002212 if (error.Success())
2213 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002214 }
2215 else
2216 {
2217 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002218 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 +00002219 return error;
2220 }
2221
2222 if (error.Success())
2223 error.SetErrorToGenericError();
2224 return error;
2225}
2226
Johnny Chen11309a32011-09-06 22:38:36 +00002227// Pre-requisite: wp != NULL.
2228static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00002229GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00002230{
2231 assert(wp);
2232 bool watch_read = wp->WatchpointRead();
2233 bool watch_write = wp->WatchpointWrite();
2234
2235 // watch_read and watch_write cannot both be false.
2236 assert(watch_read || watch_write);
2237 if (watch_read && watch_write)
2238 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00002239 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00002240 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00002241 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00002242 return eWatchpointWrite;
2243}
2244
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002245Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002246ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002247{
2248 Error error;
2249 if (wp)
2250 {
2251 user_id_t watchID = wp->GetID();
2252 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00002253 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002254 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002255 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002256 if (wp->IsEnabled())
2257 {
2258 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002259 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 +00002260 return error;
2261 }
Johnny Chen11309a32011-09-06 22:38:36 +00002262
2263 GDBStoppointType type = GetGDBStoppointType(wp);
2264 // Pass down an appropriate z/Z packet...
2265 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002266 {
Johnny Chen11309a32011-09-06 22:38:36 +00002267 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2268 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002269 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002270 return error;
2271 }
2272 else
2273 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002274 }
Johnny Chen11309a32011-09-06 22:38:36 +00002275 else
2276 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002277 }
2278 else
2279 {
Johnny Chen01a67862011-10-14 00:42:25 +00002280 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002281 }
2282 if (error.Success())
2283 error.SetErrorToGenericError();
2284 return error;
2285}
2286
2287Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002288ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002289{
2290 Error error;
2291 if (wp)
2292 {
2293 user_id_t watchID = wp->GetID();
2294
Greg Clayton5160ce52013-03-27 23:08:40 +00002295 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002296
2297 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00002298
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002299 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002300 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002301
Johnny Chen11309a32011-09-06 22:38:36 +00002302 if (!wp->IsEnabled())
2303 {
2304 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002305 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 +00002306 // See also 'class WatchpointSentry' within StopInfo.cpp.
2307 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2308 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00002309 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002310 return error;
2311 }
2312
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002313 if (wp->IsHardware())
2314 {
Johnny Chen11309a32011-09-06 22:38:36 +00002315 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002316 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00002317 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2318 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002319 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002320 return error;
2321 }
2322 else
2323 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002324 }
2325 // TODO: clear software watchpoints if we implement them
2326 }
2327 else
2328 {
Johnny Chen01a67862011-10-14 00:42:25 +00002329 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002330 }
2331 if (error.Success())
2332 error.SetErrorToGenericError();
2333 return error;
2334}
2335
2336void
2337ProcessGDBRemote::Clear()
2338{
2339 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002340 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002341 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002342}
2343
2344Error
2345ProcessGDBRemote::DoSignal (int signo)
2346{
2347 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002348 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002349 if (log)
2350 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2351
2352 if (!m_gdb_comm.SendAsyncSignal (signo))
2353 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2354 return error;
2355}
2356
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002357Error
Han Ming Ong84647042012-02-25 01:07:38 +00002358ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)
2359{
2360 ProcessLaunchInfo launch_info;
2361 return StartDebugserverProcess(debugserver_url, launch_info);
2362}
2363
2364Error
2365ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url, const ProcessInfo &process_info) // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002366{
2367 Error error;
2368 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2369 {
2370 // If we locate debugserver, keep that located version around
2371 static FileSpec g_debugserver_file_spec;
2372
Han Ming Ong84647042012-02-25 01:07:38 +00002373 ProcessLaunchInfo debugserver_launch_info;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002374 char debugserver_path[PATH_MAX];
Han Ming Ong84647042012-02-25 01:07:38 +00002375 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002376
2377 // Always check to see if we have an environment override for the path
2378 // to the debugserver to use and use it if we do.
2379 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2380 if (env_debugserver_path)
Greg Clayton274060b2010-10-20 20:54:39 +00002381 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002382 else
2383 debugserver_file_spec = g_debugserver_file_spec;
2384 bool debugserver_exists = debugserver_file_spec.Exists();
2385 if (!debugserver_exists)
2386 {
2387 // The debugserver binary is in the LLDB.framework/Resources
2388 // directory.
Greg Claytondd36def2010-10-17 22:03:32 +00002389 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002390 {
Greg Claytondd36def2010-10-17 22:03:32 +00002391 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002392 debugserver_exists = debugserver_file_spec.Exists();
Greg Claytondd36def2010-10-17 22:03:32 +00002393 if (debugserver_exists)
2394 {
2395 g_debugserver_file_spec = debugserver_file_spec;
2396 }
2397 else
2398 {
2399 g_debugserver_file_spec.Clear();
2400 debugserver_file_spec.Clear();
2401 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002402 }
2403 }
2404
2405 if (debugserver_exists)
2406 {
2407 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2408
2409 m_stdio_communication.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002410
Greg Clayton5160ce52013-03-27 23:08:40 +00002411 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002412
Han Ming Ong84647042012-02-25 01:07:38 +00002413 Args &debugserver_args = debugserver_launch_info.GetArguments();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002414 char arg_cstr[PATH_MAX];
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002415
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002416 // Start args with "debugserver /file/path -r --"
2417 debugserver_args.AppendArgument(debugserver_path);
2418 debugserver_args.AppendArgument(debugserver_url);
Greg Claytondd36def2010-10-17 22:03:32 +00002419 // use native registers, not the GDB registers
2420 debugserver_args.AppendArgument("--native-regs");
2421 // make debugserver run in its own session so signals generated by
2422 // special terminal key sequences (^C) don't affect debugserver
2423 debugserver_args.AppendArgument("--setsid");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002424
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002425 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2426 if (env_debugserver_log_file)
2427 {
2428 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2429 debugserver_args.AppendArgument(arg_cstr);
2430 }
2431
2432 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2433 if (env_debugserver_log_flags)
2434 {
2435 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2436 debugserver_args.AppendArgument(arg_cstr);
2437 }
Jim Inghama0cc6b22012-10-03 22:31:30 +00002438// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
2439// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002440
Greg Clayton8b82f082011-04-12 05:54:46 +00002441 // We currently send down all arguments, attach pids, or attach
2442 // process names in dedicated GDB server packets, so we don't need
2443 // to pass them as arguments. This is currently because of all the
2444 // things we need to setup prior to launching: the environment,
2445 // current working dir, file actions, etc.
2446#if 0
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002447 // Now append the program arguments
Greg Clayton71337622011-02-24 22:24:29 +00002448 if (inferior_argv)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002449 {
Greg Clayton71337622011-02-24 22:24:29 +00002450 // Terminate the debugserver args so we can now append the inferior args
2451 debugserver_args.AppendArgument("--");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002452
Greg Clayton71337622011-02-24 22:24:29 +00002453 for (int i = 0; inferior_argv[i] != NULL; ++i)
2454 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002455 }
2456 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2457 {
2458 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2459 debugserver_args.AppendArgument (arg_cstr);
2460 }
2461 else if (attach_name && attach_name[0])
2462 {
2463 if (wait_for_launch)
2464 debugserver_args.AppendArgument ("--waitfor");
2465 else
2466 debugserver_args.AppendArgument ("--attach");
2467 debugserver_args.AppendArgument (attach_name);
2468 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002469#endif
Greg Clayton8b82f082011-04-12 05:54:46 +00002470
2471 ProcessLaunchInfo::FileAction file_action;
2472
2473 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2474 // to "/dev/null" if we run into any problems.
2475 file_action.Close (STDIN_FILENO);
Han Ming Ong84647042012-02-25 01:07:38 +00002476 debugserver_launch_info.AppendFileAction (file_action);
Greg Clayton8b82f082011-04-12 05:54:46 +00002477 file_action.Close (STDOUT_FILENO);
Han Ming Ong84647042012-02-25 01:07:38 +00002478 debugserver_launch_info.AppendFileAction (file_action);
Greg Clayton8b82f082011-04-12 05:54:46 +00002479 file_action.Close (STDERR_FILENO);
Han Ming Ong84647042012-02-25 01:07:38 +00002480 debugserver_launch_info.AppendFileAction (file_action);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002481
2482 if (log)
2483 {
2484 StreamString strm;
2485 debugserver_args.Dump (&strm);
2486 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2487 }
2488
Han Ming Ong84647042012-02-25 01:07:38 +00002489 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2490 debugserver_launch_info.SetUserID(process_info.GetUserID());
Greg Claytone4e45922011-11-16 05:37:56 +00002491
Han Ming Ong84647042012-02-25 01:07:38 +00002492 error = Host::LaunchProcess(debugserver_launch_info);
Greg Clayton0b42ac32010-07-02 01:29:13 +00002493
Greg Clayton8b82f082011-04-12 05:54:46 +00002494 if (error.Success ())
Han Ming Ong84647042012-02-25 01:07:38 +00002495 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Greg Clayton8b82f082011-04-12 05:54:46 +00002496 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002497 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2498
2499 if (error.Fail() || log)
Greg Clayton5160ce52013-03-27 23:08:40 +00002500 error.PutToLog(log, "Host::LaunchProcess (launch_info) => pid=%" PRIu64 ", path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002501 }
2502 else
2503 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002504 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002505 }
2506
2507 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2508 StartAsyncThread ();
2509 }
2510 return error;
2511}
2512
2513bool
2514ProcessGDBRemote::MonitorDebugserverProcess
2515(
2516 void *callback_baton,
2517 lldb::pid_t debugserver_pid,
Greg Claytone4e45922011-11-16 05:37:56 +00002518 bool exited, // True if the process did exit
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002519 int signo, // Zero for no signal
2520 int exit_status // Exit value of process if signal is zero
2521)
2522{
Greg Claytone4e45922011-11-16 05:37:56 +00002523 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2524 // and might not exist anymore, so we need to carefully try to get the
2525 // target for this process first since we have a race condition when
2526 // we are done running between getting the notice that the inferior
2527 // process has died and the debugserver that was debugging this process.
2528 // In our test suite, we are also continually running process after
2529 // process, so we must be very careful to make sure:
2530 // 1 - process object hasn't been deleted already
2531 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002532
2533 // "debugserver_pid" argument passed in is the process ID for
2534 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00002535 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002536
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002537 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton6779606a2011-01-22 23:43:18 +00002538
Greg Claytone4e45922011-11-16 05:37:56 +00002539 // Get a shared pointer to the target that has a matching process pointer.
2540 // This target could be gone, or the target could already have a new process
2541 // object inside of it
2542 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2543
Greg Clayton6779606a2011-01-22 23:43:18 +00002544 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002545 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 +00002546
Greg Claytone4e45922011-11-16 05:37:56 +00002547 if (target_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002548 {
Greg Claytone4e45922011-11-16 05:37:56 +00002549 // We found a process in a target that matches, but another thread
2550 // might be in the process of launching a new process that will
2551 // soon replace it, so get a shared pointer to the process so we
2552 // can keep it alive.
2553 ProcessSP process_sp (target_sp->GetProcessSP());
2554 // Now we have a shared pointer to the process that can't go away on us
2555 // so we now make sure it was the same as the one passed in, and also make
2556 // sure that our previous "process *" didn't get deleted and have a new
2557 // "process *" created in its place with the same pointer. To verify this
2558 // we make sure the process has our debugserver process ID. If we pass all
2559 // of these tests, then we are sure that this process is the one we were
2560 // looking for.
2561 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002562 {
Greg Claytone4e45922011-11-16 05:37:56 +00002563 // Sleep for a half a second to make sure our inferior process has
2564 // time to set its exit status before we set it incorrectly when
2565 // both the debugserver and the inferior process shut down.
2566 usleep (500000);
2567 // If our process hasn't yet exited, debugserver might have died.
2568 // If the process did exit, the we are reaping it.
2569 const StateType state = process->GetState();
2570
2571 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2572 state != eStateInvalid &&
2573 state != eStateUnloaded &&
2574 state != eStateExited &&
2575 state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002576 {
Greg Claytone4e45922011-11-16 05:37:56 +00002577 char error_str[1024];
2578 if (signo)
2579 {
2580 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2581 if (signal_cstr)
2582 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2583 else
2584 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2585 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002586 else
Greg Claytone4e45922011-11-16 05:37:56 +00002587 {
2588 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2589 }
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002590
Greg Claytone4e45922011-11-16 05:37:56 +00002591 process->SetExitStatus (-1, error_str);
2592 }
2593 // Debugserver has exited we need to let our ProcessGDBRemote
2594 // know that it no longer has a debugserver instance
2595 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002596 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002597 }
2598 return true;
2599}
2600
2601void
2602ProcessGDBRemote::KillDebugserverProcess ()
2603{
2604 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2605 {
2606 ::kill (m_debugserver_pid, SIGINT);
2607 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2608 }
2609}
2610
2611void
2612ProcessGDBRemote::Initialize()
2613{
2614 static bool g_initialized = false;
2615
2616 if (g_initialized == false)
2617 {
2618 g_initialized = true;
2619 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2620 GetPluginDescriptionStatic(),
2621 CreateInstance);
2622
2623 Log::Callbacks log_callbacks = {
2624 ProcessGDBRemoteLog::DisableLog,
2625 ProcessGDBRemoteLog::EnableLog,
2626 ProcessGDBRemoteLog::ListLogCategories
2627 };
2628
2629 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2630 }
2631}
2632
2633bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002634ProcessGDBRemote::StartAsyncThread ()
2635{
Greg Clayton5160ce52013-03-27 23:08:40 +00002636 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002637
2638 if (log)
2639 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Ingham455fa5c2012-11-01 01:15:33 +00002640
2641 Mutex::Locker start_locker(m_async_thread_state_mutex);
2642 if (m_async_thread_state == eAsyncThreadNotStarted)
2643 {
2644 // Create a thread that watches our internal state and controls which
2645 // events make it to clients (into the DCProcess event queue).
2646 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2647 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2648 {
2649 m_async_thread_state = eAsyncThreadRunning;
2650 return true;
2651 }
2652 else
2653 return false;
2654 }
2655 else
2656 {
2657 // Somebody tried to start the async thread while it was either being started or stopped. If the former, and
2658 // it started up successfully, then say all's well. Otherwise it is an error, since we aren't going to restart it.
2659 if (log)
2660 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
2661 if (m_async_thread_state == eAsyncThreadRunning)
2662 return true;
2663 else
2664 return false;
2665 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002666}
2667
2668void
2669ProcessGDBRemote::StopAsyncThread ()
2670{
Greg Clayton5160ce52013-03-27 23:08:40 +00002671 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002672
2673 if (log)
2674 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2675
Jim Ingham455fa5c2012-11-01 01:15:33 +00002676 Mutex::Locker start_locker(m_async_thread_state_mutex);
2677 if (m_async_thread_state == eAsyncThreadRunning)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002678 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00002679 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2680
2681 // This will shut down the async thread.
2682 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
2683
2684 // Stop the stdio thread
2685 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2686 {
2687 Host::ThreadJoin (m_async_thread, NULL, NULL);
2688 }
2689 m_async_thread_state = eAsyncThreadDone;
2690 }
2691 else
2692 {
2693 if (log)
2694 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002695 }
2696}
2697
2698
2699void *
2700ProcessGDBRemote::AsyncThread (void *arg)
2701{
2702 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2703
Greg Clayton5160ce52013-03-27 23:08:40 +00002704 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002705 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002706 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002707
2708 Listener listener ("ProcessGDBRemote::AsyncThread");
2709 EventSP event_sp;
2710 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2711 eBroadcastBitAsyncThreadShouldExit;
2712
2713 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2714 {
Greg Clayton71337622011-02-24 22:24:29 +00002715 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2716
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002717 bool done = false;
2718 while (!done)
2719 {
2720 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002721 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002722 if (listener.WaitForEvent (NULL, event_sp))
2723 {
2724 const uint32_t event_type = event_sp->GetType();
Greg Clayton71337622011-02-24 22:24:29 +00002725 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002726 {
Greg Clayton71337622011-02-24 22:24:29 +00002727 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002728 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 +00002729
Greg Clayton71337622011-02-24 22:24:29 +00002730 switch (event_type)
2731 {
2732 case eBroadcastBitAsyncContinue:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002733 {
Greg Clayton71337622011-02-24 22:24:29 +00002734 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002735
Greg Clayton71337622011-02-24 22:24:29 +00002736 if (continue_packet)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002737 {
Greg Clayton71337622011-02-24 22:24:29 +00002738 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2739 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2740 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002741 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002742
Greg Clayton71337622011-02-24 22:24:29 +00002743 if (::strstr (continue_cstr, "vAttach") == NULL)
2744 process->SetPrivateState(eStateRunning);
2745 StringExtractorGDBRemote response;
2746 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002747
Greg Clayton0772ded2012-05-16 02:48:06 +00002748 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
2749 // The thread ID list might be contained within the "response", or the stop reply packet that
2750 // caused the stop. So clear it now before we give the stop reply packet to the process
2751 // using the process->SetLastStopPacket()...
2752 process->ClearThreadIDList ();
2753
Greg Clayton71337622011-02-24 22:24:29 +00002754 switch (stop_state)
2755 {
2756 case eStateStopped:
2757 case eStateCrashed:
2758 case eStateSuspended:
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002759 process->SetLastStopPacket (response);
Greg Clayton71337622011-02-24 22:24:29 +00002760 process->SetPrivateState (stop_state);
2761 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002762
Greg Clayton71337622011-02-24 22:24:29 +00002763 case eStateExited:
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002764 process->SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002765 process->ClearThreadIDList();
Greg Clayton71337622011-02-24 22:24:29 +00002766 response.SetFilePos(1);
2767 process->SetExitStatus(response.GetHexU8(), NULL);
2768 done = true;
2769 break;
2770
2771 case eStateInvalid:
2772 process->SetExitStatus(-1, "lost connection");
2773 break;
2774
2775 default:
2776 process->SetPrivateState (stop_state);
2777 break;
2778 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002779 }
2780 }
Greg Clayton71337622011-02-24 22:24:29 +00002781 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002782
Greg Clayton71337622011-02-24 22:24:29 +00002783 case eBroadcastBitAsyncThreadShouldExit:
2784 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002785 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Clayton71337622011-02-24 22:24:29 +00002786 done = true;
2787 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002788
Greg Clayton71337622011-02-24 22:24:29 +00002789 default:
2790 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002791 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 +00002792 done = true;
2793 break;
2794 }
2795 }
2796 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2797 {
2798 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2799 {
2800 process->SetExitStatus (-1, "lost connection");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002801 done = true;
Greg Clayton71337622011-02-24 22:24:29 +00002802 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002803 }
2804 }
2805 else
2806 {
2807 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002808 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 +00002809 done = true;
2810 }
2811 }
2812 }
2813
2814 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002815 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002816
2817 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2818 return NULL;
2819}
2820
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002821const char *
2822ProcessGDBRemote::GetDispatchQueueNameForThread
2823(
2824 addr_t thread_dispatch_qaddr,
2825 std::string &dispatch_queue_name
2826)
2827{
2828 dispatch_queue_name.clear();
2829 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2830 {
2831 // Cache the dispatch_queue_offsets_addr value so we don't always have
2832 // to look it up
2833 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2834 {
Greg Clayton897f96a2010-10-12 17:33:06 +00002835 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2836 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Claytonb9a01b32012-02-26 05:51:37 +00002837 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false));
2838 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec));
Greg Clayton897f96a2010-10-12 17:33:06 +00002839 if (module_sp)
2840 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2841
2842 if (dispatch_queue_offsets_symbol == NULL)
2843 {
Greg Claytonb9a01b32012-02-26 05:51:37 +00002844 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false));
2845 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_module_spec);
Greg Clayton897f96a2010-10-12 17:33:06 +00002846 if (module_sp)
2847 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2848 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002849 if (dispatch_queue_offsets_symbol)
Greg Claytone7612132012-03-07 21:03:09 +00002850 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002851
2852 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2853 return NULL;
2854 }
2855
2856 uint8_t memory_buffer[8];
Greg Clayton514487e2011-02-15 21:59:32 +00002857 DataExtractor data (memory_buffer,
2858 sizeof(memory_buffer),
2859 m_target.GetArchitecture().GetByteOrder(),
2860 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002861
2862 // Excerpt from src/queue_private.h
2863 struct dispatch_queue_offsets_s
2864 {
2865 uint16_t dqo_version;
Jason Molendae424a9b2012-11-10 06:54:30 +00002866 uint16_t dqo_label; // in version 1-3, offset to string; in version 4+, offset to a pointer to a string
2867 uint16_t dqo_label_size; // in version 1-3, length of string; in version 4+, size of a (void*) in this process
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002868 } dispatch_queue_offsets;
2869
2870
2871 Error error;
2872 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2873 {
Greg Claytonc7bece562013-01-25 18:06:21 +00002874 lldb::offset_t data_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002875 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2876 {
2877 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2878 {
2879 data_offset = 0;
2880 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
Jason Molendae424a9b2012-11-10 06:54:30 +00002881 if (dispatch_queue_offsets.dqo_version >= 4)
2882 {
2883 // libdispatch versions 4+, pointer to dispatch name is in the
2884 // queue structure.
2885 lldb::addr_t pointer_to_label_address = queue_addr + dispatch_queue_offsets.dqo_label;
2886 if (ReadMemory (pointer_to_label_address, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2887 {
2888 data_offset = 0;
2889 lldb::addr_t label_addr = data.GetAddress(&data_offset);
2890 ReadCStringFromMemory (label_addr, dispatch_queue_name, error);
2891 }
2892 }
2893 else
2894 {
2895 // libdispatch versions 1-3, dispatch name is a fixed width char array
2896 // in the queue structure.
2897 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2898 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2899 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2900 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2901 dispatch_queue_name.erase (bytes_read);
2902 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002903 }
2904 }
2905 }
2906 }
2907 if (dispatch_queue_name.empty())
2908 return NULL;
2909 return dispatch_queue_name.c_str();
2910}
2911
Greg Claytone996fd32011-03-08 22:40:15 +00002912//uint32_t
2913//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2914//{
2915// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2916// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2917// if (m_local_debugserver)
2918// {
2919// return Host::ListProcessesMatchingName (name, matches, pids);
2920// }
2921// else
2922// {
2923// // FIXME: Implement talking to the remote debugserver.
2924// return 0;
2925// }
2926//
2927//}
2928//
Jim Ingham1c823b42011-01-22 01:33:44 +00002929bool
2930ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2931 lldb_private::StoppointCallbackContext *context,
2932 lldb::user_id_t break_id,
2933 lldb::user_id_t break_loc_id)
2934{
2935 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2936 // run so I can stop it if that's what I want to do.
Greg Clayton5160ce52013-03-27 23:08:40 +00002937 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00002938 if (log)
2939 log->Printf("Hit New Thread Notification breakpoint.");
2940 return false;
2941}
2942
2943
2944bool
2945ProcessGDBRemote::StartNoticingNewThreads()
2946{
Greg Clayton5160ce52013-03-27 23:08:40 +00002947 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00002948 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00002949 {
Greg Clayton4116e932012-05-15 02:33:01 +00002950 if (log && log->GetVerbose())
2951 log->Printf("Enabled noticing new thread breakpoint.");
2952 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00002953 }
Greg Clayton4116e932012-05-15 02:33:01 +00002954 else
Jim Ingham1c823b42011-01-22 01:33:44 +00002955 {
Greg Clayton4116e932012-05-15 02:33:01 +00002956 PlatformSP platform_sp (m_target.GetPlatform());
2957 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00002958 {
Greg Clayton4116e932012-05-15 02:33:01 +00002959 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
2960 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00002961 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00002962 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00002963 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
2964 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00002965 }
2966 else
2967 {
2968 if (log)
2969 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00002970 }
2971 }
2972 }
Greg Clayton4116e932012-05-15 02:33:01 +00002973 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00002974}
2975
2976bool
2977ProcessGDBRemote::StopNoticingNewThreads()
2978{
Greg Clayton5160ce52013-03-27 23:08:40 +00002979 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00002980 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00002981 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00002982
2983 if (m_thread_create_bp_sp)
2984 m_thread_create_bp_sp->SetEnabled(false);
2985
Jim Ingham1c823b42011-01-22 01:33:44 +00002986 return true;
2987}
2988
Jason Molenda5e8534e2012-10-03 01:29:34 +00002989lldb_private::DynamicLoader *
2990ProcessGDBRemote::GetDynamicLoader ()
2991{
2992 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00002993 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00002994 return m_dyld_ap.get();
2995}
Jim Ingham1c823b42011-01-22 01:33:44 +00002996
Greg Clayton998255b2012-10-13 02:07:45 +00002997
Greg Clayton02686b82012-10-15 22:42:16 +00002998class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00002999{
3000private:
3001
3002public:
Greg Clayton02686b82012-10-15 22:42:16 +00003003 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00003004 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00003005 "process plugin packet history",
3006 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00003007 NULL)
3008 {
3009 }
3010
Greg Clayton02686b82012-10-15 22:42:16 +00003011 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton998255b2012-10-13 02:07:45 +00003012 {
3013 }
3014
3015 bool
3016 DoExecute (Args& command, CommandReturnObject &result)
3017 {
Greg Clayton02686b82012-10-15 22:42:16 +00003018 const size_t argc = command.GetArgumentCount();
3019 if (argc == 0)
3020 {
3021 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3022 if (process)
3023 {
3024 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
3025 result.SetStatus (eReturnStatusSuccessFinishResult);
3026 return true;
3027 }
3028 }
3029 else
3030 {
3031 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
3032 }
3033 result.SetStatus (eReturnStatusFailed);
3034 return false;
3035 }
3036};
3037
3038class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
3039{
3040private:
3041
3042public:
3043 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
3044 CommandObjectParsed (interpreter,
3045 "process plugin packet send",
3046 "Send a custom packet through the GDB remote protocol and print the answer. "
3047 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
3048 NULL)
3049 {
3050 }
3051
3052 ~CommandObjectProcessGDBRemotePacketSend ()
3053 {
3054 }
3055
3056 bool
3057 DoExecute (Args& command, CommandReturnObject &result)
3058 {
3059 const size_t argc = command.GetArgumentCount();
3060 if (argc == 0)
3061 {
3062 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
3063 result.SetStatus (eReturnStatusFailed);
3064 return false;
3065 }
3066
3067 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3068 if (process)
3069 {
Han Ming Ong84145852012-11-26 20:42:03 +00003070 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00003071 {
Han Ming Ong84145852012-11-26 20:42:03 +00003072 const char *packet_cstr = command.GetArgumentAtIndex(0);
3073 bool send_async = true;
3074 StringExtractorGDBRemote response;
3075 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3076 result.SetStatus (eReturnStatusSuccessFinishResult);
3077 Stream &output_strm = result.GetOutputStream();
3078 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00003079 std::string &response_str = response.GetStringRef();
3080
3081 if (strcmp(packet_cstr, "qGetProfileData") == 0)
3082 {
3083 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
3084 }
3085
Han Ming Ong84145852012-11-26 20:42:03 +00003086 if (response_str.empty())
3087 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3088 else
3089 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00003090 }
Greg Clayton02686b82012-10-15 22:42:16 +00003091 }
Greg Clayton998255b2012-10-13 02:07:45 +00003092 return true;
3093 }
3094};
3095
Greg Claytonba4a0a52013-02-01 23:03:47 +00003096class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
3097{
3098private:
3099
3100public:
3101 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
3102 CommandObjectRaw (interpreter,
3103 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00003104 "Send a qRcmd packet through the GDB remote protocol and print the response."
3105 "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 +00003106 NULL)
3107 {
3108 }
3109
3110 ~CommandObjectProcessGDBRemotePacketMonitor ()
3111 {
3112 }
3113
3114 bool
3115 DoExecute (const char *command, CommandReturnObject &result)
3116 {
3117 if (command == NULL || command[0] == '\0')
3118 {
3119 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
3120 result.SetStatus (eReturnStatusFailed);
3121 return false;
3122 }
3123
3124 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3125 if (process)
3126 {
3127 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00003128 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00003129 packet.PutBytesAsRawHex8(command, strlen(command));
3130 const char *packet_cstr = packet.GetString().c_str();
3131
3132 bool send_async = true;
3133 StringExtractorGDBRemote response;
3134 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3135 result.SetStatus (eReturnStatusSuccessFinishResult);
3136 Stream &output_strm = result.GetOutputStream();
3137 output_strm.Printf (" packet: %s\n", packet_cstr);
3138 const std::string &response_str = response.GetStringRef();
3139
3140 if (response_str.empty())
3141 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3142 else
3143 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
3144 }
3145 return true;
3146 }
3147};
3148
Greg Clayton02686b82012-10-15 22:42:16 +00003149class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
3150{
3151private:
3152
3153public:
3154 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
3155 CommandObjectMultiword (interpreter,
3156 "process plugin packet",
3157 "Commands that deal with GDB remote packets.",
3158 NULL)
3159 {
3160 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
3161 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00003162 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00003163 }
3164
3165 ~CommandObjectProcessGDBRemotePacket ()
3166 {
3167 }
3168};
Greg Clayton998255b2012-10-13 02:07:45 +00003169
3170class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
3171{
3172public:
3173 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
3174 CommandObjectMultiword (interpreter,
3175 "process plugin",
3176 "A set of commands for operating on a ProcessGDBRemote process.",
3177 "process plugin <subcommand> [<subcommand-options>]")
3178 {
3179 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
3180 }
3181
3182 ~CommandObjectMultiwordProcessGDBRemote ()
3183 {
3184 }
3185};
3186
Greg Clayton998255b2012-10-13 02:07:45 +00003187CommandObject *
3188ProcessGDBRemote::GetPluginCommandObject()
3189{
3190 if (!m_command_sp)
3191 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
3192 return m_command_sp.get();
3193}