blob: 30c17c9e98a730319ebd8be2241f72b0280e9f95 [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
Greg Claytond9919d32011-12-01 23:28:38 +0000471 error.SetErrorStringWithFormat ("Process %llu was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
Greg Claytone71e2582011-02-04 01:58:07 +0000472 }
473 else
Greg Claytond9919d32011-12-01 23:28:38 +0000474 error.SetErrorStringWithFormat ("Process %llu was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +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;
567 kernel_addr = data8.GetU32(&offset);
568 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];
Greg Claytond9919d32011-12-01 23:28:38 +0000963 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%llx", 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
1061Error
1062ProcessGDBRemote::WillResume ()
1063{
Greg Claytonc1f45872011-02-12 06:28:37 +00001064 m_continue_c_tids.clear();
1065 m_continue_C_tids.clear();
1066 m_continue_s_tids.clear();
1067 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001068 return Error();
1069}
1070
1071Error
1072ProcessGDBRemote::DoResume ()
1073{
Jim Ingham3ae449a2010-11-17 02:32:00 +00001074 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +00001075 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1076 if (log)
1077 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +00001078
1079 Listener listener ("gdb-remote.resume-packet-sent");
1080 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1081 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001082 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1083
Greg Claytonc1f45872011-02-12 06:28:37 +00001084 StreamString continue_packet;
1085 bool continue_packet_error = false;
1086 if (m_gdb_comm.HasAnyVContSupport ())
1087 {
1088 continue_packet.PutCString ("vCont");
1089
1090 if (!m_continue_c_tids.empty())
1091 {
1092 if (m_gdb_comm.GetVContSupported ('c'))
1093 {
1094 for (tid_collection::const_iterator t_pos = m_continue_c_tids.begin(), t_end = m_continue_c_tids.end(); t_pos != t_end; ++t_pos)
Greg Claytond9919d32011-12-01 23:28:38 +00001095 continue_packet.Printf(";c:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +00001096 }
1097 else
1098 continue_packet_error = true;
1099 }
1100
1101 if (!continue_packet_error && !m_continue_C_tids.empty())
1102 {
1103 if (m_gdb_comm.GetVContSupported ('C'))
1104 {
1105 for (tid_sig_collection::const_iterator s_pos = m_continue_C_tids.begin(), s_end = m_continue_C_tids.end(); s_pos != s_end; ++s_pos)
Greg Claytond9919d32011-12-01 23:28:38 +00001106 continue_packet.Printf(";C%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001107 }
1108 else
1109 continue_packet_error = true;
1110 }
Greg Claytonb749a262010-12-03 06:02:24 +00001111
Greg Claytonc1f45872011-02-12 06:28:37 +00001112 if (!continue_packet_error && !m_continue_s_tids.empty())
1113 {
1114 if (m_gdb_comm.GetVContSupported ('s'))
1115 {
1116 for (tid_collection::const_iterator t_pos = m_continue_s_tids.begin(), t_end = m_continue_s_tids.end(); t_pos != t_end; ++t_pos)
Greg Claytond9919d32011-12-01 23:28:38 +00001117 continue_packet.Printf(";s:%4.4llx", *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +00001118 }
1119 else
1120 continue_packet_error = true;
1121 }
1122
1123 if (!continue_packet_error && !m_continue_S_tids.empty())
1124 {
1125 if (m_gdb_comm.GetVContSupported ('S'))
1126 {
1127 for (tid_sig_collection::const_iterator s_pos = m_continue_S_tids.begin(), s_end = m_continue_S_tids.end(); s_pos != s_end; ++s_pos)
Greg Claytond9919d32011-12-01 23:28:38 +00001128 continue_packet.Printf(";S%2.2x:%4.4llx", s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001129 }
1130 else
1131 continue_packet_error = true;
1132 }
1133
1134 if (continue_packet_error)
1135 continue_packet.GetString().clear();
1136 }
1137 else
1138 continue_packet_error = true;
1139
1140 if (continue_packet_error)
1141 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001142 // Either no vCont support, or we tried to use part of the vCont
1143 // packet that wasn't supported by the remote GDB server.
1144 // We need to try and make a simple packet that can do our continue
1145 const size_t num_threads = GetThreadList().GetSize();
1146 const size_t num_continue_c_tids = m_continue_c_tids.size();
1147 const size_t num_continue_C_tids = m_continue_C_tids.size();
1148 const size_t num_continue_s_tids = m_continue_s_tids.size();
1149 const size_t num_continue_S_tids = m_continue_S_tids.size();
1150 if (num_continue_c_tids > 0)
1151 {
1152 if (num_continue_c_tids == num_threads)
1153 {
1154 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001155 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001156 continue_packet.PutChar ('c');
1157 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001158 }
1159 else if (num_continue_c_tids == 1 &&
1160 num_continue_C_tids == 0 &&
1161 num_continue_s_tids == 0 &&
1162 num_continue_S_tids == 0 )
1163 {
1164 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +00001165 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001166 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +00001167 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001168 }
1169 }
1170
Greg Claytonde1dd812011-06-24 03:21:43 +00001171 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001172 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001173 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1174 num_continue_C_tids > 0 &&
1175 num_continue_s_tids == 0 &&
1176 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +00001177 {
1178 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +00001179 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +00001180 if (num_continue_C_tids > 1)
1181 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001182 // More that one thread with a signal, yet we don't have
1183 // vCont support and we are being asked to resume each
1184 // thread with a signal, we need to make sure they are
1185 // all the same signal, or we can't issue the continue
1186 // accurately with the current support...
1187 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +00001188 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001189 continue_packet_error = false;
1190 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1191 {
1192 if (m_continue_C_tids[i].second != continue_signo)
1193 continue_packet_error = true;
1194 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001195 }
Greg Claytonde1dd812011-06-24 03:21:43 +00001196 if (!continue_packet_error)
1197 m_gdb_comm.SetCurrentThreadForRun (-1);
1198 }
1199 else
1200 {
1201 // Set the continue thread ID
1202 continue_packet_error = false;
1203 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001204 }
1205 if (!continue_packet_error)
1206 {
1207 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +00001208 continue_packet.Printf("C%2.2x", continue_signo);
1209 }
1210 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001211 }
1212
Greg Claytonde1dd812011-06-24 03:21:43 +00001213 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001214 {
1215 if (num_continue_s_tids == num_threads)
1216 {
1217 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001218 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001219 continue_packet.PutChar ('s');
1220 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001221 }
1222 else if (num_continue_c_tids == 0 &&
1223 num_continue_C_tids == 0 &&
1224 num_continue_s_tids == 1 &&
1225 num_continue_S_tids == 0 )
1226 {
1227 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001228 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001229 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001230 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001231 }
1232 }
1233
1234 if (!continue_packet_error && num_continue_S_tids > 0)
1235 {
1236 if (num_continue_S_tids == num_threads)
1237 {
1238 const int step_signo = m_continue_S_tids.front().second;
1239 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001240 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001241 if (num_continue_S_tids > 1)
1242 {
1243 for (size_t i=1; i<num_threads; ++i)
1244 {
1245 if (m_continue_S_tids[i].second != step_signo)
1246 continue_packet_error = true;
1247 }
1248 }
1249 if (!continue_packet_error)
1250 {
1251 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001252 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001253 continue_packet.Printf("S%2.2x", step_signo);
1254 }
1255 }
1256 else if (num_continue_c_tids == 0 &&
1257 num_continue_C_tids == 0 &&
1258 num_continue_s_tids == 0 &&
1259 num_continue_S_tids == 1 )
1260 {
1261 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001262 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001263 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001264 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001265 }
1266 }
1267 }
1268
1269 if (continue_packet_error)
1270 {
1271 error.SetErrorString ("can't make continue packet for this resume");
1272 }
1273 else
1274 {
1275 EventSP event_sp;
1276 TimeValue timeout;
1277 timeout = TimeValue::Now();
1278 timeout.OffsetWithSeconds (5);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001279 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1280 {
1281 error.SetErrorString ("Trying to resume but the async thread is dead.");
1282 if (log)
1283 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1284 return error;
1285 }
1286
Greg Claytonc1f45872011-02-12 06:28:37 +00001287 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1288
1289 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001290 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001291 error.SetErrorString("Resume timed out.");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001292 if (log)
1293 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1294 }
1295 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1296 {
1297 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1298 if (log)
1299 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1300 return error;
1301 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001302 }
Greg Claytonb749a262010-12-03 06:02:24 +00001303 }
1304
Jim Ingham3ae449a2010-11-17 02:32:00 +00001305 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001306}
1307
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001308void
1309ProcessGDBRemote::ClearThreadIDList ()
1310{
Greg Claytonff3448e2012-04-13 02:11:32 +00001311 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001312 m_thread_ids.clear();
1313}
1314
1315bool
1316ProcessGDBRemote::UpdateThreadIDList ()
1317{
Greg Claytonff3448e2012-04-13 02:11:32 +00001318 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001319 bool sequence_mutex_unavailable = false;
1320 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1321 if (sequence_mutex_unavailable)
1322 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001323 return false; // We just didn't get the list
1324 }
1325 return true;
1326}
1327
Greg Claytonae932352012-04-10 00:18:59 +00001328bool
Greg Clayton37f962e2011-08-22 02:49:39 +00001329ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001330{
1331 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001332 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001333 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Greg Clayton444e35b2011-10-19 18:09:39 +00001334 log->Printf ("ProcessGDBRemote::%s (pid = %llu)", __FUNCTION__, GetID());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001335
1336 size_t num_thread_ids = m_thread_ids.size();
1337 // The "m_thread_ids" thread ID list should always be updated after each stop
1338 // reply packet, but in case it isn't, update it here.
1339 if (num_thread_ids == 0)
1340 {
1341 if (!UpdateThreadIDList ())
1342 return false;
1343 num_thread_ids = m_thread_ids.size();
1344 }
Chris Lattner24943d22010-06-08 16:52:24 +00001345
Greg Clayton37f962e2011-08-22 02:49:39 +00001346 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001347 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001348 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001349 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001350 tid_t tid = m_thread_ids[i];
Greg Clayton37f962e2011-08-22 02:49:39 +00001351 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false));
1352 if (!thread_sp)
Jim Ingham94a5d0d2012-10-10 18:32:14 +00001353 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Greg Clayton37f962e2011-08-22 02:49:39 +00001354 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001355 }
Chris Lattner24943d22010-06-08 16:52:24 +00001356 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001357
Greg Claytonae932352012-04-10 00:18:59 +00001358 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001359}
1360
1361
1362StateType
1363ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1364{
Greg Clayton261a18b2011-06-02 22:22:38 +00001365 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001366 const char stop_type = stop_packet.GetChar();
1367 switch (stop_type)
1368 {
1369 case 'T':
1370 case 'S':
1371 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001372 if (GetStopID() == 0)
1373 {
1374 // Our first stop, make sure we have a process ID, and also make
1375 // sure we know about our registers
1376 if (GetID() == LLDB_INVALID_PROCESS_ID)
1377 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001378 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001379 if (pid != LLDB_INVALID_PROCESS_ID)
1380 SetID (pid);
1381 }
1382 BuildDynamicRegisterInfo (true);
1383 }
Chris Lattner24943d22010-06-08 16:52:24 +00001384 // Stop with signal and thread info
1385 const uint8_t signo = stop_packet.GetHexU8();
1386 std::string name;
1387 std::string value;
1388 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001389 std::string reason;
1390 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001391 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001392 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001393 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Claytona875b642011-01-09 21:07:35 +00001394 ThreadSP thread_sp;
1395
Chris Lattner24943d22010-06-08 16:52:24 +00001396 while (stop_packet.GetNameColonValue(name, value))
1397 {
1398 if (name.compare("metype") == 0)
1399 {
1400 // exception type in big endian hex
1401 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1402 }
Chris Lattner24943d22010-06-08 16:52:24 +00001403 else if (name.compare("medata") == 0)
1404 {
1405 // exception data in big endian hex
1406 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1407 }
1408 else if (name.compare("thread") == 0)
1409 {
1410 // thread in big endian hex
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001411 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Claytonffa43a62011-11-17 04:46:02 +00001412 // m_thread_list does have its own mutex, but we need to
1413 // hold onto the mutex between the call to m_thread_list.FindThreadByID(...)
1414 // and the m_thread_list.AddThread(...) so it doesn't change on us
Greg Claytonc3c46612011-02-15 00:19:15 +00001415 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001416 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001417 if (!thread_sp)
1418 {
1419 // Create the thread if we need to
Jim Ingham94a5d0d2012-10-10 18:32:14 +00001420 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Greg Claytonc3c46612011-02-15 00:19:15 +00001421 m_thread_list.AddThread(thread_sp);
1422 }
Chris Lattner24943d22010-06-08 16:52:24 +00001423 }
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001424 else if (name.compare("threads") == 0)
1425 {
Greg Claytonff3448e2012-04-13 02:11:32 +00001426 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001427 m_thread_ids.clear();
Greg Claytona1f645e2012-04-10 03:22:03 +00001428 // A comma separated list of all threads in the current
1429 // process that includes the thread for this stop reply
1430 // packet
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001431 size_t comma_pos;
1432 lldb::tid_t tid;
1433 while ((comma_pos = value.find(',')) != std::string::npos)
1434 {
1435 value[comma_pos] = '\0';
1436 // thread in big endian hex
1437 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1438 if (tid != LLDB_INVALID_THREAD_ID)
1439 m_thread_ids.push_back (tid);
1440 value.erase(0, comma_pos + 1);
1441
1442 }
1443 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1444 if (tid != LLDB_INVALID_THREAD_ID)
1445 m_thread_ids.push_back (tid);
1446 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001447 else if (name.compare("hexname") == 0)
1448 {
1449 StringExtractor name_extractor;
1450 // Swap "value" over into "name_extractor"
1451 name_extractor.GetStringRef().swap(value);
1452 // Now convert the HEX bytes into a string value
1453 name_extractor.GetHexByteString (value);
1454 thread_name.swap (value);
1455 }
Chris Lattner24943d22010-06-08 16:52:24 +00001456 else if (name.compare("name") == 0)
1457 {
1458 thread_name.swap (value);
1459 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001460 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001461 {
1462 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1463 }
Greg Clayton65611552011-06-04 01:26:29 +00001464 else if (name.compare("reason") == 0)
1465 {
1466 reason.swap(value);
1467 }
1468 else if (name.compare("description") == 0)
1469 {
1470 StringExtractor desc_extractor;
1471 // Swap "value" over into "name_extractor"
1472 desc_extractor.GetStringRef().swap(value);
1473 // Now convert the HEX bytes into a string value
1474 desc_extractor.GetHexByteString (thread_name);
1475 }
Greg Claytona875b642011-01-09 21:07:35 +00001476 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1477 {
1478 // We have a register number that contains an expedited
1479 // register value. Lets supply this register to our thread
1480 // so it won't have to go and read it.
1481 if (thread_sp)
1482 {
1483 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1484
1485 if (reg != UINT32_MAX)
1486 {
1487 StringExtractor reg_value_extractor;
1488 // Swap "value" over into "reg_value_extractor"
1489 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001490 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1491 {
1492 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1493 name.c_str(),
1494 reg,
1495 reg,
1496 reg_value_extractor.GetStringRef().c_str(),
1497 stop_packet.GetStringRef().c_str());
1498 }
Greg Claytona875b642011-01-09 21:07:35 +00001499 }
1500 }
1501 }
Chris Lattner24943d22010-06-08 16:52:24 +00001502 }
Chris Lattner24943d22010-06-08 16:52:24 +00001503
1504 if (thread_sp)
1505 {
1506 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1507
1508 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001509 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001510 if (exc_type != 0)
1511 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001512 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001513
1514 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1515 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001516 exc_data_size,
1517 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001518 exc_data_size >= 2 ? exc_data[1] : 0,
1519 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001520 }
Greg Clayton65611552011-06-04 01:26:29 +00001521 else
Chris Lattner24943d22010-06-08 16:52:24 +00001522 {
Greg Clayton65611552011-06-04 01:26:29 +00001523 bool handled = false;
1524 if (!reason.empty())
1525 {
1526 if (reason.compare("trace") == 0)
1527 {
1528 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1529 handled = true;
1530 }
1531 else if (reason.compare("breakpoint") == 0)
1532 {
1533 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001534 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001535 if (bp_site_sp)
1536 {
1537 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1538 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1539 // 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 +00001540 handled = true;
Greg Clayton65611552011-06-04 01:26:29 +00001541 if (bp_site_sp->ValidForThisThread (gdb_thread))
1542 {
1543 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001544 }
1545 else
1546 {
1547 StopInfoSP invalid_stop_info_sp;
1548 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Greg Clayton65611552011-06-04 01:26:29 +00001549 }
1550 }
1551
Greg Clayton65611552011-06-04 01:26:29 +00001552 }
1553 else if (reason.compare("trap") == 0)
1554 {
1555 // Let the trap just use the standard signal stop reason below...
1556 }
1557 else if (reason.compare("watchpoint") == 0)
1558 {
1559 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1560 // TODO: locate the watchpoint somehow...
1561 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1562 handled = true;
1563 }
1564 else if (reason.compare("exception") == 0)
1565 {
1566 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1567 handled = true;
1568 }
1569 }
1570
1571 if (signo)
1572 {
1573 if (signo == SIGTRAP)
1574 {
1575 // Currently we are going to assume SIGTRAP means we are either
1576 // hitting a breakpoint or hardware single stepping.
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001577 handled = true;
Greg Clayton65611552011-06-04 01:26:29 +00001578 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001579 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001580
Greg Clayton65611552011-06-04 01:26:29 +00001581 if (bp_site_sp)
1582 {
1583 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1584 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1585 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1586 if (bp_site_sp->ValidForThisThread (gdb_thread))
1587 {
1588 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001589 }
1590 else
1591 {
1592 StopInfoSP invalid_stop_info_sp;
1593 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Greg Clayton65611552011-06-04 01:26:29 +00001594 }
1595 }
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001596 else
Greg Clayton65611552011-06-04 01:26:29 +00001597 {
Jim Ingham4fa015b2012-10-27 02:52:04 +00001598 // If we were stepping then assume the stop was the result of the trace. If we were
1599 // not stepping then report the SIGTRAP.
1600 // FIXME: We are still missing the case where we single step over a trap instruction.
1601 if (gdb_thread->GetTemporaryResumeState() == eStateStepping)
1602 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1603 else
1604 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo));
Greg Clayton65611552011-06-04 01:26:29 +00001605 }
1606 }
1607 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001608 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001609 }
1610 else
1611 {
Greg Clayton643ee732010-08-04 01:40:35 +00001612 StopInfoSP invalid_stop_info_sp;
1613 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001614 }
Greg Clayton65611552011-06-04 01:26:29 +00001615
1616 if (!description.empty())
1617 {
1618 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1619 if (stop_info_sp)
1620 {
1621 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001622 }
Greg Clayton65611552011-06-04 01:26:29 +00001623 else
1624 {
1625 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1626 }
1627 }
1628 }
Chris Lattner24943d22010-06-08 16:52:24 +00001629 }
1630 return eStateStopped;
1631 }
1632 break;
1633
1634 case 'W':
1635 // process exited
1636 return eStateExited;
1637
1638 default:
1639 break;
1640 }
1641 return eStateInvalid;
1642}
1643
1644void
1645ProcessGDBRemote::RefreshStateAfterStop ()
1646{
Greg Claytonff3448e2012-04-13 02:11:32 +00001647 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001648 m_thread_ids.clear();
1649 // Set the thread stop info. It might have a "threads" key whose value is
1650 // a list of all thread IDs in the current process, so m_thread_ids might
1651 // get set.
1652 SetThreadStopInfo (m_last_stop_packet);
1653 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1654 if (m_thread_ids.empty())
1655 {
1656 // No, we need to fetch the thread list manually
1657 UpdateThreadIDList();
1658 }
1659
Chris Lattner24943d22010-06-08 16:52:24 +00001660 // Let all threads recover from stopping and do any clean up based
1661 // on the previous thread state (if any).
1662 m_thread_list.RefreshStateAfterStop();
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001663
Chris Lattner24943d22010-06-08 16:52:24 +00001664}
1665
1666Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001667ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001668{
1669 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001670
Greg Claytona4881d02011-01-22 07:12:45 +00001671 bool timed_out = false;
1672 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001673
1674 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001675 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001676 // We are being asked to halt during an attach. We need to just close
1677 // our file handle and debugserver will go away, and we can be done...
1678 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001679 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001680 else
1681 {
Greg Clayton05e4d972012-03-29 01:55:41 +00001682 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001683 {
1684 if (timed_out)
1685 error.SetErrorString("timed out sending interrupt packet");
1686 else
1687 error.SetErrorString("unknown error sending interrupt packet");
1688 }
Greg Clayton05e4d972012-03-29 01:55:41 +00001689
1690 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001691 }
Chris Lattner24943d22010-06-08 16:52:24 +00001692 return error;
1693}
1694
1695Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001696ProcessGDBRemote::InterruptIfRunning
1697(
1698 bool discard_thread_plans,
1699 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001700 EventSP &stop_event_sp
1701)
Chris Lattner24943d22010-06-08 16:52:24 +00001702{
1703 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001704
Greg Clayton2860ba92011-01-23 19:58:49 +00001705 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1706
Greg Clayton68ca8232011-01-25 02:58:48 +00001707 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001708 const bool is_running = m_gdb_comm.IsRunning();
1709 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001710 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001711 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001712 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001713 is_running);
1714
Greg Clayton2860ba92011-01-23 19:58:49 +00001715 if (discard_thread_plans)
1716 {
1717 if (log)
1718 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1719 m_thread_list.DiscardThreadPlans();
1720 }
1721 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001722 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001723 if (catch_stop_event)
1724 {
1725 if (log)
1726 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1727 PausePrivateStateThread();
1728 paused_private_state_thread = true;
1729 }
1730
Greg Clayton4fb400f2010-09-27 21:07:38 +00001731 bool timed_out = false;
1732 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001733
Greg Clayton05e4d972012-03-29 01:55:41 +00001734 if (!m_gdb_comm.SendInterrupt (locker, 1, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001735 {
1736 if (timed_out)
1737 error.SetErrorString("timed out sending interrupt packet");
1738 else
1739 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001740 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001741 ResumePrivateStateThread();
1742 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001743 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001744
Greg Clayton72e1c782011-01-22 23:43:18 +00001745 if (catch_stop_event)
1746 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001747 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001748 TimeValue timeout_time;
1749 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001750 timeout_time.OffsetWithSeconds(5);
1751 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001752
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001753 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001754 if (log)
1755 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001756
Greg Clayton2860ba92011-01-23 19:58:49 +00001757 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001758 error.SetErrorString("unable to verify target stopped");
1759 }
1760
Greg Clayton68ca8232011-01-25 02:58:48 +00001761 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001762 {
1763 if (log)
1764 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001765 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001766 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001767 }
Chris Lattner24943d22010-06-08 16:52:24 +00001768 return error;
1769}
1770
Greg Clayton4fb400f2010-09-27 21:07:38 +00001771Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001772ProcessGDBRemote::WillDetach ()
1773{
Greg Clayton2860ba92011-01-23 19:58:49 +00001774 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1775 if (log)
1776 log->Printf ("ProcessGDBRemote::WillDetach()");
1777
Greg Clayton72e1c782011-01-22 23:43:18 +00001778 bool discard_thread_plans = true;
1779 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001780 EventSP event_sp;
Jim Ingham8247e622012-06-06 00:32:39 +00001781
1782 // FIXME: InterruptIfRunning should be done in the Process base class, or better still make Halt do what is
1783 // needed. This shouldn't be a feature of a particular plugin.
1784
Greg Clayton68ca8232011-01-25 02:58:48 +00001785 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001786}
1787
1788Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001789ProcessGDBRemote::DoDetach()
1790{
1791 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001792 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001793 if (log)
1794 log->Printf ("ProcessGDBRemote::DoDetach()");
1795
1796 DisableAllBreakpointSites ();
1797
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001798 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001799
Greg Clayton516f0842012-04-11 00:24:49 +00001800 bool success = m_gdb_comm.Detach ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001801 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001802 {
Greg Clayton516f0842012-04-11 00:24:49 +00001803 if (success)
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001804 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1805 else
1806 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001807 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001808 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001809 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001810
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001811 SetPrivateState (eStateDetached);
1812 ResumePrivateStateThread();
1813
1814 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001815 return error;
1816}
Chris Lattner24943d22010-06-08 16:52:24 +00001817
Jim Ingham06b84492012-07-04 00:35:43 +00001818
Chris Lattner24943d22010-06-08 16:52:24 +00001819Error
1820ProcessGDBRemote::DoDestroy ()
1821{
1822 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001823 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001824 if (log)
1825 log->Printf ("ProcessGDBRemote::DoDestroy()");
1826
Jim Ingham06b84492012-07-04 00:35:43 +00001827 // There is a bug in older iOS debugservers where they don't shut down the process
1828 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
1829 // this can cause problems with restarting. So we check to see if any of our threads are stopped
1830 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
1831 // destroy it again.
1832 //
1833 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
1834 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
1835 // the debugservers with this bug are equal. There really should be a better way to test this!
1836 //
1837 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
1838 // get called here to destroy again and we're still at a breakpoint or exception, then we should
1839 // just do the straight-forward kill.
1840 //
1841 // And of course, if we weren't able to stop the process by the time we get here, it isn't
1842 // necessary (or helpful) to do any of this.
1843
1844 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
1845 {
1846 PlatformSP platform_sp = GetTarget().GetPlatform();
1847
1848 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
1849 if (platform_sp
1850 && platform_sp->GetName()
1851 && strcmp (platform_sp->GetName(), PlatformRemoteiOS::GetShortPluginNameStatic()) == 0)
1852 {
1853 if (m_destroy_tried_resuming)
1854 {
1855 if (log)
1856 log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again.");
1857 }
1858 else
1859 {
1860 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
1861 // but we really need it to happen here and it doesn't matter if we do it twice.
1862 m_thread_list.DiscardThreadPlans();
1863 DisableAllBreakpointSites();
1864
1865 bool stop_looks_like_crash = false;
1866 ThreadList &threads = GetThreadList();
1867
1868 {
Jim Inghamc2c65142012-09-11 00:08:52 +00001869 Mutex::Locker locker(threads.GetMutex());
Jim Ingham06b84492012-07-04 00:35:43 +00001870
1871 size_t num_threads = threads.GetSize();
1872 for (size_t i = 0; i < num_threads; i++)
1873 {
1874 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1875 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason();
1876 StopReason reason = eStopReasonInvalid;
1877 if (stop_info_sp)
1878 reason = stop_info_sp->GetStopReason();
1879 if (reason == eStopReasonBreakpoint
1880 || reason == eStopReasonException)
1881 {
1882 if (log)
1883 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: %lld stopped with reason: %s.",
1884 thread_sp->GetID(),
1885 stop_info_sp->GetDescription());
1886 stop_looks_like_crash = true;
1887 break;
1888 }
1889 }
1890 }
1891
1892 if (stop_looks_like_crash)
1893 {
1894 if (log)
1895 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
1896 m_destroy_tried_resuming = true;
1897
1898 // If we are going to run again before killing, it would be good to suspend all the threads
1899 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
1900 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
1901 // have to run the risk of letting those threads proceed a bit.
1902
1903 {
Jim Inghamc2c65142012-09-11 00:08:52 +00001904 Mutex::Locker locker(threads.GetMutex());
Jim Ingham06b84492012-07-04 00:35:43 +00001905
1906 size_t num_threads = threads.GetSize();
1907 for (size_t i = 0; i < num_threads; i++)
1908 {
1909 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1910 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason();
1911 StopReason reason = eStopReasonInvalid;
1912 if (stop_info_sp)
1913 reason = stop_info_sp->GetStopReason();
1914 if (reason != eStopReasonBreakpoint
1915 && reason != eStopReasonException)
1916 {
1917 if (log)
1918 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: %lld before running.",
1919 thread_sp->GetID());
1920 thread_sp->SetResumeState(eStateSuspended);
1921 }
1922 }
1923 }
1924 Resume ();
1925 return Destroy();
1926 }
1927 }
1928 }
1929 }
1930
Chris Lattner24943d22010-06-08 16:52:24 +00001931 // Interrupt if our inferior is running...
Jim Ingham8247e622012-06-06 00:32:39 +00001932 int exit_status = SIGABRT;
1933 std::string exit_string;
1934
Greg Claytona4881d02011-01-22 07:12:45 +00001935 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001936 {
Jim Ingham8226e942011-10-28 01:11:35 +00001937 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton72e1c782011-01-22 23:43:18 +00001938 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001939
1940 StringExtractorGDBRemote response;
1941 bool send_async = true;
Filipe Cabecinhasee188ee2012-08-22 13:25:58 +00001942 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3);
1943
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001944 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001945 {
1946 char packet_cmd = response.GetChar(0);
1947
1948 if (packet_cmd == 'W' || packet_cmd == 'X')
1949 {
Greg Clayton06709002011-12-06 04:51:14 +00001950 SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001951 ClearThreadIDList ();
Jim Ingham8247e622012-06-06 00:32:39 +00001952 exit_status = response.GetHexU8();
1953 }
1954 else
1955 {
1956 if (log)
1957 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
1958 exit_string.assign("got unexpected response to k packet: ");
1959 exit_string.append(response.GetStringRef());
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001960 }
1961 }
1962 else
1963 {
Jim Ingham8247e622012-06-06 00:32:39 +00001964 if (log)
1965 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
1966 exit_string.assign("failed to send the k packet");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001967 }
Filipe Cabecinhasee188ee2012-08-22 13:25:58 +00001968
1969 m_gdb_comm.SetPacketTimeout(old_packet_timeout);
Greg Clayton72e1c782011-01-22 23:43:18 +00001970 }
Jim Ingham8247e622012-06-06 00:32:39 +00001971 else
1972 {
1973 if (log)
1974 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
Jim Ingham5d90ade2012-07-27 23:57:19 +00001975 exit_string.assign ("killed or interrupted while attaching.");
Jim Ingham8247e622012-06-06 00:32:39 +00001976 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001977 }
Jim Ingham8247e622012-06-06 00:32:39 +00001978 else
1979 {
1980 // If we missed setting the exit status on the way out, do it here.
1981 // NB set exit status can be called multiple times, the first one sets the status.
1982 exit_string.assign("destroying when not connected to debugserver");
1983 }
1984
1985 SetExitStatus(exit_status, exit_string.c_str());
1986
Chris Lattner24943d22010-06-08 16:52:24 +00001987 StopAsyncThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00001988 KillDebugserverProcess ();
1989 return error;
1990}
1991
Chris Lattner24943d22010-06-08 16:52:24 +00001992//------------------------------------------------------------------
1993// Process Queries
1994//------------------------------------------------------------------
1995
1996bool
1997ProcessGDBRemote::IsAlive ()
1998{
Greg Clayton58e844b2010-12-08 05:08:21 +00001999 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00002000}
2001
Jason Molendad6b81222012-10-06 02:02:26 +00002002// For kernel debugging, we return the load address of the kernel binary as the
2003// ImageInfoAddress and we return the DynamicLoaderDarwinKernel as the GetDynamicLoader()
2004// name so the correct DynamicLoader plugin is chosen.
Chris Lattner24943d22010-06-08 16:52:24 +00002005addr_t
2006ProcessGDBRemote::GetImageInfoAddress()
2007{
Jason Molendab46937c2012-10-03 01:29:34 +00002008 if (m_kernel_load_addr != LLDB_INVALID_ADDRESS)
2009 return m_kernel_load_addr;
2010 else
2011 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner24943d22010-06-08 16:52:24 +00002012}
2013
Chris Lattner24943d22010-06-08 16:52:24 +00002014//------------------------------------------------------------------
2015// Process Memory
2016//------------------------------------------------------------------
2017size_t
2018ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2019{
2020 if (size > m_max_memory_size)
2021 {
2022 // Keep memory read sizes down to a sane limit. This function will be
2023 // called multiple times in order to complete the task by
2024 // lldb_private::Process so it is ok to do this.
2025 size = m_max_memory_size;
2026 }
2027
2028 char packet[64];
Greg Clayton851e30e2012-09-18 18:04:04 +00002029 const int packet_len = ::snprintf (packet, sizeof(packet), "m%llx,%llx", (uint64_t)addr, (uint64_t)size);
Chris Lattner24943d22010-06-08 16:52:24 +00002030 assert (packet_len + 1 < sizeof(packet));
2031 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00002032 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00002033 {
Greg Clayton61d043b2011-03-22 04:00:09 +00002034 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00002035 {
2036 error.Clear();
2037 return response.GetHexBytes(buf, size, '\xdd');
2038 }
Greg Clayton61d043b2011-03-22 04:00:09 +00002039 else if (response.IsErrorResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00002040 error.SetErrorString("memory read failed");
Greg Clayton61d043b2011-03-22 04:00:09 +00002041 else if (response.IsUnsupportedResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00002042 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner24943d22010-06-08 16:52:24 +00002043 else
Greg Claytonae7bebc2012-09-19 01:46:31 +00002044 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00002045 }
2046 else
2047 {
2048 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
2049 }
2050 return 0;
2051}
2052
2053size_t
2054ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2055{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00002056 if (size > m_max_memory_size)
2057 {
2058 // Keep memory read sizes down to a sane limit. This function will be
2059 // called multiple times in order to complete the task by
2060 // lldb_private::Process so it is ok to do this.
2061 size = m_max_memory_size;
2062 }
2063
Chris Lattner24943d22010-06-08 16:52:24 +00002064 StreamString packet;
Greg Clayton851e30e2012-09-18 18:04:04 +00002065 packet.Printf("M%llx,%llx:", addr, (uint64_t)size);
Greg Claytoncd548032011-02-01 01:31:41 +00002066 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00002067 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00002068 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00002069 {
Greg Clayton61d043b2011-03-22 04:00:09 +00002070 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00002071 {
2072 error.Clear();
2073 return size;
2074 }
Greg Clayton61d043b2011-03-22 04:00:09 +00002075 else if (response.IsErrorResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00002076 error.SetErrorString("memory write failed");
Greg Clayton61d043b2011-03-22 04:00:09 +00002077 else if (response.IsUnsupportedResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00002078 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner24943d22010-06-08 16:52:24 +00002079 else
Greg Claytonae7bebc2012-09-19 01:46:31 +00002080 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 +00002081 }
2082 else
2083 {
2084 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
2085 }
2086 return 0;
2087}
2088
2089lldb::addr_t
2090ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2091{
Greg Clayton989816b2011-05-14 01:50:35 +00002092 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2093
Greg Clayton2f085c62011-05-15 01:25:55 +00002094 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00002095 switch (supported)
2096 {
2097 case eLazyBoolCalculate:
2098 case eLazyBoolYes:
2099 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2100 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2101 return allocated_addr;
2102
2103 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002104 // Call mmap() to create memory in the inferior..
2105 unsigned prot = 0;
2106 if (permissions & lldb::ePermissionsReadable)
2107 prot |= eMmapProtRead;
2108 if (permissions & lldb::ePermissionsWritable)
2109 prot |= eMmapProtWrite;
2110 if (permissions & lldb::ePermissionsExecutable)
2111 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00002112
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002113 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2114 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2115 m_addr_to_mmap_size[allocated_addr] = size;
2116 else
2117 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00002118 break;
2119 }
2120
Chris Lattner24943d22010-06-08 16:52:24 +00002121 if (allocated_addr == LLDB_INVALID_ADDRESS)
Greg Clayton851e30e2012-09-18 18:04:04 +00002122 error.SetErrorStringWithFormat("unable to allocate %llu bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00002123 else
2124 error.Clear();
2125 return allocated_addr;
2126}
2127
2128Error
Greg Claytona9385532011-11-18 07:03:08 +00002129ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2130 MemoryRegionInfo &region_info)
2131{
2132
2133 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2134 return error;
2135}
2136
2137Error
Johnny Chen7cbdcfb2012-05-23 21:09:52 +00002138ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2139{
2140
2141 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2142 return error;
2143}
2144
2145Error
Enrico Granata7de2a3b2012-07-13 23:18:48 +00002146ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2147{
2148 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2149 return error;
2150}
2151
2152Error
Chris Lattner24943d22010-06-08 16:52:24 +00002153ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2154{
2155 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00002156 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2157
2158 switch (supported)
2159 {
2160 case eLazyBoolCalculate:
2161 // We should never be deallocating memory without allocating memory
2162 // first so we should never get eLazyBoolCalculate
2163 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2164 break;
2165
2166 case eLazyBoolYes:
2167 if (!m_gdb_comm.DeallocateMemory (addr))
2168 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
2169 break;
2170
2171 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002172 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00002173 {
2174 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002175 if (pos != m_addr_to_mmap_size.end() &&
2176 InferiorCallMunmap(this, addr, pos->second))
2177 m_addr_to_mmap_size.erase (pos);
2178 else
2179 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%llx", addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00002180 }
2181 break;
2182 }
2183
Chris Lattner24943d22010-06-08 16:52:24 +00002184 return error;
2185}
2186
2187
2188//------------------------------------------------------------------
2189// Process STDIO
2190//------------------------------------------------------------------
Chris Lattner24943d22010-06-08 16:52:24 +00002191size_t
2192ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2193{
2194 if (m_stdio_communication.IsConnected())
2195 {
2196 ConnectionStatus status;
2197 m_stdio_communication.Write(src, src_len, status, NULL);
2198 }
2199 return 0;
2200}
2201
2202Error
2203ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
2204{
2205 Error error;
2206 assert (bp_site != NULL);
2207
Greg Claytone005f2c2010-11-06 01:53:30 +00002208 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002209 user_id_t site_id = bp_site->GetID();
2210 const addr_t addr = bp_site->GetLoadAddress();
2211 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002212 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002213
2214 if (bp_site->IsEnabled())
2215 {
2216 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002217 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %llu) address = 0x%llx -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002218 return error;
2219 }
2220 else
2221 {
2222 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2223
2224 if (bp_site->HardwarePreferred())
2225 {
2226 // Try and set hardware breakpoint, and if that fails, fall through
2227 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00002228 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00002229 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002230 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00002231 {
2232 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002233 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00002234 return error;
2235 }
Chris Lattner24943d22010-06-08 16:52:24 +00002236 }
2237 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002238
2239 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00002240 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002241 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
2242 {
2243 bp_site->SetEnabled(true);
2244 bp_site->SetType (BreakpointSite::eExternal);
2245 return error;
2246 }
Chris Lattner24943d22010-06-08 16:52:24 +00002247 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002248
2249 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00002250 }
2251
2252 if (log)
2253 {
2254 const char *err_string = error.AsCString();
2255 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8llx: %s",
2256 bp_site->GetLoadAddress(),
2257 err_string ? err_string : "NULL");
2258 }
2259 // We shouldn't reach here on a successful breakpoint enable...
2260 if (error.Success())
2261 error.SetErrorToGenericError();
2262 return error;
2263}
2264
2265Error
2266ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
2267{
2268 Error error;
2269 assert (bp_site != NULL);
2270 addr_t addr = bp_site->GetLoadAddress();
2271 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00002272 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002273 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002274 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002275
2276 if (bp_site->IsEnabled())
2277 {
2278 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2279
Greg Claytonb72d0f02011-04-12 05:54:46 +00002280 BreakpointSite::Type bp_type = bp_site->GetType();
2281 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00002282 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002283 case BreakpointSite::eSoftware:
2284 error = DisableSoftwareBreakpoint (bp_site);
2285 break;
2286
2287 case BreakpointSite::eHardware:
2288 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2289 error.SetErrorToGenericError();
2290 break;
2291
2292 case BreakpointSite::eExternal:
2293 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2294 error.SetErrorToGenericError();
2295 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002296 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002297 if (error.Success())
2298 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00002299 }
2300 else
2301 {
2302 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002303 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002304 return error;
2305 }
2306
2307 if (error.Success())
2308 error.SetErrorToGenericError();
2309 return error;
2310}
2311
Johnny Chen21900fb2011-09-06 22:38:36 +00002312// Pre-requisite: wp != NULL.
2313static GDBStoppointType
Johnny Chenecd4feb2011-10-14 00:42:25 +00002314GetGDBStoppointType (Watchpoint *wp)
Johnny Chen21900fb2011-09-06 22:38:36 +00002315{
2316 assert(wp);
2317 bool watch_read = wp->WatchpointRead();
2318 bool watch_write = wp->WatchpointWrite();
2319
2320 // watch_read and watch_write cannot both be false.
2321 assert(watch_read || watch_write);
2322 if (watch_read && watch_write)
2323 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00002324 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00002325 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00002326 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00002327 return eWatchpointWrite;
2328}
2329
Chris Lattner24943d22010-06-08 16:52:24 +00002330Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002331ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002332{
2333 Error error;
2334 if (wp)
2335 {
2336 user_id_t watchID = wp->GetID();
2337 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00002338 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002339 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002340 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %llu)", watchID);
Chris Lattner24943d22010-06-08 16:52:24 +00002341 if (wp->IsEnabled())
2342 {
2343 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002344 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %llu) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002345 return error;
2346 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002347
2348 GDBStoppointType type = GetGDBStoppointType(wp);
2349 // Pass down an appropriate z/Z packet...
2350 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00002351 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002352 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2353 {
2354 wp->SetEnabled(true);
2355 return error;
2356 }
2357 else
2358 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002359 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002360 else
2361 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00002362 }
2363 else
2364 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002365 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002366 }
2367 if (error.Success())
2368 error.SetErrorToGenericError();
2369 return error;
2370}
2371
2372Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002373ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002374{
2375 Error error;
2376 if (wp)
2377 {
2378 user_id_t watchID = wp->GetID();
2379
Greg Claytone005f2c2010-11-06 01:53:30 +00002380 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002381
2382 addr_t addr = wp->GetLoadAddress();
2383 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002384 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002385
Johnny Chen21900fb2011-09-06 22:38:36 +00002386 if (!wp->IsEnabled())
2387 {
2388 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002389 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %llu) addr = 0x%8.8llx -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
Johnny Chen258db3a2012-08-23 22:28:26 +00002390 // See also 'class WatchpointSentry' within StopInfo.cpp.
2391 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2392 // the watchpoint object to intelligently process this action.
2393 wp->SetEnabled(false);
Johnny Chen21900fb2011-09-06 22:38:36 +00002394 return error;
2395 }
2396
Chris Lattner24943d22010-06-08 16:52:24 +00002397 if (wp->IsHardware())
2398 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002399 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00002400 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00002401 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2402 {
2403 wp->SetEnabled(false);
2404 return error;
2405 }
2406 else
2407 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002408 }
2409 // TODO: clear software watchpoints if we implement them
2410 }
2411 else
2412 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002413 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002414 }
2415 if (error.Success())
2416 error.SetErrorToGenericError();
2417 return error;
2418}
2419
2420void
2421ProcessGDBRemote::Clear()
2422{
2423 m_flags = 0;
2424 m_thread_list.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002425}
2426
2427Error
2428ProcessGDBRemote::DoSignal (int signo)
2429{
2430 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00002431 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002432 if (log)
2433 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2434
2435 if (!m_gdb_comm.SendAsyncSignal (signo))
2436 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2437 return error;
2438}
2439
Chris Lattner24943d22010-06-08 16:52:24 +00002440Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002441ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)
2442{
2443 ProcessLaunchInfo launch_info;
2444 return StartDebugserverProcess(debugserver_url, launch_info);
2445}
2446
2447Error
2448ProcessGDBRemote::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 +00002449{
2450 Error error;
2451 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2452 {
2453 // If we locate debugserver, keep that located version around
2454 static FileSpec g_debugserver_file_spec;
2455
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002456 ProcessLaunchInfo debugserver_launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002457 char debugserver_path[PATH_MAX];
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002458 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002459
2460 // Always check to see if we have an environment override for the path
2461 // to the debugserver to use and use it if we do.
2462 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2463 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002464 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002465 else
2466 debugserver_file_spec = g_debugserver_file_spec;
2467 bool debugserver_exists = debugserver_file_spec.Exists();
2468 if (!debugserver_exists)
2469 {
2470 // The debugserver binary is in the LLDB.framework/Resources
2471 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002472 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002473 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002474 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002475 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002476 if (debugserver_exists)
2477 {
2478 g_debugserver_file_spec = debugserver_file_spec;
2479 }
2480 else
2481 {
2482 g_debugserver_file_spec.Clear();
2483 debugserver_file_spec.Clear();
2484 }
Chris Lattner24943d22010-06-08 16:52:24 +00002485 }
2486 }
2487
2488 if (debugserver_exists)
2489 {
2490 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2491
2492 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002493
Greg Claytone005f2c2010-11-06 01:53:30 +00002494 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002495
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002496 Args &debugserver_args = debugserver_launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002497 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002498
Chris Lattner24943d22010-06-08 16:52:24 +00002499 // Start args with "debugserver /file/path -r --"
2500 debugserver_args.AppendArgument(debugserver_path);
2501 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002502 // use native registers, not the GDB registers
2503 debugserver_args.AppendArgument("--native-regs");
2504 // make debugserver run in its own session so signals generated by
2505 // special terminal key sequences (^C) don't affect debugserver
2506 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002507
Chris Lattner24943d22010-06-08 16:52:24 +00002508 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2509 if (env_debugserver_log_file)
2510 {
2511 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2512 debugserver_args.AppendArgument(arg_cstr);
2513 }
2514
2515 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2516 if (env_debugserver_log_flags)
2517 {
2518 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2519 debugserver_args.AppendArgument(arg_cstr);
2520 }
Jim Ingham2b2ac8c2012-10-03 22:31:30 +00002521// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
2522// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002523
Greg Claytonb72d0f02011-04-12 05:54:46 +00002524 // We currently send down all arguments, attach pids, or attach
2525 // process names in dedicated GDB server packets, so we don't need
2526 // to pass them as arguments. This is currently because of all the
2527 // things we need to setup prior to launching: the environment,
2528 // current working dir, file actions, etc.
2529#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002530 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002531 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002532 {
Greg Claytona2f74232011-02-24 22:24:29 +00002533 // Terminate the debugserver args so we can now append the inferior args
2534 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002535
Greg Claytona2f74232011-02-24 22:24:29 +00002536 for (int i = 0; inferior_argv[i] != NULL; ++i)
2537 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002538 }
2539 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2540 {
2541 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2542 debugserver_args.AppendArgument (arg_cstr);
2543 }
2544 else if (attach_name && attach_name[0])
2545 {
2546 if (wait_for_launch)
2547 debugserver_args.AppendArgument ("--waitfor");
2548 else
2549 debugserver_args.AppendArgument ("--attach");
2550 debugserver_args.AppendArgument (attach_name);
2551 }
Chris Lattner24943d22010-06-08 16:52:24 +00002552#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002553
2554 ProcessLaunchInfo::FileAction file_action;
2555
2556 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2557 // to "/dev/null" if we run into any problems.
2558 file_action.Close (STDIN_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002559 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002560 file_action.Close (STDOUT_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002561 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002562 file_action.Close (STDERR_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002563 debugserver_launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002564
2565 if (log)
2566 {
2567 StreamString strm;
2568 debugserver_args.Dump (&strm);
2569 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2570 }
2571
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002572 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2573 debugserver_launch_info.SetUserID(process_info.GetUserID());
Greg Clayton1c4642c2011-11-16 05:37:56 +00002574
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002575 error = Host::LaunchProcess(debugserver_launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002576
Greg Claytonb72d0f02011-04-12 05:54:46 +00002577 if (error.Success ())
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002578 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002579 else
Chris Lattner24943d22010-06-08 16:52:24 +00002580 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2581
2582 if (error.Fail() || log)
Greg Claytond9919d32011-12-01 23:28:38 +00002583 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%llu, path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002584 }
2585 else
2586 {
Greg Clayton9c236732011-10-26 00:56:27 +00002587 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002588 }
2589
2590 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2591 StartAsyncThread ();
2592 }
2593 return error;
2594}
2595
2596bool
2597ProcessGDBRemote::MonitorDebugserverProcess
2598(
2599 void *callback_baton,
2600 lldb::pid_t debugserver_pid,
Greg Clayton1c4642c2011-11-16 05:37:56 +00002601 bool exited, // True if the process did exit
Chris Lattner24943d22010-06-08 16:52:24 +00002602 int signo, // Zero for no signal
2603 int exit_status // Exit value of process if signal is zero
2604)
2605{
Greg Clayton1c4642c2011-11-16 05:37:56 +00002606 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2607 // and might not exist anymore, so we need to carefully try to get the
2608 // target for this process first since we have a race condition when
2609 // we are done running between getting the notice that the inferior
2610 // process has died and the debugserver that was debugging this process.
2611 // In our test suite, we are also continually running process after
2612 // process, so we must be very careful to make sure:
2613 // 1 - process object hasn't been deleted already
2614 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner24943d22010-06-08 16:52:24 +00002615
2616 // "debugserver_pid" argument passed in is the process ID for
2617 // debugserver that we are tracking...
Greg Clayton1c4642c2011-11-16 05:37:56 +00002618 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002619
Greg Clayton75ccf502010-08-21 02:22:51 +00002620 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002621
Greg Clayton1c4642c2011-11-16 05:37:56 +00002622 // Get a shared pointer to the target that has a matching process pointer.
2623 // This target could be gone, or the target could already have a new process
2624 // object inside of it
2625 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2626
Greg Clayton72e1c782011-01-22 23:43:18 +00002627 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00002628 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%llu, signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
Greg Clayton72e1c782011-01-22 23:43:18 +00002629
Greg Clayton1c4642c2011-11-16 05:37:56 +00002630 if (target_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002631 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002632 // We found a process in a target that matches, but another thread
2633 // might be in the process of launching a new process that will
2634 // soon replace it, so get a shared pointer to the process so we
2635 // can keep it alive.
2636 ProcessSP process_sp (target_sp->GetProcessSP());
2637 // Now we have a shared pointer to the process that can't go away on us
2638 // so we now make sure it was the same as the one passed in, and also make
2639 // sure that our previous "process *" didn't get deleted and have a new
2640 // "process *" created in its place with the same pointer. To verify this
2641 // we make sure the process has our debugserver process ID. If we pass all
2642 // of these tests, then we are sure that this process is the one we were
2643 // looking for.
2644 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner24943d22010-06-08 16:52:24 +00002645 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002646 // Sleep for a half a second to make sure our inferior process has
2647 // time to set its exit status before we set it incorrectly when
2648 // both the debugserver and the inferior process shut down.
2649 usleep (500000);
2650 // If our process hasn't yet exited, debugserver might have died.
2651 // If the process did exit, the we are reaping it.
2652 const StateType state = process->GetState();
2653
2654 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2655 state != eStateInvalid &&
2656 state != eStateUnloaded &&
2657 state != eStateExited &&
2658 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002659 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002660 char error_str[1024];
2661 if (signo)
2662 {
2663 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2664 if (signal_cstr)
2665 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2666 else
2667 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2668 }
Chris Lattner24943d22010-06-08 16:52:24 +00002669 else
Greg Clayton1c4642c2011-11-16 05:37:56 +00002670 {
2671 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2672 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002673
Greg Clayton1c4642c2011-11-16 05:37:56 +00002674 process->SetExitStatus (-1, error_str);
2675 }
2676 // Debugserver has exited we need to let our ProcessGDBRemote
2677 // know that it no longer has a debugserver instance
2678 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton75ccf502010-08-21 02:22:51 +00002679 }
Chris Lattner24943d22010-06-08 16:52:24 +00002680 }
2681 return true;
2682}
2683
2684void
2685ProcessGDBRemote::KillDebugserverProcess ()
2686{
2687 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2688 {
2689 ::kill (m_debugserver_pid, SIGINT);
2690 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2691 }
2692}
2693
2694void
2695ProcessGDBRemote::Initialize()
2696{
2697 static bool g_initialized = false;
2698
2699 if (g_initialized == false)
2700 {
2701 g_initialized = true;
2702 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2703 GetPluginDescriptionStatic(),
2704 CreateInstance);
2705
2706 Log::Callbacks log_callbacks = {
2707 ProcessGDBRemoteLog::DisableLog,
2708 ProcessGDBRemoteLog::EnableLog,
2709 ProcessGDBRemoteLog::ListLogCategories
2710 };
2711
2712 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2713 }
2714}
2715
2716bool
Chris Lattner24943d22010-06-08 16:52:24 +00002717ProcessGDBRemote::StartAsyncThread ()
2718{
Greg Claytone005f2c2010-11-06 01:53:30 +00002719 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002720
2721 if (log)
2722 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Inghama9488302012-11-01 01:15:33 +00002723
2724 Mutex::Locker start_locker(m_async_thread_state_mutex);
2725 if (m_async_thread_state == eAsyncThreadNotStarted)
2726 {
2727 // Create a thread that watches our internal state and controls which
2728 // events make it to clients (into the DCProcess event queue).
2729 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2730 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2731 {
2732 m_async_thread_state = eAsyncThreadRunning;
2733 return true;
2734 }
2735 else
2736 return false;
2737 }
2738 else
2739 {
2740 // Somebody tried to start the async thread while it was either being started or stopped. If the former, and
2741 // it started up successfully, then say all's well. Otherwise it is an error, since we aren't going to restart it.
2742 if (log)
2743 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
2744 if (m_async_thread_state == eAsyncThreadRunning)
2745 return true;
2746 else
2747 return false;
2748 }
Chris Lattner24943d22010-06-08 16:52:24 +00002749}
2750
2751void
2752ProcessGDBRemote::StopAsyncThread ()
2753{
Greg Claytone005f2c2010-11-06 01:53:30 +00002754 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002755
2756 if (log)
2757 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2758
Jim Inghama9488302012-11-01 01:15:33 +00002759 Mutex::Locker start_locker(m_async_thread_state_mutex);
2760 if (m_async_thread_state == eAsyncThreadRunning)
Chris Lattner24943d22010-06-08 16:52:24 +00002761 {
Jim Inghama9488302012-11-01 01:15:33 +00002762 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2763
2764 // This will shut down the async thread.
2765 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
2766
2767 // Stop the stdio thread
2768 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2769 {
2770 Host::ThreadJoin (m_async_thread, NULL, NULL);
2771 }
2772 m_async_thread_state = eAsyncThreadDone;
2773 }
2774 else
2775 {
2776 if (log)
2777 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
Chris Lattner24943d22010-06-08 16:52:24 +00002778 }
2779}
2780
2781
2782void *
2783ProcessGDBRemote::AsyncThread (void *arg)
2784{
2785 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2786
Greg Claytone005f2c2010-11-06 01:53:30 +00002787 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002788 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002789 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002790
2791 Listener listener ("ProcessGDBRemote::AsyncThread");
2792 EventSP event_sp;
2793 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2794 eBroadcastBitAsyncThreadShouldExit;
2795
2796 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2797 {
Greg Claytona2f74232011-02-24 22:24:29 +00002798 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2799
Chris Lattner24943d22010-06-08 16:52:24 +00002800 bool done = false;
2801 while (!done)
2802 {
2803 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002804 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002805 if (listener.WaitForEvent (NULL, event_sp))
2806 {
2807 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002808 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002809 {
Greg Claytona2f74232011-02-24 22:24:29 +00002810 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002811 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
Chris Lattner24943d22010-06-08 16:52:24 +00002812
Greg Claytona2f74232011-02-24 22:24:29 +00002813 switch (event_type)
2814 {
2815 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002816 {
Greg Claytona2f74232011-02-24 22:24:29 +00002817 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002818
Greg Claytona2f74232011-02-24 22:24:29 +00002819 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002820 {
Greg Claytona2f74232011-02-24 22:24:29 +00002821 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2822 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2823 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002824 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002825
Greg Claytona2f74232011-02-24 22:24:29 +00002826 if (::strstr (continue_cstr, "vAttach") == NULL)
2827 process->SetPrivateState(eStateRunning);
2828 StringExtractorGDBRemote response;
2829 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002830
Greg Clayton67b402c2012-05-16 02:48:06 +00002831 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
2832 // The thread ID list might be contained within the "response", or the stop reply packet that
2833 // caused the stop. So clear it now before we give the stop reply packet to the process
2834 // using the process->SetLastStopPacket()...
2835 process->ClearThreadIDList ();
2836
Greg Claytona2f74232011-02-24 22:24:29 +00002837 switch (stop_state)
2838 {
2839 case eStateStopped:
2840 case eStateCrashed:
2841 case eStateSuspended:
Greg Clayton06709002011-12-06 04:51:14 +00002842 process->SetLastStopPacket (response);
Greg Claytona2f74232011-02-24 22:24:29 +00002843 process->SetPrivateState (stop_state);
2844 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002845
Greg Claytona2f74232011-02-24 22:24:29 +00002846 case eStateExited:
Greg Clayton06709002011-12-06 04:51:14 +00002847 process->SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00002848 process->ClearThreadIDList();
Greg Claytona2f74232011-02-24 22:24:29 +00002849 response.SetFilePos(1);
2850 process->SetExitStatus(response.GetHexU8(), NULL);
2851 done = true;
2852 break;
2853
2854 case eStateInvalid:
2855 process->SetExitStatus(-1, "lost connection");
2856 break;
2857
2858 default:
2859 process->SetPrivateState (stop_state);
2860 break;
2861 }
Chris Lattner24943d22010-06-08 16:52:24 +00002862 }
2863 }
Greg Claytona2f74232011-02-24 22:24:29 +00002864 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002865
Greg Claytona2f74232011-02-24 22:24:29 +00002866 case eBroadcastBitAsyncThreadShouldExit:
2867 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002868 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Claytona2f74232011-02-24 22:24:29 +00002869 done = true;
2870 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002871
Greg Claytona2f74232011-02-24 22:24:29 +00002872 default:
2873 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002874 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
Greg Claytona2f74232011-02-24 22:24:29 +00002875 done = true;
2876 break;
2877 }
2878 }
2879 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2880 {
2881 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2882 {
2883 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002884 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002885 }
Chris Lattner24943d22010-06-08 16:52:24 +00002886 }
2887 }
2888 else
2889 {
2890 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002891 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002892 done = true;
2893 }
2894 }
2895 }
2896
2897 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002898 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002899
2900 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2901 return NULL;
2902}
2903
Chris Lattner24943d22010-06-08 16:52:24 +00002904const char *
2905ProcessGDBRemote::GetDispatchQueueNameForThread
2906(
2907 addr_t thread_dispatch_qaddr,
2908 std::string &dispatch_queue_name
2909)
2910{
2911 dispatch_queue_name.clear();
2912 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2913 {
2914 // Cache the dispatch_queue_offsets_addr value so we don't always have
2915 // to look it up
2916 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2917 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002918 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2919 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton444fe992012-02-26 05:51:37 +00002920 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false));
2921 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002922 if (module_sp)
2923 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2924
2925 if (dispatch_queue_offsets_symbol == NULL)
2926 {
Greg Clayton444fe992012-02-26 05:51:37 +00002927 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false));
2928 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_module_spec);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002929 if (module_sp)
2930 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2931 }
Chris Lattner24943d22010-06-08 16:52:24 +00002932 if (dispatch_queue_offsets_symbol)
Greg Clayton0c31d3d2012-03-07 21:03:09 +00002933 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002934
2935 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2936 return NULL;
2937 }
2938
2939 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002940 DataExtractor data (memory_buffer,
2941 sizeof(memory_buffer),
2942 m_target.GetArchitecture().GetByteOrder(),
2943 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002944
2945 // Excerpt from src/queue_private.h
2946 struct dispatch_queue_offsets_s
2947 {
2948 uint16_t dqo_version;
Jason Molenda9704ca22012-11-10 06:54:30 +00002949 uint16_t dqo_label; // in version 1-3, offset to string; in version 4+, offset to a pointer to a string
2950 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 +00002951 } dispatch_queue_offsets;
2952
2953
2954 Error error;
2955 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2956 {
2957 uint32_t data_offset = 0;
2958 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2959 {
2960 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2961 {
2962 data_offset = 0;
2963 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
Jason Molenda9704ca22012-11-10 06:54:30 +00002964 if (dispatch_queue_offsets.dqo_version >= 4)
2965 {
2966 // libdispatch versions 4+, pointer to dispatch name is in the
2967 // queue structure.
2968 lldb::addr_t pointer_to_label_address = queue_addr + dispatch_queue_offsets.dqo_label;
2969 if (ReadMemory (pointer_to_label_address, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2970 {
2971 data_offset = 0;
2972 lldb::addr_t label_addr = data.GetAddress(&data_offset);
2973 ReadCStringFromMemory (label_addr, dispatch_queue_name, error);
2974 }
2975 }
2976 else
2977 {
2978 // libdispatch versions 1-3, dispatch name is a fixed width char array
2979 // in the queue structure.
2980 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2981 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2982 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2983 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2984 dispatch_queue_name.erase (bytes_read);
2985 }
Chris Lattner24943d22010-06-08 16:52:24 +00002986 }
2987 }
2988 }
2989 }
2990 if (dispatch_queue_name.empty())
2991 return NULL;
2992 return dispatch_queue_name.c_str();
2993}
2994
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002995//uint32_t
2996//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2997//{
2998// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2999// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
3000// if (m_local_debugserver)
3001// {
3002// return Host::ListProcessesMatchingName (name, matches, pids);
3003// }
3004// else
3005// {
3006// // FIXME: Implement talking to the remote debugserver.
3007// return 0;
3008// }
3009//
3010//}
3011//
Jim Ingham55e01d82011-01-22 01:33:44 +00003012bool
3013ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
3014 lldb_private::StoppointCallbackContext *context,
3015 lldb::user_id_t break_id,
3016 lldb::user_id_t break_loc_id)
3017{
3018 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3019 // run so I can stop it if that's what I want to do.
3020 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
3021 if (log)
3022 log->Printf("Hit New Thread Notification breakpoint.");
3023 return false;
3024}
3025
3026
3027bool
3028ProcessGDBRemote::StartNoticingNewThreads()
3029{
Jim Ingham55e01d82011-01-22 01:33:44 +00003030 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003031 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00003032 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003033 if (log && log->GetVerbose())
3034 log->Printf("Enabled noticing new thread breakpoint.");
3035 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham55e01d82011-01-22 01:33:44 +00003036 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003037 else
Jim Ingham55e01d82011-01-22 01:33:44 +00003038 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003039 PlatformSP platform_sp (m_target.GetPlatform());
3040 if (platform_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00003041 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003042 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3043 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00003044 {
Jim Ingham6bb73372011-10-15 00:21:37 +00003045 if (log && log->GetVerbose())
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003046 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3047 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham55e01d82011-01-22 01:33:44 +00003048 }
3049 else
3050 {
3051 if (log)
3052 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00003053 }
3054 }
3055 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003056 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham55e01d82011-01-22 01:33:44 +00003057}
3058
3059bool
3060ProcessGDBRemote::StopNoticingNewThreads()
3061{
Jim Inghamff276fe2011-02-08 05:19:01 +00003062 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham6bb73372011-10-15 00:21:37 +00003063 if (log && log->GetVerbose())
Jim Inghamff276fe2011-02-08 05:19:01 +00003064 log->Printf ("Disabling new thread notification breakpoint.");
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003065
3066 if (m_thread_create_bp_sp)
3067 m_thread_create_bp_sp->SetEnabled(false);
3068
Jim Ingham55e01d82011-01-22 01:33:44 +00003069 return true;
3070}
3071
Jason Molendab46937c2012-10-03 01:29:34 +00003072lldb_private::DynamicLoader *
3073ProcessGDBRemote::GetDynamicLoader ()
3074{
3075 if (m_dyld_ap.get() == NULL)
3076 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, m_dyld_plugin_name.empty() ? NULL : m_dyld_plugin_name.c_str()));
3077 return m_dyld_ap.get();
3078}
Jim Ingham55e01d82011-01-22 01:33:44 +00003079
Greg Clayton13193d52012-10-13 02:07:45 +00003080
Greg Claytonb8596392012-10-15 22:42:16 +00003081class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton13193d52012-10-13 02:07:45 +00003082{
3083private:
3084
3085public:
Greg Claytonb8596392012-10-15 22:42:16 +00003086 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton13193d52012-10-13 02:07:45 +00003087 CommandObjectParsed (interpreter,
Greg Claytonb8596392012-10-15 22:42:16 +00003088 "process plugin packet history",
3089 "Dumps the packet history buffer. ",
Greg Clayton13193d52012-10-13 02:07:45 +00003090 NULL)
3091 {
3092 }
3093
Greg Claytonb8596392012-10-15 22:42:16 +00003094 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton13193d52012-10-13 02:07:45 +00003095 {
3096 }
3097
3098 bool
3099 DoExecute (Args& command, CommandReturnObject &result)
3100 {
Greg Claytonb8596392012-10-15 22:42:16 +00003101 const size_t argc = command.GetArgumentCount();
3102 if (argc == 0)
3103 {
3104 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3105 if (process)
3106 {
3107 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
3108 result.SetStatus (eReturnStatusSuccessFinishResult);
3109 return true;
3110 }
3111 }
3112 else
3113 {
3114 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
3115 }
3116 result.SetStatus (eReturnStatusFailed);
3117 return false;
3118 }
3119};
3120
3121class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
3122{
3123private:
3124
3125public:
3126 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
3127 CommandObjectParsed (interpreter,
3128 "process plugin packet send",
3129 "Send a custom packet through the GDB remote protocol and print the answer. "
3130 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
3131 NULL)
3132 {
3133 }
3134
3135 ~CommandObjectProcessGDBRemotePacketSend ()
3136 {
3137 }
3138
3139 bool
3140 DoExecute (Args& command, CommandReturnObject &result)
3141 {
3142 const size_t argc = command.GetArgumentCount();
3143 if (argc == 0)
3144 {
3145 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
3146 result.SetStatus (eReturnStatusFailed);
3147 return false;
3148 }
3149
3150 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3151 if (process)
3152 {
3153 const StateType state = process->GetState();
3154
3155 if (StateIsStoppedState (state, true))
3156 {
3157 for (size_t i=0; i<argc; ++ i)
3158 {
3159 const char *packet_cstr = command.GetArgumentAtIndex(0);
3160 bool send_async = false;
3161 StringExtractorGDBRemote response;
3162 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3163 result.SetStatus (eReturnStatusSuccessFinishResult);
3164 Stream &output_strm = result.GetOutputStream();
3165 output_strm.Printf (" packet: %s\n", packet_cstr);
3166 const std::string &response_str = response.GetStringRef();
3167 if (response_str.empty())
3168 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3169 else
3170 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
3171 }
3172 }
3173 else
3174 {
3175 result.AppendErrorWithFormat ("process must be stopped in order to send GDB remote packets, state is %s", StateAsCString (state));
3176 result.SetStatus (eReturnStatusFailed);
3177 return false;
3178 }
3179
3180 }
Greg Clayton13193d52012-10-13 02:07:45 +00003181 return true;
3182 }
3183};
3184
Greg Claytonb8596392012-10-15 22:42:16 +00003185class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
3186{
3187private:
3188
3189public:
3190 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
3191 CommandObjectMultiword (interpreter,
3192 "process plugin packet",
3193 "Commands that deal with GDB remote packets.",
3194 NULL)
3195 {
3196 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
3197 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
3198 }
3199
3200 ~CommandObjectProcessGDBRemotePacket ()
3201 {
3202 }
3203};
Greg Clayton13193d52012-10-13 02:07:45 +00003204
3205class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
3206{
3207public:
3208 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
3209 CommandObjectMultiword (interpreter,
3210 "process plugin",
3211 "A set of commands for operating on a ProcessGDBRemote process.",
3212 "process plugin <subcommand> [<subcommand-options>]")
3213 {
3214 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
3215 }
3216
3217 ~CommandObjectMultiwordProcessGDBRemote ()
3218 {
3219 }
3220};
3221
Greg Clayton13193d52012-10-13 02:07:45 +00003222CommandObject *
3223ProcessGDBRemote::GetPluginCommandObject()
3224{
3225 if (!m_command_sp)
3226 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
3227 return m_command_sp.get();
3228}