blob: fb539b1ea37165a2d7cf8c23c5627db2701619dc [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);
263 assert (packet_len < 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 }
747 retry_count++;
748
749 if (retry_count >= max_retry_count)
750 break;
751
752 usleep (100000);
753 }
754 }
755
756 if (!m_gdb_comm.IsConnected())
757 {
758 if (error.Success())
759 error.SetErrorString("not connected to remote gdb server");
760 return error;
761 }
762
Greg Clayton32e0a752011-03-30 18:16:51 +0000763 // We always seem to be able to open a connection to a local port
764 // so we need to make sure we can then send data to it. If we can't
765 // then we aren't actually connected to anything, so try and do the
766 // handshake with the remote GDB server and make sure that goes
767 // alright.
768 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000769 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000770 m_gdb_comm.Disconnect();
771 if (error.Success())
772 error.SetErrorString("not connected to remote gdb server");
773 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000774 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000775 m_gdb_comm.ResetDiscoverableSettings();
776 m_gdb_comm.QueryNoAckModeSupported ();
777 m_gdb_comm.GetThreadSuffixSupported ();
Greg Clayton44633992012-04-10 03:22:03 +0000778 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +0000779 m_gdb_comm.GetHostInfo ();
780 m_gdb_comm.GetVContSupported ('c');
Jim Inghamcd16df92012-07-20 21:37:13 +0000781 m_gdb_comm.GetVAttachOrWaitSupported();
Jim Ingham03afad82012-07-02 05:40:07 +0000782
783 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
784 for (size_t idx = 0; idx < num_cmds; idx++)
785 {
786 StringExtractorGDBRemote response;
Jim Ingham03afad82012-07-02 05:40:07 +0000787 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
788 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000789 return error;
790}
791
792void
793ProcessGDBRemote::DidLaunchOrAttach ()
794{
Greg Clayton5160ce52013-03-27 23:08:40 +0000795 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +0000796 if (log)
797 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton93d3c8332011-02-16 04:46:07 +0000798 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000799 {
800 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
801
Greg Clayton513c26c2011-01-29 07:10:55 +0000802 BuildDynamicRegisterInfo (false);
Greg Clayton3af9ea52010-11-18 05:57:03 +0000803
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000804 // See if the GDB server supports the qHostInfo information
Greg Clayton0d0c12a2011-02-09 03:09:55 +0000805
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000806 ArchSpec gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
807
808 // See if the GDB server supports the qProcessInfo packet, if so
809 // prefer that over the Host information as it will be more specific
810 // to our process.
811
812 if (m_gdb_comm.GetProcessArchitecture().IsValid())
813 gdb_remote_arch = m_gdb_comm.GetProcessArchitecture();
814
Greg Claytond314e812011-03-23 00:09:55 +0000815 if (gdb_remote_arch.IsValid())
Greg Clayton0d0c12a2011-02-09 03:09:55 +0000816 {
Greg Claytond314e812011-03-23 00:09:55 +0000817 ArchSpec &target_arch = GetTarget().GetArchitecture();
818
819 if (target_arch.IsValid())
820 {
821 // If the remote host is ARM and we have apple as the vendor, then
822 // ARM executables and shared libraries can have mixed ARM architectures.
823 // You can have an armv6 executable, and if the host is armv7, then the
824 // system will load the best possible architecture for all shared libraries
825 // it has, so we really need to take the remote host architecture as our
826 // defacto architecture in this case.
827
828 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
829 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
830 {
831 target_arch = gdb_remote_arch;
832 }
833 else
834 {
835 // Fill in what is missing in the triple
836 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
837 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton70b57652011-05-15 01:25:55 +0000838 if (target_triple.getVendorName().size() == 0)
839 {
Greg Claytond314e812011-03-23 00:09:55 +0000840 target_triple.setVendor (remote_triple.getVendor());
841
Greg Clayton70b57652011-05-15 01:25:55 +0000842 if (target_triple.getOSName().size() == 0)
843 {
844 target_triple.setOS (remote_triple.getOS());
Greg Claytond314e812011-03-23 00:09:55 +0000845
Greg Clayton70b57652011-05-15 01:25:55 +0000846 if (target_triple.getEnvironmentName().size() == 0)
847 target_triple.setEnvironment (remote_triple.getEnvironment());
848 }
849 }
Greg Claytond314e812011-03-23 00:09:55 +0000850 }
851 }
852 else
853 {
854 // The target doesn't have a valid architecture yet, set it from
855 // the architecture we got from the remote GDB server
856 target_arch = gdb_remote_arch;
857 }
Greg Clayton0d0c12a2011-02-09 03:09:55 +0000858 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000859 }
860}
861
862void
863ProcessGDBRemote::DidLaunch ()
864{
865 DidLaunchOrAttach ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000866}
867
868Error
Greg Claytonc982c762010-07-09 20:39:50 +0000869ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000870{
Han Ming Ong84647042012-02-25 01:07:38 +0000871 ProcessAttachInfo attach_info;
872 return DoAttachToProcessWithID(attach_pid, attach_info);
873}
874
875Error
876ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
877{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000878 Error error;
879 // Clear out and clean up from any current state
880 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000881 if (attach_pid != LLDB_INVALID_PROCESS_ID)
882 {
Greg Clayton71337622011-02-24 22:24:29 +0000883 // Make sure we aren't already connected?
884 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000885 {
Greg Clayton71337622011-02-24 22:24:29 +0000886 char host_port[128];
887 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
888 char connect_url[128];
889 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000890
Han Ming Ong84647042012-02-25 01:07:38 +0000891 error = StartDebugserverProcess (host_port, attach_info);
Greg Clayton71337622011-02-24 22:24:29 +0000892
893 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000894 {
Greg Clayton71337622011-02-24 22:24:29 +0000895 const char *error_string = error.AsCString();
896 if (error_string == NULL)
897 error_string = "unable to launch " DEBUGSERVER_BASENAME;
898
899 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000900 }
Greg Clayton71337622011-02-24 22:24:29 +0000901 else
902 {
903 error = ConnectToDebugserver (connect_url);
904 }
905 }
906
907 if (error.Success())
908 {
909 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +0000910 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Greg Clayton3b608422011-11-19 02:11:30 +0000911 SetID (attach_pid);
Greg Clayton71337622011-02-24 22:24:29 +0000912 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000913 }
914 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000915 return error;
916}
917
918size_t
919ProcessGDBRemote::AttachInputReaderCallback
920(
921 void *baton,
922 InputReader *reader,
923 lldb::InputReaderAction notification,
924 const char *bytes,
925 size_t bytes_len
926)
927{
928 if (notification == eInputReaderGotToken)
929 {
930 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
931 if (gdb_process->m_waiting_for_attach)
932 gdb_process->m_waiting_for_attach = false;
933 reader->SetIsDone(true);
934 return 1;
935 }
936 return 0;
937}
938
939Error
Han Ming Ong84647042012-02-25 01:07:38 +0000940ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000941{
942 Error error;
943 // Clear out and clean up from any current state
944 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000945
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000946 if (process_name && process_name[0])
947 {
Greg Clayton71337622011-02-24 22:24:29 +0000948 // Make sure we aren't already connected?
949 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000950 {
Greg Clayton71337622011-02-24 22:24:29 +0000951 char host_port[128];
952 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
953 char connect_url[128];
954 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
955
Han Ming Ong84647042012-02-25 01:07:38 +0000956 error = StartDebugserverProcess (host_port, attach_info);
Greg Clayton71337622011-02-24 22:24:29 +0000957 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000958 {
Greg Clayton71337622011-02-24 22:24:29 +0000959 const char *error_string = error.AsCString();
960 if (error_string == NULL)
961 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000962
Greg Clayton71337622011-02-24 22:24:29 +0000963 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000964 }
Greg Clayton71337622011-02-24 22:24:29 +0000965 else
966 {
967 error = ConnectToDebugserver (connect_url);
968 }
969 }
970
971 if (error.Success())
972 {
973 StreamString packet;
974
975 if (wait_for_launch)
Jim Inghamcd16df92012-07-20 21:37:13 +0000976 {
977 if (!m_gdb_comm.GetVAttachOrWaitSupported())
978 {
979 packet.PutCString ("vAttachWait");
980 }
981 else
982 {
983 if (attach_info.GetIgnoreExisting())
984 packet.PutCString("vAttachWait");
985 else
986 packet.PutCString ("vAttachOrWait");
987 }
988 }
Greg Clayton71337622011-02-24 22:24:29 +0000989 else
990 packet.PutCString("vAttachName");
991 packet.PutChar(';');
992 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
993
994 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
995
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000996 }
997 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000998 return error;
999}
1000
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001001
1002void
1003ProcessGDBRemote::DidAttach ()
1004{
Greg Claytonb766a732011-02-04 01:58:07 +00001005 DidLaunchOrAttach ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001006}
1007
Greg Clayton90ba8112012-12-05 00:16:59 +00001008
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001009Error
1010ProcessGDBRemote::WillResume ()
1011{
Greg Clayton71fc2a32011-02-12 06:28:37 +00001012 m_continue_c_tids.clear();
1013 m_continue_C_tids.clear();
1014 m_continue_s_tids.clear();
1015 m_continue_S_tids.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001016 return Error();
1017}
1018
1019Error
1020ProcessGDBRemote::DoResume ()
1021{
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001022 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001023 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001024 if (log)
1025 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytone5219662010-12-03 06:02:24 +00001026
1027 Listener listener ("gdb-remote.resume-packet-sent");
1028 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1029 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00001030 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1031
Greg Claytond1d06e42013-04-20 00:27:58 +00001032 const size_t num_threads = GetThreadList().GetSize();
1033
Greg Clayton71fc2a32011-02-12 06:28:37 +00001034 StreamString continue_packet;
1035 bool continue_packet_error = false;
1036 if (m_gdb_comm.HasAnyVContSupport ())
1037 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001038 if (m_continue_c_tids.size() == num_threads)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001039 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001040 // All threads are continuing, just send a "c" packet
1041 continue_packet.PutCString ("c");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001042 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001043 else
1044 {
1045 continue_packet.PutCString ("vCont");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001046
Greg Claytond1d06e42013-04-20 00:27:58 +00001047 if (!m_continue_c_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001048 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001049 if (m_gdb_comm.GetVContSupported ('c'))
1050 {
1051 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)
1052 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1053 }
1054 else
1055 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001056 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001057
1058 if (!continue_packet_error && !m_continue_C_tids.empty())
1059 {
1060 if (m_gdb_comm.GetVContSupported ('C'))
1061 {
1062 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)
1063 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1064 }
1065 else
1066 continue_packet_error = true;
1067 }
Greg Claytone5219662010-12-03 06:02:24 +00001068
Greg Claytond1d06e42013-04-20 00:27:58 +00001069 if (!continue_packet_error && !m_continue_s_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001070 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001071 if (m_gdb_comm.GetVContSupported ('s'))
1072 {
1073 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)
1074 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1075 }
1076 else
1077 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001078 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001079
1080 if (!continue_packet_error && !m_continue_S_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001081 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001082 if (m_gdb_comm.GetVContSupported ('S'))
1083 {
1084 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)
1085 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1086 }
1087 else
1088 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001089 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001090
1091 if (continue_packet_error)
1092 continue_packet.GetString().clear();
Greg Clayton71fc2a32011-02-12 06:28:37 +00001093 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001094 }
1095 else
1096 continue_packet_error = true;
1097
1098 if (continue_packet_error)
1099 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001100 // Either no vCont support, or we tried to use part of the vCont
1101 // packet that wasn't supported by the remote GDB server.
1102 // We need to try and make a simple packet that can do our continue
Greg Clayton71fc2a32011-02-12 06:28:37 +00001103 const size_t num_continue_c_tids = m_continue_c_tids.size();
1104 const size_t num_continue_C_tids = m_continue_C_tids.size();
1105 const size_t num_continue_s_tids = m_continue_s_tids.size();
1106 const size_t num_continue_S_tids = m_continue_S_tids.size();
1107 if (num_continue_c_tids > 0)
1108 {
1109 if (num_continue_c_tids == num_threads)
1110 {
1111 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001112 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001113 continue_packet.PutChar ('c');
1114 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001115 }
1116 else if (num_continue_c_tids == 1 &&
1117 num_continue_C_tids == 0 &&
1118 num_continue_s_tids == 0 &&
1119 num_continue_S_tids == 0 )
1120 {
1121 // Only one thread is continuing
Greg Clayton8b82f082011-04-12 05:54:46 +00001122 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001123 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001124 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001125 }
1126 }
1127
Greg Clayton0c74e782011-06-24 03:21:43 +00001128 if (continue_packet_error && num_continue_C_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001129 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001130 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1131 num_continue_C_tids > 0 &&
1132 num_continue_s_tids == 0 &&
1133 num_continue_S_tids == 0 )
Greg Clayton71fc2a32011-02-12 06:28:37 +00001134 {
1135 const int continue_signo = m_continue_C_tids.front().second;
Greg Clayton0c74e782011-06-24 03:21:43 +00001136 // Only one thread is continuing
Greg Clayton71fc2a32011-02-12 06:28:37 +00001137 if (num_continue_C_tids > 1)
1138 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001139 // More that one thread with a signal, yet we don't have
1140 // vCont support and we are being asked to resume each
1141 // thread with a signal, we need to make sure they are
1142 // all the same signal, or we can't issue the continue
1143 // accurately with the current support...
1144 if (num_continue_C_tids > 1)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001145 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001146 continue_packet_error = false;
1147 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1148 {
1149 if (m_continue_C_tids[i].second != continue_signo)
1150 continue_packet_error = true;
1151 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001152 }
Greg Clayton0c74e782011-06-24 03:21:43 +00001153 if (!continue_packet_error)
1154 m_gdb_comm.SetCurrentThreadForRun (-1);
1155 }
1156 else
1157 {
1158 // Set the continue thread ID
1159 continue_packet_error = false;
1160 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001161 }
1162 if (!continue_packet_error)
1163 {
1164 // Add threads continuing with the same signo...
Greg Clayton71fc2a32011-02-12 06:28:37 +00001165 continue_packet.Printf("C%2.2x", continue_signo);
1166 }
1167 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001168 }
1169
Greg Clayton0c74e782011-06-24 03:21:43 +00001170 if (continue_packet_error && num_continue_s_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001171 {
1172 if (num_continue_s_tids == num_threads)
1173 {
1174 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001175 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001176 continue_packet.PutChar ('s');
1177 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001178 }
1179 else if (num_continue_c_tids == 0 &&
1180 num_continue_C_tids == 0 &&
1181 num_continue_s_tids == 1 &&
1182 num_continue_S_tids == 0 )
1183 {
1184 // Only one thread is stepping
Greg Clayton8b82f082011-04-12 05:54:46 +00001185 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001186 continue_packet.PutChar ('s');
Greg Clayton0c74e782011-06-24 03:21:43 +00001187 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001188 }
1189 }
1190
1191 if (!continue_packet_error && num_continue_S_tids > 0)
1192 {
1193 if (num_continue_S_tids == num_threads)
1194 {
1195 const int step_signo = m_continue_S_tids.front().second;
1196 // Are all threads trying to step with the same signal?
Greg Clayton0c74e782011-06-24 03:21:43 +00001197 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001198 if (num_continue_S_tids > 1)
1199 {
1200 for (size_t i=1; i<num_threads; ++i)
1201 {
1202 if (m_continue_S_tids[i].second != step_signo)
1203 continue_packet_error = true;
1204 }
1205 }
1206 if (!continue_packet_error)
1207 {
1208 // Add threads stepping with the same signo...
Greg Clayton8b82f082011-04-12 05:54:46 +00001209 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001210 continue_packet.Printf("S%2.2x", step_signo);
1211 }
1212 }
1213 else if (num_continue_c_tids == 0 &&
1214 num_continue_C_tids == 0 &&
1215 num_continue_s_tids == 0 &&
1216 num_continue_S_tids == 1 )
1217 {
1218 // Only one thread is stepping with signal
Greg Clayton8b82f082011-04-12 05:54:46 +00001219 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001220 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Clayton0c74e782011-06-24 03:21:43 +00001221 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001222 }
1223 }
1224 }
1225
1226 if (continue_packet_error)
1227 {
1228 error.SetErrorString ("can't make continue packet for this resume");
1229 }
1230 else
1231 {
1232 EventSP event_sp;
1233 TimeValue timeout;
1234 timeout = TimeValue::Now();
1235 timeout.OffsetWithSeconds (5);
Jim Inghamb1e2e842012-04-12 18:49:31 +00001236 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1237 {
1238 error.SetErrorString ("Trying to resume but the async thread is dead.");
1239 if (log)
1240 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1241 return error;
1242 }
1243
Greg Clayton71fc2a32011-02-12 06:28:37 +00001244 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1245
1246 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Inghamb1e2e842012-04-12 18:49:31 +00001247 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001248 error.SetErrorString("Resume timed out.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00001249 if (log)
1250 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1251 }
1252 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1253 {
1254 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1255 if (log)
1256 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1257 return error;
1258 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001259 }
Greg Claytone5219662010-12-03 06:02:24 +00001260 }
1261
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001262 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001263}
1264
Greg Clayton9e920902012-04-10 02:25:43 +00001265void
1266ProcessGDBRemote::ClearThreadIDList ()
1267{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001268 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001269 m_thread_ids.clear();
1270}
1271
1272bool
1273ProcessGDBRemote::UpdateThreadIDList ()
1274{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001275 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001276 bool sequence_mutex_unavailable = false;
1277 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1278 if (sequence_mutex_unavailable)
1279 {
Greg Clayton9e920902012-04-10 02:25:43 +00001280 return false; // We just didn't get the list
1281 }
1282 return true;
1283}
1284
Greg Clayton9fc13552012-04-10 00:18:59 +00001285bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001286ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001287{
1288 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +00001289 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Clayton73b472d2010-10-27 03:32:59 +00001290 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +00001291 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton9e920902012-04-10 02:25:43 +00001292
1293 size_t num_thread_ids = m_thread_ids.size();
1294 // The "m_thread_ids" thread ID list should always be updated after each stop
1295 // reply packet, but in case it isn't, update it here.
1296 if (num_thread_ids == 0)
1297 {
1298 if (!UpdateThreadIDList ())
1299 return false;
1300 num_thread_ids = m_thread_ids.size();
1301 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001302
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001303 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001304 if (num_thread_ids > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001305 {
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001306 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001307 {
Greg Clayton9e920902012-04-10 02:25:43 +00001308 tid_t tid = m_thread_ids[i];
Greg Clayton160c9d82013-05-01 21:54:04 +00001309 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001310 if (!thread_sp)
Jim Ingham4f465cf2012-10-10 18:32:14 +00001311 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001312 new_thread_list.AddThread(thread_sp);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001313 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001314 }
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001315
1316 // Whatever that is left in old_thread_list_copy are not
1317 // present in new_thread_list. Remove non-existent threads from internal id table.
1318 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1319 for (size_t i=0; i<old_num_thread_ids; i++)
1320 {
1321 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1322 if (old_thread_sp)
1323 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001324 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001325 m_thread_id_to_index_id_map.erase(old_thread_id);
1326 }
1327 }
1328
Greg Clayton9fc13552012-04-10 00:18:59 +00001329 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001330}
1331
1332
1333StateType
1334ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1335{
Greg Claytondd0e5a52011-06-02 22:22:38 +00001336 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001337 const char stop_type = stop_packet.GetChar();
1338 switch (stop_type)
1339 {
1340 case 'T':
1341 case 'S':
1342 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00001343 // This is a bit of a hack, but is is required. If we did exec, we
1344 // need to clear our thread lists and also know to rebuild our dynamic
1345 // register info before we lookup and threads and populate the expedited
1346 // register values so we need to know this right away so we can cleanup
1347 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00001348 const uint32_t stop_id = GetStopID();
1349 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00001350 {
1351 // Our first stop, make sure we have a process ID, and also make
1352 // sure we know about our registers
1353 if (GetID() == LLDB_INVALID_PROCESS_ID)
1354 {
Greg Claytonc574ede2011-03-10 02:26:48 +00001355 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00001356 if (pid != LLDB_INVALID_PROCESS_ID)
1357 SetID (pid);
1358 }
1359 BuildDynamicRegisterInfo (true);
1360 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001361 // Stop with signal and thread info
1362 const uint8_t signo = stop_packet.GetHexU8();
1363 std::string name;
1364 std::string value;
1365 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00001366 std::string reason;
1367 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001368 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00001369 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001370 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001371 ThreadSP thread_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001372 ThreadGDBRemote *gdb_thread = NULL;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001373
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001374 while (stop_packet.GetNameColonValue(name, value))
1375 {
1376 if (name.compare("metype") == 0)
1377 {
1378 // exception type in big endian hex
1379 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1380 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001381 else if (name.compare("medata") == 0)
1382 {
1383 // exception data in big endian hex
1384 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1385 }
1386 else if (name.compare("thread") == 0)
1387 {
1388 // thread in big endian hex
Greg Clayton9e920902012-04-10 02:25:43 +00001389 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001390 // m_thread_list_real does have its own mutex, but we need to
1391 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1392 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1393 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1394 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
Greg Clayton160c9d82013-05-01 21:54:04 +00001395
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001396 if (!thread_sp)
Greg Claytond1d06e42013-04-20 00:27:58 +00001397 {
Greg Claytone576ab22011-02-15 00:19:15 +00001398 // Create the thread if we need to
Jim Ingham4f465cf2012-10-10 18:32:14 +00001399 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001400 m_thread_list_real.AddThread(thread_sp);
Greg Claytone576ab22011-02-15 00:19:15 +00001401 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001402 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1403
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001404 }
Greg Clayton9e920902012-04-10 02:25:43 +00001405 else if (name.compare("threads") == 0)
1406 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001407 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001408 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00001409 // A comma separated list of all threads in the current
1410 // process that includes the thread for this stop reply
1411 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00001412 size_t comma_pos;
1413 lldb::tid_t tid;
1414 while ((comma_pos = value.find(',')) != std::string::npos)
1415 {
1416 value[comma_pos] = '\0';
1417 // thread in big endian hex
1418 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1419 if (tid != LLDB_INVALID_THREAD_ID)
1420 m_thread_ids.push_back (tid);
1421 value.erase(0, comma_pos + 1);
1422
1423 }
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 }
Greg Claytonde9d0492011-01-08 03:17:57 +00001428 else if (name.compare("hexname") == 0)
1429 {
1430 StringExtractor name_extractor;
1431 // Swap "value" over into "name_extractor"
1432 name_extractor.GetStringRef().swap(value);
1433 // Now convert the HEX bytes into a string value
1434 name_extractor.GetHexByteString (value);
1435 thread_name.swap (value);
1436 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001437 else if (name.compare("name") == 0)
1438 {
1439 thread_name.swap (value);
1440 }
Greg Clayton6f35f5c2010-09-09 06:32:46 +00001441 else if (name.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001442 {
1443 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1444 }
Greg Claytona658fd22011-06-04 01:26:29 +00001445 else if (name.compare("reason") == 0)
1446 {
1447 reason.swap(value);
1448 }
1449 else if (name.compare("description") == 0)
1450 {
1451 StringExtractor desc_extractor;
1452 // Swap "value" over into "name_extractor"
1453 desc_extractor.GetStringRef().swap(value);
1454 // Now convert the HEX bytes into a string value
1455 desc_extractor.GetHexByteString (thread_name);
1456 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001457 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1458 {
1459 // We have a register number that contains an expedited
1460 // register value. Lets supply this register to our thread
1461 // so it won't have to go and read it.
Greg Clayton160c9d82013-05-01 21:54:04 +00001462 if (gdb_thread)
Greg Clayton3e06bd92011-01-09 21:07:35 +00001463 {
1464 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1465
1466 if (reg != UINT32_MAX)
1467 {
1468 StringExtractor reg_value_extractor;
1469 // Swap "value" over into "reg_value_extractor"
1470 reg_value_extractor.GetStringRef().swap(value);
Greg Clayton160c9d82013-05-01 21:54:04 +00001471 if (!gdb_thread->PrivateSetRegisterValue (reg, reg_value_extractor))
Greg Claytone576ab22011-02-15 00:19:15 +00001472 {
1473 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1474 name.c_str(),
1475 reg,
1476 reg,
1477 reg_value_extractor.GetStringRef().c_str(),
1478 stop_packet.GetStringRef().c_str());
1479 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001480 }
1481 }
1482 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001483 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001484
1485 if (thread_sp)
1486 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001487 // Clear the stop info just in case we don't set it to anything
1488 thread_sp->SetStopInfo (StopInfoSP());
1489
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001490 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Inghamdd2fe7a2011-01-28 02:23:12 +00001491 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001492 if (exc_type != 0)
1493 {
Greg Clayton1a65ae12011-01-25 23:55:37 +00001494 const size_t exc_data_size = exc_data.size();
Greg Claytonf4b47e12010-08-04 01:40:35 +00001495
Greg Clayton160c9d82013-05-01 21:54:04 +00001496 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1497 exc_type,
1498 exc_data_size,
1499 exc_data_size >= 1 ? exc_data[0] : 0,
1500 exc_data_size >= 2 ? exc_data[1] : 0,
1501 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001502 }
Greg Claytona658fd22011-06-04 01:26:29 +00001503 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001504 {
Greg Claytona658fd22011-06-04 01:26:29 +00001505 bool handled = false;
Greg Clayton8cda7f02013-05-21 21:55:59 +00001506 bool did_exec = false;
Greg Claytona658fd22011-06-04 01:26:29 +00001507 if (!reason.empty())
1508 {
1509 if (reason.compare("trace") == 0)
1510 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001511 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Greg Claytona658fd22011-06-04 01:26:29 +00001512 handled = true;
1513 }
1514 else if (reason.compare("breakpoint") == 0)
1515 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001516 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1517 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Claytona658fd22011-06-04 01:26:29 +00001518 if (bp_site_sp)
1519 {
1520 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1521 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1522 // 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 +00001523 handled = true;
Greg Clayton160c9d82013-05-01 21:54:04 +00001524 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00001525 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001526 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00001527 }
1528 else
1529 {
1530 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001531 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00001532 }
1533 }
1534
Greg Claytona658fd22011-06-04 01:26:29 +00001535 }
1536 else if (reason.compare("trap") == 0)
1537 {
1538 // Let the trap just use the standard signal stop reason below...
1539 }
1540 else if (reason.compare("watchpoint") == 0)
1541 {
1542 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1543 // TODO: locate the watchpoint somehow...
Greg Clayton160c9d82013-05-01 21:54:04 +00001544 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
Greg Claytona658fd22011-06-04 01:26:29 +00001545 handled = true;
1546 }
1547 else if (reason.compare("exception") == 0)
1548 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001549 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00001550 handled = true;
1551 }
Greg Clayton15fc2be2013-05-21 01:00:52 +00001552 else if (reason.compare("exec") == 0)
1553 {
Greg Clayton8cda7f02013-05-21 21:55:59 +00001554 did_exec = true;
Greg Clayton15fc2be2013-05-21 01:00:52 +00001555 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
1556 handled = true;
1557 }
Greg Claytona658fd22011-06-04 01:26:29 +00001558 }
1559
Greg Clayton15fc2be2013-05-21 01:00:52 +00001560 if (signo && did_exec == false)
Greg Claytona658fd22011-06-04 01:26:29 +00001561 {
1562 if (signo == SIGTRAP)
1563 {
1564 // Currently we are going to assume SIGTRAP means we are either
1565 // hitting a breakpoint or hardware single stepping.
Jim Ingham54cc6e42012-07-11 21:41:19 +00001566 handled = true;
Greg Clayton160c9d82013-05-01 21:54:04 +00001567 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1568 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Jim Ingham54cc6e42012-07-11 21:41:19 +00001569
Greg Claytona658fd22011-06-04 01:26:29 +00001570 if (bp_site_sp)
1571 {
1572 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1573 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1574 // 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 +00001575 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00001576 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001577 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00001578 }
1579 else
1580 {
1581 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001582 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00001583 }
1584 }
Jim Ingham54cc6e42012-07-11 21:41:19 +00001585 else
Greg Claytona658fd22011-06-04 01:26:29 +00001586 {
Jim Ingham4dc613b2012-10-27 02:52:04 +00001587 // If we were stepping then assume the stop was the result of the trace. If we were
1588 // not stepping then report the SIGTRAP.
1589 // FIXME: We are still missing the case where we single step over a trap instruction.
Greg Clayton160c9d82013-05-01 21:54:04 +00001590 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1591 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Jim Ingham4dc613b2012-10-27 02:52:04 +00001592 else
Greg Clayton160c9d82013-05-01 21:54:04 +00001593 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo));
Greg Claytona658fd22011-06-04 01:26:29 +00001594 }
1595 }
1596 if (!handled)
Greg Clayton160c9d82013-05-01 21:54:04 +00001597 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Jason Molenda8214b012013-04-25 01:33:46 +00001598 }
Greg Claytona658fd22011-06-04 01:26:29 +00001599
1600 if (!description.empty())
1601 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001602 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
Greg Claytona658fd22011-06-04 01:26:29 +00001603 if (stop_info_sp)
1604 {
1605 stop_info_sp->SetDescription (description.c_str());
Greg Clayton3418c852011-08-10 02:10:13 +00001606 }
Greg Claytona658fd22011-06-04 01:26:29 +00001607 else
1608 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001609 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00001610 }
1611 }
1612 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001613 }
1614 return eStateStopped;
1615 }
1616 break;
1617
1618 case 'W':
1619 // process exited
1620 return eStateExited;
1621
1622 default:
1623 break;
1624 }
1625 return eStateInvalid;
1626}
1627
1628void
1629ProcessGDBRemote::RefreshStateAfterStop ()
1630{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001631 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001632 m_thread_ids.clear();
1633 // Set the thread stop info. It might have a "threads" key whose value is
1634 // a list of all thread IDs in the current process, so m_thread_ids might
1635 // get set.
1636 SetThreadStopInfo (m_last_stop_packet);
1637 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1638 if (m_thread_ids.empty())
1639 {
1640 // No, we need to fetch the thread list manually
1641 UpdateThreadIDList();
1642 }
1643
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001644 // Let all threads recover from stopping and do any clean up based
1645 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001646 m_thread_list_real.RefreshStateAfterStop();
Greg Clayton9e920902012-04-10 02:25:43 +00001647
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001648}
1649
1650Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001651ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001652{
1653 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001654
Greg Clayton6ed95942011-01-22 07:12:45 +00001655 bool timed_out = false;
1656 Mutex::Locker locker;
Greg Clayton513c26c2011-01-29 07:10:55 +00001657
1658 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00001659 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001660 // We are being asked to halt during an attach. We need to just close
1661 // our file handle and debugserver will go away, and we can be done...
1662 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00001663 }
Greg Clayton513c26c2011-01-29 07:10:55 +00001664 else
1665 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001666 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton513c26c2011-01-29 07:10:55 +00001667 {
1668 if (timed_out)
1669 error.SetErrorString("timed out sending interrupt packet");
1670 else
1671 error.SetErrorString("unknown error sending interrupt packet");
1672 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001673
1674 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton513c26c2011-01-29 07:10:55 +00001675 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001676 return error;
1677}
1678
1679Error
Jim Inghamacff8952013-05-02 00:27:30 +00001680ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00001681{
1682 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001683 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00001684 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00001685 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
1686
Greg Clayton594e5ed2010-09-27 21:07:38 +00001687 DisableAllBreakpointSites ();
1688
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001689 m_thread_list.DiscardThreadPlans();
Greg Clayton594e5ed2010-09-27 21:07:38 +00001690
Jim Inghamacff8952013-05-02 00:27:30 +00001691 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001692 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00001693 {
Jim Inghamacff8952013-05-02 00:27:30 +00001694 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001695 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1696 else
Jim Inghamacff8952013-05-02 00:27:30 +00001697 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00001698 }
Jim Inghamacff8952013-05-02 00:27:30 +00001699
1700 if (!error.Success())
1701 return error;
1702
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001703 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00001704 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001705
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001706 SetPrivateState (eStateDetached);
1707 ResumePrivateStateThread();
1708
1709 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00001710 return error;
1711}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001712
Jim Ingham43c555d2012-07-04 00:35:43 +00001713
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001714Error
1715ProcessGDBRemote::DoDestroy ()
1716{
1717 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001718 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001719 if (log)
1720 log->Printf ("ProcessGDBRemote::DoDestroy()");
1721
Jim Ingham43c555d2012-07-04 00:35:43 +00001722 // There is a bug in older iOS debugservers where they don't shut down the process
1723 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
1724 // this can cause problems with restarting. So we check to see if any of our threads are stopped
1725 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
1726 // destroy it again.
1727 //
1728 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
1729 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
1730 // the debugservers with this bug are equal. There really should be a better way to test this!
1731 //
1732 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
1733 // get called here to destroy again and we're still at a breakpoint or exception, then we should
1734 // just do the straight-forward kill.
1735 //
1736 // And of course, if we weren't able to stop the process by the time we get here, it isn't
1737 // necessary (or helpful) to do any of this.
1738
1739 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
1740 {
1741 PlatformSP platform_sp = GetTarget().GetPlatform();
1742
1743 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
1744 if (platform_sp
1745 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00001746 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00001747 {
1748 if (m_destroy_tried_resuming)
1749 {
1750 if (log)
1751 log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again.");
1752 }
1753 else
1754 {
1755 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
1756 // but we really need it to happen here and it doesn't matter if we do it twice.
1757 m_thread_list.DiscardThreadPlans();
1758 DisableAllBreakpointSites();
1759
1760 bool stop_looks_like_crash = false;
1761 ThreadList &threads = GetThreadList();
1762
1763 {
Jim Ingham45350372012-09-11 00:08:52 +00001764 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00001765
1766 size_t num_threads = threads.GetSize();
1767 for (size_t i = 0; i < num_threads; i++)
1768 {
1769 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00001770 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00001771 StopReason reason = eStopReasonInvalid;
1772 if (stop_info_sp)
1773 reason = stop_info_sp->GetStopReason();
1774 if (reason == eStopReasonBreakpoint
1775 || reason == eStopReasonException)
1776 {
1777 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00001778 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
1779 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00001780 stop_info_sp->GetDescription());
1781 stop_looks_like_crash = true;
1782 break;
1783 }
1784 }
1785 }
1786
1787 if (stop_looks_like_crash)
1788 {
1789 if (log)
1790 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
1791 m_destroy_tried_resuming = true;
1792
1793 // If we are going to run again before killing, it would be good to suspend all the threads
1794 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
1795 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
1796 // have to run the risk of letting those threads proceed a bit.
1797
1798 {
Jim Ingham45350372012-09-11 00:08:52 +00001799 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00001800
1801 size_t num_threads = threads.GetSize();
1802 for (size_t i = 0; i < num_threads; i++)
1803 {
1804 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00001805 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00001806 StopReason reason = eStopReasonInvalid;
1807 if (stop_info_sp)
1808 reason = stop_info_sp->GetStopReason();
1809 if (reason != eStopReasonBreakpoint
1810 && reason != eStopReasonException)
1811 {
1812 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00001813 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
1814 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00001815 thread_sp->SetResumeState(eStateSuspended);
1816 }
1817 }
1818 }
1819 Resume ();
1820 return Destroy();
1821 }
1822 }
1823 }
1824 }
1825
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001826 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00001827 int exit_status = SIGABRT;
1828 std::string exit_string;
1829
Greg Clayton6ed95942011-01-22 07:12:45 +00001830 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001831 {
Jim Inghamaab78372011-10-28 01:11:35 +00001832 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00001833 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001834
1835 StringExtractorGDBRemote response;
1836 bool send_async = true;
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00001837 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3);
1838
Greg Claytonc574ede2011-03-10 02:26:48 +00001839 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton513c26c2011-01-29 07:10:55 +00001840 {
1841 char packet_cmd = response.GetChar(0);
1842
1843 if (packet_cmd == 'W' || packet_cmd == 'X')
1844 {
Greg Clayton09c3e3d2011-12-06 04:51:14 +00001845 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00001846 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00001847 exit_status = response.GetHexU8();
1848 }
1849 else
1850 {
1851 if (log)
1852 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
1853 exit_string.assign("got unexpected response to k packet: ");
1854 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00001855 }
1856 }
1857 else
1858 {
Jim Inghambabfc382012-06-06 00:32:39 +00001859 if (log)
1860 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
1861 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00001862 }
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00001863
1864 m_gdb_comm.SetPacketTimeout(old_packet_timeout);
Greg Clayton6779606a2011-01-22 23:43:18 +00001865 }
Jim Inghambabfc382012-06-06 00:32:39 +00001866 else
1867 {
1868 if (log)
1869 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
Jim Inghamcfc09352012-07-27 23:57:19 +00001870 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00001871 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001872 }
Jim Inghambabfc382012-06-06 00:32:39 +00001873 else
1874 {
1875 // If we missed setting the exit status on the way out, do it here.
1876 // NB set exit status can be called multiple times, the first one sets the status.
1877 exit_string.assign("destroying when not connected to debugserver");
1878 }
1879
1880 SetExitStatus(exit_status, exit_string.c_str());
1881
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001882 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001883 KillDebugserverProcess ();
1884 return error;
1885}
1886
Greg Clayton8cda7f02013-05-21 21:55:59 +00001887void
1888ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
1889{
1890 lldb_private::Mutex::Locker locker (m_last_stop_packet_mutex);
1891 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
1892 if (did_exec)
1893 {
1894 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1895 if (log)
1896 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
1897
1898 m_thread_list_real.Clear();
1899 m_thread_list.Clear();
1900 BuildDynamicRegisterInfo (true);
1901 m_gdb_comm.ResetDiscoverableSettings();
1902 }
1903 m_last_stop_packet = response;
1904}
1905
1906
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001907//------------------------------------------------------------------
1908// Process Queries
1909//------------------------------------------------------------------
1910
1911bool
1912ProcessGDBRemote::IsAlive ()
1913{
Greg Clayton10177aa2010-12-08 05:08:21 +00001914 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001915}
1916
1917addr_t
1918ProcessGDBRemote::GetImageInfoAddress()
1919{
Jason Molenda6ba6d3d2013-01-30 04:39:32 +00001920 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001921}
1922
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001923//------------------------------------------------------------------
1924// Process Memory
1925//------------------------------------------------------------------
1926size_t
1927ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1928{
1929 if (size > m_max_memory_size)
1930 {
1931 // Keep memory read sizes down to a sane limit. This function will be
1932 // called multiple times in order to complete the task by
1933 // lldb_private::Process so it is ok to do this.
1934 size = m_max_memory_size;
1935 }
1936
1937 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001938 const int packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001939 assert (packet_len + 1 < sizeof(packet));
1940 StringExtractorGDBRemote response;
Greg Claytonc574ede2011-03-10 02:26:48 +00001941 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001942 {
Greg Clayton576d8832011-03-22 04:00:09 +00001943 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001944 {
1945 error.Clear();
1946 return response.GetHexBytes(buf, size, '\xdd');
1947 }
Greg Clayton576d8832011-03-22 04:00:09 +00001948 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00001949 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00001950 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00001951 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001952 else
Greg Clayton9944cd72012-09-19 01:46:31 +00001953 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001954 }
1955 else
1956 {
1957 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1958 }
1959 return 0;
1960}
1961
1962size_t
1963ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1964{
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00001965 if (size > m_max_memory_size)
1966 {
1967 // Keep memory read sizes down to a sane limit. This function will be
1968 // called multiple times in order to complete the task by
1969 // lldb_private::Process so it is ok to do this.
1970 size = m_max_memory_size;
1971 }
1972
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001973 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00001974 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Clayton7fb56d02011-02-01 01:31:41 +00001975 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001976 StringExtractorGDBRemote response;
Greg Claytonc574ede2011-03-10 02:26:48 +00001977 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001978 {
Greg Clayton576d8832011-03-22 04:00:09 +00001979 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001980 {
1981 error.Clear();
1982 return size;
1983 }
Greg Clayton576d8832011-03-22 04:00:09 +00001984 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00001985 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00001986 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00001987 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001988 else
Greg Clayton9944cd72012-09-19 01:46:31 +00001989 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 +00001990 }
1991 else
1992 {
1993 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1994 }
1995 return 0;
1996}
1997
1998lldb::addr_t
1999ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2000{
Greg Clayton2a48f522011-05-14 01:50:35 +00002001 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2002
Greg Clayton70b57652011-05-15 01:25:55 +00002003 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton2a48f522011-05-14 01:50:35 +00002004 switch (supported)
2005 {
2006 case eLazyBoolCalculate:
2007 case eLazyBoolYes:
2008 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2009 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2010 return allocated_addr;
2011
2012 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002013 // Call mmap() to create memory in the inferior..
2014 unsigned prot = 0;
2015 if (permissions & lldb::ePermissionsReadable)
2016 prot |= eMmapProtRead;
2017 if (permissions & lldb::ePermissionsWritable)
2018 prot |= eMmapProtWrite;
2019 if (permissions & lldb::ePermissionsExecutable)
2020 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00002021
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002022 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2023 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2024 m_addr_to_mmap_size[allocated_addr] = size;
2025 else
2026 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton2a48f522011-05-14 01:50:35 +00002027 break;
2028 }
2029
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002030 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00002031 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002032 else
2033 error.Clear();
2034 return allocated_addr;
2035}
2036
2037Error
Greg Clayton46fb5582011-11-18 07:03:08 +00002038ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2039 MemoryRegionInfo &region_info)
2040{
2041
2042 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2043 return error;
2044}
2045
2046Error
Johnny Chen64637202012-05-23 21:09:52 +00002047ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2048{
2049
2050 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2051 return error;
2052}
2053
2054Error
Enrico Granataf04a2192012-07-13 23:18:48 +00002055ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2056{
2057 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2058 return error;
2059}
2060
2061Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002062ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2063{
2064 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00002065 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2066
2067 switch (supported)
2068 {
2069 case eLazyBoolCalculate:
2070 // We should never be deallocating memory without allocating memory
2071 // first so we should never get eLazyBoolCalculate
2072 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2073 break;
2074
2075 case eLazyBoolYes:
2076 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00002077 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002078 break;
2079
2080 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002081 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00002082 {
2083 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002084 if (pos != m_addr_to_mmap_size.end() &&
2085 InferiorCallMunmap(this, addr, pos->second))
2086 m_addr_to_mmap_size.erase (pos);
2087 else
Daniel Malead01b2952012-11-29 21:49:15 +00002088 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002089 }
2090 break;
2091 }
2092
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002093 return error;
2094}
2095
2096
2097//------------------------------------------------------------------
2098// Process STDIO
2099//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002100size_t
2101ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2102{
2103 if (m_stdio_communication.IsConnected())
2104 {
2105 ConnectionStatus status;
2106 m_stdio_communication.Write(src, src_len, status, NULL);
2107 }
2108 return 0;
2109}
2110
2111Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002112ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002113{
2114 Error error;
2115 assert (bp_site != NULL);
2116
Greg Clayton5160ce52013-03-27 23:08:40 +00002117 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002118 user_id_t site_id = bp_site->GetID();
2119 const addr_t addr = bp_site->GetLoadAddress();
2120 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002121 log->Printf ("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002122
2123 if (bp_site->IsEnabled())
2124 {
2125 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002126 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 +00002127 return error;
2128 }
2129 else
2130 {
2131 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2132
2133 if (bp_site->HardwarePreferred())
2134 {
2135 // Try and set hardware breakpoint, and if that fails, fall through
2136 // and set a software breakpoint?
Greg Clayton8b82f082011-04-12 05:54:46 +00002137 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002138 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002139 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002140 {
2141 bp_site->SetEnabled(true);
Greg Clayton8b82f082011-04-12 05:54:46 +00002142 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002143 return error;
2144 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002145 }
2146 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002147
2148 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002149 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002150 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
2151 {
2152 bp_site->SetEnabled(true);
2153 bp_site->SetType (BreakpointSite::eExternal);
2154 return error;
2155 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002156 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002157
2158 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002159 }
2160
2161 if (log)
2162 {
2163 const char *err_string = error.AsCString();
Jim Ingham299c0c12013-02-15 02:06:30 +00002164 log->Printf ("ProcessGDBRemote::EnableBreakpointSite () error for breakpoint at 0x%8.8" PRIx64 ": %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002165 bp_site->GetLoadAddress(),
2166 err_string ? err_string : "NULL");
2167 }
2168 // We shouldn't reach here on a successful breakpoint enable...
2169 if (error.Success())
2170 error.SetErrorToGenericError();
2171 return error;
2172}
2173
2174Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002175ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002176{
2177 Error error;
2178 assert (bp_site != NULL);
2179 addr_t addr = bp_site->GetLoadAddress();
2180 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00002181 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002182 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002183 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002184
2185 if (bp_site->IsEnabled())
2186 {
2187 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2188
Greg Clayton8b82f082011-04-12 05:54:46 +00002189 BreakpointSite::Type bp_type = bp_site->GetType();
2190 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002191 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002192 case BreakpointSite::eSoftware:
2193 error = DisableSoftwareBreakpoint (bp_site);
2194 break;
2195
2196 case BreakpointSite::eHardware:
2197 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2198 error.SetErrorToGenericError();
2199 break;
2200
2201 case BreakpointSite::eExternal:
2202 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2203 error.SetErrorToGenericError();
2204 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002205 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002206 if (error.Success())
2207 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002208 }
2209 else
2210 {
2211 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002212 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 +00002213 return error;
2214 }
2215
2216 if (error.Success())
2217 error.SetErrorToGenericError();
2218 return error;
2219}
2220
Johnny Chen11309a32011-09-06 22:38:36 +00002221// Pre-requisite: wp != NULL.
2222static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00002223GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00002224{
2225 assert(wp);
2226 bool watch_read = wp->WatchpointRead();
2227 bool watch_write = wp->WatchpointWrite();
2228
2229 // watch_read and watch_write cannot both be false.
2230 assert(watch_read || watch_write);
2231 if (watch_read && watch_write)
2232 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00002233 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00002234 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00002235 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00002236 return eWatchpointWrite;
2237}
2238
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002239Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002240ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002241{
2242 Error error;
2243 if (wp)
2244 {
2245 user_id_t watchID = wp->GetID();
2246 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00002247 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002248 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002249 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002250 if (wp->IsEnabled())
2251 {
2252 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002253 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 +00002254 return error;
2255 }
Johnny Chen11309a32011-09-06 22:38:36 +00002256
2257 GDBStoppointType type = GetGDBStoppointType(wp);
2258 // Pass down an appropriate z/Z packet...
2259 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002260 {
Johnny Chen11309a32011-09-06 22:38:36 +00002261 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2262 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002263 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002264 return error;
2265 }
2266 else
2267 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002268 }
Johnny Chen11309a32011-09-06 22:38:36 +00002269 else
2270 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002271 }
2272 else
2273 {
Johnny Chen01a67862011-10-14 00:42:25 +00002274 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002275 }
2276 if (error.Success())
2277 error.SetErrorToGenericError();
2278 return error;
2279}
2280
2281Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002282ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002283{
2284 Error error;
2285 if (wp)
2286 {
2287 user_id_t watchID = wp->GetID();
2288
Greg Clayton5160ce52013-03-27 23:08:40 +00002289 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002290
2291 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00002292
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002293 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002294 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002295
Johnny Chen11309a32011-09-06 22:38:36 +00002296 if (!wp->IsEnabled())
2297 {
2298 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002299 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 +00002300 // See also 'class WatchpointSentry' within StopInfo.cpp.
2301 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2302 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00002303 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002304 return error;
2305 }
2306
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002307 if (wp->IsHardware())
2308 {
Johnny Chen11309a32011-09-06 22:38:36 +00002309 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002310 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00002311 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2312 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002313 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002314 return error;
2315 }
2316 else
2317 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002318 }
2319 // TODO: clear software watchpoints if we implement them
2320 }
2321 else
2322 {
Johnny Chen01a67862011-10-14 00:42:25 +00002323 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002324 }
2325 if (error.Success())
2326 error.SetErrorToGenericError();
2327 return error;
2328}
2329
2330void
2331ProcessGDBRemote::Clear()
2332{
2333 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002334 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002335 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002336}
2337
2338Error
2339ProcessGDBRemote::DoSignal (int signo)
2340{
2341 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002342 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002343 if (log)
2344 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2345
2346 if (!m_gdb_comm.SendAsyncSignal (signo))
2347 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2348 return error;
2349}
2350
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002351Error
Han Ming Ong84647042012-02-25 01:07:38 +00002352ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)
2353{
2354 ProcessLaunchInfo launch_info;
2355 return StartDebugserverProcess(debugserver_url, launch_info);
2356}
2357
2358Error
2359ProcessGDBRemote::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 +00002360{
2361 Error error;
2362 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2363 {
2364 // If we locate debugserver, keep that located version around
2365 static FileSpec g_debugserver_file_spec;
2366
Han Ming Ong84647042012-02-25 01:07:38 +00002367 ProcessLaunchInfo debugserver_launch_info;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002368 char debugserver_path[PATH_MAX];
Han Ming Ong84647042012-02-25 01:07:38 +00002369 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002370
2371 // Always check to see if we have an environment override for the path
2372 // to the debugserver to use and use it if we do.
2373 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2374 if (env_debugserver_path)
Greg Clayton274060b2010-10-20 20:54:39 +00002375 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002376 else
2377 debugserver_file_spec = g_debugserver_file_spec;
2378 bool debugserver_exists = debugserver_file_spec.Exists();
2379 if (!debugserver_exists)
2380 {
2381 // The debugserver binary is in the LLDB.framework/Resources
2382 // directory.
Greg Claytondd36def2010-10-17 22:03:32 +00002383 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002384 {
Greg Claytondd36def2010-10-17 22:03:32 +00002385 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002386 debugserver_exists = debugserver_file_spec.Exists();
Greg Claytondd36def2010-10-17 22:03:32 +00002387 if (debugserver_exists)
2388 {
2389 g_debugserver_file_spec = debugserver_file_spec;
2390 }
2391 else
2392 {
2393 g_debugserver_file_spec.Clear();
2394 debugserver_file_spec.Clear();
2395 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002396 }
2397 }
2398
2399 if (debugserver_exists)
2400 {
2401 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2402
2403 m_stdio_communication.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002404
Greg Clayton5160ce52013-03-27 23:08:40 +00002405 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002406
Han Ming Ong84647042012-02-25 01:07:38 +00002407 Args &debugserver_args = debugserver_launch_info.GetArguments();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002408 char arg_cstr[PATH_MAX];
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002409
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002410 // Start args with "debugserver /file/path -r --"
2411 debugserver_args.AppendArgument(debugserver_path);
2412 debugserver_args.AppendArgument(debugserver_url);
Greg Claytondd36def2010-10-17 22:03:32 +00002413 // use native registers, not the GDB registers
2414 debugserver_args.AppendArgument("--native-regs");
2415 // make debugserver run in its own session so signals generated by
2416 // special terminal key sequences (^C) don't affect debugserver
2417 debugserver_args.AppendArgument("--setsid");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002418
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002419 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2420 if (env_debugserver_log_file)
2421 {
2422 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2423 debugserver_args.AppendArgument(arg_cstr);
2424 }
2425
2426 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2427 if (env_debugserver_log_flags)
2428 {
2429 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2430 debugserver_args.AppendArgument(arg_cstr);
2431 }
Jim Inghama0cc6b22012-10-03 22:31:30 +00002432// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
2433// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002434
Greg Clayton8b82f082011-04-12 05:54:46 +00002435 // We currently send down all arguments, attach pids, or attach
2436 // process names in dedicated GDB server packets, so we don't need
2437 // to pass them as arguments. This is currently because of all the
2438 // things we need to setup prior to launching: the environment,
2439 // current working dir, file actions, etc.
2440#if 0
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002441 // Now append the program arguments
Greg Clayton71337622011-02-24 22:24:29 +00002442 if (inferior_argv)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002443 {
Greg Clayton71337622011-02-24 22:24:29 +00002444 // Terminate the debugserver args so we can now append the inferior args
2445 debugserver_args.AppendArgument("--");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002446
Greg Clayton71337622011-02-24 22:24:29 +00002447 for (int i = 0; inferior_argv[i] != NULL; ++i)
2448 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002449 }
2450 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2451 {
2452 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2453 debugserver_args.AppendArgument (arg_cstr);
2454 }
2455 else if (attach_name && attach_name[0])
2456 {
2457 if (wait_for_launch)
2458 debugserver_args.AppendArgument ("--waitfor");
2459 else
2460 debugserver_args.AppendArgument ("--attach");
2461 debugserver_args.AppendArgument (attach_name);
2462 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002463#endif
Greg Clayton8b82f082011-04-12 05:54:46 +00002464
2465 ProcessLaunchInfo::FileAction file_action;
2466
2467 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2468 // to "/dev/null" if we run into any problems.
2469 file_action.Close (STDIN_FILENO);
Han Ming Ong84647042012-02-25 01:07:38 +00002470 debugserver_launch_info.AppendFileAction (file_action);
Greg Clayton8b82f082011-04-12 05:54:46 +00002471 file_action.Close (STDOUT_FILENO);
Han Ming Ong84647042012-02-25 01:07:38 +00002472 debugserver_launch_info.AppendFileAction (file_action);
Greg Clayton8b82f082011-04-12 05:54:46 +00002473 file_action.Close (STDERR_FILENO);
Han Ming Ong84647042012-02-25 01:07:38 +00002474 debugserver_launch_info.AppendFileAction (file_action);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002475
2476 if (log)
2477 {
2478 StreamString strm;
2479 debugserver_args.Dump (&strm);
2480 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2481 }
2482
Han Ming Ong84647042012-02-25 01:07:38 +00002483 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2484 debugserver_launch_info.SetUserID(process_info.GetUserID());
Greg Claytone4e45922011-11-16 05:37:56 +00002485
Han Ming Ong84647042012-02-25 01:07:38 +00002486 error = Host::LaunchProcess(debugserver_launch_info);
Greg Clayton0b42ac32010-07-02 01:29:13 +00002487
Greg Clayton8b82f082011-04-12 05:54:46 +00002488 if (error.Success ())
Han Ming Ong84647042012-02-25 01:07:38 +00002489 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Greg Clayton8b82f082011-04-12 05:54:46 +00002490 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002491 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2492
2493 if (error.Fail() || log)
Greg Clayton5160ce52013-03-27 23:08:40 +00002494 error.PutToLog(log, "Host::LaunchProcess (launch_info) => pid=%" PRIu64 ", path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002495 }
2496 else
2497 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002498 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002499 }
2500
2501 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2502 StartAsyncThread ();
2503 }
2504 return error;
2505}
2506
2507bool
2508ProcessGDBRemote::MonitorDebugserverProcess
2509(
2510 void *callback_baton,
2511 lldb::pid_t debugserver_pid,
Greg Claytone4e45922011-11-16 05:37:56 +00002512 bool exited, // True if the process did exit
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002513 int signo, // Zero for no signal
2514 int exit_status // Exit value of process if signal is zero
2515)
2516{
Greg Claytone4e45922011-11-16 05:37:56 +00002517 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2518 // and might not exist anymore, so we need to carefully try to get the
2519 // target for this process first since we have a race condition when
2520 // we are done running between getting the notice that the inferior
2521 // process has died and the debugserver that was debugging this process.
2522 // In our test suite, we are also continually running process after
2523 // process, so we must be very careful to make sure:
2524 // 1 - process object hasn't been deleted already
2525 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002526
2527 // "debugserver_pid" argument passed in is the process ID for
2528 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00002529 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002530
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002531 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton6779606a2011-01-22 23:43:18 +00002532
Greg Claytone4e45922011-11-16 05:37:56 +00002533 // Get a shared pointer to the target that has a matching process pointer.
2534 // This target could be gone, or the target could already have a new process
2535 // object inside of it
2536 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2537
Greg Clayton6779606a2011-01-22 23:43:18 +00002538 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002539 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 +00002540
Greg Claytone4e45922011-11-16 05:37:56 +00002541 if (target_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002542 {
Greg Claytone4e45922011-11-16 05:37:56 +00002543 // We found a process in a target that matches, but another thread
2544 // might be in the process of launching a new process that will
2545 // soon replace it, so get a shared pointer to the process so we
2546 // can keep it alive.
2547 ProcessSP process_sp (target_sp->GetProcessSP());
2548 // Now we have a shared pointer to the process that can't go away on us
2549 // so we now make sure it was the same as the one passed in, and also make
2550 // sure that our previous "process *" didn't get deleted and have a new
2551 // "process *" created in its place with the same pointer. To verify this
2552 // we make sure the process has our debugserver process ID. If we pass all
2553 // of these tests, then we are sure that this process is the one we were
2554 // looking for.
2555 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002556 {
Greg Claytone4e45922011-11-16 05:37:56 +00002557 // Sleep for a half a second to make sure our inferior process has
2558 // time to set its exit status before we set it incorrectly when
2559 // both the debugserver and the inferior process shut down.
2560 usleep (500000);
2561 // If our process hasn't yet exited, debugserver might have died.
2562 // If the process did exit, the we are reaping it.
2563 const StateType state = process->GetState();
2564
2565 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2566 state != eStateInvalid &&
2567 state != eStateUnloaded &&
2568 state != eStateExited &&
2569 state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002570 {
Greg Claytone4e45922011-11-16 05:37:56 +00002571 char error_str[1024];
2572 if (signo)
2573 {
2574 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2575 if (signal_cstr)
2576 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2577 else
2578 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2579 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002580 else
Greg Claytone4e45922011-11-16 05:37:56 +00002581 {
2582 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2583 }
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002584
Greg Claytone4e45922011-11-16 05:37:56 +00002585 process->SetExitStatus (-1, error_str);
2586 }
2587 // Debugserver has exited we need to let our ProcessGDBRemote
2588 // know that it no longer has a debugserver instance
2589 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002590 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002591 }
2592 return true;
2593}
2594
2595void
2596ProcessGDBRemote::KillDebugserverProcess ()
2597{
2598 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2599 {
2600 ::kill (m_debugserver_pid, SIGINT);
2601 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2602 }
2603}
2604
2605void
2606ProcessGDBRemote::Initialize()
2607{
2608 static bool g_initialized = false;
2609
2610 if (g_initialized == false)
2611 {
2612 g_initialized = true;
2613 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2614 GetPluginDescriptionStatic(),
2615 CreateInstance);
2616
2617 Log::Callbacks log_callbacks = {
2618 ProcessGDBRemoteLog::DisableLog,
2619 ProcessGDBRemoteLog::EnableLog,
2620 ProcessGDBRemoteLog::ListLogCategories
2621 };
2622
2623 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2624 }
2625}
2626
2627bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002628ProcessGDBRemote::StartAsyncThread ()
2629{
Greg Clayton5160ce52013-03-27 23:08:40 +00002630 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002631
2632 if (log)
2633 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Ingham455fa5c2012-11-01 01:15:33 +00002634
2635 Mutex::Locker start_locker(m_async_thread_state_mutex);
2636 if (m_async_thread_state == eAsyncThreadNotStarted)
2637 {
2638 // Create a thread that watches our internal state and controls which
2639 // events make it to clients (into the DCProcess event queue).
2640 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2641 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2642 {
2643 m_async_thread_state = eAsyncThreadRunning;
2644 return true;
2645 }
2646 else
2647 return false;
2648 }
2649 else
2650 {
2651 // Somebody tried to start the async thread while it was either being started or stopped. If the former, and
2652 // it started up successfully, then say all's well. Otherwise it is an error, since we aren't going to restart it.
2653 if (log)
2654 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
2655 if (m_async_thread_state == eAsyncThreadRunning)
2656 return true;
2657 else
2658 return false;
2659 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002660}
2661
2662void
2663ProcessGDBRemote::StopAsyncThread ()
2664{
Greg Clayton5160ce52013-03-27 23:08:40 +00002665 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002666
2667 if (log)
2668 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2669
Jim Ingham455fa5c2012-11-01 01:15:33 +00002670 Mutex::Locker start_locker(m_async_thread_state_mutex);
2671 if (m_async_thread_state == eAsyncThreadRunning)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002672 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00002673 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2674
2675 // This will shut down the async thread.
2676 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
2677
2678 // Stop the stdio thread
2679 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2680 {
2681 Host::ThreadJoin (m_async_thread, NULL, NULL);
2682 }
2683 m_async_thread_state = eAsyncThreadDone;
2684 }
2685 else
2686 {
2687 if (log)
2688 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002689 }
2690}
2691
2692
2693void *
2694ProcessGDBRemote::AsyncThread (void *arg)
2695{
2696 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2697
Greg Clayton5160ce52013-03-27 23:08:40 +00002698 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002699 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002700 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002701
2702 Listener listener ("ProcessGDBRemote::AsyncThread");
2703 EventSP event_sp;
2704 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2705 eBroadcastBitAsyncThreadShouldExit;
2706
2707 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2708 {
Greg Clayton71337622011-02-24 22:24:29 +00002709 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2710
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002711 bool done = false;
2712 while (!done)
2713 {
2714 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002715 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002716 if (listener.WaitForEvent (NULL, event_sp))
2717 {
2718 const uint32_t event_type = event_sp->GetType();
Greg Clayton71337622011-02-24 22:24:29 +00002719 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002720 {
Greg Clayton71337622011-02-24 22:24:29 +00002721 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002722 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 +00002723
Greg Clayton71337622011-02-24 22:24:29 +00002724 switch (event_type)
2725 {
2726 case eBroadcastBitAsyncContinue:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002727 {
Greg Clayton71337622011-02-24 22:24:29 +00002728 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002729
Greg Clayton71337622011-02-24 22:24:29 +00002730 if (continue_packet)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002731 {
Greg Clayton71337622011-02-24 22:24:29 +00002732 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2733 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2734 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002735 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002736
Greg Clayton71337622011-02-24 22:24:29 +00002737 if (::strstr (continue_cstr, "vAttach") == NULL)
2738 process->SetPrivateState(eStateRunning);
2739 StringExtractorGDBRemote response;
2740 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002741
Greg Clayton0772ded2012-05-16 02:48:06 +00002742 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
2743 // The thread ID list might be contained within the "response", or the stop reply packet that
2744 // caused the stop. So clear it now before we give the stop reply packet to the process
2745 // using the process->SetLastStopPacket()...
2746 process->ClearThreadIDList ();
2747
Greg Clayton71337622011-02-24 22:24:29 +00002748 switch (stop_state)
2749 {
2750 case eStateStopped:
2751 case eStateCrashed:
2752 case eStateSuspended:
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002753 process->SetLastStopPacket (response);
Greg Clayton71337622011-02-24 22:24:29 +00002754 process->SetPrivateState (stop_state);
2755 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002756
Greg Clayton71337622011-02-24 22:24:29 +00002757 case eStateExited:
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002758 process->SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002759 process->ClearThreadIDList();
Greg Clayton71337622011-02-24 22:24:29 +00002760 response.SetFilePos(1);
2761 process->SetExitStatus(response.GetHexU8(), NULL);
2762 done = true;
2763 break;
2764
2765 case eStateInvalid:
2766 process->SetExitStatus(-1, "lost connection");
2767 break;
2768
2769 default:
2770 process->SetPrivateState (stop_state);
2771 break;
2772 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002773 }
2774 }
Greg Clayton71337622011-02-24 22:24:29 +00002775 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002776
Greg Clayton71337622011-02-24 22:24:29 +00002777 case eBroadcastBitAsyncThreadShouldExit:
2778 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002779 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Clayton71337622011-02-24 22:24:29 +00002780 done = true;
2781 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002782
Greg Clayton71337622011-02-24 22:24:29 +00002783 default:
2784 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002785 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 +00002786 done = true;
2787 break;
2788 }
2789 }
2790 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2791 {
2792 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2793 {
2794 process->SetExitStatus (-1, "lost connection");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002795 done = true;
Greg Clayton71337622011-02-24 22:24:29 +00002796 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002797 }
2798 }
2799 else
2800 {
2801 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002802 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 +00002803 done = true;
2804 }
2805 }
2806 }
2807
2808 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002809 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002810
2811 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2812 return NULL;
2813}
2814
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002815const char *
2816ProcessGDBRemote::GetDispatchQueueNameForThread
2817(
2818 addr_t thread_dispatch_qaddr,
2819 std::string &dispatch_queue_name
2820)
2821{
2822 dispatch_queue_name.clear();
2823 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2824 {
2825 // Cache the dispatch_queue_offsets_addr value so we don't always have
2826 // to look it up
2827 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2828 {
Greg Clayton897f96a2010-10-12 17:33:06 +00002829 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2830 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Claytonb9a01b32012-02-26 05:51:37 +00002831 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false));
2832 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec));
Greg Clayton897f96a2010-10-12 17:33:06 +00002833 if (module_sp)
2834 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2835
2836 if (dispatch_queue_offsets_symbol == NULL)
2837 {
Greg Claytonb9a01b32012-02-26 05:51:37 +00002838 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false));
2839 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_module_spec);
Greg Clayton897f96a2010-10-12 17:33:06 +00002840 if (module_sp)
2841 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2842 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002843 if (dispatch_queue_offsets_symbol)
Greg Claytone7612132012-03-07 21:03:09 +00002844 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002845
2846 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2847 return NULL;
2848 }
2849
2850 uint8_t memory_buffer[8];
Greg Clayton514487e2011-02-15 21:59:32 +00002851 DataExtractor data (memory_buffer,
2852 sizeof(memory_buffer),
2853 m_target.GetArchitecture().GetByteOrder(),
2854 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002855
2856 // Excerpt from src/queue_private.h
2857 struct dispatch_queue_offsets_s
2858 {
2859 uint16_t dqo_version;
Jason Molendae424a9b2012-11-10 06:54:30 +00002860 uint16_t dqo_label; // in version 1-3, offset to string; in version 4+, offset to a pointer to a string
2861 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 +00002862 } dispatch_queue_offsets;
2863
2864
2865 Error error;
2866 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2867 {
Greg Claytonc7bece562013-01-25 18:06:21 +00002868 lldb::offset_t data_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002869 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2870 {
2871 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2872 {
2873 data_offset = 0;
2874 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
Jason Molendae424a9b2012-11-10 06:54:30 +00002875 if (dispatch_queue_offsets.dqo_version >= 4)
2876 {
2877 // libdispatch versions 4+, pointer to dispatch name is in the
2878 // queue structure.
2879 lldb::addr_t pointer_to_label_address = queue_addr + dispatch_queue_offsets.dqo_label;
2880 if (ReadMemory (pointer_to_label_address, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2881 {
2882 data_offset = 0;
2883 lldb::addr_t label_addr = data.GetAddress(&data_offset);
2884 ReadCStringFromMemory (label_addr, dispatch_queue_name, error);
2885 }
2886 }
2887 else
2888 {
2889 // libdispatch versions 1-3, dispatch name is a fixed width char array
2890 // in the queue structure.
2891 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2892 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2893 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2894 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2895 dispatch_queue_name.erase (bytes_read);
2896 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002897 }
2898 }
2899 }
2900 }
2901 if (dispatch_queue_name.empty())
2902 return NULL;
2903 return dispatch_queue_name.c_str();
2904}
2905
Greg Claytone996fd32011-03-08 22:40:15 +00002906//uint32_t
2907//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2908//{
2909// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2910// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2911// if (m_local_debugserver)
2912// {
2913// return Host::ListProcessesMatchingName (name, matches, pids);
2914// }
2915// else
2916// {
2917// // FIXME: Implement talking to the remote debugserver.
2918// return 0;
2919// }
2920//
2921//}
2922//
Jim Ingham1c823b42011-01-22 01:33:44 +00002923bool
2924ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2925 lldb_private::StoppointCallbackContext *context,
2926 lldb::user_id_t break_id,
2927 lldb::user_id_t break_loc_id)
2928{
2929 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2930 // run so I can stop it if that's what I want to do.
Greg Clayton5160ce52013-03-27 23:08:40 +00002931 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00002932 if (log)
2933 log->Printf("Hit New Thread Notification breakpoint.");
2934 return false;
2935}
2936
2937
2938bool
2939ProcessGDBRemote::StartNoticingNewThreads()
2940{
Greg Clayton5160ce52013-03-27 23:08:40 +00002941 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00002942 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00002943 {
Greg Clayton4116e932012-05-15 02:33:01 +00002944 if (log && log->GetVerbose())
2945 log->Printf("Enabled noticing new thread breakpoint.");
2946 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00002947 }
Greg Clayton4116e932012-05-15 02:33:01 +00002948 else
Jim Ingham1c823b42011-01-22 01:33:44 +00002949 {
Greg Clayton4116e932012-05-15 02:33:01 +00002950 PlatformSP platform_sp (m_target.GetPlatform());
2951 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00002952 {
Greg Clayton4116e932012-05-15 02:33:01 +00002953 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
2954 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00002955 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00002956 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00002957 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
2958 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00002959 }
2960 else
2961 {
2962 if (log)
2963 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00002964 }
2965 }
2966 }
Greg Clayton4116e932012-05-15 02:33:01 +00002967 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00002968}
2969
2970bool
2971ProcessGDBRemote::StopNoticingNewThreads()
2972{
Greg Clayton5160ce52013-03-27 23:08:40 +00002973 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00002974 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00002975 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00002976
2977 if (m_thread_create_bp_sp)
2978 m_thread_create_bp_sp->SetEnabled(false);
2979
Jim Ingham1c823b42011-01-22 01:33:44 +00002980 return true;
2981}
2982
Jason Molenda5e8534e2012-10-03 01:29:34 +00002983lldb_private::DynamicLoader *
2984ProcessGDBRemote::GetDynamicLoader ()
2985{
2986 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00002987 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00002988 return m_dyld_ap.get();
2989}
Jim Ingham1c823b42011-01-22 01:33:44 +00002990
Greg Clayton998255b2012-10-13 02:07:45 +00002991
Greg Clayton02686b82012-10-15 22:42:16 +00002992class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00002993{
2994private:
2995
2996public:
Greg Clayton02686b82012-10-15 22:42:16 +00002997 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00002998 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00002999 "process plugin packet history",
3000 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00003001 NULL)
3002 {
3003 }
3004
Greg Clayton02686b82012-10-15 22:42:16 +00003005 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton998255b2012-10-13 02:07:45 +00003006 {
3007 }
3008
3009 bool
3010 DoExecute (Args& command, CommandReturnObject &result)
3011 {
Greg Clayton02686b82012-10-15 22:42:16 +00003012 const size_t argc = command.GetArgumentCount();
3013 if (argc == 0)
3014 {
3015 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3016 if (process)
3017 {
3018 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
3019 result.SetStatus (eReturnStatusSuccessFinishResult);
3020 return true;
3021 }
3022 }
3023 else
3024 {
3025 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
3026 }
3027 result.SetStatus (eReturnStatusFailed);
3028 return false;
3029 }
3030};
3031
3032class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
3033{
3034private:
3035
3036public:
3037 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
3038 CommandObjectParsed (interpreter,
3039 "process plugin packet send",
3040 "Send a custom packet through the GDB remote protocol and print the answer. "
3041 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
3042 NULL)
3043 {
3044 }
3045
3046 ~CommandObjectProcessGDBRemotePacketSend ()
3047 {
3048 }
3049
3050 bool
3051 DoExecute (Args& command, CommandReturnObject &result)
3052 {
3053 const size_t argc = command.GetArgumentCount();
3054 if (argc == 0)
3055 {
3056 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
3057 result.SetStatus (eReturnStatusFailed);
3058 return false;
3059 }
3060
3061 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3062 if (process)
3063 {
Han Ming Ong84145852012-11-26 20:42:03 +00003064 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00003065 {
Han Ming Ong84145852012-11-26 20:42:03 +00003066 const char *packet_cstr = command.GetArgumentAtIndex(0);
3067 bool send_async = true;
3068 StringExtractorGDBRemote response;
3069 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3070 result.SetStatus (eReturnStatusSuccessFinishResult);
3071 Stream &output_strm = result.GetOutputStream();
3072 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00003073 std::string &response_str = response.GetStringRef();
3074
3075 if (strcmp(packet_cstr, "qGetProfileData") == 0)
3076 {
3077 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
3078 }
3079
Han Ming Ong84145852012-11-26 20:42:03 +00003080 if (response_str.empty())
3081 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3082 else
3083 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00003084 }
Greg Clayton02686b82012-10-15 22:42:16 +00003085 }
Greg Clayton998255b2012-10-13 02:07:45 +00003086 return true;
3087 }
3088};
3089
Greg Claytonba4a0a52013-02-01 23:03:47 +00003090class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
3091{
3092private:
3093
3094public:
3095 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
3096 CommandObjectRaw (interpreter,
3097 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00003098 "Send a qRcmd packet through the GDB remote protocol and print the response."
3099 "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 +00003100 NULL)
3101 {
3102 }
3103
3104 ~CommandObjectProcessGDBRemotePacketMonitor ()
3105 {
3106 }
3107
3108 bool
3109 DoExecute (const char *command, CommandReturnObject &result)
3110 {
3111 if (command == NULL || command[0] == '\0')
3112 {
3113 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
3114 result.SetStatus (eReturnStatusFailed);
3115 return false;
3116 }
3117
3118 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3119 if (process)
3120 {
3121 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00003122 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00003123 packet.PutBytesAsRawHex8(command, strlen(command));
3124 const char *packet_cstr = packet.GetString().c_str();
3125
3126 bool send_async = true;
3127 StringExtractorGDBRemote response;
3128 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3129 result.SetStatus (eReturnStatusSuccessFinishResult);
3130 Stream &output_strm = result.GetOutputStream();
3131 output_strm.Printf (" packet: %s\n", packet_cstr);
3132 const std::string &response_str = response.GetStringRef();
3133
3134 if (response_str.empty())
3135 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3136 else
3137 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
3138 }
3139 return true;
3140 }
3141};
3142
Greg Clayton02686b82012-10-15 22:42:16 +00003143class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
3144{
3145private:
3146
3147public:
3148 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
3149 CommandObjectMultiword (interpreter,
3150 "process plugin packet",
3151 "Commands that deal with GDB remote packets.",
3152 NULL)
3153 {
3154 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
3155 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00003156 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00003157 }
3158
3159 ~CommandObjectProcessGDBRemotePacket ()
3160 {
3161 }
3162};
Greg Clayton998255b2012-10-13 02:07:45 +00003163
3164class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
3165{
3166public:
3167 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
3168 CommandObjectMultiword (interpreter,
3169 "process plugin",
3170 "A set of commands for operating on a ProcessGDBRemote process.",
3171 "process plugin <subcommand> [<subcommand-options>]")
3172 {
3173 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
3174 }
3175
3176 ~CommandObjectMultiwordProcessGDBRemote ()
3177 {
3178 }
3179};
3180
Greg Clayton998255b2012-10-13 02:07:45 +00003181CommandObject *
3182ProcessGDBRemote::GetPluginCommandObject()
3183{
3184 if (!m_command_sp)
3185 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
3186 return m_command_sp.get();
3187}