blob: 0008dbfa2888ab03fdbd3b7828728286bd9b3f24 [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
119const char *
120ProcessGDBRemote::GetPluginNameStatic()
121{
Greg Claytonded470d2011-03-19 01:12:21 +0000122 return "gdb-remote";
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000123}
124
125const char *
126ProcessGDBRemote::GetPluginDescriptionStatic()
127{
128 return "GDB Remote protocol based debugging plug-in.";
129}
130
131void
132ProcessGDBRemote::Terminate()
133{
134 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
135}
136
137
Greg Claytonc3776bf2012-02-09 06:16:32 +0000138lldb::ProcessSP
139ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000140{
Greg Claytonc3776bf2012-02-09 06:16:32 +0000141 lldb::ProcessSP process_sp;
142 if (crash_file_path == NULL)
143 process_sp.reset (new ProcessGDBRemote (target, listener));
144 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000145}
146
147bool
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000148ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000149{
Greg Clayton596ed242011-10-21 21:41:45 +0000150 if (plugin_specified_by_name)
151 return true;
152
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000153 // For now we are just making sure the file exists for a given module
Greg Claytonaa149cb2011-08-11 02:48:45 +0000154 Module *exe_module = target.GetExecutableModulePointer();
155 if (exe_module)
Greg Claytonc3776bf2012-02-09 06:16:32 +0000156 {
157 ObjectFile *exe_objfile = exe_module->GetObjectFile();
158 // We can't debug core files...
159 switch (exe_objfile->GetType())
160 {
161 case ObjectFile::eTypeInvalid:
162 case ObjectFile::eTypeCoreFile:
163 case ObjectFile::eTypeDebugInfo:
164 case ObjectFile::eTypeObjectFile:
165 case ObjectFile::eTypeSharedLibrary:
166 case ObjectFile::eTypeStubLibrary:
167 return false;
168 case ObjectFile::eTypeExecutable:
169 case ObjectFile::eTypeDynamicLinker:
170 case ObjectFile::eTypeUnknown:
171 break;
172 }
Greg Claytonaa149cb2011-08-11 02:48:45 +0000173 return exe_module->GetFileSpec().Exists();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000174 }
Jim Ingham5aee1622010-08-09 23:31:02 +0000175 // However, if there is no executable module, we return true since we might be preparing to attach.
176 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000177}
178
179//----------------------------------------------------------------------
180// ProcessGDBRemote constructor
181//----------------------------------------------------------------------
182ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
183 Process (target, listener),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000184 m_flags (0),
Greg Clayton8b82f082011-04-12 05:54:46 +0000185 m_gdb_comm(false),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000186 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Claytonc982c762010-07-09 20:39:50 +0000187 m_last_stop_packet (),
Greg Clayton09c3e3d2011-12-06 04:51:14 +0000188 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000189 m_register_info (),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000190 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000191 m_async_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham455fa5c2012-11-01 01:15:33 +0000192 m_async_thread_state(eAsyncThreadNotStarted),
193 m_async_thread_state_mutex(Mutex::eMutexTypeRecursive),
Greg Clayton9e920902012-04-10 02:25:43 +0000194 m_thread_ids (),
Greg Clayton71fc2a32011-02-12 06:28:37 +0000195 m_continue_c_tids (),
196 m_continue_C_tids (),
197 m_continue_s_tids (),
198 m_continue_S_tids (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000199 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Claytonc982c762010-07-09 20:39:50 +0000200 m_max_memory_size (512),
Greg Clayton4116e932012-05-15 02:33:01 +0000201 m_addr_to_mmap_size (),
202 m_thread_create_bp_sp (),
Jim Ingham43c555d2012-07-04 00:35:43 +0000203 m_waiting_for_attach (false),
Jason Molenda5e8534e2012-10-03 01:29:34 +0000204 m_destroy_tried_resuming (false),
205 m_dyld_plugin_name(),
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//----------------------------------------------------------------------
236const char *
237ProcessGDBRemote::GetPluginName()
238{
239 return "Process debugging plug-in that uses the GDB remote protocol";
240}
241
242const char *
243ProcessGDBRemote::GetShortPluginName()
244{
245 return GetPluginNameStatic();
246}
247
248uint32_t
249ProcessGDBRemote::GetPluginVersion()
250{
251 return 1;
252}
253
254void
Greg Clayton513c26c2011-01-29 07:10:55 +0000255ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000256{
Greg Clayton513c26c2011-01-29 07:10:55 +0000257 if (!force && m_register_info.GetNumRegisters() > 0)
258 return;
259
260 char packet[128];
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000261 m_register_info.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000262 uint32_t reg_offset = 0;
263 uint32_t reg_num = 0;
Greg Clayton23f59502012-07-17 03:23:13 +0000264 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Greg Clayton576d8832011-03-22 04:00:09 +0000265 response_type == StringExtractorGDBRemote::eResponse;
266 ++reg_num)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000267 {
Greg Clayton513c26c2011-01-29 07:10:55 +0000268 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
269 assert (packet_len < sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000270 StringExtractorGDBRemote response;
Greg Claytonc574ede2011-03-10 02:26:48 +0000271 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000272 {
Greg Clayton576d8832011-03-22 04:00:09 +0000273 response_type = response.GetResponseType();
274 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000275 {
276 std::string name;
277 std::string value;
278 ConstString reg_name;
279 ConstString alt_name;
280 ConstString set_name;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000281 std::vector<uint32_t> value_regs;
282 std::vector<uint32_t> invalidate_regs;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000283 RegisterInfo reg_info = { NULL, // Name
284 NULL, // Alt name
285 0, // byte size
286 reg_offset, // offset
287 eEncodingUint, // encoding
288 eFormatHex, // formate
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000289 {
290 LLDB_INVALID_REGNUM, // GCC reg num
291 LLDB_INVALID_REGNUM, // DWARF reg num
292 LLDB_INVALID_REGNUM, // generic reg num
Jason Molendafbcb7f22010-09-10 07:49:16 +0000293 reg_num, // GDB reg num
294 reg_num // native register number
Greg Clayton435d85a2012-02-29 19:27:27 +0000295 },
296 NULL,
297 NULL
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000298 };
299
300 while (response.GetNameColonValue(name, value))
301 {
302 if (name.compare("name") == 0)
303 {
304 reg_name.SetCString(value.c_str());
305 }
306 else if (name.compare("alt-name") == 0)
307 {
308 alt_name.SetCString(value.c_str());
309 }
310 else if (name.compare("bitsize") == 0)
311 {
312 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
313 }
314 else if (name.compare("offset") == 0)
315 {
316 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda743e86a2010-06-11 23:44:18 +0000317 if (reg_offset != offset)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000318 {
319 reg_offset = offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000320 }
321 }
322 else if (name.compare("encoding") == 0)
323 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000324 const Encoding encoding = Args::StringToEncoding (value.c_str());
325 if (encoding != eEncodingInvalid)
326 reg_info.encoding = encoding;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000327 }
328 else if (name.compare("format") == 0)
329 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000330 Format format = eFormatInvalid;
331 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
332 reg_info.format = format;
333 else if (value.compare("binary") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000334 reg_info.format = eFormatBinary;
335 else if (value.compare("decimal") == 0)
336 reg_info.format = eFormatDecimal;
337 else if (value.compare("hex") == 0)
338 reg_info.format = eFormatHex;
339 else if (value.compare("float") == 0)
340 reg_info.format = eFormatFloat;
341 else if (value.compare("vector-sint8") == 0)
342 reg_info.format = eFormatVectorOfSInt8;
343 else if (value.compare("vector-uint8") == 0)
344 reg_info.format = eFormatVectorOfUInt8;
345 else if (value.compare("vector-sint16") == 0)
346 reg_info.format = eFormatVectorOfSInt16;
347 else if (value.compare("vector-uint16") == 0)
348 reg_info.format = eFormatVectorOfUInt16;
349 else if (value.compare("vector-sint32") == 0)
350 reg_info.format = eFormatVectorOfSInt32;
351 else if (value.compare("vector-uint32") == 0)
352 reg_info.format = eFormatVectorOfUInt32;
353 else if (value.compare("vector-float32") == 0)
354 reg_info.format = eFormatVectorOfFloat32;
355 else if (value.compare("vector-uint128") == 0)
356 reg_info.format = eFormatVectorOfUInt128;
357 }
358 else if (name.compare("set") == 0)
359 {
360 set_name.SetCString(value.c_str());
361 }
362 else if (name.compare("gcc") == 0)
363 {
364 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
365 }
366 else if (name.compare("dwarf") == 0)
367 {
368 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
369 }
370 else if (name.compare("generic") == 0)
371 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000372 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000373 }
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000374 else if (name.compare("container-regs") == 0)
375 {
376 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
377 value_pair.second = value;
378 do
379 {
380 value_pair = value_pair.second.split(',');
381 if (!value_pair.first.empty())
382 {
Greg Clayton0ba20242013-01-21 23:32:42 +0000383 uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
384 if (reg != LLDB_INVALID_REGNUM)
385 value_regs.push_back (reg);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000386 }
387 } while (!value_pair.second.empty());
388 }
389 else if (name.compare("invalidate-regs") == 0)
390 {
391 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
392 value_pair.second = value;
393 do
394 {
395 value_pair = value_pair.second.split(',');
396 if (!value_pair.first.empty())
397 {
Greg Clayton0ba20242013-01-21 23:32:42 +0000398 uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
399 if (reg != LLDB_INVALID_REGNUM)
400 invalidate_regs.push_back (reg);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000401 }
402 } while (!value_pair.second.empty());
403 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000404 }
405
Jason Molenda743e86a2010-06-11 23:44:18 +0000406 reg_info.byte_offset = reg_offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000407 assert (reg_info.byte_size != 0);
408 reg_offset += reg_info.byte_size;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000409 if (!value_regs.empty())
410 {
411 value_regs.push_back(LLDB_INVALID_REGNUM);
412 reg_info.value_regs = value_regs.data();
413 }
414 if (!invalidate_regs.empty())
415 {
416 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
417 reg_info.invalidate_regs = invalidate_regs.data();
418 }
419
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000420 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
421 }
422 }
423 else
424 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000425 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000426 }
427 }
428
Johnny Chen2fa9de12012-05-14 18:44:23 +0000429 // We didn't get anything if the accumulated reg_num is zero. See if we are
430 // debugging ARM and fill with a hard coded register set until we can get an
431 // updated debugserver down on the devices.
432 // On the other hand, if the accumulated reg_num is positive, see if we can
433 // add composite registers to the existing primordial ones.
434 bool from_scratch = (reg_num == 0);
435
436 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000437 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
438 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
439
440 // Use the process' architecture instead of the host arch, if available
441 ArchSpec remote_arch;
442 if (remote_process_arch.IsValid ())
443 remote_arch = remote_process_arch;
444 else
445 remote_arch = remote_host_arch;
446
Johnny Chen2fa9de12012-05-14 18:44:23 +0000447 if (!target_arch.IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000448 {
Johnny Chen2fa9de12012-05-14 18:44:23 +0000449 if (remote_arch.IsValid()
450 && remote_arch.GetMachine() == llvm::Triple::arm
451 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
452 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000453 }
Johnny Chen2fa9de12012-05-14 18:44:23 +0000454 else if (target_arch.GetMachine() == llvm::Triple::arm)
455 {
456 m_register_info.HardcodeARMRegisters(from_scratch);
457 }
458
459 // At this point, we can finalize our register info.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000460 m_register_info.Finalize ();
461}
462
463Error
464ProcessGDBRemote::WillLaunch (Module* module)
465{
466 return WillLaunchOrAttach ();
467}
468
469Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000470ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000471{
472 return WillLaunchOrAttach ();
473}
474
475Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000476ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000477{
478 return WillLaunchOrAttach ();
479}
480
481Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000482ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +0000483{
484 Error error (WillLaunchOrAttach ());
485
486 if (error.Fail())
487 return error;
488
Greg Clayton2289fa42011-04-30 01:09:13 +0000489 error = ConnectToDebugserver (remote_url);
Greg Claytonb766a732011-02-04 01:58:07 +0000490
491 if (error.Fail())
492 return error;
493 StartAsyncThread ();
494
Greg Claytonc574ede2011-03-10 02:26:48 +0000495 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonb766a732011-02-04 01:58:07 +0000496 if (pid == LLDB_INVALID_PROCESS_ID)
497 {
498 // We don't have a valid process ID, so note that we are connected
499 // and could now request to launch or attach, or get remote process
500 // listings...
501 SetPrivateState (eStateConnected);
502 }
503 else
504 {
505 // We have a valid process
506 SetID (pid);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000507 GetThreadList();
Greg Claytondd0e5a52011-06-02 22:22:38 +0000508 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytonb766a732011-02-04 01:58:07 +0000509 {
Greg Claytondd0e5a52011-06-02 22:22:38 +0000510 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytonb766a732011-02-04 01:58:07 +0000511 if (state == eStateStopped)
512 {
513 SetPrivateState (state);
514 }
515 else
Daniel Malead01b2952012-11-29 21:49:15 +0000516 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 +0000517 }
518 else
Daniel Malead01b2952012-11-29 21:49:15 +0000519 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 +0000520 }
Jason Molenda16d127c2012-05-03 22:37:30 +0000521
522 if (error.Success()
523 && !GetTarget().GetArchitecture().IsValid()
524 && m_gdb_comm.GetHostArchitecture().IsValid())
525 {
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000526 // Prefer the *process'* architecture over that of the *host*, if available.
527 if (m_gdb_comm.GetProcessArchitecture().IsValid())
528 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
529 else
530 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molenda16d127c2012-05-03 22:37:30 +0000531 }
532
Greg Claytonb766a732011-02-04 01:58:07 +0000533 return error;
534}
535
536Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000537ProcessGDBRemote::WillLaunchOrAttach ()
538{
539 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000540 m_stdio_communication.Clear ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000541 return error;
542}
543
544//----------------------------------------------------------------------
545// Process Control
546//----------------------------------------------------------------------
547Error
Greg Clayton982c9762011-11-03 21:22:33 +0000548ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000549{
Greg Clayton4957bf62010-09-30 21:49:03 +0000550 Error error;
Greg Clayton982c9762011-11-03 21:22:33 +0000551
552 uint32_t launch_flags = launch_info.GetFlags().Get();
553 const char *stdin_path = NULL;
554 const char *stdout_path = NULL;
555 const char *stderr_path = NULL;
556 const char *working_dir = launch_info.GetWorkingDirectory();
557
558 const ProcessLaunchInfo::FileAction *file_action;
559 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
560 if (file_action)
561 {
562 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
563 stdin_path = file_action->GetPath();
564 }
565 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
566 if (file_action)
567 {
568 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
569 stdout_path = file_action->GetPath();
570 }
571 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
572 if (file_action)
573 {
574 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
575 stderr_path = file_action->GetPath();
576 }
577
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000578 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
579 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
580 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton5160ce52013-03-27 23:08:40 +0000581 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000582
Greg Clayton982c9762011-11-03 21:22:33 +0000583 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000584 if (object_file)
585 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000586 char host_port[128];
587 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytonb766a732011-02-04 01:58:07 +0000588 char connect_url[128];
589 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000590
Greg Clayton71337622011-02-24 22:24:29 +0000591 // Make sure we aren't already connected?
592 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000593 {
Han Ming Ong84647042012-02-25 01:07:38 +0000594 error = StartDebugserverProcess (host_port, launch_info);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000595 if (error.Fail())
Greg Claytonc235ac72011-08-09 05:20:29 +0000596 {
Johnny Chen4c1e9202011-08-09 18:56:45 +0000597 if (log)
598 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000599 return error;
Greg Claytonc235ac72011-08-09 05:20:29 +0000600 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000601
Greg Claytonb766a732011-02-04 01:58:07 +0000602 error = ConnectToDebugserver (connect_url);
Greg Clayton71337622011-02-24 22:24:29 +0000603 }
604
605 if (error.Success())
606 {
607 lldb_utility::PseudoTerminal pty;
608 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000609
610 // If the debugserver is local and we aren't disabling STDIO, lets use
611 // a pseudo terminal to instead of relying on the 'O' packets for stdio
612 // since 'O' packets can really slow down debugging if the inferior
613 // does a lot of output.
Greg Claytonf58c2692011-06-24 22:32:10 +0000614 PlatformSP platform_sp (m_target.GetPlatform());
615 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Clayton71337622011-02-24 22:24:29 +0000616 {
617 const char *slave_name = NULL;
618 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000619 {
Greg Clayton71337622011-02-24 22:24:29 +0000620 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
621 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000622 }
Greg Clayton71337622011-02-24 22:24:29 +0000623 if (stdin_path == NULL)
624 stdin_path = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000625
Greg Clayton71337622011-02-24 22:24:29 +0000626 if (stdout_path == NULL)
627 stdout_path = slave_name;
628
629 if (stderr_path == NULL)
630 stderr_path = slave_name;
631 }
632
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000633 // Set STDIN to /dev/null if we want STDIO disabled or if either
634 // STDOUT or STDERR have been set to something and STDIN hasn't
635 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000636 stdin_path = "/dev/null";
637
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000638 // Set STDOUT to /dev/null if we want STDIO disabled or if either
639 // STDIN or STDERR have been set to something and STDOUT hasn't
640 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000641 stdout_path = "/dev/null";
642
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000643 // Set STDERR to /dev/null if we want STDIO disabled or if either
644 // STDIN or STDOUT have been set to something and STDERR hasn't
645 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000646 stderr_path = "/dev/null";
647
648 if (stdin_path)
649 m_gdb_comm.SetSTDIN (stdin_path);
650 if (stdout_path)
651 m_gdb_comm.SetSTDOUT (stdout_path);
652 if (stderr_path)
653 m_gdb_comm.SetSTDERR (stderr_path);
654
655 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
656
Greg Claytonc4103b32011-05-08 04:53:50 +0000657 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Clayton71337622011-02-24 22:24:29 +0000658
659 if (working_dir && working_dir[0])
660 {
661 m_gdb_comm.SetWorkingDir (working_dir);
662 }
663
664 // Send the environment and the program + arguments after we connect
Greg Clayton982c9762011-11-03 21:22:33 +0000665 const Args &environment = launch_info.GetEnvironmentEntries();
666 if (environment.GetArgumentCount())
Greg Clayton71337622011-02-24 22:24:29 +0000667 {
Greg Clayton982c9762011-11-03 21:22:33 +0000668 size_t num_environment_entries = environment.GetArgumentCount();
669 for (size_t i=0; i<num_environment_entries; ++i)
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000670 {
Greg Clayton982c9762011-11-03 21:22:33 +0000671 const char *env_entry = environment.GetArgumentAtIndex(i);
672 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Clayton71337622011-02-24 22:24:29 +0000673 break;
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000674 }
Greg Clayton71337622011-02-24 22:24:29 +0000675 }
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000676
Greg Claytonc574ede2011-03-10 02:26:48 +0000677 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Clayton982c9762011-11-03 21:22:33 +0000678 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info.GetArguments().GetConstArgumentVector());
Greg Clayton71337622011-02-24 22:24:29 +0000679 if (arg_packet_err == 0)
680 {
681 std::string error_str;
Greg Claytonc574ede2011-03-10 02:26:48 +0000682 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000683 {
Greg Claytonc574ede2011-03-10 02:26:48 +0000684 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000685 }
686 else
687 {
Greg Clayton71337622011-02-24 22:24:29 +0000688 error.SetErrorString (error_str.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000689 }
Greg Clayton71337622011-02-24 22:24:29 +0000690 }
691 else
692 {
Greg Clayton86edbf42011-10-26 00:56:27 +0000693 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Clayton71337622011-02-24 22:24:29 +0000694 }
Greg Clayton8b45bee2011-08-10 22:05:39 +0000695
696 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000697
Greg Clayton71337622011-02-24 22:24:29 +0000698 if (GetID() == LLDB_INVALID_PROCESS_ID)
699 {
Johnny Chen4c1e9202011-08-09 18:56:45 +0000700 if (log)
701 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton71337622011-02-24 22:24:29 +0000702 KillDebugserverProcess ();
703 return error;
704 }
705
Greg Claytondd0e5a52011-06-02 22:22:38 +0000706 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Clayton71337622011-02-24 22:24:29 +0000707 {
Greg Claytondd0e5a52011-06-02 22:22:38 +0000708 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Clayton71337622011-02-24 22:24:29 +0000709
710 if (!disable_stdio)
711 {
712 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Claytonee95ed52011-11-17 22:14:31 +0000713 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Clayton71337622011-02-24 22:24:29 +0000714 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000715 }
716 }
Greg Claytonc235ac72011-08-09 05:20:29 +0000717 else
718 {
Johnny Chen4c1e9202011-08-09 18:56:45 +0000719 if (log)
720 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytonc235ac72011-08-09 05:20:29 +0000721 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000722 }
723 else
724 {
725 // Set our user ID to an invalid process ID.
726 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton982c9762011-11-03 21:22:33 +0000727 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
728 exe_module->GetFileSpec().GetFilename().AsCString(),
729 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000730 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000731 return error;
Greg Clayton4957bf62010-09-30 21:49:03 +0000732
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000733}
734
735
736Error
Greg Claytonb766a732011-02-04 01:58:07 +0000737ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000738{
739 Error error;
740 // Sleep and wait a bit for debugserver to start to listen...
Greg Clayton7b0992d2013-04-18 22:45:39 +0000741 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000742 if (conn_ap.get())
743 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000744 const uint32_t max_retry_count = 50;
745 uint32_t retry_count = 0;
746 while (!m_gdb_comm.IsConnected())
747 {
Greg Claytonb766a732011-02-04 01:58:07 +0000748 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000749 {
750 m_gdb_comm.SetConnection (conn_ap.release());
751 break;
752 }
753 retry_count++;
754
755 if (retry_count >= max_retry_count)
756 break;
757
758 usleep (100000);
759 }
760 }
761
762 if (!m_gdb_comm.IsConnected())
763 {
764 if (error.Success())
765 error.SetErrorString("not connected to remote gdb server");
766 return error;
767 }
768
Greg Clayton32e0a752011-03-30 18:16:51 +0000769 // We always seem to be able to open a connection to a local port
770 // so we need to make sure we can then send data to it. If we can't
771 // then we aren't actually connected to anything, so try and do the
772 // handshake with the remote GDB server and make sure that goes
773 // alright.
774 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000775 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000776 m_gdb_comm.Disconnect();
777 if (error.Success())
778 error.SetErrorString("not connected to remote gdb server");
779 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000780 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000781 m_gdb_comm.ResetDiscoverableSettings();
782 m_gdb_comm.QueryNoAckModeSupported ();
783 m_gdb_comm.GetThreadSuffixSupported ();
Greg Clayton44633992012-04-10 03:22:03 +0000784 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +0000785 m_gdb_comm.GetHostInfo ();
786 m_gdb_comm.GetVContSupported ('c');
Jim Inghamcd16df92012-07-20 21:37:13 +0000787 m_gdb_comm.GetVAttachOrWaitSupported();
Jim Ingham03afad82012-07-02 05:40:07 +0000788
789 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
790 for (size_t idx = 0; idx < num_cmds; idx++)
791 {
792 StringExtractorGDBRemote response;
Jim Ingham03afad82012-07-02 05:40:07 +0000793 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
794 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000795 return error;
796}
797
798void
799ProcessGDBRemote::DidLaunchOrAttach ()
800{
Greg Clayton5160ce52013-03-27 23:08:40 +0000801 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +0000802 if (log)
803 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton93d3c8332011-02-16 04:46:07 +0000804 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000805 {
806 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
807
Greg Clayton513c26c2011-01-29 07:10:55 +0000808 BuildDynamicRegisterInfo (false);
Greg Clayton3af9ea52010-11-18 05:57:03 +0000809
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000810 // See if the GDB server supports the qHostInfo information
Greg Clayton0d0c12a2011-02-09 03:09:55 +0000811
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000812 ArchSpec gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
813
814 // See if the GDB server supports the qProcessInfo packet, if so
815 // prefer that over the Host information as it will be more specific
816 // to our process.
817
818 if (m_gdb_comm.GetProcessArchitecture().IsValid())
819 gdb_remote_arch = m_gdb_comm.GetProcessArchitecture();
820
Greg Claytond314e812011-03-23 00:09:55 +0000821 if (gdb_remote_arch.IsValid())
Greg Clayton0d0c12a2011-02-09 03:09:55 +0000822 {
Greg Claytond314e812011-03-23 00:09:55 +0000823 ArchSpec &target_arch = GetTarget().GetArchitecture();
824
825 if (target_arch.IsValid())
826 {
827 // If the remote host is ARM and we have apple as the vendor, then
828 // ARM executables and shared libraries can have mixed ARM architectures.
829 // You can have an armv6 executable, and if the host is armv7, then the
830 // system will load the best possible architecture for all shared libraries
831 // it has, so we really need to take the remote host architecture as our
832 // defacto architecture in this case.
833
834 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
835 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
836 {
837 target_arch = gdb_remote_arch;
838 }
839 else
840 {
841 // Fill in what is missing in the triple
842 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
843 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton70b57652011-05-15 01:25:55 +0000844 if (target_triple.getVendorName().size() == 0)
845 {
Greg Claytond314e812011-03-23 00:09:55 +0000846 target_triple.setVendor (remote_triple.getVendor());
847
Greg Clayton70b57652011-05-15 01:25:55 +0000848 if (target_triple.getOSName().size() == 0)
849 {
850 target_triple.setOS (remote_triple.getOS());
Greg Claytond314e812011-03-23 00:09:55 +0000851
Greg Clayton70b57652011-05-15 01:25:55 +0000852 if (target_triple.getEnvironmentName().size() == 0)
853 target_triple.setEnvironment (remote_triple.getEnvironment());
854 }
855 }
Greg Claytond314e812011-03-23 00:09:55 +0000856 }
857 }
858 else
859 {
860 // The target doesn't have a valid architecture yet, set it from
861 // the architecture we got from the remote GDB server
862 target_arch = gdb_remote_arch;
863 }
Greg Clayton0d0c12a2011-02-09 03:09:55 +0000864 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000865 }
866}
867
868void
869ProcessGDBRemote::DidLaunch ()
870{
871 DidLaunchOrAttach ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000872}
873
874Error
Greg Claytonc982c762010-07-09 20:39:50 +0000875ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000876{
Han Ming Ong84647042012-02-25 01:07:38 +0000877 ProcessAttachInfo attach_info;
878 return DoAttachToProcessWithID(attach_pid, attach_info);
879}
880
881Error
882ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
883{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000884 Error error;
885 // Clear out and clean up from any current state
886 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000887 if (attach_pid != LLDB_INVALID_PROCESS_ID)
888 {
Greg Clayton71337622011-02-24 22:24:29 +0000889 // Make sure we aren't already connected?
890 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000891 {
Greg Clayton71337622011-02-24 22:24:29 +0000892 char host_port[128];
893 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
894 char connect_url[128];
895 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000896
Han Ming Ong84647042012-02-25 01:07:38 +0000897 error = StartDebugserverProcess (host_port, attach_info);
Greg Clayton71337622011-02-24 22:24:29 +0000898
899 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000900 {
Greg Clayton71337622011-02-24 22:24:29 +0000901 const char *error_string = error.AsCString();
902 if (error_string == NULL)
903 error_string = "unable to launch " DEBUGSERVER_BASENAME;
904
905 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000906 }
Greg Clayton71337622011-02-24 22:24:29 +0000907 else
908 {
909 error = ConnectToDebugserver (connect_url);
910 }
911 }
912
913 if (error.Success())
914 {
915 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +0000916 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Greg Clayton3b608422011-11-19 02:11:30 +0000917 SetID (attach_pid);
Greg Clayton71337622011-02-24 22:24:29 +0000918 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000919 }
920 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000921 return error;
922}
923
924size_t
925ProcessGDBRemote::AttachInputReaderCallback
926(
927 void *baton,
928 InputReader *reader,
929 lldb::InputReaderAction notification,
930 const char *bytes,
931 size_t bytes_len
932)
933{
934 if (notification == eInputReaderGotToken)
935 {
936 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
937 if (gdb_process->m_waiting_for_attach)
938 gdb_process->m_waiting_for_attach = false;
939 reader->SetIsDone(true);
940 return 1;
941 }
942 return 0;
943}
944
945Error
Han Ming Ong84647042012-02-25 01:07:38 +0000946ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000947{
948 Error error;
949 // Clear out and clean up from any current state
950 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000951
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000952 if (process_name && process_name[0])
953 {
Greg Clayton71337622011-02-24 22:24:29 +0000954 // Make sure we aren't already connected?
955 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000956 {
Greg Clayton71337622011-02-24 22:24:29 +0000957 char host_port[128];
958 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
959 char connect_url[128];
960 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
961
Han Ming Ong84647042012-02-25 01:07:38 +0000962 error = StartDebugserverProcess (host_port, attach_info);
Greg Clayton71337622011-02-24 22:24:29 +0000963 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000964 {
Greg Clayton71337622011-02-24 22:24:29 +0000965 const char *error_string = error.AsCString();
966 if (error_string == NULL)
967 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000968
Greg Clayton71337622011-02-24 22:24:29 +0000969 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000970 }
Greg Clayton71337622011-02-24 22:24:29 +0000971 else
972 {
973 error = ConnectToDebugserver (connect_url);
974 }
975 }
976
977 if (error.Success())
978 {
979 StreamString packet;
980
981 if (wait_for_launch)
Jim Inghamcd16df92012-07-20 21:37:13 +0000982 {
983 if (!m_gdb_comm.GetVAttachOrWaitSupported())
984 {
985 packet.PutCString ("vAttachWait");
986 }
987 else
988 {
989 if (attach_info.GetIgnoreExisting())
990 packet.PutCString("vAttachWait");
991 else
992 packet.PutCString ("vAttachOrWait");
993 }
994 }
Greg Clayton71337622011-02-24 22:24:29 +0000995 else
996 packet.PutCString("vAttachName");
997 packet.PutChar(';');
998 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
999
1000 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1001
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001002 }
1003 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001004 return error;
1005}
1006
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001007
1008void
1009ProcessGDBRemote::DidAttach ()
1010{
Greg Claytonb766a732011-02-04 01:58:07 +00001011 DidLaunchOrAttach ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001012}
1013
Greg Clayton90ba8112012-12-05 00:16:59 +00001014void
1015ProcessGDBRemote::DoDidExec ()
1016{
1017 // The process exec'ed itself, figure out the dynamic loader, etc...
1018 BuildDynamicRegisterInfo (true);
1019 m_gdb_comm.ResetDiscoverableSettings();
1020 DidLaunchOrAttach ();
1021}
1022
1023
1024
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001025Error
1026ProcessGDBRemote::WillResume ()
1027{
Greg Clayton71fc2a32011-02-12 06:28:37 +00001028 m_continue_c_tids.clear();
1029 m_continue_C_tids.clear();
1030 m_continue_s_tids.clear();
1031 m_continue_S_tids.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001032 return Error();
1033}
1034
1035Error
1036ProcessGDBRemote::DoResume ()
1037{
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001038 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001039 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001040 if (log)
1041 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytone5219662010-12-03 06:02:24 +00001042
1043 Listener listener ("gdb-remote.resume-packet-sent");
1044 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1045 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00001046 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1047
Greg Claytond1d06e42013-04-20 00:27:58 +00001048 const size_t num_threads = GetThreadList().GetSize();
1049
Greg Clayton71fc2a32011-02-12 06:28:37 +00001050 StreamString continue_packet;
1051 bool continue_packet_error = false;
1052 if (m_gdb_comm.HasAnyVContSupport ())
1053 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001054 if (m_continue_c_tids.size() == num_threads)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001055 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001056 // All threads are continuing, just send a "c" packet
1057 continue_packet.PutCString ("c");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001058 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001059 else
1060 {
1061 continue_packet.PutCString ("vCont");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001062
Greg Claytond1d06e42013-04-20 00:27:58 +00001063 if (!m_continue_c_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001064 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001065 if (m_gdb_comm.GetVContSupported ('c'))
1066 {
1067 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)
1068 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1069 }
1070 else
1071 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001072 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001073
1074 if (!continue_packet_error && !m_continue_C_tids.empty())
1075 {
1076 if (m_gdb_comm.GetVContSupported ('C'))
1077 {
1078 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)
1079 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1080 }
1081 else
1082 continue_packet_error = true;
1083 }
Greg Claytone5219662010-12-03 06:02:24 +00001084
Greg Claytond1d06e42013-04-20 00:27:58 +00001085 if (!continue_packet_error && !m_continue_s_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001086 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001087 if (m_gdb_comm.GetVContSupported ('s'))
1088 {
1089 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)
1090 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1091 }
1092 else
1093 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001094 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001095
1096 if (!continue_packet_error && !m_continue_S_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001097 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001098 if (m_gdb_comm.GetVContSupported ('S'))
1099 {
1100 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)
1101 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1102 }
1103 else
1104 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001105 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001106
1107 if (continue_packet_error)
1108 continue_packet.GetString().clear();
Greg Clayton71fc2a32011-02-12 06:28:37 +00001109 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001110 }
1111 else
1112 continue_packet_error = true;
1113
1114 if (continue_packet_error)
1115 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001116 // Either no vCont support, or we tried to use part of the vCont
1117 // packet that wasn't supported by the remote GDB server.
1118 // We need to try and make a simple packet that can do our continue
Greg Clayton71fc2a32011-02-12 06:28:37 +00001119 const size_t num_continue_c_tids = m_continue_c_tids.size();
1120 const size_t num_continue_C_tids = m_continue_C_tids.size();
1121 const size_t num_continue_s_tids = m_continue_s_tids.size();
1122 const size_t num_continue_S_tids = m_continue_S_tids.size();
1123 if (num_continue_c_tids > 0)
1124 {
1125 if (num_continue_c_tids == num_threads)
1126 {
1127 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001128 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001129 continue_packet.PutChar ('c');
1130 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001131 }
1132 else if (num_continue_c_tids == 1 &&
1133 num_continue_C_tids == 0 &&
1134 num_continue_s_tids == 0 &&
1135 num_continue_S_tids == 0 )
1136 {
1137 // Only one thread is continuing
Greg Clayton8b82f082011-04-12 05:54:46 +00001138 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001139 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001140 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001141 }
1142 }
1143
Greg Clayton0c74e782011-06-24 03:21:43 +00001144 if (continue_packet_error && num_continue_C_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001145 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001146 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1147 num_continue_C_tids > 0 &&
1148 num_continue_s_tids == 0 &&
1149 num_continue_S_tids == 0 )
Greg Clayton71fc2a32011-02-12 06:28:37 +00001150 {
1151 const int continue_signo = m_continue_C_tids.front().second;
Greg Clayton0c74e782011-06-24 03:21:43 +00001152 // Only one thread is continuing
Greg Clayton71fc2a32011-02-12 06:28:37 +00001153 if (num_continue_C_tids > 1)
1154 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001155 // More that one thread with a signal, yet we don't have
1156 // vCont support and we are being asked to resume each
1157 // thread with a signal, we need to make sure they are
1158 // all the same signal, or we can't issue the continue
1159 // accurately with the current support...
1160 if (num_continue_C_tids > 1)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001161 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001162 continue_packet_error = false;
1163 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1164 {
1165 if (m_continue_C_tids[i].second != continue_signo)
1166 continue_packet_error = true;
1167 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001168 }
Greg Clayton0c74e782011-06-24 03:21:43 +00001169 if (!continue_packet_error)
1170 m_gdb_comm.SetCurrentThreadForRun (-1);
1171 }
1172 else
1173 {
1174 // Set the continue thread ID
1175 continue_packet_error = false;
1176 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001177 }
1178 if (!continue_packet_error)
1179 {
1180 // Add threads continuing with the same signo...
Greg Clayton71fc2a32011-02-12 06:28:37 +00001181 continue_packet.Printf("C%2.2x", continue_signo);
1182 }
1183 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001184 }
1185
Greg Clayton0c74e782011-06-24 03:21:43 +00001186 if (continue_packet_error && num_continue_s_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001187 {
1188 if (num_continue_s_tids == num_threads)
1189 {
1190 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001191 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001192 continue_packet.PutChar ('s');
1193 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001194 }
1195 else if (num_continue_c_tids == 0 &&
1196 num_continue_C_tids == 0 &&
1197 num_continue_s_tids == 1 &&
1198 num_continue_S_tids == 0 )
1199 {
1200 // Only one thread is stepping
Greg Clayton8b82f082011-04-12 05:54:46 +00001201 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001202 continue_packet.PutChar ('s');
Greg Clayton0c74e782011-06-24 03:21:43 +00001203 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001204 }
1205 }
1206
1207 if (!continue_packet_error && num_continue_S_tids > 0)
1208 {
1209 if (num_continue_S_tids == num_threads)
1210 {
1211 const int step_signo = m_continue_S_tids.front().second;
1212 // Are all threads trying to step with the same signal?
Greg Clayton0c74e782011-06-24 03:21:43 +00001213 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001214 if (num_continue_S_tids > 1)
1215 {
1216 for (size_t i=1; i<num_threads; ++i)
1217 {
1218 if (m_continue_S_tids[i].second != step_signo)
1219 continue_packet_error = true;
1220 }
1221 }
1222 if (!continue_packet_error)
1223 {
1224 // Add threads stepping with the same signo...
Greg Clayton8b82f082011-04-12 05:54:46 +00001225 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001226 continue_packet.Printf("S%2.2x", step_signo);
1227 }
1228 }
1229 else if (num_continue_c_tids == 0 &&
1230 num_continue_C_tids == 0 &&
1231 num_continue_s_tids == 0 &&
1232 num_continue_S_tids == 1 )
1233 {
1234 // Only one thread is stepping with signal
Greg Clayton8b82f082011-04-12 05:54:46 +00001235 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001236 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Clayton0c74e782011-06-24 03:21:43 +00001237 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001238 }
1239 }
1240 }
1241
1242 if (continue_packet_error)
1243 {
1244 error.SetErrorString ("can't make continue packet for this resume");
1245 }
1246 else
1247 {
1248 EventSP event_sp;
1249 TimeValue timeout;
1250 timeout = TimeValue::Now();
1251 timeout.OffsetWithSeconds (5);
Jim Inghamb1e2e842012-04-12 18:49:31 +00001252 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1253 {
1254 error.SetErrorString ("Trying to resume but the async thread is dead.");
1255 if (log)
1256 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1257 return error;
1258 }
1259
Greg Clayton71fc2a32011-02-12 06:28:37 +00001260 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1261
1262 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Inghamb1e2e842012-04-12 18:49:31 +00001263 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001264 error.SetErrorString("Resume timed out.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00001265 if (log)
1266 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1267 }
1268 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1269 {
1270 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1271 if (log)
1272 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1273 return error;
1274 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001275 }
Greg Claytone5219662010-12-03 06:02:24 +00001276 }
1277
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001278 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001279}
1280
Greg Clayton9e920902012-04-10 02:25:43 +00001281void
1282ProcessGDBRemote::ClearThreadIDList ()
1283{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001284 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001285 m_thread_ids.clear();
1286}
1287
1288bool
1289ProcessGDBRemote::UpdateThreadIDList ()
1290{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001291 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001292 bool sequence_mutex_unavailable = false;
1293 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1294 if (sequence_mutex_unavailable)
1295 {
Greg Clayton9e920902012-04-10 02:25:43 +00001296 return false; // We just didn't get the list
1297 }
1298 return true;
1299}
1300
Greg Clayton9fc13552012-04-10 00:18:59 +00001301bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001302ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001303{
1304 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +00001305 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Clayton73b472d2010-10-27 03:32:59 +00001306 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +00001307 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton9e920902012-04-10 02:25:43 +00001308
1309 size_t num_thread_ids = m_thread_ids.size();
1310 // The "m_thread_ids" thread ID list should always be updated after each stop
1311 // reply packet, but in case it isn't, update it here.
1312 if (num_thread_ids == 0)
1313 {
1314 if (!UpdateThreadIDList ())
1315 return false;
1316 num_thread_ids = m_thread_ids.size();
1317 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001318
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001319 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001320 if (num_thread_ids > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001321 {
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001322 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001323 {
Greg Clayton9e920902012-04-10 02:25:43 +00001324 tid_t tid = m_thread_ids[i];
Greg Clayton160c9d82013-05-01 21:54:04 +00001325 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001326 if (!thread_sp)
Jim Ingham4f465cf2012-10-10 18:32:14 +00001327 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001328 new_thread_list.AddThread(thread_sp);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001329 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001330 }
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001331
1332 // Whatever that is left in old_thread_list_copy are not
1333 // present in new_thread_list. Remove non-existent threads from internal id table.
1334 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1335 for (size_t i=0; i<old_num_thread_ids; i++)
1336 {
1337 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1338 if (old_thread_sp)
1339 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001340 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001341 m_thread_id_to_index_id_map.erase(old_thread_id);
1342 }
1343 }
1344
Greg Clayton9fc13552012-04-10 00:18:59 +00001345 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001346}
1347
1348
1349StateType
1350ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1351{
Greg Claytondd0e5a52011-06-02 22:22:38 +00001352 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001353 const char stop_type = stop_packet.GetChar();
1354 switch (stop_type)
1355 {
1356 case 'T':
1357 case 'S':
1358 {
Greg Claytone576ab22011-02-15 00:19:15 +00001359 if (GetStopID() == 0)
1360 {
1361 // Our first stop, make sure we have a process ID, and also make
1362 // sure we know about our registers
1363 if (GetID() == LLDB_INVALID_PROCESS_ID)
1364 {
Greg Claytonc574ede2011-03-10 02:26:48 +00001365 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00001366 if (pid != LLDB_INVALID_PROCESS_ID)
1367 SetID (pid);
1368 }
1369 BuildDynamicRegisterInfo (true);
1370 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001371 // Stop with signal and thread info
1372 const uint8_t signo = stop_packet.GetHexU8();
1373 std::string name;
1374 std::string value;
1375 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00001376 std::string reason;
1377 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001378 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00001379 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001380 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001381 ThreadSP thread_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001382 ThreadGDBRemote *gdb_thread = NULL;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001383
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001384 while (stop_packet.GetNameColonValue(name, value))
1385 {
1386 if (name.compare("metype") == 0)
1387 {
1388 // exception type in big endian hex
1389 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1390 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001391 else if (name.compare("medata") == 0)
1392 {
1393 // exception data in big endian hex
1394 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1395 }
1396 else if (name.compare("thread") == 0)
1397 {
1398 // thread in big endian hex
Greg Clayton9e920902012-04-10 02:25:43 +00001399 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001400 // m_thread_list_real does have its own mutex, but we need to
1401 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1402 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1403 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1404 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
Greg Clayton160c9d82013-05-01 21:54:04 +00001405
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001406 if (!thread_sp)
Greg Claytond1d06e42013-04-20 00:27:58 +00001407 {
Greg Claytone576ab22011-02-15 00:19:15 +00001408 // Create the thread if we need to
Jim Ingham4f465cf2012-10-10 18:32:14 +00001409 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001410 m_thread_list_real.AddThread(thread_sp);
Greg Claytone576ab22011-02-15 00:19:15 +00001411 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001412 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1413
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001414 }
Greg Clayton9e920902012-04-10 02:25:43 +00001415 else if (name.compare("threads") == 0)
1416 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001417 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001418 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00001419 // A comma separated list of all threads in the current
1420 // process that includes the thread for this stop reply
1421 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00001422 size_t comma_pos;
1423 lldb::tid_t tid;
1424 while ((comma_pos = value.find(',')) != std::string::npos)
1425 {
1426 value[comma_pos] = '\0';
1427 // thread in big endian hex
1428 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1429 if (tid != LLDB_INVALID_THREAD_ID)
1430 m_thread_ids.push_back (tid);
1431 value.erase(0, comma_pos + 1);
1432
1433 }
1434 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1435 if (tid != LLDB_INVALID_THREAD_ID)
1436 m_thread_ids.push_back (tid);
1437 }
Greg Claytonde9d0492011-01-08 03:17:57 +00001438 else if (name.compare("hexname") == 0)
1439 {
1440 StringExtractor name_extractor;
1441 // Swap "value" over into "name_extractor"
1442 name_extractor.GetStringRef().swap(value);
1443 // Now convert the HEX bytes into a string value
1444 name_extractor.GetHexByteString (value);
1445 thread_name.swap (value);
1446 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001447 else if (name.compare("name") == 0)
1448 {
1449 thread_name.swap (value);
1450 }
Greg Clayton6f35f5c2010-09-09 06:32:46 +00001451 else if (name.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001452 {
1453 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1454 }
Greg Claytona658fd22011-06-04 01:26:29 +00001455 else if (name.compare("reason") == 0)
1456 {
1457 reason.swap(value);
1458 }
1459 else if (name.compare("description") == 0)
1460 {
1461 StringExtractor desc_extractor;
1462 // Swap "value" over into "name_extractor"
1463 desc_extractor.GetStringRef().swap(value);
1464 // Now convert the HEX bytes into a string value
1465 desc_extractor.GetHexByteString (thread_name);
1466 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001467 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1468 {
1469 // We have a register number that contains an expedited
1470 // register value. Lets supply this register to our thread
1471 // so it won't have to go and read it.
Greg Clayton160c9d82013-05-01 21:54:04 +00001472 if (gdb_thread)
Greg Clayton3e06bd92011-01-09 21:07:35 +00001473 {
1474 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1475
1476 if (reg != UINT32_MAX)
1477 {
1478 StringExtractor reg_value_extractor;
1479 // Swap "value" over into "reg_value_extractor"
1480 reg_value_extractor.GetStringRef().swap(value);
Greg Clayton160c9d82013-05-01 21:54:04 +00001481 if (!gdb_thread->PrivateSetRegisterValue (reg, reg_value_extractor))
Greg Claytone576ab22011-02-15 00:19:15 +00001482 {
1483 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1484 name.c_str(),
1485 reg,
1486 reg,
1487 reg_value_extractor.GetStringRef().c_str(),
1488 stop_packet.GetStringRef().c_str());
1489 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001490 }
1491 }
1492 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001493 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001494
1495 if (thread_sp)
1496 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001497 // Clear the stop info just in case we don't set it to anything
1498 thread_sp->SetStopInfo (StopInfoSP());
1499
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001500 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Inghamdd2fe7a2011-01-28 02:23:12 +00001501 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001502 if (exc_type != 0)
1503 {
Greg Clayton1a65ae12011-01-25 23:55:37 +00001504 const size_t exc_data_size = exc_data.size();
Greg Claytonf4b47e12010-08-04 01:40:35 +00001505
Greg Clayton160c9d82013-05-01 21:54:04 +00001506 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1507 exc_type,
1508 exc_data_size,
1509 exc_data_size >= 1 ? exc_data[0] : 0,
1510 exc_data_size >= 2 ? exc_data[1] : 0,
1511 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001512 }
Greg Claytona658fd22011-06-04 01:26:29 +00001513 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001514 {
Greg Claytona658fd22011-06-04 01:26:29 +00001515 bool handled = false;
1516 if (!reason.empty())
1517 {
1518 if (reason.compare("trace") == 0)
1519 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001520 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Greg Claytona658fd22011-06-04 01:26:29 +00001521 handled = true;
1522 }
1523 else if (reason.compare("breakpoint") == 0)
1524 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001525 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1526 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Claytona658fd22011-06-04 01:26:29 +00001527 if (bp_site_sp)
1528 {
1529 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1530 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1531 // 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 +00001532 handled = true;
Greg Clayton160c9d82013-05-01 21:54:04 +00001533 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00001534 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001535 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00001536 }
1537 else
1538 {
1539 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001540 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00001541 }
1542 }
1543
Greg Claytona658fd22011-06-04 01:26:29 +00001544 }
1545 else if (reason.compare("trap") == 0)
1546 {
1547 // Let the trap just use the standard signal stop reason below...
1548 }
1549 else if (reason.compare("watchpoint") == 0)
1550 {
1551 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1552 // TODO: locate the watchpoint somehow...
Greg Clayton160c9d82013-05-01 21:54:04 +00001553 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
Greg Claytona658fd22011-06-04 01:26:29 +00001554 handled = true;
1555 }
1556 else if (reason.compare("exception") == 0)
1557 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001558 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00001559 handled = true;
1560 }
1561 }
1562
1563 if (signo)
1564 {
1565 if (signo == SIGTRAP)
1566 {
1567 // Currently we are going to assume SIGTRAP means we are either
1568 // hitting a breakpoint or hardware single stepping.
Jim Ingham54cc6e42012-07-11 21:41:19 +00001569 handled = true;
Greg Clayton160c9d82013-05-01 21:54:04 +00001570 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1571 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Jim Ingham54cc6e42012-07-11 21:41:19 +00001572
Greg Claytona658fd22011-06-04 01:26:29 +00001573 if (bp_site_sp)
1574 {
1575 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1576 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1577 // 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 +00001578 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00001579 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001580 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00001581 }
1582 else
1583 {
1584 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001585 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00001586 }
1587 }
Jim Ingham54cc6e42012-07-11 21:41:19 +00001588 else
Greg Claytona658fd22011-06-04 01:26:29 +00001589 {
Jim Ingham4dc613b2012-10-27 02:52:04 +00001590 // If we were stepping then assume the stop was the result of the trace. If we were
1591 // not stepping then report the SIGTRAP.
1592 // FIXME: We are still missing the case where we single step over a trap instruction.
Greg Clayton160c9d82013-05-01 21:54:04 +00001593 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1594 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Jim Ingham4dc613b2012-10-27 02:52:04 +00001595 else
Greg Clayton160c9d82013-05-01 21:54:04 +00001596 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo));
Greg Claytona658fd22011-06-04 01:26:29 +00001597 }
1598 }
1599 if (!handled)
Greg Clayton160c9d82013-05-01 21:54:04 +00001600 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Jason Molenda8214b012013-04-25 01:33:46 +00001601 }
Greg Claytona658fd22011-06-04 01:26:29 +00001602
1603 if (!description.empty())
1604 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001605 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
Greg Claytona658fd22011-06-04 01:26:29 +00001606 if (stop_info_sp)
1607 {
1608 stop_info_sp->SetDescription (description.c_str());
Greg Clayton3418c852011-08-10 02:10:13 +00001609 }
Greg Claytona658fd22011-06-04 01:26:29 +00001610 else
1611 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001612 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00001613 }
1614 }
1615 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001616 }
1617 return eStateStopped;
1618 }
1619 break;
1620
1621 case 'W':
1622 // process exited
1623 return eStateExited;
1624
1625 default:
1626 break;
1627 }
1628 return eStateInvalid;
1629}
1630
1631void
1632ProcessGDBRemote::RefreshStateAfterStop ()
1633{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001634 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001635 m_thread_ids.clear();
1636 // Set the thread stop info. It might have a "threads" key whose value is
1637 // a list of all thread IDs in the current process, so m_thread_ids might
1638 // get set.
1639 SetThreadStopInfo (m_last_stop_packet);
1640 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1641 if (m_thread_ids.empty())
1642 {
1643 // No, we need to fetch the thread list manually
1644 UpdateThreadIDList();
1645 }
1646
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001647 // Let all threads recover from stopping and do any clean up based
1648 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001649 m_thread_list_real.RefreshStateAfterStop();
Greg Clayton9e920902012-04-10 02:25:43 +00001650
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001651}
1652
1653Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001654ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001655{
1656 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001657
Greg Clayton6ed95942011-01-22 07:12:45 +00001658 bool timed_out = false;
1659 Mutex::Locker locker;
Greg Clayton513c26c2011-01-29 07:10:55 +00001660
1661 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00001662 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001663 // We are being asked to halt during an attach. We need to just close
1664 // our file handle and debugserver will go away, and we can be done...
1665 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00001666 }
Greg Clayton513c26c2011-01-29 07:10:55 +00001667 else
1668 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001669 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton513c26c2011-01-29 07:10:55 +00001670 {
1671 if (timed_out)
1672 error.SetErrorString("timed out sending interrupt packet");
1673 else
1674 error.SetErrorString("unknown error sending interrupt packet");
1675 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001676
1677 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton513c26c2011-01-29 07:10:55 +00001678 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001679 return error;
1680}
1681
1682Error
Jim Inghamacff8952013-05-02 00:27:30 +00001683ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00001684{
1685 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001686 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00001687 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00001688 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
1689
Greg Clayton594e5ed2010-09-27 21:07:38 +00001690 DisableAllBreakpointSites ();
1691
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001692 m_thread_list.DiscardThreadPlans();
Greg Clayton594e5ed2010-09-27 21:07:38 +00001693
Jim Inghamacff8952013-05-02 00:27:30 +00001694 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001695 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00001696 {
Jim Inghamacff8952013-05-02 00:27:30 +00001697 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001698 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1699 else
Jim Inghamacff8952013-05-02 00:27:30 +00001700 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00001701 }
Jim Inghamacff8952013-05-02 00:27:30 +00001702
1703 if (!error.Success())
1704 return error;
1705
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001706 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00001707 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001708
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001709 SetPrivateState (eStateDetached);
1710 ResumePrivateStateThread();
1711
1712 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00001713 return error;
1714}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001715
Jim Ingham43c555d2012-07-04 00:35:43 +00001716
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001717Error
1718ProcessGDBRemote::DoDestroy ()
1719{
1720 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001721 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001722 if (log)
1723 log->Printf ("ProcessGDBRemote::DoDestroy()");
1724
Jim Ingham43c555d2012-07-04 00:35:43 +00001725 // There is a bug in older iOS debugservers where they don't shut down the process
1726 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
1727 // this can cause problems with restarting. So we check to see if any of our threads are stopped
1728 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
1729 // destroy it again.
1730 //
1731 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
1732 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
1733 // the debugservers with this bug are equal. There really should be a better way to test this!
1734 //
1735 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
1736 // get called here to destroy again and we're still at a breakpoint or exception, then we should
1737 // just do the straight-forward kill.
1738 //
1739 // And of course, if we weren't able to stop the process by the time we get here, it isn't
1740 // necessary (or helpful) to do any of this.
1741
1742 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
1743 {
1744 PlatformSP platform_sp = GetTarget().GetPlatform();
1745
1746 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
1747 if (platform_sp
1748 && platform_sp->GetName()
1749 && strcmp (platform_sp->GetName(), PlatformRemoteiOS::GetShortPluginNameStatic()) == 0)
1750 {
1751 if (m_destroy_tried_resuming)
1752 {
1753 if (log)
1754 log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again.");
1755 }
1756 else
1757 {
1758 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
1759 // but we really need it to happen here and it doesn't matter if we do it twice.
1760 m_thread_list.DiscardThreadPlans();
1761 DisableAllBreakpointSites();
1762
1763 bool stop_looks_like_crash = false;
1764 ThreadList &threads = GetThreadList();
1765
1766 {
Jim Ingham45350372012-09-11 00:08:52 +00001767 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00001768
1769 size_t num_threads = threads.GetSize();
1770 for (size_t i = 0; i < num_threads; i++)
1771 {
1772 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00001773 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00001774 StopReason reason = eStopReasonInvalid;
1775 if (stop_info_sp)
1776 reason = stop_info_sp->GetStopReason();
1777 if (reason == eStopReasonBreakpoint
1778 || reason == eStopReasonException)
1779 {
1780 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00001781 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
1782 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00001783 stop_info_sp->GetDescription());
1784 stop_looks_like_crash = true;
1785 break;
1786 }
1787 }
1788 }
1789
1790 if (stop_looks_like_crash)
1791 {
1792 if (log)
1793 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
1794 m_destroy_tried_resuming = true;
1795
1796 // If we are going to run again before killing, it would be good to suspend all the threads
1797 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
1798 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
1799 // have to run the risk of letting those threads proceed a bit.
1800
1801 {
Jim Ingham45350372012-09-11 00:08:52 +00001802 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00001803
1804 size_t num_threads = threads.GetSize();
1805 for (size_t i = 0; i < num_threads; i++)
1806 {
1807 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00001808 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00001809 StopReason reason = eStopReasonInvalid;
1810 if (stop_info_sp)
1811 reason = stop_info_sp->GetStopReason();
1812 if (reason != eStopReasonBreakpoint
1813 && reason != eStopReasonException)
1814 {
1815 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00001816 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
1817 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00001818 thread_sp->SetResumeState(eStateSuspended);
1819 }
1820 }
1821 }
1822 Resume ();
1823 return Destroy();
1824 }
1825 }
1826 }
1827 }
1828
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001829 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00001830 int exit_status = SIGABRT;
1831 std::string exit_string;
1832
Greg Clayton6ed95942011-01-22 07:12:45 +00001833 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001834 {
Jim Inghamaab78372011-10-28 01:11:35 +00001835 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00001836 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001837
1838 StringExtractorGDBRemote response;
1839 bool send_async = true;
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00001840 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3);
1841
Greg Claytonc574ede2011-03-10 02:26:48 +00001842 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton513c26c2011-01-29 07:10:55 +00001843 {
1844 char packet_cmd = response.GetChar(0);
1845
1846 if (packet_cmd == 'W' || packet_cmd == 'X')
1847 {
Greg Clayton09c3e3d2011-12-06 04:51:14 +00001848 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00001849 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00001850 exit_status = response.GetHexU8();
1851 }
1852 else
1853 {
1854 if (log)
1855 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
1856 exit_string.assign("got unexpected response to k packet: ");
1857 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00001858 }
1859 }
1860 else
1861 {
Jim Inghambabfc382012-06-06 00:32:39 +00001862 if (log)
1863 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
1864 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00001865 }
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00001866
1867 m_gdb_comm.SetPacketTimeout(old_packet_timeout);
Greg Clayton6779606a2011-01-22 23:43:18 +00001868 }
Jim Inghambabfc382012-06-06 00:32:39 +00001869 else
1870 {
1871 if (log)
1872 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
Jim Inghamcfc09352012-07-27 23:57:19 +00001873 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00001874 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001875 }
Jim Inghambabfc382012-06-06 00:32:39 +00001876 else
1877 {
1878 // If we missed setting the exit status on the way out, do it here.
1879 // NB set exit status can be called multiple times, the first one sets the status.
1880 exit_string.assign("destroying when not connected to debugserver");
1881 }
1882
1883 SetExitStatus(exit_status, exit_string.c_str());
1884
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001885 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001886 KillDebugserverProcess ();
1887 return error;
1888}
1889
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001890//------------------------------------------------------------------
1891// Process Queries
1892//------------------------------------------------------------------
1893
1894bool
1895ProcessGDBRemote::IsAlive ()
1896{
Greg Clayton10177aa2010-12-08 05:08:21 +00001897 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001898}
1899
1900addr_t
1901ProcessGDBRemote::GetImageInfoAddress()
1902{
Jason Molenda6ba6d3d2013-01-30 04:39:32 +00001903 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001904}
1905
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001906//------------------------------------------------------------------
1907// Process Memory
1908//------------------------------------------------------------------
1909size_t
1910ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1911{
1912 if (size > m_max_memory_size)
1913 {
1914 // Keep memory read sizes down to a sane limit. This function will be
1915 // called multiple times in order to complete the task by
1916 // lldb_private::Process so it is ok to do this.
1917 size = m_max_memory_size;
1918 }
1919
1920 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001921 const int packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001922 assert (packet_len + 1 < sizeof(packet));
1923 StringExtractorGDBRemote response;
Greg Claytonc574ede2011-03-10 02:26:48 +00001924 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001925 {
Greg Clayton576d8832011-03-22 04:00:09 +00001926 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001927 {
1928 error.Clear();
1929 return response.GetHexBytes(buf, size, '\xdd');
1930 }
Greg Clayton576d8832011-03-22 04:00:09 +00001931 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00001932 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00001933 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00001934 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001935 else
Greg Clayton9944cd72012-09-19 01:46:31 +00001936 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001937 }
1938 else
1939 {
1940 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
1941 }
1942 return 0;
1943}
1944
1945size_t
1946ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1947{
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00001948 if (size > m_max_memory_size)
1949 {
1950 // Keep memory read sizes down to a sane limit. This function will be
1951 // called multiple times in order to complete the task by
1952 // lldb_private::Process so it is ok to do this.
1953 size = m_max_memory_size;
1954 }
1955
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001956 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00001957 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Clayton7fb56d02011-02-01 01:31:41 +00001958 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001959 StringExtractorGDBRemote response;
Greg Claytonc574ede2011-03-10 02:26:48 +00001960 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001961 {
Greg Clayton576d8832011-03-22 04:00:09 +00001962 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001963 {
1964 error.Clear();
1965 return size;
1966 }
Greg Clayton576d8832011-03-22 04:00:09 +00001967 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00001968 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00001969 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00001970 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001971 else
Greg Clayton9944cd72012-09-19 01:46:31 +00001972 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 +00001973 }
1974 else
1975 {
1976 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
1977 }
1978 return 0;
1979}
1980
1981lldb::addr_t
1982ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
1983{
Greg Clayton2a48f522011-05-14 01:50:35 +00001984 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
1985
Greg Clayton70b57652011-05-15 01:25:55 +00001986 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton2a48f522011-05-14 01:50:35 +00001987 switch (supported)
1988 {
1989 case eLazyBoolCalculate:
1990 case eLazyBoolYes:
1991 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
1992 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
1993 return allocated_addr;
1994
1995 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00001996 // Call mmap() to create memory in the inferior..
1997 unsigned prot = 0;
1998 if (permissions & lldb::ePermissionsReadable)
1999 prot |= eMmapProtRead;
2000 if (permissions & lldb::ePermissionsWritable)
2001 prot |= eMmapProtWrite;
2002 if (permissions & lldb::ePermissionsExecutable)
2003 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00002004
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002005 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2006 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2007 m_addr_to_mmap_size[allocated_addr] = size;
2008 else
2009 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton2a48f522011-05-14 01:50:35 +00002010 break;
2011 }
2012
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002013 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00002014 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002015 else
2016 error.Clear();
2017 return allocated_addr;
2018}
2019
2020Error
Greg Clayton46fb5582011-11-18 07:03:08 +00002021ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2022 MemoryRegionInfo &region_info)
2023{
2024
2025 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2026 return error;
2027}
2028
2029Error
Johnny Chen64637202012-05-23 21:09:52 +00002030ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2031{
2032
2033 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2034 return error;
2035}
2036
2037Error
Enrico Granataf04a2192012-07-13 23:18:48 +00002038ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2039{
2040 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2041 return error;
2042}
2043
2044Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002045ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2046{
2047 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00002048 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2049
2050 switch (supported)
2051 {
2052 case eLazyBoolCalculate:
2053 // We should never be deallocating memory without allocating memory
2054 // first so we should never get eLazyBoolCalculate
2055 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2056 break;
2057
2058 case eLazyBoolYes:
2059 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00002060 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002061 break;
2062
2063 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002064 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00002065 {
2066 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002067 if (pos != m_addr_to_mmap_size.end() &&
2068 InferiorCallMunmap(this, addr, pos->second))
2069 m_addr_to_mmap_size.erase (pos);
2070 else
Daniel Malead01b2952012-11-29 21:49:15 +00002071 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002072 }
2073 break;
2074 }
2075
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002076 return error;
2077}
2078
2079
2080//------------------------------------------------------------------
2081// Process STDIO
2082//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002083size_t
2084ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2085{
2086 if (m_stdio_communication.IsConnected())
2087 {
2088 ConnectionStatus status;
2089 m_stdio_communication.Write(src, src_len, status, NULL);
2090 }
2091 return 0;
2092}
2093
2094Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002095ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002096{
2097 Error error;
2098 assert (bp_site != NULL);
2099
Greg Clayton5160ce52013-03-27 23:08:40 +00002100 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002101 user_id_t site_id = bp_site->GetID();
2102 const addr_t addr = bp_site->GetLoadAddress();
2103 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002104 log->Printf ("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002105
2106 if (bp_site->IsEnabled())
2107 {
2108 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002109 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 +00002110 return error;
2111 }
2112 else
2113 {
2114 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2115
2116 if (bp_site->HardwarePreferred())
2117 {
2118 // Try and set hardware breakpoint, and if that fails, fall through
2119 // and set a software breakpoint?
Greg Clayton8b82f082011-04-12 05:54:46 +00002120 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002121 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002122 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002123 {
2124 bp_site->SetEnabled(true);
Greg Clayton8b82f082011-04-12 05:54:46 +00002125 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002126 return error;
2127 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002128 }
2129 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002130
2131 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002132 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002133 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
2134 {
2135 bp_site->SetEnabled(true);
2136 bp_site->SetType (BreakpointSite::eExternal);
2137 return error;
2138 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002139 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002140
2141 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002142 }
2143
2144 if (log)
2145 {
2146 const char *err_string = error.AsCString();
Jim Ingham299c0c12013-02-15 02:06:30 +00002147 log->Printf ("ProcessGDBRemote::EnableBreakpointSite () error for breakpoint at 0x%8.8" PRIx64 ": %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002148 bp_site->GetLoadAddress(),
2149 err_string ? err_string : "NULL");
2150 }
2151 // We shouldn't reach here on a successful breakpoint enable...
2152 if (error.Success())
2153 error.SetErrorToGenericError();
2154 return error;
2155}
2156
2157Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002158ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002159{
2160 Error error;
2161 assert (bp_site != NULL);
2162 addr_t addr = bp_site->GetLoadAddress();
2163 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00002164 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002165 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002166 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002167
2168 if (bp_site->IsEnabled())
2169 {
2170 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2171
Greg Clayton8b82f082011-04-12 05:54:46 +00002172 BreakpointSite::Type bp_type = bp_site->GetType();
2173 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002174 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002175 case BreakpointSite::eSoftware:
2176 error = DisableSoftwareBreakpoint (bp_site);
2177 break;
2178
2179 case BreakpointSite::eHardware:
2180 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2181 error.SetErrorToGenericError();
2182 break;
2183
2184 case BreakpointSite::eExternal:
2185 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2186 error.SetErrorToGenericError();
2187 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002188 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002189 if (error.Success())
2190 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002191 }
2192 else
2193 {
2194 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002195 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 +00002196 return error;
2197 }
2198
2199 if (error.Success())
2200 error.SetErrorToGenericError();
2201 return error;
2202}
2203
Johnny Chen11309a32011-09-06 22:38:36 +00002204// Pre-requisite: wp != NULL.
2205static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00002206GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00002207{
2208 assert(wp);
2209 bool watch_read = wp->WatchpointRead();
2210 bool watch_write = wp->WatchpointWrite();
2211
2212 // watch_read and watch_write cannot both be false.
2213 assert(watch_read || watch_write);
2214 if (watch_read && watch_write)
2215 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00002216 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00002217 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00002218 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00002219 return eWatchpointWrite;
2220}
2221
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002222Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002223ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002224{
2225 Error error;
2226 if (wp)
2227 {
2228 user_id_t watchID = wp->GetID();
2229 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00002230 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002231 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002232 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002233 if (wp->IsEnabled())
2234 {
2235 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002236 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 +00002237 return error;
2238 }
Johnny Chen11309a32011-09-06 22:38:36 +00002239
2240 GDBStoppointType type = GetGDBStoppointType(wp);
2241 // Pass down an appropriate z/Z packet...
2242 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002243 {
Johnny Chen11309a32011-09-06 22:38:36 +00002244 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2245 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002246 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002247 return error;
2248 }
2249 else
2250 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002251 }
Johnny Chen11309a32011-09-06 22:38:36 +00002252 else
2253 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002254 }
2255 else
2256 {
Johnny Chen01a67862011-10-14 00:42:25 +00002257 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002258 }
2259 if (error.Success())
2260 error.SetErrorToGenericError();
2261 return error;
2262}
2263
2264Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002265ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002266{
2267 Error error;
2268 if (wp)
2269 {
2270 user_id_t watchID = wp->GetID();
2271
Greg Clayton5160ce52013-03-27 23:08:40 +00002272 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002273
2274 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00002275
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002276 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002277 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002278
Johnny Chen11309a32011-09-06 22:38:36 +00002279 if (!wp->IsEnabled())
2280 {
2281 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002282 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 +00002283 // See also 'class WatchpointSentry' within StopInfo.cpp.
2284 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2285 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00002286 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002287 return error;
2288 }
2289
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002290 if (wp->IsHardware())
2291 {
Johnny Chen11309a32011-09-06 22:38:36 +00002292 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002293 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00002294 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2295 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002296 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002297 return error;
2298 }
2299 else
2300 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002301 }
2302 // TODO: clear software watchpoints if we implement them
2303 }
2304 else
2305 {
Johnny Chen01a67862011-10-14 00:42:25 +00002306 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002307 }
2308 if (error.Success())
2309 error.SetErrorToGenericError();
2310 return error;
2311}
2312
2313void
2314ProcessGDBRemote::Clear()
2315{
2316 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002317 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002318 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002319}
2320
2321Error
2322ProcessGDBRemote::DoSignal (int signo)
2323{
2324 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002325 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002326 if (log)
2327 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2328
2329 if (!m_gdb_comm.SendAsyncSignal (signo))
2330 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2331 return error;
2332}
2333
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002334Error
Han Ming Ong84647042012-02-25 01:07:38 +00002335ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)
2336{
2337 ProcessLaunchInfo launch_info;
2338 return StartDebugserverProcess(debugserver_url, launch_info);
2339}
2340
2341Error
2342ProcessGDBRemote::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 +00002343{
2344 Error error;
2345 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2346 {
2347 // If we locate debugserver, keep that located version around
2348 static FileSpec g_debugserver_file_spec;
2349
Han Ming Ong84647042012-02-25 01:07:38 +00002350 ProcessLaunchInfo debugserver_launch_info;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002351 char debugserver_path[PATH_MAX];
Han Ming Ong84647042012-02-25 01:07:38 +00002352 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002353
2354 // Always check to see if we have an environment override for the path
2355 // to the debugserver to use and use it if we do.
2356 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2357 if (env_debugserver_path)
Greg Clayton274060b2010-10-20 20:54:39 +00002358 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002359 else
2360 debugserver_file_spec = g_debugserver_file_spec;
2361 bool debugserver_exists = debugserver_file_spec.Exists();
2362 if (!debugserver_exists)
2363 {
2364 // The debugserver binary is in the LLDB.framework/Resources
2365 // directory.
Greg Claytondd36def2010-10-17 22:03:32 +00002366 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002367 {
Greg Claytondd36def2010-10-17 22:03:32 +00002368 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002369 debugserver_exists = debugserver_file_spec.Exists();
Greg Claytondd36def2010-10-17 22:03:32 +00002370 if (debugserver_exists)
2371 {
2372 g_debugserver_file_spec = debugserver_file_spec;
2373 }
2374 else
2375 {
2376 g_debugserver_file_spec.Clear();
2377 debugserver_file_spec.Clear();
2378 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002379 }
2380 }
2381
2382 if (debugserver_exists)
2383 {
2384 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2385
2386 m_stdio_communication.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002387
Greg Clayton5160ce52013-03-27 23:08:40 +00002388 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002389
Han Ming Ong84647042012-02-25 01:07:38 +00002390 Args &debugserver_args = debugserver_launch_info.GetArguments();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002391 char arg_cstr[PATH_MAX];
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002392
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002393 // Start args with "debugserver /file/path -r --"
2394 debugserver_args.AppendArgument(debugserver_path);
2395 debugserver_args.AppendArgument(debugserver_url);
Greg Claytondd36def2010-10-17 22:03:32 +00002396 // use native registers, not the GDB registers
2397 debugserver_args.AppendArgument("--native-regs");
2398 // make debugserver run in its own session so signals generated by
2399 // special terminal key sequences (^C) don't affect debugserver
2400 debugserver_args.AppendArgument("--setsid");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002401
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002402 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2403 if (env_debugserver_log_file)
2404 {
2405 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2406 debugserver_args.AppendArgument(arg_cstr);
2407 }
2408
2409 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2410 if (env_debugserver_log_flags)
2411 {
2412 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2413 debugserver_args.AppendArgument(arg_cstr);
2414 }
Jim Inghama0cc6b22012-10-03 22:31:30 +00002415// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
2416// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002417
Greg Clayton8b82f082011-04-12 05:54:46 +00002418 // We currently send down all arguments, attach pids, or attach
2419 // process names in dedicated GDB server packets, so we don't need
2420 // to pass them as arguments. This is currently because of all the
2421 // things we need to setup prior to launching: the environment,
2422 // current working dir, file actions, etc.
2423#if 0
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002424 // Now append the program arguments
Greg Clayton71337622011-02-24 22:24:29 +00002425 if (inferior_argv)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002426 {
Greg Clayton71337622011-02-24 22:24:29 +00002427 // Terminate the debugserver args so we can now append the inferior args
2428 debugserver_args.AppendArgument("--");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002429
Greg Clayton71337622011-02-24 22:24:29 +00002430 for (int i = 0; inferior_argv[i] != NULL; ++i)
2431 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002432 }
2433 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2434 {
2435 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2436 debugserver_args.AppendArgument (arg_cstr);
2437 }
2438 else if (attach_name && attach_name[0])
2439 {
2440 if (wait_for_launch)
2441 debugserver_args.AppendArgument ("--waitfor");
2442 else
2443 debugserver_args.AppendArgument ("--attach");
2444 debugserver_args.AppendArgument (attach_name);
2445 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002446#endif
Greg Clayton8b82f082011-04-12 05:54:46 +00002447
2448 ProcessLaunchInfo::FileAction file_action;
2449
2450 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2451 // to "/dev/null" if we run into any problems.
2452 file_action.Close (STDIN_FILENO);
Han Ming Ong84647042012-02-25 01:07:38 +00002453 debugserver_launch_info.AppendFileAction (file_action);
Greg Clayton8b82f082011-04-12 05:54:46 +00002454 file_action.Close (STDOUT_FILENO);
Han Ming Ong84647042012-02-25 01:07:38 +00002455 debugserver_launch_info.AppendFileAction (file_action);
Greg Clayton8b82f082011-04-12 05:54:46 +00002456 file_action.Close (STDERR_FILENO);
Han Ming Ong84647042012-02-25 01:07:38 +00002457 debugserver_launch_info.AppendFileAction (file_action);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002458
2459 if (log)
2460 {
2461 StreamString strm;
2462 debugserver_args.Dump (&strm);
2463 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2464 }
2465
Han Ming Ong84647042012-02-25 01:07:38 +00002466 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2467 debugserver_launch_info.SetUserID(process_info.GetUserID());
Greg Claytone4e45922011-11-16 05:37:56 +00002468
Han Ming Ong84647042012-02-25 01:07:38 +00002469 error = Host::LaunchProcess(debugserver_launch_info);
Greg Clayton0b42ac32010-07-02 01:29:13 +00002470
Greg Clayton8b82f082011-04-12 05:54:46 +00002471 if (error.Success ())
Han Ming Ong84647042012-02-25 01:07:38 +00002472 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Greg Clayton8b82f082011-04-12 05:54:46 +00002473 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002474 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2475
2476 if (error.Fail() || log)
Greg Clayton5160ce52013-03-27 23:08:40 +00002477 error.PutToLog(log, "Host::LaunchProcess (launch_info) => pid=%" PRIu64 ", path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002478 }
2479 else
2480 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002481 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002482 }
2483
2484 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2485 StartAsyncThread ();
2486 }
2487 return error;
2488}
2489
2490bool
2491ProcessGDBRemote::MonitorDebugserverProcess
2492(
2493 void *callback_baton,
2494 lldb::pid_t debugserver_pid,
Greg Claytone4e45922011-11-16 05:37:56 +00002495 bool exited, // True if the process did exit
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002496 int signo, // Zero for no signal
2497 int exit_status // Exit value of process if signal is zero
2498)
2499{
Greg Claytone4e45922011-11-16 05:37:56 +00002500 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2501 // and might not exist anymore, so we need to carefully try to get the
2502 // target for this process first since we have a race condition when
2503 // we are done running between getting the notice that the inferior
2504 // process has died and the debugserver that was debugging this process.
2505 // In our test suite, we are also continually running process after
2506 // process, so we must be very careful to make sure:
2507 // 1 - process object hasn't been deleted already
2508 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002509
2510 // "debugserver_pid" argument passed in is the process ID for
2511 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00002512 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002513
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002514 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton6779606a2011-01-22 23:43:18 +00002515
Greg Claytone4e45922011-11-16 05:37:56 +00002516 // Get a shared pointer to the target that has a matching process pointer.
2517 // This target could be gone, or the target could already have a new process
2518 // object inside of it
2519 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2520
Greg Clayton6779606a2011-01-22 23:43:18 +00002521 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002522 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 +00002523
Greg Claytone4e45922011-11-16 05:37:56 +00002524 if (target_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002525 {
Greg Claytone4e45922011-11-16 05:37:56 +00002526 // We found a process in a target that matches, but another thread
2527 // might be in the process of launching a new process that will
2528 // soon replace it, so get a shared pointer to the process so we
2529 // can keep it alive.
2530 ProcessSP process_sp (target_sp->GetProcessSP());
2531 // Now we have a shared pointer to the process that can't go away on us
2532 // so we now make sure it was the same as the one passed in, and also make
2533 // sure that our previous "process *" didn't get deleted and have a new
2534 // "process *" created in its place with the same pointer. To verify this
2535 // we make sure the process has our debugserver process ID. If we pass all
2536 // of these tests, then we are sure that this process is the one we were
2537 // looking for.
2538 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002539 {
Greg Claytone4e45922011-11-16 05:37:56 +00002540 // Sleep for a half a second to make sure our inferior process has
2541 // time to set its exit status before we set it incorrectly when
2542 // both the debugserver and the inferior process shut down.
2543 usleep (500000);
2544 // If our process hasn't yet exited, debugserver might have died.
2545 // If the process did exit, the we are reaping it.
2546 const StateType state = process->GetState();
2547
2548 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2549 state != eStateInvalid &&
2550 state != eStateUnloaded &&
2551 state != eStateExited &&
2552 state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002553 {
Greg Claytone4e45922011-11-16 05:37:56 +00002554 char error_str[1024];
2555 if (signo)
2556 {
2557 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2558 if (signal_cstr)
2559 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2560 else
2561 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2562 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002563 else
Greg Claytone4e45922011-11-16 05:37:56 +00002564 {
2565 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2566 }
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002567
Greg Claytone4e45922011-11-16 05:37:56 +00002568 process->SetExitStatus (-1, error_str);
2569 }
2570 // Debugserver has exited we need to let our ProcessGDBRemote
2571 // know that it no longer has a debugserver instance
2572 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002573 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002574 }
2575 return true;
2576}
2577
2578void
2579ProcessGDBRemote::KillDebugserverProcess ()
2580{
2581 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2582 {
2583 ::kill (m_debugserver_pid, SIGINT);
2584 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2585 }
2586}
2587
2588void
2589ProcessGDBRemote::Initialize()
2590{
2591 static bool g_initialized = false;
2592
2593 if (g_initialized == false)
2594 {
2595 g_initialized = true;
2596 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2597 GetPluginDescriptionStatic(),
2598 CreateInstance);
2599
2600 Log::Callbacks log_callbacks = {
2601 ProcessGDBRemoteLog::DisableLog,
2602 ProcessGDBRemoteLog::EnableLog,
2603 ProcessGDBRemoteLog::ListLogCategories
2604 };
2605
2606 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2607 }
2608}
2609
2610bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002611ProcessGDBRemote::StartAsyncThread ()
2612{
Greg Clayton5160ce52013-03-27 23:08:40 +00002613 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002614
2615 if (log)
2616 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Ingham455fa5c2012-11-01 01:15:33 +00002617
2618 Mutex::Locker start_locker(m_async_thread_state_mutex);
2619 if (m_async_thread_state == eAsyncThreadNotStarted)
2620 {
2621 // Create a thread that watches our internal state and controls which
2622 // events make it to clients (into the DCProcess event queue).
2623 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2624 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2625 {
2626 m_async_thread_state = eAsyncThreadRunning;
2627 return true;
2628 }
2629 else
2630 return false;
2631 }
2632 else
2633 {
2634 // Somebody tried to start the async thread while it was either being started or stopped. If the former, and
2635 // it started up successfully, then say all's well. Otherwise it is an error, since we aren't going to restart it.
2636 if (log)
2637 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
2638 if (m_async_thread_state == eAsyncThreadRunning)
2639 return true;
2640 else
2641 return false;
2642 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002643}
2644
2645void
2646ProcessGDBRemote::StopAsyncThread ()
2647{
Greg Clayton5160ce52013-03-27 23:08:40 +00002648 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002649
2650 if (log)
2651 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2652
Jim Ingham455fa5c2012-11-01 01:15:33 +00002653 Mutex::Locker start_locker(m_async_thread_state_mutex);
2654 if (m_async_thread_state == eAsyncThreadRunning)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002655 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00002656 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2657
2658 // This will shut down the async thread.
2659 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
2660
2661 // Stop the stdio thread
2662 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2663 {
2664 Host::ThreadJoin (m_async_thread, NULL, NULL);
2665 }
2666 m_async_thread_state = eAsyncThreadDone;
2667 }
2668 else
2669 {
2670 if (log)
2671 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002672 }
2673}
2674
2675
2676void *
2677ProcessGDBRemote::AsyncThread (void *arg)
2678{
2679 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2680
Greg Clayton5160ce52013-03-27 23:08:40 +00002681 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002682 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002683 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002684
2685 Listener listener ("ProcessGDBRemote::AsyncThread");
2686 EventSP event_sp;
2687 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2688 eBroadcastBitAsyncThreadShouldExit;
2689
2690 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2691 {
Greg Clayton71337622011-02-24 22:24:29 +00002692 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2693
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002694 bool done = false;
2695 while (!done)
2696 {
2697 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002698 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002699 if (listener.WaitForEvent (NULL, event_sp))
2700 {
2701 const uint32_t event_type = event_sp->GetType();
Greg Clayton71337622011-02-24 22:24:29 +00002702 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002703 {
Greg Clayton71337622011-02-24 22:24:29 +00002704 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002705 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 +00002706
Greg Clayton71337622011-02-24 22:24:29 +00002707 switch (event_type)
2708 {
2709 case eBroadcastBitAsyncContinue:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002710 {
Greg Clayton71337622011-02-24 22:24:29 +00002711 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002712
Greg Clayton71337622011-02-24 22:24:29 +00002713 if (continue_packet)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002714 {
Greg Clayton71337622011-02-24 22:24:29 +00002715 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2716 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2717 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002718 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002719
Greg Clayton71337622011-02-24 22:24:29 +00002720 if (::strstr (continue_cstr, "vAttach") == NULL)
2721 process->SetPrivateState(eStateRunning);
2722 StringExtractorGDBRemote response;
2723 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002724
Greg Clayton0772ded2012-05-16 02:48:06 +00002725 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
2726 // The thread ID list might be contained within the "response", or the stop reply packet that
2727 // caused the stop. So clear it now before we give the stop reply packet to the process
2728 // using the process->SetLastStopPacket()...
2729 process->ClearThreadIDList ();
2730
Greg Clayton71337622011-02-24 22:24:29 +00002731 switch (stop_state)
2732 {
2733 case eStateStopped:
2734 case eStateCrashed:
2735 case eStateSuspended:
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002736 process->SetLastStopPacket (response);
Greg Clayton71337622011-02-24 22:24:29 +00002737 process->SetPrivateState (stop_state);
2738 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002739
Greg Clayton71337622011-02-24 22:24:29 +00002740 case eStateExited:
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002741 process->SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002742 process->ClearThreadIDList();
Greg Clayton71337622011-02-24 22:24:29 +00002743 response.SetFilePos(1);
2744 process->SetExitStatus(response.GetHexU8(), NULL);
2745 done = true;
2746 break;
2747
2748 case eStateInvalid:
2749 process->SetExitStatus(-1, "lost connection");
2750 break;
2751
2752 default:
2753 process->SetPrivateState (stop_state);
2754 break;
2755 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002756 }
2757 }
Greg Clayton71337622011-02-24 22:24:29 +00002758 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002759
Greg Clayton71337622011-02-24 22:24:29 +00002760 case eBroadcastBitAsyncThreadShouldExit:
2761 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002762 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Clayton71337622011-02-24 22:24:29 +00002763 done = true;
2764 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002765
Greg Clayton71337622011-02-24 22:24:29 +00002766 default:
2767 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002768 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 +00002769 done = true;
2770 break;
2771 }
2772 }
2773 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2774 {
2775 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2776 {
2777 process->SetExitStatus (-1, "lost connection");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002778 done = true;
Greg Clayton71337622011-02-24 22:24:29 +00002779 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002780 }
2781 }
2782 else
2783 {
2784 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002785 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 +00002786 done = true;
2787 }
2788 }
2789 }
2790
2791 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002792 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002793
2794 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2795 return NULL;
2796}
2797
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002798const char *
2799ProcessGDBRemote::GetDispatchQueueNameForThread
2800(
2801 addr_t thread_dispatch_qaddr,
2802 std::string &dispatch_queue_name
2803)
2804{
2805 dispatch_queue_name.clear();
2806 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2807 {
2808 // Cache the dispatch_queue_offsets_addr value so we don't always have
2809 // to look it up
2810 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2811 {
Greg Clayton897f96a2010-10-12 17:33:06 +00002812 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2813 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Claytonb9a01b32012-02-26 05:51:37 +00002814 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false));
2815 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec));
Greg Clayton897f96a2010-10-12 17:33:06 +00002816 if (module_sp)
2817 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2818
2819 if (dispatch_queue_offsets_symbol == NULL)
2820 {
Greg Claytonb9a01b32012-02-26 05:51:37 +00002821 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false));
2822 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_module_spec);
Greg Clayton897f96a2010-10-12 17:33:06 +00002823 if (module_sp)
2824 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2825 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002826 if (dispatch_queue_offsets_symbol)
Greg Claytone7612132012-03-07 21:03:09 +00002827 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002828
2829 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2830 return NULL;
2831 }
2832
2833 uint8_t memory_buffer[8];
Greg Clayton514487e2011-02-15 21:59:32 +00002834 DataExtractor data (memory_buffer,
2835 sizeof(memory_buffer),
2836 m_target.GetArchitecture().GetByteOrder(),
2837 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002838
2839 // Excerpt from src/queue_private.h
2840 struct dispatch_queue_offsets_s
2841 {
2842 uint16_t dqo_version;
Jason Molendae424a9b2012-11-10 06:54:30 +00002843 uint16_t dqo_label; // in version 1-3, offset to string; in version 4+, offset to a pointer to a string
2844 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 +00002845 } dispatch_queue_offsets;
2846
2847
2848 Error error;
2849 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2850 {
Greg Claytonc7bece562013-01-25 18:06:21 +00002851 lldb::offset_t data_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002852 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2853 {
2854 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2855 {
2856 data_offset = 0;
2857 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
Jason Molendae424a9b2012-11-10 06:54:30 +00002858 if (dispatch_queue_offsets.dqo_version >= 4)
2859 {
2860 // libdispatch versions 4+, pointer to dispatch name is in the
2861 // queue structure.
2862 lldb::addr_t pointer_to_label_address = queue_addr + dispatch_queue_offsets.dqo_label;
2863 if (ReadMemory (pointer_to_label_address, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2864 {
2865 data_offset = 0;
2866 lldb::addr_t label_addr = data.GetAddress(&data_offset);
2867 ReadCStringFromMemory (label_addr, dispatch_queue_name, error);
2868 }
2869 }
2870 else
2871 {
2872 // libdispatch versions 1-3, dispatch name is a fixed width char array
2873 // in the queue structure.
2874 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2875 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2876 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2877 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2878 dispatch_queue_name.erase (bytes_read);
2879 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002880 }
2881 }
2882 }
2883 }
2884 if (dispatch_queue_name.empty())
2885 return NULL;
2886 return dispatch_queue_name.c_str();
2887}
2888
Greg Claytone996fd32011-03-08 22:40:15 +00002889//uint32_t
2890//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2891//{
2892// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2893// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2894// if (m_local_debugserver)
2895// {
2896// return Host::ListProcessesMatchingName (name, matches, pids);
2897// }
2898// else
2899// {
2900// // FIXME: Implement talking to the remote debugserver.
2901// return 0;
2902// }
2903//
2904//}
2905//
Jim Ingham1c823b42011-01-22 01:33:44 +00002906bool
2907ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2908 lldb_private::StoppointCallbackContext *context,
2909 lldb::user_id_t break_id,
2910 lldb::user_id_t break_loc_id)
2911{
2912 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2913 // run so I can stop it if that's what I want to do.
Greg Clayton5160ce52013-03-27 23:08:40 +00002914 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00002915 if (log)
2916 log->Printf("Hit New Thread Notification breakpoint.");
2917 return false;
2918}
2919
2920
2921bool
2922ProcessGDBRemote::StartNoticingNewThreads()
2923{
Greg Clayton5160ce52013-03-27 23:08:40 +00002924 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00002925 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00002926 {
Greg Clayton4116e932012-05-15 02:33:01 +00002927 if (log && log->GetVerbose())
2928 log->Printf("Enabled noticing new thread breakpoint.");
2929 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00002930 }
Greg Clayton4116e932012-05-15 02:33:01 +00002931 else
Jim Ingham1c823b42011-01-22 01:33:44 +00002932 {
Greg Clayton4116e932012-05-15 02:33:01 +00002933 PlatformSP platform_sp (m_target.GetPlatform());
2934 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00002935 {
Greg Clayton4116e932012-05-15 02:33:01 +00002936 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
2937 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00002938 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00002939 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00002940 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
2941 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00002942 }
2943 else
2944 {
2945 if (log)
2946 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00002947 }
2948 }
2949 }
Greg Clayton4116e932012-05-15 02:33:01 +00002950 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00002951}
2952
2953bool
2954ProcessGDBRemote::StopNoticingNewThreads()
2955{
Greg Clayton5160ce52013-03-27 23:08:40 +00002956 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00002957 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00002958 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00002959
2960 if (m_thread_create_bp_sp)
2961 m_thread_create_bp_sp->SetEnabled(false);
2962
Jim Ingham1c823b42011-01-22 01:33:44 +00002963 return true;
2964}
2965
Jason Molenda5e8534e2012-10-03 01:29:34 +00002966lldb_private::DynamicLoader *
2967ProcessGDBRemote::GetDynamicLoader ()
2968{
2969 if (m_dyld_ap.get() == NULL)
2970 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, m_dyld_plugin_name.empty() ? NULL : m_dyld_plugin_name.c_str()));
2971 return m_dyld_ap.get();
2972}
Jim Ingham1c823b42011-01-22 01:33:44 +00002973
Greg Clayton998255b2012-10-13 02:07:45 +00002974
Greg Clayton02686b82012-10-15 22:42:16 +00002975class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00002976{
2977private:
2978
2979public:
Greg Clayton02686b82012-10-15 22:42:16 +00002980 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00002981 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00002982 "process plugin packet history",
2983 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00002984 NULL)
2985 {
2986 }
2987
Greg Clayton02686b82012-10-15 22:42:16 +00002988 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton998255b2012-10-13 02:07:45 +00002989 {
2990 }
2991
2992 bool
2993 DoExecute (Args& command, CommandReturnObject &result)
2994 {
Greg Clayton02686b82012-10-15 22:42:16 +00002995 const size_t argc = command.GetArgumentCount();
2996 if (argc == 0)
2997 {
2998 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
2999 if (process)
3000 {
3001 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
3002 result.SetStatus (eReturnStatusSuccessFinishResult);
3003 return true;
3004 }
3005 }
3006 else
3007 {
3008 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
3009 }
3010 result.SetStatus (eReturnStatusFailed);
3011 return false;
3012 }
3013};
3014
3015class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
3016{
3017private:
3018
3019public:
3020 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
3021 CommandObjectParsed (interpreter,
3022 "process plugin packet send",
3023 "Send a custom packet through the GDB remote protocol and print the answer. "
3024 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
3025 NULL)
3026 {
3027 }
3028
3029 ~CommandObjectProcessGDBRemotePacketSend ()
3030 {
3031 }
3032
3033 bool
3034 DoExecute (Args& command, CommandReturnObject &result)
3035 {
3036 const size_t argc = command.GetArgumentCount();
3037 if (argc == 0)
3038 {
3039 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
3040 result.SetStatus (eReturnStatusFailed);
3041 return false;
3042 }
3043
3044 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3045 if (process)
3046 {
Han Ming Ong84145852012-11-26 20:42:03 +00003047 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00003048 {
Han Ming Ong84145852012-11-26 20:42:03 +00003049 const char *packet_cstr = command.GetArgumentAtIndex(0);
3050 bool send_async = true;
3051 StringExtractorGDBRemote response;
3052 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3053 result.SetStatus (eReturnStatusSuccessFinishResult);
3054 Stream &output_strm = result.GetOutputStream();
3055 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00003056 std::string &response_str = response.GetStringRef();
3057
3058 if (strcmp(packet_cstr, "qGetProfileData") == 0)
3059 {
3060 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
3061 }
3062
Han Ming Ong84145852012-11-26 20:42:03 +00003063 if (response_str.empty())
3064 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3065 else
3066 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00003067 }
Greg Clayton02686b82012-10-15 22:42:16 +00003068 }
Greg Clayton998255b2012-10-13 02:07:45 +00003069 return true;
3070 }
3071};
3072
Greg Claytonba4a0a52013-02-01 23:03:47 +00003073class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
3074{
3075private:
3076
3077public:
3078 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
3079 CommandObjectRaw (interpreter,
3080 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00003081 "Send a qRcmd packet through the GDB remote protocol and print the response."
3082 "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 +00003083 NULL)
3084 {
3085 }
3086
3087 ~CommandObjectProcessGDBRemotePacketMonitor ()
3088 {
3089 }
3090
3091 bool
3092 DoExecute (const char *command, CommandReturnObject &result)
3093 {
3094 if (command == NULL || command[0] == '\0')
3095 {
3096 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
3097 result.SetStatus (eReturnStatusFailed);
3098 return false;
3099 }
3100
3101 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3102 if (process)
3103 {
3104 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00003105 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00003106 packet.PutBytesAsRawHex8(command, strlen(command));
3107 const char *packet_cstr = packet.GetString().c_str();
3108
3109 bool send_async = true;
3110 StringExtractorGDBRemote response;
3111 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3112 result.SetStatus (eReturnStatusSuccessFinishResult);
3113 Stream &output_strm = result.GetOutputStream();
3114 output_strm.Printf (" packet: %s\n", packet_cstr);
3115 const std::string &response_str = response.GetStringRef();
3116
3117 if (response_str.empty())
3118 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3119 else
3120 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
3121 }
3122 return true;
3123 }
3124};
3125
Greg Clayton02686b82012-10-15 22:42:16 +00003126class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
3127{
3128private:
3129
3130public:
3131 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
3132 CommandObjectMultiword (interpreter,
3133 "process plugin packet",
3134 "Commands that deal with GDB remote packets.",
3135 NULL)
3136 {
3137 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
3138 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00003139 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00003140 }
3141
3142 ~CommandObjectProcessGDBRemotePacket ()
3143 {
3144 }
3145};
Greg Clayton998255b2012-10-13 02:07:45 +00003146
3147class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
3148{
3149public:
3150 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
3151 CommandObjectMultiword (interpreter,
3152 "process plugin",
3153 "A set of commands for operating on a ProcessGDBRemote process.",
3154 "process plugin <subcommand> [<subcommand-options>]")
3155 {
3156 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
3157 }
3158
3159 ~CommandObjectMultiwordProcessGDBRemote ()
3160 {
3161 }
3162};
3163
Greg Clayton998255b2012-10-13 02:07:45 +00003164CommandObject *
3165ProcessGDBRemote::GetPluginCommandObject()
3166{
3167 if (!m_command_sp)
3168 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
3169 return m_command_sp.get();
3170}