blob: a0658ab4f5b03833bc27d22a5883419e333b4da7 [file] [log] [blame]
Chris Lattner24943d22010-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
10// C Includes
11#include <errno.h>
Chris Lattner24943d22010-06-08 16:52:24 +000012#include <spawn.h>
Stephen Wilson50daf772011-03-25 18:16:28 +000013#include <stdlib.h>
Sean Callanan483d00a2012-07-19 18:07:36 +000014#include <netinet/in.h>
Greg Clayton989816b2011-05-14 01:50:35 +000015#include <sys/mman.h> // for mmap
Chris Lattner24943d22010-06-08 16:52:24 +000016#include <sys/stat.h>
Greg Clayton989816b2011-05-14 01:50:35 +000017#include <sys/types.h>
Stephen Wilson60f19d52011-03-30 00:12:40 +000018#include <time.h>
Chris Lattner24943d22010-06-08 16:52:24 +000019
20// C++ Includes
21#include <algorithm>
22#include <map>
23
24// Other libraries and framework includes
25
Johnny Chenecd4feb2011-10-14 00:42:25 +000026#include "lldb/Breakpoint/Watchpoint.h"
Jim Ingham84cdc152010-06-15 19:49:27 +000027#include "lldb/Interpreter/Args.h"
Chris Lattner24943d22010-06-08 16:52:24 +000028#include "lldb/Core/ArchSpec.h"
29#include "lldb/Core/Debugger.h"
30#include "lldb/Core/ConnectionFileDescriptor.h"
Greg Clayton5f54ac32011-02-08 05:05:52 +000031#include "lldb/Host/FileSpec.h"
Chris Lattner24943d22010-06-08 16:52:24 +000032#include "lldb/Core/InputReader.h"
33#include "lldb/Core/Module.h"
Greg Clayton49ce8962012-08-29 21:13:06 +000034#include "lldb/Core/ModuleSpec.h"
Chris Lattner24943d22010-06-08 16:52:24 +000035#include "lldb/Core/PluginManager.h"
36#include "lldb/Core/State.h"
Greg Clayton33559462012-04-13 21:24:18 +000037#include "lldb/Core/StreamFile.h"
Chris Lattner24943d22010-06-08 16:52:24 +000038#include "lldb/Core/StreamString.h"
39#include "lldb/Core/Timer.h"
Greg Clayton2f085c62011-05-15 01:25:55 +000040#include "lldb/Core/Value.h"
Jason Molendab0e3c7c2012-09-29 08:03:33 +000041#include "lldb/Host/Symbols.h"
Chris Lattner24943d22010-06-08 16:52:24 +000042#include "lldb/Host/TimeValue.h"
43#include "lldb/Symbol/ObjectFile.h"
44#include "lldb/Target/DynamicLoader.h"
45#include "lldb/Target/Target.h"
46#include "lldb/Target/TargetList.h"
Greg Clayton989816b2011-05-14 01:50:35 +000047#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molendadea5ea72010-06-09 21:28:42 +000048#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner24943d22010-06-08 16:52:24 +000049
50// Project includes
51#include "lldb/Host/Host.h"
Peter Collingbourne4d623e82011-06-03 20:40:38 +000052#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Jason Molenda3aeb2862012-07-25 03:40:06 +000053#include "Plugins/Process/Utility/StopInfoMachException.h"
Jim Ingham06b84492012-07-04 00:35:43 +000054#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
Greg Clayton54e7afa2010-07-09 20:39:50 +000055#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner24943d22010-06-08 16:52:24 +000056#include "GDBRemoteRegisterContext.h"
57#include "ProcessGDBRemote.h"
58#include "ProcessGDBRemoteLog.h"
59#include "ThreadGDBRemote.h"
Greg Clayton643ee732010-08-04 01:40:35 +000060
Jason Molendab46937c2012-10-03 01:29:34 +000061#include "Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.h"
62
Greg Clayton451fa822012-04-09 22:46:21 +000063namespace lldb
64{
65 // Provide a function that can easily dump the packet history if we know a
66 // ProcessGDBRemote * value (which we can get from logs or from debugging).
67 // We need the function in the lldb namespace so it makes it into the final
68 // executable since the LLDB shared library only exports stuff in the lldb
69 // namespace. This allows you to attach with a debugger and call this
70 // function and get the packet history dumped to a file.
71 void
72 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
73 {
Greg Clayton33559462012-04-13 21:24:18 +000074 lldb_private::StreamFile strm;
75 lldb_private::Error error (strm.GetFile().Open(path, lldb_private::File::eOpenOptionWrite | lldb_private::File::eOpenOptionCanCreate));
76 if (error.Success())
77 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
Greg Clayton451fa822012-04-09 22:46:21 +000078 }
Filipe Cabecinhas021086a2012-05-23 16:27:09 +000079}
Chris Lattner24943d22010-06-08 16:52:24 +000080
Chris Lattner24943d22010-06-08 16:52:24 +000081
82#define DEBUGSERVER_BASENAME "debugserver"
83using namespace lldb;
84using namespace lldb_private;
85
Jim Inghamf9600482011-03-29 21:45:47 +000086static bool rand_initialized = false;
87
Sean Callanan483d00a2012-07-19 18:07:36 +000088// TODO Randomly assigning a port is unsafe. We should get an unused
89// ephemeral port from the kernel and make sure we reserve it before passing
90// it to debugserver.
91
92#if defined (__APPLE__)
93#define LOW_PORT (IPPORT_RESERVED)
94#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
95#else
96#define LOW_PORT (1024u)
97#define HIGH_PORT (49151u)
98#endif
99
Chris Lattner24943d22010-06-08 16:52:24 +0000100static inline uint16_t
101get_random_port ()
102{
Jim Inghamf9600482011-03-29 21:45:47 +0000103 if (!rand_initialized)
104 {
Stephen Wilson60f19d52011-03-30 00:12:40 +0000105 time_t seed = time(NULL);
106
Jim Inghamf9600482011-03-29 21:45:47 +0000107 rand_initialized = true;
Stephen Wilson60f19d52011-03-30 00:12:40 +0000108 srand(seed);
Jim Inghamf9600482011-03-29 21:45:47 +0000109 }
Sean Callanan483d00a2012-07-19 18:07:36 +0000110 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
Chris Lattner24943d22010-06-08 16:52:24 +0000111}
112
113
114const char *
115ProcessGDBRemote::GetPluginNameStatic()
116{
Greg Claytonb1888f22011-03-19 01:12:21 +0000117 return "gdb-remote";
Chris Lattner24943d22010-06-08 16:52:24 +0000118}
119
120const char *
121ProcessGDBRemote::GetPluginDescriptionStatic()
122{
123 return "GDB Remote protocol based debugging plug-in.";
124}
125
126void
127ProcessGDBRemote::Terminate()
128{
129 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
130}
131
132
Greg Clayton46c9a352012-02-09 06:16:32 +0000133lldb::ProcessSP
134ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner24943d22010-06-08 16:52:24 +0000135{
Greg Clayton46c9a352012-02-09 06:16:32 +0000136 lldb::ProcessSP process_sp;
137 if (crash_file_path == NULL)
138 process_sp.reset (new ProcessGDBRemote (target, listener));
139 return process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000140}
141
142bool
Greg Clayton8d2ea282011-07-17 20:36:25 +0000143ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
Chris Lattner24943d22010-06-08 16:52:24 +0000144{
Greg Clayton61ddf562011-10-21 21:41:45 +0000145 if (plugin_specified_by_name)
146 return true;
147
Chris Lattner24943d22010-06-08 16:52:24 +0000148 // For now we are just making sure the file exists for a given module
Greg Clayton5beb99d2011-08-11 02:48:45 +0000149 Module *exe_module = target.GetExecutableModulePointer();
150 if (exe_module)
Greg Clayton46c9a352012-02-09 06:16:32 +0000151 {
152 ObjectFile *exe_objfile = exe_module->GetObjectFile();
153 // We can't debug core files...
154 switch (exe_objfile->GetType())
155 {
156 case ObjectFile::eTypeInvalid:
157 case ObjectFile::eTypeCoreFile:
158 case ObjectFile::eTypeDebugInfo:
159 case ObjectFile::eTypeObjectFile:
160 case ObjectFile::eTypeSharedLibrary:
161 case ObjectFile::eTypeStubLibrary:
162 return false;
163 case ObjectFile::eTypeExecutable:
164 case ObjectFile::eTypeDynamicLinker:
165 case ObjectFile::eTypeUnknown:
166 break;
167 }
Greg Clayton5beb99d2011-08-11 02:48:45 +0000168 return exe_module->GetFileSpec().Exists();
Greg Clayton46c9a352012-02-09 06:16:32 +0000169 }
Jim Ingham7508e732010-08-09 23:31:02 +0000170 // However, if there is no executable module, we return true since we might be preparing to attach.
171 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000172}
173
174//----------------------------------------------------------------------
175// ProcessGDBRemote constructor
176//----------------------------------------------------------------------
177ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
178 Process (target, listener),
Chris Lattner24943d22010-06-08 16:52:24 +0000179 m_flags (0),
Greg Claytonb72d0f02011-04-12 05:54:46 +0000180 m_gdb_comm(false),
Chris Lattner24943d22010-06-08 16:52:24 +0000181 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000182 m_last_stop_packet (),
Greg Clayton06709002011-12-06 04:51:14 +0000183 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
Chris Lattner24943d22010-06-08 16:52:24 +0000184 m_register_info (),
Jim Ingham5a15e692012-02-16 06:50:00 +0000185 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
Chris Lattner24943d22010-06-08 16:52:24 +0000186 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton5a9f85c2012-04-10 02:25:43 +0000187 m_thread_ids (),
Greg Claytonc1f45872011-02-12 06:28:37 +0000188 m_continue_c_tids (),
189 m_continue_C_tids (),
190 m_continue_s_tids (),
191 m_continue_S_tids (),
Chris Lattner24943d22010-06-08 16:52:24 +0000192 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000193 m_max_memory_size (512),
Greg Claytonbd5c23d2012-05-15 02:33:01 +0000194 m_addr_to_mmap_size (),
195 m_thread_create_bp_sp (),
Jim Ingham06b84492012-07-04 00:35:43 +0000196 m_waiting_for_attach (false),
Jason Molendab46937c2012-10-03 01:29:34 +0000197 m_destroy_tried_resuming (false),
198 m_dyld_plugin_name(),
Greg Clayton13193d52012-10-13 02:07:45 +0000199 m_kernel_load_addr (LLDB_INVALID_ADDRESS),
200 m_command_sp ()
Chris Lattner24943d22010-06-08 16:52:24 +0000201{
Greg Claytonff39f742011-04-01 00:29:43 +0000202 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
203 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +0000204 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Chris Lattner24943d22010-06-08 16:52:24 +0000205}
206
207//----------------------------------------------------------------------
208// Destructor
209//----------------------------------------------------------------------
210ProcessGDBRemote::~ProcessGDBRemote()
211{
212 // m_mach_process.UnregisterNotificationCallbacks (this);
213 Clear();
Greg Clayton2f57db02011-10-01 00:45:15 +0000214 // We need to call finalize on the process before destroying ourselves
215 // to make sure all of the broadcaster cleanup goes as planned. If we
216 // destruct this class, then Process::~Process() might have problems
217 // trying to fully destroy the broadcaster.
218 Finalize();
Chris Lattner24943d22010-06-08 16:52:24 +0000219}
220
221//----------------------------------------------------------------------
222// PluginInterface
223//----------------------------------------------------------------------
224const char *
225ProcessGDBRemote::GetPluginName()
226{
227 return "Process debugging plug-in that uses the GDB remote protocol";
228}
229
230const char *
231ProcessGDBRemote::GetShortPluginName()
232{
233 return GetPluginNameStatic();
234}
235
236uint32_t
237ProcessGDBRemote::GetPluginVersion()
238{
239 return 1;
240}
241
242void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000243ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000244{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000245 if (!force && m_register_info.GetNumRegisters() > 0)
246 return;
247
248 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000249 m_register_info.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000250 uint32_t reg_offset = 0;
251 uint32_t reg_num = 0;
Greg Clayton4a379b12012-07-17 03:23:13 +0000252 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Greg Clayton61d043b2011-03-22 04:00:09 +0000253 response_type == StringExtractorGDBRemote::eResponse;
254 ++reg_num)
Chris Lattner24943d22010-06-08 16:52:24 +0000255 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000256 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
257 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000258 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000259 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000260 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000261 response_type = response.GetResponseType();
262 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner24943d22010-06-08 16:52:24 +0000263 {
264 std::string name;
265 std::string value;
266 ConstString reg_name;
267 ConstString alt_name;
268 ConstString set_name;
269 RegisterInfo reg_info = { NULL, // Name
270 NULL, // Alt name
271 0, // byte size
272 reg_offset, // offset
273 eEncodingUint, // encoding
274 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000275 {
276 LLDB_INVALID_REGNUM, // GCC reg num
277 LLDB_INVALID_REGNUM, // DWARF reg num
278 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000279 reg_num, // GDB reg num
280 reg_num // native register number
Greg Claytoncd330422012-02-29 19:27:27 +0000281 },
282 NULL,
283 NULL
Chris Lattner24943d22010-06-08 16:52:24 +0000284 };
285
286 while (response.GetNameColonValue(name, value))
287 {
288 if (name.compare("name") == 0)
289 {
290 reg_name.SetCString(value.c_str());
291 }
292 else if (name.compare("alt-name") == 0)
293 {
294 alt_name.SetCString(value.c_str());
295 }
296 else if (name.compare("bitsize") == 0)
297 {
298 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
299 }
300 else if (name.compare("offset") == 0)
301 {
302 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000303 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000304 {
305 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000306 }
307 }
308 else if (name.compare("encoding") == 0)
309 {
Greg Clayton88b980b2012-08-24 01:42:50 +0000310 const Encoding encoding = Args::StringToEncoding (value.c_str());
311 if (encoding != eEncodingInvalid)
312 reg_info.encoding = encoding;
Chris Lattner24943d22010-06-08 16:52:24 +0000313 }
314 else if (name.compare("format") == 0)
315 {
Greg Clayton88b980b2012-08-24 01:42:50 +0000316 Format format = eFormatInvalid;
317 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
318 reg_info.format = format;
319 else if (value.compare("binary") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +0000320 reg_info.format = eFormatBinary;
321 else if (value.compare("decimal") == 0)
322 reg_info.format = eFormatDecimal;
323 else if (value.compare("hex") == 0)
324 reg_info.format = eFormatHex;
325 else if (value.compare("float") == 0)
326 reg_info.format = eFormatFloat;
327 else if (value.compare("vector-sint8") == 0)
328 reg_info.format = eFormatVectorOfSInt8;
329 else if (value.compare("vector-uint8") == 0)
330 reg_info.format = eFormatVectorOfUInt8;
331 else if (value.compare("vector-sint16") == 0)
332 reg_info.format = eFormatVectorOfSInt16;
333 else if (value.compare("vector-uint16") == 0)
334 reg_info.format = eFormatVectorOfUInt16;
335 else if (value.compare("vector-sint32") == 0)
336 reg_info.format = eFormatVectorOfSInt32;
337 else if (value.compare("vector-uint32") == 0)
338 reg_info.format = eFormatVectorOfUInt32;
339 else if (value.compare("vector-float32") == 0)
340 reg_info.format = eFormatVectorOfFloat32;
341 else if (value.compare("vector-uint128") == 0)
342 reg_info.format = eFormatVectorOfUInt128;
343 }
344 else if (name.compare("set") == 0)
345 {
346 set_name.SetCString(value.c_str());
347 }
348 else if (name.compare("gcc") == 0)
349 {
350 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
351 }
352 else if (name.compare("dwarf") == 0)
353 {
354 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
355 }
356 else if (name.compare("generic") == 0)
357 {
Greg Clayton88b980b2012-08-24 01:42:50 +0000358 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000359 }
360 }
361
Jason Molenda53d96862010-06-11 23:44:18 +0000362 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000363 assert (reg_info.byte_size != 0);
364 reg_offset += reg_info.byte_size;
365 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
366 }
367 }
368 else
369 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000370 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000371 }
372 }
373
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000374 // We didn't get anything if the accumulated reg_num is zero. See if we are
375 // debugging ARM and fill with a hard coded register set until we can get an
376 // updated debugserver down on the devices.
377 // On the other hand, if the accumulated reg_num is positive, see if we can
378 // add composite registers to the existing primordial ones.
379 bool from_scratch = (reg_num == 0);
380
381 const ArchSpec &target_arch = GetTarget().GetArchitecture();
382 const ArchSpec &remote_arch = m_gdb_comm.GetHostArchitecture();
383 if (!target_arch.IsValid())
Chris Lattner24943d22010-06-08 16:52:24 +0000384 {
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000385 if (remote_arch.IsValid()
386 && remote_arch.GetMachine() == llvm::Triple::arm
387 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
388 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner24943d22010-06-08 16:52:24 +0000389 }
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000390 else if (target_arch.GetMachine() == llvm::Triple::arm)
391 {
392 m_register_info.HardcodeARMRegisters(from_scratch);
393 }
394
Johnny Chend2e30662012-05-22 00:57:05 +0000395 // Add some convenience registers (eax, ebx, ecx, edx, esi, edi, ebp, esp) to x86_64.
Johnny Chenbe315a62012-06-08 19:06:28 +0000396 if ((target_arch.IsValid() && target_arch.GetMachine() == llvm::Triple::x86_64)
397 || (remote_arch.IsValid() && remote_arch.GetMachine() == llvm::Triple::x86_64))
Johnny Chend2e30662012-05-22 00:57:05 +0000398 m_register_info.Addx86_64ConvenienceRegisters();
399
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000400 // At this point, we can finalize our register info.
Chris Lattner24943d22010-06-08 16:52:24 +0000401 m_register_info.Finalize ();
402}
403
404Error
405ProcessGDBRemote::WillLaunch (Module* module)
406{
407 return WillLaunchOrAttach ();
408}
409
410Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000411ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000412{
413 return WillLaunchOrAttach ();
414}
415
416Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000417ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000418{
419 return WillLaunchOrAttach ();
420}
421
422Error
Jason Molendafac2e622012-09-29 04:02:01 +0000423ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytone71e2582011-02-04 01:58:07 +0000424{
425 Error error (WillLaunchOrAttach ());
426
427 if (error.Fail())
428 return error;
429
Greg Clayton180546b2011-04-30 01:09:13 +0000430 error = ConnectToDebugserver (remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000431
432 if (error.Fail())
433 return error;
434 StartAsyncThread ();
435
Jason Molendab46937c2012-10-03 01:29:34 +0000436 CheckForKernel (strm);
Jason Molendafac2e622012-09-29 04:02:01 +0000437
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000438 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000439 if (pid == LLDB_INVALID_PROCESS_ID)
440 {
441 // We don't have a valid process ID, so note that we are connected
442 // and could now request to launch or attach, or get remote process
443 // listings...
444 SetPrivateState (eStateConnected);
445 }
446 else
447 {
448 // We have a valid process
449 SetID (pid);
Greg Clayton37f962e2011-08-22 02:49:39 +0000450 GetThreadList();
Greg Clayton261a18b2011-06-02 22:22:38 +0000451 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000452 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000453 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytone71e2582011-02-04 01:58:07 +0000454 if (state == eStateStopped)
455 {
456 SetPrivateState (state);
457 }
458 else
Greg Claytond9919d32011-12-01 23:28:38 +0000459 error.SetErrorStringWithFormat ("Process %llu was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
Greg Claytone71e2582011-02-04 01:58:07 +0000460 }
461 else
Greg Claytond9919d32011-12-01 23:28:38 +0000462 error.SetErrorStringWithFormat ("Process %llu was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000463 }
Jason Molendacb740b32012-05-03 22:37:30 +0000464
465 if (error.Success()
466 && !GetTarget().GetArchitecture().IsValid()
467 && m_gdb_comm.GetHostArchitecture().IsValid())
468 {
469 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
470 }
471
Greg Claytone71e2582011-02-04 01:58:07 +0000472 return error;
473}
474
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000475// When we are establishing a connection to a remote system and we have no executable specified,
476// or the executable is a kernel, we may be looking at a KASLR situation (where the kernel has been
477// slid in memory.)
478//
Jason Molendab46937c2012-10-03 01:29:34 +0000479// This function tries to locate the kernel in memory if this is possibly a kernel debug session.
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000480//
Jason Molendab46937c2012-10-03 01:29:34 +0000481// If a kernel is found, return the address of the kernel in GetImageInfoAddress() -- the
482// DynamicLoaderDarwinKernel plugin uses this address as the kernel load address and will load the
483// binary, if needed, along with all the kexts.
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000484
485void
Jason Molendab46937c2012-10-03 01:29:34 +0000486ProcessGDBRemote::CheckForKernel (Stream *strm)
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000487{
488 // early return if this isn't an "unknown" system (kernel debugging doesn't have a system type)
489 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
490 if (!gdb_remote_arch.IsValid() || gdb_remote_arch.GetTriple().getVendor() != llvm::Triple::UnknownVendor)
491 return;
492
493 Module *exe_module = GetTarget().GetExecutableModulePointer();
494 ObjectFile *exe_objfile = NULL;
495 if (exe_module)
496 exe_objfile = exe_module->GetObjectFile();
497
498 // early return if we have an executable and it is not a kernel--this is very unlikely to be a kernel debug session.
499 if (exe_objfile
500 && (exe_objfile->GetType() != ObjectFile::eTypeExecutable
501 || exe_objfile->GetStrata() != ObjectFile::eStrataKernel))
502 return;
503
504 // See if the kernel is in memory at the File address (slide == 0) -- no work needed, if so.
505 if (exe_objfile && exe_objfile->GetHeaderAddress().IsValid())
506 {
507 ModuleSP memory_module_sp;
508 memory_module_sp = ReadModuleFromMemory (exe_module->GetFileSpec(), exe_objfile->GetHeaderAddress().GetFileAddress(), false, false);
509 if (memory_module_sp.get()
510 && memory_module_sp->GetUUID().IsValid()
511 && memory_module_sp->GetUUID() == exe_module->GetUUID())
512 {
Jason Molendab46937c2012-10-03 01:29:34 +0000513 m_kernel_load_addr = exe_objfile->GetHeaderAddress().GetFileAddress();
514 m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
Jason Molendad6b81222012-10-06 02:02:26 +0000515 SetCanJIT(false);
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000516 return;
517 }
518 }
519
520 // See if the kernel's load address is stored in the kernel's low globals page; this is
521 // done when a debug boot-arg has been set.
522
523 Error error;
524 uint8_t buf[24];
525 ModuleSP memory_module_sp;
526 addr_t kernel_addr = LLDB_INVALID_ADDRESS;
527
528 // First try the 32-bit
529 if (memory_module_sp.get() == NULL)
530 {
531 DataExtractor data4 (buf, sizeof(buf), gdb_remote_arch.GetByteOrder(), 4);
532 if (DoReadMemory (0xffff0110, buf, 4, error) == 4)
533 {
534 uint32_t offset = 0;
535 kernel_addr = data4.GetU32(&offset);
536 memory_module_sp = ReadModuleFromMemory (FileSpec("mach_kernel", false), kernel_addr, false, false);
537 if (!memory_module_sp.get()
538 || !memory_module_sp->GetUUID().IsValid()
539 || memory_module_sp->GetObjectFile() == NULL
540 || memory_module_sp->GetObjectFile()->GetType() != ObjectFile::eTypeExecutable
541 || memory_module_sp->GetObjectFile()->GetStrata() != ObjectFile::eStrataKernel)
542 {
543 memory_module_sp.reset();
544 }
545 }
546 }
547
548 // Now try the 64-bit location
549 if (memory_module_sp.get() == NULL)
550 {
551 DataExtractor data8 (buf, sizeof(buf), gdb_remote_arch.GetByteOrder(), 8);
552 if (DoReadMemory (0xffffff8000002010ULL, buf, 8, error) == 8)
553 {
554 uint32_t offset = 0;
555 kernel_addr = data8.GetU32(&offset);
556 memory_module_sp = ReadModuleFromMemory (FileSpec("mach_kernel", false), kernel_addr, false, false);
557 if (!memory_module_sp.get()
558 || !memory_module_sp->GetUUID().IsValid()
559 || memory_module_sp->GetObjectFile() == NULL
560 || memory_module_sp->GetObjectFile()->GetType() != ObjectFile::eTypeExecutable
561 || memory_module_sp->GetObjectFile()->GetStrata() != ObjectFile::eStrataKernel)
562 {
563 memory_module_sp.reset();
564 }
565 }
566 }
567
Jason Molendab46937c2012-10-03 01:29:34 +0000568 if (memory_module_sp.get()
569 && memory_module_sp->GetArchitecture().IsValid()
570 && memory_module_sp->GetArchitecture().GetTriple().getVendor() == llvm::Triple::Apple)
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000571 {
Jason Molendab46937c2012-10-03 01:29:34 +0000572 m_kernel_load_addr = kernel_addr;
573 m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
Jason Molendad6b81222012-10-06 02:02:26 +0000574 SetCanJIT(false);
Jason Molendab46937c2012-10-03 01:29:34 +0000575 return;
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000576 }
577}
578
Greg Claytone71e2582011-02-04 01:58:07 +0000579Error
Chris Lattner24943d22010-06-08 16:52:24 +0000580ProcessGDBRemote::WillLaunchOrAttach ()
581{
582 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000583 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000584 return error;
585}
586
587//----------------------------------------------------------------------
588// Process Control
589//----------------------------------------------------------------------
590Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000591ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000592{
Greg Clayton4b407112010-09-30 21:49:03 +0000593 Error error;
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000594
595 uint32_t launch_flags = launch_info.GetFlags().Get();
596 const char *stdin_path = NULL;
597 const char *stdout_path = NULL;
598 const char *stderr_path = NULL;
599 const char *working_dir = launch_info.GetWorkingDirectory();
600
601 const ProcessLaunchInfo::FileAction *file_action;
602 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
603 if (file_action)
604 {
605 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
606 stdin_path = file_action->GetPath();
607 }
608 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
609 if (file_action)
610 {
611 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
612 stdout_path = file_action->GetPath();
613 }
614 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
615 if (file_action)
616 {
617 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
618 stderr_path = file_action->GetPath();
619 }
620
Chris Lattner24943d22010-06-08 16:52:24 +0000621 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
622 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
623 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton716cefb2011-08-09 05:20:29 +0000624 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000625
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000626 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner24943d22010-06-08 16:52:24 +0000627 if (object_file)
628 {
Chris Lattner24943d22010-06-08 16:52:24 +0000629 char host_port[128];
630 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000631 char connect_url[128];
632 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000633
Greg Claytona2f74232011-02-24 22:24:29 +0000634 // Make sure we aren't already connected?
635 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000636 {
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000637 error = StartDebugserverProcess (host_port, launch_info);
Chris Lattner24943d22010-06-08 16:52:24 +0000638 if (error.Fail())
Greg Clayton716cefb2011-08-09 05:20:29 +0000639 {
Johnny Chenc143d622011-08-09 18:56:45 +0000640 if (log)
641 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner24943d22010-06-08 16:52:24 +0000642 return error;
Greg Clayton716cefb2011-08-09 05:20:29 +0000643 }
Chris Lattner24943d22010-06-08 16:52:24 +0000644
Greg Claytone71e2582011-02-04 01:58:07 +0000645 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000646 }
647
648 if (error.Success())
649 {
650 lldb_utility::PseudoTerminal pty;
651 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000652
653 // If the debugserver is local and we aren't disabling STDIO, lets use
654 // a pseudo terminal to instead of relying on the 'O' packets for stdio
655 // since 'O' packets can really slow down debugging if the inferior
656 // does a lot of output.
Greg Claytonb4747822011-06-24 22:32:10 +0000657 PlatformSP platform_sp (m_target.GetPlatform());
658 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000659 {
660 const char *slave_name = NULL;
661 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000662 {
Greg Claytona2f74232011-02-24 22:24:29 +0000663 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
664 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000665 }
Greg Claytona2f74232011-02-24 22:24:29 +0000666 if (stdin_path == NULL)
667 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000668
Greg Claytona2f74232011-02-24 22:24:29 +0000669 if (stdout_path == NULL)
670 stdout_path = slave_name;
671
672 if (stderr_path == NULL)
673 stderr_path = slave_name;
674 }
675
Greg Claytonafb81862011-03-02 21:34:46 +0000676 // Set STDIN to /dev/null if we want STDIO disabled or if either
677 // STDOUT or STDERR have been set to something and STDIN hasn't
678 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000679 stdin_path = "/dev/null";
680
Greg Claytonafb81862011-03-02 21:34:46 +0000681 // Set STDOUT to /dev/null if we want STDIO disabled or if either
682 // STDIN or STDERR have been set to something and STDOUT hasn't
683 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000684 stdout_path = "/dev/null";
685
Greg Claytonafb81862011-03-02 21:34:46 +0000686 // Set STDERR to /dev/null if we want STDIO disabled or if either
687 // STDIN or STDOUT have been set to something and STDERR hasn't
688 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000689 stderr_path = "/dev/null";
690
691 if (stdin_path)
692 m_gdb_comm.SetSTDIN (stdin_path);
693 if (stdout_path)
694 m_gdb_comm.SetSTDOUT (stdout_path);
695 if (stderr_path)
696 m_gdb_comm.SetSTDERR (stderr_path);
697
698 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
699
Greg Claytona4582402011-05-08 04:53:50 +0000700 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000701
702 if (working_dir && working_dir[0])
703 {
704 m_gdb_comm.SetWorkingDir (working_dir);
705 }
706
707 // Send the environment and the program + arguments after we connect
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000708 const Args &environment = launch_info.GetEnvironmentEntries();
709 if (environment.GetArgumentCount())
Greg Claytona2f74232011-02-24 22:24:29 +0000710 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000711 size_t num_environment_entries = environment.GetArgumentCount();
712 for (size_t i=0; i<num_environment_entries; ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000713 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000714 const char *env_entry = environment.GetArgumentAtIndex(i);
715 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000716 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000717 }
Greg Claytona2f74232011-02-24 22:24:29 +0000718 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000719
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000720 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000721 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info.GetArguments().GetConstArgumentVector());
Greg Claytona2f74232011-02-24 22:24:29 +0000722 if (arg_packet_err == 0)
723 {
724 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000725 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000726 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000727 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000728 }
729 else
730 {
Greg Claytona2f74232011-02-24 22:24:29 +0000731 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000732 }
Greg Claytona2f74232011-02-24 22:24:29 +0000733 }
734 else
735 {
Greg Clayton9c236732011-10-26 00:56:27 +0000736 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Claytona2f74232011-02-24 22:24:29 +0000737 }
Greg Clayton7c4fc6e2011-08-10 22:05:39 +0000738
739 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner24943d22010-06-08 16:52:24 +0000740
Greg Claytona2f74232011-02-24 22:24:29 +0000741 if (GetID() == LLDB_INVALID_PROCESS_ID)
742 {
Johnny Chenc143d622011-08-09 18:56:45 +0000743 if (log)
744 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytona2f74232011-02-24 22:24:29 +0000745 KillDebugserverProcess ();
746 return error;
747 }
748
Greg Clayton261a18b2011-06-02 22:22:38 +0000749 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000750 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000751 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Claytona2f74232011-02-24 22:24:29 +0000752
753 if (!disable_stdio)
754 {
755 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Clayton464c6162011-11-17 22:14:31 +0000756 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Claytona2f74232011-02-24 22:24:29 +0000757 }
Chris Lattner24943d22010-06-08 16:52:24 +0000758 }
759 }
Greg Clayton716cefb2011-08-09 05:20:29 +0000760 else
761 {
Johnny Chenc143d622011-08-09 18:56:45 +0000762 if (log)
763 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton716cefb2011-08-09 05:20:29 +0000764 }
Chris Lattner24943d22010-06-08 16:52:24 +0000765 }
766 else
767 {
768 // Set our user ID to an invalid process ID.
769 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000770 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
771 exe_module->GetFileSpec().GetFilename().AsCString(),
772 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000773 }
Chris Lattner24943d22010-06-08 16:52:24 +0000774 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000775
Chris Lattner24943d22010-06-08 16:52:24 +0000776}
777
778
779Error
Greg Claytone71e2582011-02-04 01:58:07 +0000780ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000781{
782 Error error;
783 // Sleep and wait a bit for debugserver to start to listen...
784 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
785 if (conn_ap.get())
786 {
Chris Lattner24943d22010-06-08 16:52:24 +0000787 const uint32_t max_retry_count = 50;
788 uint32_t retry_count = 0;
789 while (!m_gdb_comm.IsConnected())
790 {
Greg Claytone71e2582011-02-04 01:58:07 +0000791 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000792 {
793 m_gdb_comm.SetConnection (conn_ap.release());
794 break;
795 }
796 retry_count++;
797
798 if (retry_count >= max_retry_count)
799 break;
800
801 usleep (100000);
802 }
803 }
804
805 if (!m_gdb_comm.IsConnected())
806 {
807 if (error.Success())
808 error.SetErrorString("not connected to remote gdb server");
809 return error;
810 }
811
Greg Clayton24bc5d92011-03-30 18:16:51 +0000812 // We always seem to be able to open a connection to a local port
813 // so we need to make sure we can then send data to it. If we can't
814 // then we aren't actually connected to anything, so try and do the
815 // handshake with the remote GDB server and make sure that goes
816 // alright.
817 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000818 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000819 m_gdb_comm.Disconnect();
820 if (error.Success())
821 error.SetErrorString("not connected to remote gdb server");
822 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000823 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000824 m_gdb_comm.ResetDiscoverableSettings();
825 m_gdb_comm.QueryNoAckModeSupported ();
826 m_gdb_comm.GetThreadSuffixSupported ();
Greg Claytona1f645e2012-04-10 03:22:03 +0000827 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000828 m_gdb_comm.GetHostInfo ();
829 m_gdb_comm.GetVContSupported ('c');
Jim Ingham3a458eb2012-07-20 21:37:13 +0000830 m_gdb_comm.GetVAttachOrWaitSupported();
Jim Ingham86827fb2012-07-02 05:40:07 +0000831
832 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
833 for (size_t idx = 0; idx < num_cmds; idx++)
834 {
835 StringExtractorGDBRemote response;
836 printf ("Sending command: \%s.\n", GetExtraStartupCommands().GetArgumentAtIndex(idx));
837 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
838 }
Chris Lattner24943d22010-06-08 16:52:24 +0000839 return error;
840}
841
842void
843ProcessGDBRemote::DidLaunchOrAttach ()
844{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000845 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
846 if (log)
847 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000848 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000849 {
850 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
851
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000852 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000853
Chris Lattner24943d22010-06-08 16:52:24 +0000854 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000855
Greg Claytoncb8977d2011-03-23 00:09:55 +0000856 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
857 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000858 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000859 ArchSpec &target_arch = GetTarget().GetArchitecture();
860
861 if (target_arch.IsValid())
862 {
863 // If the remote host is ARM and we have apple as the vendor, then
864 // ARM executables and shared libraries can have mixed ARM architectures.
865 // You can have an armv6 executable, and if the host is armv7, then the
866 // system will load the best possible architecture for all shared libraries
867 // it has, so we really need to take the remote host architecture as our
868 // defacto architecture in this case.
869
870 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
871 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
872 {
873 target_arch = gdb_remote_arch;
874 }
875 else
876 {
877 // Fill in what is missing in the triple
878 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
879 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000880 if (target_triple.getVendorName().size() == 0)
881 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000882 target_triple.setVendor (remote_triple.getVendor());
883
Greg Clayton2f085c62011-05-15 01:25:55 +0000884 if (target_triple.getOSName().size() == 0)
885 {
886 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000887
Greg Clayton2f085c62011-05-15 01:25:55 +0000888 if (target_triple.getEnvironmentName().size() == 0)
889 target_triple.setEnvironment (remote_triple.getEnvironment());
890 }
891 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000892 }
893 }
894 else
895 {
896 // The target doesn't have a valid architecture yet, set it from
897 // the architecture we got from the remote GDB server
898 target_arch = gdb_remote_arch;
899 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000900 }
Chris Lattner24943d22010-06-08 16:52:24 +0000901 }
902}
903
904void
905ProcessGDBRemote::DidLaunch ()
906{
907 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000908}
909
910Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000911ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000912{
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000913 ProcessAttachInfo attach_info;
914 return DoAttachToProcessWithID(attach_pid, attach_info);
915}
916
917Error
918ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
919{
Chris Lattner24943d22010-06-08 16:52:24 +0000920 Error error;
921 // Clear out and clean up from any current state
922 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000923 if (attach_pid != LLDB_INVALID_PROCESS_ID)
924 {
Greg Claytona2f74232011-02-24 22:24:29 +0000925 // Make sure we aren't already connected?
926 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000927 {
Greg Claytona2f74232011-02-24 22:24:29 +0000928 char host_port[128];
929 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
930 char connect_url[128];
931 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000932
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000933 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000934
935 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000936 {
Greg Claytona2f74232011-02-24 22:24:29 +0000937 const char *error_string = error.AsCString();
938 if (error_string == NULL)
939 error_string = "unable to launch " DEBUGSERVER_BASENAME;
940
941 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000942 }
Greg Claytona2f74232011-02-24 22:24:29 +0000943 else
944 {
945 error = ConnectToDebugserver (connect_url);
946 }
947 }
948
949 if (error.Success())
950 {
951 char packet[64];
Greg Claytond9919d32011-12-01 23:28:38 +0000952 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%llx", attach_pid);
Greg Clayton489575c2011-11-19 02:11:30 +0000953 SetID (attach_pid);
Greg Claytona2f74232011-02-24 22:24:29 +0000954 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000955 }
956 }
Chris Lattner24943d22010-06-08 16:52:24 +0000957 return error;
958}
959
960size_t
961ProcessGDBRemote::AttachInputReaderCallback
962(
963 void *baton,
964 InputReader *reader,
965 lldb::InputReaderAction notification,
966 const char *bytes,
967 size_t bytes_len
968)
969{
970 if (notification == eInputReaderGotToken)
971 {
972 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
973 if (gdb_process->m_waiting_for_attach)
974 gdb_process->m_waiting_for_attach = false;
975 reader->SetIsDone(true);
976 return 1;
977 }
978 return 0;
979}
980
981Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000982ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000983{
984 Error error;
985 // Clear out and clean up from any current state
986 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000987
Chris Lattner24943d22010-06-08 16:52:24 +0000988 if (process_name && process_name[0])
989 {
Greg Claytona2f74232011-02-24 22:24:29 +0000990 // Make sure we aren't already connected?
991 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000992 {
Greg Claytona2f74232011-02-24 22:24:29 +0000993 char host_port[128];
994 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
995 char connect_url[128];
996 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
997
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000998 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000999 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +00001000 {
Greg Claytona2f74232011-02-24 22:24:29 +00001001 const char *error_string = error.AsCString();
1002 if (error_string == NULL)
1003 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +00001004
Greg Claytona2f74232011-02-24 22:24:29 +00001005 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +00001006 }
Greg Claytona2f74232011-02-24 22:24:29 +00001007 else
1008 {
1009 error = ConnectToDebugserver (connect_url);
1010 }
1011 }
1012
1013 if (error.Success())
1014 {
1015 StreamString packet;
1016
1017 if (wait_for_launch)
Jim Ingham3a458eb2012-07-20 21:37:13 +00001018 {
1019 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1020 {
1021 packet.PutCString ("vAttachWait");
1022 }
1023 else
1024 {
1025 if (attach_info.GetIgnoreExisting())
1026 packet.PutCString("vAttachWait");
1027 else
1028 packet.PutCString ("vAttachOrWait");
1029 }
1030 }
Greg Claytona2f74232011-02-24 22:24:29 +00001031 else
1032 packet.PutCString("vAttachName");
1033 packet.PutChar(';');
1034 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1035
1036 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1037
Chris Lattner24943d22010-06-08 16:52:24 +00001038 }
1039 }
Chris Lattner24943d22010-06-08 16:52:24 +00001040 return error;
1041}
1042
Chris Lattner24943d22010-06-08 16:52:24 +00001043
1044void
1045ProcessGDBRemote::DidAttach ()
1046{
Greg Claytone71e2582011-02-04 01:58:07 +00001047 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +00001048}
1049
1050Error
1051ProcessGDBRemote::WillResume ()
1052{
Greg Claytonc1f45872011-02-12 06:28:37 +00001053 m_continue_c_tids.clear();
1054 m_continue_C_tids.clear();
1055 m_continue_s_tids.clear();
1056 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001057 return Error();
1058}
1059
1060Error
1061ProcessGDBRemote::DoResume ()
1062{
Jim Ingham3ae449a2010-11-17 02:32:00 +00001063 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +00001064 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1065 if (log)
1066 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +00001067
1068 Listener listener ("gdb-remote.resume-packet-sent");
1069 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1070 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001071 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1072
Greg Claytonc1f45872011-02-12 06:28:37 +00001073 StreamString continue_packet;
1074 bool continue_packet_error = false;
1075 if (m_gdb_comm.HasAnyVContSupport ())
1076 {
1077 continue_packet.PutCString ("vCont");
1078
1079 if (!m_continue_c_tids.empty())
1080 {
1081 if (m_gdb_comm.GetVContSupported ('c'))
1082 {
1083 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)
Greg Claytond9919d32011-12-01 23:28:38 +00001084 continue_packet.Printf(";c:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +00001085 }
1086 else
1087 continue_packet_error = true;
1088 }
1089
1090 if (!continue_packet_error && !m_continue_C_tids.empty())
1091 {
1092 if (m_gdb_comm.GetVContSupported ('C'))
1093 {
1094 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)
Greg Claytond9919d32011-12-01 23:28:38 +00001095 continue_packet.Printf(";C%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001096 }
1097 else
1098 continue_packet_error = true;
1099 }
Greg Claytonb749a262010-12-03 06:02:24 +00001100
Greg Claytonc1f45872011-02-12 06:28:37 +00001101 if (!continue_packet_error && !m_continue_s_tids.empty())
1102 {
1103 if (m_gdb_comm.GetVContSupported ('s'))
1104 {
1105 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)
Greg Claytond9919d32011-12-01 23:28:38 +00001106 continue_packet.Printf(";s:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +00001107 }
1108 else
1109 continue_packet_error = true;
1110 }
1111
1112 if (!continue_packet_error && !m_continue_S_tids.empty())
1113 {
1114 if (m_gdb_comm.GetVContSupported ('S'))
1115 {
1116 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)
Greg Claytond9919d32011-12-01 23:28:38 +00001117 continue_packet.Printf(";S%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001118 }
1119 else
1120 continue_packet_error = true;
1121 }
1122
1123 if (continue_packet_error)
1124 continue_packet.GetString().clear();
1125 }
1126 else
1127 continue_packet_error = true;
1128
1129 if (continue_packet_error)
1130 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001131 // Either no vCont support, or we tried to use part of the vCont
1132 // packet that wasn't supported by the remote GDB server.
1133 // We need to try and make a simple packet that can do our continue
1134 const size_t num_threads = GetThreadList().GetSize();
1135 const size_t num_continue_c_tids = m_continue_c_tids.size();
1136 const size_t num_continue_C_tids = m_continue_C_tids.size();
1137 const size_t num_continue_s_tids = m_continue_s_tids.size();
1138 const size_t num_continue_S_tids = m_continue_S_tids.size();
1139 if (num_continue_c_tids > 0)
1140 {
1141 if (num_continue_c_tids == num_threads)
1142 {
1143 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001144 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001145 continue_packet.PutChar ('c');
1146 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001147 }
1148 else if (num_continue_c_tids == 1 &&
1149 num_continue_C_tids == 0 &&
1150 num_continue_s_tids == 0 &&
1151 num_continue_S_tids == 0 )
1152 {
1153 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +00001154 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001155 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +00001156 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001157 }
1158 }
1159
Greg Claytonde1dd812011-06-24 03:21:43 +00001160 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001161 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001162 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1163 num_continue_C_tids > 0 &&
1164 num_continue_s_tids == 0 &&
1165 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +00001166 {
1167 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +00001168 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +00001169 if (num_continue_C_tids > 1)
1170 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001171 // More that one thread with a signal, yet we don't have
1172 // vCont support and we are being asked to resume each
1173 // thread with a signal, we need to make sure they are
1174 // all the same signal, or we can't issue the continue
1175 // accurately with the current support...
1176 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +00001177 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001178 continue_packet_error = false;
1179 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1180 {
1181 if (m_continue_C_tids[i].second != continue_signo)
1182 continue_packet_error = true;
1183 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001184 }
Greg Claytonde1dd812011-06-24 03:21:43 +00001185 if (!continue_packet_error)
1186 m_gdb_comm.SetCurrentThreadForRun (-1);
1187 }
1188 else
1189 {
1190 // Set the continue thread ID
1191 continue_packet_error = false;
1192 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001193 }
1194 if (!continue_packet_error)
1195 {
1196 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +00001197 continue_packet.Printf("C%2.2x", continue_signo);
1198 }
1199 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001200 }
1201
Greg Claytonde1dd812011-06-24 03:21:43 +00001202 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001203 {
1204 if (num_continue_s_tids == num_threads)
1205 {
1206 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001207 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001208 continue_packet.PutChar ('s');
1209 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001210 }
1211 else if (num_continue_c_tids == 0 &&
1212 num_continue_C_tids == 0 &&
1213 num_continue_s_tids == 1 &&
1214 num_continue_S_tids == 0 )
1215 {
1216 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001217 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001218 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001219 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001220 }
1221 }
1222
1223 if (!continue_packet_error && num_continue_S_tids > 0)
1224 {
1225 if (num_continue_S_tids == num_threads)
1226 {
1227 const int step_signo = m_continue_S_tids.front().second;
1228 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001229 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001230 if (num_continue_S_tids > 1)
1231 {
1232 for (size_t i=1; i<num_threads; ++i)
1233 {
1234 if (m_continue_S_tids[i].second != step_signo)
1235 continue_packet_error = true;
1236 }
1237 }
1238 if (!continue_packet_error)
1239 {
1240 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001241 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001242 continue_packet.Printf("S%2.2x", step_signo);
1243 }
1244 }
1245 else if (num_continue_c_tids == 0 &&
1246 num_continue_C_tids == 0 &&
1247 num_continue_s_tids == 0 &&
1248 num_continue_S_tids == 1 )
1249 {
1250 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001251 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001252 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001253 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001254 }
1255 }
1256 }
1257
1258 if (continue_packet_error)
1259 {
1260 error.SetErrorString ("can't make continue packet for this resume");
1261 }
1262 else
1263 {
1264 EventSP event_sp;
1265 TimeValue timeout;
1266 timeout = TimeValue::Now();
1267 timeout.OffsetWithSeconds (5);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001268 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1269 {
1270 error.SetErrorString ("Trying to resume but the async thread is dead.");
1271 if (log)
1272 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1273 return error;
1274 }
1275
Greg Claytonc1f45872011-02-12 06:28:37 +00001276 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1277
1278 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001279 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001280 error.SetErrorString("Resume timed out.");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001281 if (log)
1282 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1283 }
1284 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1285 {
1286 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1287 if (log)
1288 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1289 return error;
1290 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001291 }
Greg Claytonb749a262010-12-03 06:02:24 +00001292 }
1293
Jim Ingham3ae449a2010-11-17 02:32:00 +00001294 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001295}
1296
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001297void
1298ProcessGDBRemote::ClearThreadIDList ()
1299{
Greg Claytonff3448e2012-04-13 02:11:32 +00001300 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001301 m_thread_ids.clear();
1302}
1303
1304bool
1305ProcessGDBRemote::UpdateThreadIDList ()
1306{
Greg Claytonff3448e2012-04-13 02:11:32 +00001307 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001308 bool sequence_mutex_unavailable = false;
1309 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1310 if (sequence_mutex_unavailable)
1311 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001312 return false; // We just didn't get the list
1313 }
1314 return true;
1315}
1316
Greg Claytonae932352012-04-10 00:18:59 +00001317bool
Greg Clayton37f962e2011-08-22 02:49:39 +00001318ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001319{
1320 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001321 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001322 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Greg Clayton444e35b2011-10-19 18:09:39 +00001323 log->Printf ("ProcessGDBRemote::%s (pid = %llu)", __FUNCTION__, GetID());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001324
1325 size_t num_thread_ids = m_thread_ids.size();
1326 // The "m_thread_ids" thread ID list should always be updated after each stop
1327 // reply packet, but in case it isn't, update it here.
1328 if (num_thread_ids == 0)
1329 {
1330 if (!UpdateThreadIDList ())
1331 return false;
1332 num_thread_ids = m_thread_ids.size();
1333 }
Chris Lattner24943d22010-06-08 16:52:24 +00001334
Greg Clayton37f962e2011-08-22 02:49:39 +00001335 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001336 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001337 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001338 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001339 tid_t tid = m_thread_ids[i];
Greg Clayton37f962e2011-08-22 02:49:39 +00001340 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false));
1341 if (!thread_sp)
Jim Ingham94a5d0d2012-10-10 18:32:14 +00001342 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Greg Clayton37f962e2011-08-22 02:49:39 +00001343 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001344 }
Chris Lattner24943d22010-06-08 16:52:24 +00001345 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001346
Greg Claytonae932352012-04-10 00:18:59 +00001347 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001348}
1349
1350
1351StateType
1352ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1353{
Greg Clayton261a18b2011-06-02 22:22:38 +00001354 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001355 const char stop_type = stop_packet.GetChar();
1356 switch (stop_type)
1357 {
1358 case 'T':
1359 case 'S':
1360 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001361 if (GetStopID() == 0)
1362 {
1363 // Our first stop, make sure we have a process ID, and also make
1364 // sure we know about our registers
1365 if (GetID() == LLDB_INVALID_PROCESS_ID)
1366 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001367 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001368 if (pid != LLDB_INVALID_PROCESS_ID)
1369 SetID (pid);
1370 }
1371 BuildDynamicRegisterInfo (true);
1372 }
Chris Lattner24943d22010-06-08 16:52:24 +00001373 // Stop with signal and thread info
1374 const uint8_t signo = stop_packet.GetHexU8();
1375 std::string name;
1376 std::string value;
1377 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001378 std::string reason;
1379 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001380 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001381 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001382 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Claytona875b642011-01-09 21:07:35 +00001383 ThreadSP thread_sp;
1384
Chris Lattner24943d22010-06-08 16:52:24 +00001385 while (stop_packet.GetNameColonValue(name, value))
1386 {
1387 if (name.compare("metype") == 0)
1388 {
1389 // exception type in big endian hex
1390 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1391 }
Chris Lattner24943d22010-06-08 16:52:24 +00001392 else if (name.compare("medata") == 0)
1393 {
1394 // exception data in big endian hex
1395 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1396 }
1397 else if (name.compare("thread") == 0)
1398 {
1399 // thread in big endian hex
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001400 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Claytonffa43a62011-11-17 04:46:02 +00001401 // m_thread_list does have its own mutex, but we need to
1402 // hold onto the mutex between the call to m_thread_list.FindThreadByID(...)
1403 // and the m_thread_list.AddThread(...) so it doesn't change on us
Greg Claytonc3c46612011-02-15 00:19:15 +00001404 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001405 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001406 if (!thread_sp)
1407 {
1408 // Create the thread if we need to
Jim Ingham94a5d0d2012-10-10 18:32:14 +00001409 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Greg Claytonc3c46612011-02-15 00:19:15 +00001410 m_thread_list.AddThread(thread_sp);
1411 }
Chris Lattner24943d22010-06-08 16:52:24 +00001412 }
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001413 else if (name.compare("threads") == 0)
1414 {
Greg Claytonff3448e2012-04-13 02:11:32 +00001415 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001416 m_thread_ids.clear();
Greg Claytona1f645e2012-04-10 03:22:03 +00001417 // A comma separated list of all threads in the current
1418 // process that includes the thread for this stop reply
1419 // packet
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001420 size_t comma_pos;
1421 lldb::tid_t tid;
1422 while ((comma_pos = value.find(',')) != std::string::npos)
1423 {
1424 value[comma_pos] = '\0';
1425 // thread in big endian hex
1426 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1427 if (tid != LLDB_INVALID_THREAD_ID)
1428 m_thread_ids.push_back (tid);
1429 value.erase(0, comma_pos + 1);
1430
1431 }
1432 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1433 if (tid != LLDB_INVALID_THREAD_ID)
1434 m_thread_ids.push_back (tid);
1435 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001436 else if (name.compare("hexname") == 0)
1437 {
1438 StringExtractor name_extractor;
1439 // Swap "value" over into "name_extractor"
1440 name_extractor.GetStringRef().swap(value);
1441 // Now convert the HEX bytes into a string value
1442 name_extractor.GetHexByteString (value);
1443 thread_name.swap (value);
1444 }
Chris Lattner24943d22010-06-08 16:52:24 +00001445 else if (name.compare("name") == 0)
1446 {
1447 thread_name.swap (value);
1448 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001449 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001450 {
1451 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1452 }
Greg Clayton65611552011-06-04 01:26:29 +00001453 else if (name.compare("reason") == 0)
1454 {
1455 reason.swap(value);
1456 }
1457 else if (name.compare("description") == 0)
1458 {
1459 StringExtractor desc_extractor;
1460 // Swap "value" over into "name_extractor"
1461 desc_extractor.GetStringRef().swap(value);
1462 // Now convert the HEX bytes into a string value
1463 desc_extractor.GetHexByteString (thread_name);
1464 }
Greg Claytona875b642011-01-09 21:07:35 +00001465 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1466 {
1467 // We have a register number that contains an expedited
1468 // register value. Lets supply this register to our thread
1469 // so it won't have to go and read it.
1470 if (thread_sp)
1471 {
1472 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1473
1474 if (reg != UINT32_MAX)
1475 {
1476 StringExtractor reg_value_extractor;
1477 // Swap "value" over into "reg_value_extractor"
1478 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001479 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1480 {
1481 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1482 name.c_str(),
1483 reg,
1484 reg,
1485 reg_value_extractor.GetStringRef().c_str(),
1486 stop_packet.GetStringRef().c_str());
1487 }
Greg Claytona875b642011-01-09 21:07:35 +00001488 }
1489 }
1490 }
Chris Lattner24943d22010-06-08 16:52:24 +00001491 }
Chris Lattner24943d22010-06-08 16:52:24 +00001492
1493 if (thread_sp)
1494 {
1495 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1496
1497 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001498 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001499 if (exc_type != 0)
1500 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001501 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001502
1503 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1504 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001505 exc_data_size,
1506 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001507 exc_data_size >= 2 ? exc_data[1] : 0,
1508 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001509 }
Greg Clayton65611552011-06-04 01:26:29 +00001510 else
Chris Lattner24943d22010-06-08 16:52:24 +00001511 {
Greg Clayton65611552011-06-04 01:26:29 +00001512 bool handled = false;
1513 if (!reason.empty())
1514 {
1515 if (reason.compare("trace") == 0)
1516 {
1517 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1518 handled = true;
1519 }
1520 else if (reason.compare("breakpoint") == 0)
1521 {
1522 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001523 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001524 if (bp_site_sp)
1525 {
1526 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1527 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1528 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001529 handled = true;
Greg Clayton65611552011-06-04 01:26:29 +00001530 if (bp_site_sp->ValidForThisThread (gdb_thread))
1531 {
1532 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001533 }
1534 else
1535 {
1536 StopInfoSP invalid_stop_info_sp;
1537 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Greg Clayton65611552011-06-04 01:26:29 +00001538 }
1539 }
1540
Greg Clayton65611552011-06-04 01:26:29 +00001541 }
1542 else if (reason.compare("trap") == 0)
1543 {
1544 // Let the trap just use the standard signal stop reason below...
1545 }
1546 else if (reason.compare("watchpoint") == 0)
1547 {
1548 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1549 // TODO: locate the watchpoint somehow...
1550 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1551 handled = true;
1552 }
1553 else if (reason.compare("exception") == 0)
1554 {
1555 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1556 handled = true;
1557 }
1558 }
1559
1560 if (signo)
1561 {
1562 if (signo == SIGTRAP)
1563 {
1564 // Currently we are going to assume SIGTRAP means we are either
1565 // hitting a breakpoint or hardware single stepping.
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001566 handled = true;
Greg Clayton65611552011-06-04 01:26:29 +00001567 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001568 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001569
Greg Clayton65611552011-06-04 01:26:29 +00001570 if (bp_site_sp)
1571 {
1572 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1573 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1574 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1575 if (bp_site_sp->ValidForThisThread (gdb_thread))
1576 {
1577 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001578 }
1579 else
1580 {
1581 StopInfoSP invalid_stop_info_sp;
1582 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Greg Clayton65611552011-06-04 01:26:29 +00001583 }
1584 }
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001585 else
Greg Clayton65611552011-06-04 01:26:29 +00001586 {
1587 // TODO: check for breakpoint or trap opcode in case there is a hard
1588 // coded software trap
1589 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Greg Clayton65611552011-06-04 01:26:29 +00001590 }
1591 }
1592 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001593 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001594 }
1595 else
1596 {
Greg Clayton643ee732010-08-04 01:40:35 +00001597 StopInfoSP invalid_stop_info_sp;
1598 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001599 }
Greg Clayton65611552011-06-04 01:26:29 +00001600
1601 if (!description.empty())
1602 {
1603 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1604 if (stop_info_sp)
1605 {
1606 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001607 }
Greg Clayton65611552011-06-04 01:26:29 +00001608 else
1609 {
1610 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1611 }
1612 }
1613 }
Chris Lattner24943d22010-06-08 16:52:24 +00001614 }
1615 return eStateStopped;
1616 }
1617 break;
1618
1619 case 'W':
1620 // process exited
1621 return eStateExited;
1622
1623 default:
1624 break;
1625 }
1626 return eStateInvalid;
1627}
1628
1629void
1630ProcessGDBRemote::RefreshStateAfterStop ()
1631{
Greg Claytonff3448e2012-04-13 02:11:32 +00001632 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001633 m_thread_ids.clear();
1634 // Set the thread stop info. It might have a "threads" key whose value is
1635 // a list of all thread IDs in the current process, so m_thread_ids might
1636 // get set.
1637 SetThreadStopInfo (m_last_stop_packet);
1638 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1639 if (m_thread_ids.empty())
1640 {
1641 // No, we need to fetch the thread list manually
1642 UpdateThreadIDList();
1643 }
1644
Chris Lattner24943d22010-06-08 16:52:24 +00001645 // Let all threads recover from stopping and do any clean up based
1646 // on the previous thread state (if any).
1647 m_thread_list.RefreshStateAfterStop();
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001648
Chris Lattner24943d22010-06-08 16:52:24 +00001649}
1650
1651Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001652ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001653{
1654 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001655
Greg Claytona4881d02011-01-22 07:12:45 +00001656 bool timed_out = false;
1657 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001658
1659 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001660 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001661 // We are being asked to halt during an attach. We need to just close
1662 // our file handle and debugserver will go away, and we can be done...
1663 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001664 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001665 else
1666 {
Greg Clayton05e4d972012-03-29 01:55:41 +00001667 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001668 {
1669 if (timed_out)
1670 error.SetErrorString("timed out sending interrupt packet");
1671 else
1672 error.SetErrorString("unknown error sending interrupt packet");
1673 }
Greg Clayton05e4d972012-03-29 01:55:41 +00001674
1675 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001676 }
Chris Lattner24943d22010-06-08 16:52:24 +00001677 return error;
1678}
1679
1680Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001681ProcessGDBRemote::InterruptIfRunning
1682(
1683 bool discard_thread_plans,
1684 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001685 EventSP &stop_event_sp
1686)
Chris Lattner24943d22010-06-08 16:52:24 +00001687{
1688 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001689
Greg Clayton2860ba92011-01-23 19:58:49 +00001690 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1691
Greg Clayton68ca8232011-01-25 02:58:48 +00001692 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001693 const bool is_running = m_gdb_comm.IsRunning();
1694 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001695 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001696 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001697 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001698 is_running);
1699
Greg Clayton2860ba92011-01-23 19:58:49 +00001700 if (discard_thread_plans)
1701 {
1702 if (log)
1703 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1704 m_thread_list.DiscardThreadPlans();
1705 }
1706 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001707 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001708 if (catch_stop_event)
1709 {
1710 if (log)
1711 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1712 PausePrivateStateThread();
1713 paused_private_state_thread = true;
1714 }
1715
Greg Clayton4fb400f2010-09-27 21:07:38 +00001716 bool timed_out = false;
1717 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001718
Greg Clayton05e4d972012-03-29 01:55:41 +00001719 if (!m_gdb_comm.SendInterrupt (locker, 1, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001720 {
1721 if (timed_out)
1722 error.SetErrorString("timed out sending interrupt packet");
1723 else
1724 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001725 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001726 ResumePrivateStateThread();
1727 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001728 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001729
Greg Clayton72e1c782011-01-22 23:43:18 +00001730 if (catch_stop_event)
1731 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001732 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001733 TimeValue timeout_time;
1734 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001735 timeout_time.OffsetWithSeconds(5);
1736 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001737
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001738 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001739 if (log)
1740 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001741
Greg Clayton2860ba92011-01-23 19:58:49 +00001742 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001743 error.SetErrorString("unable to verify target stopped");
1744 }
1745
Greg Clayton68ca8232011-01-25 02:58:48 +00001746 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001747 {
1748 if (log)
1749 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001750 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001751 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001752 }
Chris Lattner24943d22010-06-08 16:52:24 +00001753 return error;
1754}
1755
Greg Clayton4fb400f2010-09-27 21:07:38 +00001756Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001757ProcessGDBRemote::WillDetach ()
1758{
Greg Clayton2860ba92011-01-23 19:58:49 +00001759 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1760 if (log)
1761 log->Printf ("ProcessGDBRemote::WillDetach()");
1762
Greg Clayton72e1c782011-01-22 23:43:18 +00001763 bool discard_thread_plans = true;
1764 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001765 EventSP event_sp;
Jim Ingham8247e622012-06-06 00:32:39 +00001766
1767 // FIXME: InterruptIfRunning should be done in the Process base class, or better still make Halt do what is
1768 // needed. This shouldn't be a feature of a particular plugin.
1769
Greg Clayton68ca8232011-01-25 02:58:48 +00001770 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001771}
1772
1773Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001774ProcessGDBRemote::DoDetach()
1775{
1776 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001777 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001778 if (log)
1779 log->Printf ("ProcessGDBRemote::DoDetach()");
1780
1781 DisableAllBreakpointSites ();
1782
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001783 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001784
Greg Clayton516f0842012-04-11 00:24:49 +00001785 bool success = m_gdb_comm.Detach ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001786 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001787 {
Greg Clayton516f0842012-04-11 00:24:49 +00001788 if (success)
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001789 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1790 else
1791 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001792 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001793 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001794 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001795
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001796 SetPrivateState (eStateDetached);
1797 ResumePrivateStateThread();
1798
1799 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001800 return error;
1801}
Chris Lattner24943d22010-06-08 16:52:24 +00001802
Jim Ingham06b84492012-07-04 00:35:43 +00001803
Chris Lattner24943d22010-06-08 16:52:24 +00001804Error
1805ProcessGDBRemote::DoDestroy ()
1806{
1807 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001808 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001809 if (log)
1810 log->Printf ("ProcessGDBRemote::DoDestroy()");
1811
Jim Ingham06b84492012-07-04 00:35:43 +00001812 // There is a bug in older iOS debugservers where they don't shut down the process
1813 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
1814 // this can cause problems with restarting. So we check to see if any of our threads are stopped
1815 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
1816 // destroy it again.
1817 //
1818 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
1819 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
1820 // the debugservers with this bug are equal. There really should be a better way to test this!
1821 //
1822 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
1823 // get called here to destroy again and we're still at a breakpoint or exception, then we should
1824 // just do the straight-forward kill.
1825 //
1826 // And of course, if we weren't able to stop the process by the time we get here, it isn't
1827 // necessary (or helpful) to do any of this.
1828
1829 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
1830 {
1831 PlatformSP platform_sp = GetTarget().GetPlatform();
1832
1833 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
1834 if (platform_sp
1835 && platform_sp->GetName()
1836 && strcmp (platform_sp->GetName(), PlatformRemoteiOS::GetShortPluginNameStatic()) == 0)
1837 {
1838 if (m_destroy_tried_resuming)
1839 {
1840 if (log)
1841 log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again.");
1842 }
1843 else
1844 {
1845 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
1846 // but we really need it to happen here and it doesn't matter if we do it twice.
1847 m_thread_list.DiscardThreadPlans();
1848 DisableAllBreakpointSites();
1849
1850 bool stop_looks_like_crash = false;
1851 ThreadList &threads = GetThreadList();
1852
1853 {
Jim Inghamc2c65142012-09-11 00:08:52 +00001854 Mutex::Locker locker(threads.GetMutex());
Jim Ingham06b84492012-07-04 00:35:43 +00001855
1856 size_t num_threads = threads.GetSize();
1857 for (size_t i = 0; i < num_threads; i++)
1858 {
1859 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1860 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason();
1861 StopReason reason = eStopReasonInvalid;
1862 if (stop_info_sp)
1863 reason = stop_info_sp->GetStopReason();
1864 if (reason == eStopReasonBreakpoint
1865 || reason == eStopReasonException)
1866 {
1867 if (log)
1868 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: %lld stopped with reason: %s.",
1869 thread_sp->GetID(),
1870 stop_info_sp->GetDescription());
1871 stop_looks_like_crash = true;
1872 break;
1873 }
1874 }
1875 }
1876
1877 if (stop_looks_like_crash)
1878 {
1879 if (log)
1880 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
1881 m_destroy_tried_resuming = true;
1882
1883 // If we are going to run again before killing, it would be good to suspend all the threads
1884 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
1885 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
1886 // have to run the risk of letting those threads proceed a bit.
1887
1888 {
Jim Inghamc2c65142012-09-11 00:08:52 +00001889 Mutex::Locker locker(threads.GetMutex());
Jim Ingham06b84492012-07-04 00:35:43 +00001890
1891 size_t num_threads = threads.GetSize();
1892 for (size_t i = 0; i < num_threads; i++)
1893 {
1894 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1895 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason();
1896 StopReason reason = eStopReasonInvalid;
1897 if (stop_info_sp)
1898 reason = stop_info_sp->GetStopReason();
1899 if (reason != eStopReasonBreakpoint
1900 && reason != eStopReasonException)
1901 {
1902 if (log)
1903 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: %lld before running.",
1904 thread_sp->GetID());
1905 thread_sp->SetResumeState(eStateSuspended);
1906 }
1907 }
1908 }
1909 Resume ();
1910 return Destroy();
1911 }
1912 }
1913 }
1914 }
1915
Chris Lattner24943d22010-06-08 16:52:24 +00001916 // Interrupt if our inferior is running...
Jim Ingham8247e622012-06-06 00:32:39 +00001917 int exit_status = SIGABRT;
1918 std::string exit_string;
1919
Greg Claytona4881d02011-01-22 07:12:45 +00001920 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001921 {
Jim Ingham8226e942011-10-28 01:11:35 +00001922 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton72e1c782011-01-22 23:43:18 +00001923 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001924
1925 StringExtractorGDBRemote response;
1926 bool send_async = true;
Filipe Cabecinhasee188ee2012-08-22 13:25:58 +00001927 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3);
1928
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001929 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001930 {
1931 char packet_cmd = response.GetChar(0);
1932
1933 if (packet_cmd == 'W' || packet_cmd == 'X')
1934 {
Greg Clayton06709002011-12-06 04:51:14 +00001935 SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001936 ClearThreadIDList ();
Jim Ingham8247e622012-06-06 00:32:39 +00001937 exit_status = response.GetHexU8();
1938 }
1939 else
1940 {
1941 if (log)
1942 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
1943 exit_string.assign("got unexpected response to k packet: ");
1944 exit_string.append(response.GetStringRef());
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001945 }
1946 }
1947 else
1948 {
Jim Ingham8247e622012-06-06 00:32:39 +00001949 if (log)
1950 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
1951 exit_string.assign("failed to send the k packet");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001952 }
Filipe Cabecinhasee188ee2012-08-22 13:25:58 +00001953
1954 m_gdb_comm.SetPacketTimeout(old_packet_timeout);
Greg Clayton72e1c782011-01-22 23:43:18 +00001955 }
Jim Ingham8247e622012-06-06 00:32:39 +00001956 else
1957 {
1958 if (log)
1959 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
Jim Ingham5d90ade2012-07-27 23:57:19 +00001960 exit_string.assign ("killed or interrupted while attaching.");
Jim Ingham8247e622012-06-06 00:32:39 +00001961 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001962 }
Jim Ingham8247e622012-06-06 00:32:39 +00001963 else
1964 {
1965 // If we missed setting the exit status on the way out, do it here.
1966 // NB set exit status can be called multiple times, the first one sets the status.
1967 exit_string.assign("destroying when not connected to debugserver");
1968 }
1969
1970 SetExitStatus(exit_status, exit_string.c_str());
1971
Chris Lattner24943d22010-06-08 16:52:24 +00001972 StopAsyncThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001973 KillDebugserverProcess ();
1974 return error;
1975}
1976
Chris Lattner24943d22010-06-08 16:52:24 +00001977//------------------------------------------------------------------
1978// Process Queries
1979//------------------------------------------------------------------
1980
1981bool
1982ProcessGDBRemote::IsAlive ()
1983{
Greg Clayton58e844b2010-12-08 05:08:21 +00001984 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001985}
1986
Jason Molendad6b81222012-10-06 02:02:26 +00001987// For kernel debugging, we return the load address of the kernel binary as the
1988// ImageInfoAddress and we return the DynamicLoaderDarwinKernel as the GetDynamicLoader()
1989// name so the correct DynamicLoader plugin is chosen.
Chris Lattner24943d22010-06-08 16:52:24 +00001990addr_t
1991ProcessGDBRemote::GetImageInfoAddress()
1992{
Jason Molendab46937c2012-10-03 01:29:34 +00001993 if (m_kernel_load_addr != LLDB_INVALID_ADDRESS)
1994 return m_kernel_load_addr;
1995 else
1996 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner24943d22010-06-08 16:52:24 +00001997}
1998
Chris Lattner24943d22010-06-08 16:52:24 +00001999//------------------------------------------------------------------
2000// Process Memory
2001//------------------------------------------------------------------
2002size_t
2003ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2004{
2005 if (size > m_max_memory_size)
2006 {
2007 // Keep memory read sizes down to a sane limit. This function will be
2008 // called multiple times in order to complete the task by
2009 // lldb_private::Process so it is ok to do this.
2010 size = m_max_memory_size;
2011 }
2012
2013 char packet[64];
Greg Clayton851e30e2012-09-18 18:04:04 +00002014 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%llx", (uint64_t)addr, (uint64_t)size);
Chris Lattner24943d22010-06-08 16:52:24 +00002015 assert (packet_len + 1 < sizeof(packet));
2016 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00002017 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00002018 {
Greg Clayton61d043b2011-03-22 04:00:09 +00002019 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00002020 {
2021 error.Clear();
2022 return response.GetHexBytes(buf, size, '\xdd');
2023 }
Greg Clayton61d043b2011-03-22 04:00:09 +00002024 else if (response.IsErrorResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00002025 error.SetErrorString("memory read failed");
Greg Clayton61d043b2011-03-22 04:00:09 +00002026 else if (response.IsUnsupportedResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00002027 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner24943d22010-06-08 16:52:24 +00002028 else
Greg Claytonae7bebc2012-09-19 01:46:31 +00002029 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00002030 }
2031 else
2032 {
2033 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
2034 }
2035 return 0;
2036}
2037
2038size_t
2039ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2040{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00002041 if (size > m_max_memory_size)
2042 {
2043 // Keep memory read sizes down to a sane limit. This function will be
2044 // called multiple times in order to complete the task by
2045 // lldb_private::Process so it is ok to do this.
2046 size = m_max_memory_size;
2047 }
2048
Chris Lattner24943d22010-06-08 16:52:24 +00002049 StreamString packet;
Greg Clayton851e30e2012-09-18 18:04:04 +00002050 packet.Printf("M%llx,%llx:", addr, (uint64_t)size);
Greg Claytoncd548032011-02-01 01:31:41 +00002051 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00002052 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00002053 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00002054 {
Greg Clayton61d043b2011-03-22 04:00:09 +00002055 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00002056 {
2057 error.Clear();
2058 return size;
2059 }
Greg Clayton61d043b2011-03-22 04:00:09 +00002060 else if (response.IsErrorResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00002061 error.SetErrorString("memory write failed");
Greg Clayton61d043b2011-03-22 04:00:09 +00002062 else if (response.IsUnsupportedResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00002063 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner24943d22010-06-08 16:52:24 +00002064 else
Greg Claytonae7bebc2012-09-19 01:46:31 +00002065 error.SetErrorStringWithFormat("unexpected response to GDB server memory write packet '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00002066 }
2067 else
2068 {
2069 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
2070 }
2071 return 0;
2072}
2073
2074lldb::addr_t
2075ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2076{
Greg Clayton989816b2011-05-14 01:50:35 +00002077 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2078
Greg Clayton2f085c62011-05-15 01:25:55 +00002079 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00002080 switch (supported)
2081 {
2082 case eLazyBoolCalculate:
2083 case eLazyBoolYes:
2084 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2085 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2086 return allocated_addr;
2087
2088 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002089 // Call mmap() to create memory in the inferior..
2090 unsigned prot = 0;
2091 if (permissions & lldb::ePermissionsReadable)
2092 prot |= eMmapProtRead;
2093 if (permissions & lldb::ePermissionsWritable)
2094 prot |= eMmapProtWrite;
2095 if (permissions & lldb::ePermissionsExecutable)
2096 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00002097
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002098 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2099 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2100 m_addr_to_mmap_size[allocated_addr] = size;
2101 else
2102 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00002103 break;
2104 }
2105
Chris Lattner24943d22010-06-08 16:52:24 +00002106 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton851e30e2012-09-18 18:04:04 +00002107 error.SetErrorStringWithFormat("unable to allocate %llu bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00002108 else
2109 error.Clear();
2110 return allocated_addr;
2111}
2112
2113Error
Greg Claytona9385532011-11-18 07:03:08 +00002114ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2115 MemoryRegionInfo &region_info)
2116{
2117
2118 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2119 return error;
2120}
2121
2122Error
Johnny Chen7cbdcfb2012-05-23 21:09:52 +00002123ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2124{
2125
2126 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2127 return error;
2128}
2129
2130Error
Enrico Granata7de2a3b2012-07-13 23:18:48 +00002131ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2132{
2133 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2134 return error;
2135}
2136
2137Error
Chris Lattner24943d22010-06-08 16:52:24 +00002138ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2139{
2140 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00002141 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2142
2143 switch (supported)
2144 {
2145 case eLazyBoolCalculate:
2146 // We should never be deallocating memory without allocating memory
2147 // first so we should never get eLazyBoolCalculate
2148 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2149 break;
2150
2151 case eLazyBoolYes:
2152 if (!m_gdb_comm.DeallocateMemory (addr))
2153 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
2154 break;
2155
2156 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002157 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00002158 {
2159 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002160 if (pos != m_addr_to_mmap_size.end() &&
2161 InferiorCallMunmap(this, addr, pos->second))
2162 m_addr_to_mmap_size.erase (pos);
2163 else
2164 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00002165 }
2166 break;
2167 }
2168
Chris Lattner24943d22010-06-08 16:52:24 +00002169 return error;
2170}
2171
2172
2173//------------------------------------------------------------------
2174// Process STDIO
2175//------------------------------------------------------------------
Chris Lattner24943d22010-06-08 16:52:24 +00002176size_t
2177ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2178{
2179 if (m_stdio_communication.IsConnected())
2180 {
2181 ConnectionStatus status;
2182 m_stdio_communication.Write(src, src_len, status, NULL);
2183 }
2184 return 0;
2185}
2186
2187Error
2188ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
2189{
2190 Error error;
2191 assert (bp_site != NULL);
2192
Greg Claytone005f2c2010-11-06 01:53:30 +00002193 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002194 user_id_t site_id = bp_site->GetID();
2195 const addr_t addr = bp_site->GetLoadAddress();
2196 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002197 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002198
2199 if (bp_site->IsEnabled())
2200 {
2201 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002202 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002203 return error;
2204 }
2205 else
2206 {
2207 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2208
2209 if (bp_site->HardwarePreferred())
2210 {
2211 // Try and set hardware breakpoint, and if that fails, fall through
2212 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00002213 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00002214 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002215 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00002216 {
2217 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002218 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00002219 return error;
2220 }
Chris Lattner24943d22010-06-08 16:52:24 +00002221 }
2222 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002223
2224 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00002225 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002226 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
2227 {
2228 bp_site->SetEnabled(true);
2229 bp_site->SetType (BreakpointSite::eExternal);
2230 return error;
2231 }
Chris Lattner24943d22010-06-08 16:52:24 +00002232 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002233
2234 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00002235 }
2236
2237 if (log)
2238 {
2239 const char *err_string = error.AsCString();
2240 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
2241 bp_site->GetLoadAddress(),
2242 err_string ? err_string : "NULL");
2243 }
2244 // We shouldn't reach here on a successful breakpoint enable...
2245 if (error.Success())
2246 error.SetErrorToGenericError();
2247 return error;
2248}
2249
2250Error
2251ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
2252{
2253 Error error;
2254 assert (bp_site != NULL);
2255 addr_t addr = bp_site->GetLoadAddress();
2256 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00002257 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002258 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002259 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002260
2261 if (bp_site->IsEnabled())
2262 {
2263 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2264
Greg Claytonb72d0f02011-04-12 05:54:46 +00002265 BreakpointSite::Type bp_type = bp_site->GetType();
2266 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00002267 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002268 case BreakpointSite::eSoftware:
2269 error = DisableSoftwareBreakpoint (bp_site);
2270 break;
2271
2272 case BreakpointSite::eHardware:
2273 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2274 error.SetErrorToGenericError();
2275 break;
2276
2277 case BreakpointSite::eExternal:
2278 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2279 error.SetErrorToGenericError();
2280 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002281 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002282 if (error.Success())
2283 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00002284 }
2285 else
2286 {
2287 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002288 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002289 return error;
2290 }
2291
2292 if (error.Success())
2293 error.SetErrorToGenericError();
2294 return error;
2295}
2296
Johnny Chen21900fb2011-09-06 22:38:36 +00002297// Pre-requisite: wp != NULL.
2298static GDBStoppointType
Johnny Chenecd4feb2011-10-14 00:42:25 +00002299GetGDBStoppointType (Watchpoint *wp)
Johnny Chen21900fb2011-09-06 22:38:36 +00002300{
2301 assert(wp);
2302 bool watch_read = wp->WatchpointRead();
2303 bool watch_write = wp->WatchpointWrite();
2304
2305 // watch_read and watch_write cannot both be false.
2306 assert(watch_read || watch_write);
2307 if (watch_read && watch_write)
2308 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00002309 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00002310 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00002311 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00002312 return eWatchpointWrite;
2313}
2314
Chris Lattner24943d22010-06-08 16:52:24 +00002315Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002316ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002317{
2318 Error error;
2319 if (wp)
2320 {
2321 user_id_t watchID = wp->GetID();
2322 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00002323 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002324 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002325 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %llu)", watchID);
Chris Lattner24943d22010-06-08 16:52:24 +00002326 if (wp->IsEnabled())
2327 {
2328 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002329 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %llu) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002330 return error;
2331 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002332
2333 GDBStoppointType type = GetGDBStoppointType(wp);
2334 // Pass down an appropriate z/Z packet...
2335 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00002336 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002337 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2338 {
2339 wp->SetEnabled(true);
2340 return error;
2341 }
2342 else
2343 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002344 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002345 else
2346 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00002347 }
2348 else
2349 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002350 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002351 }
2352 if (error.Success())
2353 error.SetErrorToGenericError();
2354 return error;
2355}
2356
2357Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002358ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002359{
2360 Error error;
2361 if (wp)
2362 {
2363 user_id_t watchID = wp->GetID();
2364
Greg Claytone005f2c2010-11-06 01:53:30 +00002365 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002366
2367 addr_t addr = wp->GetLoadAddress();
2368 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002369 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002370
Johnny Chen21900fb2011-09-06 22:38:36 +00002371 if (!wp->IsEnabled())
2372 {
2373 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002374 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
Johnny Chen258db3a2012-08-23 22:28:26 +00002375 // See also 'class WatchpointSentry' within StopInfo.cpp.
2376 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2377 // the watchpoint object to intelligently process this action.
2378 wp->SetEnabled(false);
Johnny Chen21900fb2011-09-06 22:38:36 +00002379 return error;
2380 }
2381
Chris Lattner24943d22010-06-08 16:52:24 +00002382 if (wp->IsHardware())
2383 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002384 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00002385 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00002386 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2387 {
2388 wp->SetEnabled(false);
2389 return error;
2390 }
2391 else
2392 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002393 }
2394 // TODO: clear software watchpoints if we implement them
2395 }
2396 else
2397 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002398 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002399 }
2400 if (error.Success())
2401 error.SetErrorToGenericError();
2402 return error;
2403}
2404
2405void
2406ProcessGDBRemote::Clear()
2407{
2408 m_flags = 0;
2409 m_thread_list.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002410}
2411
2412Error
2413ProcessGDBRemote::DoSignal (int signo)
2414{
2415 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00002416 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002417 if (log)
2418 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2419
2420 if (!m_gdb_comm.SendAsyncSignal (signo))
2421 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2422 return error;
2423}
2424
Chris Lattner24943d22010-06-08 16:52:24 +00002425Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002426ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)
2427{
2428 ProcessLaunchInfo launch_info;
2429 return StartDebugserverProcess(debugserver_url, launch_info);
2430}
2431
2432Error
2433ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url, const ProcessInfo &process_info) // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
Chris Lattner24943d22010-06-08 16:52:24 +00002434{
2435 Error error;
2436 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2437 {
2438 // If we locate debugserver, keep that located version around
2439 static FileSpec g_debugserver_file_spec;
2440
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002441 ProcessLaunchInfo debugserver_launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002442 char debugserver_path[PATH_MAX];
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002443 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002444
2445 // Always check to see if we have an environment override for the path
2446 // to the debugserver to use and use it if we do.
2447 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2448 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002449 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002450 else
2451 debugserver_file_spec = g_debugserver_file_spec;
2452 bool debugserver_exists = debugserver_file_spec.Exists();
2453 if (!debugserver_exists)
2454 {
2455 // The debugserver binary is in the LLDB.framework/Resources
2456 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002457 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002458 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002459 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002460 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002461 if (debugserver_exists)
2462 {
2463 g_debugserver_file_spec = debugserver_file_spec;
2464 }
2465 else
2466 {
2467 g_debugserver_file_spec.Clear();
2468 debugserver_file_spec.Clear();
2469 }
Chris Lattner24943d22010-06-08 16:52:24 +00002470 }
2471 }
2472
2473 if (debugserver_exists)
2474 {
2475 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2476
2477 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002478
Greg Claytone005f2c2010-11-06 01:53:30 +00002479 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002480
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002481 Args &debugserver_args = debugserver_launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002482 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002483
Chris Lattner24943d22010-06-08 16:52:24 +00002484 // Start args with "debugserver /file/path -r --"
2485 debugserver_args.AppendArgument(debugserver_path);
2486 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002487 // use native registers, not the GDB registers
2488 debugserver_args.AppendArgument("--native-regs");
2489 // make debugserver run in its own session so signals generated by
2490 // special terminal key sequences (^C) don't affect debugserver
2491 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002492
Chris Lattner24943d22010-06-08 16:52:24 +00002493 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2494 if (env_debugserver_log_file)
2495 {
2496 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2497 debugserver_args.AppendArgument(arg_cstr);
2498 }
2499
2500 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2501 if (env_debugserver_log_flags)
2502 {
2503 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2504 debugserver_args.AppendArgument(arg_cstr);
2505 }
Jim Ingham2b2ac8c2012-10-03 22:31:30 +00002506// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
2507// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002508
Greg Claytonb72d0f02011-04-12 05:54:46 +00002509 // We currently send down all arguments, attach pids, or attach
2510 // process names in dedicated GDB server packets, so we don't need
2511 // to pass them as arguments. This is currently because of all the
2512 // things we need to setup prior to launching: the environment,
2513 // current working dir, file actions, etc.
2514#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002515 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002516 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002517 {
Greg Claytona2f74232011-02-24 22:24:29 +00002518 // Terminate the debugserver args so we can now append the inferior args
2519 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002520
Greg Claytona2f74232011-02-24 22:24:29 +00002521 for (int i = 0; inferior_argv[i] != NULL; ++i)
2522 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002523 }
2524 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2525 {
2526 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2527 debugserver_args.AppendArgument (arg_cstr);
2528 }
2529 else if (attach_name && attach_name[0])
2530 {
2531 if (wait_for_launch)
2532 debugserver_args.AppendArgument ("--waitfor");
2533 else
2534 debugserver_args.AppendArgument ("--attach");
2535 debugserver_args.AppendArgument (attach_name);
2536 }
Chris Lattner24943d22010-06-08 16:52:24 +00002537#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002538
2539 ProcessLaunchInfo::FileAction file_action;
2540
2541 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2542 // to "/dev/null" if we run into any problems.
2543 file_action.Close (STDIN_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002544 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002545 file_action.Close (STDOUT_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002546 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002547 file_action.Close (STDERR_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002548 debugserver_launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002549
2550 if (log)
2551 {
2552 StreamString strm;
2553 debugserver_args.Dump (&strm);
2554 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2555 }
2556
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002557 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2558 debugserver_launch_info.SetUserID(process_info.GetUserID());
Greg Clayton1c4642c2011-11-16 05:37:56 +00002559
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002560 error = Host::LaunchProcess(debugserver_launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002561
Greg Claytonb72d0f02011-04-12 05:54:46 +00002562 if (error.Success ())
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002563 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002564 else
Chris Lattner24943d22010-06-08 16:52:24 +00002565 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2566
2567 if (error.Fail() || log)
Greg Claytond9919d32011-12-01 23:28:38 +00002568 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%llu, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002569 }
2570 else
2571 {
Greg Clayton9c236732011-10-26 00:56:27 +00002572 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002573 }
2574
2575 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2576 StartAsyncThread ();
2577 }
2578 return error;
2579}
2580
2581bool
2582ProcessGDBRemote::MonitorDebugserverProcess
2583(
2584 void *callback_baton,
2585 lldb::pid_t debugserver_pid,
Greg Clayton1c4642c2011-11-16 05:37:56 +00002586 bool exited, // True if the process did exit
Chris Lattner24943d22010-06-08 16:52:24 +00002587 int signo, // Zero for no signal
2588 int exit_status // Exit value of process if signal is zero
2589)
2590{
Greg Clayton1c4642c2011-11-16 05:37:56 +00002591 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2592 // and might not exist anymore, so we need to carefully try to get the
2593 // target for this process first since we have a race condition when
2594 // we are done running between getting the notice that the inferior
2595 // process has died and the debugserver that was debugging this process.
2596 // In our test suite, we are also continually running process after
2597 // process, so we must be very careful to make sure:
2598 // 1 - process object hasn't been deleted already
2599 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner24943d22010-06-08 16:52:24 +00002600
2601 // "debugserver_pid" argument passed in is the process ID for
2602 // debugserver that we are tracking...
Greg Clayton1c4642c2011-11-16 05:37:56 +00002603 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002604
Greg Clayton75ccf502010-08-21 02:22:51 +00002605 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002606
Greg Clayton1c4642c2011-11-16 05:37:56 +00002607 // Get a shared pointer to the target that has a matching process pointer.
2608 // This target could be gone, or the target could already have a new process
2609 // object inside of it
2610 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2611
Greg Clayton72e1c782011-01-22 23:43:18 +00002612 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00002613 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%llu, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
Greg Clayton72e1c782011-01-22 23:43:18 +00002614
Greg Clayton1c4642c2011-11-16 05:37:56 +00002615 if (target_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002616 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002617 // We found a process in a target that matches, but another thread
2618 // might be in the process of launching a new process that will
2619 // soon replace it, so get a shared pointer to the process so we
2620 // can keep it alive.
2621 ProcessSP process_sp (target_sp->GetProcessSP());
2622 // Now we have a shared pointer to the process that can't go away on us
2623 // so we now make sure it was the same as the one passed in, and also make
2624 // sure that our previous "process *" didn't get deleted and have a new
2625 // "process *" created in its place with the same pointer. To verify this
2626 // we make sure the process has our debugserver process ID. If we pass all
2627 // of these tests, then we are sure that this process is the one we were
2628 // looking for.
2629 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner24943d22010-06-08 16:52:24 +00002630 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002631 // Sleep for a half a second to make sure our inferior process has
2632 // time to set its exit status before we set it incorrectly when
2633 // both the debugserver and the inferior process shut down.
2634 usleep (500000);
2635 // If our process hasn't yet exited, debugserver might have died.
2636 // If the process did exit, the we are reaping it.
2637 const StateType state = process->GetState();
2638
2639 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2640 state != eStateInvalid &&
2641 state != eStateUnloaded &&
2642 state != eStateExited &&
2643 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002644 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002645 char error_str[1024];
2646 if (signo)
2647 {
2648 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2649 if (signal_cstr)
2650 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2651 else
2652 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2653 }
Chris Lattner24943d22010-06-08 16:52:24 +00002654 else
Greg Clayton1c4642c2011-11-16 05:37:56 +00002655 {
2656 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2657 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002658
Greg Clayton1c4642c2011-11-16 05:37:56 +00002659 process->SetExitStatus (-1, error_str);
2660 }
2661 // Debugserver has exited we need to let our ProcessGDBRemote
2662 // know that it no longer has a debugserver instance
2663 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton75ccf502010-08-21 02:22:51 +00002664 }
Chris Lattner24943d22010-06-08 16:52:24 +00002665 }
2666 return true;
2667}
2668
2669void
2670ProcessGDBRemote::KillDebugserverProcess ()
2671{
2672 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2673 {
2674 ::kill (m_debugserver_pid, SIGINT);
2675 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2676 }
2677}
2678
2679void
2680ProcessGDBRemote::Initialize()
2681{
2682 static bool g_initialized = false;
2683
2684 if (g_initialized == false)
2685 {
2686 g_initialized = true;
2687 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2688 GetPluginDescriptionStatic(),
2689 CreateInstance);
2690
2691 Log::Callbacks log_callbacks = {
2692 ProcessGDBRemoteLog::DisableLog,
2693 ProcessGDBRemoteLog::EnableLog,
2694 ProcessGDBRemoteLog::ListLogCategories
2695 };
2696
2697 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2698 }
2699}
2700
2701bool
Chris Lattner24943d22010-06-08 16:52:24 +00002702ProcessGDBRemote::StartAsyncThread ()
2703{
Greg Claytone005f2c2010-11-06 01:53:30 +00002704 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002705
2706 if (log)
2707 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2708
2709 // Create a thread that watches our internal state and controls which
2710 // events make it to clients (into the DCProcess event queue).
2711 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002712 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002713}
2714
2715void
2716ProcessGDBRemote::StopAsyncThread ()
2717{
Greg Claytone005f2c2010-11-06 01:53:30 +00002718 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002719
2720 if (log)
2721 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2722
2723 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
Jim Ingham8226e942011-10-28 01:11:35 +00002724
2725 // This will shut down the async thread.
2726 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00002727
2728 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002729 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002730 {
2731 Host::ThreadJoin (m_async_thread, NULL, NULL);
2732 }
2733}
2734
2735
2736void *
2737ProcessGDBRemote::AsyncThread (void *arg)
2738{
2739 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2740
Greg Claytone005f2c2010-11-06 01:53:30 +00002741 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002742 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002743 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002744
2745 Listener listener ("ProcessGDBRemote::AsyncThread");
2746 EventSP event_sp;
2747 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2748 eBroadcastBitAsyncThreadShouldExit;
2749
2750 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2751 {
Greg Claytona2f74232011-02-24 22:24:29 +00002752 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2753
Chris Lattner24943d22010-06-08 16:52:24 +00002754 bool done = false;
2755 while (!done)
2756 {
2757 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002758 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002759 if (listener.WaitForEvent (NULL, event_sp))
2760 {
2761 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002762 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002763 {
Greg Claytona2f74232011-02-24 22:24:29 +00002764 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002765 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
Chris Lattner24943d22010-06-08 16:52:24 +00002766
Greg Claytona2f74232011-02-24 22:24:29 +00002767 switch (event_type)
2768 {
2769 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002770 {
Greg Claytona2f74232011-02-24 22:24:29 +00002771 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002772
Greg Claytona2f74232011-02-24 22:24:29 +00002773 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002774 {
Greg Claytona2f74232011-02-24 22:24:29 +00002775 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2776 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2777 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002778 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002779
Greg Claytona2f74232011-02-24 22:24:29 +00002780 if (::strstr (continue_cstr, "vAttach") == NULL)
2781 process->SetPrivateState(eStateRunning);
2782 StringExtractorGDBRemote response;
2783 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002784
Greg Clayton67b402c2012-05-16 02:48:06 +00002785 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
2786 // The thread ID list might be contained within the "response", or the stop reply packet that
2787 // caused the stop. So clear it now before we give the stop reply packet to the process
2788 // using the process->SetLastStopPacket()...
2789 process->ClearThreadIDList ();
2790
Greg Claytona2f74232011-02-24 22:24:29 +00002791 switch (stop_state)
2792 {
2793 case eStateStopped:
2794 case eStateCrashed:
2795 case eStateSuspended:
Greg Clayton06709002011-12-06 04:51:14 +00002796 process->SetLastStopPacket (response);
Greg Claytona2f74232011-02-24 22:24:29 +00002797 process->SetPrivateState (stop_state);
2798 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002799
Greg Claytona2f74232011-02-24 22:24:29 +00002800 case eStateExited:
Greg Clayton06709002011-12-06 04:51:14 +00002801 process->SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00002802 process->ClearThreadIDList();
Greg Claytona2f74232011-02-24 22:24:29 +00002803 response.SetFilePos(1);
2804 process->SetExitStatus(response.GetHexU8(), NULL);
2805 done = true;
2806 break;
2807
2808 case eStateInvalid:
2809 process->SetExitStatus(-1, "lost connection");
2810 break;
2811
2812 default:
2813 process->SetPrivateState (stop_state);
2814 break;
2815 }
Chris Lattner24943d22010-06-08 16:52:24 +00002816 }
2817 }
Greg Claytona2f74232011-02-24 22:24:29 +00002818 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002819
Greg Claytona2f74232011-02-24 22:24:29 +00002820 case eBroadcastBitAsyncThreadShouldExit:
2821 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002822 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Claytona2f74232011-02-24 22:24:29 +00002823 done = true;
2824 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002825
Greg Claytona2f74232011-02-24 22:24:29 +00002826 default:
2827 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002828 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
Greg Claytona2f74232011-02-24 22:24:29 +00002829 done = true;
2830 break;
2831 }
2832 }
2833 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2834 {
2835 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2836 {
2837 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002838 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002839 }
Chris Lattner24943d22010-06-08 16:52:24 +00002840 }
2841 }
2842 else
2843 {
2844 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002845 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002846 done = true;
2847 }
2848 }
2849 }
2850
2851 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002852 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002853
2854 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2855 return NULL;
2856}
2857
Chris Lattner24943d22010-06-08 16:52:24 +00002858const char *
2859ProcessGDBRemote::GetDispatchQueueNameForThread
2860(
2861 addr_t thread_dispatch_qaddr,
2862 std::string &dispatch_queue_name
2863)
2864{
2865 dispatch_queue_name.clear();
2866 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2867 {
2868 // Cache the dispatch_queue_offsets_addr value so we don't always have
2869 // to look it up
2870 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2871 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002872 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2873 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton444fe992012-02-26 05:51:37 +00002874 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false));
2875 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002876 if (module_sp)
2877 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2878
2879 if (dispatch_queue_offsets_symbol == NULL)
2880 {
Greg Clayton444fe992012-02-26 05:51:37 +00002881 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false));
2882 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_module_spec);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002883 if (module_sp)
2884 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2885 }
Chris Lattner24943d22010-06-08 16:52:24 +00002886 if (dispatch_queue_offsets_symbol)
Greg Clayton0c31d3d2012-03-07 21:03:09 +00002887 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002888
2889 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2890 return NULL;
2891 }
2892
2893 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002894 DataExtractor data (memory_buffer,
2895 sizeof(memory_buffer),
2896 m_target.GetArchitecture().GetByteOrder(),
2897 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002898
2899 // Excerpt from src/queue_private.h
2900 struct dispatch_queue_offsets_s
2901 {
2902 uint16_t dqo_version;
2903 uint16_t dqo_label;
2904 uint16_t dqo_label_size;
2905 } dispatch_queue_offsets;
2906
2907
2908 Error error;
2909 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2910 {
2911 uint32_t data_offset = 0;
2912 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2913 {
2914 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2915 {
2916 data_offset = 0;
2917 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2918 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2919 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2920 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2921 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2922 dispatch_queue_name.erase (bytes_read);
2923 }
2924 }
2925 }
2926 }
2927 if (dispatch_queue_name.empty())
2928 return NULL;
2929 return dispatch_queue_name.c_str();
2930}
2931
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002932//uint32_t
2933//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2934//{
2935// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2936// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2937// if (m_local_debugserver)
2938// {
2939// return Host::ListProcessesMatchingName (name, matches, pids);
2940// }
2941// else
2942// {
2943// // FIXME: Implement talking to the remote debugserver.
2944// return 0;
2945// }
2946//
2947//}
2948//
Jim Ingham55e01d82011-01-22 01:33:44 +00002949bool
2950ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2951 lldb_private::StoppointCallbackContext *context,
2952 lldb::user_id_t break_id,
2953 lldb::user_id_t break_loc_id)
2954{
2955 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2956 // run so I can stop it if that's what I want to do.
2957 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2958 if (log)
2959 log->Printf("Hit New Thread Notification breakpoint.");
2960 return false;
2961}
2962
2963
2964bool
2965ProcessGDBRemote::StartNoticingNewThreads()
2966{
Jim Ingham55e01d82011-01-22 01:33:44 +00002967 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002968 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00002969 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002970 if (log && log->GetVerbose())
2971 log->Printf("Enabled noticing new thread breakpoint.");
2972 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham55e01d82011-01-22 01:33:44 +00002973 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002974 else
Jim Ingham55e01d82011-01-22 01:33:44 +00002975 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002976 PlatformSP platform_sp (m_target.GetPlatform());
2977 if (platform_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00002978 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002979 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
2980 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00002981 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002982 if (log && log->GetVerbose())
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002983 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
2984 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham55e01d82011-01-22 01:33:44 +00002985 }
2986 else
2987 {
2988 if (log)
2989 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002990 }
2991 }
2992 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002993 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham55e01d82011-01-22 01:33:44 +00002994}
2995
2996bool
2997ProcessGDBRemote::StopNoticingNewThreads()
2998{
Jim Inghamff276fe2011-02-08 05:19:01 +00002999 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham6bb73372011-10-15 00:21:37 +00003000 if (log && log->GetVerbose())
Jim Inghamff276fe2011-02-08 05:19:01 +00003001 log->Printf ("Disabling new thread notification breakpoint.");
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003002
3003 if (m_thread_create_bp_sp)
3004 m_thread_create_bp_sp->SetEnabled(false);
3005
Jim Ingham55e01d82011-01-22 01:33:44 +00003006 return true;
3007}
3008
Jason Molendab46937c2012-10-03 01:29:34 +00003009lldb_private::DynamicLoader *
3010ProcessGDBRemote::GetDynamicLoader ()
3011{
3012 if (m_dyld_ap.get() == NULL)
3013 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, m_dyld_plugin_name.empty() ? NULL : m_dyld_plugin_name.c_str()));
3014 return m_dyld_ap.get();
3015}
Jim Ingham55e01d82011-01-22 01:33:44 +00003016
Greg Clayton13193d52012-10-13 02:07:45 +00003017#include "lldb/Interpreter/CommandObject.h"
3018#include "lldb/Interpreter/CommandObjectMultiword.h"
3019
3020class CommandObjectProcessGDBRemotePacket : public CommandObjectParsed
3021{
3022private:
3023
3024public:
3025 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
3026 CommandObjectParsed (interpreter,
3027 "process plugin packet",
3028 "Send a custom packet through the GDB remote protocol and print the answer.",
3029 NULL)
3030 {
3031 }
3032
3033 ~CommandObjectProcessGDBRemotePacket ()
3034 {
3035 }
3036
3037 bool
3038 DoExecute (Args& command, CommandReturnObject &result)
3039 {
3040 printf ("CommandObjectProcessGDBRemotePacket::DoExecute() called!!!\n");
3041 return true;
3042 }
3043};
3044
3045
3046class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
3047{
3048public:
3049 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
3050 CommandObjectMultiword (interpreter,
3051 "process plugin",
3052 "A set of commands for operating on a ProcessGDBRemote process.",
3053 "process plugin <subcommand> [<subcommand-options>]")
3054 {
3055 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
3056 }
3057
3058 ~CommandObjectMultiwordProcessGDBRemote ()
3059 {
3060 }
3061};
3062
3063
3064
3065CommandObject *
3066ProcessGDBRemote::GetPluginCommandObject()
3067{
3068 if (!m_command_sp)
3069 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
3070 return m_command_sp.get();
3071}