blob: 1b3ebc7bcceae9ab9ccc65780aafbfd637252e2c [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"
Greg Claytonb8596392012-10-15 22:42:16 +000043#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton307c7fd2012-10-19 22:22:57 +000044#include "lldb/Interpreter/CommandObject.h"
45#include "lldb/Interpreter/CommandObjectMultiword.h"
Greg Claytonb8596392012-10-15 22:42:16 +000046#include "lldb/Interpreter/CommandReturnObject.h"
Chris Lattner24943d22010-06-08 16:52:24 +000047#include "lldb/Symbol/ObjectFile.h"
48#include "lldb/Target/DynamicLoader.h"
49#include "lldb/Target/Target.h"
50#include "lldb/Target/TargetList.h"
Greg Clayton989816b2011-05-14 01:50:35 +000051#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molendadea5ea72010-06-09 21:28:42 +000052#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner24943d22010-06-08 16:52:24 +000053
54// Project includes
55#include "lldb/Host/Host.h"
Peter Collingbourne4d623e82011-06-03 20:40:38 +000056#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Jason Molenda3aeb2862012-07-25 03:40:06 +000057#include "Plugins/Process/Utility/StopInfoMachException.h"
Jim Ingham06b84492012-07-04 00:35:43 +000058#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
Greg Clayton54e7afa2010-07-09 20:39:50 +000059#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner24943d22010-06-08 16:52:24 +000060#include "GDBRemoteRegisterContext.h"
61#include "ProcessGDBRemote.h"
62#include "ProcessGDBRemoteLog.h"
63#include "ThreadGDBRemote.h"
Greg Clayton643ee732010-08-04 01:40:35 +000064
Jason Molendab46937c2012-10-03 01:29:34 +000065#include "Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.h"
66
Greg Clayton451fa822012-04-09 22:46:21 +000067namespace lldb
68{
69 // Provide a function that can easily dump the packet history if we know a
70 // ProcessGDBRemote * value (which we can get from logs or from debugging).
71 // We need the function in the lldb namespace so it makes it into the final
72 // executable since the LLDB shared library only exports stuff in the lldb
73 // namespace. This allows you to attach with a debugger and call this
74 // function and get the packet history dumped to a file.
75 void
76 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
77 {
Greg Clayton33559462012-04-13 21:24:18 +000078 lldb_private::StreamFile strm;
79 lldb_private::Error error (strm.GetFile().Open(path, lldb_private::File::eOpenOptionWrite | lldb_private::File::eOpenOptionCanCreate));
80 if (error.Success())
81 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
Greg Clayton451fa822012-04-09 22:46:21 +000082 }
Filipe Cabecinhas021086a2012-05-23 16:27:09 +000083}
Chris Lattner24943d22010-06-08 16:52:24 +000084
Chris Lattner24943d22010-06-08 16:52:24 +000085
86#define DEBUGSERVER_BASENAME "debugserver"
87using namespace lldb;
88using namespace lldb_private;
89
Jim Inghamf9600482011-03-29 21:45:47 +000090static bool rand_initialized = false;
91
Sean Callanan483d00a2012-07-19 18:07:36 +000092// TODO Randomly assigning a port is unsafe. We should get an unused
93// ephemeral port from the kernel and make sure we reserve it before passing
94// it to debugserver.
95
96#if defined (__APPLE__)
97#define LOW_PORT (IPPORT_RESERVED)
98#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
99#else
100#define LOW_PORT (1024u)
101#define HIGH_PORT (49151u)
102#endif
103
Chris Lattner24943d22010-06-08 16:52:24 +0000104static inline uint16_t
105get_random_port ()
106{
Jim Inghamf9600482011-03-29 21:45:47 +0000107 if (!rand_initialized)
108 {
Stephen Wilson60f19d52011-03-30 00:12:40 +0000109 time_t seed = time(NULL);
110
Jim Inghamf9600482011-03-29 21:45:47 +0000111 rand_initialized = true;
Stephen Wilson60f19d52011-03-30 00:12:40 +0000112 srand(seed);
Jim Inghamf9600482011-03-29 21:45:47 +0000113 }
Sean Callanan483d00a2012-07-19 18:07:36 +0000114 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
Chris Lattner24943d22010-06-08 16:52:24 +0000115}
116
117
118const char *
119ProcessGDBRemote::GetPluginNameStatic()
120{
Greg Claytonb1888f22011-03-19 01:12:21 +0000121 return "gdb-remote";
Chris Lattner24943d22010-06-08 16:52:24 +0000122}
123
124const char *
125ProcessGDBRemote::GetPluginDescriptionStatic()
126{
127 return "GDB Remote protocol based debugging plug-in.";
128}
129
130void
131ProcessGDBRemote::Terminate()
132{
133 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
134}
135
136
Greg Clayton46c9a352012-02-09 06:16:32 +0000137lldb::ProcessSP
138ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner24943d22010-06-08 16:52:24 +0000139{
Greg Clayton46c9a352012-02-09 06:16:32 +0000140 lldb::ProcessSP process_sp;
141 if (crash_file_path == NULL)
142 process_sp.reset (new ProcessGDBRemote (target, listener));
143 return process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000144}
145
146bool
Greg Clayton8d2ea282011-07-17 20:36:25 +0000147ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
Chris Lattner24943d22010-06-08 16:52:24 +0000148{
Greg Clayton61ddf562011-10-21 21:41:45 +0000149 if (plugin_specified_by_name)
150 return true;
151
Chris Lattner24943d22010-06-08 16:52:24 +0000152 // For now we are just making sure the file exists for a given module
Greg Clayton5beb99d2011-08-11 02:48:45 +0000153 Module *exe_module = target.GetExecutableModulePointer();
154 if (exe_module)
Greg Clayton46c9a352012-02-09 06:16:32 +0000155 {
156 ObjectFile *exe_objfile = exe_module->GetObjectFile();
157 // We can't debug core files...
158 switch (exe_objfile->GetType())
159 {
160 case ObjectFile::eTypeInvalid:
161 case ObjectFile::eTypeCoreFile:
162 case ObjectFile::eTypeDebugInfo:
163 case ObjectFile::eTypeObjectFile:
164 case ObjectFile::eTypeSharedLibrary:
165 case ObjectFile::eTypeStubLibrary:
166 return false;
167 case ObjectFile::eTypeExecutable:
168 case ObjectFile::eTypeDynamicLinker:
169 case ObjectFile::eTypeUnknown:
170 break;
171 }
Greg Clayton5beb99d2011-08-11 02:48:45 +0000172 return exe_module->GetFileSpec().Exists();
Greg Clayton46c9a352012-02-09 06:16:32 +0000173 }
Jim Ingham7508e732010-08-09 23:31:02 +0000174 // However, if there is no executable module, we return true since we might be preparing to attach.
175 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000176}
177
178//----------------------------------------------------------------------
179// ProcessGDBRemote constructor
180//----------------------------------------------------------------------
181ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
182 Process (target, listener),
Chris Lattner24943d22010-06-08 16:52:24 +0000183 m_flags (0),
Greg Claytonb72d0f02011-04-12 05:54:46 +0000184 m_gdb_comm(false),
Chris Lattner24943d22010-06-08 16:52:24 +0000185 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000186 m_last_stop_packet (),
Greg Clayton06709002011-12-06 04:51:14 +0000187 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
Chris Lattner24943d22010-06-08 16:52:24 +0000188 m_register_info (),
Jim Ingham5a15e692012-02-16 06:50:00 +0000189 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
Chris Lattner24943d22010-06-08 16:52:24 +0000190 m_async_thread (LLDB_INVALID_HOST_THREAD),
Greg Clayton5a9f85c2012-04-10 02:25:43 +0000191 m_thread_ids (),
Greg Claytonc1f45872011-02-12 06:28:37 +0000192 m_continue_c_tids (),
193 m_continue_C_tids (),
194 m_continue_s_tids (),
195 m_continue_S_tids (),
Chris Lattner24943d22010-06-08 16:52:24 +0000196 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000197 m_max_memory_size (512),
Greg Claytonbd5c23d2012-05-15 02:33:01 +0000198 m_addr_to_mmap_size (),
199 m_thread_create_bp_sp (),
Jim Ingham06b84492012-07-04 00:35:43 +0000200 m_waiting_for_attach (false),
Jason Molendab46937c2012-10-03 01:29:34 +0000201 m_destroy_tried_resuming (false),
202 m_dyld_plugin_name(),
Greg Clayton13193d52012-10-13 02:07:45 +0000203 m_kernel_load_addr (LLDB_INVALID_ADDRESS),
204 m_command_sp ()
Chris Lattner24943d22010-06-08 16:52:24 +0000205{
Greg Claytonff39f742011-04-01 00:29:43 +0000206 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
207 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +0000208 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Chris Lattner24943d22010-06-08 16:52:24 +0000209}
210
211//----------------------------------------------------------------------
212// Destructor
213//----------------------------------------------------------------------
214ProcessGDBRemote::~ProcessGDBRemote()
215{
216 // m_mach_process.UnregisterNotificationCallbacks (this);
217 Clear();
Greg Clayton2f57db02011-10-01 00:45:15 +0000218 // We need to call finalize on the process before destroying ourselves
219 // to make sure all of the broadcaster cleanup goes as planned. If we
220 // destruct this class, then Process::~Process() might have problems
221 // trying to fully destroy the broadcaster.
222 Finalize();
Chris Lattner24943d22010-06-08 16:52:24 +0000223}
224
225//----------------------------------------------------------------------
226// PluginInterface
227//----------------------------------------------------------------------
228const char *
229ProcessGDBRemote::GetPluginName()
230{
231 return "Process debugging plug-in that uses the GDB remote protocol";
232}
233
234const char *
235ProcessGDBRemote::GetShortPluginName()
236{
237 return GetPluginNameStatic();
238}
239
240uint32_t
241ProcessGDBRemote::GetPluginVersion()
242{
243 return 1;
244}
245
246void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000247ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000248{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000249 if (!force && m_register_info.GetNumRegisters() > 0)
250 return;
251
252 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000253 m_register_info.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000254 uint32_t reg_offset = 0;
255 uint32_t reg_num = 0;
Greg Clayton4a379b12012-07-17 03:23:13 +0000256 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Greg Clayton61d043b2011-03-22 04:00:09 +0000257 response_type == StringExtractorGDBRemote::eResponse;
258 ++reg_num)
Chris Lattner24943d22010-06-08 16:52:24 +0000259 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000260 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
261 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000262 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000263 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000264 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000265 response_type = response.GetResponseType();
266 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner24943d22010-06-08 16:52:24 +0000267 {
268 std::string name;
269 std::string value;
270 ConstString reg_name;
271 ConstString alt_name;
272 ConstString set_name;
273 RegisterInfo reg_info = { NULL, // Name
274 NULL, // Alt name
275 0, // byte size
276 reg_offset, // offset
277 eEncodingUint, // encoding
278 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000279 {
280 LLDB_INVALID_REGNUM, // GCC reg num
281 LLDB_INVALID_REGNUM, // DWARF reg num
282 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000283 reg_num, // GDB reg num
284 reg_num // native register number
Greg Claytoncd330422012-02-29 19:27:27 +0000285 },
286 NULL,
287 NULL
Chris Lattner24943d22010-06-08 16:52:24 +0000288 };
289
290 while (response.GetNameColonValue(name, value))
291 {
292 if (name.compare("name") == 0)
293 {
294 reg_name.SetCString(value.c_str());
295 }
296 else if (name.compare("alt-name") == 0)
297 {
298 alt_name.SetCString(value.c_str());
299 }
300 else if (name.compare("bitsize") == 0)
301 {
302 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
303 }
304 else if (name.compare("offset") == 0)
305 {
306 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000307 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000308 {
309 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000310 }
311 }
312 else if (name.compare("encoding") == 0)
313 {
Greg Clayton88b980b2012-08-24 01:42:50 +0000314 const Encoding encoding = Args::StringToEncoding (value.c_str());
315 if (encoding != eEncodingInvalid)
316 reg_info.encoding = encoding;
Chris Lattner24943d22010-06-08 16:52:24 +0000317 }
318 else if (name.compare("format") == 0)
319 {
Greg Clayton88b980b2012-08-24 01:42:50 +0000320 Format format = eFormatInvalid;
321 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
322 reg_info.format = format;
323 else if (value.compare("binary") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +0000324 reg_info.format = eFormatBinary;
325 else if (value.compare("decimal") == 0)
326 reg_info.format = eFormatDecimal;
327 else if (value.compare("hex") == 0)
328 reg_info.format = eFormatHex;
329 else if (value.compare("float") == 0)
330 reg_info.format = eFormatFloat;
331 else if (value.compare("vector-sint8") == 0)
332 reg_info.format = eFormatVectorOfSInt8;
333 else if (value.compare("vector-uint8") == 0)
334 reg_info.format = eFormatVectorOfUInt8;
335 else if (value.compare("vector-sint16") == 0)
336 reg_info.format = eFormatVectorOfSInt16;
337 else if (value.compare("vector-uint16") == 0)
338 reg_info.format = eFormatVectorOfUInt16;
339 else if (value.compare("vector-sint32") == 0)
340 reg_info.format = eFormatVectorOfSInt32;
341 else if (value.compare("vector-uint32") == 0)
342 reg_info.format = eFormatVectorOfUInt32;
343 else if (value.compare("vector-float32") == 0)
344 reg_info.format = eFormatVectorOfFloat32;
345 else if (value.compare("vector-uint128") == 0)
346 reg_info.format = eFormatVectorOfUInt128;
347 }
348 else if (name.compare("set") == 0)
349 {
350 set_name.SetCString(value.c_str());
351 }
352 else if (name.compare("gcc") == 0)
353 {
354 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
355 }
356 else if (name.compare("dwarf") == 0)
357 {
358 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
359 }
360 else if (name.compare("generic") == 0)
361 {
Greg Clayton88b980b2012-08-24 01:42:50 +0000362 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000363 }
364 }
365
Jason Molenda53d96862010-06-11 23:44:18 +0000366 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000367 assert (reg_info.byte_size != 0);
368 reg_offset += reg_info.byte_size;
369 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
370 }
371 }
372 else
373 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000374 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000375 }
376 }
377
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000378 // We didn't get anything if the accumulated reg_num is zero. See if we are
379 // debugging ARM and fill with a hard coded register set until we can get an
380 // updated debugserver down on the devices.
381 // On the other hand, if the accumulated reg_num is positive, see if we can
382 // add composite registers to the existing primordial ones.
383 bool from_scratch = (reg_num == 0);
384
385 const ArchSpec &target_arch = GetTarget().GetArchitecture();
386 const ArchSpec &remote_arch = m_gdb_comm.GetHostArchitecture();
387 if (!target_arch.IsValid())
Chris Lattner24943d22010-06-08 16:52:24 +0000388 {
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000389 if (remote_arch.IsValid()
390 && remote_arch.GetMachine() == llvm::Triple::arm
391 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
392 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner24943d22010-06-08 16:52:24 +0000393 }
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000394 else if (target_arch.GetMachine() == llvm::Triple::arm)
395 {
396 m_register_info.HardcodeARMRegisters(from_scratch);
397 }
398
Johnny Chend2e30662012-05-22 00:57:05 +0000399 // Add some convenience registers (eax, ebx, ecx, edx, esi, edi, ebp, esp) to x86_64.
Johnny Chenbe315a62012-06-08 19:06:28 +0000400 if ((target_arch.IsValid() && target_arch.GetMachine() == llvm::Triple::x86_64)
401 || (remote_arch.IsValid() && remote_arch.GetMachine() == llvm::Triple::x86_64))
Johnny Chend2e30662012-05-22 00:57:05 +0000402 m_register_info.Addx86_64ConvenienceRegisters();
403
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000404 // At this point, we can finalize our register info.
Chris Lattner24943d22010-06-08 16:52:24 +0000405 m_register_info.Finalize ();
406}
407
408Error
409ProcessGDBRemote::WillLaunch (Module* module)
410{
411 return WillLaunchOrAttach ();
412}
413
414Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000415ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000416{
417 return WillLaunchOrAttach ();
418}
419
420Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000421ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000422{
423 return WillLaunchOrAttach ();
424}
425
426Error
Jason Molendafac2e622012-09-29 04:02:01 +0000427ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytone71e2582011-02-04 01:58:07 +0000428{
429 Error error (WillLaunchOrAttach ());
430
431 if (error.Fail())
432 return error;
433
Greg Clayton180546b2011-04-30 01:09:13 +0000434 error = ConnectToDebugserver (remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000435
436 if (error.Fail())
437 return error;
438 StartAsyncThread ();
439
Jason Molendab46937c2012-10-03 01:29:34 +0000440 CheckForKernel (strm);
Jason Molendafac2e622012-09-29 04:02:01 +0000441
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000442 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000443 if (pid == LLDB_INVALID_PROCESS_ID)
444 {
445 // We don't have a valid process ID, so note that we are connected
446 // and could now request to launch or attach, or get remote process
447 // listings...
448 SetPrivateState (eStateConnected);
449 }
450 else
451 {
452 // We have a valid process
453 SetID (pid);
Greg Clayton37f962e2011-08-22 02:49:39 +0000454 GetThreadList();
Greg Clayton261a18b2011-06-02 22:22:38 +0000455 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000456 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000457 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytone71e2582011-02-04 01:58:07 +0000458 if (state == eStateStopped)
459 {
460 SetPrivateState (state);
461 }
462 else
Greg Claytond9919d32011-12-01 23:28:38 +0000463 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 +0000464 }
465 else
Greg Claytond9919d32011-12-01 23:28:38 +0000466 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 +0000467 }
Jason Molendacb740b32012-05-03 22:37:30 +0000468
469 if (error.Success()
470 && !GetTarget().GetArchitecture().IsValid()
471 && m_gdb_comm.GetHostArchitecture().IsValid())
472 {
473 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
474 }
475
Greg Claytone71e2582011-02-04 01:58:07 +0000476 return error;
477}
478
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000479// When we are establishing a connection to a remote system and we have no executable specified,
480// or the executable is a kernel, we may be looking at a KASLR situation (where the kernel has been
481// slid in memory.)
482//
Jason Molendab46937c2012-10-03 01:29:34 +0000483// This function tries to locate the kernel in memory if this is possibly a kernel debug session.
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000484//
Jason Molendab46937c2012-10-03 01:29:34 +0000485// If a kernel is found, return the address of the kernel in GetImageInfoAddress() -- the
486// DynamicLoaderDarwinKernel plugin uses this address as the kernel load address and will load the
487// binary, if needed, along with all the kexts.
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000488
489void
Jason Molendab46937c2012-10-03 01:29:34 +0000490ProcessGDBRemote::CheckForKernel (Stream *strm)
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000491{
492 // early return if this isn't an "unknown" system (kernel debugging doesn't have a system type)
493 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
494 if (!gdb_remote_arch.IsValid() || gdb_remote_arch.GetTriple().getVendor() != llvm::Triple::UnknownVendor)
495 return;
496
497 Module *exe_module = GetTarget().GetExecutableModulePointer();
498 ObjectFile *exe_objfile = NULL;
499 if (exe_module)
500 exe_objfile = exe_module->GetObjectFile();
501
502 // early return if we have an executable and it is not a kernel--this is very unlikely to be a kernel debug session.
503 if (exe_objfile
504 && (exe_objfile->GetType() != ObjectFile::eTypeExecutable
505 || exe_objfile->GetStrata() != ObjectFile::eStrataKernel))
506 return;
507
508 // See if the kernel is in memory at the File address (slide == 0) -- no work needed, if so.
509 if (exe_objfile && exe_objfile->GetHeaderAddress().IsValid())
510 {
511 ModuleSP memory_module_sp;
512 memory_module_sp = ReadModuleFromMemory (exe_module->GetFileSpec(), exe_objfile->GetHeaderAddress().GetFileAddress(), false, false);
513 if (memory_module_sp.get()
514 && memory_module_sp->GetUUID().IsValid()
515 && memory_module_sp->GetUUID() == exe_module->GetUUID())
516 {
Jason Molendab46937c2012-10-03 01:29:34 +0000517 m_kernel_load_addr = exe_objfile->GetHeaderAddress().GetFileAddress();
518 m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
Jason Molendad6b81222012-10-06 02:02:26 +0000519 SetCanJIT(false);
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000520 return;
521 }
522 }
523
524 // See if the kernel's load address is stored in the kernel's low globals page; this is
525 // done when a debug boot-arg has been set.
526
527 Error error;
528 uint8_t buf[24];
529 ModuleSP memory_module_sp;
530 addr_t kernel_addr = LLDB_INVALID_ADDRESS;
531
532 // First try the 32-bit
533 if (memory_module_sp.get() == NULL)
534 {
535 DataExtractor data4 (buf, sizeof(buf), gdb_remote_arch.GetByteOrder(), 4);
536 if (DoReadMemory (0xffff0110, buf, 4, error) == 4)
537 {
538 uint32_t offset = 0;
539 kernel_addr = data4.GetU32(&offset);
540 memory_module_sp = ReadModuleFromMemory (FileSpec("mach_kernel", false), kernel_addr, false, false);
541 if (!memory_module_sp.get()
542 || !memory_module_sp->GetUUID().IsValid()
543 || memory_module_sp->GetObjectFile() == NULL
544 || memory_module_sp->GetObjectFile()->GetType() != ObjectFile::eTypeExecutable
545 || memory_module_sp->GetObjectFile()->GetStrata() != ObjectFile::eStrataKernel)
546 {
547 memory_module_sp.reset();
548 }
549 }
550 }
551
552 // Now try the 64-bit location
553 if (memory_module_sp.get() == NULL)
554 {
555 DataExtractor data8 (buf, sizeof(buf), gdb_remote_arch.GetByteOrder(), 8);
556 if (DoReadMemory (0xffffff8000002010ULL, buf, 8, error) == 8)
557 {
558 uint32_t offset = 0;
559 kernel_addr = data8.GetU32(&offset);
560 memory_module_sp = ReadModuleFromMemory (FileSpec("mach_kernel", false), kernel_addr, false, false);
561 if (!memory_module_sp.get()
562 || !memory_module_sp->GetUUID().IsValid()
563 || memory_module_sp->GetObjectFile() == NULL
564 || memory_module_sp->GetObjectFile()->GetType() != ObjectFile::eTypeExecutable
565 || memory_module_sp->GetObjectFile()->GetStrata() != ObjectFile::eStrataKernel)
566 {
567 memory_module_sp.reset();
568 }
569 }
570 }
571
Jason Molendab46937c2012-10-03 01:29:34 +0000572 if (memory_module_sp.get()
573 && memory_module_sp->GetArchitecture().IsValid()
574 && memory_module_sp->GetArchitecture().GetTriple().getVendor() == llvm::Triple::Apple)
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000575 {
Jason Molendab46937c2012-10-03 01:29:34 +0000576 m_kernel_load_addr = kernel_addr;
577 m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
Jason Molendad6b81222012-10-06 02:02:26 +0000578 SetCanJIT(false);
Jason Molendab46937c2012-10-03 01:29:34 +0000579 return;
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000580 }
581}
582
Greg Claytone71e2582011-02-04 01:58:07 +0000583Error
Chris Lattner24943d22010-06-08 16:52:24 +0000584ProcessGDBRemote::WillLaunchOrAttach ()
585{
586 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000587 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000588 return error;
589}
590
591//----------------------------------------------------------------------
592// Process Control
593//----------------------------------------------------------------------
594Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000595ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000596{
Greg Clayton4b407112010-09-30 21:49:03 +0000597 Error error;
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000598
599 uint32_t launch_flags = launch_info.GetFlags().Get();
600 const char *stdin_path = NULL;
601 const char *stdout_path = NULL;
602 const char *stderr_path = NULL;
603 const char *working_dir = launch_info.GetWorkingDirectory();
604
605 const ProcessLaunchInfo::FileAction *file_action;
606 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
607 if (file_action)
608 {
609 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
610 stdin_path = file_action->GetPath();
611 }
612 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
613 if (file_action)
614 {
615 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
616 stdout_path = file_action->GetPath();
617 }
618 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
619 if (file_action)
620 {
621 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
622 stderr_path = file_action->GetPath();
623 }
624
Chris Lattner24943d22010-06-08 16:52:24 +0000625 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
626 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
627 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton716cefb2011-08-09 05:20:29 +0000628 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000629
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000630 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner24943d22010-06-08 16:52:24 +0000631 if (object_file)
632 {
Chris Lattner24943d22010-06-08 16:52:24 +0000633 char host_port[128];
634 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000635 char connect_url[128];
636 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000637
Greg Claytona2f74232011-02-24 22:24:29 +0000638 // Make sure we aren't already connected?
639 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000640 {
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000641 error = StartDebugserverProcess (host_port, launch_info);
Chris Lattner24943d22010-06-08 16:52:24 +0000642 if (error.Fail())
Greg Clayton716cefb2011-08-09 05:20:29 +0000643 {
Johnny Chenc143d622011-08-09 18:56:45 +0000644 if (log)
645 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner24943d22010-06-08 16:52:24 +0000646 return error;
Greg Clayton716cefb2011-08-09 05:20:29 +0000647 }
Chris Lattner24943d22010-06-08 16:52:24 +0000648
Greg Claytone71e2582011-02-04 01:58:07 +0000649 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000650 }
651
652 if (error.Success())
653 {
654 lldb_utility::PseudoTerminal pty;
655 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000656
657 // If the debugserver is local and we aren't disabling STDIO, lets use
658 // a pseudo terminal to instead of relying on the 'O' packets for stdio
659 // since 'O' packets can really slow down debugging if the inferior
660 // does a lot of output.
Greg Claytonb4747822011-06-24 22:32:10 +0000661 PlatformSP platform_sp (m_target.GetPlatform());
662 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000663 {
664 const char *slave_name = NULL;
665 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000666 {
Greg Claytona2f74232011-02-24 22:24:29 +0000667 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
668 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000669 }
Greg Claytona2f74232011-02-24 22:24:29 +0000670 if (stdin_path == NULL)
671 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000672
Greg Claytona2f74232011-02-24 22:24:29 +0000673 if (stdout_path == NULL)
674 stdout_path = slave_name;
675
676 if (stderr_path == NULL)
677 stderr_path = slave_name;
678 }
679
Greg Claytonafb81862011-03-02 21:34:46 +0000680 // Set STDIN to /dev/null if we want STDIO disabled or if either
681 // STDOUT or STDERR have been set to something and STDIN hasn't
682 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000683 stdin_path = "/dev/null";
684
Greg Claytonafb81862011-03-02 21:34:46 +0000685 // Set STDOUT to /dev/null if we want STDIO disabled or if either
686 // STDIN or STDERR have been set to something and STDOUT hasn't
687 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000688 stdout_path = "/dev/null";
689
Greg Claytonafb81862011-03-02 21:34:46 +0000690 // Set STDERR to /dev/null if we want STDIO disabled or if either
691 // STDIN or STDOUT have been set to something and STDERR hasn't
692 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000693 stderr_path = "/dev/null";
694
695 if (stdin_path)
696 m_gdb_comm.SetSTDIN (stdin_path);
697 if (stdout_path)
698 m_gdb_comm.SetSTDOUT (stdout_path);
699 if (stderr_path)
700 m_gdb_comm.SetSTDERR (stderr_path);
701
702 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
703
Greg Claytona4582402011-05-08 04:53:50 +0000704 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000705
706 if (working_dir && working_dir[0])
707 {
708 m_gdb_comm.SetWorkingDir (working_dir);
709 }
710
711 // Send the environment and the program + arguments after we connect
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000712 const Args &environment = launch_info.GetEnvironmentEntries();
713 if (environment.GetArgumentCount())
Greg Claytona2f74232011-02-24 22:24:29 +0000714 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000715 size_t num_environment_entries = environment.GetArgumentCount();
716 for (size_t i=0; i<num_environment_entries; ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000717 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000718 const char *env_entry = environment.GetArgumentAtIndex(i);
719 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000720 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000721 }
Greg Claytona2f74232011-02-24 22:24:29 +0000722 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000723
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000724 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000725 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info.GetArguments().GetConstArgumentVector());
Greg Claytona2f74232011-02-24 22:24:29 +0000726 if (arg_packet_err == 0)
727 {
728 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000729 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000730 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000731 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000732 }
733 else
734 {
Greg Claytona2f74232011-02-24 22:24:29 +0000735 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000736 }
Greg Claytona2f74232011-02-24 22:24:29 +0000737 }
738 else
739 {
Greg Clayton9c236732011-10-26 00:56:27 +0000740 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Claytona2f74232011-02-24 22:24:29 +0000741 }
Greg Clayton7c4fc6e2011-08-10 22:05:39 +0000742
743 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner24943d22010-06-08 16:52:24 +0000744
Greg Claytona2f74232011-02-24 22:24:29 +0000745 if (GetID() == LLDB_INVALID_PROCESS_ID)
746 {
Johnny Chenc143d622011-08-09 18:56:45 +0000747 if (log)
748 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytona2f74232011-02-24 22:24:29 +0000749 KillDebugserverProcess ();
750 return error;
751 }
752
Greg Clayton261a18b2011-06-02 22:22:38 +0000753 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000754 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000755 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Claytona2f74232011-02-24 22:24:29 +0000756
757 if (!disable_stdio)
758 {
759 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Clayton464c6162011-11-17 22:14:31 +0000760 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Claytona2f74232011-02-24 22:24:29 +0000761 }
Chris Lattner24943d22010-06-08 16:52:24 +0000762 }
763 }
Greg Clayton716cefb2011-08-09 05:20:29 +0000764 else
765 {
Johnny Chenc143d622011-08-09 18:56:45 +0000766 if (log)
767 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton716cefb2011-08-09 05:20:29 +0000768 }
Chris Lattner24943d22010-06-08 16:52:24 +0000769 }
770 else
771 {
772 // Set our user ID to an invalid process ID.
773 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000774 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
775 exe_module->GetFileSpec().GetFilename().AsCString(),
776 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000777 }
Chris Lattner24943d22010-06-08 16:52:24 +0000778 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000779
Chris Lattner24943d22010-06-08 16:52:24 +0000780}
781
782
783Error
Greg Claytone71e2582011-02-04 01:58:07 +0000784ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000785{
786 Error error;
787 // Sleep and wait a bit for debugserver to start to listen...
788 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
789 if (conn_ap.get())
790 {
Chris Lattner24943d22010-06-08 16:52:24 +0000791 const uint32_t max_retry_count = 50;
792 uint32_t retry_count = 0;
793 while (!m_gdb_comm.IsConnected())
794 {
Greg Claytone71e2582011-02-04 01:58:07 +0000795 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000796 {
797 m_gdb_comm.SetConnection (conn_ap.release());
798 break;
799 }
800 retry_count++;
801
802 if (retry_count >= max_retry_count)
803 break;
804
805 usleep (100000);
806 }
807 }
808
809 if (!m_gdb_comm.IsConnected())
810 {
811 if (error.Success())
812 error.SetErrorString("not connected to remote gdb server");
813 return error;
814 }
815
Greg Clayton24bc5d92011-03-30 18:16:51 +0000816 // We always seem to be able to open a connection to a local port
817 // so we need to make sure we can then send data to it. If we can't
818 // then we aren't actually connected to anything, so try and do the
819 // handshake with the remote GDB server and make sure that goes
820 // alright.
821 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000822 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000823 m_gdb_comm.Disconnect();
824 if (error.Success())
825 error.SetErrorString("not connected to remote gdb server");
826 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000827 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000828 m_gdb_comm.ResetDiscoverableSettings();
829 m_gdb_comm.QueryNoAckModeSupported ();
830 m_gdb_comm.GetThreadSuffixSupported ();
Greg Claytona1f645e2012-04-10 03:22:03 +0000831 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000832 m_gdb_comm.GetHostInfo ();
833 m_gdb_comm.GetVContSupported ('c');
Jim Ingham3a458eb2012-07-20 21:37:13 +0000834 m_gdb_comm.GetVAttachOrWaitSupported();
Jim Ingham86827fb2012-07-02 05:40:07 +0000835
836 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
837 for (size_t idx = 0; idx < num_cmds; idx++)
838 {
839 StringExtractorGDBRemote response;
840 printf ("Sending command: \%s.\n", GetExtraStartupCommands().GetArgumentAtIndex(idx));
841 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
842 }
Chris Lattner24943d22010-06-08 16:52:24 +0000843 return error;
844}
845
846void
847ProcessGDBRemote::DidLaunchOrAttach ()
848{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000849 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
850 if (log)
851 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000852 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000853 {
854 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
855
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000856 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000857
Chris Lattner24943d22010-06-08 16:52:24 +0000858 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000859
Greg Claytoncb8977d2011-03-23 00:09:55 +0000860 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
861 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000862 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000863 ArchSpec &target_arch = GetTarget().GetArchitecture();
864
865 if (target_arch.IsValid())
866 {
867 // If the remote host is ARM and we have apple as the vendor, then
868 // ARM executables and shared libraries can have mixed ARM architectures.
869 // You can have an armv6 executable, and if the host is armv7, then the
870 // system will load the best possible architecture for all shared libraries
871 // it has, so we really need to take the remote host architecture as our
872 // defacto architecture in this case.
873
874 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
875 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
876 {
877 target_arch = gdb_remote_arch;
878 }
879 else
880 {
881 // Fill in what is missing in the triple
882 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
883 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000884 if (target_triple.getVendorName().size() == 0)
885 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000886 target_triple.setVendor (remote_triple.getVendor());
887
Greg Clayton2f085c62011-05-15 01:25:55 +0000888 if (target_triple.getOSName().size() == 0)
889 {
890 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000891
Greg Clayton2f085c62011-05-15 01:25:55 +0000892 if (target_triple.getEnvironmentName().size() == 0)
893 target_triple.setEnvironment (remote_triple.getEnvironment());
894 }
895 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000896 }
897 }
898 else
899 {
900 // The target doesn't have a valid architecture yet, set it from
901 // the architecture we got from the remote GDB server
902 target_arch = gdb_remote_arch;
903 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000904 }
Chris Lattner24943d22010-06-08 16:52:24 +0000905 }
906}
907
908void
909ProcessGDBRemote::DidLaunch ()
910{
911 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000912}
913
914Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000915ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000916{
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000917 ProcessAttachInfo attach_info;
918 return DoAttachToProcessWithID(attach_pid, attach_info);
919}
920
921Error
922ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
923{
Chris Lattner24943d22010-06-08 16:52:24 +0000924 Error error;
925 // Clear out and clean up from any current state
926 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000927 if (attach_pid != LLDB_INVALID_PROCESS_ID)
928 {
Greg Claytona2f74232011-02-24 22:24:29 +0000929 // Make sure we aren't already connected?
930 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000931 {
Greg Claytona2f74232011-02-24 22:24:29 +0000932 char host_port[128];
933 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
934 char connect_url[128];
935 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000936
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000937 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000938
939 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000940 {
Greg Claytona2f74232011-02-24 22:24:29 +0000941 const char *error_string = error.AsCString();
942 if (error_string == NULL)
943 error_string = "unable to launch " DEBUGSERVER_BASENAME;
944
945 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000946 }
Greg Claytona2f74232011-02-24 22:24:29 +0000947 else
948 {
949 error = ConnectToDebugserver (connect_url);
950 }
951 }
952
953 if (error.Success())
954 {
955 char packet[64];
Greg Claytond9919d32011-12-01 23:28:38 +0000956 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%llx", attach_pid);
Greg Clayton489575c2011-11-19 02:11:30 +0000957 SetID (attach_pid);
Greg Claytona2f74232011-02-24 22:24:29 +0000958 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000959 }
960 }
Chris Lattner24943d22010-06-08 16:52:24 +0000961 return error;
962}
963
964size_t
965ProcessGDBRemote::AttachInputReaderCallback
966(
967 void *baton,
968 InputReader *reader,
969 lldb::InputReaderAction notification,
970 const char *bytes,
971 size_t bytes_len
972)
973{
974 if (notification == eInputReaderGotToken)
975 {
976 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
977 if (gdb_process->m_waiting_for_attach)
978 gdb_process->m_waiting_for_attach = false;
979 reader->SetIsDone(true);
980 return 1;
981 }
982 return 0;
983}
984
985Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000986ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000987{
988 Error error;
989 // Clear out and clean up from any current state
990 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000991
Chris Lattner24943d22010-06-08 16:52:24 +0000992 if (process_name && process_name[0])
993 {
Greg Claytona2f74232011-02-24 22:24:29 +0000994 // Make sure we aren't already connected?
995 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000996 {
Greg Claytona2f74232011-02-24 22:24:29 +0000997 char host_port[128];
998 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
999 char connect_url[128];
1000 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
1001
Han Ming Ongd1040dd2012-02-25 01:07:38 +00001002 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +00001003 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +00001004 {
Greg Claytona2f74232011-02-24 22:24:29 +00001005 const char *error_string = error.AsCString();
1006 if (error_string == NULL)
1007 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +00001008
Greg Claytona2f74232011-02-24 22:24:29 +00001009 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +00001010 }
Greg Claytona2f74232011-02-24 22:24:29 +00001011 else
1012 {
1013 error = ConnectToDebugserver (connect_url);
1014 }
1015 }
1016
1017 if (error.Success())
1018 {
1019 StreamString packet;
1020
1021 if (wait_for_launch)
Jim Ingham3a458eb2012-07-20 21:37:13 +00001022 {
1023 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1024 {
1025 packet.PutCString ("vAttachWait");
1026 }
1027 else
1028 {
1029 if (attach_info.GetIgnoreExisting())
1030 packet.PutCString("vAttachWait");
1031 else
1032 packet.PutCString ("vAttachOrWait");
1033 }
1034 }
Greg Claytona2f74232011-02-24 22:24:29 +00001035 else
1036 packet.PutCString("vAttachName");
1037 packet.PutChar(';');
1038 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1039
1040 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1041
Chris Lattner24943d22010-06-08 16:52:24 +00001042 }
1043 }
Chris Lattner24943d22010-06-08 16:52:24 +00001044 return error;
1045}
1046
Chris Lattner24943d22010-06-08 16:52:24 +00001047
1048void
1049ProcessGDBRemote::DidAttach ()
1050{
Greg Claytone71e2582011-02-04 01:58:07 +00001051 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +00001052}
1053
1054Error
1055ProcessGDBRemote::WillResume ()
1056{
Greg Claytonc1f45872011-02-12 06:28:37 +00001057 m_continue_c_tids.clear();
1058 m_continue_C_tids.clear();
1059 m_continue_s_tids.clear();
1060 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001061 return Error();
1062}
1063
1064Error
1065ProcessGDBRemote::DoResume ()
1066{
Jim Ingham3ae449a2010-11-17 02:32:00 +00001067 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +00001068 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1069 if (log)
1070 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +00001071
1072 Listener listener ("gdb-remote.resume-packet-sent");
1073 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1074 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001075 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1076
Greg Claytonc1f45872011-02-12 06:28:37 +00001077 StreamString continue_packet;
1078 bool continue_packet_error = false;
1079 if (m_gdb_comm.HasAnyVContSupport ())
1080 {
1081 continue_packet.PutCString ("vCont");
1082
1083 if (!m_continue_c_tids.empty())
1084 {
1085 if (m_gdb_comm.GetVContSupported ('c'))
1086 {
1087 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 +00001088 continue_packet.Printf(";c:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +00001089 }
1090 else
1091 continue_packet_error = true;
1092 }
1093
1094 if (!continue_packet_error && !m_continue_C_tids.empty())
1095 {
1096 if (m_gdb_comm.GetVContSupported ('C'))
1097 {
1098 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 +00001099 continue_packet.Printf(";C%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001100 }
1101 else
1102 continue_packet_error = true;
1103 }
Greg Claytonb749a262010-12-03 06:02:24 +00001104
Greg Claytonc1f45872011-02-12 06:28:37 +00001105 if (!continue_packet_error && !m_continue_s_tids.empty())
1106 {
1107 if (m_gdb_comm.GetVContSupported ('s'))
1108 {
1109 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 +00001110 continue_packet.Printf(";s:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +00001111 }
1112 else
1113 continue_packet_error = true;
1114 }
1115
1116 if (!continue_packet_error && !m_continue_S_tids.empty())
1117 {
1118 if (m_gdb_comm.GetVContSupported ('S'))
1119 {
1120 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 +00001121 continue_packet.Printf(";S%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001122 }
1123 else
1124 continue_packet_error = true;
1125 }
1126
1127 if (continue_packet_error)
1128 continue_packet.GetString().clear();
1129 }
1130 else
1131 continue_packet_error = true;
1132
1133 if (continue_packet_error)
1134 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001135 // Either no vCont support, or we tried to use part of the vCont
1136 // packet that wasn't supported by the remote GDB server.
1137 // We need to try and make a simple packet that can do our continue
1138 const size_t num_threads = GetThreadList().GetSize();
1139 const size_t num_continue_c_tids = m_continue_c_tids.size();
1140 const size_t num_continue_C_tids = m_continue_C_tids.size();
1141 const size_t num_continue_s_tids = m_continue_s_tids.size();
1142 const size_t num_continue_S_tids = m_continue_S_tids.size();
1143 if (num_continue_c_tids > 0)
1144 {
1145 if (num_continue_c_tids == num_threads)
1146 {
1147 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001148 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001149 continue_packet.PutChar ('c');
1150 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001151 }
1152 else if (num_continue_c_tids == 1 &&
1153 num_continue_C_tids == 0 &&
1154 num_continue_s_tids == 0 &&
1155 num_continue_S_tids == 0 )
1156 {
1157 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +00001158 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001159 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +00001160 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001161 }
1162 }
1163
Greg Claytonde1dd812011-06-24 03:21:43 +00001164 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001165 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001166 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1167 num_continue_C_tids > 0 &&
1168 num_continue_s_tids == 0 &&
1169 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +00001170 {
1171 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +00001172 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +00001173 if (num_continue_C_tids > 1)
1174 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001175 // More that one thread with a signal, yet we don't have
1176 // vCont support and we are being asked to resume each
1177 // thread with a signal, we need to make sure they are
1178 // all the same signal, or we can't issue the continue
1179 // accurately with the current support...
1180 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +00001181 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001182 continue_packet_error = false;
1183 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1184 {
1185 if (m_continue_C_tids[i].second != continue_signo)
1186 continue_packet_error = true;
1187 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001188 }
Greg Claytonde1dd812011-06-24 03:21:43 +00001189 if (!continue_packet_error)
1190 m_gdb_comm.SetCurrentThreadForRun (-1);
1191 }
1192 else
1193 {
1194 // Set the continue thread ID
1195 continue_packet_error = false;
1196 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001197 }
1198 if (!continue_packet_error)
1199 {
1200 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +00001201 continue_packet.Printf("C%2.2x", continue_signo);
1202 }
1203 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001204 }
1205
Greg Claytonde1dd812011-06-24 03:21:43 +00001206 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001207 {
1208 if (num_continue_s_tids == num_threads)
1209 {
1210 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001211 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001212 continue_packet.PutChar ('s');
1213 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001214 }
1215 else if (num_continue_c_tids == 0 &&
1216 num_continue_C_tids == 0 &&
1217 num_continue_s_tids == 1 &&
1218 num_continue_S_tids == 0 )
1219 {
1220 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001221 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001222 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001223 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001224 }
1225 }
1226
1227 if (!continue_packet_error && num_continue_S_tids > 0)
1228 {
1229 if (num_continue_S_tids == num_threads)
1230 {
1231 const int step_signo = m_continue_S_tids.front().second;
1232 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001233 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001234 if (num_continue_S_tids > 1)
1235 {
1236 for (size_t i=1; i<num_threads; ++i)
1237 {
1238 if (m_continue_S_tids[i].second != step_signo)
1239 continue_packet_error = true;
1240 }
1241 }
1242 if (!continue_packet_error)
1243 {
1244 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001245 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001246 continue_packet.Printf("S%2.2x", step_signo);
1247 }
1248 }
1249 else if (num_continue_c_tids == 0 &&
1250 num_continue_C_tids == 0 &&
1251 num_continue_s_tids == 0 &&
1252 num_continue_S_tids == 1 )
1253 {
1254 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001255 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001256 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001257 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001258 }
1259 }
1260 }
1261
1262 if (continue_packet_error)
1263 {
1264 error.SetErrorString ("can't make continue packet for this resume");
1265 }
1266 else
1267 {
1268 EventSP event_sp;
1269 TimeValue timeout;
1270 timeout = TimeValue::Now();
1271 timeout.OffsetWithSeconds (5);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001272 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1273 {
1274 error.SetErrorString ("Trying to resume but the async thread is dead.");
1275 if (log)
1276 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1277 return error;
1278 }
1279
Greg Claytonc1f45872011-02-12 06:28:37 +00001280 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1281
1282 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001283 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001284 error.SetErrorString("Resume timed out.");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001285 if (log)
1286 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1287 }
1288 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1289 {
1290 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1291 if (log)
1292 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1293 return error;
1294 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001295 }
Greg Claytonb749a262010-12-03 06:02:24 +00001296 }
1297
Jim Ingham3ae449a2010-11-17 02:32:00 +00001298 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001299}
1300
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001301void
1302ProcessGDBRemote::ClearThreadIDList ()
1303{
Greg Claytonff3448e2012-04-13 02:11:32 +00001304 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001305 m_thread_ids.clear();
1306}
1307
1308bool
1309ProcessGDBRemote::UpdateThreadIDList ()
1310{
Greg Claytonff3448e2012-04-13 02:11:32 +00001311 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001312 bool sequence_mutex_unavailable = false;
1313 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1314 if (sequence_mutex_unavailable)
1315 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001316 return false; // We just didn't get the list
1317 }
1318 return true;
1319}
1320
Greg Claytonae932352012-04-10 00:18:59 +00001321bool
Greg Clayton37f962e2011-08-22 02:49:39 +00001322ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001323{
1324 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001325 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001326 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Greg Clayton444e35b2011-10-19 18:09:39 +00001327 log->Printf ("ProcessGDBRemote::%s (pid = %llu)", __FUNCTION__, GetID());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001328
1329 size_t num_thread_ids = m_thread_ids.size();
1330 // The "m_thread_ids" thread ID list should always be updated after each stop
1331 // reply packet, but in case it isn't, update it here.
1332 if (num_thread_ids == 0)
1333 {
1334 if (!UpdateThreadIDList ())
1335 return false;
1336 num_thread_ids = m_thread_ids.size();
1337 }
Chris Lattner24943d22010-06-08 16:52:24 +00001338
Greg Clayton37f962e2011-08-22 02:49:39 +00001339 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001340 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001341 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001342 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001343 tid_t tid = m_thread_ids[i];
Greg Clayton37f962e2011-08-22 02:49:39 +00001344 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false));
1345 if (!thread_sp)
Jim Ingham94a5d0d2012-10-10 18:32:14 +00001346 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Greg Clayton37f962e2011-08-22 02:49:39 +00001347 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001348 }
Chris Lattner24943d22010-06-08 16:52:24 +00001349 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001350
Greg Claytonae932352012-04-10 00:18:59 +00001351 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001352}
1353
1354
1355StateType
1356ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1357{
Greg Clayton261a18b2011-06-02 22:22:38 +00001358 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001359 const char stop_type = stop_packet.GetChar();
1360 switch (stop_type)
1361 {
1362 case 'T':
1363 case 'S':
1364 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001365 if (GetStopID() == 0)
1366 {
1367 // Our first stop, make sure we have a process ID, and also make
1368 // sure we know about our registers
1369 if (GetID() == LLDB_INVALID_PROCESS_ID)
1370 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001371 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001372 if (pid != LLDB_INVALID_PROCESS_ID)
1373 SetID (pid);
1374 }
1375 BuildDynamicRegisterInfo (true);
1376 }
Chris Lattner24943d22010-06-08 16:52:24 +00001377 // Stop with signal and thread info
1378 const uint8_t signo = stop_packet.GetHexU8();
1379 std::string name;
1380 std::string value;
1381 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001382 std::string reason;
1383 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001384 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001385 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001386 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Claytona875b642011-01-09 21:07:35 +00001387 ThreadSP thread_sp;
1388
Chris Lattner24943d22010-06-08 16:52:24 +00001389 while (stop_packet.GetNameColonValue(name, value))
1390 {
1391 if (name.compare("metype") == 0)
1392 {
1393 // exception type in big endian hex
1394 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1395 }
Chris Lattner24943d22010-06-08 16:52:24 +00001396 else if (name.compare("medata") == 0)
1397 {
1398 // exception data in big endian hex
1399 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1400 }
1401 else if (name.compare("thread") == 0)
1402 {
1403 // thread in big endian hex
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001404 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Claytonffa43a62011-11-17 04:46:02 +00001405 // m_thread_list does have its own mutex, but we need to
1406 // hold onto the mutex between the call to m_thread_list.FindThreadByID(...)
1407 // and the m_thread_list.AddThread(...) so it doesn't change on us
Greg Claytonc3c46612011-02-15 00:19:15 +00001408 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001409 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001410 if (!thread_sp)
1411 {
1412 // Create the thread if we need to
Jim Ingham94a5d0d2012-10-10 18:32:14 +00001413 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Greg Claytonc3c46612011-02-15 00:19:15 +00001414 m_thread_list.AddThread(thread_sp);
1415 }
Chris Lattner24943d22010-06-08 16:52:24 +00001416 }
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001417 else if (name.compare("threads") == 0)
1418 {
Greg Claytonff3448e2012-04-13 02:11:32 +00001419 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001420 m_thread_ids.clear();
Greg Claytona1f645e2012-04-10 03:22:03 +00001421 // A comma separated list of all threads in the current
1422 // process that includes the thread for this stop reply
1423 // packet
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001424 size_t comma_pos;
1425 lldb::tid_t tid;
1426 while ((comma_pos = value.find(',')) != std::string::npos)
1427 {
1428 value[comma_pos] = '\0';
1429 // thread in big endian hex
1430 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1431 if (tid != LLDB_INVALID_THREAD_ID)
1432 m_thread_ids.push_back (tid);
1433 value.erase(0, comma_pos + 1);
1434
1435 }
1436 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1437 if (tid != LLDB_INVALID_THREAD_ID)
1438 m_thread_ids.push_back (tid);
1439 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001440 else if (name.compare("hexname") == 0)
1441 {
1442 StringExtractor name_extractor;
1443 // Swap "value" over into "name_extractor"
1444 name_extractor.GetStringRef().swap(value);
1445 // Now convert the HEX bytes into a string value
1446 name_extractor.GetHexByteString (value);
1447 thread_name.swap (value);
1448 }
Chris Lattner24943d22010-06-08 16:52:24 +00001449 else if (name.compare("name") == 0)
1450 {
1451 thread_name.swap (value);
1452 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001453 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001454 {
1455 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1456 }
Greg Clayton65611552011-06-04 01:26:29 +00001457 else if (name.compare("reason") == 0)
1458 {
1459 reason.swap(value);
1460 }
1461 else if (name.compare("description") == 0)
1462 {
1463 StringExtractor desc_extractor;
1464 // Swap "value" over into "name_extractor"
1465 desc_extractor.GetStringRef().swap(value);
1466 // Now convert the HEX bytes into a string value
1467 desc_extractor.GetHexByteString (thread_name);
1468 }
Greg Claytona875b642011-01-09 21:07:35 +00001469 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1470 {
1471 // We have a register number that contains an expedited
1472 // register value. Lets supply this register to our thread
1473 // so it won't have to go and read it.
1474 if (thread_sp)
1475 {
1476 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1477
1478 if (reg != UINT32_MAX)
1479 {
1480 StringExtractor reg_value_extractor;
1481 // Swap "value" over into "reg_value_extractor"
1482 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001483 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1484 {
1485 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1486 name.c_str(),
1487 reg,
1488 reg,
1489 reg_value_extractor.GetStringRef().c_str(),
1490 stop_packet.GetStringRef().c_str());
1491 }
Greg Claytona875b642011-01-09 21:07:35 +00001492 }
1493 }
1494 }
Chris Lattner24943d22010-06-08 16:52:24 +00001495 }
Chris Lattner24943d22010-06-08 16:52:24 +00001496
1497 if (thread_sp)
1498 {
1499 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1500
1501 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001502 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001503 if (exc_type != 0)
1504 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001505 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001506
1507 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1508 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001509 exc_data_size,
1510 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001511 exc_data_size >= 2 ? exc_data[1] : 0,
1512 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001513 }
Greg Clayton65611552011-06-04 01:26:29 +00001514 else
Chris Lattner24943d22010-06-08 16:52:24 +00001515 {
Greg Clayton65611552011-06-04 01:26:29 +00001516 bool handled = false;
1517 if (!reason.empty())
1518 {
1519 if (reason.compare("trace") == 0)
1520 {
1521 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1522 handled = true;
1523 }
1524 else if (reason.compare("breakpoint") == 0)
1525 {
1526 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001527 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001528 if (bp_site_sp)
1529 {
1530 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1531 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1532 // 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 +00001533 handled = true;
Greg Clayton65611552011-06-04 01:26:29 +00001534 if (bp_site_sp->ValidForThisThread (gdb_thread))
1535 {
1536 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001537 }
1538 else
1539 {
1540 StopInfoSP invalid_stop_info_sp;
1541 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Greg Clayton65611552011-06-04 01:26:29 +00001542 }
1543 }
1544
Greg Clayton65611552011-06-04 01:26:29 +00001545 }
1546 else if (reason.compare("trap") == 0)
1547 {
1548 // Let the trap just use the standard signal stop reason below...
1549 }
1550 else if (reason.compare("watchpoint") == 0)
1551 {
1552 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1553 // TODO: locate the watchpoint somehow...
1554 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1555 handled = true;
1556 }
1557 else if (reason.compare("exception") == 0)
1558 {
1559 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1560 handled = true;
1561 }
1562 }
1563
1564 if (signo)
1565 {
1566 if (signo == SIGTRAP)
1567 {
1568 // Currently we are going to assume SIGTRAP means we are either
1569 // hitting a breakpoint or hardware single stepping.
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001570 handled = true;
Greg Clayton65611552011-06-04 01:26:29 +00001571 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001572 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001573
Greg Clayton65611552011-06-04 01:26:29 +00001574 if (bp_site_sp)
1575 {
1576 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1577 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1578 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1579 if (bp_site_sp->ValidForThisThread (gdb_thread))
1580 {
1581 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001582 }
1583 else
1584 {
1585 StopInfoSP invalid_stop_info_sp;
1586 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Greg Clayton65611552011-06-04 01:26:29 +00001587 }
1588 }
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001589 else
Greg Clayton65611552011-06-04 01:26:29 +00001590 {
1591 // TODO: check for breakpoint or trap opcode in case there is a hard
1592 // coded software trap
1593 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Greg Clayton65611552011-06-04 01:26:29 +00001594 }
1595 }
1596 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001597 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001598 }
1599 else
1600 {
Greg Clayton643ee732010-08-04 01:40:35 +00001601 StopInfoSP invalid_stop_info_sp;
1602 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001603 }
Greg Clayton65611552011-06-04 01:26:29 +00001604
1605 if (!description.empty())
1606 {
1607 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1608 if (stop_info_sp)
1609 {
1610 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001611 }
Greg Clayton65611552011-06-04 01:26:29 +00001612 else
1613 {
1614 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1615 }
1616 }
1617 }
Chris Lattner24943d22010-06-08 16:52:24 +00001618 }
1619 return eStateStopped;
1620 }
1621 break;
1622
1623 case 'W':
1624 // process exited
1625 return eStateExited;
1626
1627 default:
1628 break;
1629 }
1630 return eStateInvalid;
1631}
1632
1633void
1634ProcessGDBRemote::RefreshStateAfterStop ()
1635{
Greg Claytonff3448e2012-04-13 02:11:32 +00001636 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001637 m_thread_ids.clear();
1638 // Set the thread stop info. It might have a "threads" key whose value is
1639 // a list of all thread IDs in the current process, so m_thread_ids might
1640 // get set.
1641 SetThreadStopInfo (m_last_stop_packet);
1642 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1643 if (m_thread_ids.empty())
1644 {
1645 // No, we need to fetch the thread list manually
1646 UpdateThreadIDList();
1647 }
1648
Chris Lattner24943d22010-06-08 16:52:24 +00001649 // Let all threads recover from stopping and do any clean up based
1650 // on the previous thread state (if any).
1651 m_thread_list.RefreshStateAfterStop();
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001652
Chris Lattner24943d22010-06-08 16:52:24 +00001653}
1654
1655Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001656ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001657{
1658 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001659
Greg Claytona4881d02011-01-22 07:12:45 +00001660 bool timed_out = false;
1661 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001662
1663 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001664 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001665 // We are being asked to halt during an attach. We need to just close
1666 // our file handle and debugserver will go away, and we can be done...
1667 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001668 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001669 else
1670 {
Greg Clayton05e4d972012-03-29 01:55:41 +00001671 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001672 {
1673 if (timed_out)
1674 error.SetErrorString("timed out sending interrupt packet");
1675 else
1676 error.SetErrorString("unknown error sending interrupt packet");
1677 }
Greg Clayton05e4d972012-03-29 01:55:41 +00001678
1679 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001680 }
Chris Lattner24943d22010-06-08 16:52:24 +00001681 return error;
1682}
1683
1684Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001685ProcessGDBRemote::InterruptIfRunning
1686(
1687 bool discard_thread_plans,
1688 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001689 EventSP &stop_event_sp
1690)
Chris Lattner24943d22010-06-08 16:52:24 +00001691{
1692 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001693
Greg Clayton2860ba92011-01-23 19:58:49 +00001694 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1695
Greg Clayton68ca8232011-01-25 02:58:48 +00001696 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001697 const bool is_running = m_gdb_comm.IsRunning();
1698 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001699 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001700 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001701 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001702 is_running);
1703
Greg Clayton2860ba92011-01-23 19:58:49 +00001704 if (discard_thread_plans)
1705 {
1706 if (log)
1707 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1708 m_thread_list.DiscardThreadPlans();
1709 }
1710 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001711 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001712 if (catch_stop_event)
1713 {
1714 if (log)
1715 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1716 PausePrivateStateThread();
1717 paused_private_state_thread = true;
1718 }
1719
Greg Clayton4fb400f2010-09-27 21:07:38 +00001720 bool timed_out = false;
1721 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001722
Greg Clayton05e4d972012-03-29 01:55:41 +00001723 if (!m_gdb_comm.SendInterrupt (locker, 1, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001724 {
1725 if (timed_out)
1726 error.SetErrorString("timed out sending interrupt packet");
1727 else
1728 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001729 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001730 ResumePrivateStateThread();
1731 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001732 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001733
Greg Clayton72e1c782011-01-22 23:43:18 +00001734 if (catch_stop_event)
1735 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001736 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001737 TimeValue timeout_time;
1738 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001739 timeout_time.OffsetWithSeconds(5);
1740 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001741
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001742 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001743 if (log)
1744 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001745
Greg Clayton2860ba92011-01-23 19:58:49 +00001746 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001747 error.SetErrorString("unable to verify target stopped");
1748 }
1749
Greg Clayton68ca8232011-01-25 02:58:48 +00001750 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001751 {
1752 if (log)
1753 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001754 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001755 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001756 }
Chris Lattner24943d22010-06-08 16:52:24 +00001757 return error;
1758}
1759
Greg Clayton4fb400f2010-09-27 21:07:38 +00001760Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001761ProcessGDBRemote::WillDetach ()
1762{
Greg Clayton2860ba92011-01-23 19:58:49 +00001763 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1764 if (log)
1765 log->Printf ("ProcessGDBRemote::WillDetach()");
1766
Greg Clayton72e1c782011-01-22 23:43:18 +00001767 bool discard_thread_plans = true;
1768 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001769 EventSP event_sp;
Jim Ingham8247e622012-06-06 00:32:39 +00001770
1771 // FIXME: InterruptIfRunning should be done in the Process base class, or better still make Halt do what is
1772 // needed. This shouldn't be a feature of a particular plugin.
1773
Greg Clayton68ca8232011-01-25 02:58:48 +00001774 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001775}
1776
1777Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001778ProcessGDBRemote::DoDetach()
1779{
1780 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001781 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001782 if (log)
1783 log->Printf ("ProcessGDBRemote::DoDetach()");
1784
1785 DisableAllBreakpointSites ();
1786
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001787 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001788
Greg Clayton516f0842012-04-11 00:24:49 +00001789 bool success = m_gdb_comm.Detach ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001790 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001791 {
Greg Clayton516f0842012-04-11 00:24:49 +00001792 if (success)
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001793 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1794 else
1795 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001796 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001797 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001798 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001799
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001800 SetPrivateState (eStateDetached);
1801 ResumePrivateStateThread();
1802
1803 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001804 return error;
1805}
Chris Lattner24943d22010-06-08 16:52:24 +00001806
Jim Ingham06b84492012-07-04 00:35:43 +00001807
Chris Lattner24943d22010-06-08 16:52:24 +00001808Error
1809ProcessGDBRemote::DoDestroy ()
1810{
1811 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001812 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001813 if (log)
1814 log->Printf ("ProcessGDBRemote::DoDestroy()");
1815
Jim Ingham06b84492012-07-04 00:35:43 +00001816 // There is a bug in older iOS debugservers where they don't shut down the process
1817 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
1818 // this can cause problems with restarting. So we check to see if any of our threads are stopped
1819 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
1820 // destroy it again.
1821 //
1822 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
1823 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
1824 // the debugservers with this bug are equal. There really should be a better way to test this!
1825 //
1826 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
1827 // get called here to destroy again and we're still at a breakpoint or exception, then we should
1828 // just do the straight-forward kill.
1829 //
1830 // And of course, if we weren't able to stop the process by the time we get here, it isn't
1831 // necessary (or helpful) to do any of this.
1832
1833 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
1834 {
1835 PlatformSP platform_sp = GetTarget().GetPlatform();
1836
1837 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
1838 if (platform_sp
1839 && platform_sp->GetName()
1840 && strcmp (platform_sp->GetName(), PlatformRemoteiOS::GetShortPluginNameStatic()) == 0)
1841 {
1842 if (m_destroy_tried_resuming)
1843 {
1844 if (log)
1845 log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again.");
1846 }
1847 else
1848 {
1849 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
1850 // but we really need it to happen here and it doesn't matter if we do it twice.
1851 m_thread_list.DiscardThreadPlans();
1852 DisableAllBreakpointSites();
1853
1854 bool stop_looks_like_crash = false;
1855 ThreadList &threads = GetThreadList();
1856
1857 {
Jim Inghamc2c65142012-09-11 00:08:52 +00001858 Mutex::Locker locker(threads.GetMutex());
Jim Ingham06b84492012-07-04 00:35:43 +00001859
1860 size_t num_threads = threads.GetSize();
1861 for (size_t i = 0; i < num_threads; i++)
1862 {
1863 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1864 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason();
1865 StopReason reason = eStopReasonInvalid;
1866 if (stop_info_sp)
1867 reason = stop_info_sp->GetStopReason();
1868 if (reason == eStopReasonBreakpoint
1869 || reason == eStopReasonException)
1870 {
1871 if (log)
1872 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: %lld stopped with reason: %s.",
1873 thread_sp->GetID(),
1874 stop_info_sp->GetDescription());
1875 stop_looks_like_crash = true;
1876 break;
1877 }
1878 }
1879 }
1880
1881 if (stop_looks_like_crash)
1882 {
1883 if (log)
1884 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
1885 m_destroy_tried_resuming = true;
1886
1887 // If we are going to run again before killing, it would be good to suspend all the threads
1888 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
1889 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
1890 // have to run the risk of letting those threads proceed a bit.
1891
1892 {
Jim Inghamc2c65142012-09-11 00:08:52 +00001893 Mutex::Locker locker(threads.GetMutex());
Jim Ingham06b84492012-07-04 00:35:43 +00001894
1895 size_t num_threads = threads.GetSize();
1896 for (size_t i = 0; i < num_threads; i++)
1897 {
1898 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1899 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason();
1900 StopReason reason = eStopReasonInvalid;
1901 if (stop_info_sp)
1902 reason = stop_info_sp->GetStopReason();
1903 if (reason != eStopReasonBreakpoint
1904 && reason != eStopReasonException)
1905 {
1906 if (log)
1907 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: %lld before running.",
1908 thread_sp->GetID());
1909 thread_sp->SetResumeState(eStateSuspended);
1910 }
1911 }
1912 }
1913 Resume ();
1914 return Destroy();
1915 }
1916 }
1917 }
1918 }
1919
Chris Lattner24943d22010-06-08 16:52:24 +00001920 // Interrupt if our inferior is running...
Jim Ingham8247e622012-06-06 00:32:39 +00001921 int exit_status = SIGABRT;
1922 std::string exit_string;
1923
Greg Claytona4881d02011-01-22 07:12:45 +00001924 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001925 {
Jim Ingham8226e942011-10-28 01:11:35 +00001926 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton72e1c782011-01-22 23:43:18 +00001927 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001928
1929 StringExtractorGDBRemote response;
1930 bool send_async = true;
Filipe Cabecinhasee188ee2012-08-22 13:25:58 +00001931 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3);
1932
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001933 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001934 {
1935 char packet_cmd = response.GetChar(0);
1936
1937 if (packet_cmd == 'W' || packet_cmd == 'X')
1938 {
Greg Clayton06709002011-12-06 04:51:14 +00001939 SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001940 ClearThreadIDList ();
Jim Ingham8247e622012-06-06 00:32:39 +00001941 exit_status = response.GetHexU8();
1942 }
1943 else
1944 {
1945 if (log)
1946 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
1947 exit_string.assign("got unexpected response to k packet: ");
1948 exit_string.append(response.GetStringRef());
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001949 }
1950 }
1951 else
1952 {
Jim Ingham8247e622012-06-06 00:32:39 +00001953 if (log)
1954 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
1955 exit_string.assign("failed to send the k packet");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001956 }
Filipe Cabecinhasee188ee2012-08-22 13:25:58 +00001957
1958 m_gdb_comm.SetPacketTimeout(old_packet_timeout);
Greg Clayton72e1c782011-01-22 23:43:18 +00001959 }
Jim Ingham8247e622012-06-06 00:32:39 +00001960 else
1961 {
1962 if (log)
1963 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
Jim Ingham5d90ade2012-07-27 23:57:19 +00001964 exit_string.assign ("killed or interrupted while attaching.");
Jim Ingham8247e622012-06-06 00:32:39 +00001965 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001966 }
Jim Ingham8247e622012-06-06 00:32:39 +00001967 else
1968 {
1969 // If we missed setting the exit status on the way out, do it here.
1970 // NB set exit status can be called multiple times, the first one sets the status.
1971 exit_string.assign("destroying when not connected to debugserver");
1972 }
1973
1974 SetExitStatus(exit_status, exit_string.c_str());
1975
Chris Lattner24943d22010-06-08 16:52:24 +00001976 StopAsyncThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001977 KillDebugserverProcess ();
1978 return error;
1979}
1980
Chris Lattner24943d22010-06-08 16:52:24 +00001981//------------------------------------------------------------------
1982// Process Queries
1983//------------------------------------------------------------------
1984
1985bool
1986ProcessGDBRemote::IsAlive ()
1987{
Greg Clayton58e844b2010-12-08 05:08:21 +00001988 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00001989}
1990
Jason Molendad6b81222012-10-06 02:02:26 +00001991// For kernel debugging, we return the load address of the kernel binary as the
1992// ImageInfoAddress and we return the DynamicLoaderDarwinKernel as the GetDynamicLoader()
1993// name so the correct DynamicLoader plugin is chosen.
Chris Lattner24943d22010-06-08 16:52:24 +00001994addr_t
1995ProcessGDBRemote::GetImageInfoAddress()
1996{
Jason Molendab46937c2012-10-03 01:29:34 +00001997 if (m_kernel_load_addr != LLDB_INVALID_ADDRESS)
1998 return m_kernel_load_addr;
1999 else
2000 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner24943d22010-06-08 16:52:24 +00002001}
2002
Chris Lattner24943d22010-06-08 16:52:24 +00002003//------------------------------------------------------------------
2004// Process Memory
2005//------------------------------------------------------------------
2006size_t
2007ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2008{
2009 if (size > m_max_memory_size)
2010 {
2011 // Keep memory read sizes down to a sane limit. This function will be
2012 // called multiple times in order to complete the task by
2013 // lldb_private::Process so it is ok to do this.
2014 size = m_max_memory_size;
2015 }
2016
2017 char packet[64];
Greg Clayton851e30e2012-09-18 18:04:04 +00002018 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%llx", (uint64_t)addr, (uint64_t)size);
Chris Lattner24943d22010-06-08 16:52:24 +00002019 assert (packet_len + 1 < sizeof(packet));
2020 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00002021 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00002022 {
Greg Clayton61d043b2011-03-22 04:00:09 +00002023 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00002024 {
2025 error.Clear();
2026 return response.GetHexBytes(buf, size, '\xdd');
2027 }
Greg Clayton61d043b2011-03-22 04:00:09 +00002028 else if (response.IsErrorResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00002029 error.SetErrorString("memory read failed");
Greg Clayton61d043b2011-03-22 04:00:09 +00002030 else if (response.IsUnsupportedResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00002031 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner24943d22010-06-08 16:52:24 +00002032 else
Greg Claytonae7bebc2012-09-19 01:46:31 +00002033 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00002034 }
2035 else
2036 {
2037 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
2038 }
2039 return 0;
2040}
2041
2042size_t
2043ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2044{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00002045 if (size > m_max_memory_size)
2046 {
2047 // Keep memory read sizes down to a sane limit. This function will be
2048 // called multiple times in order to complete the task by
2049 // lldb_private::Process so it is ok to do this.
2050 size = m_max_memory_size;
2051 }
2052
Chris Lattner24943d22010-06-08 16:52:24 +00002053 StreamString packet;
Greg Clayton851e30e2012-09-18 18:04:04 +00002054 packet.Printf("M%llx,%llx:", addr, (uint64_t)size);
Greg Claytoncd548032011-02-01 01:31:41 +00002055 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00002056 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00002057 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00002058 {
Greg Clayton61d043b2011-03-22 04:00:09 +00002059 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00002060 {
2061 error.Clear();
2062 return size;
2063 }
Greg Clayton61d043b2011-03-22 04:00:09 +00002064 else if (response.IsErrorResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00002065 error.SetErrorString("memory write failed");
Greg Clayton61d043b2011-03-22 04:00:09 +00002066 else if (response.IsUnsupportedResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00002067 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner24943d22010-06-08 16:52:24 +00002068 else
Greg Claytonae7bebc2012-09-19 01:46:31 +00002069 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 +00002070 }
2071 else
2072 {
2073 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
2074 }
2075 return 0;
2076}
2077
2078lldb::addr_t
2079ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2080{
Greg Clayton989816b2011-05-14 01:50:35 +00002081 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2082
Greg Clayton2f085c62011-05-15 01:25:55 +00002083 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00002084 switch (supported)
2085 {
2086 case eLazyBoolCalculate:
2087 case eLazyBoolYes:
2088 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2089 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2090 return allocated_addr;
2091
2092 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002093 // Call mmap() to create memory in the inferior..
2094 unsigned prot = 0;
2095 if (permissions & lldb::ePermissionsReadable)
2096 prot |= eMmapProtRead;
2097 if (permissions & lldb::ePermissionsWritable)
2098 prot |= eMmapProtWrite;
2099 if (permissions & lldb::ePermissionsExecutable)
2100 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00002101
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002102 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2103 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2104 m_addr_to_mmap_size[allocated_addr] = size;
2105 else
2106 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00002107 break;
2108 }
2109
Chris Lattner24943d22010-06-08 16:52:24 +00002110 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton851e30e2012-09-18 18:04:04 +00002111 error.SetErrorStringWithFormat("unable to allocate %llu bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00002112 else
2113 error.Clear();
2114 return allocated_addr;
2115}
2116
2117Error
Greg Claytona9385532011-11-18 07:03:08 +00002118ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2119 MemoryRegionInfo &region_info)
2120{
2121
2122 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2123 return error;
2124}
2125
2126Error
Johnny Chen7cbdcfb2012-05-23 21:09:52 +00002127ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2128{
2129
2130 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2131 return error;
2132}
2133
2134Error
Enrico Granata7de2a3b2012-07-13 23:18:48 +00002135ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2136{
2137 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2138 return error;
2139}
2140
2141Error
Chris Lattner24943d22010-06-08 16:52:24 +00002142ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2143{
2144 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00002145 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2146
2147 switch (supported)
2148 {
2149 case eLazyBoolCalculate:
2150 // We should never be deallocating memory without allocating memory
2151 // first so we should never get eLazyBoolCalculate
2152 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2153 break;
2154
2155 case eLazyBoolYes:
2156 if (!m_gdb_comm.DeallocateMemory (addr))
2157 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
2158 break;
2159
2160 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002161 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00002162 {
2163 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002164 if (pos != m_addr_to_mmap_size.end() &&
2165 InferiorCallMunmap(this, addr, pos->second))
2166 m_addr_to_mmap_size.erase (pos);
2167 else
2168 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00002169 }
2170 break;
2171 }
2172
Chris Lattner24943d22010-06-08 16:52:24 +00002173 return error;
2174}
2175
2176
2177//------------------------------------------------------------------
2178// Process STDIO
2179//------------------------------------------------------------------
Chris Lattner24943d22010-06-08 16:52:24 +00002180size_t
2181ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2182{
2183 if (m_stdio_communication.IsConnected())
2184 {
2185 ConnectionStatus status;
2186 m_stdio_communication.Write(src, src_len, status, NULL);
2187 }
2188 return 0;
2189}
2190
2191Error
2192ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
2193{
2194 Error error;
2195 assert (bp_site != NULL);
2196
Greg Claytone005f2c2010-11-06 01:53:30 +00002197 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002198 user_id_t site_id = bp_site->GetID();
2199 const addr_t addr = bp_site->GetLoadAddress();
2200 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002201 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002202
2203 if (bp_site->IsEnabled())
2204 {
2205 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002206 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 +00002207 return error;
2208 }
2209 else
2210 {
2211 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2212
2213 if (bp_site->HardwarePreferred())
2214 {
2215 // Try and set hardware breakpoint, and if that fails, fall through
2216 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00002217 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00002218 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002219 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00002220 {
2221 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002222 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00002223 return error;
2224 }
Chris Lattner24943d22010-06-08 16:52:24 +00002225 }
2226 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002227
2228 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00002229 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002230 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
2231 {
2232 bp_site->SetEnabled(true);
2233 bp_site->SetType (BreakpointSite::eExternal);
2234 return error;
2235 }
Chris Lattner24943d22010-06-08 16:52:24 +00002236 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002237
2238 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00002239 }
2240
2241 if (log)
2242 {
2243 const char *err_string = error.AsCString();
2244 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
2245 bp_site->GetLoadAddress(),
2246 err_string ? err_string : "NULL");
2247 }
2248 // We shouldn't reach here on a successful breakpoint enable...
2249 if (error.Success())
2250 error.SetErrorToGenericError();
2251 return error;
2252}
2253
2254Error
2255ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
2256{
2257 Error error;
2258 assert (bp_site != NULL);
2259 addr_t addr = bp_site->GetLoadAddress();
2260 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00002261 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002262 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002263 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002264
2265 if (bp_site->IsEnabled())
2266 {
2267 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2268
Greg Claytonb72d0f02011-04-12 05:54:46 +00002269 BreakpointSite::Type bp_type = bp_site->GetType();
2270 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00002271 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002272 case BreakpointSite::eSoftware:
2273 error = DisableSoftwareBreakpoint (bp_site);
2274 break;
2275
2276 case BreakpointSite::eHardware:
2277 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2278 error.SetErrorToGenericError();
2279 break;
2280
2281 case BreakpointSite::eExternal:
2282 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2283 error.SetErrorToGenericError();
2284 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002285 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002286 if (error.Success())
2287 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00002288 }
2289 else
2290 {
2291 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002292 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 +00002293 return error;
2294 }
2295
2296 if (error.Success())
2297 error.SetErrorToGenericError();
2298 return error;
2299}
2300
Johnny Chen21900fb2011-09-06 22:38:36 +00002301// Pre-requisite: wp != NULL.
2302static GDBStoppointType
Johnny Chenecd4feb2011-10-14 00:42:25 +00002303GetGDBStoppointType (Watchpoint *wp)
Johnny Chen21900fb2011-09-06 22:38:36 +00002304{
2305 assert(wp);
2306 bool watch_read = wp->WatchpointRead();
2307 bool watch_write = wp->WatchpointWrite();
2308
2309 // watch_read and watch_write cannot both be false.
2310 assert(watch_read || watch_write);
2311 if (watch_read && watch_write)
2312 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00002313 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00002314 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00002315 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00002316 return eWatchpointWrite;
2317}
2318
Chris Lattner24943d22010-06-08 16:52:24 +00002319Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002320ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002321{
2322 Error error;
2323 if (wp)
2324 {
2325 user_id_t watchID = wp->GetID();
2326 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00002327 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002328 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002329 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %llu)", watchID);
Chris Lattner24943d22010-06-08 16:52:24 +00002330 if (wp->IsEnabled())
2331 {
2332 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002333 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %llu) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002334 return error;
2335 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002336
2337 GDBStoppointType type = GetGDBStoppointType(wp);
2338 // Pass down an appropriate z/Z packet...
2339 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00002340 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002341 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2342 {
2343 wp->SetEnabled(true);
2344 return error;
2345 }
2346 else
2347 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002348 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002349 else
2350 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00002351 }
2352 else
2353 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002354 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002355 }
2356 if (error.Success())
2357 error.SetErrorToGenericError();
2358 return error;
2359}
2360
2361Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002362ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002363{
2364 Error error;
2365 if (wp)
2366 {
2367 user_id_t watchID = wp->GetID();
2368
Greg Claytone005f2c2010-11-06 01:53:30 +00002369 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002370
2371 addr_t addr = wp->GetLoadAddress();
2372 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002373 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002374
Johnny Chen21900fb2011-09-06 22:38:36 +00002375 if (!wp->IsEnabled())
2376 {
2377 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002378 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
Johnny Chen258db3a2012-08-23 22:28:26 +00002379 // See also 'class WatchpointSentry' within StopInfo.cpp.
2380 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2381 // the watchpoint object to intelligently process this action.
2382 wp->SetEnabled(false);
Johnny Chen21900fb2011-09-06 22:38:36 +00002383 return error;
2384 }
2385
Chris Lattner24943d22010-06-08 16:52:24 +00002386 if (wp->IsHardware())
2387 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002388 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00002389 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00002390 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2391 {
2392 wp->SetEnabled(false);
2393 return error;
2394 }
2395 else
2396 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002397 }
2398 // TODO: clear software watchpoints if we implement them
2399 }
2400 else
2401 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002402 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002403 }
2404 if (error.Success())
2405 error.SetErrorToGenericError();
2406 return error;
2407}
2408
2409void
2410ProcessGDBRemote::Clear()
2411{
2412 m_flags = 0;
2413 m_thread_list.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002414}
2415
2416Error
2417ProcessGDBRemote::DoSignal (int signo)
2418{
2419 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00002420 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002421 if (log)
2422 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2423
2424 if (!m_gdb_comm.SendAsyncSignal (signo))
2425 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2426 return error;
2427}
2428
Chris Lattner24943d22010-06-08 16:52:24 +00002429Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002430ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)
2431{
2432 ProcessLaunchInfo launch_info;
2433 return StartDebugserverProcess(debugserver_url, launch_info);
2434}
2435
2436Error
2437ProcessGDBRemote::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 +00002438{
2439 Error error;
2440 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2441 {
2442 // If we locate debugserver, keep that located version around
2443 static FileSpec g_debugserver_file_spec;
2444
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002445 ProcessLaunchInfo debugserver_launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002446 char debugserver_path[PATH_MAX];
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002447 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002448
2449 // Always check to see if we have an environment override for the path
2450 // to the debugserver to use and use it if we do.
2451 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2452 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002453 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002454 else
2455 debugserver_file_spec = g_debugserver_file_spec;
2456 bool debugserver_exists = debugserver_file_spec.Exists();
2457 if (!debugserver_exists)
2458 {
2459 // The debugserver binary is in the LLDB.framework/Resources
2460 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002461 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002462 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002463 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002464 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002465 if (debugserver_exists)
2466 {
2467 g_debugserver_file_spec = debugserver_file_spec;
2468 }
2469 else
2470 {
2471 g_debugserver_file_spec.Clear();
2472 debugserver_file_spec.Clear();
2473 }
Chris Lattner24943d22010-06-08 16:52:24 +00002474 }
2475 }
2476
2477 if (debugserver_exists)
2478 {
2479 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2480
2481 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002482
Greg Claytone005f2c2010-11-06 01:53:30 +00002483 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002484
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002485 Args &debugserver_args = debugserver_launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002486 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002487
Chris Lattner24943d22010-06-08 16:52:24 +00002488 // Start args with "debugserver /file/path -r --"
2489 debugserver_args.AppendArgument(debugserver_path);
2490 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002491 // use native registers, not the GDB registers
2492 debugserver_args.AppendArgument("--native-regs");
2493 // make debugserver run in its own session so signals generated by
2494 // special terminal key sequences (^C) don't affect debugserver
2495 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002496
Chris Lattner24943d22010-06-08 16:52:24 +00002497 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2498 if (env_debugserver_log_file)
2499 {
2500 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2501 debugserver_args.AppendArgument(arg_cstr);
2502 }
2503
2504 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2505 if (env_debugserver_log_flags)
2506 {
2507 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2508 debugserver_args.AppendArgument(arg_cstr);
2509 }
Jim Ingham2b2ac8c2012-10-03 22:31:30 +00002510// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
2511// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002512
Greg Claytonb72d0f02011-04-12 05:54:46 +00002513 // We currently send down all arguments, attach pids, or attach
2514 // process names in dedicated GDB server packets, so we don't need
2515 // to pass them as arguments. This is currently because of all the
2516 // things we need to setup prior to launching: the environment,
2517 // current working dir, file actions, etc.
2518#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002519 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002520 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002521 {
Greg Claytona2f74232011-02-24 22:24:29 +00002522 // Terminate the debugserver args so we can now append the inferior args
2523 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002524
Greg Claytona2f74232011-02-24 22:24:29 +00002525 for (int i = 0; inferior_argv[i] != NULL; ++i)
2526 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002527 }
2528 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2529 {
2530 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2531 debugserver_args.AppendArgument (arg_cstr);
2532 }
2533 else if (attach_name && attach_name[0])
2534 {
2535 if (wait_for_launch)
2536 debugserver_args.AppendArgument ("--waitfor");
2537 else
2538 debugserver_args.AppendArgument ("--attach");
2539 debugserver_args.AppendArgument (attach_name);
2540 }
Chris Lattner24943d22010-06-08 16:52:24 +00002541#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002542
2543 ProcessLaunchInfo::FileAction file_action;
2544
2545 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2546 // to "/dev/null" if we run into any problems.
2547 file_action.Close (STDIN_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002548 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002549 file_action.Close (STDOUT_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002550 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002551 file_action.Close (STDERR_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002552 debugserver_launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002553
2554 if (log)
2555 {
2556 StreamString strm;
2557 debugserver_args.Dump (&strm);
2558 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2559 }
2560
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002561 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2562 debugserver_launch_info.SetUserID(process_info.GetUserID());
Greg Clayton1c4642c2011-11-16 05:37:56 +00002563
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002564 error = Host::LaunchProcess(debugserver_launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002565
Greg Claytonb72d0f02011-04-12 05:54:46 +00002566 if (error.Success ())
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002567 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002568 else
Chris Lattner24943d22010-06-08 16:52:24 +00002569 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2570
2571 if (error.Fail() || log)
Greg Claytond9919d32011-12-01 23:28:38 +00002572 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%llu, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002573 }
2574 else
2575 {
Greg Clayton9c236732011-10-26 00:56:27 +00002576 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002577 }
2578
2579 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2580 StartAsyncThread ();
2581 }
2582 return error;
2583}
2584
2585bool
2586ProcessGDBRemote::MonitorDebugserverProcess
2587(
2588 void *callback_baton,
2589 lldb::pid_t debugserver_pid,
Greg Clayton1c4642c2011-11-16 05:37:56 +00002590 bool exited, // True if the process did exit
Chris Lattner24943d22010-06-08 16:52:24 +00002591 int signo, // Zero for no signal
2592 int exit_status // Exit value of process if signal is zero
2593)
2594{
Greg Clayton1c4642c2011-11-16 05:37:56 +00002595 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2596 // and might not exist anymore, so we need to carefully try to get the
2597 // target for this process first since we have a race condition when
2598 // we are done running between getting the notice that the inferior
2599 // process has died and the debugserver that was debugging this process.
2600 // In our test suite, we are also continually running process after
2601 // process, so we must be very careful to make sure:
2602 // 1 - process object hasn't been deleted already
2603 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner24943d22010-06-08 16:52:24 +00002604
2605 // "debugserver_pid" argument passed in is the process ID for
2606 // debugserver that we are tracking...
Greg Clayton1c4642c2011-11-16 05:37:56 +00002607 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002608
Greg Clayton75ccf502010-08-21 02:22:51 +00002609 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002610
Greg Clayton1c4642c2011-11-16 05:37:56 +00002611 // Get a shared pointer to the target that has a matching process pointer.
2612 // This target could be gone, or the target could already have a new process
2613 // object inside of it
2614 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2615
Greg Clayton72e1c782011-01-22 23:43:18 +00002616 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00002617 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 +00002618
Greg Clayton1c4642c2011-11-16 05:37:56 +00002619 if (target_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002620 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002621 // We found a process in a target that matches, but another thread
2622 // might be in the process of launching a new process that will
2623 // soon replace it, so get a shared pointer to the process so we
2624 // can keep it alive.
2625 ProcessSP process_sp (target_sp->GetProcessSP());
2626 // Now we have a shared pointer to the process that can't go away on us
2627 // so we now make sure it was the same as the one passed in, and also make
2628 // sure that our previous "process *" didn't get deleted and have a new
2629 // "process *" created in its place with the same pointer. To verify this
2630 // we make sure the process has our debugserver process ID. If we pass all
2631 // of these tests, then we are sure that this process is the one we were
2632 // looking for.
2633 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner24943d22010-06-08 16:52:24 +00002634 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002635 // Sleep for a half a second to make sure our inferior process has
2636 // time to set its exit status before we set it incorrectly when
2637 // both the debugserver and the inferior process shut down.
2638 usleep (500000);
2639 // If our process hasn't yet exited, debugserver might have died.
2640 // If the process did exit, the we are reaping it.
2641 const StateType state = process->GetState();
2642
2643 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2644 state != eStateInvalid &&
2645 state != eStateUnloaded &&
2646 state != eStateExited &&
2647 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002648 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002649 char error_str[1024];
2650 if (signo)
2651 {
2652 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2653 if (signal_cstr)
2654 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2655 else
2656 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2657 }
Chris Lattner24943d22010-06-08 16:52:24 +00002658 else
Greg Clayton1c4642c2011-11-16 05:37:56 +00002659 {
2660 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2661 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002662
Greg Clayton1c4642c2011-11-16 05:37:56 +00002663 process->SetExitStatus (-1, error_str);
2664 }
2665 // Debugserver has exited we need to let our ProcessGDBRemote
2666 // know that it no longer has a debugserver instance
2667 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton75ccf502010-08-21 02:22:51 +00002668 }
Chris Lattner24943d22010-06-08 16:52:24 +00002669 }
2670 return true;
2671}
2672
2673void
2674ProcessGDBRemote::KillDebugserverProcess ()
2675{
2676 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2677 {
2678 ::kill (m_debugserver_pid, SIGINT);
2679 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2680 }
2681}
2682
2683void
2684ProcessGDBRemote::Initialize()
2685{
2686 static bool g_initialized = false;
2687
2688 if (g_initialized == false)
2689 {
2690 g_initialized = true;
2691 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2692 GetPluginDescriptionStatic(),
2693 CreateInstance);
2694
2695 Log::Callbacks log_callbacks = {
2696 ProcessGDBRemoteLog::DisableLog,
2697 ProcessGDBRemoteLog::EnableLog,
2698 ProcessGDBRemoteLog::ListLogCategories
2699 };
2700
2701 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2702 }
2703}
2704
2705bool
Chris Lattner24943d22010-06-08 16:52:24 +00002706ProcessGDBRemote::StartAsyncThread ()
2707{
Greg Claytone005f2c2010-11-06 01:53:30 +00002708 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002709
2710 if (log)
2711 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2712
2713 // Create a thread that watches our internal state and controls which
2714 // events make it to clients (into the DCProcess event queue).
2715 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002716 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002717}
2718
2719void
2720ProcessGDBRemote::StopAsyncThread ()
2721{
Greg Claytone005f2c2010-11-06 01:53:30 +00002722 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002723
2724 if (log)
2725 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2726
2727 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
Jim Ingham8226e942011-10-28 01:11:35 +00002728
2729 // This will shut down the async thread.
2730 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
Chris Lattner24943d22010-06-08 16:52:24 +00002731
2732 // Stop the stdio thread
Greg Clayton09c81ef2011-02-08 01:34:25 +00002733 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002734 {
2735 Host::ThreadJoin (m_async_thread, NULL, NULL);
2736 }
2737}
2738
2739
2740void *
2741ProcessGDBRemote::AsyncThread (void *arg)
2742{
2743 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2744
Greg Claytone005f2c2010-11-06 01:53:30 +00002745 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002746 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002747 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002748
2749 Listener listener ("ProcessGDBRemote::AsyncThread");
2750 EventSP event_sp;
2751 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2752 eBroadcastBitAsyncThreadShouldExit;
2753
2754 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2755 {
Greg Claytona2f74232011-02-24 22:24:29 +00002756 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2757
Chris Lattner24943d22010-06-08 16:52:24 +00002758 bool done = false;
2759 while (!done)
2760 {
2761 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002762 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002763 if (listener.WaitForEvent (NULL, event_sp))
2764 {
2765 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002766 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002767 {
Greg Claytona2f74232011-02-24 22:24:29 +00002768 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002769 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 +00002770
Greg Claytona2f74232011-02-24 22:24:29 +00002771 switch (event_type)
2772 {
2773 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002774 {
Greg Claytona2f74232011-02-24 22:24:29 +00002775 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002776
Greg Claytona2f74232011-02-24 22:24:29 +00002777 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002778 {
Greg Claytona2f74232011-02-24 22:24:29 +00002779 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2780 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2781 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002782 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002783
Greg Claytona2f74232011-02-24 22:24:29 +00002784 if (::strstr (continue_cstr, "vAttach") == NULL)
2785 process->SetPrivateState(eStateRunning);
2786 StringExtractorGDBRemote response;
2787 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002788
Greg Clayton67b402c2012-05-16 02:48:06 +00002789 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
2790 // The thread ID list might be contained within the "response", or the stop reply packet that
2791 // caused the stop. So clear it now before we give the stop reply packet to the process
2792 // using the process->SetLastStopPacket()...
2793 process->ClearThreadIDList ();
2794
Greg Claytona2f74232011-02-24 22:24:29 +00002795 switch (stop_state)
2796 {
2797 case eStateStopped:
2798 case eStateCrashed:
2799 case eStateSuspended:
Greg Clayton06709002011-12-06 04:51:14 +00002800 process->SetLastStopPacket (response);
Greg Claytona2f74232011-02-24 22:24:29 +00002801 process->SetPrivateState (stop_state);
2802 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002803
Greg Claytona2f74232011-02-24 22:24:29 +00002804 case eStateExited:
Greg Clayton06709002011-12-06 04:51:14 +00002805 process->SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00002806 process->ClearThreadIDList();
Greg Claytona2f74232011-02-24 22:24:29 +00002807 response.SetFilePos(1);
2808 process->SetExitStatus(response.GetHexU8(), NULL);
2809 done = true;
2810 break;
2811
2812 case eStateInvalid:
2813 process->SetExitStatus(-1, "lost connection");
2814 break;
2815
2816 default:
2817 process->SetPrivateState (stop_state);
2818 break;
2819 }
Chris Lattner24943d22010-06-08 16:52:24 +00002820 }
2821 }
Greg Claytona2f74232011-02-24 22:24:29 +00002822 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002823
Greg Claytona2f74232011-02-24 22:24:29 +00002824 case eBroadcastBitAsyncThreadShouldExit:
2825 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002826 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Claytona2f74232011-02-24 22:24:29 +00002827 done = true;
2828 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002829
Greg Claytona2f74232011-02-24 22:24:29 +00002830 default:
2831 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002832 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 +00002833 done = true;
2834 break;
2835 }
2836 }
2837 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2838 {
2839 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2840 {
2841 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002842 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002843 }
Chris Lattner24943d22010-06-08 16:52:24 +00002844 }
2845 }
2846 else
2847 {
2848 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002849 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 +00002850 done = true;
2851 }
2852 }
2853 }
2854
2855 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002856 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002857
2858 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2859 return NULL;
2860}
2861
Chris Lattner24943d22010-06-08 16:52:24 +00002862const char *
2863ProcessGDBRemote::GetDispatchQueueNameForThread
2864(
2865 addr_t thread_dispatch_qaddr,
2866 std::string &dispatch_queue_name
2867)
2868{
2869 dispatch_queue_name.clear();
2870 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2871 {
2872 // Cache the dispatch_queue_offsets_addr value so we don't always have
2873 // to look it up
2874 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2875 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002876 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2877 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton444fe992012-02-26 05:51:37 +00002878 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false));
2879 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002880 if (module_sp)
2881 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2882
2883 if (dispatch_queue_offsets_symbol == NULL)
2884 {
Greg Clayton444fe992012-02-26 05:51:37 +00002885 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false));
2886 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_module_spec);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002887 if (module_sp)
2888 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2889 }
Chris Lattner24943d22010-06-08 16:52:24 +00002890 if (dispatch_queue_offsets_symbol)
Greg Clayton0c31d3d2012-03-07 21:03:09 +00002891 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002892
2893 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2894 return NULL;
2895 }
2896
2897 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002898 DataExtractor data (memory_buffer,
2899 sizeof(memory_buffer),
2900 m_target.GetArchitecture().GetByteOrder(),
2901 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002902
2903 // Excerpt from src/queue_private.h
2904 struct dispatch_queue_offsets_s
2905 {
2906 uint16_t dqo_version;
2907 uint16_t dqo_label;
2908 uint16_t dqo_label_size;
2909 } dispatch_queue_offsets;
2910
2911
2912 Error error;
2913 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2914 {
2915 uint32_t data_offset = 0;
2916 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2917 {
2918 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2919 {
2920 data_offset = 0;
2921 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
2922 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2923 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2924 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2925 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2926 dispatch_queue_name.erase (bytes_read);
2927 }
2928 }
2929 }
2930 }
2931 if (dispatch_queue_name.empty())
2932 return NULL;
2933 return dispatch_queue_name.c_str();
2934}
2935
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002936//uint32_t
2937//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2938//{
2939// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2940// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2941// if (m_local_debugserver)
2942// {
2943// return Host::ListProcessesMatchingName (name, matches, pids);
2944// }
2945// else
2946// {
2947// // FIXME: Implement talking to the remote debugserver.
2948// return 0;
2949// }
2950//
2951//}
2952//
Jim Ingham55e01d82011-01-22 01:33:44 +00002953bool
2954ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2955 lldb_private::StoppointCallbackContext *context,
2956 lldb::user_id_t break_id,
2957 lldb::user_id_t break_loc_id)
2958{
2959 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2960 // run so I can stop it if that's what I want to do.
2961 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
2962 if (log)
2963 log->Printf("Hit New Thread Notification breakpoint.");
2964 return false;
2965}
2966
2967
2968bool
2969ProcessGDBRemote::StartNoticingNewThreads()
2970{
Jim Ingham55e01d82011-01-22 01:33:44 +00002971 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002972 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00002973 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002974 if (log && log->GetVerbose())
2975 log->Printf("Enabled noticing new thread breakpoint.");
2976 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham55e01d82011-01-22 01:33:44 +00002977 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002978 else
Jim Ingham55e01d82011-01-22 01:33:44 +00002979 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002980 PlatformSP platform_sp (m_target.GetPlatform());
2981 if (platform_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00002982 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002983 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
2984 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00002985 {
Jim Ingham6bb73372011-10-15 00:21:37 +00002986 if (log && log->GetVerbose())
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002987 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
2988 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham55e01d82011-01-22 01:33:44 +00002989 }
2990 else
2991 {
2992 if (log)
2993 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00002994 }
2995 }
2996 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00002997 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham55e01d82011-01-22 01:33:44 +00002998}
2999
3000bool
3001ProcessGDBRemote::StopNoticingNewThreads()
3002{
Jim Inghamff276fe2011-02-08 05:19:01 +00003003 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham6bb73372011-10-15 00:21:37 +00003004 if (log && log->GetVerbose())
Jim Inghamff276fe2011-02-08 05:19:01 +00003005 log->Printf ("Disabling new thread notification breakpoint.");
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003006
3007 if (m_thread_create_bp_sp)
3008 m_thread_create_bp_sp->SetEnabled(false);
3009
Jim Ingham55e01d82011-01-22 01:33:44 +00003010 return true;
3011}
3012
Jason Molendab46937c2012-10-03 01:29:34 +00003013lldb_private::DynamicLoader *
3014ProcessGDBRemote::GetDynamicLoader ()
3015{
3016 if (m_dyld_ap.get() == NULL)
3017 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, m_dyld_plugin_name.empty() ? NULL : m_dyld_plugin_name.c_str()));
3018 return m_dyld_ap.get();
3019}
Jim Ingham55e01d82011-01-22 01:33:44 +00003020
Greg Clayton13193d52012-10-13 02:07:45 +00003021
Greg Claytonb8596392012-10-15 22:42:16 +00003022class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton13193d52012-10-13 02:07:45 +00003023{
3024private:
3025
3026public:
Greg Claytonb8596392012-10-15 22:42:16 +00003027 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton13193d52012-10-13 02:07:45 +00003028 CommandObjectParsed (interpreter,
Greg Claytonb8596392012-10-15 22:42:16 +00003029 "process plugin packet history",
3030 "Dumps the packet history buffer. ",
Greg Clayton13193d52012-10-13 02:07:45 +00003031 NULL)
3032 {
3033 }
3034
Greg Claytonb8596392012-10-15 22:42:16 +00003035 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton13193d52012-10-13 02:07:45 +00003036 {
3037 }
3038
3039 bool
3040 DoExecute (Args& command, CommandReturnObject &result)
3041 {
Greg Claytonb8596392012-10-15 22:42:16 +00003042 const size_t argc = command.GetArgumentCount();
3043 if (argc == 0)
3044 {
3045 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3046 if (process)
3047 {
3048 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
3049 result.SetStatus (eReturnStatusSuccessFinishResult);
3050 return true;
3051 }
3052 }
3053 else
3054 {
3055 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
3056 }
3057 result.SetStatus (eReturnStatusFailed);
3058 return false;
3059 }
3060};
3061
3062class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
3063{
3064private:
3065
3066public:
3067 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
3068 CommandObjectParsed (interpreter,
3069 "process plugin packet send",
3070 "Send a custom packet through the GDB remote protocol and print the answer. "
3071 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
3072 NULL)
3073 {
3074 }
3075
3076 ~CommandObjectProcessGDBRemotePacketSend ()
3077 {
3078 }
3079
3080 bool
3081 DoExecute (Args& command, CommandReturnObject &result)
3082 {
3083 const size_t argc = command.GetArgumentCount();
3084 if (argc == 0)
3085 {
3086 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
3087 result.SetStatus (eReturnStatusFailed);
3088 return false;
3089 }
3090
3091 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3092 if (process)
3093 {
3094 const StateType state = process->GetState();
3095
3096 if (StateIsStoppedState (state, true))
3097 {
3098 for (size_t i=0; i<argc; ++ i)
3099 {
3100 const char *packet_cstr = command.GetArgumentAtIndex(0);
3101 bool send_async = false;
3102 StringExtractorGDBRemote response;
3103 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3104 result.SetStatus (eReturnStatusSuccessFinishResult);
3105 Stream &output_strm = result.GetOutputStream();
3106 output_strm.Printf (" packet: %s\n", packet_cstr);
3107 const std::string &response_str = response.GetStringRef();
3108 if (response_str.empty())
3109 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3110 else
3111 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
3112 }
3113 }
3114 else
3115 {
3116 result.AppendErrorWithFormat ("process must be stopped in order to send GDB remote packets, state is %s", StateAsCString (state));
3117 result.SetStatus (eReturnStatusFailed);
3118 return false;
3119 }
3120
3121 }
Greg Clayton13193d52012-10-13 02:07:45 +00003122 return true;
3123 }
3124};
3125
Greg Claytonb8596392012-10-15 22:42:16 +00003126class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
3127{
3128private:
3129
3130public:
3131 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
3132 CommandObjectMultiword (interpreter,
3133 "process plugin packet",
3134 "Commands that deal with GDB remote packets.",
3135 NULL)
3136 {
3137 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
3138 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
3139 }
3140
3141 ~CommandObjectProcessGDBRemotePacket ()
3142 {
3143 }
3144};
Greg Clayton13193d52012-10-13 02:07:45 +00003145
3146class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
3147{
3148public:
3149 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
3150 CommandObjectMultiword (interpreter,
3151 "process plugin",
3152 "A set of commands for operating on a ProcessGDBRemote process.",
3153 "process plugin <subcommand> [<subcommand-options>]")
3154 {
3155 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
3156 }
3157
3158 ~CommandObjectMultiwordProcessGDBRemote ()
3159 {
3160 }
3161};
3162
Greg Clayton13193d52012-10-13 02:07:45 +00003163CommandObject *
3164ProcessGDBRemote::GetPluginCommandObject()
3165{
3166 if (!m_command_sp)
3167 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
3168 return m_command_sp.get();
3169}