blob: 9269c267d7ec1e587fef1a8781dd0144b4c88546 [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();
396 const ArchSpec &remote_arch = m_gdb_comm.GetHostArchitecture();
397 if (!target_arch.IsValid())
Chris Lattner24943d22010-06-08 16:52:24 +0000398 {
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000399 if (remote_arch.IsValid()
400 && remote_arch.GetMachine() == llvm::Triple::arm
401 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
402 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner24943d22010-06-08 16:52:24 +0000403 }
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000404 else if (target_arch.GetMachine() == llvm::Triple::arm)
405 {
406 m_register_info.HardcodeARMRegisters(from_scratch);
407 }
408
Johnny Chend2e30662012-05-22 00:57:05 +0000409 // Add some convenience registers (eax, ebx, ecx, edx, esi, edi, ebp, esp) to x86_64.
Johnny Chenbe315a62012-06-08 19:06:28 +0000410 if ((target_arch.IsValid() && target_arch.GetMachine() == llvm::Triple::x86_64)
411 || (remote_arch.IsValid() && remote_arch.GetMachine() == llvm::Triple::x86_64))
Johnny Chend2e30662012-05-22 00:57:05 +0000412 m_register_info.Addx86_64ConvenienceRegisters();
413
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000414 // At this point, we can finalize our register info.
Chris Lattner24943d22010-06-08 16:52:24 +0000415 m_register_info.Finalize ();
416}
417
418Error
419ProcessGDBRemote::WillLaunch (Module* module)
420{
421 return WillLaunchOrAttach ();
422}
423
424Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000425ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000426{
427 return WillLaunchOrAttach ();
428}
429
430Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000431ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000432{
433 return WillLaunchOrAttach ();
434}
435
436Error
Jason Molendafac2e622012-09-29 04:02:01 +0000437ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytone71e2582011-02-04 01:58:07 +0000438{
439 Error error (WillLaunchOrAttach ());
440
441 if (error.Fail())
442 return error;
443
Greg Clayton180546b2011-04-30 01:09:13 +0000444 error = ConnectToDebugserver (remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000445
446 if (error.Fail())
447 return error;
448 StartAsyncThread ();
449
Jason Molendab46937c2012-10-03 01:29:34 +0000450 CheckForKernel (strm);
Jason Molendafac2e622012-09-29 04:02:01 +0000451
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000452 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000453 if (pid == LLDB_INVALID_PROCESS_ID)
454 {
455 // We don't have a valid process ID, so note that we are connected
456 // and could now request to launch or attach, or get remote process
457 // listings...
458 SetPrivateState (eStateConnected);
459 }
460 else
461 {
462 // We have a valid process
463 SetID (pid);
Greg Clayton37f962e2011-08-22 02:49:39 +0000464 GetThreadList();
Greg Clayton261a18b2011-06-02 22:22:38 +0000465 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000466 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000467 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytone71e2582011-02-04 01:58:07 +0000468 if (state == eStateStopped)
469 {
470 SetPrivateState (state);
471 }
472 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000473 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 +0000474 }
475 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000476 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 +0000477 }
Jason Molendacb740b32012-05-03 22:37:30 +0000478
479 if (error.Success()
480 && !GetTarget().GetArchitecture().IsValid()
481 && m_gdb_comm.GetHostArchitecture().IsValid())
482 {
483 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
484 }
485
Greg Claytone71e2582011-02-04 01:58:07 +0000486 return error;
487}
488
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000489// When we are establishing a connection to a remote system and we have no executable specified,
490// or the executable is a kernel, we may be looking at a KASLR situation (where the kernel has been
491// slid in memory.)
492//
Jason Molendab46937c2012-10-03 01:29:34 +0000493// This function tries to locate the kernel in memory if this is possibly a kernel debug session.
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000494//
Jason Molendab46937c2012-10-03 01:29:34 +0000495// If a kernel is found, return the address of the kernel in GetImageInfoAddress() -- the
496// DynamicLoaderDarwinKernel plugin uses this address as the kernel load address and will load the
497// binary, if needed, along with all the kexts.
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000498
499void
Jason Molendab46937c2012-10-03 01:29:34 +0000500ProcessGDBRemote::CheckForKernel (Stream *strm)
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000501{
502 // early return if this isn't an "unknown" system (kernel debugging doesn't have a system type)
503 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
504 if (!gdb_remote_arch.IsValid() || gdb_remote_arch.GetTriple().getVendor() != llvm::Triple::UnknownVendor)
505 return;
506
507 Module *exe_module = GetTarget().GetExecutableModulePointer();
508 ObjectFile *exe_objfile = NULL;
509 if (exe_module)
510 exe_objfile = exe_module->GetObjectFile();
511
512 // early return if we have an executable and it is not a kernel--this is very unlikely to be a kernel debug session.
513 if (exe_objfile
514 && (exe_objfile->GetType() != ObjectFile::eTypeExecutable
515 || exe_objfile->GetStrata() != ObjectFile::eStrataKernel))
516 return;
517
518 // See if the kernel is in memory at the File address (slide == 0) -- no work needed, if so.
519 if (exe_objfile && exe_objfile->GetHeaderAddress().IsValid())
520 {
521 ModuleSP memory_module_sp;
522 memory_module_sp = ReadModuleFromMemory (exe_module->GetFileSpec(), exe_objfile->GetHeaderAddress().GetFileAddress(), false, false);
523 if (memory_module_sp.get()
524 && memory_module_sp->GetUUID().IsValid()
525 && memory_module_sp->GetUUID() == exe_module->GetUUID())
526 {
Jason Molendab46937c2012-10-03 01:29:34 +0000527 m_kernel_load_addr = exe_objfile->GetHeaderAddress().GetFileAddress();
528 m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
Jason Molendad6b81222012-10-06 02:02:26 +0000529 SetCanJIT(false);
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000530 return;
531 }
532 }
533
534 // See if the kernel's load address is stored in the kernel's low globals page; this is
535 // done when a debug boot-arg has been set.
536
537 Error error;
538 uint8_t buf[24];
539 ModuleSP memory_module_sp;
540 addr_t kernel_addr = LLDB_INVALID_ADDRESS;
541
542 // First try the 32-bit
543 if (memory_module_sp.get() == NULL)
544 {
545 DataExtractor data4 (buf, sizeof(buf), gdb_remote_arch.GetByteOrder(), 4);
546 if (DoReadMemory (0xffff0110, buf, 4, error) == 4)
547 {
548 uint32_t offset = 0;
549 kernel_addr = data4.GetU32(&offset);
550 memory_module_sp = ReadModuleFromMemory (FileSpec("mach_kernel", false), kernel_addr, false, false);
551 if (!memory_module_sp.get()
552 || !memory_module_sp->GetUUID().IsValid()
553 || memory_module_sp->GetObjectFile() == NULL
554 || memory_module_sp->GetObjectFile()->GetType() != ObjectFile::eTypeExecutable
555 || memory_module_sp->GetObjectFile()->GetStrata() != ObjectFile::eStrataKernel)
556 {
557 memory_module_sp.reset();
558 }
559 }
560 }
561
562 // Now try the 64-bit location
563 if (memory_module_sp.get() == NULL)
564 {
565 DataExtractor data8 (buf, sizeof(buf), gdb_remote_arch.GetByteOrder(), 8);
566 if (DoReadMemory (0xffffff8000002010ULL, buf, 8, error) == 8)
567 {
568 uint32_t offset = 0;
Jason Molendac557e7d2012-12-01 04:46:58 +0000569 kernel_addr = data8.GetU64(&offset);
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000570 memory_module_sp = ReadModuleFromMemory (FileSpec("mach_kernel", false), kernel_addr, false, false);
571 if (!memory_module_sp.get()
572 || !memory_module_sp->GetUUID().IsValid()
573 || memory_module_sp->GetObjectFile() == NULL
574 || memory_module_sp->GetObjectFile()->GetType() != ObjectFile::eTypeExecutable
575 || memory_module_sp->GetObjectFile()->GetStrata() != ObjectFile::eStrataKernel)
576 {
577 memory_module_sp.reset();
578 }
579 }
580 }
581
Jason Molendab46937c2012-10-03 01:29:34 +0000582 if (memory_module_sp.get()
583 && memory_module_sp->GetArchitecture().IsValid()
584 && memory_module_sp->GetArchitecture().GetTriple().getVendor() == llvm::Triple::Apple)
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000585 {
Jason Molendab46937c2012-10-03 01:29:34 +0000586 m_kernel_load_addr = kernel_addr;
587 m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
Jason Molendad6b81222012-10-06 02:02:26 +0000588 SetCanJIT(false);
Jason Molendab46937c2012-10-03 01:29:34 +0000589 return;
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000590 }
591}
592
Greg Claytone71e2582011-02-04 01:58:07 +0000593Error
Chris Lattner24943d22010-06-08 16:52:24 +0000594ProcessGDBRemote::WillLaunchOrAttach ()
595{
596 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000597 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000598 return error;
599}
600
601//----------------------------------------------------------------------
602// Process Control
603//----------------------------------------------------------------------
604Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000605ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000606{
Greg Clayton4b407112010-09-30 21:49:03 +0000607 Error error;
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000608
609 uint32_t launch_flags = launch_info.GetFlags().Get();
610 const char *stdin_path = NULL;
611 const char *stdout_path = NULL;
612 const char *stderr_path = NULL;
613 const char *working_dir = launch_info.GetWorkingDirectory();
614
615 const ProcessLaunchInfo::FileAction *file_action;
616 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
617 if (file_action)
618 {
619 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
620 stdin_path = file_action->GetPath();
621 }
622 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
623 if (file_action)
624 {
625 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
626 stdout_path = file_action->GetPath();
627 }
628 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
629 if (file_action)
630 {
631 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
632 stderr_path = file_action->GetPath();
633 }
634
Chris Lattner24943d22010-06-08 16:52:24 +0000635 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
636 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
637 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton716cefb2011-08-09 05:20:29 +0000638 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000639
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000640 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner24943d22010-06-08 16:52:24 +0000641 if (object_file)
642 {
Chris Lattner24943d22010-06-08 16:52:24 +0000643 char host_port[128];
644 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000645 char connect_url[128];
646 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000647
Greg Claytona2f74232011-02-24 22:24:29 +0000648 // Make sure we aren't already connected?
649 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000650 {
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000651 error = StartDebugserverProcess (host_port, launch_info);
Chris Lattner24943d22010-06-08 16:52:24 +0000652 if (error.Fail())
Greg Clayton716cefb2011-08-09 05:20:29 +0000653 {
Johnny Chenc143d622011-08-09 18:56:45 +0000654 if (log)
655 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner24943d22010-06-08 16:52:24 +0000656 return error;
Greg Clayton716cefb2011-08-09 05:20:29 +0000657 }
Chris Lattner24943d22010-06-08 16:52:24 +0000658
Greg Claytone71e2582011-02-04 01:58:07 +0000659 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000660 }
661
662 if (error.Success())
663 {
664 lldb_utility::PseudoTerminal pty;
665 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000666
667 // If the debugserver is local and we aren't disabling STDIO, lets use
668 // a pseudo terminal to instead of relying on the 'O' packets for stdio
669 // since 'O' packets can really slow down debugging if the inferior
670 // does a lot of output.
Greg Claytonb4747822011-06-24 22:32:10 +0000671 PlatformSP platform_sp (m_target.GetPlatform());
672 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000673 {
674 const char *slave_name = NULL;
675 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000676 {
Greg Claytona2f74232011-02-24 22:24:29 +0000677 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
678 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000679 }
Greg Claytona2f74232011-02-24 22:24:29 +0000680 if (stdin_path == NULL)
681 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000682
Greg Claytona2f74232011-02-24 22:24:29 +0000683 if (stdout_path == NULL)
684 stdout_path = slave_name;
685
686 if (stderr_path == NULL)
687 stderr_path = slave_name;
688 }
689
Greg Claytonafb81862011-03-02 21:34:46 +0000690 // Set STDIN to /dev/null if we want STDIO disabled or if either
691 // STDOUT or STDERR have been set to something and STDIN hasn't
692 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000693 stdin_path = "/dev/null";
694
Greg Claytonafb81862011-03-02 21:34:46 +0000695 // Set STDOUT to /dev/null if we want STDIO disabled or if either
696 // STDIN or STDERR have been set to something and STDOUT hasn't
697 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000698 stdout_path = "/dev/null";
699
Greg Claytonafb81862011-03-02 21:34:46 +0000700 // Set STDERR to /dev/null if we want STDIO disabled or if either
701 // STDIN or STDOUT have been set to something and STDERR hasn't
702 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000703 stderr_path = "/dev/null";
704
705 if (stdin_path)
706 m_gdb_comm.SetSTDIN (stdin_path);
707 if (stdout_path)
708 m_gdb_comm.SetSTDOUT (stdout_path);
709 if (stderr_path)
710 m_gdb_comm.SetSTDERR (stderr_path);
711
712 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
713
Greg Claytona4582402011-05-08 04:53:50 +0000714 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000715
716 if (working_dir && working_dir[0])
717 {
718 m_gdb_comm.SetWorkingDir (working_dir);
719 }
720
721 // Send the environment and the program + arguments after we connect
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000722 const Args &environment = launch_info.GetEnvironmentEntries();
723 if (environment.GetArgumentCount())
Greg Claytona2f74232011-02-24 22:24:29 +0000724 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000725 size_t num_environment_entries = environment.GetArgumentCount();
726 for (size_t i=0; i<num_environment_entries; ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000727 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000728 const char *env_entry = environment.GetArgumentAtIndex(i);
729 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000730 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000731 }
Greg Claytona2f74232011-02-24 22:24:29 +0000732 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000733
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000734 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000735 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info.GetArguments().GetConstArgumentVector());
Greg Claytona2f74232011-02-24 22:24:29 +0000736 if (arg_packet_err == 0)
737 {
738 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000739 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000740 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000741 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000742 }
743 else
744 {
Greg Claytona2f74232011-02-24 22:24:29 +0000745 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000746 }
Greg Claytona2f74232011-02-24 22:24:29 +0000747 }
748 else
749 {
Greg Clayton9c236732011-10-26 00:56:27 +0000750 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Claytona2f74232011-02-24 22:24:29 +0000751 }
Greg Clayton7c4fc6e2011-08-10 22:05:39 +0000752
753 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner24943d22010-06-08 16:52:24 +0000754
Greg Claytona2f74232011-02-24 22:24:29 +0000755 if (GetID() == LLDB_INVALID_PROCESS_ID)
756 {
Johnny Chenc143d622011-08-09 18:56:45 +0000757 if (log)
758 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytona2f74232011-02-24 22:24:29 +0000759 KillDebugserverProcess ();
760 return error;
761 }
762
Greg Clayton261a18b2011-06-02 22:22:38 +0000763 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000764 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000765 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Claytona2f74232011-02-24 22:24:29 +0000766
767 if (!disable_stdio)
768 {
769 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Clayton464c6162011-11-17 22:14:31 +0000770 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Claytona2f74232011-02-24 22:24:29 +0000771 }
Chris Lattner24943d22010-06-08 16:52:24 +0000772 }
773 }
Greg Clayton716cefb2011-08-09 05:20:29 +0000774 else
775 {
Johnny Chenc143d622011-08-09 18:56:45 +0000776 if (log)
777 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton716cefb2011-08-09 05:20:29 +0000778 }
Chris Lattner24943d22010-06-08 16:52:24 +0000779 }
780 else
781 {
782 // Set our user ID to an invalid process ID.
783 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000784 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
785 exe_module->GetFileSpec().GetFilename().AsCString(),
786 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000787 }
Chris Lattner24943d22010-06-08 16:52:24 +0000788 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000789
Chris Lattner24943d22010-06-08 16:52:24 +0000790}
791
792
793Error
Greg Claytone71e2582011-02-04 01:58:07 +0000794ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000795{
796 Error error;
797 // Sleep and wait a bit for debugserver to start to listen...
798 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
799 if (conn_ap.get())
800 {
Chris Lattner24943d22010-06-08 16:52:24 +0000801 const uint32_t max_retry_count = 50;
802 uint32_t retry_count = 0;
803 while (!m_gdb_comm.IsConnected())
804 {
Greg Claytone71e2582011-02-04 01:58:07 +0000805 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000806 {
807 m_gdb_comm.SetConnection (conn_ap.release());
808 break;
809 }
810 retry_count++;
811
812 if (retry_count >= max_retry_count)
813 break;
814
815 usleep (100000);
816 }
817 }
818
819 if (!m_gdb_comm.IsConnected())
820 {
821 if (error.Success())
822 error.SetErrorString("not connected to remote gdb server");
823 return error;
824 }
825
Greg Clayton24bc5d92011-03-30 18:16:51 +0000826 // We always seem to be able to open a connection to a local port
827 // so we need to make sure we can then send data to it. If we can't
828 // then we aren't actually connected to anything, so try and do the
829 // handshake with the remote GDB server and make sure that goes
830 // alright.
831 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000832 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000833 m_gdb_comm.Disconnect();
834 if (error.Success())
835 error.SetErrorString("not connected to remote gdb server");
836 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000837 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000838 m_gdb_comm.ResetDiscoverableSettings();
839 m_gdb_comm.QueryNoAckModeSupported ();
840 m_gdb_comm.GetThreadSuffixSupported ();
Greg Claytona1f645e2012-04-10 03:22:03 +0000841 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000842 m_gdb_comm.GetHostInfo ();
843 m_gdb_comm.GetVContSupported ('c');
Jim Ingham3a458eb2012-07-20 21:37:13 +0000844 m_gdb_comm.GetVAttachOrWaitSupported();
Jim Ingham86827fb2012-07-02 05:40:07 +0000845
846 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
847 for (size_t idx = 0; idx < num_cmds; idx++)
848 {
849 StringExtractorGDBRemote response;
Jim Ingham86827fb2012-07-02 05:40:07 +0000850 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
851 }
Chris Lattner24943d22010-06-08 16:52:24 +0000852 return error;
853}
854
855void
856ProcessGDBRemote::DidLaunchOrAttach ()
857{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000858 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
859 if (log)
860 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000861 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000862 {
863 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
864
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000865 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000866
Chris Lattner24943d22010-06-08 16:52:24 +0000867 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000868
Greg Claytoncb8977d2011-03-23 00:09:55 +0000869 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
870 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000871 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000872 ArchSpec &target_arch = GetTarget().GetArchitecture();
873
874 if (target_arch.IsValid())
875 {
876 // If the remote host is ARM and we have apple as the vendor, then
877 // ARM executables and shared libraries can have mixed ARM architectures.
878 // You can have an armv6 executable, and if the host is armv7, then the
879 // system will load the best possible architecture for all shared libraries
880 // it has, so we really need to take the remote host architecture as our
881 // defacto architecture in this case.
882
883 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
884 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
885 {
886 target_arch = gdb_remote_arch;
887 }
888 else
889 {
890 // Fill in what is missing in the triple
891 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
892 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000893 if (target_triple.getVendorName().size() == 0)
894 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000895 target_triple.setVendor (remote_triple.getVendor());
896
Greg Clayton2f085c62011-05-15 01:25:55 +0000897 if (target_triple.getOSName().size() == 0)
898 {
899 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000900
Greg Clayton2f085c62011-05-15 01:25:55 +0000901 if (target_triple.getEnvironmentName().size() == 0)
902 target_triple.setEnvironment (remote_triple.getEnvironment());
903 }
904 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000905 }
906 }
907 else
908 {
909 // The target doesn't have a valid architecture yet, set it from
910 // the architecture we got from the remote GDB server
911 target_arch = gdb_remote_arch;
912 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000913 }
Chris Lattner24943d22010-06-08 16:52:24 +0000914 }
915}
916
917void
918ProcessGDBRemote::DidLaunch ()
919{
920 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000921}
922
923Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000924ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000925{
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000926 ProcessAttachInfo attach_info;
927 return DoAttachToProcessWithID(attach_pid, attach_info);
928}
929
930Error
931ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
932{
Chris Lattner24943d22010-06-08 16:52:24 +0000933 Error error;
934 // Clear out and clean up from any current state
935 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000936 if (attach_pid != LLDB_INVALID_PROCESS_ID)
937 {
Greg Claytona2f74232011-02-24 22:24:29 +0000938 // Make sure we aren't already connected?
939 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000940 {
Greg Claytona2f74232011-02-24 22:24:29 +0000941 char host_port[128];
942 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
943 char connect_url[128];
944 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000945
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000946 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +0000947
948 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +0000949 {
Greg Claytona2f74232011-02-24 22:24:29 +0000950 const char *error_string = error.AsCString();
951 if (error_string == NULL)
952 error_string = "unable to launch " DEBUGSERVER_BASENAME;
953
954 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +0000955 }
Greg Claytona2f74232011-02-24 22:24:29 +0000956 else
957 {
958 error = ConnectToDebugserver (connect_url);
959 }
960 }
961
962 if (error.Success())
963 {
964 char packet[64];
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000965 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Greg Clayton489575c2011-11-19 02:11:30 +0000966 SetID (attach_pid);
Greg Claytona2f74232011-02-24 22:24:29 +0000967 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +0000968 }
969 }
Chris Lattner24943d22010-06-08 16:52:24 +0000970 return error;
971}
972
973size_t
974ProcessGDBRemote::AttachInputReaderCallback
975(
976 void *baton,
977 InputReader *reader,
978 lldb::InputReaderAction notification,
979 const char *bytes,
980 size_t bytes_len
981)
982{
983 if (notification == eInputReaderGotToken)
984 {
985 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
986 if (gdb_process->m_waiting_for_attach)
987 gdb_process->m_waiting_for_attach = false;
988 reader->SetIsDone(true);
989 return 1;
990 }
991 return 0;
992}
993
994Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000995ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000996{
997 Error error;
998 // Clear out and clean up from any current state
999 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001000
Chris Lattner24943d22010-06-08 16:52:24 +00001001 if (process_name && process_name[0])
1002 {
Greg Claytona2f74232011-02-24 22:24:29 +00001003 // Make sure we aren't already connected?
1004 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001005 {
Greg Claytona2f74232011-02-24 22:24:29 +00001006 char host_port[128];
1007 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
1008 char connect_url[128];
1009 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
1010
Han Ming Ongd1040dd2012-02-25 01:07:38 +00001011 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +00001012 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +00001013 {
Greg Claytona2f74232011-02-24 22:24:29 +00001014 const char *error_string = error.AsCString();
1015 if (error_string == NULL)
1016 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +00001017
Greg Claytona2f74232011-02-24 22:24:29 +00001018 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +00001019 }
Greg Claytona2f74232011-02-24 22:24:29 +00001020 else
1021 {
1022 error = ConnectToDebugserver (connect_url);
1023 }
1024 }
1025
1026 if (error.Success())
1027 {
1028 StreamString packet;
1029
1030 if (wait_for_launch)
Jim Ingham3a458eb2012-07-20 21:37:13 +00001031 {
1032 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1033 {
1034 packet.PutCString ("vAttachWait");
1035 }
1036 else
1037 {
1038 if (attach_info.GetIgnoreExisting())
1039 packet.PutCString("vAttachWait");
1040 else
1041 packet.PutCString ("vAttachOrWait");
1042 }
1043 }
Greg Claytona2f74232011-02-24 22:24:29 +00001044 else
1045 packet.PutCString("vAttachName");
1046 packet.PutChar(';');
1047 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1048
1049 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1050
Chris Lattner24943d22010-06-08 16:52:24 +00001051 }
1052 }
Chris Lattner24943d22010-06-08 16:52:24 +00001053 return error;
1054}
1055
Chris Lattner24943d22010-06-08 16:52:24 +00001056
1057void
1058ProcessGDBRemote::DidAttach ()
1059{
Greg Claytone71e2582011-02-04 01:58:07 +00001060 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +00001061}
1062
Greg Clayton0bce9a22012-12-05 00:16:59 +00001063void
1064ProcessGDBRemote::DoDidExec ()
1065{
1066 // The process exec'ed itself, figure out the dynamic loader, etc...
1067 BuildDynamicRegisterInfo (true);
1068 m_gdb_comm.ResetDiscoverableSettings();
1069 DidLaunchOrAttach ();
1070}
1071
1072
1073
Chris Lattner24943d22010-06-08 16:52:24 +00001074Error
1075ProcessGDBRemote::WillResume ()
1076{
Greg Claytonc1f45872011-02-12 06:28:37 +00001077 m_continue_c_tids.clear();
1078 m_continue_C_tids.clear();
1079 m_continue_s_tids.clear();
1080 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001081 return Error();
1082}
1083
1084Error
1085ProcessGDBRemote::DoResume ()
1086{
Jim Ingham3ae449a2010-11-17 02:32:00 +00001087 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +00001088 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1089 if (log)
1090 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +00001091
1092 Listener listener ("gdb-remote.resume-packet-sent");
1093 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1094 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001095 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1096
Greg Claytonc1f45872011-02-12 06:28:37 +00001097 StreamString continue_packet;
1098 bool continue_packet_error = false;
1099 if (m_gdb_comm.HasAnyVContSupport ())
1100 {
1101 continue_packet.PutCString ("vCont");
1102
1103 if (!m_continue_c_tids.empty())
1104 {
1105 if (m_gdb_comm.GetVContSupported ('c'))
1106 {
1107 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 +00001108 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +00001109 }
1110 else
1111 continue_packet_error = true;
1112 }
1113
1114 if (!continue_packet_error && !m_continue_C_tids.empty())
1115 {
1116 if (m_gdb_comm.GetVContSupported ('C'))
1117 {
1118 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 +00001119 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001120 }
1121 else
1122 continue_packet_error = true;
1123 }
Greg Claytonb749a262010-12-03 06:02:24 +00001124
Greg Claytonc1f45872011-02-12 06:28:37 +00001125 if (!continue_packet_error && !m_continue_s_tids.empty())
1126 {
1127 if (m_gdb_comm.GetVContSupported ('s'))
1128 {
1129 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 +00001130 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +00001131 }
1132 else
1133 continue_packet_error = true;
1134 }
1135
1136 if (!continue_packet_error && !m_continue_S_tids.empty())
1137 {
1138 if (m_gdb_comm.GetVContSupported ('S'))
1139 {
1140 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 +00001141 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001142 }
1143 else
1144 continue_packet_error = true;
1145 }
1146
1147 if (continue_packet_error)
1148 continue_packet.GetString().clear();
1149 }
1150 else
1151 continue_packet_error = true;
1152
1153 if (continue_packet_error)
1154 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001155 // Either no vCont support, or we tried to use part of the vCont
1156 // packet that wasn't supported by the remote GDB server.
1157 // We need to try and make a simple packet that can do our continue
1158 const size_t num_threads = GetThreadList().GetSize();
1159 const size_t num_continue_c_tids = m_continue_c_tids.size();
1160 const size_t num_continue_C_tids = m_continue_C_tids.size();
1161 const size_t num_continue_s_tids = m_continue_s_tids.size();
1162 const size_t num_continue_S_tids = m_continue_S_tids.size();
1163 if (num_continue_c_tids > 0)
1164 {
1165 if (num_continue_c_tids == num_threads)
1166 {
1167 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001168 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001169 continue_packet.PutChar ('c');
1170 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001171 }
1172 else if (num_continue_c_tids == 1 &&
1173 num_continue_C_tids == 0 &&
1174 num_continue_s_tids == 0 &&
1175 num_continue_S_tids == 0 )
1176 {
1177 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +00001178 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001179 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +00001180 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001181 }
1182 }
1183
Greg Claytonde1dd812011-06-24 03:21:43 +00001184 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001185 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001186 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1187 num_continue_C_tids > 0 &&
1188 num_continue_s_tids == 0 &&
1189 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +00001190 {
1191 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +00001192 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +00001193 if (num_continue_C_tids > 1)
1194 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001195 // More that one thread with a signal, yet we don't have
1196 // vCont support and we are being asked to resume each
1197 // thread with a signal, we need to make sure they are
1198 // all the same signal, or we can't issue the continue
1199 // accurately with the current support...
1200 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +00001201 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001202 continue_packet_error = false;
1203 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1204 {
1205 if (m_continue_C_tids[i].second != continue_signo)
1206 continue_packet_error = true;
1207 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001208 }
Greg Claytonde1dd812011-06-24 03:21:43 +00001209 if (!continue_packet_error)
1210 m_gdb_comm.SetCurrentThreadForRun (-1);
1211 }
1212 else
1213 {
1214 // Set the continue thread ID
1215 continue_packet_error = false;
1216 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001217 }
1218 if (!continue_packet_error)
1219 {
1220 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +00001221 continue_packet.Printf("C%2.2x", continue_signo);
1222 }
1223 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001224 }
1225
Greg Claytonde1dd812011-06-24 03:21:43 +00001226 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001227 {
1228 if (num_continue_s_tids == num_threads)
1229 {
1230 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001231 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001232 continue_packet.PutChar ('s');
1233 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001234 }
1235 else if (num_continue_c_tids == 0 &&
1236 num_continue_C_tids == 0 &&
1237 num_continue_s_tids == 1 &&
1238 num_continue_S_tids == 0 )
1239 {
1240 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001241 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001242 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001243 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001244 }
1245 }
1246
1247 if (!continue_packet_error && num_continue_S_tids > 0)
1248 {
1249 if (num_continue_S_tids == num_threads)
1250 {
1251 const int step_signo = m_continue_S_tids.front().second;
1252 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001253 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001254 if (num_continue_S_tids > 1)
1255 {
1256 for (size_t i=1; i<num_threads; ++i)
1257 {
1258 if (m_continue_S_tids[i].second != step_signo)
1259 continue_packet_error = true;
1260 }
1261 }
1262 if (!continue_packet_error)
1263 {
1264 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001265 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001266 continue_packet.Printf("S%2.2x", step_signo);
1267 }
1268 }
1269 else if (num_continue_c_tids == 0 &&
1270 num_continue_C_tids == 0 &&
1271 num_continue_s_tids == 0 &&
1272 num_continue_S_tids == 1 )
1273 {
1274 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001275 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001276 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001277 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001278 }
1279 }
1280 }
1281
1282 if (continue_packet_error)
1283 {
1284 error.SetErrorString ("can't make continue packet for this resume");
1285 }
1286 else
1287 {
1288 EventSP event_sp;
1289 TimeValue timeout;
1290 timeout = TimeValue::Now();
1291 timeout.OffsetWithSeconds (5);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001292 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1293 {
1294 error.SetErrorString ("Trying to resume but the async thread is dead.");
1295 if (log)
1296 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1297 return error;
1298 }
1299
Greg Claytonc1f45872011-02-12 06:28:37 +00001300 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1301
1302 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001303 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001304 error.SetErrorString("Resume timed out.");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001305 if (log)
1306 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1307 }
1308 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1309 {
1310 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1311 if (log)
1312 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1313 return error;
1314 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001315 }
Greg Claytonb749a262010-12-03 06:02:24 +00001316 }
1317
Jim Ingham3ae449a2010-11-17 02:32:00 +00001318 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001319}
1320
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001321void
1322ProcessGDBRemote::ClearThreadIDList ()
1323{
Greg Claytonff3448e2012-04-13 02:11:32 +00001324 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001325 m_thread_ids.clear();
1326}
1327
1328bool
1329ProcessGDBRemote::UpdateThreadIDList ()
1330{
Greg Claytonff3448e2012-04-13 02:11:32 +00001331 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001332 bool sequence_mutex_unavailable = false;
1333 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1334 if (sequence_mutex_unavailable)
1335 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001336 return false; // We just didn't get the list
1337 }
1338 return true;
1339}
1340
Greg Claytonae932352012-04-10 00:18:59 +00001341bool
Greg Clayton37f962e2011-08-22 02:49:39 +00001342ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001343{
1344 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001345 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001346 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001347 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001348
1349 size_t num_thread_ids = m_thread_ids.size();
1350 // The "m_thread_ids" thread ID list should always be updated after each stop
1351 // reply packet, but in case it isn't, update it here.
1352 if (num_thread_ids == 0)
1353 {
1354 if (!UpdateThreadIDList ())
1355 return false;
1356 num_thread_ids = m_thread_ids.size();
1357 }
Chris Lattner24943d22010-06-08 16:52:24 +00001358
Greg Clayton37f962e2011-08-22 02:49:39 +00001359 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001360 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001361 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001362 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001363 tid_t tid = m_thread_ids[i];
Greg Clayton37f962e2011-08-22 02:49:39 +00001364 ThreadSP thread_sp (old_thread_list.FindThreadByID (tid, false));
1365 if (!thread_sp)
Jim Ingham94a5d0d2012-10-10 18:32:14 +00001366 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Greg Clayton37f962e2011-08-22 02:49:39 +00001367 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001368 }
Chris Lattner24943d22010-06-08 16:52:24 +00001369 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001370
Greg Claytonae932352012-04-10 00:18:59 +00001371 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001372}
1373
1374
1375StateType
1376ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1377{
Greg Clayton261a18b2011-06-02 22:22:38 +00001378 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001379 const char stop_type = stop_packet.GetChar();
1380 switch (stop_type)
1381 {
1382 case 'T':
1383 case 'S':
1384 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001385 if (GetStopID() == 0)
1386 {
1387 // Our first stop, make sure we have a process ID, and also make
1388 // sure we know about our registers
1389 if (GetID() == LLDB_INVALID_PROCESS_ID)
1390 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001391 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001392 if (pid != LLDB_INVALID_PROCESS_ID)
1393 SetID (pid);
1394 }
1395 BuildDynamicRegisterInfo (true);
1396 }
Chris Lattner24943d22010-06-08 16:52:24 +00001397 // Stop with signal and thread info
1398 const uint8_t signo = stop_packet.GetHexU8();
1399 std::string name;
1400 std::string value;
1401 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001402 std::string reason;
1403 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001404 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001405 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001406 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Claytona875b642011-01-09 21:07:35 +00001407 ThreadSP thread_sp;
1408
Chris Lattner24943d22010-06-08 16:52:24 +00001409 while (stop_packet.GetNameColonValue(name, value))
1410 {
1411 if (name.compare("metype") == 0)
1412 {
1413 // exception type in big endian hex
1414 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1415 }
Chris Lattner24943d22010-06-08 16:52:24 +00001416 else if (name.compare("medata") == 0)
1417 {
1418 // exception data in big endian hex
1419 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1420 }
1421 else if (name.compare("thread") == 0)
1422 {
1423 // thread in big endian hex
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001424 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Claytonffa43a62011-11-17 04:46:02 +00001425 // m_thread_list does have its own mutex, but we need to
1426 // hold onto the mutex between the call to m_thread_list.FindThreadByID(...)
1427 // and the m_thread_list.AddThread(...) so it doesn't change on us
Greg Claytonc3c46612011-02-15 00:19:15 +00001428 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001429 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001430 if (!thread_sp)
1431 {
1432 // Create the thread if we need to
Jim Ingham94a5d0d2012-10-10 18:32:14 +00001433 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Greg Claytonc3c46612011-02-15 00:19:15 +00001434 m_thread_list.AddThread(thread_sp);
1435 }
Chris Lattner24943d22010-06-08 16:52:24 +00001436 }
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001437 else if (name.compare("threads") == 0)
1438 {
Greg Claytonff3448e2012-04-13 02:11:32 +00001439 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001440 m_thread_ids.clear();
Greg Claytona1f645e2012-04-10 03:22:03 +00001441 // A comma separated list of all threads in the current
1442 // process that includes the thread for this stop reply
1443 // packet
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001444 size_t comma_pos;
1445 lldb::tid_t tid;
1446 while ((comma_pos = value.find(',')) != std::string::npos)
1447 {
1448 value[comma_pos] = '\0';
1449 // thread in big endian hex
1450 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1451 if (tid != LLDB_INVALID_THREAD_ID)
1452 m_thread_ids.push_back (tid);
1453 value.erase(0, comma_pos + 1);
1454
1455 }
1456 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1457 if (tid != LLDB_INVALID_THREAD_ID)
1458 m_thread_ids.push_back (tid);
1459 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001460 else if (name.compare("hexname") == 0)
1461 {
1462 StringExtractor name_extractor;
1463 // Swap "value" over into "name_extractor"
1464 name_extractor.GetStringRef().swap(value);
1465 // Now convert the HEX bytes into a string value
1466 name_extractor.GetHexByteString (value);
1467 thread_name.swap (value);
1468 }
Chris Lattner24943d22010-06-08 16:52:24 +00001469 else if (name.compare("name") == 0)
1470 {
1471 thread_name.swap (value);
1472 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001473 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001474 {
1475 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1476 }
Greg Clayton65611552011-06-04 01:26:29 +00001477 else if (name.compare("reason") == 0)
1478 {
1479 reason.swap(value);
1480 }
1481 else if (name.compare("description") == 0)
1482 {
1483 StringExtractor desc_extractor;
1484 // Swap "value" over into "name_extractor"
1485 desc_extractor.GetStringRef().swap(value);
1486 // Now convert the HEX bytes into a string value
1487 desc_extractor.GetHexByteString (thread_name);
1488 }
Greg Claytona875b642011-01-09 21:07:35 +00001489 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1490 {
1491 // We have a register number that contains an expedited
1492 // register value. Lets supply this register to our thread
1493 // so it won't have to go and read it.
1494 if (thread_sp)
1495 {
1496 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1497
1498 if (reg != UINT32_MAX)
1499 {
1500 StringExtractor reg_value_extractor;
1501 // Swap "value" over into "reg_value_extractor"
1502 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001503 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1504 {
1505 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1506 name.c_str(),
1507 reg,
1508 reg,
1509 reg_value_extractor.GetStringRef().c_str(),
1510 stop_packet.GetStringRef().c_str());
1511 }
Greg Claytona875b642011-01-09 21:07:35 +00001512 }
1513 }
1514 }
Chris Lattner24943d22010-06-08 16:52:24 +00001515 }
Chris Lattner24943d22010-06-08 16:52:24 +00001516
1517 if (thread_sp)
1518 {
1519 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1520
1521 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001522 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001523 if (exc_type != 0)
1524 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001525 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001526
1527 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1528 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001529 exc_data_size,
1530 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001531 exc_data_size >= 2 ? exc_data[1] : 0,
1532 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001533 }
Greg Clayton65611552011-06-04 01:26:29 +00001534 else
Chris Lattner24943d22010-06-08 16:52:24 +00001535 {
Greg Clayton65611552011-06-04 01:26:29 +00001536 bool handled = false;
1537 if (!reason.empty())
1538 {
1539 if (reason.compare("trace") == 0)
1540 {
1541 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1542 handled = true;
1543 }
1544 else if (reason.compare("breakpoint") == 0)
1545 {
1546 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001547 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001548 if (bp_site_sp)
1549 {
1550 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1551 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1552 // 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 +00001553 handled = true;
Greg Clayton65611552011-06-04 01:26:29 +00001554 if (bp_site_sp->ValidForThisThread (gdb_thread))
1555 {
1556 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001557 }
1558 else
1559 {
1560 StopInfoSP invalid_stop_info_sp;
1561 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Greg Clayton65611552011-06-04 01:26:29 +00001562 }
1563 }
1564
Greg Clayton65611552011-06-04 01:26:29 +00001565 }
1566 else if (reason.compare("trap") == 0)
1567 {
1568 // Let the trap just use the standard signal stop reason below...
1569 }
1570 else if (reason.compare("watchpoint") == 0)
1571 {
1572 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1573 // TODO: locate the watchpoint somehow...
1574 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1575 handled = true;
1576 }
1577 else if (reason.compare("exception") == 0)
1578 {
1579 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1580 handled = true;
1581 }
1582 }
1583
1584 if (signo)
1585 {
1586 if (signo == SIGTRAP)
1587 {
1588 // Currently we are going to assume SIGTRAP means we are either
1589 // hitting a breakpoint or hardware single stepping.
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001590 handled = true;
Greg Clayton65611552011-06-04 01:26:29 +00001591 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001592 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001593
Greg Clayton65611552011-06-04 01:26:29 +00001594 if (bp_site_sp)
1595 {
1596 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1597 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1598 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1599 if (bp_site_sp->ValidForThisThread (gdb_thread))
1600 {
1601 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001602 }
1603 else
1604 {
1605 StopInfoSP invalid_stop_info_sp;
1606 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Greg Clayton65611552011-06-04 01:26:29 +00001607 }
1608 }
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001609 else
Greg Clayton65611552011-06-04 01:26:29 +00001610 {
Jim Ingham4fa015b2012-10-27 02:52:04 +00001611 // If we were stepping then assume the stop was the result of the trace. If we were
1612 // not stepping then report the SIGTRAP.
1613 // FIXME: We are still missing the case where we single step over a trap instruction.
1614 if (gdb_thread->GetTemporaryResumeState() == eStateStepping)
1615 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1616 else
1617 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo));
Greg Clayton65611552011-06-04 01:26:29 +00001618 }
1619 }
1620 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001621 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001622 }
1623 else
1624 {
Greg Clayton643ee732010-08-04 01:40:35 +00001625 StopInfoSP invalid_stop_info_sp;
1626 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001627 }
Greg Clayton65611552011-06-04 01:26:29 +00001628
1629 if (!description.empty())
1630 {
1631 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1632 if (stop_info_sp)
1633 {
1634 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001635 }
Greg Clayton65611552011-06-04 01:26:29 +00001636 else
1637 {
1638 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1639 }
1640 }
1641 }
Chris Lattner24943d22010-06-08 16:52:24 +00001642 }
1643 return eStateStopped;
1644 }
1645 break;
1646
1647 case 'W':
1648 // process exited
1649 return eStateExited;
1650
1651 default:
1652 break;
1653 }
1654 return eStateInvalid;
1655}
1656
1657void
1658ProcessGDBRemote::RefreshStateAfterStop ()
1659{
Greg Claytonff3448e2012-04-13 02:11:32 +00001660 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001661 m_thread_ids.clear();
1662 // Set the thread stop info. It might have a "threads" key whose value is
1663 // a list of all thread IDs in the current process, so m_thread_ids might
1664 // get set.
1665 SetThreadStopInfo (m_last_stop_packet);
1666 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1667 if (m_thread_ids.empty())
1668 {
1669 // No, we need to fetch the thread list manually
1670 UpdateThreadIDList();
1671 }
1672
Chris Lattner24943d22010-06-08 16:52:24 +00001673 // Let all threads recover from stopping and do any clean up based
1674 // on the previous thread state (if any).
1675 m_thread_list.RefreshStateAfterStop();
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001676
Chris Lattner24943d22010-06-08 16:52:24 +00001677}
1678
1679Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001680ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001681{
1682 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001683
Greg Claytona4881d02011-01-22 07:12:45 +00001684 bool timed_out = false;
1685 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001686
1687 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001688 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001689 // We are being asked to halt during an attach. We need to just close
1690 // our file handle and debugserver will go away, and we can be done...
1691 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001692 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001693 else
1694 {
Greg Clayton05e4d972012-03-29 01:55:41 +00001695 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001696 {
1697 if (timed_out)
1698 error.SetErrorString("timed out sending interrupt packet");
1699 else
1700 error.SetErrorString("unknown error sending interrupt packet");
1701 }
Greg Clayton05e4d972012-03-29 01:55:41 +00001702
1703 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001704 }
Chris Lattner24943d22010-06-08 16:52:24 +00001705 return error;
1706}
1707
1708Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001709ProcessGDBRemote::InterruptIfRunning
1710(
1711 bool discard_thread_plans,
1712 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001713 EventSP &stop_event_sp
1714)
Chris Lattner24943d22010-06-08 16:52:24 +00001715{
1716 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001717
Greg Clayton2860ba92011-01-23 19:58:49 +00001718 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1719
Greg Clayton68ca8232011-01-25 02:58:48 +00001720 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001721 const bool is_running = m_gdb_comm.IsRunning();
1722 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001723 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001724 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001725 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001726 is_running);
1727
Greg Clayton2860ba92011-01-23 19:58:49 +00001728 if (discard_thread_plans)
1729 {
1730 if (log)
1731 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1732 m_thread_list.DiscardThreadPlans();
1733 }
1734 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001735 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001736 if (catch_stop_event)
1737 {
1738 if (log)
1739 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1740 PausePrivateStateThread();
1741 paused_private_state_thread = true;
1742 }
1743
Greg Clayton4fb400f2010-09-27 21:07:38 +00001744 bool timed_out = false;
1745 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001746
Greg Clayton05e4d972012-03-29 01:55:41 +00001747 if (!m_gdb_comm.SendInterrupt (locker, 1, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001748 {
1749 if (timed_out)
1750 error.SetErrorString("timed out sending interrupt packet");
1751 else
1752 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001753 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001754 ResumePrivateStateThread();
1755 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001756 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001757
Greg Clayton72e1c782011-01-22 23:43:18 +00001758 if (catch_stop_event)
1759 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001760 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001761 TimeValue timeout_time;
1762 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001763 timeout_time.OffsetWithSeconds(5);
1764 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001765
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001766 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001767 if (log)
1768 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001769
Greg Clayton2860ba92011-01-23 19:58:49 +00001770 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001771 error.SetErrorString("unable to verify target stopped");
1772 }
1773
Greg Clayton68ca8232011-01-25 02:58:48 +00001774 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001775 {
1776 if (log)
1777 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001778 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001779 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001780 }
Chris Lattner24943d22010-06-08 16:52:24 +00001781 return error;
1782}
1783
Greg Clayton4fb400f2010-09-27 21:07:38 +00001784Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001785ProcessGDBRemote::WillDetach ()
1786{
Greg Clayton2860ba92011-01-23 19:58:49 +00001787 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1788 if (log)
1789 log->Printf ("ProcessGDBRemote::WillDetach()");
1790
Greg Clayton72e1c782011-01-22 23:43:18 +00001791 bool discard_thread_plans = true;
1792 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001793 EventSP event_sp;
Jim Ingham8247e622012-06-06 00:32:39 +00001794
1795 // FIXME: InterruptIfRunning should be done in the Process base class, or better still make Halt do what is
1796 // needed. This shouldn't be a feature of a particular plugin.
1797
Greg Clayton68ca8232011-01-25 02:58:48 +00001798 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001799}
1800
1801Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001802ProcessGDBRemote::DoDetach()
1803{
1804 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001805 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001806 if (log)
1807 log->Printf ("ProcessGDBRemote::DoDetach()");
1808
1809 DisableAllBreakpointSites ();
1810
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001811 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001812
Greg Clayton516f0842012-04-11 00:24:49 +00001813 bool success = m_gdb_comm.Detach ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001814 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001815 {
Greg Clayton516f0842012-04-11 00:24:49 +00001816 if (success)
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001817 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1818 else
1819 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001820 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001821 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001822 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001823
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001824 SetPrivateState (eStateDetached);
1825 ResumePrivateStateThread();
1826
1827 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001828 return error;
1829}
Chris Lattner24943d22010-06-08 16:52:24 +00001830
Jim Ingham06b84492012-07-04 00:35:43 +00001831
Chris Lattner24943d22010-06-08 16:52:24 +00001832Error
1833ProcessGDBRemote::DoDestroy ()
1834{
1835 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001836 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001837 if (log)
1838 log->Printf ("ProcessGDBRemote::DoDestroy()");
1839
Jim Ingham06b84492012-07-04 00:35:43 +00001840 // There is a bug in older iOS debugservers where they don't shut down the process
1841 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
1842 // this can cause problems with restarting. So we check to see if any of our threads are stopped
1843 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
1844 // destroy it again.
1845 //
1846 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
1847 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
1848 // the debugservers with this bug are equal. There really should be a better way to test this!
1849 //
1850 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
1851 // get called here to destroy again and we're still at a breakpoint or exception, then we should
1852 // just do the straight-forward kill.
1853 //
1854 // And of course, if we weren't able to stop the process by the time we get here, it isn't
1855 // necessary (or helpful) to do any of this.
1856
1857 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
1858 {
1859 PlatformSP platform_sp = GetTarget().GetPlatform();
1860
1861 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
1862 if (platform_sp
1863 && platform_sp->GetName()
1864 && strcmp (platform_sp->GetName(), PlatformRemoteiOS::GetShortPluginNameStatic()) == 0)
1865 {
1866 if (m_destroy_tried_resuming)
1867 {
1868 if (log)
1869 log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again.");
1870 }
1871 else
1872 {
1873 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
1874 // but we really need it to happen here and it doesn't matter if we do it twice.
1875 m_thread_list.DiscardThreadPlans();
1876 DisableAllBreakpointSites();
1877
1878 bool stop_looks_like_crash = false;
1879 ThreadList &threads = GetThreadList();
1880
1881 {
Jim Inghamc2c65142012-09-11 00:08:52 +00001882 Mutex::Locker locker(threads.GetMutex());
Jim Ingham06b84492012-07-04 00:35:43 +00001883
1884 size_t num_threads = threads.GetSize();
1885 for (size_t i = 0; i < num_threads; i++)
1886 {
1887 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1888 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason();
1889 StopReason reason = eStopReasonInvalid;
1890 if (stop_info_sp)
1891 reason = stop_info_sp->GetStopReason();
1892 if (reason == eStopReasonBreakpoint
1893 || reason == eStopReasonException)
1894 {
1895 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001896 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: %" PRId64 " stopped with reason: %s.",
Jim Ingham06b84492012-07-04 00:35:43 +00001897 thread_sp->GetID(),
1898 stop_info_sp->GetDescription());
1899 stop_looks_like_crash = true;
1900 break;
1901 }
1902 }
1903 }
1904
1905 if (stop_looks_like_crash)
1906 {
1907 if (log)
1908 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
1909 m_destroy_tried_resuming = true;
1910
1911 // If we are going to run again before killing, it would be good to suspend all the threads
1912 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
1913 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
1914 // have to run the risk of letting those threads proceed a bit.
1915
1916 {
Jim Inghamc2c65142012-09-11 00:08:52 +00001917 Mutex::Locker locker(threads.GetMutex());
Jim Ingham06b84492012-07-04 00:35:43 +00001918
1919 size_t num_threads = threads.GetSize();
1920 for (size_t i = 0; i < num_threads; i++)
1921 {
1922 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1923 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason();
1924 StopReason reason = eStopReasonInvalid;
1925 if (stop_info_sp)
1926 reason = stop_info_sp->GetStopReason();
1927 if (reason != eStopReasonBreakpoint
1928 && reason != eStopReasonException)
1929 {
1930 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001931 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: %" PRId64 " before running.",
Jim Ingham06b84492012-07-04 00:35:43 +00001932 thread_sp->GetID());
1933 thread_sp->SetResumeState(eStateSuspended);
1934 }
1935 }
1936 }
1937 Resume ();
1938 return Destroy();
1939 }
1940 }
1941 }
1942 }
1943
Chris Lattner24943d22010-06-08 16:52:24 +00001944 // Interrupt if our inferior is running...
Jim Ingham8247e622012-06-06 00:32:39 +00001945 int exit_status = SIGABRT;
1946 std::string exit_string;
1947
Greg Claytona4881d02011-01-22 07:12:45 +00001948 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001949 {
Jim Ingham8226e942011-10-28 01:11:35 +00001950 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton72e1c782011-01-22 23:43:18 +00001951 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001952
1953 StringExtractorGDBRemote response;
1954 bool send_async = true;
Filipe Cabecinhasee188ee2012-08-22 13:25:58 +00001955 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3);
1956
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001957 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001958 {
1959 char packet_cmd = response.GetChar(0);
1960
1961 if (packet_cmd == 'W' || packet_cmd == 'X')
1962 {
Greg Clayton06709002011-12-06 04:51:14 +00001963 SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001964 ClearThreadIDList ();
Jim Ingham8247e622012-06-06 00:32:39 +00001965 exit_status = response.GetHexU8();
1966 }
1967 else
1968 {
1969 if (log)
1970 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
1971 exit_string.assign("got unexpected response to k packet: ");
1972 exit_string.append(response.GetStringRef());
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001973 }
1974 }
1975 else
1976 {
Jim Ingham8247e622012-06-06 00:32:39 +00001977 if (log)
1978 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
1979 exit_string.assign("failed to send the k packet");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001980 }
Filipe Cabecinhasee188ee2012-08-22 13:25:58 +00001981
1982 m_gdb_comm.SetPacketTimeout(old_packet_timeout);
Greg Clayton72e1c782011-01-22 23:43:18 +00001983 }
Jim Ingham8247e622012-06-06 00:32:39 +00001984 else
1985 {
1986 if (log)
1987 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
Jim Ingham5d90ade2012-07-27 23:57:19 +00001988 exit_string.assign ("killed or interrupted while attaching.");
Jim Ingham8247e622012-06-06 00:32:39 +00001989 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001990 }
Jim Ingham8247e622012-06-06 00:32:39 +00001991 else
1992 {
1993 // If we missed setting the exit status on the way out, do it here.
1994 // NB set exit status can be called multiple times, the first one sets the status.
1995 exit_string.assign("destroying when not connected to debugserver");
1996 }
1997
1998 SetExitStatus(exit_status, exit_string.c_str());
1999
Chris Lattner24943d22010-06-08 16:52:24 +00002000 StopAsyncThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002001 KillDebugserverProcess ();
2002 return error;
2003}
2004
Chris Lattner24943d22010-06-08 16:52:24 +00002005//------------------------------------------------------------------
2006// Process Queries
2007//------------------------------------------------------------------
2008
2009bool
2010ProcessGDBRemote::IsAlive ()
2011{
Greg Clayton58e844b2010-12-08 05:08:21 +00002012 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00002013}
2014
Jason Molendad6b81222012-10-06 02:02:26 +00002015// For kernel debugging, we return the load address of the kernel binary as the
2016// ImageInfoAddress and we return the DynamicLoaderDarwinKernel as the GetDynamicLoader()
2017// name so the correct DynamicLoader plugin is chosen.
Chris Lattner24943d22010-06-08 16:52:24 +00002018addr_t
2019ProcessGDBRemote::GetImageInfoAddress()
2020{
Jason Molendab46937c2012-10-03 01:29:34 +00002021 if (m_kernel_load_addr != LLDB_INVALID_ADDRESS)
2022 return m_kernel_load_addr;
2023 else
2024 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner24943d22010-06-08 16:52:24 +00002025}
2026
Chris Lattner24943d22010-06-08 16:52:24 +00002027//------------------------------------------------------------------
2028// Process Memory
2029//------------------------------------------------------------------
2030size_t
2031ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2032{
2033 if (size > m_max_memory_size)
2034 {
2035 // Keep memory read sizes down to a sane limit. This function will be
2036 // called multiple times in order to complete the task by
2037 // lldb_private::Process so it is ok to do this.
2038 size = m_max_memory_size;
2039 }
2040
2041 char packet[64];
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002042 const int packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
Chris Lattner24943d22010-06-08 16:52:24 +00002043 assert (packet_len + 1 < sizeof(packet));
2044 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00002045 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00002046 {
Greg Clayton61d043b2011-03-22 04:00:09 +00002047 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00002048 {
2049 error.Clear();
2050 return response.GetHexBytes(buf, size, '\xdd');
2051 }
Greg Clayton61d043b2011-03-22 04:00:09 +00002052 else if (response.IsErrorResponse())
Greg Clayton49d888d2012-12-06 22:49:16 +00002053 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton61d043b2011-03-22 04:00:09 +00002054 else if (response.IsUnsupportedResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00002055 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner24943d22010-06-08 16:52:24 +00002056 else
Greg Claytonae7bebc2012-09-19 01:46:31 +00002057 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00002058 }
2059 else
2060 {
2061 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
2062 }
2063 return 0;
2064}
2065
2066size_t
2067ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2068{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00002069 if (size > m_max_memory_size)
2070 {
2071 // Keep memory read sizes down to a sane limit. This function will be
2072 // called multiple times in order to complete the task by
2073 // lldb_private::Process so it is ok to do this.
2074 size = m_max_memory_size;
2075 }
2076
Chris Lattner24943d22010-06-08 16:52:24 +00002077 StreamString packet;
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002078 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Claytoncd548032011-02-01 01:31:41 +00002079 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00002080 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00002081 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00002082 {
Greg Clayton61d043b2011-03-22 04:00:09 +00002083 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00002084 {
2085 error.Clear();
2086 return size;
2087 }
Greg Clayton61d043b2011-03-22 04:00:09 +00002088 else if (response.IsErrorResponse())
Greg Clayton49d888d2012-12-06 22:49:16 +00002089 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton61d043b2011-03-22 04:00:09 +00002090 else if (response.IsUnsupportedResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00002091 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner24943d22010-06-08 16:52:24 +00002092 else
Greg Claytonae7bebc2012-09-19 01:46:31 +00002093 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 +00002094 }
2095 else
2096 {
2097 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
2098 }
2099 return 0;
2100}
2101
2102lldb::addr_t
2103ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2104{
Greg Clayton989816b2011-05-14 01:50:35 +00002105 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2106
Greg Clayton2f085c62011-05-15 01:25:55 +00002107 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00002108 switch (supported)
2109 {
2110 case eLazyBoolCalculate:
2111 case eLazyBoolYes:
2112 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2113 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2114 return allocated_addr;
2115
2116 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002117 // Call mmap() to create memory in the inferior..
2118 unsigned prot = 0;
2119 if (permissions & lldb::ePermissionsReadable)
2120 prot |= eMmapProtRead;
2121 if (permissions & lldb::ePermissionsWritable)
2122 prot |= eMmapProtWrite;
2123 if (permissions & lldb::ePermissionsExecutable)
2124 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00002125
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002126 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2127 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2128 m_addr_to_mmap_size[allocated_addr] = size;
2129 else
2130 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00002131 break;
2132 }
2133
Chris Lattner24943d22010-06-08 16:52:24 +00002134 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002135 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00002136 else
2137 error.Clear();
2138 return allocated_addr;
2139}
2140
2141Error
Greg Claytona9385532011-11-18 07:03:08 +00002142ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2143 MemoryRegionInfo &region_info)
2144{
2145
2146 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2147 return error;
2148}
2149
2150Error
Johnny Chen7cbdcfb2012-05-23 21:09:52 +00002151ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2152{
2153
2154 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2155 return error;
2156}
2157
2158Error
Enrico Granata7de2a3b2012-07-13 23:18:48 +00002159ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2160{
2161 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2162 return error;
2163}
2164
2165Error
Chris Lattner24943d22010-06-08 16:52:24 +00002166ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2167{
2168 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00002169 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2170
2171 switch (supported)
2172 {
2173 case eLazyBoolCalculate:
2174 // We should never be deallocating memory without allocating memory
2175 // first so we should never get eLazyBoolCalculate
2176 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2177 break;
2178
2179 case eLazyBoolYes:
2180 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002181 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00002182 break;
2183
2184 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002185 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00002186 {
2187 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002188 if (pos != m_addr_to_mmap_size.end() &&
2189 InferiorCallMunmap(this, addr, pos->second))
2190 m_addr_to_mmap_size.erase (pos);
2191 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002192 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00002193 }
2194 break;
2195 }
2196
Chris Lattner24943d22010-06-08 16:52:24 +00002197 return error;
2198}
2199
2200
2201//------------------------------------------------------------------
2202// Process STDIO
2203//------------------------------------------------------------------
Chris Lattner24943d22010-06-08 16:52:24 +00002204size_t
2205ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2206{
2207 if (m_stdio_communication.IsConnected())
2208 {
2209 ConnectionStatus status;
2210 m_stdio_communication.Write(src, src_len, status, NULL);
2211 }
2212 return 0;
2213}
2214
2215Error
2216ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
2217{
2218 Error error;
2219 assert (bp_site != NULL);
2220
Greg Claytone005f2c2010-11-06 01:53:30 +00002221 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002222 user_id_t site_id = bp_site->GetID();
2223 const addr_t addr = bp_site->GetLoadAddress();
2224 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002225 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002226
2227 if (bp_site->IsEnabled())
2228 {
2229 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002230 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 +00002231 return error;
2232 }
2233 else
2234 {
2235 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2236
2237 if (bp_site->HardwarePreferred())
2238 {
2239 // Try and set hardware breakpoint, and if that fails, fall through
2240 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00002241 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00002242 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002243 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00002244 {
2245 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002246 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00002247 return error;
2248 }
Chris Lattner24943d22010-06-08 16:52:24 +00002249 }
2250 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002251
2252 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00002253 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002254 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
2255 {
2256 bp_site->SetEnabled(true);
2257 bp_site->SetType (BreakpointSite::eExternal);
2258 return error;
2259 }
Chris Lattner24943d22010-06-08 16:52:24 +00002260 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002261
2262 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00002263 }
2264
2265 if (log)
2266 {
2267 const char *err_string = error.AsCString();
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002268 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8" PRIx64 ": %s",
Chris Lattner24943d22010-06-08 16:52:24 +00002269 bp_site->GetLoadAddress(),
2270 err_string ? err_string : "NULL");
2271 }
2272 // We shouldn't reach here on a successful breakpoint enable...
2273 if (error.Success())
2274 error.SetErrorToGenericError();
2275 return error;
2276}
2277
2278Error
2279ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
2280{
2281 Error error;
2282 assert (bp_site != NULL);
2283 addr_t addr = bp_site->GetLoadAddress();
2284 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00002285 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002286 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002287 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002288
2289 if (bp_site->IsEnabled())
2290 {
2291 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2292
Greg Claytonb72d0f02011-04-12 05:54:46 +00002293 BreakpointSite::Type bp_type = bp_site->GetType();
2294 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00002295 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002296 case BreakpointSite::eSoftware:
2297 error = DisableSoftwareBreakpoint (bp_site);
2298 break;
2299
2300 case BreakpointSite::eHardware:
2301 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2302 error.SetErrorToGenericError();
2303 break;
2304
2305 case BreakpointSite::eExternal:
2306 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2307 error.SetErrorToGenericError();
2308 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002309 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002310 if (error.Success())
2311 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00002312 }
2313 else
2314 {
2315 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002316 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 +00002317 return error;
2318 }
2319
2320 if (error.Success())
2321 error.SetErrorToGenericError();
2322 return error;
2323}
2324
Johnny Chen21900fb2011-09-06 22:38:36 +00002325// Pre-requisite: wp != NULL.
2326static GDBStoppointType
Johnny Chenecd4feb2011-10-14 00:42:25 +00002327GetGDBStoppointType (Watchpoint *wp)
Johnny Chen21900fb2011-09-06 22:38:36 +00002328{
2329 assert(wp);
2330 bool watch_read = wp->WatchpointRead();
2331 bool watch_write = wp->WatchpointWrite();
2332
2333 // watch_read and watch_write cannot both be false.
2334 assert(watch_read || watch_write);
2335 if (watch_read && watch_write)
2336 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00002337 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00002338 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00002339 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00002340 return eWatchpointWrite;
2341}
2342
Chris Lattner24943d22010-06-08 16:52:24 +00002343Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002344ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002345{
2346 Error error;
2347 if (wp)
2348 {
2349 user_id_t watchID = wp->GetID();
2350 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00002351 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002352 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002353 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner24943d22010-06-08 16:52:24 +00002354 if (wp->IsEnabled())
2355 {
2356 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002357 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 +00002358 return error;
2359 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002360
2361 GDBStoppointType type = GetGDBStoppointType(wp);
2362 // Pass down an appropriate z/Z packet...
2363 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00002364 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002365 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2366 {
2367 wp->SetEnabled(true);
2368 return error;
2369 }
2370 else
2371 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002372 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002373 else
2374 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00002375 }
2376 else
2377 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002378 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002379 }
2380 if (error.Success())
2381 error.SetErrorToGenericError();
2382 return error;
2383}
2384
2385Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002386ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp)
Chris Lattner24943d22010-06-08 16:52:24 +00002387{
2388 Error error;
2389 if (wp)
2390 {
2391 user_id_t watchID = wp->GetID();
2392
Greg Claytone005f2c2010-11-06 01:53:30 +00002393 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002394
2395 addr_t addr = wp->GetLoadAddress();
2396 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002397 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002398
Johnny Chen21900fb2011-09-06 22:38:36 +00002399 if (!wp->IsEnabled())
2400 {
2401 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002402 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 +00002403 // See also 'class WatchpointSentry' within StopInfo.cpp.
2404 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2405 // the watchpoint object to intelligently process this action.
2406 wp->SetEnabled(false);
Johnny Chen21900fb2011-09-06 22:38:36 +00002407 return error;
2408 }
2409
Chris Lattner24943d22010-06-08 16:52:24 +00002410 if (wp->IsHardware())
2411 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002412 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00002413 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00002414 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2415 {
2416 wp->SetEnabled(false);
2417 return error;
2418 }
2419 else
2420 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002421 }
2422 // TODO: clear software watchpoints if we implement them
2423 }
2424 else
2425 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002426 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002427 }
2428 if (error.Success())
2429 error.SetErrorToGenericError();
2430 return error;
2431}
2432
2433void
2434ProcessGDBRemote::Clear()
2435{
2436 m_flags = 0;
2437 m_thread_list.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002438}
2439
2440Error
2441ProcessGDBRemote::DoSignal (int signo)
2442{
2443 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00002444 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002445 if (log)
2446 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2447
2448 if (!m_gdb_comm.SendAsyncSignal (signo))
2449 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2450 return error;
2451}
2452
Chris Lattner24943d22010-06-08 16:52:24 +00002453Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002454ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)
2455{
2456 ProcessLaunchInfo launch_info;
2457 return StartDebugserverProcess(debugserver_url, launch_info);
2458}
2459
2460Error
2461ProcessGDBRemote::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 +00002462{
2463 Error error;
2464 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2465 {
2466 // If we locate debugserver, keep that located version around
2467 static FileSpec g_debugserver_file_spec;
2468
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002469 ProcessLaunchInfo debugserver_launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002470 char debugserver_path[PATH_MAX];
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002471 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002472
2473 // Always check to see if we have an environment override for the path
2474 // to the debugserver to use and use it if we do.
2475 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2476 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002477 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002478 else
2479 debugserver_file_spec = g_debugserver_file_spec;
2480 bool debugserver_exists = debugserver_file_spec.Exists();
2481 if (!debugserver_exists)
2482 {
2483 // The debugserver binary is in the LLDB.framework/Resources
2484 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002485 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002486 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002487 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002488 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002489 if (debugserver_exists)
2490 {
2491 g_debugserver_file_spec = debugserver_file_spec;
2492 }
2493 else
2494 {
2495 g_debugserver_file_spec.Clear();
2496 debugserver_file_spec.Clear();
2497 }
Chris Lattner24943d22010-06-08 16:52:24 +00002498 }
2499 }
2500
2501 if (debugserver_exists)
2502 {
2503 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2504
2505 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002506
Greg Claytone005f2c2010-11-06 01:53:30 +00002507 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002508
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002509 Args &debugserver_args = debugserver_launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002510 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002511
Chris Lattner24943d22010-06-08 16:52:24 +00002512 // Start args with "debugserver /file/path -r --"
2513 debugserver_args.AppendArgument(debugserver_path);
2514 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002515 // use native registers, not the GDB registers
2516 debugserver_args.AppendArgument("--native-regs");
2517 // make debugserver run in its own session so signals generated by
2518 // special terminal key sequences (^C) don't affect debugserver
2519 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002520
Chris Lattner24943d22010-06-08 16:52:24 +00002521 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2522 if (env_debugserver_log_file)
2523 {
2524 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2525 debugserver_args.AppendArgument(arg_cstr);
2526 }
2527
2528 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2529 if (env_debugserver_log_flags)
2530 {
2531 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2532 debugserver_args.AppendArgument(arg_cstr);
2533 }
Jim Ingham2b2ac8c2012-10-03 22:31:30 +00002534// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
2535// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002536
Greg Claytonb72d0f02011-04-12 05:54:46 +00002537 // We currently send down all arguments, attach pids, or attach
2538 // process names in dedicated GDB server packets, so we don't need
2539 // to pass them as arguments. This is currently because of all the
2540 // things we need to setup prior to launching: the environment,
2541 // current working dir, file actions, etc.
2542#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002543 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002544 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002545 {
Greg Claytona2f74232011-02-24 22:24:29 +00002546 // Terminate the debugserver args so we can now append the inferior args
2547 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002548
Greg Claytona2f74232011-02-24 22:24:29 +00002549 for (int i = 0; inferior_argv[i] != NULL; ++i)
2550 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002551 }
2552 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2553 {
2554 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2555 debugserver_args.AppendArgument (arg_cstr);
2556 }
2557 else if (attach_name && attach_name[0])
2558 {
2559 if (wait_for_launch)
2560 debugserver_args.AppendArgument ("--waitfor");
2561 else
2562 debugserver_args.AppendArgument ("--attach");
2563 debugserver_args.AppendArgument (attach_name);
2564 }
Chris Lattner24943d22010-06-08 16:52:24 +00002565#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002566
2567 ProcessLaunchInfo::FileAction file_action;
2568
2569 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2570 // to "/dev/null" if we run into any problems.
2571 file_action.Close (STDIN_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002572 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002573 file_action.Close (STDOUT_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002574 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002575 file_action.Close (STDERR_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002576 debugserver_launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002577
2578 if (log)
2579 {
2580 StreamString strm;
2581 debugserver_args.Dump (&strm);
2582 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2583 }
2584
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002585 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2586 debugserver_launch_info.SetUserID(process_info.GetUserID());
Greg Clayton1c4642c2011-11-16 05:37:56 +00002587
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002588 error = Host::LaunchProcess(debugserver_launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002589
Greg Claytonb72d0f02011-04-12 05:54:46 +00002590 if (error.Success ())
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002591 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002592 else
Chris Lattner24943d22010-06-08 16:52:24 +00002593 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2594
2595 if (error.Fail() || log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002596 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%" PRIu64 ", path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002597 }
2598 else
2599 {
Greg Clayton9c236732011-10-26 00:56:27 +00002600 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002601 }
2602
2603 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2604 StartAsyncThread ();
2605 }
2606 return error;
2607}
2608
2609bool
2610ProcessGDBRemote::MonitorDebugserverProcess
2611(
2612 void *callback_baton,
2613 lldb::pid_t debugserver_pid,
Greg Clayton1c4642c2011-11-16 05:37:56 +00002614 bool exited, // True if the process did exit
Chris Lattner24943d22010-06-08 16:52:24 +00002615 int signo, // Zero for no signal
2616 int exit_status // Exit value of process if signal is zero
2617)
2618{
Greg Clayton1c4642c2011-11-16 05:37:56 +00002619 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2620 // and might not exist anymore, so we need to carefully try to get the
2621 // target for this process first since we have a race condition when
2622 // we are done running between getting the notice that the inferior
2623 // process has died and the debugserver that was debugging this process.
2624 // In our test suite, we are also continually running process after
2625 // process, so we must be very careful to make sure:
2626 // 1 - process object hasn't been deleted already
2627 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner24943d22010-06-08 16:52:24 +00002628
2629 // "debugserver_pid" argument passed in is the process ID for
2630 // debugserver that we are tracking...
Greg Clayton1c4642c2011-11-16 05:37:56 +00002631 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002632
Greg Clayton75ccf502010-08-21 02:22:51 +00002633 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002634
Greg Clayton1c4642c2011-11-16 05:37:56 +00002635 // Get a shared pointer to the target that has a matching process pointer.
2636 // This target could be gone, or the target could already have a new process
2637 // object inside of it
2638 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2639
Greg Clayton72e1c782011-01-22 23:43:18 +00002640 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002641 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 +00002642
Greg Clayton1c4642c2011-11-16 05:37:56 +00002643 if (target_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002644 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002645 // We found a process in a target that matches, but another thread
2646 // might be in the process of launching a new process that will
2647 // soon replace it, so get a shared pointer to the process so we
2648 // can keep it alive.
2649 ProcessSP process_sp (target_sp->GetProcessSP());
2650 // Now we have a shared pointer to the process that can't go away on us
2651 // so we now make sure it was the same as the one passed in, and also make
2652 // sure that our previous "process *" didn't get deleted and have a new
2653 // "process *" created in its place with the same pointer. To verify this
2654 // we make sure the process has our debugserver process ID. If we pass all
2655 // of these tests, then we are sure that this process is the one we were
2656 // looking for.
2657 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner24943d22010-06-08 16:52:24 +00002658 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002659 // Sleep for a half a second to make sure our inferior process has
2660 // time to set its exit status before we set it incorrectly when
2661 // both the debugserver and the inferior process shut down.
2662 usleep (500000);
2663 // If our process hasn't yet exited, debugserver might have died.
2664 // If the process did exit, the we are reaping it.
2665 const StateType state = process->GetState();
2666
2667 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2668 state != eStateInvalid &&
2669 state != eStateUnloaded &&
2670 state != eStateExited &&
2671 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002672 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002673 char error_str[1024];
2674 if (signo)
2675 {
2676 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2677 if (signal_cstr)
2678 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2679 else
2680 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2681 }
Chris Lattner24943d22010-06-08 16:52:24 +00002682 else
Greg Clayton1c4642c2011-11-16 05:37:56 +00002683 {
2684 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2685 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002686
Greg Clayton1c4642c2011-11-16 05:37:56 +00002687 process->SetExitStatus (-1, error_str);
2688 }
2689 // Debugserver has exited we need to let our ProcessGDBRemote
2690 // know that it no longer has a debugserver instance
2691 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton75ccf502010-08-21 02:22:51 +00002692 }
Chris Lattner24943d22010-06-08 16:52:24 +00002693 }
2694 return true;
2695}
2696
2697void
2698ProcessGDBRemote::KillDebugserverProcess ()
2699{
2700 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2701 {
2702 ::kill (m_debugserver_pid, SIGINT);
2703 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2704 }
2705}
2706
2707void
2708ProcessGDBRemote::Initialize()
2709{
2710 static bool g_initialized = false;
2711
2712 if (g_initialized == false)
2713 {
2714 g_initialized = true;
2715 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2716 GetPluginDescriptionStatic(),
2717 CreateInstance);
2718
2719 Log::Callbacks log_callbacks = {
2720 ProcessGDBRemoteLog::DisableLog,
2721 ProcessGDBRemoteLog::EnableLog,
2722 ProcessGDBRemoteLog::ListLogCategories
2723 };
2724
2725 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2726 }
2727}
2728
2729bool
Chris Lattner24943d22010-06-08 16:52:24 +00002730ProcessGDBRemote::StartAsyncThread ()
2731{
Greg Claytone005f2c2010-11-06 01:53:30 +00002732 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002733
2734 if (log)
2735 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Inghama9488302012-11-01 01:15:33 +00002736
2737 Mutex::Locker start_locker(m_async_thread_state_mutex);
2738 if (m_async_thread_state == eAsyncThreadNotStarted)
2739 {
2740 // Create a thread that watches our internal state and controls which
2741 // events make it to clients (into the DCProcess event queue).
2742 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2743 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2744 {
2745 m_async_thread_state = eAsyncThreadRunning;
2746 return true;
2747 }
2748 else
2749 return false;
2750 }
2751 else
2752 {
2753 // Somebody tried to start the async thread while it was either being started or stopped. If the former, and
2754 // it started up successfully, then say all's well. Otherwise it is an error, since we aren't going to restart it.
2755 if (log)
2756 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
2757 if (m_async_thread_state == eAsyncThreadRunning)
2758 return true;
2759 else
2760 return false;
2761 }
Chris Lattner24943d22010-06-08 16:52:24 +00002762}
2763
2764void
2765ProcessGDBRemote::StopAsyncThread ()
2766{
Greg Claytone005f2c2010-11-06 01:53:30 +00002767 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002768
2769 if (log)
2770 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2771
Jim Inghama9488302012-11-01 01:15:33 +00002772 Mutex::Locker start_locker(m_async_thread_state_mutex);
2773 if (m_async_thread_state == eAsyncThreadRunning)
Chris Lattner24943d22010-06-08 16:52:24 +00002774 {
Jim Inghama9488302012-11-01 01:15:33 +00002775 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2776
2777 // This will shut down the async thread.
2778 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
2779
2780 // Stop the stdio thread
2781 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2782 {
2783 Host::ThreadJoin (m_async_thread, NULL, NULL);
2784 }
2785 m_async_thread_state = eAsyncThreadDone;
2786 }
2787 else
2788 {
2789 if (log)
2790 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
Chris Lattner24943d22010-06-08 16:52:24 +00002791 }
2792}
2793
2794
2795void *
2796ProcessGDBRemote::AsyncThread (void *arg)
2797{
2798 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2799
Greg Claytone005f2c2010-11-06 01:53:30 +00002800 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002801 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002802 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002803
2804 Listener listener ("ProcessGDBRemote::AsyncThread");
2805 EventSP event_sp;
2806 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2807 eBroadcastBitAsyncThreadShouldExit;
2808
2809 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2810 {
Greg Claytona2f74232011-02-24 22:24:29 +00002811 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2812
Chris Lattner24943d22010-06-08 16:52:24 +00002813 bool done = false;
2814 while (!done)
2815 {
2816 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002817 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002818 if (listener.WaitForEvent (NULL, event_sp))
2819 {
2820 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002821 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002822 {
Greg Claytona2f74232011-02-24 22:24:29 +00002823 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002824 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 +00002825
Greg Claytona2f74232011-02-24 22:24:29 +00002826 switch (event_type)
2827 {
2828 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002829 {
Greg Claytona2f74232011-02-24 22:24:29 +00002830 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002831
Greg Claytona2f74232011-02-24 22:24:29 +00002832 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002833 {
Greg Claytona2f74232011-02-24 22:24:29 +00002834 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2835 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2836 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002837 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002838
Greg Claytona2f74232011-02-24 22:24:29 +00002839 if (::strstr (continue_cstr, "vAttach") == NULL)
2840 process->SetPrivateState(eStateRunning);
2841 StringExtractorGDBRemote response;
2842 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002843
Greg Clayton67b402c2012-05-16 02:48:06 +00002844 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
2845 // The thread ID list might be contained within the "response", or the stop reply packet that
2846 // caused the stop. So clear it now before we give the stop reply packet to the process
2847 // using the process->SetLastStopPacket()...
2848 process->ClearThreadIDList ();
2849
Greg Claytona2f74232011-02-24 22:24:29 +00002850 switch (stop_state)
2851 {
2852 case eStateStopped:
2853 case eStateCrashed:
2854 case eStateSuspended:
Greg Clayton06709002011-12-06 04:51:14 +00002855 process->SetLastStopPacket (response);
Greg Claytona2f74232011-02-24 22:24:29 +00002856 process->SetPrivateState (stop_state);
2857 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002858
Greg Claytona2f74232011-02-24 22:24:29 +00002859 case eStateExited:
Greg Clayton06709002011-12-06 04:51:14 +00002860 process->SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00002861 process->ClearThreadIDList();
Greg Claytona2f74232011-02-24 22:24:29 +00002862 response.SetFilePos(1);
2863 process->SetExitStatus(response.GetHexU8(), NULL);
2864 done = true;
2865 break;
2866
2867 case eStateInvalid:
2868 process->SetExitStatus(-1, "lost connection");
2869 break;
2870
2871 default:
2872 process->SetPrivateState (stop_state);
2873 break;
2874 }
Chris Lattner24943d22010-06-08 16:52:24 +00002875 }
2876 }
Greg Claytona2f74232011-02-24 22:24:29 +00002877 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002878
Greg Claytona2f74232011-02-24 22:24:29 +00002879 case eBroadcastBitAsyncThreadShouldExit:
2880 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002881 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Claytona2f74232011-02-24 22:24:29 +00002882 done = true;
2883 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002884
Greg Claytona2f74232011-02-24 22:24:29 +00002885 default:
2886 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002887 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 +00002888 done = true;
2889 break;
2890 }
2891 }
2892 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2893 {
2894 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2895 {
2896 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002897 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002898 }
Chris Lattner24943d22010-06-08 16:52:24 +00002899 }
2900 }
2901 else
2902 {
2903 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002904 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 +00002905 done = true;
2906 }
2907 }
2908 }
2909
2910 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002911 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002912
2913 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2914 return NULL;
2915}
2916
Chris Lattner24943d22010-06-08 16:52:24 +00002917const char *
2918ProcessGDBRemote::GetDispatchQueueNameForThread
2919(
2920 addr_t thread_dispatch_qaddr,
2921 std::string &dispatch_queue_name
2922)
2923{
2924 dispatch_queue_name.clear();
2925 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2926 {
2927 // Cache the dispatch_queue_offsets_addr value so we don't always have
2928 // to look it up
2929 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2930 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002931 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
2932 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton444fe992012-02-26 05:51:37 +00002933 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false));
2934 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002935 if (module_sp)
2936 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2937
2938 if (dispatch_queue_offsets_symbol == NULL)
2939 {
Greg Clayton444fe992012-02-26 05:51:37 +00002940 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false));
2941 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_module_spec);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00002942 if (module_sp)
2943 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
2944 }
Chris Lattner24943d22010-06-08 16:52:24 +00002945 if (dispatch_queue_offsets_symbol)
Greg Clayton0c31d3d2012-03-07 21:03:09 +00002946 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002947
2948 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
2949 return NULL;
2950 }
2951
2952 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00002953 DataExtractor data (memory_buffer,
2954 sizeof(memory_buffer),
2955 m_target.GetArchitecture().GetByteOrder(),
2956 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00002957
2958 // Excerpt from src/queue_private.h
2959 struct dispatch_queue_offsets_s
2960 {
2961 uint16_t dqo_version;
Jason Molenda9704ca22012-11-10 06:54:30 +00002962 uint16_t dqo_label; // in version 1-3, offset to string; in version 4+, offset to a pointer to a string
2963 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 +00002964 } dispatch_queue_offsets;
2965
2966
2967 Error error;
2968 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
2969 {
2970 uint32_t data_offset = 0;
2971 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
2972 {
2973 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2974 {
2975 data_offset = 0;
2976 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
Jason Molenda9704ca22012-11-10 06:54:30 +00002977 if (dispatch_queue_offsets.dqo_version >= 4)
2978 {
2979 // libdispatch versions 4+, pointer to dispatch name is in the
2980 // queue structure.
2981 lldb::addr_t pointer_to_label_address = queue_addr + dispatch_queue_offsets.dqo_label;
2982 if (ReadMemory (pointer_to_label_address, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
2983 {
2984 data_offset = 0;
2985 lldb::addr_t label_addr = data.GetAddress(&data_offset);
2986 ReadCStringFromMemory (label_addr, dispatch_queue_name, error);
2987 }
2988 }
2989 else
2990 {
2991 // libdispatch versions 1-3, dispatch name is a fixed width char array
2992 // in the queue structure.
2993 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
2994 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
2995 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
2996 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
2997 dispatch_queue_name.erase (bytes_read);
2998 }
Chris Lattner24943d22010-06-08 16:52:24 +00002999 }
3000 }
3001 }
3002 }
3003 if (dispatch_queue_name.empty())
3004 return NULL;
3005 return dispatch_queue_name.c_str();
3006}
3007
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003008//uint32_t
3009//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3010//{
3011// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
3012// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
3013// if (m_local_debugserver)
3014// {
3015// return Host::ListProcessesMatchingName (name, matches, pids);
3016// }
3017// else
3018// {
3019// // FIXME: Implement talking to the remote debugserver.
3020// return 0;
3021// }
3022//
3023//}
3024//
Jim Ingham55e01d82011-01-22 01:33:44 +00003025bool
3026ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
3027 lldb_private::StoppointCallbackContext *context,
3028 lldb::user_id_t break_id,
3029 lldb::user_id_t break_loc_id)
3030{
3031 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3032 // run so I can stop it if that's what I want to do.
3033 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
3034 if (log)
3035 log->Printf("Hit New Thread Notification breakpoint.");
3036 return false;
3037}
3038
3039
3040bool
3041ProcessGDBRemote::StartNoticingNewThreads()
3042{
Jim Ingham55e01d82011-01-22 01:33:44 +00003043 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003044 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00003045 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003046 if (log && log->GetVerbose())
3047 log->Printf("Enabled noticing new thread breakpoint.");
3048 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham55e01d82011-01-22 01:33:44 +00003049 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003050 else
Jim Ingham55e01d82011-01-22 01:33:44 +00003051 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003052 PlatformSP platform_sp (m_target.GetPlatform());
3053 if (platform_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00003054 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003055 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3056 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00003057 {
Jim Ingham6bb73372011-10-15 00:21:37 +00003058 if (log && log->GetVerbose())
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003059 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3060 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham55e01d82011-01-22 01:33:44 +00003061 }
3062 else
3063 {
3064 if (log)
3065 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00003066 }
3067 }
3068 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003069 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham55e01d82011-01-22 01:33:44 +00003070}
3071
3072bool
3073ProcessGDBRemote::StopNoticingNewThreads()
3074{
Jim Inghamff276fe2011-02-08 05:19:01 +00003075 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham6bb73372011-10-15 00:21:37 +00003076 if (log && log->GetVerbose())
Jim Inghamff276fe2011-02-08 05:19:01 +00003077 log->Printf ("Disabling new thread notification breakpoint.");
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003078
3079 if (m_thread_create_bp_sp)
3080 m_thread_create_bp_sp->SetEnabled(false);
3081
Jim Ingham55e01d82011-01-22 01:33:44 +00003082 return true;
3083}
3084
Jason Molendab46937c2012-10-03 01:29:34 +00003085lldb_private::DynamicLoader *
3086ProcessGDBRemote::GetDynamicLoader ()
3087{
3088 if (m_dyld_ap.get() == NULL)
3089 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, m_dyld_plugin_name.empty() ? NULL : m_dyld_plugin_name.c_str()));
3090 return m_dyld_ap.get();
3091}
Jim Ingham55e01d82011-01-22 01:33:44 +00003092
Greg Clayton13193d52012-10-13 02:07:45 +00003093
Greg Claytonb8596392012-10-15 22:42:16 +00003094class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton13193d52012-10-13 02:07:45 +00003095{
3096private:
3097
3098public:
Greg Claytonb8596392012-10-15 22:42:16 +00003099 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton13193d52012-10-13 02:07:45 +00003100 CommandObjectParsed (interpreter,
Greg Claytonb8596392012-10-15 22:42:16 +00003101 "process plugin packet history",
3102 "Dumps the packet history buffer. ",
Greg Clayton13193d52012-10-13 02:07:45 +00003103 NULL)
3104 {
3105 }
3106
Greg Claytonb8596392012-10-15 22:42:16 +00003107 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton13193d52012-10-13 02:07:45 +00003108 {
3109 }
3110
3111 bool
3112 DoExecute (Args& command, CommandReturnObject &result)
3113 {
Greg Claytonb8596392012-10-15 22:42:16 +00003114 const size_t argc = command.GetArgumentCount();
3115 if (argc == 0)
3116 {
3117 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3118 if (process)
3119 {
3120 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
3121 result.SetStatus (eReturnStatusSuccessFinishResult);
3122 return true;
3123 }
3124 }
3125 else
3126 {
3127 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
3128 }
3129 result.SetStatus (eReturnStatusFailed);
3130 return false;
3131 }
3132};
3133
3134class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
3135{
3136private:
3137
3138public:
3139 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
3140 CommandObjectParsed (interpreter,
3141 "process plugin packet send",
3142 "Send a custom packet through the GDB remote protocol and print the answer. "
3143 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
3144 NULL)
3145 {
3146 }
3147
3148 ~CommandObjectProcessGDBRemotePacketSend ()
3149 {
3150 }
3151
3152 bool
3153 DoExecute (Args& command, CommandReturnObject &result)
3154 {
3155 const size_t argc = command.GetArgumentCount();
3156 if (argc == 0)
3157 {
3158 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
3159 result.SetStatus (eReturnStatusFailed);
3160 return false;
3161 }
3162
3163 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3164 if (process)
3165 {
Han Ming Ongae9cc552012-11-26 20:42:03 +00003166 for (size_t i=0; i<argc; ++ i)
Greg Claytonb8596392012-10-15 22:42:16 +00003167 {
Han Ming Ongae9cc552012-11-26 20:42:03 +00003168 const char *packet_cstr = command.GetArgumentAtIndex(0);
3169 bool send_async = true;
3170 StringExtractorGDBRemote response;
3171 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3172 result.SetStatus (eReturnStatusSuccessFinishResult);
3173 Stream &output_strm = result.GetOutputStream();
3174 output_strm.Printf (" packet: %s\n", packet_cstr);
3175 const std::string &response_str = response.GetStringRef();
3176 if (response_str.empty())
3177 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3178 else
3179 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Claytonb8596392012-10-15 22:42:16 +00003180 }
Greg Claytonb8596392012-10-15 22:42:16 +00003181 }
Greg Clayton13193d52012-10-13 02:07:45 +00003182 return true;
3183 }
3184};
3185
Greg Claytonb8596392012-10-15 22:42:16 +00003186class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
3187{
3188private:
3189
3190public:
3191 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
3192 CommandObjectMultiword (interpreter,
3193 "process plugin packet",
3194 "Commands that deal with GDB remote packets.",
3195 NULL)
3196 {
3197 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
3198 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
3199 }
3200
3201 ~CommandObjectProcessGDBRemotePacket ()
3202 {
3203 }
3204};
Greg Clayton13193d52012-10-13 02:07:45 +00003205
3206class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
3207{
3208public:
3209 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
3210 CommandObjectMultiword (interpreter,
3211 "process plugin",
3212 "A set of commands for operating on a ProcessGDBRemote process.",
3213 "process plugin <subcommand> [<subcommand-options>]")
3214 {
3215 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
3216 }
3217
3218 ~CommandObjectMultiwordProcessGDBRemote ()
3219 {
3220 }
3221};
3222
Greg Clayton13193d52012-10-13 02:07:45 +00003223CommandObject *
3224ProcessGDBRemote::GetPluginCommandObject()
3225{
3226 if (!m_command_sp)
3227 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
3228 return m_command_sp.get();
3229}