blob: 7bc03005b70bb975abfc98a6b508b604e6f5a36e [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),
Jim Inghama9488302012-11-01 01:15:33 +0000191 m_async_thread_state(eAsyncThreadNotStarted),
192 m_async_thread_state_mutex(Mutex::eMutexTypeRecursive),
Greg Clayton5a9f85c2012-04-10 02:25:43 +0000193 m_thread_ids (),
Greg Claytonc1f45872011-02-12 06:28:37 +0000194 m_continue_c_tids (),
195 m_continue_C_tids (),
196 m_continue_s_tids (),
197 m_continue_S_tids (),
Chris Lattner24943d22010-06-08 16:52:24 +0000198 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000199 m_max_memory_size (512),
Greg Claytonbd5c23d2012-05-15 02:33:01 +0000200 m_addr_to_mmap_size (),
201 m_thread_create_bp_sp (),
Jim Ingham06b84492012-07-04 00:35:43 +0000202 m_waiting_for_attach (false),
Jason Molendab46937c2012-10-03 01:29:34 +0000203 m_destroy_tried_resuming (false),
204 m_dyld_plugin_name(),
Greg Clayton13193d52012-10-13 02:07:45 +0000205 m_kernel_load_addr (LLDB_INVALID_ADDRESS),
206 m_command_sp ()
Chris Lattner24943d22010-06-08 16:52:24 +0000207{
Greg Claytonff39f742011-04-01 00:29:43 +0000208 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
209 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +0000210 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Chris Lattner24943d22010-06-08 16:52:24 +0000211}
212
213//----------------------------------------------------------------------
214// Destructor
215//----------------------------------------------------------------------
216ProcessGDBRemote::~ProcessGDBRemote()
217{
218 // m_mach_process.UnregisterNotificationCallbacks (this);
219 Clear();
Greg Clayton2f57db02011-10-01 00:45:15 +0000220 // We need to call finalize on the process before destroying ourselves
221 // to make sure all of the broadcaster cleanup goes as planned. If we
222 // destruct this class, then Process::~Process() might have problems
223 // trying to fully destroy the broadcaster.
224 Finalize();
Jim Inghama9488302012-11-01 01:15:33 +0000225
226 // The general Finalize is going to try to destroy the process and that SHOULD
227 // shut down the async thread. However, if we don't kill it it will get stranded and
228 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
229 StopAsyncThread();
230 KillDebugserverProcess();
Chris Lattner24943d22010-06-08 16:52:24 +0000231}
232
233//----------------------------------------------------------------------
234// PluginInterface
235//----------------------------------------------------------------------
236const char *
237ProcessGDBRemote::GetPluginName()
238{
239 return "Process debugging plug-in that uses the GDB remote protocol";
240}
241
242const char *
243ProcessGDBRemote::GetShortPluginName()
244{
245 return GetPluginNameStatic();
246}
247
248uint32_t
249ProcessGDBRemote::GetPluginVersion()
250{
251 return 1;
252}
253
254void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000255ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000256{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000257 if (!force && m_register_info.GetNumRegisters() > 0)
258 return;
259
260 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000261 m_register_info.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000262 uint32_t reg_offset = 0;
263 uint32_t reg_num = 0;
Greg Clayton4a379b12012-07-17 03:23:13 +0000264 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Greg Clayton61d043b2011-03-22 04:00:09 +0000265 response_type == StringExtractorGDBRemote::eResponse;
266 ++reg_num)
Chris Lattner24943d22010-06-08 16:52:24 +0000267 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000268 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
269 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000270 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000271 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000272 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000273 response_type = response.GetResponseType();
274 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner24943d22010-06-08 16:52:24 +0000275 {
276 std::string name;
277 std::string value;
278 ConstString reg_name;
279 ConstString alt_name;
280 ConstString set_name;
281 RegisterInfo reg_info = { NULL, // Name
282 NULL, // Alt name
283 0, // byte size
284 reg_offset, // offset
285 eEncodingUint, // encoding
286 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000287 {
288 LLDB_INVALID_REGNUM, // GCC reg num
289 LLDB_INVALID_REGNUM, // DWARF reg num
290 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000291 reg_num, // GDB reg num
292 reg_num // native register number
Greg Claytoncd330422012-02-29 19:27:27 +0000293 },
294 NULL,
295 NULL
Chris Lattner24943d22010-06-08 16:52:24 +0000296 };
297
298 while (response.GetNameColonValue(name, value))
299 {
300 if (name.compare("name") == 0)
301 {
302 reg_name.SetCString(value.c_str());
303 }
304 else if (name.compare("alt-name") == 0)
305 {
306 alt_name.SetCString(value.c_str());
307 }
308 else if (name.compare("bitsize") == 0)
309 {
310 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
311 }
312 else if (name.compare("offset") == 0)
313 {
314 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000315 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000316 {
317 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000318 }
319 }
320 else if (name.compare("encoding") == 0)
321 {
Greg Clayton88b980b2012-08-24 01:42:50 +0000322 const Encoding encoding = Args::StringToEncoding (value.c_str());
323 if (encoding != eEncodingInvalid)
324 reg_info.encoding = encoding;
Chris Lattner24943d22010-06-08 16:52:24 +0000325 }
326 else if (name.compare("format") == 0)
327 {
Greg Clayton88b980b2012-08-24 01:42:50 +0000328 Format format = eFormatInvalid;
329 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
330 reg_info.format = format;
331 else if (value.compare("binary") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +0000332 reg_info.format = eFormatBinary;
333 else if (value.compare("decimal") == 0)
334 reg_info.format = eFormatDecimal;
335 else if (value.compare("hex") == 0)
336 reg_info.format = eFormatHex;
337 else if (value.compare("float") == 0)
338 reg_info.format = eFormatFloat;
339 else if (value.compare("vector-sint8") == 0)
340 reg_info.format = eFormatVectorOfSInt8;
341 else if (value.compare("vector-uint8") == 0)
342 reg_info.format = eFormatVectorOfUInt8;
343 else if (value.compare("vector-sint16") == 0)
344 reg_info.format = eFormatVectorOfSInt16;
345 else if (value.compare("vector-uint16") == 0)
346 reg_info.format = eFormatVectorOfUInt16;
347 else if (value.compare("vector-sint32") == 0)
348 reg_info.format = eFormatVectorOfSInt32;
349 else if (value.compare("vector-uint32") == 0)
350 reg_info.format = eFormatVectorOfUInt32;
351 else if (value.compare("vector-float32") == 0)
352 reg_info.format = eFormatVectorOfFloat32;
353 else if (value.compare("vector-uint128") == 0)
354 reg_info.format = eFormatVectorOfUInt128;
355 }
356 else if (name.compare("set") == 0)
357 {
358 set_name.SetCString(value.c_str());
359 }
360 else if (name.compare("gcc") == 0)
361 {
362 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
363 }
364 else if (name.compare("dwarf") == 0)
365 {
366 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
367 }
368 else if (name.compare("generic") == 0)
369 {
Greg Clayton88b980b2012-08-24 01:42:50 +0000370 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000371 }
372 }
373
Jason Molenda53d96862010-06-11 23:44:18 +0000374 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000375 assert (reg_info.byte_size != 0);
376 reg_offset += reg_info.byte_size;
377 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
378 }
379 }
380 else
381 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000382 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000383 }
384 }
385
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000386 // We didn't get anything if the accumulated reg_num is zero. See if we are
387 // debugging ARM and fill with a hard coded register set until we can get an
388 // updated debugserver down on the devices.
389 // On the other hand, if the accumulated reg_num is positive, see if we can
390 // add composite registers to the existing primordial ones.
391 bool from_scratch = (reg_num == 0);
392
393 const ArchSpec &target_arch = GetTarget().GetArchitecture();
394 const ArchSpec &remote_arch = m_gdb_comm.GetHostArchitecture();
395 if (!target_arch.IsValid())
Chris Lattner24943d22010-06-08 16:52:24 +0000396 {
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000397 if (remote_arch.IsValid()
398 && remote_arch.GetMachine() == llvm::Triple::arm
399 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
400 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner24943d22010-06-08 16:52:24 +0000401 }
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000402 else if (target_arch.GetMachine() == llvm::Triple::arm)
403 {
404 m_register_info.HardcodeARMRegisters(from_scratch);
405 }
406
Johnny Chend2e30662012-05-22 00:57:05 +0000407 // Add some convenience registers (eax, ebx, ecx, edx, esi, edi, ebp, esp) to x86_64.
Johnny Chenbe315a62012-06-08 19:06:28 +0000408 if ((target_arch.IsValid() && target_arch.GetMachine() == llvm::Triple::x86_64)
409 || (remote_arch.IsValid() && remote_arch.GetMachine() == llvm::Triple::x86_64))
Johnny Chend2e30662012-05-22 00:57:05 +0000410 m_register_info.Addx86_64ConvenienceRegisters();
411
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000412 // At this point, we can finalize our register info.
Chris Lattner24943d22010-06-08 16:52:24 +0000413 m_register_info.Finalize ();
414}
415
416Error
417ProcessGDBRemote::WillLaunch (Module* module)
418{
419 return WillLaunchOrAttach ();
420}
421
422Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000423ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000424{
425 return WillLaunchOrAttach ();
426}
427
428Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000429ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000430{
431 return WillLaunchOrAttach ();
432}
433
434Error
Jason Molendafac2e622012-09-29 04:02:01 +0000435ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytone71e2582011-02-04 01:58:07 +0000436{
437 Error error (WillLaunchOrAttach ());
438
439 if (error.Fail())
440 return error;
441
Greg Clayton180546b2011-04-30 01:09:13 +0000442 error = ConnectToDebugserver (remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000443
444 if (error.Fail())
445 return error;
446 StartAsyncThread ();
447
Jason Molendab46937c2012-10-03 01:29:34 +0000448 CheckForKernel (strm);
Jason Molendafac2e622012-09-29 04:02:01 +0000449
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000450 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000451 if (pid == LLDB_INVALID_PROCESS_ID)
452 {
453 // We don't have a valid process ID, so note that we are connected
454 // and could now request to launch or attach, or get remote process
455 // listings...
456 SetPrivateState (eStateConnected);
457 }
458 else
459 {
460 // We have a valid process
461 SetID (pid);
Greg Clayton37f962e2011-08-22 02:49:39 +0000462 GetThreadList();
Greg Clayton261a18b2011-06-02 22:22:38 +0000463 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000464 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000465 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytone71e2582011-02-04 01:58:07 +0000466 if (state == eStateStopped)
467 {
468 SetPrivateState (state);
469 }
470 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000471 error.SetErrorStringWithFormat ("Process %" PRIu64 " was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
Greg Claytone71e2582011-02-04 01:58:07 +0000472 }
473 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000474 error.SetErrorStringWithFormat ("Process %" PRIu64 " was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000475 }
Jason Molendacb740b32012-05-03 22:37:30 +0000476
477 if (error.Success()
478 && !GetTarget().GetArchitecture().IsValid()
479 && m_gdb_comm.GetHostArchitecture().IsValid())
480 {
481 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
482 }
483
Greg Claytone71e2582011-02-04 01:58:07 +0000484 return error;
485}
486
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000487// When we are establishing a connection to a remote system and we have no executable specified,
488// or the executable is a kernel, we may be looking at a KASLR situation (where the kernel has been
489// slid in memory.)
490//
Jason Molendab46937c2012-10-03 01:29:34 +0000491// This function tries to locate the kernel in memory if this is possibly a kernel debug session.
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000492//
Jason Molendab46937c2012-10-03 01:29:34 +0000493// If a kernel is found, return the address of the kernel in GetImageInfoAddress() -- the
494// DynamicLoaderDarwinKernel plugin uses this address as the kernel load address and will load the
495// binary, if needed, along with all the kexts.
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000496
497void
Jason Molendab46937c2012-10-03 01:29:34 +0000498ProcessGDBRemote::CheckForKernel (Stream *strm)
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000499{
500 // early return if this isn't an "unknown" system (kernel debugging doesn't have a system type)
501 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
502 if (!gdb_remote_arch.IsValid() || gdb_remote_arch.GetTriple().getVendor() != llvm::Triple::UnknownVendor)
503 return;
504
505 Module *exe_module = GetTarget().GetExecutableModulePointer();
506 ObjectFile *exe_objfile = NULL;
507 if (exe_module)
508 exe_objfile = exe_module->GetObjectFile();
509
510 // early return if we have an executable and it is not a kernel--this is very unlikely to be a kernel debug session.
511 if (exe_objfile
512 && (exe_objfile->GetType() != ObjectFile::eTypeExecutable
513 || exe_objfile->GetStrata() != ObjectFile::eStrataKernel))
514 return;
515
516 // See if the kernel is in memory at the File address (slide == 0) -- no work needed, if so.
517 if (exe_objfile && exe_objfile->GetHeaderAddress().IsValid())
518 {
519 ModuleSP memory_module_sp;
520 memory_module_sp = ReadModuleFromMemory (exe_module->GetFileSpec(), exe_objfile->GetHeaderAddress().GetFileAddress(), false, false);
521 if (memory_module_sp.get()
522 && memory_module_sp->GetUUID().IsValid()
523 && memory_module_sp->GetUUID() == exe_module->GetUUID())
524 {
Jason Molendab46937c2012-10-03 01:29:34 +0000525 m_kernel_load_addr = exe_objfile->GetHeaderAddress().GetFileAddress();
526 m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
Jason Molendad6b81222012-10-06 02:02:26 +0000527 SetCanJIT(false);
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000528 return;
529 }
530 }
531
532 // See if the kernel's load address is stored in the kernel's low globals page; this is
533 // done when a debug boot-arg has been set.
534
535 Error error;
536 uint8_t buf[24];
537 ModuleSP memory_module_sp;
538 addr_t kernel_addr = LLDB_INVALID_ADDRESS;
539
540 // First try the 32-bit
541 if (memory_module_sp.get() == NULL)
542 {
543 DataExtractor data4 (buf, sizeof(buf), gdb_remote_arch.GetByteOrder(), 4);
544 if (DoReadMemory (0xffff0110, buf, 4, error) == 4)
545 {
546 uint32_t offset = 0;
547 kernel_addr = data4.GetU32(&offset);
548 memory_module_sp = ReadModuleFromMemory (FileSpec("mach_kernel", false), kernel_addr, false, false);
549 if (!memory_module_sp.get()
550 || !memory_module_sp->GetUUID().IsValid()
551 || memory_module_sp->GetObjectFile() == NULL
552 || memory_module_sp->GetObjectFile()->GetType() != ObjectFile::eTypeExecutable
553 || memory_module_sp->GetObjectFile()->GetStrata() != ObjectFile::eStrataKernel)
554 {
555 memory_module_sp.reset();
556 }
557 }
558 }
559
560 // Now try the 64-bit location
561 if (memory_module_sp.get() == NULL)
562 {
563 DataExtractor data8 (buf, sizeof(buf), gdb_remote_arch.GetByteOrder(), 8);
564 if (DoReadMemory (0xffffff8000002010ULL, buf, 8, error) == 8)
565 {
566 uint32_t offset = 0;
Jason Molendac557e7d2012-12-01 04:46:58 +0000567 kernel_addr = data8.GetU64(&offset);
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000568 memory_module_sp = ReadModuleFromMemory (FileSpec("mach_kernel", false), kernel_addr, false, false);
569 if (!memory_module_sp.get()
570 || !memory_module_sp->GetUUID().IsValid()
571 || memory_module_sp->GetObjectFile() == NULL
572 || memory_module_sp->GetObjectFile()->GetType() != ObjectFile::eTypeExecutable
573 || memory_module_sp->GetObjectFile()->GetStrata() != ObjectFile::eStrataKernel)
574 {
575 memory_module_sp.reset();
576 }
577 }
578 }
579
Jason Molendab46937c2012-10-03 01:29:34 +0000580 if (memory_module_sp.get()
581 && memory_module_sp->GetArchitecture().IsValid()
582 && memory_module_sp->GetArchitecture().GetTriple().getVendor() == llvm::Triple::Apple)
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000583 {
Jason Molendab46937c2012-10-03 01:29:34 +0000584 m_kernel_load_addr = kernel_addr;
585 m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
Jason Molendad6b81222012-10-06 02:02:26 +0000586 SetCanJIT(false);
Jason Molendab46937c2012-10-03 01:29:34 +0000587 return;
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000588 }
589}
590
Greg Claytone71e2582011-02-04 01:58:07 +0000591Error
Chris Lattner24943d22010-06-08 16:52:24 +0000592ProcessGDBRemote::WillLaunchOrAttach ()
593{
594 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000595 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000596 return error;
597}
598
599//----------------------------------------------------------------------
600// Process Control
601//----------------------------------------------------------------------
602Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000603ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000604{
Greg Clayton4b407112010-09-30 21:49:03 +0000605 Error error;
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000606
607 uint32_t launch_flags = launch_info.GetFlags().Get();
608 const char *stdin_path = NULL;
609 const char *stdout_path = NULL;
610 const char *stderr_path = NULL;
611 const char *working_dir = launch_info.GetWorkingDirectory();
612
613 const ProcessLaunchInfo::FileAction *file_action;
614 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
615 if (file_action)
616 {
617 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
618 stdin_path = file_action->GetPath();
619 }
620 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
621 if (file_action)
622 {
623 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
624 stdout_path = file_action->GetPath();
625 }
626 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
627 if (file_action)
628 {
629 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
630 stderr_path = file_action->GetPath();
631 }
632
Chris Lattner24943d22010-06-08 16:52:24 +0000633 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
634 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
635 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton716cefb2011-08-09 05:20:29 +0000636 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000637
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000638 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner24943d22010-06-08 16:52:24 +0000639 if (object_file)
640 {
Chris Lattner24943d22010-06-08 16:52:24 +0000641 char host_port[128];
642 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000643 char connect_url[128];
644 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000645
Greg Claytona2f74232011-02-24 22:24:29 +0000646 // Make sure we aren't already connected?
647 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000648 {
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000649 error = StartDebugserverProcess (host_port, launch_info);
Chris Lattner24943d22010-06-08 16:52:24 +0000650 if (error.Fail())
Greg Clayton716cefb2011-08-09 05:20:29 +0000651 {
Johnny Chenc143d622011-08-09 18:56:45 +0000652 if (log)
653 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner24943d22010-06-08 16:52:24 +0000654 return error;
Greg Clayton716cefb2011-08-09 05:20:29 +0000655 }
Chris Lattner24943d22010-06-08 16:52:24 +0000656
Greg Claytone71e2582011-02-04 01:58:07 +0000657 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000658 }
659
660 if (error.Success())
661 {
662 lldb_utility::PseudoTerminal pty;
663 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000664
665 // If the debugserver is local and we aren't disabling STDIO, lets use
666 // a pseudo terminal to instead of relying on the 'O' packets for stdio
667 // since 'O' packets can really slow down debugging if the inferior
668 // does a lot of output.
Greg Claytonb4747822011-06-24 22:32:10 +0000669 PlatformSP platform_sp (m_target.GetPlatform());
670 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000671 {
672 const char *slave_name = NULL;
673 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000674 {
Greg Claytona2f74232011-02-24 22:24:29 +0000675 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
676 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000677 }
Greg Claytona2f74232011-02-24 22:24:29 +0000678 if (stdin_path == NULL)
679 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000680
Greg Claytona2f74232011-02-24 22:24:29 +0000681 if (stdout_path == NULL)
682 stdout_path = slave_name;
683
684 if (stderr_path == NULL)
685 stderr_path = slave_name;
686 }
687
Greg Claytonafb81862011-03-02 21:34:46 +0000688 // Set STDIN to /dev/null if we want STDIO disabled or if either
689 // STDOUT or STDERR have been set to something and STDIN hasn't
690 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000691 stdin_path = "/dev/null";
692
Greg Claytonafb81862011-03-02 21:34:46 +0000693 // Set STDOUT to /dev/null if we want STDIO disabled or if either
694 // STDIN or STDERR have been set to something and STDOUT hasn't
695 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000696 stdout_path = "/dev/null";
697
Greg Claytonafb81862011-03-02 21:34:46 +0000698 // Set STDERR to /dev/null if we want STDIO disabled or if either
699 // STDIN or STDOUT have been set to something and STDERR hasn't
700 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000701 stderr_path = "/dev/null";
702
703 if (stdin_path)
704 m_gdb_comm.SetSTDIN (stdin_path);
705 if (stdout_path)
706 m_gdb_comm.SetSTDOUT (stdout_path);
707 if (stderr_path)
708 m_gdb_comm.SetSTDERR (stderr_path);
709
710 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
711
Greg Claytona4582402011-05-08 04:53:50 +0000712 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000713
714 if (working_dir && working_dir[0])
715 {
716 m_gdb_comm.SetWorkingDir (working_dir);
717 }
718
719 // Send the environment and the program + arguments after we connect
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000720 const Args &environment = launch_info.GetEnvironmentEntries();
721 if (environment.GetArgumentCount())
Greg Claytona2f74232011-02-24 22:24:29 +0000722 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000723 size_t num_environment_entries = environment.GetArgumentCount();
724 for (size_t i=0; i<num_environment_entries; ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000725 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000726 const char *env_entry = environment.GetArgumentAtIndex(i);
727 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000728 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000729 }
Greg Claytona2f74232011-02-24 22:24:29 +0000730 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000731
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000732 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000733 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info.GetArguments().GetConstArgumentVector());
Greg Claytona2f74232011-02-24 22:24:29 +0000734 if (arg_packet_err == 0)
735 {
736 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000737 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000738 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000739 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000740 }
741 else
742 {
Greg Claytona2f74232011-02-24 22:24:29 +0000743 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000744 }
Greg Claytona2f74232011-02-24 22:24:29 +0000745 }
746 else
747 {
Greg Clayton9c236732011-10-26 00:56:27 +0000748 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Claytona2f74232011-02-24 22:24:29 +0000749 }
Greg Clayton7c4fc6e2011-08-10 22:05:39 +0000750
751 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner24943d22010-06-08 16:52:24 +0000752
Greg Claytona2f74232011-02-24 22:24:29 +0000753 if (GetID() == LLDB_INVALID_PROCESS_ID)
754 {
Johnny Chenc143d622011-08-09 18:56:45 +0000755 if (log)
756 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytona2f74232011-02-24 22:24:29 +0000757 KillDebugserverProcess ();
758 return error;
759 }
760
Greg Clayton261a18b2011-06-02 22:22:38 +0000761 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000762 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000763 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Claytona2f74232011-02-24 22:24:29 +0000764
765 if (!disable_stdio)
766 {
767 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Clayton464c6162011-11-17 22:14:31 +0000768 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Claytona2f74232011-02-24 22:24:29 +0000769 }
Chris Lattner24943d22010-06-08 16:52:24 +0000770 }
771 }
Greg Clayton716cefb2011-08-09 05:20:29 +0000772 else
773 {
Johnny Chenc143d622011-08-09 18:56:45 +0000774 if (log)
775 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton716cefb2011-08-09 05:20:29 +0000776 }
Chris Lattner24943d22010-06-08 16:52:24 +0000777 }
778 else
779 {
780 // Set our user ID to an invalid process ID.
781 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000782 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
783 exe_module->GetFileSpec().GetFilename().AsCString(),
784 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000785 }
Chris Lattner24943d22010-06-08 16:52:24 +0000786 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000787
Chris Lattner24943d22010-06-08 16:52:24 +0000788}
789
790
791Error
Greg Claytone71e2582011-02-04 01:58:07 +0000792ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000793{
794 Error error;
795 // Sleep and wait a bit for debugserver to start to listen...
796 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
797 if (conn_ap.get())
798 {
Chris Lattner24943d22010-06-08 16:52:24 +0000799 const uint32_t max_retry_count = 50;
800 uint32_t retry_count = 0;
801 while (!m_gdb_comm.IsConnected())
802 {
Greg Claytone71e2582011-02-04 01:58:07 +0000803 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000804 {
805 m_gdb_comm.SetConnection (conn_ap.release());
806 break;
807 }
808 retry_count++;
809
810 if (retry_count >= max_retry_count)
811 break;
812
813 usleep (100000);
814 }
815 }
816
817 if (!m_gdb_comm.IsConnected())
818 {
819 if (error.Success())
820 error.SetErrorString("not connected to remote gdb server");
821 return error;
822 }
823
Greg Clayton24bc5d92011-03-30 18:16:51 +0000824 // We always seem to be able to open a connection to a local port
825 // so we need to make sure we can then send data to it. If we can't
826 // then we aren't actually connected to anything, so try and do the
827 // handshake with the remote GDB server and make sure that goes
828 // alright.
829 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000830 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000831 m_gdb_comm.Disconnect();
832 if (error.Success())
833 error.SetErrorString("not connected to remote gdb server");
834 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000835 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000836 m_gdb_comm.ResetDiscoverableSettings();
837 m_gdb_comm.QueryNoAckModeSupported ();
838 m_gdb_comm.GetThreadSuffixSupported ();
Greg Claytona1f645e2012-04-10 03:22:03 +0000839 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000840 m_gdb_comm.GetHostInfo ();
841 m_gdb_comm.GetVContSupported ('c');
Jim Ingham3a458eb2012-07-20 21:37:13 +0000842 m_gdb_comm.GetVAttachOrWaitSupported();
Jim Ingham86827fb2012-07-02 05:40:07 +0000843
844 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
845 for (size_t idx = 0; idx < num_cmds; idx++)
846 {
847 StringExtractorGDBRemote response;
Jim Ingham86827fb2012-07-02 05:40:07 +0000848 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
849 }
Chris Lattner24943d22010-06-08 16:52:24 +0000850 return error;
851}
852
853void
854ProcessGDBRemote::DidLaunchOrAttach ()
855{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000856 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
857 if (log)
858 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000859 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000860 {
861 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
862
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000863 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000864
Chris Lattner24943d22010-06-08 16:52:24 +0000865 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000866
Greg Claytoncb8977d2011-03-23 00:09:55 +0000867 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
868 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000869 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000870 ArchSpec &target_arch = GetTarget().GetArchitecture();
871
872 if (target_arch.IsValid())
873 {
874 // If the remote host is ARM and we have apple as the vendor, then
875 // ARM executables and shared libraries can have mixed ARM architectures.
876 // You can have an armv6 executable, and if the host is armv7, then the
877 // system will load the best possible architecture for all shared libraries
878 // it has, so we really need to take the remote host architecture as our
879 // defacto architecture in this case.
880
881 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
882 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
883 {
884 target_arch = gdb_remote_arch;
885 }
886 else
887 {
888 // Fill in what is missing in the triple
889 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
890 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000891 if (target_triple.getVendorName().size() == 0)
892 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000893 target_triple.setVendor (remote_triple.getVendor());
894
Greg Clayton2f085c62011-05-15 01:25:55 +0000895 if (target_triple.getOSName().size() == 0)
896 {
897 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000898
Greg Clayton2f085c62011-05-15 01:25:55 +0000899 if (target_triple.getEnvironmentName().size() == 0)
900 target_triple.setEnvironment (remote_triple.getEnvironment());
901 }
902 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000903 }
904 }
905 else
906 {
907 // The target doesn't have a valid architecture yet, set it from
908 // the architecture we got from the remote GDB server
909 target_arch = gdb_remote_arch;
910 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000911 }
Chris Lattner24943d22010-06-08 16:52:24 +0000912 }
913}
914
915void
916ProcessGDBRemote::DidLaunch ()
917{
918 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000919}
920
921Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000922ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000923{
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000924 ProcessAttachInfo attach_info;
925 return DoAttachToProcessWithID(attach_pid, attach_info);
926}
927
928Error
929ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
930{
Chris Lattner24943d22010-06-08 16:52:24 +0000931 Error error;
932 // Clear out and clean up from any current state
933 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000934 if (attach_pid != LLDB_INVALID_PROCESS_ID)
935 {
Greg Claytona2f74232011-02-24 22:24:29 +0000936 // Make sure we aren't already connected?
937 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000938 {
Greg Claytona2f74232011-02-24 22:24:29 +0000939 char host_port[128];
940 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
941 char connect_url[128];
942 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000943
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000944 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000945
946 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000947 {
Greg Claytona2f74232011-02-24 22:24:29 +0000948 const char *error_string = error.AsCString();
949 if (error_string == NULL)
950 error_string = "unable to launch " DEBUGSERVER_BASENAME;
951
952 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000953 }
Greg Claytona2f74232011-02-24 22:24:29 +0000954 else
955 {
956 error = ConnectToDebugserver (connect_url);
957 }
958 }
959
960 if (error.Success())
961 {
962 char packet[64];
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000963 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Greg Clayton489575c2011-11-19 02:11:30 +0000964 SetID (attach_pid);
Greg Claytona2f74232011-02-24 22:24:29 +0000965 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000966 }
967 }
Chris Lattner24943d22010-06-08 16:52:24 +0000968 return error;
969}
970
971size_t
972ProcessGDBRemote::AttachInputReaderCallback
973(
974 void *baton,
975 InputReader *reader,
976 lldb::InputReaderAction notification,
977 const char *bytes,
978 size_t bytes_len
979)
980{
981 if (notification == eInputReaderGotToken)
982 {
983 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
984 if (gdb_process->m_waiting_for_attach)
985 gdb_process->m_waiting_for_attach = false;
986 reader->SetIsDone(true);
987 return 1;
988 }
989 return 0;
990}
991
992Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000993ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000994{
995 Error error;
996 // Clear out and clean up from any current state
997 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000998
Chris Lattner24943d22010-06-08 16:52:24 +0000999 if (process_name && process_name[0])
1000 {
Greg Claytona2f74232011-02-24 22:24:29 +00001001 // Make sure we aren't already connected?
1002 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001003 {
Greg Claytona2f74232011-02-24 22:24:29 +00001004 char host_port[128];
1005 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
1006 char connect_url[128];
1007 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
1008
Han Ming Ongd1040dd2012-02-25 01:07:38 +00001009 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +00001010 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +00001011 {
Greg Claytona2f74232011-02-24 22:24:29 +00001012 const char *error_string = error.AsCString();
1013 if (error_string == NULL)
1014 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +00001015
Greg Claytona2f74232011-02-24 22:24:29 +00001016 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +00001017 }
Greg Claytona2f74232011-02-24 22:24:29 +00001018 else
1019 {
1020 error = ConnectToDebugserver (connect_url);
1021 }
1022 }
1023
1024 if (error.Success())
1025 {
1026 StreamString packet;
1027
1028 if (wait_for_launch)
Jim Ingham3a458eb2012-07-20 21:37:13 +00001029 {
1030 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1031 {
1032 packet.PutCString ("vAttachWait");
1033 }
1034 else
1035 {
1036 if (attach_info.GetIgnoreExisting())
1037 packet.PutCString("vAttachWait");
1038 else
1039 packet.PutCString ("vAttachOrWait");
1040 }
1041 }
Greg Claytona2f74232011-02-24 22:24:29 +00001042 else
1043 packet.PutCString("vAttachName");
1044 packet.PutChar(';');
1045 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1046
1047 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1048
Chris Lattner24943d22010-06-08 16:52:24 +00001049 }
1050 }
Chris Lattner24943d22010-06-08 16:52:24 +00001051 return error;
1052}
1053
Chris Lattner24943d22010-06-08 16:52:24 +00001054
1055void
1056ProcessGDBRemote::DidAttach ()
1057{
Greg Claytone71e2582011-02-04 01:58:07 +00001058 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +00001059}
1060
Greg Clayton0bce9a22012-12-05 00:16:59 +00001061void
1062ProcessGDBRemote::DoDidExec ()
1063{
1064 // The process exec'ed itself, figure out the dynamic loader, etc...
1065 BuildDynamicRegisterInfo (true);
1066 m_gdb_comm.ResetDiscoverableSettings();
1067 DidLaunchOrAttach ();
1068}
1069
1070
1071
Chris Lattner24943d22010-06-08 16:52:24 +00001072Error
1073ProcessGDBRemote::WillResume ()
1074{
Greg Claytonc1f45872011-02-12 06:28:37 +00001075 m_continue_c_tids.clear();
1076 m_continue_C_tids.clear();
1077 m_continue_s_tids.clear();
1078 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001079 return Error();
1080}
1081
1082Error
1083ProcessGDBRemote::DoResume ()
1084{
Jim Ingham3ae449a2010-11-17 02:32:00 +00001085 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +00001086 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1087 if (log)
1088 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +00001089
1090 Listener listener ("gdb-remote.resume-packet-sent");
1091 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1092 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001093 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1094
Greg Claytonc1f45872011-02-12 06:28:37 +00001095 StreamString continue_packet;
1096 bool continue_packet_error = false;
1097 if (m_gdb_comm.HasAnyVContSupport ())
1098 {
1099 continue_packet.PutCString ("vCont");
1100
1101 if (!m_continue_c_tids.empty())
1102 {
1103 if (m_gdb_comm.GetVContSupported ('c'))
1104 {
1105 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)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001106 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +00001107 }
1108 else
1109 continue_packet_error = true;
1110 }
1111
1112 if (!continue_packet_error && !m_continue_C_tids.empty())
1113 {
1114 if (m_gdb_comm.GetVContSupported ('C'))
1115 {
1116 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)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001117 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001118 }
1119 else
1120 continue_packet_error = true;
1121 }
Greg Claytonb749a262010-12-03 06:02:24 +00001122
Greg Claytonc1f45872011-02-12 06:28:37 +00001123 if (!continue_packet_error && !m_continue_s_tids.empty())
1124 {
1125 if (m_gdb_comm.GetVContSupported ('s'))
1126 {
1127 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)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001128 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +00001129 }
1130 else
1131 continue_packet_error = true;
1132 }
1133
1134 if (!continue_packet_error && !m_continue_S_tids.empty())
1135 {
1136 if (m_gdb_comm.GetVContSupported ('S'))
1137 {
1138 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)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001139 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001140 }
1141 else
1142 continue_packet_error = true;
1143 }
1144
1145 if (continue_packet_error)
1146 continue_packet.GetString().clear();
1147 }
1148 else
1149 continue_packet_error = true;
1150
1151 if (continue_packet_error)
1152 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001153 // Either no vCont support, or we tried to use part of the vCont
1154 // packet that wasn't supported by the remote GDB server.
1155 // We need to try and make a simple packet that can do our continue
1156 const size_t num_threads = GetThreadList().GetSize();
1157 const size_t num_continue_c_tids = m_continue_c_tids.size();
1158 const size_t num_continue_C_tids = m_continue_C_tids.size();
1159 const size_t num_continue_s_tids = m_continue_s_tids.size();
1160 const size_t num_continue_S_tids = m_continue_S_tids.size();
1161 if (num_continue_c_tids > 0)
1162 {
1163 if (num_continue_c_tids == num_threads)
1164 {
1165 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001166 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001167 continue_packet.PutChar ('c');
1168 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001169 }
1170 else if (num_continue_c_tids == 1 &&
1171 num_continue_C_tids == 0 &&
1172 num_continue_s_tids == 0 &&
1173 num_continue_S_tids == 0 )
1174 {
1175 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +00001176 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001177 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +00001178 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001179 }
1180 }
1181
Greg Claytonde1dd812011-06-24 03:21:43 +00001182 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001183 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001184 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1185 num_continue_C_tids > 0 &&
1186 num_continue_s_tids == 0 &&
1187 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +00001188 {
1189 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +00001190 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +00001191 if (num_continue_C_tids > 1)
1192 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001193 // More that one thread with a signal, yet we don't have
1194 // vCont support and we are being asked to resume each
1195 // thread with a signal, we need to make sure they are
1196 // all the same signal, or we can't issue the continue
1197 // accurately with the current support...
1198 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +00001199 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001200 continue_packet_error = false;
1201 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1202 {
1203 if (m_continue_C_tids[i].second != continue_signo)
1204 continue_packet_error = true;
1205 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001206 }
Greg Claytonde1dd812011-06-24 03:21:43 +00001207 if (!continue_packet_error)
1208 m_gdb_comm.SetCurrentThreadForRun (-1);
1209 }
1210 else
1211 {
1212 // Set the continue thread ID
1213 continue_packet_error = false;
1214 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001215 }
1216 if (!continue_packet_error)
1217 {
1218 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +00001219 continue_packet.Printf("C%2.2x", continue_signo);
1220 }
1221 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001222 }
1223
Greg Claytonde1dd812011-06-24 03:21:43 +00001224 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001225 {
1226 if (num_continue_s_tids == num_threads)
1227 {
1228 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001229 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001230 continue_packet.PutChar ('s');
1231 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001232 }
1233 else if (num_continue_c_tids == 0 &&
1234 num_continue_C_tids == 0 &&
1235 num_continue_s_tids == 1 &&
1236 num_continue_S_tids == 0 )
1237 {
1238 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001239 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001240 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001241 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001242 }
1243 }
1244
1245 if (!continue_packet_error && num_continue_S_tids > 0)
1246 {
1247 if (num_continue_S_tids == num_threads)
1248 {
1249 const int step_signo = m_continue_S_tids.front().second;
1250 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001251 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001252 if (num_continue_S_tids > 1)
1253 {
1254 for (size_t i=1; i<num_threads; ++i)
1255 {
1256 if (m_continue_S_tids[i].second != step_signo)
1257 continue_packet_error = true;
1258 }
1259 }
1260 if (!continue_packet_error)
1261 {
1262 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001263 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001264 continue_packet.Printf("S%2.2x", step_signo);
1265 }
1266 }
1267 else if (num_continue_c_tids == 0 &&
1268 num_continue_C_tids == 0 &&
1269 num_continue_s_tids == 0 &&
1270 num_continue_S_tids == 1 )
1271 {
1272 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001273 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001274 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001275 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001276 }
1277 }
1278 }
1279
1280 if (continue_packet_error)
1281 {
1282 error.SetErrorString ("can't make continue packet for this resume");
1283 }
1284 else
1285 {
1286 EventSP event_sp;
1287 TimeValue timeout;
1288 timeout = TimeValue::Now();
1289 timeout.OffsetWithSeconds (5);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001290 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1291 {
1292 error.SetErrorString ("Trying to resume but the async thread is dead.");
1293 if (log)
1294 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1295 return error;
1296 }
1297
Greg Claytonc1f45872011-02-12 06:28:37 +00001298 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1299
1300 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001301 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001302 error.SetErrorString("Resume timed out.");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001303 if (log)
1304 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1305 }
1306 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1307 {
1308 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1309 if (log)
1310 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1311 return error;
1312 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001313 }
Greg Claytonb749a262010-12-03 06:02:24 +00001314 }
1315
Jim Ingham3ae449a2010-11-17 02:32:00 +00001316 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001317}
1318
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001319void
1320ProcessGDBRemote::ClearThreadIDList ()
1321{
Greg Claytonff3448e2012-04-13 02:11:32 +00001322 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001323 m_thread_ids.clear();
1324}
1325
1326bool
1327ProcessGDBRemote::UpdateThreadIDList ()
1328{
Greg Claytonff3448e2012-04-13 02:11:32 +00001329 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001330 bool sequence_mutex_unavailable = false;
1331 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1332 if (sequence_mutex_unavailable)
1333 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001334 return false; // We just didn't get the list
1335 }
1336 return true;
1337}
1338
Greg Claytonae932352012-04-10 00:18:59 +00001339bool
Greg Clayton37f962e2011-08-22 02:49:39 +00001340ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001341{
1342 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001343 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001344 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001345 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001346
1347 size_t num_thread_ids = m_thread_ids.size();
1348 // The "m_thread_ids" thread ID list should always be updated after each stop
1349 // reply packet, but in case it isn't, update it here.
1350 if (num_thread_ids == 0)
1351 {
1352 if (!UpdateThreadIDList ())
1353 return false;
1354 num_thread_ids = m_thread_ids.size();
1355 }
Chris Lattner24943d22010-06-08 16:52:24 +00001356
Greg Clayton37f962e2011-08-22 02:49:39 +00001357 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001358 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001359 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001360 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001361 tid_t tid = m_thread_ids[i];
Greg Clayton37f962e2011-08-22 02:49:39 +00001362 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false));
1363 if (!thread_sp)
Jim Ingham94a5d0d2012-10-10 18:32:14 +00001364 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Greg Clayton37f962e2011-08-22 02:49:39 +00001365 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001366 }
Chris Lattner24943d22010-06-08 16:52:24 +00001367 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001368
Greg Claytonae932352012-04-10 00:18:59 +00001369 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001370}
1371
1372
1373StateType
1374ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1375{
Greg Clayton261a18b2011-06-02 22:22:38 +00001376 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001377 const char stop_type = stop_packet.GetChar();
1378 switch (stop_type)
1379 {
1380 case 'T':
1381 case 'S':
1382 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001383 if (GetStopID() == 0)
1384 {
1385 // Our first stop, make sure we have a process ID, and also make
1386 // sure we know about our registers
1387 if (GetID() == LLDB_INVALID_PROCESS_ID)
1388 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001389 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001390 if (pid != LLDB_INVALID_PROCESS_ID)
1391 SetID (pid);
1392 }
1393 BuildDynamicRegisterInfo (true);
1394 }
Chris Lattner24943d22010-06-08 16:52:24 +00001395 // Stop with signal and thread info
1396 const uint8_t signo = stop_packet.GetHexU8();
1397 std::string name;
1398 std::string value;
1399 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001400 std::string reason;
1401 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001402 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001403 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001404 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Claytona875b642011-01-09 21:07:35 +00001405 ThreadSP thread_sp;
1406
Chris Lattner24943d22010-06-08 16:52:24 +00001407 while (stop_packet.GetNameColonValue(name, value))
1408 {
1409 if (name.compare("metype") == 0)
1410 {
1411 // exception type in big endian hex
1412 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1413 }
Chris Lattner24943d22010-06-08 16:52:24 +00001414 else if (name.compare("medata") == 0)
1415 {
1416 // exception data in big endian hex
1417 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1418 }
1419 else if (name.compare("thread") == 0)
1420 {
1421 // thread in big endian hex
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001422 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Claytonffa43a62011-11-17 04:46:02 +00001423 // m_thread_list does have its own mutex, but we need to
1424 // hold onto the mutex between the call to m_thread_list.FindThreadByID(...)
1425 // and the m_thread_list.AddThread(...) so it doesn't change on us
Greg Claytonc3c46612011-02-15 00:19:15 +00001426 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001427 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001428 if (!thread_sp)
1429 {
1430 // Create the thread if we need to
Jim Ingham94a5d0d2012-10-10 18:32:14 +00001431 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Greg Claytonc3c46612011-02-15 00:19:15 +00001432 m_thread_list.AddThread(thread_sp);
1433 }
Chris Lattner24943d22010-06-08 16:52:24 +00001434 }
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001435 else if (name.compare("threads") == 0)
1436 {
Greg Claytonff3448e2012-04-13 02:11:32 +00001437 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001438 m_thread_ids.clear();
Greg Claytona1f645e2012-04-10 03:22:03 +00001439 // A comma separated list of all threads in the current
1440 // process that includes the thread for this stop reply
1441 // packet
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001442 size_t comma_pos;
1443 lldb::tid_t tid;
1444 while ((comma_pos = value.find(',')) != std::string::npos)
1445 {
1446 value[comma_pos] = '\0';
1447 // thread in big endian hex
1448 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1449 if (tid != LLDB_INVALID_THREAD_ID)
1450 m_thread_ids.push_back (tid);
1451 value.erase(0, comma_pos + 1);
1452
1453 }
1454 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1455 if (tid != LLDB_INVALID_THREAD_ID)
1456 m_thread_ids.push_back (tid);
1457 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001458 else if (name.compare("hexname") == 0)
1459 {
1460 StringExtractor name_extractor;
1461 // Swap "value" over into "name_extractor"
1462 name_extractor.GetStringRef().swap(value);
1463 // Now convert the HEX bytes into a string value
1464 name_extractor.GetHexByteString (value);
1465 thread_name.swap (value);
1466 }
Chris Lattner24943d22010-06-08 16:52:24 +00001467 else if (name.compare("name") == 0)
1468 {
1469 thread_name.swap (value);
1470 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001471 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001472 {
1473 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1474 }
Greg Clayton65611552011-06-04 01:26:29 +00001475 else if (name.compare("reason") == 0)
1476 {
1477 reason.swap(value);
1478 }
1479 else if (name.compare("description") == 0)
1480 {
1481 StringExtractor desc_extractor;
1482 // Swap "value" over into "name_extractor"
1483 desc_extractor.GetStringRef().swap(value);
1484 // Now convert the HEX bytes into a string value
1485 desc_extractor.GetHexByteString (thread_name);
1486 }
Greg Claytona875b642011-01-09 21:07:35 +00001487 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1488 {
1489 // We have a register number that contains an expedited
1490 // register value. Lets supply this register to our thread
1491 // so it won't have to go and read it.
1492 if (thread_sp)
1493 {
1494 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1495
1496 if (reg != UINT32_MAX)
1497 {
1498 StringExtractor reg_value_extractor;
1499 // Swap "value" over into "reg_value_extractor"
1500 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001501 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1502 {
1503 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1504 name.c_str(),
1505 reg,
1506 reg,
1507 reg_value_extractor.GetStringRef().c_str(),
1508 stop_packet.GetStringRef().c_str());
1509 }
Greg Claytona875b642011-01-09 21:07:35 +00001510 }
1511 }
1512 }
Chris Lattner24943d22010-06-08 16:52:24 +00001513 }
Chris Lattner24943d22010-06-08 16:52:24 +00001514
1515 if (thread_sp)
1516 {
1517 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1518
1519 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001520 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001521 if (exc_type != 0)
1522 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001523 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001524
1525 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1526 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001527 exc_data_size,
1528 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001529 exc_data_size >= 2 ? exc_data[1] : 0,
1530 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001531 }
Greg Clayton65611552011-06-04 01:26:29 +00001532 else
Chris Lattner24943d22010-06-08 16:52:24 +00001533 {
Greg Clayton65611552011-06-04 01:26:29 +00001534 bool handled = false;
1535 if (!reason.empty())
1536 {
1537 if (reason.compare("trace") == 0)
1538 {
1539 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1540 handled = true;
1541 }
1542 else if (reason.compare("breakpoint") == 0)
1543 {
1544 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001545 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001546 if (bp_site_sp)
1547 {
1548 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1549 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1550 // 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 +00001551 handled = true;
Greg Clayton65611552011-06-04 01:26:29 +00001552 if (bp_site_sp->ValidForThisThread (gdb_thread))
1553 {
1554 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001555 }
1556 else
1557 {
1558 StopInfoSP invalid_stop_info_sp;
1559 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Greg Clayton65611552011-06-04 01:26:29 +00001560 }
1561 }
1562
Greg Clayton65611552011-06-04 01:26:29 +00001563 }
1564 else if (reason.compare("trap") == 0)
1565 {
1566 // Let the trap just use the standard signal stop reason below...
1567 }
1568 else if (reason.compare("watchpoint") == 0)
1569 {
1570 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1571 // TODO: locate the watchpoint somehow...
1572 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1573 handled = true;
1574 }
1575 else if (reason.compare("exception") == 0)
1576 {
1577 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1578 handled = true;
1579 }
1580 }
1581
1582 if (signo)
1583 {
1584 if (signo == SIGTRAP)
1585 {
1586 // Currently we are going to assume SIGTRAP means we are either
1587 // hitting a breakpoint or hardware single stepping.
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001588 handled = true;
Greg Clayton65611552011-06-04 01:26:29 +00001589 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001590 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001591
Greg Clayton65611552011-06-04 01:26:29 +00001592 if (bp_site_sp)
1593 {
1594 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1595 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1596 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1597 if (bp_site_sp->ValidForThisThread (gdb_thread))
1598 {
1599 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001600 }
1601 else
1602 {
1603 StopInfoSP invalid_stop_info_sp;
1604 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Greg Clayton65611552011-06-04 01:26:29 +00001605 }
1606 }
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001607 else
Greg Clayton65611552011-06-04 01:26:29 +00001608 {
Jim Ingham4fa015b2012-10-27 02:52:04 +00001609 // If we were stepping then assume the stop was the result of the trace. If we were
1610 // not stepping then report the SIGTRAP.
1611 // FIXME: We are still missing the case where we single step over a trap instruction.
1612 if (gdb_thread->GetTemporaryResumeState() == eStateStepping)
1613 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1614 else
1615 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo));
Greg Clayton65611552011-06-04 01:26:29 +00001616 }
1617 }
1618 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001619 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001620 }
1621 else
1622 {
Greg Clayton643ee732010-08-04 01:40:35 +00001623 StopInfoSP invalid_stop_info_sp;
1624 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001625 }
Greg Clayton65611552011-06-04 01:26:29 +00001626
1627 if (!description.empty())
1628 {
1629 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1630 if (stop_info_sp)
1631 {
1632 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001633 }
Greg Clayton65611552011-06-04 01:26:29 +00001634 else
1635 {
1636 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1637 }
1638 }
1639 }
Chris Lattner24943d22010-06-08 16:52:24 +00001640 }
1641 return eStateStopped;
1642 }
1643 break;
1644
1645 case 'W':
1646 // process exited
1647 return eStateExited;
1648
1649 default:
1650 break;
1651 }
1652 return eStateInvalid;
1653}
1654
1655void
1656ProcessGDBRemote::RefreshStateAfterStop ()
1657{
Greg Claytonff3448e2012-04-13 02:11:32 +00001658 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001659 m_thread_ids.clear();
1660 // Set the thread stop info. It might have a "threads" key whose value is
1661 // a list of all thread IDs in the current process, so m_thread_ids might
1662 // get set.
1663 SetThreadStopInfo (m_last_stop_packet);
1664 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1665 if (m_thread_ids.empty())
1666 {
1667 // No, we need to fetch the thread list manually
1668 UpdateThreadIDList();
1669 }
1670
Chris Lattner24943d22010-06-08 16:52:24 +00001671 // Let all threads recover from stopping and do any clean up based
1672 // on the previous thread state (if any).
1673 m_thread_list.RefreshStateAfterStop();
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001674
Chris Lattner24943d22010-06-08 16:52:24 +00001675}
1676
1677Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001678ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001679{
1680 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001681
Greg Claytona4881d02011-01-22 07:12:45 +00001682 bool timed_out = false;
1683 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001684
1685 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001686 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001687 // We are being asked to halt during an attach. We need to just close
1688 // our file handle and debugserver will go away, and we can be done...
1689 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001690 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001691 else
1692 {
Greg Clayton05e4d972012-03-29 01:55:41 +00001693 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001694 {
1695 if (timed_out)
1696 error.SetErrorString("timed out sending interrupt packet");
1697 else
1698 error.SetErrorString("unknown error sending interrupt packet");
1699 }
Greg Clayton05e4d972012-03-29 01:55:41 +00001700
1701 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001702 }
Chris Lattner24943d22010-06-08 16:52:24 +00001703 return error;
1704}
1705
1706Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001707ProcessGDBRemote::InterruptIfRunning
1708(
1709 bool discard_thread_plans,
1710 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001711 EventSP &stop_event_sp
1712)
Chris Lattner24943d22010-06-08 16:52:24 +00001713{
1714 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001715
Greg Clayton2860ba92011-01-23 19:58:49 +00001716 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1717
Greg Clayton68ca8232011-01-25 02:58:48 +00001718 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001719 const bool is_running = m_gdb_comm.IsRunning();
1720 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001721 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001722 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001723 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001724 is_running);
1725
Greg Clayton2860ba92011-01-23 19:58:49 +00001726 if (discard_thread_plans)
1727 {
1728 if (log)
1729 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1730 m_thread_list.DiscardThreadPlans();
1731 }
1732 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001733 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001734 if (catch_stop_event)
1735 {
1736 if (log)
1737 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1738 PausePrivateStateThread();
1739 paused_private_state_thread = true;
1740 }
1741
Greg Clayton4fb400f2010-09-27 21:07:38 +00001742 bool timed_out = false;
1743 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001744
Greg Clayton05e4d972012-03-29 01:55:41 +00001745 if (!m_gdb_comm.SendInterrupt (locker, 1, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001746 {
1747 if (timed_out)
1748 error.SetErrorString("timed out sending interrupt packet");
1749 else
1750 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001751 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001752 ResumePrivateStateThread();
1753 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001754 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001755
Greg Clayton72e1c782011-01-22 23:43:18 +00001756 if (catch_stop_event)
1757 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001758 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001759 TimeValue timeout_time;
1760 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001761 timeout_time.OffsetWithSeconds(5);
1762 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001763
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001764 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001765 if (log)
1766 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001767
Greg Clayton2860ba92011-01-23 19:58:49 +00001768 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001769 error.SetErrorString("unable to verify target stopped");
1770 }
1771
Greg Clayton68ca8232011-01-25 02:58:48 +00001772 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001773 {
1774 if (log)
1775 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001776 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001777 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001778 }
Chris Lattner24943d22010-06-08 16:52:24 +00001779 return error;
1780}
1781
Greg Clayton4fb400f2010-09-27 21:07:38 +00001782Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001783ProcessGDBRemote::WillDetach ()
1784{
Greg Clayton2860ba92011-01-23 19:58:49 +00001785 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1786 if (log)
1787 log->Printf ("ProcessGDBRemote::WillDetach()");
1788
Greg Clayton72e1c782011-01-22 23:43:18 +00001789 bool discard_thread_plans = true;
1790 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001791 EventSP event_sp;
Jim Ingham8247e622012-06-06 00:32:39 +00001792
1793 // FIXME: InterruptIfRunning should be done in the Process base class, or better still make Halt do what is
1794 // needed. This shouldn't be a feature of a particular plugin.
1795
Greg Clayton68ca8232011-01-25 02:58:48 +00001796 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001797}
1798
1799Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001800ProcessGDBRemote::DoDetach()
1801{
1802 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001803 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001804 if (log)
1805 log->Printf ("ProcessGDBRemote::DoDetach()");
1806
1807 DisableAllBreakpointSites ();
1808
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001809 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001810
Greg Clayton516f0842012-04-11 00:24:49 +00001811 bool success = m_gdb_comm.Detach ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001812 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001813 {
Greg Clayton516f0842012-04-11 00:24:49 +00001814 if (success)
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001815 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1816 else
1817 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001818 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001819 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001820 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001821
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001822 SetPrivateState (eStateDetached);
1823 ResumePrivateStateThread();
1824
1825 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001826 return error;
1827}
Chris Lattner24943d22010-06-08 16:52:24 +00001828
Jim Ingham06b84492012-07-04 00:35:43 +00001829
Chris Lattner24943d22010-06-08 16:52:24 +00001830Error
1831ProcessGDBRemote::DoDestroy ()
1832{
1833 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001834 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001835 if (log)
1836 log->Printf ("ProcessGDBRemote::DoDestroy()");
1837
Jim Ingham06b84492012-07-04 00:35:43 +00001838 // There is a bug in older iOS debugservers where they don't shut down the process
1839 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
1840 // this can cause problems with restarting. So we check to see if any of our threads are stopped
1841 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
1842 // destroy it again.
1843 //
1844 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
1845 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
1846 // the debugservers with this bug are equal. There really should be a better way to test this!
1847 //
1848 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
1849 // get called here to destroy again and we're still at a breakpoint or exception, then we should
1850 // just do the straight-forward kill.
1851 //
1852 // And of course, if we weren't able to stop the process by the time we get here, it isn't
1853 // necessary (or helpful) to do any of this.
1854
1855 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
1856 {
1857 PlatformSP platform_sp = GetTarget().GetPlatform();
1858
1859 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
1860 if (platform_sp
1861 && platform_sp->GetName()
1862 && strcmp (platform_sp->GetName(), PlatformRemoteiOS::GetShortPluginNameStatic()) == 0)
1863 {
1864 if (m_destroy_tried_resuming)
1865 {
1866 if (log)
1867 log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again.");
1868 }
1869 else
1870 {
1871 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
1872 // but we really need it to happen here and it doesn't matter if we do it twice.
1873 m_thread_list.DiscardThreadPlans();
1874 DisableAllBreakpointSites();
1875
1876 bool stop_looks_like_crash = false;
1877 ThreadList &threads = GetThreadList();
1878
1879 {
Jim Inghamc2c65142012-09-11 00:08:52 +00001880 Mutex::Locker locker(threads.GetMutex());
Jim Ingham06b84492012-07-04 00:35:43 +00001881
1882 size_t num_threads = threads.GetSize();
1883 for (size_t i = 0; i < num_threads; i++)
1884 {
1885 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1886 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason();
1887 StopReason reason = eStopReasonInvalid;
1888 if (stop_info_sp)
1889 reason = stop_info_sp->GetStopReason();
1890 if (reason == eStopReasonBreakpoint
1891 || reason == eStopReasonException)
1892 {
1893 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001894 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: %" PRId64 " stopped with reason: %s.",
Jim Ingham06b84492012-07-04 00:35:43 +00001895 thread_sp->GetID(),
1896 stop_info_sp->GetDescription());
1897 stop_looks_like_crash = true;
1898 break;
1899 }
1900 }
1901 }
1902
1903 if (stop_looks_like_crash)
1904 {
1905 if (log)
1906 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
1907 m_destroy_tried_resuming = true;
1908
1909 // If we are going to run again before killing, it would be good to suspend all the threads
1910 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
1911 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
1912 // have to run the risk of letting those threads proceed a bit.
1913
1914 {
Jim Inghamc2c65142012-09-11 00:08:52 +00001915 Mutex::Locker locker(threads.GetMutex());
Jim Ingham06b84492012-07-04 00:35:43 +00001916
1917 size_t num_threads = threads.GetSize();
1918 for (size_t i = 0; i < num_threads; i++)
1919 {
1920 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1921 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason();
1922 StopReason reason = eStopReasonInvalid;
1923 if (stop_info_sp)
1924 reason = stop_info_sp->GetStopReason();
1925 if (reason != eStopReasonBreakpoint
1926 && reason != eStopReasonException)
1927 {
1928 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001929 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: %" PRId64 " before running.",
Jim Ingham06b84492012-07-04 00:35:43 +00001930 thread_sp->GetID());
1931 thread_sp->SetResumeState(eStateSuspended);
1932 }
1933 }
1934 }
1935 Resume ();
1936 return Destroy();
1937 }
1938 }
1939 }
1940 }
1941
Chris Lattner24943d22010-06-08 16:52:24 +00001942 // Interrupt if our inferior is running...
Jim Ingham8247e622012-06-06 00:32:39 +00001943 int exit_status = SIGABRT;
1944 std::string exit_string;
1945
Greg Claytona4881d02011-01-22 07:12:45 +00001946 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001947 {
Jim Ingham8226e942011-10-28 01:11:35 +00001948 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton72e1c782011-01-22 23:43:18 +00001949 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001950
1951 StringExtractorGDBRemote response;
1952 bool send_async = true;
Filipe Cabecinhasee188ee2012-08-22 13:25:58 +00001953 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3);
1954
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001955 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001956 {
1957 char packet_cmd = response.GetChar(0);
1958
1959 if (packet_cmd == 'W' || packet_cmd == 'X')
1960 {
Greg Clayton06709002011-12-06 04:51:14 +00001961 SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001962 ClearThreadIDList ();
Jim Ingham8247e622012-06-06 00:32:39 +00001963 exit_status = response.GetHexU8();
1964 }
1965 else
1966 {
1967 if (log)
1968 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
1969 exit_string.assign("got unexpected response to k packet: ");
1970 exit_string.append(response.GetStringRef());
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001971 }
1972 }
1973 else
1974 {
Jim Ingham8247e622012-06-06 00:32:39 +00001975 if (log)
1976 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
1977 exit_string.assign("failed to send the k packet");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001978 }
Filipe Cabecinhasee188ee2012-08-22 13:25:58 +00001979
1980 m_gdb_comm.SetPacketTimeout(old_packet_timeout);
Greg Clayton72e1c782011-01-22 23:43:18 +00001981 }
Jim Ingham8247e622012-06-06 00:32:39 +00001982 else
1983 {
1984 if (log)
1985 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
Jim Ingham5d90ade2012-07-27 23:57:19 +00001986 exit_string.assign ("killed or interrupted while attaching.");
Jim Ingham8247e622012-06-06 00:32:39 +00001987 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001988 }
Jim Ingham8247e622012-06-06 00:32:39 +00001989 else
1990 {
1991 // If we missed setting the exit status on the way out, do it here.
1992 // NB set exit status can be called multiple times, the first one sets the status.
1993 exit_string.assign("destroying when not connected to debugserver");
1994 }
1995
1996 SetExitStatus(exit_status, exit_string.c_str());
1997
Chris Lattner24943d22010-06-08 16:52:24 +00001998 StopAsyncThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001999 KillDebugserverProcess ();
2000 return error;
2001}
2002
Chris Lattner24943d22010-06-08 16:52:24 +00002003//------------------------------------------------------------------
2004// Process Queries
2005//------------------------------------------------------------------
2006
2007bool
2008ProcessGDBRemote::IsAlive ()
2009{
Greg Clayton58e844b2010-12-08 05:08:21 +00002010 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00002011}
2012
Jason Molendad6b81222012-10-06 02:02:26 +00002013// For kernel debugging, we return the load address of the kernel binary as the
2014// ImageInfoAddress and we return the DynamicLoaderDarwinKernel as the GetDynamicLoader()
2015// name so the correct DynamicLoader plugin is chosen.
Chris Lattner24943d22010-06-08 16:52:24 +00002016addr_t
2017ProcessGDBRemote::GetImageInfoAddress()
2018{
Jason Molendab46937c2012-10-03 01:29:34 +00002019 if (m_kernel_load_addr != LLDB_INVALID_ADDRESS)
2020 return m_kernel_load_addr;
2021 else
2022 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner24943d22010-06-08 16:52:24 +00002023}
2024
Chris Lattner24943d22010-06-08 16:52:24 +00002025//------------------------------------------------------------------
2026// Process Memory
2027//------------------------------------------------------------------
2028size_t
2029ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2030{
2031 if (size > m_max_memory_size)
2032 {
2033 // Keep memory read sizes down to a sane limit. This function will be
2034 // called multiple times in order to complete the task by
2035 // lldb_private::Process so it is ok to do this.
2036 size = m_max_memory_size;
2037 }
2038
2039 char packet[64];
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002040 const int packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
Chris Lattner24943d22010-06-08 16:52:24 +00002041 assert (packet_len + 1 < sizeof(packet));
2042 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00002043 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00002044 {
Greg Clayton61d043b2011-03-22 04:00:09 +00002045 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00002046 {
2047 error.Clear();
2048 return response.GetHexBytes(buf, size, '\xdd');
2049 }
Greg Clayton61d043b2011-03-22 04:00:09 +00002050 else if (response.IsErrorResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00002051 error.SetErrorString("memory read failed");
Greg Clayton61d043b2011-03-22 04:00:09 +00002052 else if (response.IsUnsupportedResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00002053 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner24943d22010-06-08 16:52:24 +00002054 else
Greg Claytonae7bebc2012-09-19 01:46:31 +00002055 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00002056 }
2057 else
2058 {
2059 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
2060 }
2061 return 0;
2062}
2063
2064size_t
2065ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2066{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00002067 if (size > m_max_memory_size)
2068 {
2069 // Keep memory read sizes down to a sane limit. This function will be
2070 // called multiple times in order to complete the task by
2071 // lldb_private::Process so it is ok to do this.
2072 size = m_max_memory_size;
2073 }
2074
Chris Lattner24943d22010-06-08 16:52:24 +00002075 StreamString packet;
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002076 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Claytoncd548032011-02-01 01:31:41 +00002077 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00002078 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00002079 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00002080 {
Greg Clayton61d043b2011-03-22 04:00:09 +00002081 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00002082 {
2083 error.Clear();
2084 return size;
2085 }
Greg Clayton61d043b2011-03-22 04:00:09 +00002086 else if (response.IsErrorResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00002087 error.SetErrorString("memory write failed");
Greg Clayton61d043b2011-03-22 04:00:09 +00002088 else if (response.IsUnsupportedResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00002089 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner24943d22010-06-08 16:52:24 +00002090 else
Greg Claytonae7bebc2012-09-19 01:46:31 +00002091 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 +00002092 }
2093 else
2094 {
2095 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
2096 }
2097 return 0;
2098}
2099
2100lldb::addr_t
2101ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2102{
Greg Clayton989816b2011-05-14 01:50:35 +00002103 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2104
Greg Clayton2f085c62011-05-15 01:25:55 +00002105 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00002106 switch (supported)
2107 {
2108 case eLazyBoolCalculate:
2109 case eLazyBoolYes:
2110 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2111 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2112 return allocated_addr;
2113
2114 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002115 // Call mmap() to create memory in the inferior..
2116 unsigned prot = 0;
2117 if (permissions & lldb::ePermissionsReadable)
2118 prot |= eMmapProtRead;
2119 if (permissions & lldb::ePermissionsWritable)
2120 prot |= eMmapProtWrite;
2121 if (permissions & lldb::ePermissionsExecutable)
2122 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00002123
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002124 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2125 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2126 m_addr_to_mmap_size[allocated_addr] = size;
2127 else
2128 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00002129 break;
2130 }
2131
Chris Lattner24943d22010-06-08 16:52:24 +00002132 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002133 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00002134 else
2135 error.Clear();
2136 return allocated_addr;
2137}
2138
2139Error
Greg Claytona9385532011-11-18 07:03:08 +00002140ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2141 MemoryRegionInfo &region_info)
2142{
2143
2144 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2145 return error;
2146}
2147
2148Error
Johnny Chen7cbdcfb2012-05-23 21:09:52 +00002149ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2150{
2151
2152 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2153 return error;
2154}
2155
2156Error
Enrico Granata7de2a3b2012-07-13 23:18:48 +00002157ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2158{
2159 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2160 return error;
2161}
2162
2163Error
Chris Lattner24943d22010-06-08 16:52:24 +00002164ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2165{
2166 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00002167 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2168
2169 switch (supported)
2170 {
2171 case eLazyBoolCalculate:
2172 // We should never be deallocating memory without allocating memory
2173 // first so we should never get eLazyBoolCalculate
2174 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2175 break;
2176
2177 case eLazyBoolYes:
2178 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002179 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00002180 break;
2181
2182 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002183 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00002184 {
2185 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002186 if (pos != m_addr_to_mmap_size.end() &&
2187 InferiorCallMunmap(this, addr, pos->second))
2188 m_addr_to_mmap_size.erase (pos);
2189 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002190 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00002191 }
2192 break;
2193 }
2194
Chris Lattner24943d22010-06-08 16:52:24 +00002195 return error;
2196}
2197
2198
2199//------------------------------------------------------------------
2200// Process STDIO
2201//------------------------------------------------------------------
Chris Lattner24943d22010-06-08 16:52:24 +00002202size_t
2203ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2204{
2205 if (m_stdio_communication.IsConnected())
2206 {
2207 ConnectionStatus status;
2208 m_stdio_communication.Write(src, src_len, status, NULL);
2209 }
2210 return 0;
2211}
2212
2213Error
2214ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
2215{
2216 Error error;
2217 assert (bp_site != NULL);
2218
Greg Claytone005f2c2010-11-06 01:53:30 +00002219 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002220 user_id_t site_id = bp_site->GetID();
2221 const addr_t addr = bp_site->GetLoadAddress();
2222 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002223 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002224
2225 if (bp_site->IsEnabled())
2226 {
2227 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002228 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %" PRIu64 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002229 return error;
2230 }
2231 else
2232 {
2233 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2234
2235 if (bp_site->HardwarePreferred())
2236 {
2237 // Try and set hardware breakpoint, and if that fails, fall through
2238 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00002239 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00002240 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002241 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00002242 {
2243 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002244 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00002245 return error;
2246 }
Chris Lattner24943d22010-06-08 16:52:24 +00002247 }
2248 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002249
2250 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00002251 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002252 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
2253 {
2254 bp_site->SetEnabled(true);
2255 bp_site->SetType (BreakpointSite::eExternal);
2256 return error;
2257 }
Chris Lattner24943d22010-06-08 16:52:24 +00002258 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002259
2260 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00002261 }
2262
2263 if (log)
2264 {
2265 const char *err_string = error.AsCString();
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002266 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8" PRIx64 ": %s",
Chris Lattner24943d22010-06-08 16:52:24 +00002267 bp_site->GetLoadAddress(),
2268 err_string ? err_string : "NULL");
2269 }
2270 // We shouldn't reach here on a successful breakpoint enable...
2271 if (error.Success())
2272 error.SetErrorToGenericError();
2273 return error;
2274}
2275
2276Error
2277ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
2278{
2279 Error error;
2280 assert (bp_site != NULL);
2281 addr_t addr = bp_site->GetLoadAddress();
2282 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00002283 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002284 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002285 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002286
2287 if (bp_site->IsEnabled())
2288 {
2289 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2290
Greg Claytonb72d0f02011-04-12 05:54:46 +00002291 BreakpointSite::Type bp_type = bp_site->GetType();
2292 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00002293 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002294 case BreakpointSite::eSoftware:
2295 error = DisableSoftwareBreakpoint (bp_site);
2296 break;
2297
2298 case BreakpointSite::eHardware:
2299 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2300 error.SetErrorToGenericError();
2301 break;
2302
2303 case BreakpointSite::eExternal:
2304 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2305 error.SetErrorToGenericError();
2306 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002307 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002308 if (error.Success())
2309 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00002310 }
2311 else
2312 {
2313 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002314 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002315 return error;
2316 }
2317
2318 if (error.Success())
2319 error.SetErrorToGenericError();
2320 return error;
2321}
2322
Johnny Chen21900fb2011-09-06 22:38:36 +00002323// Pre-requisite: wp != NULL.
2324static GDBStoppointType
Johnny Chenecd4feb2011-10-14 00:42:25 +00002325GetGDBStoppointType (Watchpoint *wp)
Johnny Chen21900fb2011-09-06 22:38:36 +00002326{
2327 assert(wp);
2328 bool watch_read = wp->WatchpointRead();
2329 bool watch_write = wp->WatchpointWrite();
2330
2331 // watch_read and watch_write cannot both be false.
2332 assert(watch_read || watch_write);
2333 if (watch_read && watch_write)
2334 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00002335 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00002336 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00002337 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00002338 return eWatchpointWrite;
2339}
2340
Chris Lattner24943d22010-06-08 16:52:24 +00002341Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002342ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002343{
2344 Error error;
2345 if (wp)
2346 {
2347 user_id_t watchID = wp->GetID();
2348 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00002349 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002350 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002351 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner24943d22010-06-08 16:52:24 +00002352 if (wp->IsEnabled())
2353 {
2354 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002355 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002356 return error;
2357 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002358
2359 GDBStoppointType type = GetGDBStoppointType(wp);
2360 // Pass down an appropriate z/Z packet...
2361 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00002362 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002363 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2364 {
2365 wp->SetEnabled(true);
2366 return error;
2367 }
2368 else
2369 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002370 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002371 else
2372 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00002373 }
2374 else
2375 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002376 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002377 }
2378 if (error.Success())
2379 error.SetErrorToGenericError();
2380 return error;
2381}
2382
2383Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002384ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002385{
2386 Error error;
2387 if (wp)
2388 {
2389 user_id_t watchID = wp->GetID();
2390
Greg Claytone005f2c2010-11-06 01:53:30 +00002391 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002392
2393 addr_t addr = wp->GetLoadAddress();
2394 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002395 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002396
Johnny Chen21900fb2011-09-06 22:38:36 +00002397 if (!wp->IsEnabled())
2398 {
2399 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002400 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
Johnny Chen258db3a2012-08-23 22:28:26 +00002401 // See also 'class WatchpointSentry' within StopInfo.cpp.
2402 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2403 // the watchpoint object to intelligently process this action.
2404 wp->SetEnabled(false);
Johnny Chen21900fb2011-09-06 22:38:36 +00002405 return error;
2406 }
2407
Chris Lattner24943d22010-06-08 16:52:24 +00002408 if (wp->IsHardware())
2409 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002410 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00002411 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00002412 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2413 {
2414 wp->SetEnabled(false);
2415 return error;
2416 }
2417 else
2418 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002419 }
2420 // TODO: clear software watchpoints if we implement them
2421 }
2422 else
2423 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002424 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002425 }
2426 if (error.Success())
2427 error.SetErrorToGenericError();
2428 return error;
2429}
2430
2431void
2432ProcessGDBRemote::Clear()
2433{
2434 m_flags = 0;
2435 m_thread_list.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002436}
2437
2438Error
2439ProcessGDBRemote::DoSignal (int signo)
2440{
2441 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00002442 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002443 if (log)
2444 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2445
2446 if (!m_gdb_comm.SendAsyncSignal (signo))
2447 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2448 return error;
2449}
2450
Chris Lattner24943d22010-06-08 16:52:24 +00002451Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002452ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)
2453{
2454 ProcessLaunchInfo launch_info;
2455 return StartDebugserverProcess(debugserver_url, launch_info);
2456}
2457
2458Error
2459ProcessGDBRemote::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 +00002460{
2461 Error error;
2462 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2463 {
2464 // If we locate debugserver, keep that located version around
2465 static FileSpec g_debugserver_file_spec;
2466
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002467 ProcessLaunchInfo debugserver_launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002468 char debugserver_path[PATH_MAX];
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002469 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002470
2471 // Always check to see if we have an environment override for the path
2472 // to the debugserver to use and use it if we do.
2473 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2474 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002475 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002476 else
2477 debugserver_file_spec = g_debugserver_file_spec;
2478 bool debugserver_exists = debugserver_file_spec.Exists();
2479 if (!debugserver_exists)
2480 {
2481 // The debugserver binary is in the LLDB.framework/Resources
2482 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002483 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002484 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002485 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002486 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002487 if (debugserver_exists)
2488 {
2489 g_debugserver_file_spec = debugserver_file_spec;
2490 }
2491 else
2492 {
2493 g_debugserver_file_spec.Clear();
2494 debugserver_file_spec.Clear();
2495 }
Chris Lattner24943d22010-06-08 16:52:24 +00002496 }
2497 }
2498
2499 if (debugserver_exists)
2500 {
2501 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2502
2503 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002504
Greg Claytone005f2c2010-11-06 01:53:30 +00002505 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002506
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002507 Args &debugserver_args = debugserver_launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002508 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002509
Chris Lattner24943d22010-06-08 16:52:24 +00002510 // Start args with "debugserver /file/path -r --"
2511 debugserver_args.AppendArgument(debugserver_path);
2512 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002513 // use native registers, not the GDB registers
2514 debugserver_args.AppendArgument("--native-regs");
2515 // make debugserver run in its own session so signals generated by
2516 // special terminal key sequences (^C) don't affect debugserver
2517 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002518
Chris Lattner24943d22010-06-08 16:52:24 +00002519 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2520 if (env_debugserver_log_file)
2521 {
2522 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2523 debugserver_args.AppendArgument(arg_cstr);
2524 }
2525
2526 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2527 if (env_debugserver_log_flags)
2528 {
2529 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2530 debugserver_args.AppendArgument(arg_cstr);
2531 }
Jim Ingham2b2ac8c2012-10-03 22:31:30 +00002532// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
2533// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002534
Greg Claytonb72d0f02011-04-12 05:54:46 +00002535 // We currently send down all arguments, attach pids, or attach
2536 // process names in dedicated GDB server packets, so we don't need
2537 // to pass them as arguments. This is currently because of all the
2538 // things we need to setup prior to launching: the environment,
2539 // current working dir, file actions, etc.
2540#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002541 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002542 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002543 {
Greg Claytona2f74232011-02-24 22:24:29 +00002544 // Terminate the debugserver args so we can now append the inferior args
2545 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002546
Greg Claytona2f74232011-02-24 22:24:29 +00002547 for (int i = 0; inferior_argv[i] != NULL; ++i)
2548 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002549 }
2550 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2551 {
2552 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2553 debugserver_args.AppendArgument (arg_cstr);
2554 }
2555 else if (attach_name && attach_name[0])
2556 {
2557 if (wait_for_launch)
2558 debugserver_args.AppendArgument ("--waitfor");
2559 else
2560 debugserver_args.AppendArgument ("--attach");
2561 debugserver_args.AppendArgument (attach_name);
2562 }
Chris Lattner24943d22010-06-08 16:52:24 +00002563#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002564
2565 ProcessLaunchInfo::FileAction file_action;
2566
2567 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2568 // to "/dev/null" if we run into any problems.
2569 file_action.Close (STDIN_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002570 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002571 file_action.Close (STDOUT_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002572 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002573 file_action.Close (STDERR_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002574 debugserver_launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002575
2576 if (log)
2577 {
2578 StreamString strm;
2579 debugserver_args.Dump (&strm);
2580 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2581 }
2582
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002583 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2584 debugserver_launch_info.SetUserID(process_info.GetUserID());
Greg Clayton1c4642c2011-11-16 05:37:56 +00002585
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002586 error = Host::LaunchProcess(debugserver_launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002587
Greg Claytonb72d0f02011-04-12 05:54:46 +00002588 if (error.Success ())
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002589 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002590 else
Chris Lattner24943d22010-06-08 16:52:24 +00002591 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2592
2593 if (error.Fail() || log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002594 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%" PRIu64 ", path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002595 }
2596 else
2597 {
Greg Clayton9c236732011-10-26 00:56:27 +00002598 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002599 }
2600
2601 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2602 StartAsyncThread ();
2603 }
2604 return error;
2605}
2606
2607bool
2608ProcessGDBRemote::MonitorDebugserverProcess
2609(
2610 void *callback_baton,
2611 lldb::pid_t debugserver_pid,
Greg Clayton1c4642c2011-11-16 05:37:56 +00002612 bool exited, // True if the process did exit
Chris Lattner24943d22010-06-08 16:52:24 +00002613 int signo, // Zero for no signal
2614 int exit_status // Exit value of process if signal is zero
2615)
2616{
Greg Clayton1c4642c2011-11-16 05:37:56 +00002617 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2618 // and might not exist anymore, so we need to carefully try to get the
2619 // target for this process first since we have a race condition when
2620 // we are done running between getting the notice that the inferior
2621 // process has died and the debugserver that was debugging this process.
2622 // In our test suite, we are also continually running process after
2623 // process, so we must be very careful to make sure:
2624 // 1 - process object hasn't been deleted already
2625 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner24943d22010-06-08 16:52:24 +00002626
2627 // "debugserver_pid" argument passed in is the process ID for
2628 // debugserver that we are tracking...
Greg Clayton1c4642c2011-11-16 05:37:56 +00002629 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002630
Greg Clayton75ccf502010-08-21 02:22:51 +00002631 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002632
Greg Clayton1c4642c2011-11-16 05:37:56 +00002633 // Get a shared pointer to the target that has a matching process pointer.
2634 // This target could be gone, or the target could already have a new process
2635 // object inside of it
2636 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2637
Greg Clayton72e1c782011-01-22 23:43:18 +00002638 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002639 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%" PRIu64 ", signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
Greg Clayton72e1c782011-01-22 23:43:18 +00002640
Greg Clayton1c4642c2011-11-16 05:37:56 +00002641 if (target_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002642 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002643 // We found a process in a target that matches, but another thread
2644 // might be in the process of launching a new process that will
2645 // soon replace it, so get a shared pointer to the process so we
2646 // can keep it alive.
2647 ProcessSP process_sp (target_sp->GetProcessSP());
2648 // Now we have a shared pointer to the process that can't go away on us
2649 // so we now make sure it was the same as the one passed in, and also make
2650 // sure that our previous "process *" didn't get deleted and have a new
2651 // "process *" created in its place with the same pointer. To verify this
2652 // we make sure the process has our debugserver process ID. If we pass all
2653 // of these tests, then we are sure that this process is the one we were
2654 // looking for.
2655 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner24943d22010-06-08 16:52:24 +00002656 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002657 // Sleep for a half a second to make sure our inferior process has
2658 // time to set its exit status before we set it incorrectly when
2659 // both the debugserver and the inferior process shut down.
2660 usleep (500000);
2661 // If our process hasn't yet exited, debugserver might have died.
2662 // If the process did exit, the we are reaping it.
2663 const StateType state = process->GetState();
2664
2665 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2666 state != eStateInvalid &&
2667 state != eStateUnloaded &&
2668 state != eStateExited &&
2669 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002670 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002671 char error_str[1024];
2672 if (signo)
2673 {
2674 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2675 if (signal_cstr)
2676 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2677 else
2678 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2679 }
Chris Lattner24943d22010-06-08 16:52:24 +00002680 else
Greg Clayton1c4642c2011-11-16 05:37:56 +00002681 {
2682 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2683 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002684
Greg Clayton1c4642c2011-11-16 05:37:56 +00002685 process->SetExitStatus (-1, error_str);
2686 }
2687 // Debugserver has exited we need to let our ProcessGDBRemote
2688 // know that it no longer has a debugserver instance
2689 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton75ccf502010-08-21 02:22:51 +00002690 }
Chris Lattner24943d22010-06-08 16:52:24 +00002691 }
2692 return true;
2693}
2694
2695void
2696ProcessGDBRemote::KillDebugserverProcess ()
2697{
2698 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2699 {
2700 ::kill (m_debugserver_pid, SIGINT);
2701 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2702 }
2703}
2704
2705void
2706ProcessGDBRemote::Initialize()
2707{
2708 static bool g_initialized = false;
2709
2710 if (g_initialized == false)
2711 {
2712 g_initialized = true;
2713 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2714 GetPluginDescriptionStatic(),
2715 CreateInstance);
2716
2717 Log::Callbacks log_callbacks = {
2718 ProcessGDBRemoteLog::DisableLog,
2719 ProcessGDBRemoteLog::EnableLog,
2720 ProcessGDBRemoteLog::ListLogCategories
2721 };
2722
2723 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2724 }
2725}
2726
2727bool
Chris Lattner24943d22010-06-08 16:52:24 +00002728ProcessGDBRemote::StartAsyncThread ()
2729{
Greg Claytone005f2c2010-11-06 01:53:30 +00002730 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002731
2732 if (log)
2733 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Inghama9488302012-11-01 01:15:33 +00002734
2735 Mutex::Locker start_locker(m_async_thread_state_mutex);
2736 if (m_async_thread_state == eAsyncThreadNotStarted)
2737 {
2738 // Create a thread that watches our internal state and controls which
2739 // events make it to clients (into the DCProcess event queue).
2740 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2741 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2742 {
2743 m_async_thread_state = eAsyncThreadRunning;
2744 return true;
2745 }
2746 else
2747 return false;
2748 }
2749 else
2750 {
2751 // Somebody tried to start the async thread while it was either being started or stopped. If the former, and
2752 // it started up successfully, then say all's well. Otherwise it is an error, since we aren't going to restart it.
2753 if (log)
2754 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
2755 if (m_async_thread_state == eAsyncThreadRunning)
2756 return true;
2757 else
2758 return false;
2759 }
Chris Lattner24943d22010-06-08 16:52:24 +00002760}
2761
2762void
2763ProcessGDBRemote::StopAsyncThread ()
2764{
Greg Claytone005f2c2010-11-06 01:53:30 +00002765 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002766
2767 if (log)
2768 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2769
Jim Inghama9488302012-11-01 01:15:33 +00002770 Mutex::Locker start_locker(m_async_thread_state_mutex);
2771 if (m_async_thread_state == eAsyncThreadRunning)
Chris Lattner24943d22010-06-08 16:52:24 +00002772 {
Jim Inghama9488302012-11-01 01:15:33 +00002773 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2774
2775 // This will shut down the async thread.
2776 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
2777
2778 // Stop the stdio thread
2779 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2780 {
2781 Host::ThreadJoin (m_async_thread, NULL, NULL);
2782 }
2783 m_async_thread_state = eAsyncThreadDone;
2784 }
2785 else
2786 {
2787 if (log)
2788 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
Chris Lattner24943d22010-06-08 16:52:24 +00002789 }
2790}
2791
2792
2793void *
2794ProcessGDBRemote::AsyncThread (void *arg)
2795{
2796 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2797
Greg Claytone005f2c2010-11-06 01:53:30 +00002798 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002799 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002800 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002801
2802 Listener listener ("ProcessGDBRemote::AsyncThread");
2803 EventSP event_sp;
2804 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2805 eBroadcastBitAsyncThreadShouldExit;
2806
2807 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2808 {
Greg Claytona2f74232011-02-24 22:24:29 +00002809 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2810
Chris Lattner24943d22010-06-08 16:52:24 +00002811 bool done = false;
2812 while (!done)
2813 {
2814 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002815 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002816 if (listener.WaitForEvent (NULL, event_sp))
2817 {
2818 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002819 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002820 {
Greg Claytona2f74232011-02-24 22:24:29 +00002821 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002822 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
Chris Lattner24943d22010-06-08 16:52:24 +00002823
Greg Claytona2f74232011-02-24 22:24:29 +00002824 switch (event_type)
2825 {
2826 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002827 {
Greg Claytona2f74232011-02-24 22:24:29 +00002828 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002829
Greg Claytona2f74232011-02-24 22:24:29 +00002830 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002831 {
Greg Claytona2f74232011-02-24 22:24:29 +00002832 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2833 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2834 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002835 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002836
Greg Claytona2f74232011-02-24 22:24:29 +00002837 if (::strstr (continue_cstr, "vAttach") == NULL)
2838 process->SetPrivateState(eStateRunning);
2839 StringExtractorGDBRemote response;
2840 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002841
Greg Clayton67b402c2012-05-16 02:48:06 +00002842 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
2843 // The thread ID list might be contained within the "response", or the stop reply packet that
2844 // caused the stop. So clear it now before we give the stop reply packet to the process
2845 // using the process->SetLastStopPacket()...
2846 process->ClearThreadIDList ();
2847
Greg Claytona2f74232011-02-24 22:24:29 +00002848 switch (stop_state)
2849 {
2850 case eStateStopped:
2851 case eStateCrashed:
2852 case eStateSuspended:
Greg Clayton06709002011-12-06 04:51:14 +00002853 process->SetLastStopPacket (response);
Greg Claytona2f74232011-02-24 22:24:29 +00002854 process->SetPrivateState (stop_state);
2855 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002856
Greg Claytona2f74232011-02-24 22:24:29 +00002857 case eStateExited:
Greg Clayton06709002011-12-06 04:51:14 +00002858 process->SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00002859 process->ClearThreadIDList();
Greg Claytona2f74232011-02-24 22:24:29 +00002860 response.SetFilePos(1);
2861 process->SetExitStatus(response.GetHexU8(), NULL);
2862 done = true;
2863 break;
2864
2865 case eStateInvalid:
2866 process->SetExitStatus(-1, "lost connection");
2867 break;
2868
2869 default:
2870 process->SetPrivateState (stop_state);
2871 break;
2872 }
Chris Lattner24943d22010-06-08 16:52:24 +00002873 }
2874 }
Greg Claytona2f74232011-02-24 22:24:29 +00002875 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002876
Greg Claytona2f74232011-02-24 22:24:29 +00002877 case eBroadcastBitAsyncThreadShouldExit:
2878 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002879 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Claytona2f74232011-02-24 22:24:29 +00002880 done = true;
2881 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002882
Greg Claytona2f74232011-02-24 22:24:29 +00002883 default:
2884 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002885 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
Greg Claytona2f74232011-02-24 22:24:29 +00002886 done = true;
2887 break;
2888 }
2889 }
2890 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2891 {
2892 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2893 {
2894 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002895 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002896 }
Chris Lattner24943d22010-06-08 16:52:24 +00002897 }
2898 }
2899 else
2900 {
2901 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002902 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002903 done = true;
2904 }
2905 }
2906 }
2907
2908 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002909 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002910
2911 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2912 return NULL;
2913}
2914
Chris Lattner24943d22010-06-08 16:52:24 +00002915const char *
2916ProcessGDBRemote::GetDispatchQueueNameForThread
2917(
2918 addr_t thread_dispatch_qaddr,
2919 std::string &dispatch_queue_name
2920)
2921{
2922 dispatch_queue_name.clear();
2923 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2924 {
2925 // Cache the dispatch_queue_offsets_addr value so we don't always have
2926 // to look it up
2927 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2928 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002929 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2930 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton444fe992012-02-26 05:51:37 +00002931 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false));
2932 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002933 if (module_sp)
2934 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2935
2936 if (dispatch_queue_offsets_symbol == NULL)
2937 {
Greg Clayton444fe992012-02-26 05:51:37 +00002938 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false));
2939 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_module_spec);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002940 if (module_sp)
2941 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2942 }
Chris Lattner24943d22010-06-08 16:52:24 +00002943 if (dispatch_queue_offsets_symbol)
Greg Clayton0c31d3d2012-03-07 21:03:09 +00002944 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002945
2946 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2947 return NULL;
2948 }
2949
2950 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002951 DataExtractor data (memory_buffer,
2952 sizeof(memory_buffer),
2953 m_target.GetArchitecture().GetByteOrder(),
2954 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002955
2956 // Excerpt from src/queue_private.h
2957 struct dispatch_queue_offsets_s
2958 {
2959 uint16_t dqo_version;
Jason Molenda9704ca22012-11-10 06:54:30 +00002960 uint16_t dqo_label; // in version 1-3, offset to string; in version 4+, offset to a pointer to a string
2961 uint16_t dqo_label_size; // in version 1-3, length of string; in version 4+, size of a (void*) in this process
Chris Lattner24943d22010-06-08 16:52:24 +00002962 } dispatch_queue_offsets;
2963
2964
2965 Error error;
2966 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2967 {
2968 uint32_t data_offset = 0;
2969 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2970 {
2971 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2972 {
2973 data_offset = 0;
2974 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
Jason Molenda9704ca22012-11-10 06:54:30 +00002975 if (dispatch_queue_offsets.dqo_version >= 4)
2976 {
2977 // libdispatch versions 4+, pointer to dispatch name is in the
2978 // queue structure.
2979 lldb::addr_t pointer_to_label_address = queue_addr + dispatch_queue_offsets.dqo_label;
2980 if (ReadMemory (pointer_to_label_address, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2981 {
2982 data_offset = 0;
2983 lldb::addr_t label_addr = data.GetAddress(&data_offset);
2984 ReadCStringFromMemory (label_addr, dispatch_queue_name, error);
2985 }
2986 }
2987 else
2988 {
2989 // libdispatch versions 1-3, dispatch name is a fixed width char array
2990 // in the queue structure.
2991 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2992 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2993 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2994 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2995 dispatch_queue_name.erase (bytes_read);
2996 }
Chris Lattner24943d22010-06-08 16:52:24 +00002997 }
2998 }
2999 }
3000 }
3001 if (dispatch_queue_name.empty())
3002 return NULL;
3003 return dispatch_queue_name.c_str();
3004}
3005
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003006//uint32_t
3007//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3008//{
3009// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
3010// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
3011// if (m_local_debugserver)
3012// {
3013// return Host::ListProcessesMatchingName (name, matches, pids);
3014// }
3015// else
3016// {
3017// // FIXME: Implement talking to the remote debugserver.
3018// return 0;
3019// }
3020//
3021//}
3022//
Jim Ingham55e01d82011-01-22 01:33:44 +00003023bool
3024ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
3025 lldb_private::StoppointCallbackContext *context,
3026 lldb::user_id_t break_id,
3027 lldb::user_id_t break_loc_id)
3028{
3029 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3030 // run so I can stop it if that's what I want to do.
3031 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
3032 if (log)
3033 log->Printf("Hit New Thread Notification breakpoint.");
3034 return false;
3035}
3036
3037
3038bool
3039ProcessGDBRemote::StartNoticingNewThreads()
3040{
Jim Ingham55e01d82011-01-22 01:33:44 +00003041 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003042 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00003043 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003044 if (log && log->GetVerbose())
3045 log->Printf("Enabled noticing new thread breakpoint.");
3046 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham55e01d82011-01-22 01:33:44 +00003047 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003048 else
Jim Ingham55e01d82011-01-22 01:33:44 +00003049 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003050 PlatformSP platform_sp (m_target.GetPlatform());
3051 if (platform_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00003052 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003053 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3054 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00003055 {
Jim Ingham6bb73372011-10-15 00:21:37 +00003056 if (log && log->GetVerbose())
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003057 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3058 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham55e01d82011-01-22 01:33:44 +00003059 }
3060 else
3061 {
3062 if (log)
3063 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00003064 }
3065 }
3066 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003067 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham55e01d82011-01-22 01:33:44 +00003068}
3069
3070bool
3071ProcessGDBRemote::StopNoticingNewThreads()
3072{
Jim Inghamff276fe2011-02-08 05:19:01 +00003073 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham6bb73372011-10-15 00:21:37 +00003074 if (log && log->GetVerbose())
Jim Inghamff276fe2011-02-08 05:19:01 +00003075 log->Printf ("Disabling new thread notification breakpoint.");
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003076
3077 if (m_thread_create_bp_sp)
3078 m_thread_create_bp_sp->SetEnabled(false);
3079
Jim Ingham55e01d82011-01-22 01:33:44 +00003080 return true;
3081}
3082
Jason Molendab46937c2012-10-03 01:29:34 +00003083lldb_private::DynamicLoader *
3084ProcessGDBRemote::GetDynamicLoader ()
3085{
3086 if (m_dyld_ap.get() == NULL)
3087 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, m_dyld_plugin_name.empty() ? NULL : m_dyld_plugin_name.c_str()));
3088 return m_dyld_ap.get();
3089}
Jim Ingham55e01d82011-01-22 01:33:44 +00003090
Greg Clayton13193d52012-10-13 02:07:45 +00003091
Greg Claytonb8596392012-10-15 22:42:16 +00003092class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton13193d52012-10-13 02:07:45 +00003093{
3094private:
3095
3096public:
Greg Claytonb8596392012-10-15 22:42:16 +00003097 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton13193d52012-10-13 02:07:45 +00003098 CommandObjectParsed (interpreter,
Greg Claytonb8596392012-10-15 22:42:16 +00003099 "process plugin packet history",
3100 "Dumps the packet history buffer. ",
Greg Clayton13193d52012-10-13 02:07:45 +00003101 NULL)
3102 {
3103 }
3104
Greg Claytonb8596392012-10-15 22:42:16 +00003105 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton13193d52012-10-13 02:07:45 +00003106 {
3107 }
3108
3109 bool
3110 DoExecute (Args& command, CommandReturnObject &result)
3111 {
Greg Claytonb8596392012-10-15 22:42:16 +00003112 const size_t argc = command.GetArgumentCount();
3113 if (argc == 0)
3114 {
3115 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3116 if (process)
3117 {
3118 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
3119 result.SetStatus (eReturnStatusSuccessFinishResult);
3120 return true;
3121 }
3122 }
3123 else
3124 {
3125 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
3126 }
3127 result.SetStatus (eReturnStatusFailed);
3128 return false;
3129 }
3130};
3131
3132class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
3133{
3134private:
3135
3136public:
3137 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
3138 CommandObjectParsed (interpreter,
3139 "process plugin packet send",
3140 "Send a custom packet through the GDB remote protocol and print the answer. "
3141 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
3142 NULL)
3143 {
3144 }
3145
3146 ~CommandObjectProcessGDBRemotePacketSend ()
3147 {
3148 }
3149
3150 bool
3151 DoExecute (Args& command, CommandReturnObject &result)
3152 {
3153 const size_t argc = command.GetArgumentCount();
3154 if (argc == 0)
3155 {
3156 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
3157 result.SetStatus (eReturnStatusFailed);
3158 return false;
3159 }
3160
3161 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3162 if (process)
3163 {
Han Ming Ongae9cc552012-11-26 20:42:03 +00003164 for (size_t i=0; i<argc; ++ i)
Greg Claytonb8596392012-10-15 22:42:16 +00003165 {
Han Ming Ongae9cc552012-11-26 20:42:03 +00003166 const char *packet_cstr = command.GetArgumentAtIndex(0);
3167 bool send_async = true;
3168 StringExtractorGDBRemote response;
3169 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3170 result.SetStatus (eReturnStatusSuccessFinishResult);
3171 Stream &output_strm = result.GetOutputStream();
3172 output_strm.Printf (" packet: %s\n", packet_cstr);
3173 const std::string &response_str = response.GetStringRef();
3174 if (response_str.empty())
3175 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3176 else
3177 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Claytonb8596392012-10-15 22:42:16 +00003178 }
Greg Claytonb8596392012-10-15 22:42:16 +00003179 }
Greg Clayton13193d52012-10-13 02:07:45 +00003180 return true;
3181 }
3182};
3183
Greg Claytonb8596392012-10-15 22:42:16 +00003184class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
3185{
3186private:
3187
3188public:
3189 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
3190 CommandObjectMultiword (interpreter,
3191 "process plugin packet",
3192 "Commands that deal with GDB remote packets.",
3193 NULL)
3194 {
3195 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
3196 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
3197 }
3198
3199 ~CommandObjectProcessGDBRemotePacket ()
3200 {
3201 }
3202};
Greg Clayton13193d52012-10-13 02:07:45 +00003203
3204class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
3205{
3206public:
3207 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
3208 CommandObjectMultiword (interpreter,
3209 "process plugin",
3210 "A set of commands for operating on a ProcessGDBRemote process.",
3211 "process plugin <subcommand> [<subcommand-options>]")
3212 {
3213 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
3214 }
3215
3216 ~CommandObjectMultiwordProcessGDBRemote ()
3217 {
3218 }
3219};
3220
Greg Clayton13193d52012-10-13 02:07:45 +00003221CommandObject *
3222ProcessGDBRemote::GetPluginCommandObject()
3223{
3224 if (!m_command_sp)
3225 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
3226 return m_command_sp.get();
3227}