blob: b00c4c95a56dc4edab32d6d29ab282750d9fb4d8 [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
Daniel Malead891f9b2012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
11
Chris Lattner24943d22010-06-08 16:52:24 +000012// C Includes
13#include <errno.h>
Chris Lattner24943d22010-06-08 16:52:24 +000014#include <spawn.h>
Stephen Wilson50daf772011-03-25 18:16:28 +000015#include <stdlib.h>
Sean Callanan483d00a2012-07-19 18:07:36 +000016#include <netinet/in.h>
Greg Clayton989816b2011-05-14 01:50:35 +000017#include <sys/mman.h> // for mmap
Chris Lattner24943d22010-06-08 16:52:24 +000018#include <sys/stat.h>
Greg Clayton989816b2011-05-14 01:50:35 +000019#include <sys/types.h>
Stephen Wilson60f19d52011-03-30 00:12:40 +000020#include <time.h>
Chris Lattner24943d22010-06-08 16:52:24 +000021
22// C++ Includes
23#include <algorithm>
24#include <map>
25
26// Other libraries and framework includes
27
Johnny Chenecd4feb2011-10-14 00:42:25 +000028#include "lldb/Breakpoint/Watchpoint.h"
Jim Ingham84cdc152010-06-15 19:49:27 +000029#include "lldb/Interpreter/Args.h"
Chris Lattner24943d22010-06-08 16:52:24 +000030#include "lldb/Core/ArchSpec.h"
31#include "lldb/Core/Debugger.h"
32#include "lldb/Core/ConnectionFileDescriptor.h"
Greg Clayton5f54ac32011-02-08 05:05:52 +000033#include "lldb/Host/FileSpec.h"
Chris Lattner24943d22010-06-08 16:52:24 +000034#include "lldb/Core/InputReader.h"
35#include "lldb/Core/Module.h"
Greg Clayton49ce8962012-08-29 21:13:06 +000036#include "lldb/Core/ModuleSpec.h"
Chris Lattner24943d22010-06-08 16:52:24 +000037#include "lldb/Core/PluginManager.h"
38#include "lldb/Core/State.h"
Greg Clayton33559462012-04-13 21:24:18 +000039#include "lldb/Core/StreamFile.h"
Chris Lattner24943d22010-06-08 16:52:24 +000040#include "lldb/Core/StreamString.h"
41#include "lldb/Core/Timer.h"
Greg Clayton2f085c62011-05-15 01:25:55 +000042#include "lldb/Core/Value.h"
Jason Molendab0e3c7c2012-09-29 08:03:33 +000043#include "lldb/Host/Symbols.h"
Chris Lattner24943d22010-06-08 16:52:24 +000044#include "lldb/Host/TimeValue.h"
Greg Claytonb8596392012-10-15 22:42:16 +000045#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton307c7fd2012-10-19 22:22:57 +000046#include "lldb/Interpreter/CommandObject.h"
47#include "lldb/Interpreter/CommandObjectMultiword.h"
Greg Claytonb8596392012-10-15 22:42:16 +000048#include "lldb/Interpreter/CommandReturnObject.h"
Chris Lattner24943d22010-06-08 16:52:24 +000049#include "lldb/Symbol/ObjectFile.h"
50#include "lldb/Target/DynamicLoader.h"
51#include "lldb/Target/Target.h"
52#include "lldb/Target/TargetList.h"
Greg Clayton989816b2011-05-14 01:50:35 +000053#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molendadea5ea72010-06-09 21:28:42 +000054#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner24943d22010-06-08 16:52:24 +000055
56// Project includes
57#include "lldb/Host/Host.h"
Peter Collingbourne4d623e82011-06-03 20:40:38 +000058#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Jason Molenda3aeb2862012-07-25 03:40:06 +000059#include "Plugins/Process/Utility/StopInfoMachException.h"
Jim Ingham06b84492012-07-04 00:35:43 +000060#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
Greg Clayton54e7afa2010-07-09 20:39:50 +000061#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner24943d22010-06-08 16:52:24 +000062#include "GDBRemoteRegisterContext.h"
63#include "ProcessGDBRemote.h"
64#include "ProcessGDBRemoteLog.h"
65#include "ThreadGDBRemote.h"
Greg Clayton643ee732010-08-04 01:40:35 +000066
Jason Molendab46937c2012-10-03 01:29:34 +000067#include "Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.h"
68
Greg Clayton451fa822012-04-09 22:46:21 +000069namespace lldb
70{
71 // Provide a function that can easily dump the packet history if we know a
72 // ProcessGDBRemote * value (which we can get from logs or from debugging).
73 // We need the function in the lldb namespace so it makes it into the final
74 // executable since the LLDB shared library only exports stuff in the lldb
75 // namespace. This allows you to attach with a debugger and call this
76 // function and get the packet history dumped to a file.
77 void
78 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
79 {
Greg Clayton33559462012-04-13 21:24:18 +000080 lldb_private::StreamFile strm;
81 lldb_private::Error error (strm.GetFile().Open(path, lldb_private::File::eOpenOptionWrite | lldb_private::File::eOpenOptionCanCreate));
82 if (error.Success())
83 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
Greg Clayton451fa822012-04-09 22:46:21 +000084 }
Filipe Cabecinhas021086a2012-05-23 16:27:09 +000085}
Chris Lattner24943d22010-06-08 16:52:24 +000086
Chris Lattner24943d22010-06-08 16:52:24 +000087
88#define DEBUGSERVER_BASENAME "debugserver"
89using namespace lldb;
90using namespace lldb_private;
91
Jim Inghamf9600482011-03-29 21:45:47 +000092static bool rand_initialized = false;
93
Sean Callanan483d00a2012-07-19 18:07:36 +000094// TODO Randomly assigning a port is unsafe. We should get an unused
95// ephemeral port from the kernel and make sure we reserve it before passing
96// it to debugserver.
97
98#if defined (__APPLE__)
99#define LOW_PORT (IPPORT_RESERVED)
100#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
101#else
102#define LOW_PORT (1024u)
103#define HIGH_PORT (49151u)
104#endif
105
Chris Lattner24943d22010-06-08 16:52:24 +0000106static inline uint16_t
107get_random_port ()
108{
Jim Inghamf9600482011-03-29 21:45:47 +0000109 if (!rand_initialized)
110 {
Stephen Wilson60f19d52011-03-30 00:12:40 +0000111 time_t seed = time(NULL);
112
Jim Inghamf9600482011-03-29 21:45:47 +0000113 rand_initialized = true;
Stephen Wilson60f19d52011-03-30 00:12:40 +0000114 srand(seed);
Jim Inghamf9600482011-03-29 21:45:47 +0000115 }
Sean Callanan483d00a2012-07-19 18:07:36 +0000116 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
Chris Lattner24943d22010-06-08 16:52:24 +0000117}
118
119
120const char *
121ProcessGDBRemote::GetPluginNameStatic()
122{
Greg Claytonb1888f22011-03-19 01:12:21 +0000123 return "gdb-remote";
Chris Lattner24943d22010-06-08 16:52:24 +0000124}
125
126const char *
127ProcessGDBRemote::GetPluginDescriptionStatic()
128{
129 return "GDB Remote protocol based debugging plug-in.";
130}
131
132void
133ProcessGDBRemote::Terminate()
134{
135 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
136}
137
138
Greg Clayton46c9a352012-02-09 06:16:32 +0000139lldb::ProcessSP
140ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner24943d22010-06-08 16:52:24 +0000141{
Greg Clayton46c9a352012-02-09 06:16:32 +0000142 lldb::ProcessSP process_sp;
143 if (crash_file_path == NULL)
144 process_sp.reset (new ProcessGDBRemote (target, listener));
145 return process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000146}
147
148bool
Greg Clayton8d2ea282011-07-17 20:36:25 +0000149ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
Chris Lattner24943d22010-06-08 16:52:24 +0000150{
Greg Clayton61ddf562011-10-21 21:41:45 +0000151 if (plugin_specified_by_name)
152 return true;
153
Chris Lattner24943d22010-06-08 16:52:24 +0000154 // For now we are just making sure the file exists for a given module
Greg Clayton5beb99d2011-08-11 02:48:45 +0000155 Module *exe_module = target.GetExecutableModulePointer();
156 if (exe_module)
Greg Clayton46c9a352012-02-09 06:16:32 +0000157 {
158 ObjectFile *exe_objfile = exe_module->GetObjectFile();
159 // We can't debug core files...
160 switch (exe_objfile->GetType())
161 {
162 case ObjectFile::eTypeInvalid:
163 case ObjectFile::eTypeCoreFile:
164 case ObjectFile::eTypeDebugInfo:
165 case ObjectFile::eTypeObjectFile:
166 case ObjectFile::eTypeSharedLibrary:
167 case ObjectFile::eTypeStubLibrary:
168 return false;
169 case ObjectFile::eTypeExecutable:
170 case ObjectFile::eTypeDynamicLinker:
171 case ObjectFile::eTypeUnknown:
172 break;
173 }
Greg Clayton5beb99d2011-08-11 02:48:45 +0000174 return exe_module->GetFileSpec().Exists();
Greg Clayton46c9a352012-02-09 06:16:32 +0000175 }
Jim Ingham7508e732010-08-09 23:31:02 +0000176 // However, if there is no executable module, we return true since we might be preparing to attach.
177 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000178}
179
180//----------------------------------------------------------------------
181// ProcessGDBRemote constructor
182//----------------------------------------------------------------------
183ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
184 Process (target, listener),
Chris Lattner24943d22010-06-08 16:52:24 +0000185 m_flags (0),
Greg Claytonb72d0f02011-04-12 05:54:46 +0000186 m_gdb_comm(false),
Chris Lattner24943d22010-06-08 16:52:24 +0000187 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000188 m_last_stop_packet (),
Greg Clayton06709002011-12-06 04:51:14 +0000189 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
Chris Lattner24943d22010-06-08 16:52:24 +0000190 m_register_info (),
Jim Ingham5a15e692012-02-16 06:50:00 +0000191 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
Chris Lattner24943d22010-06-08 16:52:24 +0000192 m_async_thread (LLDB_INVALID_HOST_THREAD),
Jim Inghama9488302012-11-01 01:15:33 +0000193 m_async_thread_state(eAsyncThreadNotStarted),
194 m_async_thread_state_mutex(Mutex::eMutexTypeRecursive),
Greg Clayton5a9f85c2012-04-10 02:25:43 +0000195 m_thread_ids (),
Greg Claytonc1f45872011-02-12 06:28:37 +0000196 m_continue_c_tids (),
197 m_continue_C_tids (),
198 m_continue_s_tids (),
199 m_continue_S_tids (),
Chris Lattner24943d22010-06-08 16:52:24 +0000200 m_dispatch_queue_offsets_addr (LLDB_INVALID_ADDRESS),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000201 m_max_memory_size (512),
Greg Claytonbd5c23d2012-05-15 02:33:01 +0000202 m_addr_to_mmap_size (),
203 m_thread_create_bp_sp (),
Jim Ingham06b84492012-07-04 00:35:43 +0000204 m_waiting_for_attach (false),
Jason Molendab46937c2012-10-03 01:29:34 +0000205 m_destroy_tried_resuming (false),
206 m_dyld_plugin_name(),
Greg Clayton13193d52012-10-13 02:07:45 +0000207 m_kernel_load_addr (LLDB_INVALID_ADDRESS),
208 m_command_sp ()
Chris Lattner24943d22010-06-08 16:52:24 +0000209{
Greg Claytonff39f742011-04-01 00:29:43 +0000210 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
211 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +0000212 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Chris Lattner24943d22010-06-08 16:52:24 +0000213}
214
215//----------------------------------------------------------------------
216// Destructor
217//----------------------------------------------------------------------
218ProcessGDBRemote::~ProcessGDBRemote()
219{
220 // m_mach_process.UnregisterNotificationCallbacks (this);
221 Clear();
Greg Clayton2f57db02011-10-01 00:45:15 +0000222 // We need to call finalize on the process before destroying ourselves
223 // to make sure all of the broadcaster cleanup goes as planned. If we
224 // destruct this class, then Process::~Process() might have problems
225 // trying to fully destroy the broadcaster.
226 Finalize();
Jim Inghama9488302012-11-01 01:15:33 +0000227
228 // The general Finalize is going to try to destroy the process and that SHOULD
229 // shut down the async thread. However, if we don't kill it it will get stranded and
230 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
231 StopAsyncThread();
232 KillDebugserverProcess();
Chris Lattner24943d22010-06-08 16:52:24 +0000233}
234
235//----------------------------------------------------------------------
236// PluginInterface
237//----------------------------------------------------------------------
238const char *
239ProcessGDBRemote::GetPluginName()
240{
241 return "Process debugging plug-in that uses the GDB remote protocol";
242}
243
244const char *
245ProcessGDBRemote::GetShortPluginName()
246{
247 return GetPluginNameStatic();
248}
249
250uint32_t
251ProcessGDBRemote::GetPluginVersion()
252{
253 return 1;
254}
255
256void
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000257ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +0000258{
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000259 if (!force && m_register_info.GetNumRegisters() > 0)
260 return;
261
262 char packet[128];
Chris Lattner24943d22010-06-08 16:52:24 +0000263 m_register_info.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000264 uint32_t reg_offset = 0;
265 uint32_t reg_num = 0;
Greg Clayton4a379b12012-07-17 03:23:13 +0000266 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Greg Clayton61d043b2011-03-22 04:00:09 +0000267 response_type == StringExtractorGDBRemote::eResponse;
268 ++reg_num)
Chris Lattner24943d22010-06-08 16:52:24 +0000269 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000270 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
271 assert (packet_len < sizeof(packet));
Chris Lattner24943d22010-06-08 16:52:24 +0000272 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000273 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner24943d22010-06-08 16:52:24 +0000274 {
Greg Clayton61d043b2011-03-22 04:00:09 +0000275 response_type = response.GetResponseType();
276 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner24943d22010-06-08 16:52:24 +0000277 {
278 std::string name;
279 std::string value;
280 ConstString reg_name;
281 ConstString alt_name;
282 ConstString set_name;
283 RegisterInfo reg_info = { NULL, // Name
284 NULL, // Alt name
285 0, // byte size
286 reg_offset, // offset
287 eEncodingUint, // encoding
288 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000289 {
290 LLDB_INVALID_REGNUM, // GCC reg num
291 LLDB_INVALID_REGNUM, // DWARF reg num
292 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000293 reg_num, // GDB reg num
294 reg_num // native register number
Greg Claytoncd330422012-02-29 19:27:27 +0000295 },
296 NULL,
297 NULL
Chris Lattner24943d22010-06-08 16:52:24 +0000298 };
299
300 while (response.GetNameColonValue(name, value))
301 {
302 if (name.compare("name") == 0)
303 {
304 reg_name.SetCString(value.c_str());
305 }
306 else if (name.compare("alt-name") == 0)
307 {
308 alt_name.SetCString(value.c_str());
309 }
310 else if (name.compare("bitsize") == 0)
311 {
312 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
313 }
314 else if (name.compare("offset") == 0)
315 {
316 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000317 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000318 {
319 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000320 }
321 }
322 else if (name.compare("encoding") == 0)
323 {
Greg Clayton88b980b2012-08-24 01:42:50 +0000324 const Encoding encoding = Args::StringToEncoding (value.c_str());
325 if (encoding != eEncodingInvalid)
326 reg_info.encoding = encoding;
Chris Lattner24943d22010-06-08 16:52:24 +0000327 }
328 else if (name.compare("format") == 0)
329 {
Greg Clayton88b980b2012-08-24 01:42:50 +0000330 Format format = eFormatInvalid;
331 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
332 reg_info.format = format;
333 else if (value.compare("binary") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +0000334 reg_info.format = eFormatBinary;
335 else if (value.compare("decimal") == 0)
336 reg_info.format = eFormatDecimal;
337 else if (value.compare("hex") == 0)
338 reg_info.format = eFormatHex;
339 else if (value.compare("float") == 0)
340 reg_info.format = eFormatFloat;
341 else if (value.compare("vector-sint8") == 0)
342 reg_info.format = eFormatVectorOfSInt8;
343 else if (value.compare("vector-uint8") == 0)
344 reg_info.format = eFormatVectorOfUInt8;
345 else if (value.compare("vector-sint16") == 0)
346 reg_info.format = eFormatVectorOfSInt16;
347 else if (value.compare("vector-uint16") == 0)
348 reg_info.format = eFormatVectorOfUInt16;
349 else if (value.compare("vector-sint32") == 0)
350 reg_info.format = eFormatVectorOfSInt32;
351 else if (value.compare("vector-uint32") == 0)
352 reg_info.format = eFormatVectorOfUInt32;
353 else if (value.compare("vector-float32") == 0)
354 reg_info.format = eFormatVectorOfFloat32;
355 else if (value.compare("vector-uint128") == 0)
356 reg_info.format = eFormatVectorOfUInt128;
357 }
358 else if (name.compare("set") == 0)
359 {
360 set_name.SetCString(value.c_str());
361 }
362 else if (name.compare("gcc") == 0)
363 {
364 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
365 }
366 else if (name.compare("dwarf") == 0)
367 {
368 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
369 }
370 else if (name.compare("generic") == 0)
371 {
Greg Clayton88b980b2012-08-24 01:42:50 +0000372 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000373 }
374 }
375
Jason Molenda53d96862010-06-11 23:44:18 +0000376 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000377 assert (reg_info.byte_size != 0);
378 reg_offset += reg_info.byte_size;
379 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
380 }
381 }
382 else
383 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000384 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000385 }
386 }
387
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000388 // We didn't get anything if the accumulated reg_num is zero. See if we are
389 // debugging ARM and fill with a hard coded register set until we can get an
390 // updated debugserver down on the devices.
391 // On the other hand, if the accumulated reg_num is positive, see if we can
392 // add composite registers to the existing primordial ones.
393 bool from_scratch = (reg_num == 0);
394
395 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Jason Molendafe555672012-12-19 02:54:03 +0000396 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
397 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
398
399 // Use the process' architecture instead of the host arch, if available
400 ArchSpec remote_arch;
401 if (remote_process_arch.IsValid ())
402 remote_arch = remote_process_arch;
403 else
404 remote_arch = remote_host_arch;
405
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000406 if (!target_arch.IsValid())
Chris Lattner24943d22010-06-08 16:52:24 +0000407 {
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000408 if (remote_arch.IsValid()
409 && remote_arch.GetMachine() == llvm::Triple::arm
410 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
411 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner24943d22010-06-08 16:52:24 +0000412 }
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000413 else if (target_arch.GetMachine() == llvm::Triple::arm)
414 {
415 m_register_info.HardcodeARMRegisters(from_scratch);
416 }
417
Johnny Chend2e30662012-05-22 00:57:05 +0000418 // Add some convenience registers (eax, ebx, ecx, edx, esi, edi, ebp, esp) to x86_64.
Johnny Chenbe315a62012-06-08 19:06:28 +0000419 if ((target_arch.IsValid() && target_arch.GetMachine() == llvm::Triple::x86_64)
420 || (remote_arch.IsValid() && remote_arch.GetMachine() == llvm::Triple::x86_64))
Johnny Chend2e30662012-05-22 00:57:05 +0000421 m_register_info.Addx86_64ConvenienceRegisters();
422
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000423 // At this point, we can finalize our register info.
Chris Lattner24943d22010-06-08 16:52:24 +0000424 m_register_info.Finalize ();
425}
426
427Error
428ProcessGDBRemote::WillLaunch (Module* module)
429{
430 return WillLaunchOrAttach ();
431}
432
433Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000434ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000435{
436 return WillLaunchOrAttach ();
437}
438
439Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000440ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000441{
442 return WillLaunchOrAttach ();
443}
444
445Error
Jason Molendafac2e622012-09-29 04:02:01 +0000446ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytone71e2582011-02-04 01:58:07 +0000447{
448 Error error (WillLaunchOrAttach ());
449
450 if (error.Fail())
451 return error;
452
Greg Clayton180546b2011-04-30 01:09:13 +0000453 error = ConnectToDebugserver (remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000454
455 if (error.Fail())
456 return error;
457 StartAsyncThread ();
458
Jason Molendab46937c2012-10-03 01:29:34 +0000459 CheckForKernel (strm);
Jason Molendafac2e622012-09-29 04:02:01 +0000460
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000461 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000462 if (pid == LLDB_INVALID_PROCESS_ID)
463 {
464 // We don't have a valid process ID, so note that we are connected
465 // and could now request to launch or attach, or get remote process
466 // listings...
467 SetPrivateState (eStateConnected);
468 }
469 else
470 {
471 // We have a valid process
472 SetID (pid);
Greg Clayton37f962e2011-08-22 02:49:39 +0000473 GetThreadList();
Greg Clayton261a18b2011-06-02 22:22:38 +0000474 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000475 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000476 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytone71e2582011-02-04 01:58:07 +0000477 if (state == eStateStopped)
478 {
479 SetPrivateState (state);
480 }
481 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000482 error.SetErrorStringWithFormat ("Process %" PRIu64 " was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
Greg Claytone71e2582011-02-04 01:58:07 +0000483 }
484 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000485 error.SetErrorStringWithFormat ("Process %" PRIu64 " was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000486 }
Jason Molendacb740b32012-05-03 22:37:30 +0000487
488 if (error.Success()
489 && !GetTarget().GetArchitecture().IsValid()
490 && m_gdb_comm.GetHostArchitecture().IsValid())
491 {
Jason Molendafe555672012-12-19 02:54:03 +0000492 // Prefer the *process'* architecture over that of the *host*, if available.
493 if (m_gdb_comm.GetProcessArchitecture().IsValid())
494 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
495 else
496 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molendacb740b32012-05-03 22:37:30 +0000497 }
498
Greg Claytone71e2582011-02-04 01:58:07 +0000499 return error;
500}
501
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000502// When we are establishing a connection to a remote system and we have no executable specified,
503// or the executable is a kernel, we may be looking at a KASLR situation (where the kernel has been
504// slid in memory.)
505//
Jason Molendab46937c2012-10-03 01:29:34 +0000506// This function tries to locate the kernel in memory if this is possibly a kernel debug session.
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000507//
Jason Molendab46937c2012-10-03 01:29:34 +0000508// If a kernel is found, return the address of the kernel in GetImageInfoAddress() -- the
509// DynamicLoaderDarwinKernel plugin uses this address as the kernel load address and will load the
510// binary, if needed, along with all the kexts.
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000511
512void
Jason Molendab46937c2012-10-03 01:29:34 +0000513ProcessGDBRemote::CheckForKernel (Stream *strm)
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000514{
515 // early return if this isn't an "unknown" system (kernel debugging doesn't have a system type)
516 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
517 if (!gdb_remote_arch.IsValid() || gdb_remote_arch.GetTriple().getVendor() != llvm::Triple::UnknownVendor)
518 return;
519
520 Module *exe_module = GetTarget().GetExecutableModulePointer();
521 ObjectFile *exe_objfile = NULL;
522 if (exe_module)
523 exe_objfile = exe_module->GetObjectFile();
524
525 // early return if we have an executable and it is not a kernel--this is very unlikely to be a kernel debug session.
526 if (exe_objfile
527 && (exe_objfile->GetType() != ObjectFile::eTypeExecutable
528 || exe_objfile->GetStrata() != ObjectFile::eStrataKernel))
529 return;
530
531 // See if the kernel is in memory at the File address (slide == 0) -- no work needed, if so.
532 if (exe_objfile && exe_objfile->GetHeaderAddress().IsValid())
533 {
534 ModuleSP memory_module_sp;
535 memory_module_sp = ReadModuleFromMemory (exe_module->GetFileSpec(), exe_objfile->GetHeaderAddress().GetFileAddress(), false, false);
536 if (memory_module_sp.get()
537 && memory_module_sp->GetUUID().IsValid()
538 && memory_module_sp->GetUUID() == exe_module->GetUUID())
539 {
Jason Molendab46937c2012-10-03 01:29:34 +0000540 m_kernel_load_addr = exe_objfile->GetHeaderAddress().GetFileAddress();
541 m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
Jason Molendad6b81222012-10-06 02:02:26 +0000542 SetCanJIT(false);
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000543 return;
544 }
545 }
546
547 // See if the kernel's load address is stored in the kernel's low globals page; this is
548 // done when a debug boot-arg has been set.
549
550 Error error;
551 uint8_t buf[24];
552 ModuleSP memory_module_sp;
553 addr_t kernel_addr = LLDB_INVALID_ADDRESS;
554
555 // First try the 32-bit
556 if (memory_module_sp.get() == NULL)
557 {
558 DataExtractor data4 (buf, sizeof(buf), gdb_remote_arch.GetByteOrder(), 4);
559 if (DoReadMemory (0xffff0110, buf, 4, error) == 4)
560 {
561 uint32_t offset = 0;
562 kernel_addr = data4.GetU32(&offset);
563 memory_module_sp = ReadModuleFromMemory (FileSpec("mach_kernel", false), kernel_addr, false, false);
564 if (!memory_module_sp.get()
565 || !memory_module_sp->GetUUID().IsValid()
566 || memory_module_sp->GetObjectFile() == NULL
567 || memory_module_sp->GetObjectFile()->GetType() != ObjectFile::eTypeExecutable
568 || memory_module_sp->GetObjectFile()->GetStrata() != ObjectFile::eStrataKernel)
569 {
570 memory_module_sp.reset();
571 }
572 }
573 }
574
575 // Now try the 64-bit location
576 if (memory_module_sp.get() == NULL)
577 {
578 DataExtractor data8 (buf, sizeof(buf), gdb_remote_arch.GetByteOrder(), 8);
579 if (DoReadMemory (0xffffff8000002010ULL, buf, 8, error) == 8)
580 {
581 uint32_t offset = 0;
Jason Molendac557e7d2012-12-01 04:46:58 +0000582 kernel_addr = data8.GetU64(&offset);
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000583 memory_module_sp = ReadModuleFromMemory (FileSpec("mach_kernel", false), kernel_addr, false, false);
584 if (!memory_module_sp.get()
585 || !memory_module_sp->GetUUID().IsValid()
586 || memory_module_sp->GetObjectFile() == NULL
587 || memory_module_sp->GetObjectFile()->GetType() != ObjectFile::eTypeExecutable
588 || memory_module_sp->GetObjectFile()->GetStrata() != ObjectFile::eStrataKernel)
589 {
590 memory_module_sp.reset();
591 }
592 }
593 }
594
Jason Molendab46937c2012-10-03 01:29:34 +0000595 if (memory_module_sp.get()
596 && memory_module_sp->GetArchitecture().IsValid()
597 && memory_module_sp->GetArchitecture().GetTriple().getVendor() == llvm::Triple::Apple)
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000598 {
Jason Molendab46937c2012-10-03 01:29:34 +0000599 m_kernel_load_addr = kernel_addr;
600 m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
Jason Molendad6b81222012-10-06 02:02:26 +0000601 SetCanJIT(false);
Jason Molendab46937c2012-10-03 01:29:34 +0000602 return;
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000603 }
604}
605
Greg Claytone71e2582011-02-04 01:58:07 +0000606Error
Chris Lattner24943d22010-06-08 16:52:24 +0000607ProcessGDBRemote::WillLaunchOrAttach ()
608{
609 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000610 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000611 return error;
612}
613
614//----------------------------------------------------------------------
615// Process Control
616//----------------------------------------------------------------------
617Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000618ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000619{
Greg Clayton4b407112010-09-30 21:49:03 +0000620 Error error;
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000621
622 uint32_t launch_flags = launch_info.GetFlags().Get();
623 const char *stdin_path = NULL;
624 const char *stdout_path = NULL;
625 const char *stderr_path = NULL;
626 const char *working_dir = launch_info.GetWorkingDirectory();
627
628 const ProcessLaunchInfo::FileAction *file_action;
629 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
630 if (file_action)
631 {
632 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
633 stdin_path = file_action->GetPath();
634 }
635 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
636 if (file_action)
637 {
638 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
639 stdout_path = file_action->GetPath();
640 }
641 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
642 if (file_action)
643 {
644 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
645 stderr_path = file_action->GetPath();
646 }
647
Chris Lattner24943d22010-06-08 16:52:24 +0000648 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
649 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
650 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton716cefb2011-08-09 05:20:29 +0000651 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000652
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000653 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner24943d22010-06-08 16:52:24 +0000654 if (object_file)
655 {
Chris Lattner24943d22010-06-08 16:52:24 +0000656 char host_port[128];
657 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000658 char connect_url[128];
659 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000660
Greg Claytona2f74232011-02-24 22:24:29 +0000661 // Make sure we aren't already connected?
662 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000663 {
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000664 error = StartDebugserverProcess (host_port, launch_info);
Chris Lattner24943d22010-06-08 16:52:24 +0000665 if (error.Fail())
Greg Clayton716cefb2011-08-09 05:20:29 +0000666 {
Johnny Chenc143d622011-08-09 18:56:45 +0000667 if (log)
668 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner24943d22010-06-08 16:52:24 +0000669 return error;
Greg Clayton716cefb2011-08-09 05:20:29 +0000670 }
Chris Lattner24943d22010-06-08 16:52:24 +0000671
Greg Claytone71e2582011-02-04 01:58:07 +0000672 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000673 }
674
675 if (error.Success())
676 {
677 lldb_utility::PseudoTerminal pty;
678 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000679
680 // If the debugserver is local and we aren't disabling STDIO, lets use
681 // a pseudo terminal to instead of relying on the 'O' packets for stdio
682 // since 'O' packets can really slow down debugging if the inferior
683 // does a lot of output.
Greg Claytonb4747822011-06-24 22:32:10 +0000684 PlatformSP platform_sp (m_target.GetPlatform());
685 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000686 {
687 const char *slave_name = NULL;
688 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000689 {
Greg Claytona2f74232011-02-24 22:24:29 +0000690 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
691 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000692 }
Greg Claytona2f74232011-02-24 22:24:29 +0000693 if (stdin_path == NULL)
694 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000695
Greg Claytona2f74232011-02-24 22:24:29 +0000696 if (stdout_path == NULL)
697 stdout_path = slave_name;
698
699 if (stderr_path == NULL)
700 stderr_path = slave_name;
701 }
702
Greg Claytonafb81862011-03-02 21:34:46 +0000703 // Set STDIN to /dev/null if we want STDIO disabled or if either
704 // STDOUT or STDERR have been set to something and STDIN hasn't
705 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000706 stdin_path = "/dev/null";
707
Greg Claytonafb81862011-03-02 21:34:46 +0000708 // Set STDOUT to /dev/null if we want STDIO disabled or if either
709 // STDIN or STDERR have been set to something and STDOUT hasn't
710 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000711 stdout_path = "/dev/null";
712
Greg Claytonafb81862011-03-02 21:34:46 +0000713 // Set STDERR to /dev/null if we want STDIO disabled or if either
714 // STDIN or STDOUT have been set to something and STDERR hasn't
715 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000716 stderr_path = "/dev/null";
717
718 if (stdin_path)
719 m_gdb_comm.SetSTDIN (stdin_path);
720 if (stdout_path)
721 m_gdb_comm.SetSTDOUT (stdout_path);
722 if (stderr_path)
723 m_gdb_comm.SetSTDERR (stderr_path);
724
725 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
726
Greg Claytona4582402011-05-08 04:53:50 +0000727 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000728
729 if (working_dir && working_dir[0])
730 {
731 m_gdb_comm.SetWorkingDir (working_dir);
732 }
733
734 // Send the environment and the program + arguments after we connect
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000735 const Args &environment = launch_info.GetEnvironmentEntries();
736 if (environment.GetArgumentCount())
Greg Claytona2f74232011-02-24 22:24:29 +0000737 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000738 size_t num_environment_entries = environment.GetArgumentCount();
739 for (size_t i=0; i<num_environment_entries; ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000740 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000741 const char *env_entry = environment.GetArgumentAtIndex(i);
742 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000743 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000744 }
Greg Claytona2f74232011-02-24 22:24:29 +0000745 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000746
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000747 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000748 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info.GetArguments().GetConstArgumentVector());
Greg Claytona2f74232011-02-24 22:24:29 +0000749 if (arg_packet_err == 0)
750 {
751 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000752 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000753 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000754 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000755 }
756 else
757 {
Greg Claytona2f74232011-02-24 22:24:29 +0000758 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000759 }
Greg Claytona2f74232011-02-24 22:24:29 +0000760 }
761 else
762 {
Greg Clayton9c236732011-10-26 00:56:27 +0000763 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Claytona2f74232011-02-24 22:24:29 +0000764 }
Greg Clayton7c4fc6e2011-08-10 22:05:39 +0000765
766 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner24943d22010-06-08 16:52:24 +0000767
Greg Claytona2f74232011-02-24 22:24:29 +0000768 if (GetID() == LLDB_INVALID_PROCESS_ID)
769 {
Johnny Chenc143d622011-08-09 18:56:45 +0000770 if (log)
771 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytona2f74232011-02-24 22:24:29 +0000772 KillDebugserverProcess ();
773 return error;
774 }
775
Greg Clayton261a18b2011-06-02 22:22:38 +0000776 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000777 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000778 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Claytona2f74232011-02-24 22:24:29 +0000779
780 if (!disable_stdio)
781 {
782 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Clayton464c6162011-11-17 22:14:31 +0000783 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Claytona2f74232011-02-24 22:24:29 +0000784 }
Chris Lattner24943d22010-06-08 16:52:24 +0000785 }
786 }
Greg Clayton716cefb2011-08-09 05:20:29 +0000787 else
788 {
Johnny Chenc143d622011-08-09 18:56:45 +0000789 if (log)
790 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton716cefb2011-08-09 05:20:29 +0000791 }
Chris Lattner24943d22010-06-08 16:52:24 +0000792 }
793 else
794 {
795 // Set our user ID to an invalid process ID.
796 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000797 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
798 exe_module->GetFileSpec().GetFilename().AsCString(),
799 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000800 }
Chris Lattner24943d22010-06-08 16:52:24 +0000801 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000802
Chris Lattner24943d22010-06-08 16:52:24 +0000803}
804
805
806Error
Greg Claytone71e2582011-02-04 01:58:07 +0000807ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000808{
809 Error error;
810 // Sleep and wait a bit for debugserver to start to listen...
811 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
812 if (conn_ap.get())
813 {
Chris Lattner24943d22010-06-08 16:52:24 +0000814 const uint32_t max_retry_count = 50;
815 uint32_t retry_count = 0;
816 while (!m_gdb_comm.IsConnected())
817 {
Greg Claytone71e2582011-02-04 01:58:07 +0000818 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000819 {
820 m_gdb_comm.SetConnection (conn_ap.release());
821 break;
822 }
823 retry_count++;
824
825 if (retry_count >= max_retry_count)
826 break;
827
828 usleep (100000);
829 }
830 }
831
832 if (!m_gdb_comm.IsConnected())
833 {
834 if (error.Success())
835 error.SetErrorString("not connected to remote gdb server");
836 return error;
837 }
838
Greg Clayton24bc5d92011-03-30 18:16:51 +0000839 // We always seem to be able to open a connection to a local port
840 // so we need to make sure we can then send data to it. If we can't
841 // then we aren't actually connected to anything, so try and do the
842 // handshake with the remote GDB server and make sure that goes
843 // alright.
844 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000845 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000846 m_gdb_comm.Disconnect();
847 if (error.Success())
848 error.SetErrorString("not connected to remote gdb server");
849 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000850 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000851 m_gdb_comm.ResetDiscoverableSettings();
852 m_gdb_comm.QueryNoAckModeSupported ();
853 m_gdb_comm.GetThreadSuffixSupported ();
Greg Claytona1f645e2012-04-10 03:22:03 +0000854 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000855 m_gdb_comm.GetHostInfo ();
856 m_gdb_comm.GetVContSupported ('c');
Jim Ingham3a458eb2012-07-20 21:37:13 +0000857 m_gdb_comm.GetVAttachOrWaitSupported();
Jim Ingham86827fb2012-07-02 05:40:07 +0000858
859 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
860 for (size_t idx = 0; idx < num_cmds; idx++)
861 {
862 StringExtractorGDBRemote response;
Jim Ingham86827fb2012-07-02 05:40:07 +0000863 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
864 }
Chris Lattner24943d22010-06-08 16:52:24 +0000865 return error;
866}
867
868void
869ProcessGDBRemote::DidLaunchOrAttach ()
870{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000871 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
872 if (log)
873 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000874 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000875 {
876 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
877
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000878 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000879
Chris Lattner24943d22010-06-08 16:52:24 +0000880 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000881
Jason Molendafe555672012-12-19 02:54:03 +0000882 ArchSpec gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
883
884 // See if the GDB server supports the qProcessInfo packet, if so
885 // prefer that over the Host information as it will be more specific
886 // to our process.
887
888 if (m_gdb_comm.GetProcessArchitecture().IsValid())
889 gdb_remote_arch = m_gdb_comm.GetProcessArchitecture();
890
Greg Claytoncb8977d2011-03-23 00:09:55 +0000891 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000892 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000893 ArchSpec &target_arch = GetTarget().GetArchitecture();
894
895 if (target_arch.IsValid())
896 {
897 // If the remote host is ARM and we have apple as the vendor, then
898 // ARM executables and shared libraries can have mixed ARM architectures.
899 // You can have an armv6 executable, and if the host is armv7, then the
900 // system will load the best possible architecture for all shared libraries
901 // it has, so we really need to take the remote host architecture as our
902 // defacto architecture in this case.
903
904 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
905 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
906 {
907 target_arch = gdb_remote_arch;
908 }
909 else
910 {
911 // Fill in what is missing in the triple
912 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
913 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000914 if (target_triple.getVendorName().size() == 0)
915 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000916 target_triple.setVendor (remote_triple.getVendor());
917
Greg Clayton2f085c62011-05-15 01:25:55 +0000918 if (target_triple.getOSName().size() == 0)
919 {
920 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000921
Greg Clayton2f085c62011-05-15 01:25:55 +0000922 if (target_triple.getEnvironmentName().size() == 0)
923 target_triple.setEnvironment (remote_triple.getEnvironment());
924 }
925 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000926 }
927 }
928 else
929 {
930 // The target doesn't have a valid architecture yet, set it from
931 // the architecture we got from the remote GDB server
932 target_arch = gdb_remote_arch;
933 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000934 }
Chris Lattner24943d22010-06-08 16:52:24 +0000935 }
936}
937
938void
939ProcessGDBRemote::DidLaunch ()
940{
941 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000942}
943
944Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000945ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000946{
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000947 ProcessAttachInfo attach_info;
948 return DoAttachToProcessWithID(attach_pid, attach_info);
949}
950
951Error
952ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
953{
Chris Lattner24943d22010-06-08 16:52:24 +0000954 Error error;
955 // Clear out and clean up from any current state
956 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000957 if (attach_pid != LLDB_INVALID_PROCESS_ID)
958 {
Greg Claytona2f74232011-02-24 22:24:29 +0000959 // Make sure we aren't already connected?
960 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000961 {
Greg Claytona2f74232011-02-24 22:24:29 +0000962 char host_port[128];
963 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
964 char connect_url[128];
965 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000966
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000967 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000968
969 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000970 {
Greg Claytona2f74232011-02-24 22:24:29 +0000971 const char *error_string = error.AsCString();
972 if (error_string == NULL)
973 error_string = "unable to launch " DEBUGSERVER_BASENAME;
974
975 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000976 }
Greg Claytona2f74232011-02-24 22:24:29 +0000977 else
978 {
979 error = ConnectToDebugserver (connect_url);
980 }
981 }
982
983 if (error.Success())
984 {
985 char packet[64];
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000986 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Greg Clayton489575c2011-11-19 02:11:30 +0000987 SetID (attach_pid);
Greg Claytona2f74232011-02-24 22:24:29 +0000988 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000989 }
990 }
Chris Lattner24943d22010-06-08 16:52:24 +0000991 return error;
992}
993
994size_t
995ProcessGDBRemote::AttachInputReaderCallback
996(
997 void *baton,
998 InputReader *reader,
999 lldb::InputReaderAction notification,
1000 const char *bytes,
1001 size_t bytes_len
1002)
1003{
1004 if (notification == eInputReaderGotToken)
1005 {
1006 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
1007 if (gdb_process->m_waiting_for_attach)
1008 gdb_process->m_waiting_for_attach = false;
1009 reader->SetIsDone(true);
1010 return 1;
1011 }
1012 return 0;
1013}
1014
1015Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +00001016ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +00001017{
1018 Error error;
1019 // Clear out and clean up from any current state
1020 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001021
Chris Lattner24943d22010-06-08 16:52:24 +00001022 if (process_name && process_name[0])
1023 {
Greg Claytona2f74232011-02-24 22:24:29 +00001024 // Make sure we aren't already connected?
1025 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001026 {
Greg Claytona2f74232011-02-24 22:24:29 +00001027 char host_port[128];
1028 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
1029 char connect_url[128];
1030 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
1031
Han Ming Ongd1040dd2012-02-25 01:07:38 +00001032 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +00001033 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +00001034 {
Greg Claytona2f74232011-02-24 22:24:29 +00001035 const char *error_string = error.AsCString();
1036 if (error_string == NULL)
1037 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +00001038
Greg Claytona2f74232011-02-24 22:24:29 +00001039 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +00001040 }
Greg Claytona2f74232011-02-24 22:24:29 +00001041 else
1042 {
1043 error = ConnectToDebugserver (connect_url);
1044 }
1045 }
1046
1047 if (error.Success())
1048 {
1049 StreamString packet;
1050
1051 if (wait_for_launch)
Jim Ingham3a458eb2012-07-20 21:37:13 +00001052 {
1053 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1054 {
1055 packet.PutCString ("vAttachWait");
1056 }
1057 else
1058 {
1059 if (attach_info.GetIgnoreExisting())
1060 packet.PutCString("vAttachWait");
1061 else
1062 packet.PutCString ("vAttachOrWait");
1063 }
1064 }
Greg Claytona2f74232011-02-24 22:24:29 +00001065 else
1066 packet.PutCString("vAttachName");
1067 packet.PutChar(';');
1068 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1069
1070 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1071
Chris Lattner24943d22010-06-08 16:52:24 +00001072 }
1073 }
Chris Lattner24943d22010-06-08 16:52:24 +00001074 return error;
1075}
1076
Chris Lattner24943d22010-06-08 16:52:24 +00001077
1078void
1079ProcessGDBRemote::DidAttach ()
1080{
Greg Claytone71e2582011-02-04 01:58:07 +00001081 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +00001082}
1083
Greg Clayton0bce9a22012-12-05 00:16:59 +00001084void
1085ProcessGDBRemote::DoDidExec ()
1086{
1087 // The process exec'ed itself, figure out the dynamic loader, etc...
1088 BuildDynamicRegisterInfo (true);
1089 m_gdb_comm.ResetDiscoverableSettings();
1090 DidLaunchOrAttach ();
1091}
1092
1093
1094
Chris Lattner24943d22010-06-08 16:52:24 +00001095Error
1096ProcessGDBRemote::WillResume ()
1097{
Greg Claytonc1f45872011-02-12 06:28:37 +00001098 m_continue_c_tids.clear();
1099 m_continue_C_tids.clear();
1100 m_continue_s_tids.clear();
1101 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001102 return Error();
1103}
1104
1105Error
1106ProcessGDBRemote::DoResume ()
1107{
Jim Ingham3ae449a2010-11-17 02:32:00 +00001108 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +00001109 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1110 if (log)
1111 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +00001112
1113 Listener listener ("gdb-remote.resume-packet-sent");
1114 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1115 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001116 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1117
Greg Claytonc1f45872011-02-12 06:28:37 +00001118 StreamString continue_packet;
1119 bool continue_packet_error = false;
1120 if (m_gdb_comm.HasAnyVContSupport ())
1121 {
1122 continue_packet.PutCString ("vCont");
1123
1124 if (!m_continue_c_tids.empty())
1125 {
1126 if (m_gdb_comm.GetVContSupported ('c'))
1127 {
1128 for (tid_collection::const_iterator t_pos = m_continue_c_tids.begin(), t_end = m_continue_c_tids.end(); t_pos != t_end; ++t_pos)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001129 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +00001130 }
1131 else
1132 continue_packet_error = true;
1133 }
1134
1135 if (!continue_packet_error && !m_continue_C_tids.empty())
1136 {
1137 if (m_gdb_comm.GetVContSupported ('C'))
1138 {
1139 for (tid_sig_collection::const_iterator s_pos = m_continue_C_tids.begin(), s_end = m_continue_C_tids.end(); s_pos != s_end; ++s_pos)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001140 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001141 }
1142 else
1143 continue_packet_error = true;
1144 }
Greg Claytonb749a262010-12-03 06:02:24 +00001145
Greg Claytonc1f45872011-02-12 06:28:37 +00001146 if (!continue_packet_error && !m_continue_s_tids.empty())
1147 {
1148 if (m_gdb_comm.GetVContSupported ('s'))
1149 {
1150 for (tid_collection::const_iterator t_pos = m_continue_s_tids.begin(), t_end = m_continue_s_tids.end(); t_pos != t_end; ++t_pos)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001151 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +00001152 }
1153 else
1154 continue_packet_error = true;
1155 }
1156
1157 if (!continue_packet_error && !m_continue_S_tids.empty())
1158 {
1159 if (m_gdb_comm.GetVContSupported ('S'))
1160 {
1161 for (tid_sig_collection::const_iterator s_pos = m_continue_S_tids.begin(), s_end = m_continue_S_tids.end(); s_pos != s_end; ++s_pos)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001162 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001163 }
1164 else
1165 continue_packet_error = true;
1166 }
1167
1168 if (continue_packet_error)
1169 continue_packet.GetString().clear();
1170 }
1171 else
1172 continue_packet_error = true;
1173
1174 if (continue_packet_error)
1175 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001176 // Either no vCont support, or we tried to use part of the vCont
1177 // packet that wasn't supported by the remote GDB server.
1178 // We need to try and make a simple packet that can do our continue
1179 const size_t num_threads = GetThreadList().GetSize();
1180 const size_t num_continue_c_tids = m_continue_c_tids.size();
1181 const size_t num_continue_C_tids = m_continue_C_tids.size();
1182 const size_t num_continue_s_tids = m_continue_s_tids.size();
1183 const size_t num_continue_S_tids = m_continue_S_tids.size();
1184 if (num_continue_c_tids > 0)
1185 {
1186 if (num_continue_c_tids == num_threads)
1187 {
1188 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001189 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001190 continue_packet.PutChar ('c');
1191 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001192 }
1193 else if (num_continue_c_tids == 1 &&
1194 num_continue_C_tids == 0 &&
1195 num_continue_s_tids == 0 &&
1196 num_continue_S_tids == 0 )
1197 {
1198 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +00001199 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001200 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +00001201 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001202 }
1203 }
1204
Greg Claytonde1dd812011-06-24 03:21:43 +00001205 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001206 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001207 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1208 num_continue_C_tids > 0 &&
1209 num_continue_s_tids == 0 &&
1210 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +00001211 {
1212 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +00001213 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +00001214 if (num_continue_C_tids > 1)
1215 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001216 // More that one thread with a signal, yet we don't have
1217 // vCont support and we are being asked to resume each
1218 // thread with a signal, we need to make sure they are
1219 // all the same signal, or we can't issue the continue
1220 // accurately with the current support...
1221 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +00001222 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001223 continue_packet_error = false;
1224 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1225 {
1226 if (m_continue_C_tids[i].second != continue_signo)
1227 continue_packet_error = true;
1228 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001229 }
Greg Claytonde1dd812011-06-24 03:21:43 +00001230 if (!continue_packet_error)
1231 m_gdb_comm.SetCurrentThreadForRun (-1);
1232 }
1233 else
1234 {
1235 // Set the continue thread ID
1236 continue_packet_error = false;
1237 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001238 }
1239 if (!continue_packet_error)
1240 {
1241 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +00001242 continue_packet.Printf("C%2.2x", continue_signo);
1243 }
1244 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001245 }
1246
Greg Claytonde1dd812011-06-24 03:21:43 +00001247 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001248 {
1249 if (num_continue_s_tids == num_threads)
1250 {
1251 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001252 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001253 continue_packet.PutChar ('s');
1254 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001255 }
1256 else if (num_continue_c_tids == 0 &&
1257 num_continue_C_tids == 0 &&
1258 num_continue_s_tids == 1 &&
1259 num_continue_S_tids == 0 )
1260 {
1261 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001262 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001263 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001264 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001265 }
1266 }
1267
1268 if (!continue_packet_error && num_continue_S_tids > 0)
1269 {
1270 if (num_continue_S_tids == num_threads)
1271 {
1272 const int step_signo = m_continue_S_tids.front().second;
1273 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001274 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001275 if (num_continue_S_tids > 1)
1276 {
1277 for (size_t i=1; i<num_threads; ++i)
1278 {
1279 if (m_continue_S_tids[i].second != step_signo)
1280 continue_packet_error = true;
1281 }
1282 }
1283 if (!continue_packet_error)
1284 {
1285 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001286 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001287 continue_packet.Printf("S%2.2x", step_signo);
1288 }
1289 }
1290 else if (num_continue_c_tids == 0 &&
1291 num_continue_C_tids == 0 &&
1292 num_continue_s_tids == 0 &&
1293 num_continue_S_tids == 1 )
1294 {
1295 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001296 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001297 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001298 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001299 }
1300 }
1301 }
1302
1303 if (continue_packet_error)
1304 {
1305 error.SetErrorString ("can't make continue packet for this resume");
1306 }
1307 else
1308 {
1309 EventSP event_sp;
1310 TimeValue timeout;
1311 timeout = TimeValue::Now();
1312 timeout.OffsetWithSeconds (5);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001313 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1314 {
1315 error.SetErrorString ("Trying to resume but the async thread is dead.");
1316 if (log)
1317 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1318 return error;
1319 }
1320
Greg Claytonc1f45872011-02-12 06:28:37 +00001321 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1322
1323 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001324 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001325 error.SetErrorString("Resume timed out.");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001326 if (log)
1327 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1328 }
1329 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1330 {
1331 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1332 if (log)
1333 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1334 return error;
1335 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001336 }
Greg Claytonb749a262010-12-03 06:02:24 +00001337 }
1338
Jim Ingham3ae449a2010-11-17 02:32:00 +00001339 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001340}
1341
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001342void
1343ProcessGDBRemote::ClearThreadIDList ()
1344{
Greg Claytonff3448e2012-04-13 02:11:32 +00001345 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001346 m_thread_ids.clear();
1347}
1348
1349bool
1350ProcessGDBRemote::UpdateThreadIDList ()
1351{
Greg Claytonff3448e2012-04-13 02:11:32 +00001352 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001353 bool sequence_mutex_unavailable = false;
1354 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1355 if (sequence_mutex_unavailable)
1356 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001357 return false; // We just didn't get the list
1358 }
1359 return true;
1360}
1361
Greg Claytonae932352012-04-10 00:18:59 +00001362bool
Greg Clayton37f962e2011-08-22 02:49:39 +00001363ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001364{
1365 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001366 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001367 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001368 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001369
1370 size_t num_thread_ids = m_thread_ids.size();
1371 // The "m_thread_ids" thread ID list should always be updated after each stop
1372 // reply packet, but in case it isn't, update it here.
1373 if (num_thread_ids == 0)
1374 {
1375 if (!UpdateThreadIDList ())
1376 return false;
1377 num_thread_ids = m_thread_ids.size();
1378 }
Chris Lattner24943d22010-06-08 16:52:24 +00001379
Greg Clayton37f962e2011-08-22 02:49:39 +00001380 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001381 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001382 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001383 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001384 tid_t tid = m_thread_ids[i];
Greg Clayton37f962e2011-08-22 02:49:39 +00001385 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false));
1386 if (!thread_sp)
Jim Ingham94a5d0d2012-10-10 18:32:14 +00001387 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Greg Clayton37f962e2011-08-22 02:49:39 +00001388 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001389 }
Chris Lattner24943d22010-06-08 16:52:24 +00001390 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001391
Greg Claytonae932352012-04-10 00:18:59 +00001392 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001393}
1394
1395
1396StateType
1397ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1398{
Greg Clayton261a18b2011-06-02 22:22:38 +00001399 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001400 const char stop_type = stop_packet.GetChar();
1401 switch (stop_type)
1402 {
1403 case 'T':
1404 case 'S':
1405 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001406 if (GetStopID() == 0)
1407 {
1408 // Our first stop, make sure we have a process ID, and also make
1409 // sure we know about our registers
1410 if (GetID() == LLDB_INVALID_PROCESS_ID)
1411 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001412 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001413 if (pid != LLDB_INVALID_PROCESS_ID)
1414 SetID (pid);
1415 }
1416 BuildDynamicRegisterInfo (true);
1417 }
Chris Lattner24943d22010-06-08 16:52:24 +00001418 // Stop with signal and thread info
1419 const uint8_t signo = stop_packet.GetHexU8();
1420 std::string name;
1421 std::string value;
1422 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001423 std::string reason;
1424 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001425 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001426 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001427 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Claytona875b642011-01-09 21:07:35 +00001428 ThreadSP thread_sp;
1429
Chris Lattner24943d22010-06-08 16:52:24 +00001430 while (stop_packet.GetNameColonValue(name, value))
1431 {
1432 if (name.compare("metype") == 0)
1433 {
1434 // exception type in big endian hex
1435 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1436 }
Chris Lattner24943d22010-06-08 16:52:24 +00001437 else if (name.compare("medata") == 0)
1438 {
1439 // exception data in big endian hex
1440 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1441 }
1442 else if (name.compare("thread") == 0)
1443 {
1444 // thread in big endian hex
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001445 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Claytonffa43a62011-11-17 04:46:02 +00001446 // m_thread_list does have its own mutex, but we need to
1447 // hold onto the mutex between the call to m_thread_list.FindThreadByID(...)
1448 // and the m_thread_list.AddThread(...) so it doesn't change on us
Greg Claytonc3c46612011-02-15 00:19:15 +00001449 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001450 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001451 if (!thread_sp)
1452 {
1453 // Create the thread if we need to
Jim Ingham94a5d0d2012-10-10 18:32:14 +00001454 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Greg Claytonc3c46612011-02-15 00:19:15 +00001455 m_thread_list.AddThread(thread_sp);
1456 }
Chris Lattner24943d22010-06-08 16:52:24 +00001457 }
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001458 else if (name.compare("threads") == 0)
1459 {
Greg Claytonff3448e2012-04-13 02:11:32 +00001460 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001461 m_thread_ids.clear();
Greg Claytona1f645e2012-04-10 03:22:03 +00001462 // A comma separated list of all threads in the current
1463 // process that includes the thread for this stop reply
1464 // packet
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001465 size_t comma_pos;
1466 lldb::tid_t tid;
1467 while ((comma_pos = value.find(',')) != std::string::npos)
1468 {
1469 value[comma_pos] = '\0';
1470 // thread in big endian hex
1471 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1472 if (tid != LLDB_INVALID_THREAD_ID)
1473 m_thread_ids.push_back (tid);
1474 value.erase(0, comma_pos + 1);
1475
1476 }
1477 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1478 if (tid != LLDB_INVALID_THREAD_ID)
1479 m_thread_ids.push_back (tid);
1480 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001481 else if (name.compare("hexname") == 0)
1482 {
1483 StringExtractor name_extractor;
1484 // Swap "value" over into "name_extractor"
1485 name_extractor.GetStringRef().swap(value);
1486 // Now convert the HEX bytes into a string value
1487 name_extractor.GetHexByteString (value);
1488 thread_name.swap (value);
1489 }
Chris Lattner24943d22010-06-08 16:52:24 +00001490 else if (name.compare("name") == 0)
1491 {
1492 thread_name.swap (value);
1493 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001494 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001495 {
1496 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1497 }
Greg Clayton65611552011-06-04 01:26:29 +00001498 else if (name.compare("reason") == 0)
1499 {
1500 reason.swap(value);
1501 }
1502 else if (name.compare("description") == 0)
1503 {
1504 StringExtractor desc_extractor;
1505 // Swap "value" over into "name_extractor"
1506 desc_extractor.GetStringRef().swap(value);
1507 // Now convert the HEX bytes into a string value
1508 desc_extractor.GetHexByteString (thread_name);
1509 }
Greg Claytona875b642011-01-09 21:07:35 +00001510 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1511 {
1512 // We have a register number that contains an expedited
1513 // register value. Lets supply this register to our thread
1514 // so it won't have to go and read it.
1515 if (thread_sp)
1516 {
1517 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1518
1519 if (reg != UINT32_MAX)
1520 {
1521 StringExtractor reg_value_extractor;
1522 // Swap "value" over into "reg_value_extractor"
1523 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001524 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1525 {
1526 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1527 name.c_str(),
1528 reg,
1529 reg,
1530 reg_value_extractor.GetStringRef().c_str(),
1531 stop_packet.GetStringRef().c_str());
1532 }
Greg Claytona875b642011-01-09 21:07:35 +00001533 }
1534 }
1535 }
Chris Lattner24943d22010-06-08 16:52:24 +00001536 }
Chris Lattner24943d22010-06-08 16:52:24 +00001537
1538 if (thread_sp)
1539 {
1540 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1541
1542 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001543 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001544 if (exc_type != 0)
1545 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001546 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001547
1548 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1549 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001550 exc_data_size,
1551 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001552 exc_data_size >= 2 ? exc_data[1] : 0,
1553 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001554 }
Greg Clayton65611552011-06-04 01:26:29 +00001555 else
Chris Lattner24943d22010-06-08 16:52:24 +00001556 {
Greg Clayton65611552011-06-04 01:26:29 +00001557 bool handled = false;
1558 if (!reason.empty())
1559 {
1560 if (reason.compare("trace") == 0)
1561 {
1562 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1563 handled = true;
1564 }
1565 else if (reason.compare("breakpoint") == 0)
1566 {
1567 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001568 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001569 if (bp_site_sp)
1570 {
1571 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1572 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1573 // 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 +00001574 handled = true;
Greg Clayton65611552011-06-04 01:26:29 +00001575 if (bp_site_sp->ValidForThisThread (gdb_thread))
1576 {
1577 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001578 }
1579 else
1580 {
1581 StopInfoSP invalid_stop_info_sp;
1582 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Greg Clayton65611552011-06-04 01:26:29 +00001583 }
1584 }
1585
Greg Clayton65611552011-06-04 01:26:29 +00001586 }
1587 else if (reason.compare("trap") == 0)
1588 {
1589 // Let the trap just use the standard signal stop reason below...
1590 }
1591 else if (reason.compare("watchpoint") == 0)
1592 {
1593 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1594 // TODO: locate the watchpoint somehow...
1595 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1596 handled = true;
1597 }
1598 else if (reason.compare("exception") == 0)
1599 {
1600 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1601 handled = true;
1602 }
1603 }
1604
1605 if (signo)
1606 {
1607 if (signo == SIGTRAP)
1608 {
1609 // Currently we are going to assume SIGTRAP means we are either
1610 // hitting a breakpoint or hardware single stepping.
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001611 handled = true;
Greg Clayton65611552011-06-04 01:26:29 +00001612 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001613 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001614
Greg Clayton65611552011-06-04 01:26:29 +00001615 if (bp_site_sp)
1616 {
1617 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1618 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1619 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1620 if (bp_site_sp->ValidForThisThread (gdb_thread))
1621 {
1622 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001623 }
1624 else
1625 {
1626 StopInfoSP invalid_stop_info_sp;
1627 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Greg Clayton65611552011-06-04 01:26:29 +00001628 }
1629 }
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001630 else
Greg Clayton65611552011-06-04 01:26:29 +00001631 {
Jim Ingham4fa015b2012-10-27 02:52:04 +00001632 // If we were stepping then assume the stop was the result of the trace. If we were
1633 // not stepping then report the SIGTRAP.
1634 // FIXME: We are still missing the case where we single step over a trap instruction.
1635 if (gdb_thread->GetTemporaryResumeState() == eStateStepping)
1636 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1637 else
1638 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo));
Greg Clayton65611552011-06-04 01:26:29 +00001639 }
1640 }
1641 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001642 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001643 }
1644 else
1645 {
Greg Clayton643ee732010-08-04 01:40:35 +00001646 StopInfoSP invalid_stop_info_sp;
1647 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001648 }
Greg Clayton65611552011-06-04 01:26:29 +00001649
1650 if (!description.empty())
1651 {
1652 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1653 if (stop_info_sp)
1654 {
1655 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001656 }
Greg Clayton65611552011-06-04 01:26:29 +00001657 else
1658 {
1659 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1660 }
1661 }
1662 }
Chris Lattner24943d22010-06-08 16:52:24 +00001663 }
1664 return eStateStopped;
1665 }
1666 break;
1667
1668 case 'W':
1669 // process exited
1670 return eStateExited;
1671
1672 default:
1673 break;
1674 }
1675 return eStateInvalid;
1676}
1677
1678void
1679ProcessGDBRemote::RefreshStateAfterStop ()
1680{
Greg Claytonff3448e2012-04-13 02:11:32 +00001681 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001682 m_thread_ids.clear();
1683 // Set the thread stop info. It might have a "threads" key whose value is
1684 // a list of all thread IDs in the current process, so m_thread_ids might
1685 // get set.
1686 SetThreadStopInfo (m_last_stop_packet);
1687 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1688 if (m_thread_ids.empty())
1689 {
1690 // No, we need to fetch the thread list manually
1691 UpdateThreadIDList();
1692 }
1693
Chris Lattner24943d22010-06-08 16:52:24 +00001694 // Let all threads recover from stopping and do any clean up based
1695 // on the previous thread state (if any).
1696 m_thread_list.RefreshStateAfterStop();
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001697
Chris Lattner24943d22010-06-08 16:52:24 +00001698}
1699
1700Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001701ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001702{
1703 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001704
Greg Claytona4881d02011-01-22 07:12:45 +00001705 bool timed_out = false;
1706 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001707
1708 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001709 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001710 // We are being asked to halt during an attach. We need to just close
1711 // our file handle and debugserver will go away, and we can be done...
1712 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001713 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001714 else
1715 {
Greg Clayton05e4d972012-03-29 01:55:41 +00001716 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001717 {
1718 if (timed_out)
1719 error.SetErrorString("timed out sending interrupt packet");
1720 else
1721 error.SetErrorString("unknown error sending interrupt packet");
1722 }
Greg Clayton05e4d972012-03-29 01:55:41 +00001723
1724 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001725 }
Chris Lattner24943d22010-06-08 16:52:24 +00001726 return error;
1727}
1728
1729Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001730ProcessGDBRemote::InterruptIfRunning
1731(
1732 bool discard_thread_plans,
1733 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001734 EventSP &stop_event_sp
1735)
Chris Lattner24943d22010-06-08 16:52:24 +00001736{
1737 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001738
Greg Clayton2860ba92011-01-23 19:58:49 +00001739 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1740
Greg Clayton68ca8232011-01-25 02:58:48 +00001741 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001742 const bool is_running = m_gdb_comm.IsRunning();
1743 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001744 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001745 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001746 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001747 is_running);
1748
Greg Clayton2860ba92011-01-23 19:58:49 +00001749 if (discard_thread_plans)
1750 {
1751 if (log)
1752 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1753 m_thread_list.DiscardThreadPlans();
1754 }
1755 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001756 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001757 if (catch_stop_event)
1758 {
1759 if (log)
1760 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1761 PausePrivateStateThread();
1762 paused_private_state_thread = true;
1763 }
1764
Greg Clayton4fb400f2010-09-27 21:07:38 +00001765 bool timed_out = false;
1766 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001767
Greg Clayton05e4d972012-03-29 01:55:41 +00001768 if (!m_gdb_comm.SendInterrupt (locker, 1, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001769 {
1770 if (timed_out)
1771 error.SetErrorString("timed out sending interrupt packet");
1772 else
1773 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001774 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001775 ResumePrivateStateThread();
1776 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001777 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001778
Greg Clayton72e1c782011-01-22 23:43:18 +00001779 if (catch_stop_event)
1780 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001781 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001782 TimeValue timeout_time;
1783 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001784 timeout_time.OffsetWithSeconds(5);
1785 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001786
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001787 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001788 if (log)
1789 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001790
Greg Clayton2860ba92011-01-23 19:58:49 +00001791 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001792 error.SetErrorString("unable to verify target stopped");
1793 }
1794
Greg Clayton68ca8232011-01-25 02:58:48 +00001795 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001796 {
1797 if (log)
1798 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001799 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001800 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001801 }
Chris Lattner24943d22010-06-08 16:52:24 +00001802 return error;
1803}
1804
Greg Clayton4fb400f2010-09-27 21:07:38 +00001805Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001806ProcessGDBRemote::WillDetach ()
1807{
Greg Clayton2860ba92011-01-23 19:58:49 +00001808 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1809 if (log)
1810 log->Printf ("ProcessGDBRemote::WillDetach()");
1811
Greg Clayton72e1c782011-01-22 23:43:18 +00001812 bool discard_thread_plans = true;
1813 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001814 EventSP event_sp;
Jim Ingham8247e622012-06-06 00:32:39 +00001815
1816 // FIXME: InterruptIfRunning should be done in the Process base class, or better still make Halt do what is
1817 // needed. This shouldn't be a feature of a particular plugin.
1818
Greg Clayton68ca8232011-01-25 02:58:48 +00001819 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001820}
1821
1822Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001823ProcessGDBRemote::DoDetach()
1824{
1825 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001826 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001827 if (log)
1828 log->Printf ("ProcessGDBRemote::DoDetach()");
1829
1830 DisableAllBreakpointSites ();
1831
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001832 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001833
Greg Clayton516f0842012-04-11 00:24:49 +00001834 bool success = m_gdb_comm.Detach ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001835 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001836 {
Greg Clayton516f0842012-04-11 00:24:49 +00001837 if (success)
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001838 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1839 else
1840 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001841 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001842 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001843 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001844
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001845 SetPrivateState (eStateDetached);
1846 ResumePrivateStateThread();
1847
1848 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001849 return error;
1850}
Chris Lattner24943d22010-06-08 16:52:24 +00001851
Jim Ingham06b84492012-07-04 00:35:43 +00001852
Chris Lattner24943d22010-06-08 16:52:24 +00001853Error
1854ProcessGDBRemote::DoDestroy ()
1855{
1856 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001857 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001858 if (log)
1859 log->Printf ("ProcessGDBRemote::DoDestroy()");
1860
Jim Ingham06b84492012-07-04 00:35:43 +00001861 // There is a bug in older iOS debugservers where they don't shut down the process
1862 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
1863 // this can cause problems with restarting. So we check to see if any of our threads are stopped
1864 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
1865 // destroy it again.
1866 //
1867 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
1868 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
1869 // the debugservers with this bug are equal. There really should be a better way to test this!
1870 //
1871 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
1872 // get called here to destroy again and we're still at a breakpoint or exception, then we should
1873 // just do the straight-forward kill.
1874 //
1875 // And of course, if we weren't able to stop the process by the time we get here, it isn't
1876 // necessary (or helpful) to do any of this.
1877
1878 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
1879 {
1880 PlatformSP platform_sp = GetTarget().GetPlatform();
1881
1882 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
1883 if (platform_sp
1884 && platform_sp->GetName()
1885 && strcmp (platform_sp->GetName(), PlatformRemoteiOS::GetShortPluginNameStatic()) == 0)
1886 {
1887 if (m_destroy_tried_resuming)
1888 {
1889 if (log)
1890 log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again.");
1891 }
1892 else
1893 {
1894 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
1895 // but we really need it to happen here and it doesn't matter if we do it twice.
1896 m_thread_list.DiscardThreadPlans();
1897 DisableAllBreakpointSites();
1898
1899 bool stop_looks_like_crash = false;
1900 ThreadList &threads = GetThreadList();
1901
1902 {
Jim Inghamc2c65142012-09-11 00:08:52 +00001903 Mutex::Locker locker(threads.GetMutex());
Jim Ingham06b84492012-07-04 00:35:43 +00001904
1905 size_t num_threads = threads.GetSize();
1906 for (size_t i = 0; i < num_threads; i++)
1907 {
1908 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1909 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason();
1910 StopReason reason = eStopReasonInvalid;
1911 if (stop_info_sp)
1912 reason = stop_info_sp->GetStopReason();
1913 if (reason == eStopReasonBreakpoint
1914 || reason == eStopReasonException)
1915 {
1916 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001917 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: %" PRId64 " stopped with reason: %s.",
Jim Ingham06b84492012-07-04 00:35:43 +00001918 thread_sp->GetID(),
1919 stop_info_sp->GetDescription());
1920 stop_looks_like_crash = true;
1921 break;
1922 }
1923 }
1924 }
1925
1926 if (stop_looks_like_crash)
1927 {
1928 if (log)
1929 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
1930 m_destroy_tried_resuming = true;
1931
1932 // If we are going to run again before killing, it would be good to suspend all the threads
1933 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
1934 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
1935 // have to run the risk of letting those threads proceed a bit.
1936
1937 {
Jim Inghamc2c65142012-09-11 00:08:52 +00001938 Mutex::Locker locker(threads.GetMutex());
Jim Ingham06b84492012-07-04 00:35:43 +00001939
1940 size_t num_threads = threads.GetSize();
1941 for (size_t i = 0; i < num_threads; i++)
1942 {
1943 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1944 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason();
1945 StopReason reason = eStopReasonInvalid;
1946 if (stop_info_sp)
1947 reason = stop_info_sp->GetStopReason();
1948 if (reason != eStopReasonBreakpoint
1949 && reason != eStopReasonException)
1950 {
1951 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001952 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: %" PRId64 " before running.",
Jim Ingham06b84492012-07-04 00:35:43 +00001953 thread_sp->GetID());
1954 thread_sp->SetResumeState(eStateSuspended);
1955 }
1956 }
1957 }
1958 Resume ();
1959 return Destroy();
1960 }
1961 }
1962 }
1963 }
1964
Chris Lattner24943d22010-06-08 16:52:24 +00001965 // Interrupt if our inferior is running...
Jim Ingham8247e622012-06-06 00:32:39 +00001966 int exit_status = SIGABRT;
1967 std::string exit_string;
1968
Greg Claytona4881d02011-01-22 07:12:45 +00001969 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001970 {
Jim Ingham8226e942011-10-28 01:11:35 +00001971 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton72e1c782011-01-22 23:43:18 +00001972 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001973
1974 StringExtractorGDBRemote response;
1975 bool send_async = true;
Filipe Cabecinhasee188ee2012-08-22 13:25:58 +00001976 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3);
1977
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001978 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001979 {
1980 char packet_cmd = response.GetChar(0);
1981
1982 if (packet_cmd == 'W' || packet_cmd == 'X')
1983 {
Greg Clayton06709002011-12-06 04:51:14 +00001984 SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001985 ClearThreadIDList ();
Jim Ingham8247e622012-06-06 00:32:39 +00001986 exit_status = response.GetHexU8();
1987 }
1988 else
1989 {
1990 if (log)
1991 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
1992 exit_string.assign("got unexpected response to k packet: ");
1993 exit_string.append(response.GetStringRef());
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001994 }
1995 }
1996 else
1997 {
Jim Ingham8247e622012-06-06 00:32:39 +00001998 if (log)
1999 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2000 exit_string.assign("failed to send the k packet");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002001 }
Filipe Cabecinhasee188ee2012-08-22 13:25:58 +00002002
2003 m_gdb_comm.SetPacketTimeout(old_packet_timeout);
Greg Clayton72e1c782011-01-22 23:43:18 +00002004 }
Jim Ingham8247e622012-06-06 00:32:39 +00002005 else
2006 {
2007 if (log)
2008 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
Jim Ingham5d90ade2012-07-27 23:57:19 +00002009 exit_string.assign ("killed or interrupted while attaching.");
Jim Ingham8247e622012-06-06 00:32:39 +00002010 }
Greg Clayton72e1c782011-01-22 23:43:18 +00002011 }
Jim Ingham8247e622012-06-06 00:32:39 +00002012 else
2013 {
2014 // If we missed setting the exit status on the way out, do it here.
2015 // NB set exit status can be called multiple times, the first one sets the status.
2016 exit_string.assign("destroying when not connected to debugserver");
2017 }
2018
2019 SetExitStatus(exit_status, exit_string.c_str());
2020
Chris Lattner24943d22010-06-08 16:52:24 +00002021 StopAsyncThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002022 KillDebugserverProcess ();
2023 return error;
2024}
2025
Chris Lattner24943d22010-06-08 16:52:24 +00002026//------------------------------------------------------------------
2027// Process Queries
2028//------------------------------------------------------------------
2029
2030bool
2031ProcessGDBRemote::IsAlive ()
2032{
Greg Clayton58e844b2010-12-08 05:08:21 +00002033 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00002034}
2035
Jason Molendad6b81222012-10-06 02:02:26 +00002036// For kernel debugging, we return the load address of the kernel binary as the
2037// ImageInfoAddress and we return the DynamicLoaderDarwinKernel as the GetDynamicLoader()
2038// name so the correct DynamicLoader plugin is chosen.
Chris Lattner24943d22010-06-08 16:52:24 +00002039addr_t
2040ProcessGDBRemote::GetImageInfoAddress()
2041{
Jason Molendab46937c2012-10-03 01:29:34 +00002042 if (m_kernel_load_addr != LLDB_INVALID_ADDRESS)
2043 return m_kernel_load_addr;
2044 else
2045 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner24943d22010-06-08 16:52:24 +00002046}
2047
Chris Lattner24943d22010-06-08 16:52:24 +00002048//------------------------------------------------------------------
2049// Process Memory
2050//------------------------------------------------------------------
2051size_t
2052ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2053{
2054 if (size > m_max_memory_size)
2055 {
2056 // Keep memory read sizes down to a sane limit. This function will be
2057 // called multiple times in order to complete the task by
2058 // lldb_private::Process so it is ok to do this.
2059 size = m_max_memory_size;
2060 }
2061
2062 char packet[64];
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002063 const int packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
Chris Lattner24943d22010-06-08 16:52:24 +00002064 assert (packet_len + 1 < sizeof(packet));
2065 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00002066 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00002067 {
Greg Clayton61d043b2011-03-22 04:00:09 +00002068 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00002069 {
2070 error.Clear();
2071 return response.GetHexBytes(buf, size, '\xdd');
2072 }
Greg Clayton61d043b2011-03-22 04:00:09 +00002073 else if (response.IsErrorResponse())
Greg Clayton49d888d2012-12-06 22:49:16 +00002074 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton61d043b2011-03-22 04:00:09 +00002075 else if (response.IsUnsupportedResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00002076 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner24943d22010-06-08 16:52:24 +00002077 else
Greg Claytonae7bebc2012-09-19 01:46:31 +00002078 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00002079 }
2080 else
2081 {
2082 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
2083 }
2084 return 0;
2085}
2086
2087size_t
2088ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2089{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00002090 if (size > m_max_memory_size)
2091 {
2092 // Keep memory read sizes down to a sane limit. This function will be
2093 // called multiple times in order to complete the task by
2094 // lldb_private::Process so it is ok to do this.
2095 size = m_max_memory_size;
2096 }
2097
Chris Lattner24943d22010-06-08 16:52:24 +00002098 StreamString packet;
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002099 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Claytoncd548032011-02-01 01:31:41 +00002100 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00002101 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00002102 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00002103 {
Greg Clayton61d043b2011-03-22 04:00:09 +00002104 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00002105 {
2106 error.Clear();
2107 return size;
2108 }
Greg Clayton61d043b2011-03-22 04:00:09 +00002109 else if (response.IsErrorResponse())
Greg Clayton49d888d2012-12-06 22:49:16 +00002110 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton61d043b2011-03-22 04:00:09 +00002111 else if (response.IsUnsupportedResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00002112 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner24943d22010-06-08 16:52:24 +00002113 else
Greg Claytonae7bebc2012-09-19 01:46:31 +00002114 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 +00002115 }
2116 else
2117 {
2118 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
2119 }
2120 return 0;
2121}
2122
2123lldb::addr_t
2124ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2125{
Greg Clayton989816b2011-05-14 01:50:35 +00002126 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2127
Greg Clayton2f085c62011-05-15 01:25:55 +00002128 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00002129 switch (supported)
2130 {
2131 case eLazyBoolCalculate:
2132 case eLazyBoolYes:
2133 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2134 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2135 return allocated_addr;
2136
2137 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002138 // Call mmap() to create memory in the inferior..
2139 unsigned prot = 0;
2140 if (permissions & lldb::ePermissionsReadable)
2141 prot |= eMmapProtRead;
2142 if (permissions & lldb::ePermissionsWritable)
2143 prot |= eMmapProtWrite;
2144 if (permissions & lldb::ePermissionsExecutable)
2145 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00002146
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002147 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2148 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2149 m_addr_to_mmap_size[allocated_addr] = size;
2150 else
2151 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00002152 break;
2153 }
2154
Chris Lattner24943d22010-06-08 16:52:24 +00002155 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002156 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00002157 else
2158 error.Clear();
2159 return allocated_addr;
2160}
2161
2162Error
Greg Claytona9385532011-11-18 07:03:08 +00002163ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2164 MemoryRegionInfo &region_info)
2165{
2166
2167 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2168 return error;
2169}
2170
2171Error
Johnny Chen7cbdcfb2012-05-23 21:09:52 +00002172ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2173{
2174
2175 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2176 return error;
2177}
2178
2179Error
Enrico Granata7de2a3b2012-07-13 23:18:48 +00002180ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2181{
2182 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2183 return error;
2184}
2185
2186Error
Chris Lattner24943d22010-06-08 16:52:24 +00002187ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2188{
2189 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00002190 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2191
2192 switch (supported)
2193 {
2194 case eLazyBoolCalculate:
2195 // We should never be deallocating memory without allocating memory
2196 // first so we should never get eLazyBoolCalculate
2197 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2198 break;
2199
2200 case eLazyBoolYes:
2201 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002202 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00002203 break;
2204
2205 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002206 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00002207 {
2208 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002209 if (pos != m_addr_to_mmap_size.end() &&
2210 InferiorCallMunmap(this, addr, pos->second))
2211 m_addr_to_mmap_size.erase (pos);
2212 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002213 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00002214 }
2215 break;
2216 }
2217
Chris Lattner24943d22010-06-08 16:52:24 +00002218 return error;
2219}
2220
2221
2222//------------------------------------------------------------------
2223// Process STDIO
2224//------------------------------------------------------------------
Chris Lattner24943d22010-06-08 16:52:24 +00002225size_t
2226ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2227{
2228 if (m_stdio_communication.IsConnected())
2229 {
2230 ConnectionStatus status;
2231 m_stdio_communication.Write(src, src_len, status, NULL);
2232 }
2233 return 0;
2234}
2235
2236Error
2237ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
2238{
2239 Error error;
2240 assert (bp_site != NULL);
2241
Greg Claytone005f2c2010-11-06 01:53:30 +00002242 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002243 user_id_t site_id = bp_site->GetID();
2244 const addr_t addr = bp_site->GetLoadAddress();
2245 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002246 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002247
2248 if (bp_site->IsEnabled())
2249 {
2250 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002251 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %" PRIu64 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002252 return error;
2253 }
2254 else
2255 {
2256 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2257
2258 if (bp_site->HardwarePreferred())
2259 {
2260 // Try and set hardware breakpoint, and if that fails, fall through
2261 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00002262 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00002263 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002264 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00002265 {
2266 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002267 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00002268 return error;
2269 }
Chris Lattner24943d22010-06-08 16:52:24 +00002270 }
2271 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002272
2273 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00002274 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002275 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
2276 {
2277 bp_site->SetEnabled(true);
2278 bp_site->SetType (BreakpointSite::eExternal);
2279 return error;
2280 }
Chris Lattner24943d22010-06-08 16:52:24 +00002281 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002282
2283 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00002284 }
2285
2286 if (log)
2287 {
2288 const char *err_string = error.AsCString();
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002289 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8" PRIx64 ": %s",
Chris Lattner24943d22010-06-08 16:52:24 +00002290 bp_site->GetLoadAddress(),
2291 err_string ? err_string : "NULL");
2292 }
2293 // We shouldn't reach here on a successful breakpoint enable...
2294 if (error.Success())
2295 error.SetErrorToGenericError();
2296 return error;
2297}
2298
2299Error
2300ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
2301{
2302 Error error;
2303 assert (bp_site != NULL);
2304 addr_t addr = bp_site->GetLoadAddress();
2305 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00002306 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002307 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002308 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002309
2310 if (bp_site->IsEnabled())
2311 {
2312 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2313
Greg Claytonb72d0f02011-04-12 05:54:46 +00002314 BreakpointSite::Type bp_type = bp_site->GetType();
2315 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00002316 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002317 case BreakpointSite::eSoftware:
2318 error = DisableSoftwareBreakpoint (bp_site);
2319 break;
2320
2321 case BreakpointSite::eHardware:
2322 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2323 error.SetErrorToGenericError();
2324 break;
2325
2326 case BreakpointSite::eExternal:
2327 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2328 error.SetErrorToGenericError();
2329 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002330 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002331 if (error.Success())
2332 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00002333 }
2334 else
2335 {
2336 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002337 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002338 return error;
2339 }
2340
2341 if (error.Success())
2342 error.SetErrorToGenericError();
2343 return error;
2344}
2345
Johnny Chen21900fb2011-09-06 22:38:36 +00002346// Pre-requisite: wp != NULL.
2347static GDBStoppointType
Johnny Chenecd4feb2011-10-14 00:42:25 +00002348GetGDBStoppointType (Watchpoint *wp)
Johnny Chen21900fb2011-09-06 22:38:36 +00002349{
2350 assert(wp);
2351 bool watch_read = wp->WatchpointRead();
2352 bool watch_write = wp->WatchpointWrite();
2353
2354 // watch_read and watch_write cannot both be false.
2355 assert(watch_read || watch_write);
2356 if (watch_read && watch_write)
2357 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00002358 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00002359 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00002360 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00002361 return eWatchpointWrite;
2362}
2363
Chris Lattner24943d22010-06-08 16:52:24 +00002364Error
Jim Ingham9c970a32012-12-18 02:03:49 +00002365ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner24943d22010-06-08 16:52:24 +00002366{
2367 Error error;
2368 if (wp)
2369 {
2370 user_id_t watchID = wp->GetID();
2371 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00002372 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002373 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002374 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner24943d22010-06-08 16:52:24 +00002375 if (wp->IsEnabled())
2376 {
2377 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002378 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.", watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002379 return error;
2380 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002381
2382 GDBStoppointType type = GetGDBStoppointType(wp);
2383 // Pass down an appropriate z/Z packet...
2384 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00002385 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002386 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2387 {
Jim Ingham9c970a32012-12-18 02:03:49 +00002388 wp->SetEnabled(true, notify);
Johnny Chen21900fb2011-09-06 22:38:36 +00002389 return error;
2390 }
2391 else
2392 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002393 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002394 else
2395 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00002396 }
2397 else
2398 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002399 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002400 }
2401 if (error.Success())
2402 error.SetErrorToGenericError();
2403 return error;
2404}
2405
2406Error
Jim Ingham9c970a32012-12-18 02:03:49 +00002407ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner24943d22010-06-08 16:52:24 +00002408{
2409 Error error;
2410 if (wp)
2411 {
2412 user_id_t watchID = wp->GetID();
2413
Greg Claytone005f2c2010-11-06 01:53:30 +00002414 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002415
2416 addr_t addr = wp->GetLoadAddress();
Jim Ingham9c970a32012-12-18 02:03:49 +00002417
Chris Lattner24943d22010-06-08 16:52:24 +00002418 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002419 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002420
Johnny Chen21900fb2011-09-06 22:38:36 +00002421 if (!wp->IsEnabled())
2422 {
2423 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002424 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
Johnny Chen258db3a2012-08-23 22:28:26 +00002425 // See also 'class WatchpointSentry' within StopInfo.cpp.
2426 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2427 // the watchpoint object to intelligently process this action.
Jim Ingham9c970a32012-12-18 02:03:49 +00002428 wp->SetEnabled(false, notify);
Johnny Chen21900fb2011-09-06 22:38:36 +00002429 return error;
2430 }
2431
Chris Lattner24943d22010-06-08 16:52:24 +00002432 if (wp->IsHardware())
2433 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002434 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00002435 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00002436 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2437 {
Jim Ingham9c970a32012-12-18 02:03:49 +00002438 wp->SetEnabled(false, notify);
Johnny Chen21900fb2011-09-06 22:38:36 +00002439 return error;
2440 }
2441 else
2442 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002443 }
2444 // TODO: clear software watchpoints if we implement them
2445 }
2446 else
2447 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002448 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002449 }
2450 if (error.Success())
2451 error.SetErrorToGenericError();
2452 return error;
2453}
2454
2455void
2456ProcessGDBRemote::Clear()
2457{
2458 m_flags = 0;
2459 m_thread_list.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002460}
2461
2462Error
2463ProcessGDBRemote::DoSignal (int signo)
2464{
2465 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00002466 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002467 if (log)
2468 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2469
2470 if (!m_gdb_comm.SendAsyncSignal (signo))
2471 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2472 return error;
2473}
2474
Chris Lattner24943d22010-06-08 16:52:24 +00002475Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002476ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)
2477{
2478 ProcessLaunchInfo launch_info;
2479 return StartDebugserverProcess(debugserver_url, launch_info);
2480}
2481
2482Error
2483ProcessGDBRemote::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 +00002484{
2485 Error error;
2486 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2487 {
2488 // If we locate debugserver, keep that located version around
2489 static FileSpec g_debugserver_file_spec;
2490
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002491 ProcessLaunchInfo debugserver_launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002492 char debugserver_path[PATH_MAX];
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002493 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002494
2495 // Always check to see if we have an environment override for the path
2496 // to the debugserver to use and use it if we do.
2497 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2498 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002499 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002500 else
2501 debugserver_file_spec = g_debugserver_file_spec;
2502 bool debugserver_exists = debugserver_file_spec.Exists();
2503 if (!debugserver_exists)
2504 {
2505 // The debugserver binary is in the LLDB.framework/Resources
2506 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002507 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002508 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002509 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002510 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002511 if (debugserver_exists)
2512 {
2513 g_debugserver_file_spec = debugserver_file_spec;
2514 }
2515 else
2516 {
2517 g_debugserver_file_spec.Clear();
2518 debugserver_file_spec.Clear();
2519 }
Chris Lattner24943d22010-06-08 16:52:24 +00002520 }
2521 }
2522
2523 if (debugserver_exists)
2524 {
2525 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2526
2527 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002528
Greg Claytone005f2c2010-11-06 01:53:30 +00002529 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002530
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002531 Args &debugserver_args = debugserver_launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002532 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002533
Chris Lattner24943d22010-06-08 16:52:24 +00002534 // Start args with "debugserver /file/path -r --"
2535 debugserver_args.AppendArgument(debugserver_path);
2536 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002537 // use native registers, not the GDB registers
2538 debugserver_args.AppendArgument("--native-regs");
2539 // make debugserver run in its own session so signals generated by
2540 // special terminal key sequences (^C) don't affect debugserver
2541 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002542
Chris Lattner24943d22010-06-08 16:52:24 +00002543 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2544 if (env_debugserver_log_file)
2545 {
2546 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2547 debugserver_args.AppendArgument(arg_cstr);
2548 }
2549
2550 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2551 if (env_debugserver_log_flags)
2552 {
2553 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2554 debugserver_args.AppendArgument(arg_cstr);
2555 }
Jim Ingham2b2ac8c2012-10-03 22:31:30 +00002556// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
2557// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002558
Greg Claytonb72d0f02011-04-12 05:54:46 +00002559 // We currently send down all arguments, attach pids, or attach
2560 // process names in dedicated GDB server packets, so we don't need
2561 // to pass them as arguments. This is currently because of all the
2562 // things we need to setup prior to launching: the environment,
2563 // current working dir, file actions, etc.
2564#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002565 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002566 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002567 {
Greg Claytona2f74232011-02-24 22:24:29 +00002568 // Terminate the debugserver args so we can now append the inferior args
2569 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002570
Greg Claytona2f74232011-02-24 22:24:29 +00002571 for (int i = 0; inferior_argv[i] != NULL; ++i)
2572 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002573 }
2574 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2575 {
2576 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2577 debugserver_args.AppendArgument (arg_cstr);
2578 }
2579 else if (attach_name && attach_name[0])
2580 {
2581 if (wait_for_launch)
2582 debugserver_args.AppendArgument ("--waitfor");
2583 else
2584 debugserver_args.AppendArgument ("--attach");
2585 debugserver_args.AppendArgument (attach_name);
2586 }
Chris Lattner24943d22010-06-08 16:52:24 +00002587#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002588
2589 ProcessLaunchInfo::FileAction file_action;
2590
2591 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2592 // to "/dev/null" if we run into any problems.
2593 file_action.Close (STDIN_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002594 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002595 file_action.Close (STDOUT_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002596 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002597 file_action.Close (STDERR_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002598 debugserver_launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002599
2600 if (log)
2601 {
2602 StreamString strm;
2603 debugserver_args.Dump (&strm);
2604 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2605 }
2606
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002607 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2608 debugserver_launch_info.SetUserID(process_info.GetUserID());
Greg Clayton1c4642c2011-11-16 05:37:56 +00002609
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002610 error = Host::LaunchProcess(debugserver_launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002611
Greg Claytonb72d0f02011-04-12 05:54:46 +00002612 if (error.Success ())
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002613 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002614 else
Chris Lattner24943d22010-06-08 16:52:24 +00002615 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2616
2617 if (error.Fail() || log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002618 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%" PRIu64 ", path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002619 }
2620 else
2621 {
Greg Clayton9c236732011-10-26 00:56:27 +00002622 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002623 }
2624
2625 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2626 StartAsyncThread ();
2627 }
2628 return error;
2629}
2630
2631bool
2632ProcessGDBRemote::MonitorDebugserverProcess
2633(
2634 void *callback_baton,
2635 lldb::pid_t debugserver_pid,
Greg Clayton1c4642c2011-11-16 05:37:56 +00002636 bool exited, // True if the process did exit
Chris Lattner24943d22010-06-08 16:52:24 +00002637 int signo, // Zero for no signal
2638 int exit_status // Exit value of process if signal is zero
2639)
2640{
Greg Clayton1c4642c2011-11-16 05:37:56 +00002641 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2642 // and might not exist anymore, so we need to carefully try to get the
2643 // target for this process first since we have a race condition when
2644 // we are done running between getting the notice that the inferior
2645 // process has died and the debugserver that was debugging this process.
2646 // In our test suite, we are also continually running process after
2647 // process, so we must be very careful to make sure:
2648 // 1 - process object hasn't been deleted already
2649 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner24943d22010-06-08 16:52:24 +00002650
2651 // "debugserver_pid" argument passed in is the process ID for
2652 // debugserver that we are tracking...
Greg Clayton1c4642c2011-11-16 05:37:56 +00002653 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002654
Greg Clayton75ccf502010-08-21 02:22:51 +00002655 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002656
Greg Clayton1c4642c2011-11-16 05:37:56 +00002657 // Get a shared pointer to the target that has a matching process pointer.
2658 // This target could be gone, or the target could already have a new process
2659 // object inside of it
2660 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2661
Greg Clayton72e1c782011-01-22 23:43:18 +00002662 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002663 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%" PRIu64 ", signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
Greg Clayton72e1c782011-01-22 23:43:18 +00002664
Greg Clayton1c4642c2011-11-16 05:37:56 +00002665 if (target_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002666 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002667 // We found a process in a target that matches, but another thread
2668 // might be in the process of launching a new process that will
2669 // soon replace it, so get a shared pointer to the process so we
2670 // can keep it alive.
2671 ProcessSP process_sp (target_sp->GetProcessSP());
2672 // Now we have a shared pointer to the process that can't go away on us
2673 // so we now make sure it was the same as the one passed in, and also make
2674 // sure that our previous "process *" didn't get deleted and have a new
2675 // "process *" created in its place with the same pointer. To verify this
2676 // we make sure the process has our debugserver process ID. If we pass all
2677 // of these tests, then we are sure that this process is the one we were
2678 // looking for.
2679 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner24943d22010-06-08 16:52:24 +00002680 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002681 // Sleep for a half a second to make sure our inferior process has
2682 // time to set its exit status before we set it incorrectly when
2683 // both the debugserver and the inferior process shut down.
2684 usleep (500000);
2685 // If our process hasn't yet exited, debugserver might have died.
2686 // If the process did exit, the we are reaping it.
2687 const StateType state = process->GetState();
2688
2689 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2690 state != eStateInvalid &&
2691 state != eStateUnloaded &&
2692 state != eStateExited &&
2693 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002694 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002695 char error_str[1024];
2696 if (signo)
2697 {
2698 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2699 if (signal_cstr)
2700 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2701 else
2702 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2703 }
Chris Lattner24943d22010-06-08 16:52:24 +00002704 else
Greg Clayton1c4642c2011-11-16 05:37:56 +00002705 {
2706 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2707 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002708
Greg Clayton1c4642c2011-11-16 05:37:56 +00002709 process->SetExitStatus (-1, error_str);
2710 }
2711 // Debugserver has exited we need to let our ProcessGDBRemote
2712 // know that it no longer has a debugserver instance
2713 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton75ccf502010-08-21 02:22:51 +00002714 }
Chris Lattner24943d22010-06-08 16:52:24 +00002715 }
2716 return true;
2717}
2718
2719void
2720ProcessGDBRemote::KillDebugserverProcess ()
2721{
2722 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2723 {
2724 ::kill (m_debugserver_pid, SIGINT);
2725 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2726 }
2727}
2728
2729void
2730ProcessGDBRemote::Initialize()
2731{
2732 static bool g_initialized = false;
2733
2734 if (g_initialized == false)
2735 {
2736 g_initialized = true;
2737 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2738 GetPluginDescriptionStatic(),
2739 CreateInstance);
2740
2741 Log::Callbacks log_callbacks = {
2742 ProcessGDBRemoteLog::DisableLog,
2743 ProcessGDBRemoteLog::EnableLog,
2744 ProcessGDBRemoteLog::ListLogCategories
2745 };
2746
2747 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2748 }
2749}
2750
2751bool
Chris Lattner24943d22010-06-08 16:52:24 +00002752ProcessGDBRemote::StartAsyncThread ()
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__);
Jim Inghama9488302012-11-01 01:15:33 +00002758
2759 Mutex::Locker start_locker(m_async_thread_state_mutex);
2760 if (m_async_thread_state == eAsyncThreadNotStarted)
2761 {
2762 // Create a thread that watches our internal state and controls which
2763 // events make it to clients (into the DCProcess event queue).
2764 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2765 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2766 {
2767 m_async_thread_state = eAsyncThreadRunning;
2768 return true;
2769 }
2770 else
2771 return false;
2772 }
2773 else
2774 {
2775 // Somebody tried to start the async thread while it was either being started or stopped. If the former, and
2776 // it started up successfully, then say all's well. Otherwise it is an error, since we aren't going to restart it.
2777 if (log)
2778 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
2779 if (m_async_thread_state == eAsyncThreadRunning)
2780 return true;
2781 else
2782 return false;
2783 }
Chris Lattner24943d22010-06-08 16:52:24 +00002784}
2785
2786void
2787ProcessGDBRemote::StopAsyncThread ()
2788{
Greg Claytone005f2c2010-11-06 01:53:30 +00002789 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002790
2791 if (log)
2792 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2793
Jim Inghama9488302012-11-01 01:15:33 +00002794 Mutex::Locker start_locker(m_async_thread_state_mutex);
2795 if (m_async_thread_state == eAsyncThreadRunning)
Chris Lattner24943d22010-06-08 16:52:24 +00002796 {
Jim Inghama9488302012-11-01 01:15:33 +00002797 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2798
2799 // This will shut down the async thread.
2800 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
2801
2802 // Stop the stdio thread
2803 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2804 {
2805 Host::ThreadJoin (m_async_thread, NULL, NULL);
2806 }
2807 m_async_thread_state = eAsyncThreadDone;
2808 }
2809 else
2810 {
2811 if (log)
2812 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
Chris Lattner24943d22010-06-08 16:52:24 +00002813 }
2814}
2815
2816
2817void *
2818ProcessGDBRemote::AsyncThread (void *arg)
2819{
2820 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2821
Greg Claytone005f2c2010-11-06 01:53:30 +00002822 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002823 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002824 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002825
2826 Listener listener ("ProcessGDBRemote::AsyncThread");
2827 EventSP event_sp;
2828 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2829 eBroadcastBitAsyncThreadShouldExit;
2830
2831 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2832 {
Greg Claytona2f74232011-02-24 22:24:29 +00002833 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2834
Chris Lattner24943d22010-06-08 16:52:24 +00002835 bool done = false;
2836 while (!done)
2837 {
2838 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002839 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002840 if (listener.WaitForEvent (NULL, event_sp))
2841 {
2842 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002843 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002844 {
Greg Claytona2f74232011-02-24 22:24:29 +00002845 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002846 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
Chris Lattner24943d22010-06-08 16:52:24 +00002847
Greg Claytona2f74232011-02-24 22:24:29 +00002848 switch (event_type)
2849 {
2850 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002851 {
Greg Claytona2f74232011-02-24 22:24:29 +00002852 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002853
Greg Claytona2f74232011-02-24 22:24:29 +00002854 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002855 {
Greg Claytona2f74232011-02-24 22:24:29 +00002856 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2857 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2858 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002859 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002860
Greg Claytona2f74232011-02-24 22:24:29 +00002861 if (::strstr (continue_cstr, "vAttach") == NULL)
2862 process->SetPrivateState(eStateRunning);
2863 StringExtractorGDBRemote response;
2864 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002865
Greg Clayton67b402c2012-05-16 02:48:06 +00002866 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
2867 // The thread ID list might be contained within the "response", or the stop reply packet that
2868 // caused the stop. So clear it now before we give the stop reply packet to the process
2869 // using the process->SetLastStopPacket()...
2870 process->ClearThreadIDList ();
2871
Greg Claytona2f74232011-02-24 22:24:29 +00002872 switch (stop_state)
2873 {
2874 case eStateStopped:
2875 case eStateCrashed:
2876 case eStateSuspended:
Greg Clayton06709002011-12-06 04:51:14 +00002877 process->SetLastStopPacket (response);
Greg Claytona2f74232011-02-24 22:24:29 +00002878 process->SetPrivateState (stop_state);
2879 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002880
Greg Claytona2f74232011-02-24 22:24:29 +00002881 case eStateExited:
Greg Clayton06709002011-12-06 04:51:14 +00002882 process->SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00002883 process->ClearThreadIDList();
Greg Claytona2f74232011-02-24 22:24:29 +00002884 response.SetFilePos(1);
2885 process->SetExitStatus(response.GetHexU8(), NULL);
2886 done = true;
2887 break;
2888
2889 case eStateInvalid:
2890 process->SetExitStatus(-1, "lost connection");
2891 break;
2892
2893 default:
2894 process->SetPrivateState (stop_state);
2895 break;
2896 }
Chris Lattner24943d22010-06-08 16:52:24 +00002897 }
2898 }
Greg Claytona2f74232011-02-24 22:24:29 +00002899 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002900
Greg Claytona2f74232011-02-24 22:24:29 +00002901 case eBroadcastBitAsyncThreadShouldExit:
2902 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002903 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Claytona2f74232011-02-24 22:24:29 +00002904 done = true;
2905 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002906
Greg Claytona2f74232011-02-24 22:24:29 +00002907 default:
2908 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002909 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
Greg Claytona2f74232011-02-24 22:24:29 +00002910 done = true;
2911 break;
2912 }
2913 }
2914 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2915 {
2916 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2917 {
2918 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002919 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002920 }
Chris Lattner24943d22010-06-08 16:52:24 +00002921 }
2922 }
2923 else
2924 {
2925 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002926 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002927 done = true;
2928 }
2929 }
2930 }
2931
2932 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002933 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002934
2935 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2936 return NULL;
2937}
2938
Chris Lattner24943d22010-06-08 16:52:24 +00002939const char *
2940ProcessGDBRemote::GetDispatchQueueNameForThread
2941(
2942 addr_t thread_dispatch_qaddr,
2943 std::string &dispatch_queue_name
2944)
2945{
2946 dispatch_queue_name.clear();
2947 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2948 {
2949 // Cache the dispatch_queue_offsets_addr value so we don't always have
2950 // to look it up
2951 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2952 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002953 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2954 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton444fe992012-02-26 05:51:37 +00002955 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false));
2956 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002957 if (module_sp)
2958 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2959
2960 if (dispatch_queue_offsets_symbol == NULL)
2961 {
Greg Clayton444fe992012-02-26 05:51:37 +00002962 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false));
2963 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_module_spec);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002964 if (module_sp)
2965 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2966 }
Chris Lattner24943d22010-06-08 16:52:24 +00002967 if (dispatch_queue_offsets_symbol)
Greg Clayton0c31d3d2012-03-07 21:03:09 +00002968 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002969
2970 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2971 return NULL;
2972 }
2973
2974 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002975 DataExtractor data (memory_buffer,
2976 sizeof(memory_buffer),
2977 m_target.GetArchitecture().GetByteOrder(),
2978 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002979
2980 // Excerpt from src/queue_private.h
2981 struct dispatch_queue_offsets_s
2982 {
2983 uint16_t dqo_version;
Jason Molenda9704ca22012-11-10 06:54:30 +00002984 uint16_t dqo_label; // in version 1-3, offset to string; in version 4+, offset to a pointer to a string
2985 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 +00002986 } dispatch_queue_offsets;
2987
2988
2989 Error error;
2990 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2991 {
2992 uint32_t data_offset = 0;
2993 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2994 {
2995 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2996 {
2997 data_offset = 0;
2998 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
Jason Molenda9704ca22012-11-10 06:54:30 +00002999 if (dispatch_queue_offsets.dqo_version >= 4)
3000 {
3001 // libdispatch versions 4+, pointer to dispatch name is in the
3002 // queue structure.
3003 lldb::addr_t pointer_to_label_address = queue_addr + dispatch_queue_offsets.dqo_label;
3004 if (ReadMemory (pointer_to_label_address, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
3005 {
3006 data_offset = 0;
3007 lldb::addr_t label_addr = data.GetAddress(&data_offset);
3008 ReadCStringFromMemory (label_addr, dispatch_queue_name, error);
3009 }
3010 }
3011 else
3012 {
3013 // libdispatch versions 1-3, dispatch name is a fixed width char array
3014 // in the queue structure.
3015 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
3016 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
3017 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
3018 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
3019 dispatch_queue_name.erase (bytes_read);
3020 }
Chris Lattner24943d22010-06-08 16:52:24 +00003021 }
3022 }
3023 }
3024 }
3025 if (dispatch_queue_name.empty())
3026 return NULL;
3027 return dispatch_queue_name.c_str();
3028}
3029
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003030//uint32_t
3031//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3032//{
3033// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
3034// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
3035// if (m_local_debugserver)
3036// {
3037// return Host::ListProcessesMatchingName (name, matches, pids);
3038// }
3039// else
3040// {
3041// // FIXME: Implement talking to the remote debugserver.
3042// return 0;
3043// }
3044//
3045//}
3046//
Jim Ingham55e01d82011-01-22 01:33:44 +00003047bool
3048ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
3049 lldb_private::StoppointCallbackContext *context,
3050 lldb::user_id_t break_id,
3051 lldb::user_id_t break_loc_id)
3052{
3053 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3054 // run so I can stop it if that's what I want to do.
3055 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
3056 if (log)
3057 log->Printf("Hit New Thread Notification breakpoint.");
3058 return false;
3059}
3060
3061
3062bool
3063ProcessGDBRemote::StartNoticingNewThreads()
3064{
Jim Ingham55e01d82011-01-22 01:33:44 +00003065 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003066 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00003067 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003068 if (log && log->GetVerbose())
3069 log->Printf("Enabled noticing new thread breakpoint.");
3070 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham55e01d82011-01-22 01:33:44 +00003071 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003072 else
Jim Ingham55e01d82011-01-22 01:33:44 +00003073 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003074 PlatformSP platform_sp (m_target.GetPlatform());
3075 if (platform_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00003076 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003077 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3078 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00003079 {
Jim Ingham6bb73372011-10-15 00:21:37 +00003080 if (log && log->GetVerbose())
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003081 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3082 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham55e01d82011-01-22 01:33:44 +00003083 }
3084 else
3085 {
3086 if (log)
3087 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00003088 }
3089 }
3090 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003091 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham55e01d82011-01-22 01:33:44 +00003092}
3093
3094bool
3095ProcessGDBRemote::StopNoticingNewThreads()
3096{
Jim Inghamff276fe2011-02-08 05:19:01 +00003097 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham6bb73372011-10-15 00:21:37 +00003098 if (log && log->GetVerbose())
Jim Inghamff276fe2011-02-08 05:19:01 +00003099 log->Printf ("Disabling new thread notification breakpoint.");
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003100
3101 if (m_thread_create_bp_sp)
3102 m_thread_create_bp_sp->SetEnabled(false);
3103
Jim Ingham55e01d82011-01-22 01:33:44 +00003104 return true;
3105}
3106
Jason Molendab46937c2012-10-03 01:29:34 +00003107lldb_private::DynamicLoader *
3108ProcessGDBRemote::GetDynamicLoader ()
3109{
3110 if (m_dyld_ap.get() == NULL)
3111 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, m_dyld_plugin_name.empty() ? NULL : m_dyld_plugin_name.c_str()));
3112 return m_dyld_ap.get();
3113}
Jim Ingham55e01d82011-01-22 01:33:44 +00003114
Greg Clayton13193d52012-10-13 02:07:45 +00003115
Greg Claytonb8596392012-10-15 22:42:16 +00003116class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton13193d52012-10-13 02:07:45 +00003117{
3118private:
3119
3120public:
Greg Claytonb8596392012-10-15 22:42:16 +00003121 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton13193d52012-10-13 02:07:45 +00003122 CommandObjectParsed (interpreter,
Greg Claytonb8596392012-10-15 22:42:16 +00003123 "process plugin packet history",
3124 "Dumps the packet history buffer. ",
Greg Clayton13193d52012-10-13 02:07:45 +00003125 NULL)
3126 {
3127 }
3128
Greg Claytonb8596392012-10-15 22:42:16 +00003129 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton13193d52012-10-13 02:07:45 +00003130 {
3131 }
3132
3133 bool
3134 DoExecute (Args& command, CommandReturnObject &result)
3135 {
Greg Claytonb8596392012-10-15 22:42:16 +00003136 const size_t argc = command.GetArgumentCount();
3137 if (argc == 0)
3138 {
3139 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3140 if (process)
3141 {
3142 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
3143 result.SetStatus (eReturnStatusSuccessFinishResult);
3144 return true;
3145 }
3146 }
3147 else
3148 {
3149 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
3150 }
3151 result.SetStatus (eReturnStatusFailed);
3152 return false;
3153 }
3154};
3155
3156class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
3157{
3158private:
3159
3160public:
3161 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
3162 CommandObjectParsed (interpreter,
3163 "process plugin packet send",
3164 "Send a custom packet through the GDB remote protocol and print the answer. "
3165 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
3166 NULL)
3167 {
3168 }
3169
3170 ~CommandObjectProcessGDBRemotePacketSend ()
3171 {
3172 }
3173
3174 bool
3175 DoExecute (Args& command, CommandReturnObject &result)
3176 {
3177 const size_t argc = command.GetArgumentCount();
3178 if (argc == 0)
3179 {
3180 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
3181 result.SetStatus (eReturnStatusFailed);
3182 return false;
3183 }
3184
3185 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3186 if (process)
3187 {
Han Ming Ongae9cc552012-11-26 20:42:03 +00003188 for (size_t i=0; i<argc; ++ i)
Greg Claytonb8596392012-10-15 22:42:16 +00003189 {
Han Ming Ongae9cc552012-11-26 20:42:03 +00003190 const char *packet_cstr = command.GetArgumentAtIndex(0);
3191 bool send_async = true;
3192 StringExtractorGDBRemote response;
3193 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3194 result.SetStatus (eReturnStatusSuccessFinishResult);
3195 Stream &output_strm = result.GetOutputStream();
3196 output_strm.Printf (" packet: %s\n", packet_cstr);
3197 const std::string &response_str = response.GetStringRef();
3198 if (response_str.empty())
3199 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3200 else
3201 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Claytonb8596392012-10-15 22:42:16 +00003202 }
Greg Claytonb8596392012-10-15 22:42:16 +00003203 }
Greg Clayton13193d52012-10-13 02:07:45 +00003204 return true;
3205 }
3206};
3207
Greg Claytonb8596392012-10-15 22:42:16 +00003208class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
3209{
3210private:
3211
3212public:
3213 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
3214 CommandObjectMultiword (interpreter,
3215 "process plugin packet",
3216 "Commands that deal with GDB remote packets.",
3217 NULL)
3218 {
3219 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
3220 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
3221 }
3222
3223 ~CommandObjectProcessGDBRemotePacket ()
3224 {
3225 }
3226};
Greg Clayton13193d52012-10-13 02:07:45 +00003227
3228class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
3229{
3230public:
3231 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
3232 CommandObjectMultiword (interpreter,
3233 "process plugin",
3234 "A set of commands for operating on a ProcessGDBRemote process.",
3235 "process plugin <subcommand> [<subcommand-options>]")
3236 {
3237 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
3238 }
3239
3240 ~CommandObjectMultiwordProcessGDBRemote ()
3241 {
3242 }
3243};
3244
Greg Clayton13193d52012-10-13 02:07:45 +00003245CommandObject *
3246ProcessGDBRemote::GetPluginCommandObject()
3247{
3248 if (!m_command_sp)
3249 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
3250 return m_command_sp.get();
3251}