blob: ce220d33abd97702f4e35e6aa2ada9900a287a5b [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;
Greg Claytonc290ba42013-01-21 22:17:50 +0000283 std::vector<uint32_t> value_regs;
284 std::vector<uint32_t> invalidate_regs;
Chris Lattner24943d22010-06-08 16:52:24 +0000285 RegisterInfo reg_info = { NULL, // Name
286 NULL, // Alt name
287 0, // byte size
288 reg_offset, // offset
289 eEncodingUint, // encoding
290 eFormatHex, // formate
Chris Lattner24943d22010-06-08 16:52:24 +0000291 {
292 LLDB_INVALID_REGNUM, // GCC reg num
293 LLDB_INVALID_REGNUM, // DWARF reg num
294 LLDB_INVALID_REGNUM, // generic reg num
Jason Molenda3a4ea242010-09-10 07:49:16 +0000295 reg_num, // GDB reg num
296 reg_num // native register number
Greg Claytoncd330422012-02-29 19:27:27 +0000297 },
298 NULL,
299 NULL
Chris Lattner24943d22010-06-08 16:52:24 +0000300 };
301
302 while (response.GetNameColonValue(name, value))
303 {
304 if (name.compare("name") == 0)
305 {
306 reg_name.SetCString(value.c_str());
307 }
308 else if (name.compare("alt-name") == 0)
309 {
310 alt_name.SetCString(value.c_str());
311 }
312 else if (name.compare("bitsize") == 0)
313 {
314 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
315 }
316 else if (name.compare("offset") == 0)
317 {
318 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda53d96862010-06-11 23:44:18 +0000319 if (reg_offset != offset)
Chris Lattner24943d22010-06-08 16:52:24 +0000320 {
321 reg_offset = offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000322 }
323 }
324 else if (name.compare("encoding") == 0)
325 {
Greg Clayton88b980b2012-08-24 01:42:50 +0000326 const Encoding encoding = Args::StringToEncoding (value.c_str());
327 if (encoding != eEncodingInvalid)
328 reg_info.encoding = encoding;
Chris Lattner24943d22010-06-08 16:52:24 +0000329 }
330 else if (name.compare("format") == 0)
331 {
Greg Clayton88b980b2012-08-24 01:42:50 +0000332 Format format = eFormatInvalid;
333 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
334 reg_info.format = format;
335 else if (value.compare("binary") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +0000336 reg_info.format = eFormatBinary;
337 else if (value.compare("decimal") == 0)
338 reg_info.format = eFormatDecimal;
339 else if (value.compare("hex") == 0)
340 reg_info.format = eFormatHex;
341 else if (value.compare("float") == 0)
342 reg_info.format = eFormatFloat;
343 else if (value.compare("vector-sint8") == 0)
344 reg_info.format = eFormatVectorOfSInt8;
345 else if (value.compare("vector-uint8") == 0)
346 reg_info.format = eFormatVectorOfUInt8;
347 else if (value.compare("vector-sint16") == 0)
348 reg_info.format = eFormatVectorOfSInt16;
349 else if (value.compare("vector-uint16") == 0)
350 reg_info.format = eFormatVectorOfUInt16;
351 else if (value.compare("vector-sint32") == 0)
352 reg_info.format = eFormatVectorOfSInt32;
353 else if (value.compare("vector-uint32") == 0)
354 reg_info.format = eFormatVectorOfUInt32;
355 else if (value.compare("vector-float32") == 0)
356 reg_info.format = eFormatVectorOfFloat32;
357 else if (value.compare("vector-uint128") == 0)
358 reg_info.format = eFormatVectorOfUInt128;
359 }
360 else if (name.compare("set") == 0)
361 {
362 set_name.SetCString(value.c_str());
363 }
364 else if (name.compare("gcc") == 0)
365 {
366 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
367 }
368 else if (name.compare("dwarf") == 0)
369 {
370 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
371 }
372 else if (name.compare("generic") == 0)
373 {
Greg Clayton88b980b2012-08-24 01:42:50 +0000374 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000375 }
Greg Claytonc290ba42013-01-21 22:17:50 +0000376 else if (name.compare("container-regs") == 0)
377 {
378 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
379 value_pair.second = value;
380 do
381 {
382 value_pair = value_pair.second.split(',');
383 if (!value_pair.first.empty())
384 {
385 value_regs.push_back (Args::StringToUInt32 (value_pair.first.str().c_str()));
386 }
387 } while (!value_pair.second.empty());
388 }
389 else if (name.compare("invalidate-regs") == 0)
390 {
391 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
392 value_pair.second = value;
393 do
394 {
395 value_pair = value_pair.second.split(',');
396 if (!value_pair.first.empty())
397 {
398 invalidate_regs.push_back (Args::StringToUInt32 (value_pair.first.str().c_str()));
399 }
400 } while (!value_pair.second.empty());
401 }
Chris Lattner24943d22010-06-08 16:52:24 +0000402 }
403
Jason Molenda53d96862010-06-11 23:44:18 +0000404 reg_info.byte_offset = reg_offset;
Chris Lattner24943d22010-06-08 16:52:24 +0000405 assert (reg_info.byte_size != 0);
406 reg_offset += reg_info.byte_size;
Greg Claytonc290ba42013-01-21 22:17:50 +0000407 if (!value_regs.empty())
408 {
409 value_regs.push_back(LLDB_INVALID_REGNUM);
410 reg_info.value_regs = value_regs.data();
411 }
412 if (!invalidate_regs.empty())
413 {
414 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
415 reg_info.invalidate_regs = invalidate_regs.data();
416 }
417
Chris Lattner24943d22010-06-08 16:52:24 +0000418 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
419 }
420 }
421 else
422 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000423 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000424 }
425 }
426
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000427 // We didn't get anything if the accumulated reg_num is zero. See if we are
428 // debugging ARM and fill with a hard coded register set until we can get an
429 // updated debugserver down on the devices.
430 // On the other hand, if the accumulated reg_num is positive, see if we can
431 // add composite registers to the existing primordial ones.
432 bool from_scratch = (reg_num == 0);
433
434 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Jason Molendafe555672012-12-19 02:54:03 +0000435 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
436 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
437
438 // Use the process' architecture instead of the host arch, if available
439 ArchSpec remote_arch;
440 if (remote_process_arch.IsValid ())
441 remote_arch = remote_process_arch;
442 else
443 remote_arch = remote_host_arch;
444
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000445 if (!target_arch.IsValid())
Chris Lattner24943d22010-06-08 16:52:24 +0000446 {
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000447 if (remote_arch.IsValid()
448 && remote_arch.GetMachine() == llvm::Triple::arm
449 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
450 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner24943d22010-06-08 16:52:24 +0000451 }
Johnny Chenb7cdd6c2012-05-14 18:44:23 +0000452 else if (target_arch.GetMachine() == llvm::Triple::arm)
453 {
454 m_register_info.HardcodeARMRegisters(from_scratch);
455 }
456
457 // At this point, we can finalize our register info.
Chris Lattner24943d22010-06-08 16:52:24 +0000458 m_register_info.Finalize ();
459}
460
461Error
462ProcessGDBRemote::WillLaunch (Module* module)
463{
464 return WillLaunchOrAttach ();
465}
466
467Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000468ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000469{
470 return WillLaunchOrAttach ();
471}
472
473Error
Greg Clayton20d338f2010-11-18 05:57:03 +0000474ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +0000475{
476 return WillLaunchOrAttach ();
477}
478
479Error
Jason Molendafac2e622012-09-29 04:02:01 +0000480ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytone71e2582011-02-04 01:58:07 +0000481{
482 Error error (WillLaunchOrAttach ());
483
484 if (error.Fail())
485 return error;
486
Greg Clayton180546b2011-04-30 01:09:13 +0000487 error = ConnectToDebugserver (remote_url);
Greg Claytone71e2582011-02-04 01:58:07 +0000488
489 if (error.Fail())
490 return error;
491 StartAsyncThread ();
492
Jason Molendab46937c2012-10-03 01:29:34 +0000493 CheckForKernel (strm);
Jason Molendafac2e622012-09-29 04:02:01 +0000494
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000495 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone71e2582011-02-04 01:58:07 +0000496 if (pid == LLDB_INVALID_PROCESS_ID)
497 {
498 // We don't have a valid process ID, so note that we are connected
499 // and could now request to launch or attach, or get remote process
500 // listings...
501 SetPrivateState (eStateConnected);
502 }
503 else
504 {
505 // We have a valid process
506 SetID (pid);
Greg Clayton37f962e2011-08-22 02:49:39 +0000507 GetThreadList();
Greg Clayton261a18b2011-06-02 22:22:38 +0000508 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytone71e2582011-02-04 01:58:07 +0000509 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000510 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytone71e2582011-02-04 01:58:07 +0000511 if (state == eStateStopped)
512 {
513 SetPrivateState (state);
514 }
515 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000516 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 +0000517 }
518 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000519 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 +0000520 }
Jason Molendacb740b32012-05-03 22:37:30 +0000521
522 if (error.Success()
523 && !GetTarget().GetArchitecture().IsValid()
524 && m_gdb_comm.GetHostArchitecture().IsValid())
525 {
Jason Molendafe555672012-12-19 02:54:03 +0000526 // Prefer the *process'* architecture over that of the *host*, if available.
527 if (m_gdb_comm.GetProcessArchitecture().IsValid())
528 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
529 else
530 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molendacb740b32012-05-03 22:37:30 +0000531 }
532
Greg Claytone71e2582011-02-04 01:58:07 +0000533 return error;
534}
535
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000536// When we are establishing a connection to a remote system and we have no executable specified,
537// or the executable is a kernel, we may be looking at a KASLR situation (where the kernel has been
538// slid in memory.)
539//
Jason Molendab46937c2012-10-03 01:29:34 +0000540// This function tries to locate the kernel in memory if this is possibly a kernel debug session.
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000541//
Jason Molendab46937c2012-10-03 01:29:34 +0000542// If a kernel is found, return the address of the kernel in GetImageInfoAddress() -- the
543// DynamicLoaderDarwinKernel plugin uses this address as the kernel load address and will load the
544// binary, if needed, along with all the kexts.
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000545
546void
Jason Molendab46937c2012-10-03 01:29:34 +0000547ProcessGDBRemote::CheckForKernel (Stream *strm)
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000548{
549 // early return if this isn't an "unknown" system (kernel debugging doesn't have a system type)
550 const ArchSpec &gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
551 if (!gdb_remote_arch.IsValid() || gdb_remote_arch.GetTriple().getVendor() != llvm::Triple::UnknownVendor)
552 return;
553
554 Module *exe_module = GetTarget().GetExecutableModulePointer();
555 ObjectFile *exe_objfile = NULL;
556 if (exe_module)
557 exe_objfile = exe_module->GetObjectFile();
558
559 // early return if we have an executable and it is not a kernel--this is very unlikely to be a kernel debug session.
560 if (exe_objfile
561 && (exe_objfile->GetType() != ObjectFile::eTypeExecutable
562 || exe_objfile->GetStrata() != ObjectFile::eStrataKernel))
563 return;
564
565 // See if the kernel is in memory at the File address (slide == 0) -- no work needed, if so.
566 if (exe_objfile && exe_objfile->GetHeaderAddress().IsValid())
567 {
568 ModuleSP memory_module_sp;
569 memory_module_sp = ReadModuleFromMemory (exe_module->GetFileSpec(), exe_objfile->GetHeaderAddress().GetFileAddress(), false, false);
570 if (memory_module_sp.get()
571 && memory_module_sp->GetUUID().IsValid()
572 && memory_module_sp->GetUUID() == exe_module->GetUUID())
573 {
Jason Molendab46937c2012-10-03 01:29:34 +0000574 m_kernel_load_addr = exe_objfile->GetHeaderAddress().GetFileAddress();
575 m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
Jason Molendad6b81222012-10-06 02:02:26 +0000576 SetCanJIT(false);
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000577 return;
578 }
579 }
580
581 // See if the kernel's load address is stored in the kernel's low globals page; this is
582 // done when a debug boot-arg has been set.
583
584 Error error;
585 uint8_t buf[24];
586 ModuleSP memory_module_sp;
587 addr_t kernel_addr = LLDB_INVALID_ADDRESS;
588
589 // First try the 32-bit
590 if (memory_module_sp.get() == NULL)
591 {
592 DataExtractor data4 (buf, sizeof(buf), gdb_remote_arch.GetByteOrder(), 4);
593 if (DoReadMemory (0xffff0110, buf, 4, error) == 4)
594 {
595 uint32_t offset = 0;
596 kernel_addr = data4.GetU32(&offset);
597 memory_module_sp = ReadModuleFromMemory (FileSpec("mach_kernel", false), kernel_addr, false, false);
598 if (!memory_module_sp.get()
599 || !memory_module_sp->GetUUID().IsValid()
600 || memory_module_sp->GetObjectFile() == NULL
601 || memory_module_sp->GetObjectFile()->GetType() != ObjectFile::eTypeExecutable
602 || memory_module_sp->GetObjectFile()->GetStrata() != ObjectFile::eStrataKernel)
603 {
604 memory_module_sp.reset();
605 }
606 }
607 }
608
609 // Now try the 64-bit location
610 if (memory_module_sp.get() == NULL)
611 {
612 DataExtractor data8 (buf, sizeof(buf), gdb_remote_arch.GetByteOrder(), 8);
613 if (DoReadMemory (0xffffff8000002010ULL, buf, 8, error) == 8)
614 {
615 uint32_t offset = 0;
Jason Molendac557e7d2012-12-01 04:46:58 +0000616 kernel_addr = data8.GetU64(&offset);
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000617 memory_module_sp = ReadModuleFromMemory (FileSpec("mach_kernel", false), kernel_addr, false, false);
618 if (!memory_module_sp.get()
619 || !memory_module_sp->GetUUID().IsValid()
620 || memory_module_sp->GetObjectFile() == NULL
621 || memory_module_sp->GetObjectFile()->GetType() != ObjectFile::eTypeExecutable
622 || memory_module_sp->GetObjectFile()->GetStrata() != ObjectFile::eStrataKernel)
623 {
624 memory_module_sp.reset();
625 }
626 }
627 }
628
Jason Molendab46937c2012-10-03 01:29:34 +0000629 if (memory_module_sp.get()
630 && memory_module_sp->GetArchitecture().IsValid()
631 && memory_module_sp->GetArchitecture().GetTriple().getVendor() == llvm::Triple::Apple)
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000632 {
Jason Molendab46937c2012-10-03 01:29:34 +0000633 m_kernel_load_addr = kernel_addr;
634 m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
Jason Molendad6b81222012-10-06 02:02:26 +0000635 SetCanJIT(false);
Jason Molendab46937c2012-10-03 01:29:34 +0000636 return;
Jason Molendab0e3c7c2012-09-29 08:03:33 +0000637 }
638}
639
Greg Claytone71e2582011-02-04 01:58:07 +0000640Error
Chris Lattner24943d22010-06-08 16:52:24 +0000641ProcessGDBRemote::WillLaunchOrAttach ()
642{
643 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000644 m_stdio_communication.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000645 return error;
646}
647
648//----------------------------------------------------------------------
649// Process Control
650//----------------------------------------------------------------------
651Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000652ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +0000653{
Greg Clayton4b407112010-09-30 21:49:03 +0000654 Error error;
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000655
656 uint32_t launch_flags = launch_info.GetFlags().Get();
657 const char *stdin_path = NULL;
658 const char *stdout_path = NULL;
659 const char *stderr_path = NULL;
660 const char *working_dir = launch_info.GetWorkingDirectory();
661
662 const ProcessLaunchInfo::FileAction *file_action;
663 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
664 if (file_action)
665 {
666 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
667 stdin_path = file_action->GetPath();
668 }
669 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
670 if (file_action)
671 {
672 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
673 stdout_path = file_action->GetPath();
674 }
675 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
676 if (file_action)
677 {
678 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
679 stderr_path = file_action->GetPath();
680 }
681
Chris Lattner24943d22010-06-08 16:52:24 +0000682 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
683 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
684 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton716cefb2011-08-09 05:20:29 +0000685 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000686
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000687 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner24943d22010-06-08 16:52:24 +0000688 if (object_file)
689 {
Chris Lattner24943d22010-06-08 16:52:24 +0000690 char host_port[128];
691 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytone71e2582011-02-04 01:58:07 +0000692 char connect_url[128];
693 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +0000694
Greg Claytona2f74232011-02-24 22:24:29 +0000695 // Make sure we aren't already connected?
696 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000697 {
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000698 error = StartDebugserverProcess (host_port, launch_info);
Chris Lattner24943d22010-06-08 16:52:24 +0000699 if (error.Fail())
Greg Clayton716cefb2011-08-09 05:20:29 +0000700 {
Johnny Chenc143d622011-08-09 18:56:45 +0000701 if (log)
702 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner24943d22010-06-08 16:52:24 +0000703 return error;
Greg Clayton716cefb2011-08-09 05:20:29 +0000704 }
Chris Lattner24943d22010-06-08 16:52:24 +0000705
Greg Claytone71e2582011-02-04 01:58:07 +0000706 error = ConnectToDebugserver (connect_url);
Greg Claytona2f74232011-02-24 22:24:29 +0000707 }
708
709 if (error.Success())
710 {
711 lldb_utility::PseudoTerminal pty;
712 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Claytonafb81862011-03-02 21:34:46 +0000713
714 // If the debugserver is local and we aren't disabling STDIO, lets use
715 // a pseudo terminal to instead of relying on the 'O' packets for stdio
716 // since 'O' packets can really slow down debugging if the inferior
717 // does a lot of output.
Greg Claytonb4747822011-06-24 22:32:10 +0000718 PlatformSP platform_sp (m_target.GetPlatform());
719 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Claytona2f74232011-02-24 22:24:29 +0000720 {
721 const char *slave_name = NULL;
722 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000723 {
Greg Claytona2f74232011-02-24 22:24:29 +0000724 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
725 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000726 }
Greg Claytona2f74232011-02-24 22:24:29 +0000727 if (stdin_path == NULL)
728 stdin_path = slave_name;
Chris Lattner24943d22010-06-08 16:52:24 +0000729
Greg Claytona2f74232011-02-24 22:24:29 +0000730 if (stdout_path == NULL)
731 stdout_path = slave_name;
732
733 if (stderr_path == NULL)
734 stderr_path = slave_name;
735 }
736
Greg Claytonafb81862011-03-02 21:34:46 +0000737 // Set STDIN to /dev/null if we want STDIO disabled or if either
738 // STDOUT or STDERR have been set to something and STDIN hasn't
739 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000740 stdin_path = "/dev/null";
741
Greg Claytonafb81862011-03-02 21:34:46 +0000742 // Set STDOUT to /dev/null if we want STDIO disabled or if either
743 // STDIN or STDERR have been set to something and STDOUT hasn't
744 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000745 stdout_path = "/dev/null";
746
Greg Claytonafb81862011-03-02 21:34:46 +0000747 // Set STDERR to /dev/null if we want STDIO disabled or if either
748 // STDIN or STDOUT have been set to something and STDERR hasn't
749 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Claytona2f74232011-02-24 22:24:29 +0000750 stderr_path = "/dev/null";
751
752 if (stdin_path)
753 m_gdb_comm.SetSTDIN (stdin_path);
754 if (stdout_path)
755 m_gdb_comm.SetSTDOUT (stdout_path);
756 if (stderr_path)
757 m_gdb_comm.SetSTDERR (stderr_path);
758
759 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
760
Greg Claytona4582402011-05-08 04:53:50 +0000761 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Claytona2f74232011-02-24 22:24:29 +0000762
763 if (working_dir && working_dir[0])
764 {
765 m_gdb_comm.SetWorkingDir (working_dir);
766 }
767
768 // Send the environment and the program + arguments after we connect
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000769 const Args &environment = launch_info.GetEnvironmentEntries();
770 if (environment.GetArgumentCount())
Greg Claytona2f74232011-02-24 22:24:29 +0000771 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000772 size_t num_environment_entries = environment.GetArgumentCount();
773 for (size_t i=0; i<num_environment_entries; ++i)
Greg Clayton960d6a42010-08-03 00:35:52 +0000774 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000775 const char *env_entry = environment.GetArgumentAtIndex(i);
776 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Claytona2f74232011-02-24 22:24:29 +0000777 break;
Greg Clayton960d6a42010-08-03 00:35:52 +0000778 }
Greg Claytona2f74232011-02-24 22:24:29 +0000779 }
Greg Clayton960d6a42010-08-03 00:35:52 +0000780
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000781 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000782 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info.GetArguments().GetConstArgumentVector());
Greg Claytona2f74232011-02-24 22:24:29 +0000783 if (arg_packet_err == 0)
784 {
785 std::string error_str;
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000786 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner24943d22010-06-08 16:52:24 +0000787 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000788 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner24943d22010-06-08 16:52:24 +0000789 }
790 else
791 {
Greg Claytona2f74232011-02-24 22:24:29 +0000792 error.SetErrorString (error_str.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +0000793 }
Greg Claytona2f74232011-02-24 22:24:29 +0000794 }
795 else
796 {
Greg Clayton9c236732011-10-26 00:56:27 +0000797 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Claytona2f74232011-02-24 22:24:29 +0000798 }
Greg Clayton7c4fc6e2011-08-10 22:05:39 +0000799
800 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner24943d22010-06-08 16:52:24 +0000801
Greg Claytona2f74232011-02-24 22:24:29 +0000802 if (GetID() == LLDB_INVALID_PROCESS_ID)
803 {
Johnny Chenc143d622011-08-09 18:56:45 +0000804 if (log)
805 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytona2f74232011-02-24 22:24:29 +0000806 KillDebugserverProcess ();
807 return error;
808 }
809
Greg Clayton261a18b2011-06-02 22:22:38 +0000810 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytona2f74232011-02-24 22:24:29 +0000811 {
Greg Clayton261a18b2011-06-02 22:22:38 +0000812 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Claytona2f74232011-02-24 22:24:29 +0000813
814 if (!disable_stdio)
815 {
816 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Clayton464c6162011-11-17 22:14:31 +0000817 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Claytona2f74232011-02-24 22:24:29 +0000818 }
Chris Lattner24943d22010-06-08 16:52:24 +0000819 }
820 }
Greg Clayton716cefb2011-08-09 05:20:29 +0000821 else
822 {
Johnny Chenc143d622011-08-09 18:56:45 +0000823 if (log)
824 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton716cefb2011-08-09 05:20:29 +0000825 }
Chris Lattner24943d22010-06-08 16:52:24 +0000826 }
827 else
828 {
829 // Set our user ID to an invalid process ID.
830 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000831 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
832 exe_module->GetFileSpec().GetFilename().AsCString(),
833 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner24943d22010-06-08 16:52:24 +0000834 }
Chris Lattner24943d22010-06-08 16:52:24 +0000835 return error;
Greg Clayton4b407112010-09-30 21:49:03 +0000836
Chris Lattner24943d22010-06-08 16:52:24 +0000837}
838
839
840Error
Greg Claytone71e2582011-02-04 01:58:07 +0000841ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner24943d22010-06-08 16:52:24 +0000842{
843 Error error;
844 // Sleep and wait a bit for debugserver to start to listen...
845 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
846 if (conn_ap.get())
847 {
Chris Lattner24943d22010-06-08 16:52:24 +0000848 const uint32_t max_retry_count = 50;
849 uint32_t retry_count = 0;
850 while (!m_gdb_comm.IsConnected())
851 {
Greg Claytone71e2582011-02-04 01:58:07 +0000852 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner24943d22010-06-08 16:52:24 +0000853 {
854 m_gdb_comm.SetConnection (conn_ap.release());
855 break;
856 }
857 retry_count++;
858
859 if (retry_count >= max_retry_count)
860 break;
861
862 usleep (100000);
863 }
864 }
865
866 if (!m_gdb_comm.IsConnected())
867 {
868 if (error.Success())
869 error.SetErrorString("not connected to remote gdb server");
870 return error;
871 }
872
Greg Clayton24bc5d92011-03-30 18:16:51 +0000873 // We always seem to be able to open a connection to a local port
874 // so we need to make sure we can then send data to it. If we can't
875 // then we aren't actually connected to anything, so try and do the
876 // handshake with the remote GDB server and make sure that goes
877 // alright.
878 if (!m_gdb_comm.HandshakeWithServer (NULL))
Chris Lattner24943d22010-06-08 16:52:24 +0000879 {
Greg Clayton24bc5d92011-03-30 18:16:51 +0000880 m_gdb_comm.Disconnect();
881 if (error.Success())
882 error.SetErrorString("not connected to remote gdb server");
883 return error;
Chris Lattner24943d22010-06-08 16:52:24 +0000884 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000885 m_gdb_comm.ResetDiscoverableSettings();
886 m_gdb_comm.QueryNoAckModeSupported ();
887 m_gdb_comm.GetThreadSuffixSupported ();
Greg Claytona1f645e2012-04-10 03:22:03 +0000888 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000889 m_gdb_comm.GetHostInfo ();
890 m_gdb_comm.GetVContSupported ('c');
Jim Ingham3a458eb2012-07-20 21:37:13 +0000891 m_gdb_comm.GetVAttachOrWaitSupported();
Jim Ingham86827fb2012-07-02 05:40:07 +0000892
893 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
894 for (size_t idx = 0; idx < num_cmds; idx++)
895 {
896 StringExtractorGDBRemote response;
Jim Ingham86827fb2012-07-02 05:40:07 +0000897 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
898 }
Chris Lattner24943d22010-06-08 16:52:24 +0000899 return error;
900}
901
902void
903ProcessGDBRemote::DidLaunchOrAttach ()
904{
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000905 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
906 if (log)
907 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton75c703d2011-02-16 04:46:07 +0000908 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner24943d22010-06-08 16:52:24 +0000909 {
910 m_dispatch_queue_offsets_addr = LLDB_INVALID_ADDRESS;
911
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000912 BuildDynamicRegisterInfo (false);
Greg Clayton20d338f2010-11-18 05:57:03 +0000913
Chris Lattner24943d22010-06-08 16:52:24 +0000914 // See if the GDB server supports the qHostInfo information
Greg Claytonfc7920f2011-02-09 03:09:55 +0000915
Jason Molendafe555672012-12-19 02:54:03 +0000916 ArchSpec gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
917
918 // See if the GDB server supports the qProcessInfo packet, if so
919 // prefer that over the Host information as it will be more specific
920 // to our process.
921
922 if (m_gdb_comm.GetProcessArchitecture().IsValid())
923 gdb_remote_arch = m_gdb_comm.GetProcessArchitecture();
924
Greg Claytoncb8977d2011-03-23 00:09:55 +0000925 if (gdb_remote_arch.IsValid())
Greg Claytonfc7920f2011-02-09 03:09:55 +0000926 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000927 ArchSpec &target_arch = GetTarget().GetArchitecture();
928
929 if (target_arch.IsValid())
930 {
931 // If the remote host is ARM and we have apple as the vendor, then
932 // ARM executables and shared libraries can have mixed ARM architectures.
933 // You can have an armv6 executable, and if the host is armv7, then the
934 // system will load the best possible architecture for all shared libraries
935 // it has, so we really need to take the remote host architecture as our
936 // defacto architecture in this case.
937
938 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
939 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
940 {
941 target_arch = gdb_remote_arch;
942 }
943 else
944 {
945 // Fill in what is missing in the triple
946 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
947 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton2f085c62011-05-15 01:25:55 +0000948 if (target_triple.getVendorName().size() == 0)
949 {
Greg Claytoncb8977d2011-03-23 00:09:55 +0000950 target_triple.setVendor (remote_triple.getVendor());
951
Greg Clayton2f085c62011-05-15 01:25:55 +0000952 if (target_triple.getOSName().size() == 0)
953 {
954 target_triple.setOS (remote_triple.getOS());
Greg Claytoncb8977d2011-03-23 00:09:55 +0000955
Greg Clayton2f085c62011-05-15 01:25:55 +0000956 if (target_triple.getEnvironmentName().size() == 0)
957 target_triple.setEnvironment (remote_triple.getEnvironment());
958 }
959 }
Greg Claytoncb8977d2011-03-23 00:09:55 +0000960 }
961 }
962 else
963 {
964 // The target doesn't have a valid architecture yet, set it from
965 // the architecture we got from the remote GDB server
966 target_arch = gdb_remote_arch;
967 }
Greg Claytonfc7920f2011-02-09 03:09:55 +0000968 }
Chris Lattner24943d22010-06-08 16:52:24 +0000969 }
970}
971
972void
973ProcessGDBRemote::DidLaunch ()
974{
975 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +0000976}
977
978Error
Greg Clayton54e7afa2010-07-09 20:39:50 +0000979ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner24943d22010-06-08 16:52:24 +0000980{
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000981 ProcessAttachInfo attach_info;
982 return DoAttachToProcessWithID(attach_pid, attach_info);
983}
984
985Error
986ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
987{
Chris Lattner24943d22010-06-08 16:52:24 +0000988 Error error;
989 // Clear out and clean up from any current state
990 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000991 if (attach_pid != LLDB_INVALID_PROCESS_ID)
992 {
Greg Claytona2f74232011-02-24 22:24:29 +0000993 // Make sure we aren't already connected?
994 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +0000995 {
Greg Claytona2f74232011-02-24 22:24:29 +0000996 char host_port[128];
997 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
998 char connect_url[128];
999 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner24943d22010-06-08 16:52:24 +00001000
Han Ming Ongd1040dd2012-02-25 01:07:38 +00001001 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +00001002
1003 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +00001004 {
Greg Claytona2f74232011-02-24 22:24:29 +00001005 const char *error_string = error.AsCString();
1006 if (error_string == NULL)
1007 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1008
1009 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +00001010 }
Greg Claytona2f74232011-02-24 22:24:29 +00001011 else
1012 {
1013 error = ConnectToDebugserver (connect_url);
1014 }
1015 }
1016
1017 if (error.Success())
1018 {
1019 char packet[64];
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001020 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Greg Clayton489575c2011-11-19 02:11:30 +00001021 SetID (attach_pid);
Greg Claytona2f74232011-02-24 22:24:29 +00001022 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner24943d22010-06-08 16:52:24 +00001023 }
1024 }
Chris Lattner24943d22010-06-08 16:52:24 +00001025 return error;
1026}
1027
1028size_t
1029ProcessGDBRemote::AttachInputReaderCallback
1030(
1031 void *baton,
1032 InputReader *reader,
1033 lldb::InputReaderAction notification,
1034 const char *bytes,
1035 size_t bytes_len
1036)
1037{
1038 if (notification == eInputReaderGotToken)
1039 {
1040 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
1041 if (gdb_process->m_waiting_for_attach)
1042 gdb_process->m_waiting_for_attach = false;
1043 reader->SetIsDone(true);
1044 return 1;
1045 }
1046 return 0;
1047}
1048
1049Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +00001050ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +00001051{
1052 Error error;
1053 // Clear out and clean up from any current state
1054 Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001055
Chris Lattner24943d22010-06-08 16:52:24 +00001056 if (process_name && process_name[0])
1057 {
Greg Claytona2f74232011-02-24 22:24:29 +00001058 // Make sure we aren't already connected?
1059 if (!m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00001060 {
Greg Claytona2f74232011-02-24 22:24:29 +00001061 char host_port[128];
1062 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
1063 char connect_url[128];
1064 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
1065
Han Ming Ongd1040dd2012-02-25 01:07:38 +00001066 error = StartDebugserverProcess (host_port, attach_info);
Greg Claytona2f74232011-02-24 22:24:29 +00001067 if (error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +00001068 {
Greg Claytona2f74232011-02-24 22:24:29 +00001069 const char *error_string = error.AsCString();
1070 if (error_string == NULL)
1071 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner24943d22010-06-08 16:52:24 +00001072
Greg Claytona2f74232011-02-24 22:24:29 +00001073 SetExitStatus (-1, error_string);
Chris Lattner24943d22010-06-08 16:52:24 +00001074 }
Greg Claytona2f74232011-02-24 22:24:29 +00001075 else
1076 {
1077 error = ConnectToDebugserver (connect_url);
1078 }
1079 }
1080
1081 if (error.Success())
1082 {
1083 StreamString packet;
1084
1085 if (wait_for_launch)
Jim Ingham3a458eb2012-07-20 21:37:13 +00001086 {
1087 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1088 {
1089 packet.PutCString ("vAttachWait");
1090 }
1091 else
1092 {
1093 if (attach_info.GetIgnoreExisting())
1094 packet.PutCString("vAttachWait");
1095 else
1096 packet.PutCString ("vAttachOrWait");
1097 }
1098 }
Greg Claytona2f74232011-02-24 22:24:29 +00001099 else
1100 packet.PutCString("vAttachName");
1101 packet.PutChar(';');
1102 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1103
1104 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1105
Chris Lattner24943d22010-06-08 16:52:24 +00001106 }
1107 }
Chris Lattner24943d22010-06-08 16:52:24 +00001108 return error;
1109}
1110
Chris Lattner24943d22010-06-08 16:52:24 +00001111
1112void
1113ProcessGDBRemote::DidAttach ()
1114{
Greg Claytone71e2582011-02-04 01:58:07 +00001115 DidLaunchOrAttach ();
Chris Lattner24943d22010-06-08 16:52:24 +00001116}
1117
Greg Clayton0bce9a22012-12-05 00:16:59 +00001118void
1119ProcessGDBRemote::DoDidExec ()
1120{
1121 // The process exec'ed itself, figure out the dynamic loader, etc...
1122 BuildDynamicRegisterInfo (true);
1123 m_gdb_comm.ResetDiscoverableSettings();
1124 DidLaunchOrAttach ();
1125}
1126
1127
1128
Chris Lattner24943d22010-06-08 16:52:24 +00001129Error
1130ProcessGDBRemote::WillResume ()
1131{
Greg Claytonc1f45872011-02-12 06:28:37 +00001132 m_continue_c_tids.clear();
1133 m_continue_C_tids.clear();
1134 m_continue_s_tids.clear();
1135 m_continue_S_tids.clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001136 return Error();
1137}
1138
1139Error
1140ProcessGDBRemote::DoResume ()
1141{
Jim Ingham3ae449a2010-11-17 02:32:00 +00001142 Error error;
Greg Clayton0bfda0b2011-02-05 02:25:06 +00001143 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1144 if (log)
1145 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytonb749a262010-12-03 06:02:24 +00001146
1147 Listener listener ("gdb-remote.resume-packet-sent");
1148 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1149 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001150 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1151
Greg Claytonc1f45872011-02-12 06:28:37 +00001152 StreamString continue_packet;
1153 bool continue_packet_error = false;
1154 if (m_gdb_comm.HasAnyVContSupport ())
1155 {
1156 continue_packet.PutCString ("vCont");
1157
1158 if (!m_continue_c_tids.empty())
1159 {
1160 if (m_gdb_comm.GetVContSupported ('c'))
1161 {
1162 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 +00001163 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +00001164 }
1165 else
1166 continue_packet_error = true;
1167 }
1168
1169 if (!continue_packet_error && !m_continue_C_tids.empty())
1170 {
1171 if (m_gdb_comm.GetVContSupported ('C'))
1172 {
1173 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 +00001174 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001175 }
1176 else
1177 continue_packet_error = true;
1178 }
Greg Claytonb749a262010-12-03 06:02:24 +00001179
Greg Claytonc1f45872011-02-12 06:28:37 +00001180 if (!continue_packet_error && !m_continue_s_tids.empty())
1181 {
1182 if (m_gdb_comm.GetVContSupported ('s'))
1183 {
1184 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 +00001185 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
Greg Claytonc1f45872011-02-12 06:28:37 +00001186 }
1187 else
1188 continue_packet_error = true;
1189 }
1190
1191 if (!continue_packet_error && !m_continue_S_tids.empty())
1192 {
1193 if (m_gdb_comm.GetVContSupported ('S'))
1194 {
1195 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 +00001196 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001197 }
1198 else
1199 continue_packet_error = true;
1200 }
1201
1202 if (continue_packet_error)
1203 continue_packet.GetString().clear();
1204 }
1205 else
1206 continue_packet_error = true;
1207
1208 if (continue_packet_error)
1209 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001210 // Either no vCont support, or we tried to use part of the vCont
1211 // packet that wasn't supported by the remote GDB server.
1212 // We need to try and make a simple packet that can do our continue
1213 const size_t num_threads = GetThreadList().GetSize();
1214 const size_t num_continue_c_tids = m_continue_c_tids.size();
1215 const size_t num_continue_C_tids = m_continue_C_tids.size();
1216 const size_t num_continue_s_tids = m_continue_s_tids.size();
1217 const size_t num_continue_S_tids = m_continue_S_tids.size();
1218 if (num_continue_c_tids > 0)
1219 {
1220 if (num_continue_c_tids == num_threads)
1221 {
1222 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001223 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001224 continue_packet.PutChar ('c');
1225 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001226 }
1227 else if (num_continue_c_tids == 1 &&
1228 num_continue_C_tids == 0 &&
1229 num_continue_s_tids == 0 &&
1230 num_continue_S_tids == 0 )
1231 {
1232 // Only one thread is continuing
Greg Claytonb72d0f02011-04-12 05:54:46 +00001233 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001234 continue_packet.PutChar ('c');
Greg Claytonde1dd812011-06-24 03:21:43 +00001235 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001236 }
1237 }
1238
Greg Claytonde1dd812011-06-24 03:21:43 +00001239 if (continue_packet_error && num_continue_C_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001240 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001241 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1242 num_continue_C_tids > 0 &&
1243 num_continue_s_tids == 0 &&
1244 num_continue_S_tids == 0 )
Greg Claytonc1f45872011-02-12 06:28:37 +00001245 {
1246 const int continue_signo = m_continue_C_tids.front().second;
Greg Claytonde1dd812011-06-24 03:21:43 +00001247 // Only one thread is continuing
Greg Claytonc1f45872011-02-12 06:28:37 +00001248 if (num_continue_C_tids > 1)
1249 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001250 // More that one thread with a signal, yet we don't have
1251 // vCont support and we are being asked to resume each
1252 // thread with a signal, we need to make sure they are
1253 // all the same signal, or we can't issue the continue
1254 // accurately with the current support...
1255 if (num_continue_C_tids > 1)
Greg Claytonc1f45872011-02-12 06:28:37 +00001256 {
Greg Claytonde1dd812011-06-24 03:21:43 +00001257 continue_packet_error = false;
1258 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1259 {
1260 if (m_continue_C_tids[i].second != continue_signo)
1261 continue_packet_error = true;
1262 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001263 }
Greg Claytonde1dd812011-06-24 03:21:43 +00001264 if (!continue_packet_error)
1265 m_gdb_comm.SetCurrentThreadForRun (-1);
1266 }
1267 else
1268 {
1269 // Set the continue thread ID
1270 continue_packet_error = false;
1271 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001272 }
1273 if (!continue_packet_error)
1274 {
1275 // Add threads continuing with the same signo...
Greg Claytonc1f45872011-02-12 06:28:37 +00001276 continue_packet.Printf("C%2.2x", continue_signo);
1277 }
1278 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001279 }
1280
Greg Claytonde1dd812011-06-24 03:21:43 +00001281 if (continue_packet_error && num_continue_s_tids > 0)
Greg Claytonc1f45872011-02-12 06:28:37 +00001282 {
1283 if (num_continue_s_tids == num_threads)
1284 {
1285 // All threads are resuming...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001286 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonde1dd812011-06-24 03:21:43 +00001287 continue_packet.PutChar ('s');
1288 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001289 }
1290 else if (num_continue_c_tids == 0 &&
1291 num_continue_C_tids == 0 &&
1292 num_continue_s_tids == 1 &&
1293 num_continue_S_tids == 0 )
1294 {
1295 // Only one thread is stepping
Greg Claytonb72d0f02011-04-12 05:54:46 +00001296 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Claytonc1f45872011-02-12 06:28:37 +00001297 continue_packet.PutChar ('s');
Greg Claytonde1dd812011-06-24 03:21:43 +00001298 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001299 }
1300 }
1301
1302 if (!continue_packet_error && num_continue_S_tids > 0)
1303 {
1304 if (num_continue_S_tids == num_threads)
1305 {
1306 const int step_signo = m_continue_S_tids.front().second;
1307 // Are all threads trying to step with the same signal?
Greg Claytonde1dd812011-06-24 03:21:43 +00001308 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001309 if (num_continue_S_tids > 1)
1310 {
1311 for (size_t i=1; i<num_threads; ++i)
1312 {
1313 if (m_continue_S_tids[i].second != step_signo)
1314 continue_packet_error = true;
1315 }
1316 }
1317 if (!continue_packet_error)
1318 {
1319 // Add threads stepping with the same signo...
Greg Claytonb72d0f02011-04-12 05:54:46 +00001320 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Claytonc1f45872011-02-12 06:28:37 +00001321 continue_packet.Printf("S%2.2x", step_signo);
1322 }
1323 }
1324 else if (num_continue_c_tids == 0 &&
1325 num_continue_C_tids == 0 &&
1326 num_continue_s_tids == 0 &&
1327 num_continue_S_tids == 1 )
1328 {
1329 // Only one thread is stepping with signal
Greg Claytonb72d0f02011-04-12 05:54:46 +00001330 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Claytonc1f45872011-02-12 06:28:37 +00001331 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Claytonde1dd812011-06-24 03:21:43 +00001332 continue_packet_error = false;
Greg Claytonc1f45872011-02-12 06:28:37 +00001333 }
1334 }
1335 }
1336
1337 if (continue_packet_error)
1338 {
1339 error.SetErrorString ("can't make continue packet for this resume");
1340 }
1341 else
1342 {
1343 EventSP event_sp;
1344 TimeValue timeout;
1345 timeout = TimeValue::Now();
1346 timeout.OffsetWithSeconds (5);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001347 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1348 {
1349 error.SetErrorString ("Trying to resume but the async thread is dead.");
1350 if (log)
1351 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1352 return error;
1353 }
1354
Greg Claytonc1f45872011-02-12 06:28:37 +00001355 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1356
1357 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001358 {
Greg Claytonc1f45872011-02-12 06:28:37 +00001359 error.SetErrorString("Resume timed out.");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00001360 if (log)
1361 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1362 }
1363 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1364 {
1365 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1366 if (log)
1367 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1368 return error;
1369 }
Greg Claytonc1f45872011-02-12 06:28:37 +00001370 }
Greg Claytonb749a262010-12-03 06:02:24 +00001371 }
1372
Jim Ingham3ae449a2010-11-17 02:32:00 +00001373 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001374}
1375
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001376void
1377ProcessGDBRemote::ClearThreadIDList ()
1378{
Greg Claytonff3448e2012-04-13 02:11:32 +00001379 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001380 m_thread_ids.clear();
1381}
1382
1383bool
1384ProcessGDBRemote::UpdateThreadIDList ()
1385{
Greg Claytonff3448e2012-04-13 02:11:32 +00001386 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001387 bool sequence_mutex_unavailable = false;
1388 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1389 if (sequence_mutex_unavailable)
1390 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001391 return false; // We just didn't get the list
1392 }
1393 return true;
1394}
1395
Greg Claytonae932352012-04-10 00:18:59 +00001396bool
Greg Clayton37f962e2011-08-22 02:49:39 +00001397ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner24943d22010-06-08 16:52:24 +00001398{
1399 // locker will keep a mutex locked until it goes out of scope
Greg Claytone005f2c2010-11-06 01:53:30 +00001400 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Claytonf3d0b0c2010-10-27 03:32:59 +00001401 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001402 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001403
1404 size_t num_thread_ids = m_thread_ids.size();
1405 // The "m_thread_ids" thread ID list should always be updated after each stop
1406 // reply packet, but in case it isn't, update it here.
1407 if (num_thread_ids == 0)
1408 {
1409 if (!UpdateThreadIDList ())
1410 return false;
1411 num_thread_ids = m_thread_ids.size();
1412 }
Chris Lattner24943d22010-06-08 16:52:24 +00001413
Han Ming Ongccd5c4e2013-01-08 22:10:01 +00001414 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton37f962e2011-08-22 02:49:39 +00001415 if (num_thread_ids > 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001416 {
Greg Clayton37f962e2011-08-22 02:49:39 +00001417 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001418 {
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001419 tid_t tid = m_thread_ids[i];
Han Ming Ongccd5c4e2013-01-08 22:10:01 +00001420 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByID (tid, false));
Greg Clayton37f962e2011-08-22 02:49:39 +00001421 if (!thread_sp)
Jim Ingham94a5d0d2012-10-10 18:32:14 +00001422 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Greg Clayton37f962e2011-08-22 02:49:39 +00001423 new_thread_list.AddThread(thread_sp);
Greg Clayton4a60f9e2011-05-20 23:38:13 +00001424 }
Chris Lattner24943d22010-06-08 16:52:24 +00001425 }
Han Ming Ongccd5c4e2013-01-08 22:10:01 +00001426
1427 // Whatever that is left in old_thread_list_copy are not
1428 // present in new_thread_list. Remove non-existent threads from internal id table.
1429 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1430 for (size_t i=0; i<old_num_thread_ids; i++)
1431 {
1432 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1433 if (old_thread_sp)
1434 {
1435 lldb::tid_t old_thread_id = old_thread_sp->GetID();
1436 m_thread_id_to_index_id_map.erase(old_thread_id);
1437 }
1438 }
1439
Greg Claytonae932352012-04-10 00:18:59 +00001440 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001441}
1442
1443
1444StateType
1445ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1446{
Greg Clayton261a18b2011-06-02 22:22:38 +00001447 stop_packet.SetFilePos (0);
Chris Lattner24943d22010-06-08 16:52:24 +00001448 const char stop_type = stop_packet.GetChar();
1449 switch (stop_type)
1450 {
1451 case 'T':
1452 case 'S':
1453 {
Greg Claytonc3c46612011-02-15 00:19:15 +00001454 if (GetStopID() == 0)
1455 {
1456 // Our first stop, make sure we have a process ID, and also make
1457 // sure we know about our registers
1458 if (GetID() == LLDB_INVALID_PROCESS_ID)
1459 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +00001460 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonc3c46612011-02-15 00:19:15 +00001461 if (pid != LLDB_INVALID_PROCESS_ID)
1462 SetID (pid);
1463 }
1464 BuildDynamicRegisterInfo (true);
1465 }
Chris Lattner24943d22010-06-08 16:52:24 +00001466 // Stop with signal and thread info
1467 const uint8_t signo = stop_packet.GetHexU8();
1468 std::string name;
1469 std::string value;
1470 std::string thread_name;
Greg Clayton65611552011-06-04 01:26:29 +00001471 std::string reason;
1472 std::string description;
Chris Lattner24943d22010-06-08 16:52:24 +00001473 uint32_t exc_type = 0;
Greg Clayton7661a982010-07-23 16:45:51 +00001474 std::vector<addr_t> exc_data;
Chris Lattner24943d22010-06-08 16:52:24 +00001475 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Claytona875b642011-01-09 21:07:35 +00001476 ThreadSP thread_sp;
1477
Chris Lattner24943d22010-06-08 16:52:24 +00001478 while (stop_packet.GetNameColonValue(name, value))
1479 {
1480 if (name.compare("metype") == 0)
1481 {
1482 // exception type in big endian hex
1483 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1484 }
Chris Lattner24943d22010-06-08 16:52:24 +00001485 else if (name.compare("medata") == 0)
1486 {
1487 // exception data in big endian hex
1488 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1489 }
1490 else if (name.compare("thread") == 0)
1491 {
1492 // thread in big endian hex
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001493 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Greg Claytonffa43a62011-11-17 04:46:02 +00001494 // m_thread_list does have its own mutex, but we need to
1495 // hold onto the mutex between the call to m_thread_list.FindThreadByID(...)
1496 // and the m_thread_list.AddThread(...) so it doesn't change on us
Greg Claytonc3c46612011-02-15 00:19:15 +00001497 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytona875b642011-01-09 21:07:35 +00001498 thread_sp = m_thread_list.FindThreadByID(tid, false);
Greg Claytonc3c46612011-02-15 00:19:15 +00001499 if (!thread_sp)
1500 {
1501 // Create the thread if we need to
Jim Ingham94a5d0d2012-10-10 18:32:14 +00001502 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Greg Claytonc3c46612011-02-15 00:19:15 +00001503 m_thread_list.AddThread(thread_sp);
1504 }
Chris Lattner24943d22010-06-08 16:52:24 +00001505 }
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001506 else if (name.compare("threads") == 0)
1507 {
Greg Claytonff3448e2012-04-13 02:11:32 +00001508 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001509 m_thread_ids.clear();
Greg Claytona1f645e2012-04-10 03:22:03 +00001510 // A comma separated list of all threads in the current
1511 // process that includes the thread for this stop reply
1512 // packet
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001513 size_t comma_pos;
1514 lldb::tid_t tid;
1515 while ((comma_pos = value.find(',')) != std::string::npos)
1516 {
1517 value[comma_pos] = '\0';
1518 // thread in big endian hex
1519 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1520 if (tid != LLDB_INVALID_THREAD_ID)
1521 m_thread_ids.push_back (tid);
1522 value.erase(0, comma_pos + 1);
1523
1524 }
1525 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1526 if (tid != LLDB_INVALID_THREAD_ID)
1527 m_thread_ids.push_back (tid);
1528 }
Greg Clayton4862fa22011-01-08 03:17:57 +00001529 else if (name.compare("hexname") == 0)
1530 {
1531 StringExtractor name_extractor;
1532 // Swap "value" over into "name_extractor"
1533 name_extractor.GetStringRef().swap(value);
1534 // Now convert the HEX bytes into a string value
1535 name_extractor.GetHexByteString (value);
1536 thread_name.swap (value);
1537 }
Chris Lattner24943d22010-06-08 16:52:24 +00001538 else if (name.compare("name") == 0)
1539 {
1540 thread_name.swap (value);
1541 }
Greg Clayton0a7f75f2010-09-09 06:32:46 +00001542 else if (name.compare("qaddr") == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00001543 {
1544 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1545 }
Greg Clayton65611552011-06-04 01:26:29 +00001546 else if (name.compare("reason") == 0)
1547 {
1548 reason.swap(value);
1549 }
1550 else if (name.compare("description") == 0)
1551 {
1552 StringExtractor desc_extractor;
1553 // Swap "value" over into "name_extractor"
1554 desc_extractor.GetStringRef().swap(value);
1555 // Now convert the HEX bytes into a string value
1556 desc_extractor.GetHexByteString (thread_name);
1557 }
Greg Claytona875b642011-01-09 21:07:35 +00001558 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1559 {
1560 // We have a register number that contains an expedited
1561 // register value. Lets supply this register to our thread
1562 // so it won't have to go and read it.
1563 if (thread_sp)
1564 {
1565 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1566
1567 if (reg != UINT32_MAX)
1568 {
1569 StringExtractor reg_value_extractor;
1570 // Swap "value" over into "reg_value_extractor"
1571 reg_value_extractor.GetStringRef().swap(value);
Greg Claytonc3c46612011-02-15 00:19:15 +00001572 if (!static_cast<ThreadGDBRemote *> (thread_sp.get())->PrivateSetRegisterValue (reg, reg_value_extractor))
1573 {
1574 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1575 name.c_str(),
1576 reg,
1577 reg,
1578 reg_value_extractor.GetStringRef().c_str(),
1579 stop_packet.GetStringRef().c_str());
1580 }
Greg Claytona875b642011-01-09 21:07:35 +00001581 }
1582 }
1583 }
Chris Lattner24943d22010-06-08 16:52:24 +00001584 }
Chris Lattner24943d22010-06-08 16:52:24 +00001585
1586 if (thread_sp)
1587 {
1588 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1589
1590 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Ingham9082c8a2011-01-28 02:23:12 +00001591 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001592 if (exc_type != 0)
1593 {
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001594 const size_t exc_data_size = exc_data.size();
Greg Clayton643ee732010-08-04 01:40:35 +00001595
1596 gdb_thread->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1597 exc_type,
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001598 exc_data_size,
1599 exc_data_size >= 1 ? exc_data[0] : 0,
Johnny Chen36889ad2011-09-17 01:05:03 +00001600 exc_data_size >= 2 ? exc_data[1] : 0,
1601 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner24943d22010-06-08 16:52:24 +00001602 }
Greg Clayton65611552011-06-04 01:26:29 +00001603 else
Chris Lattner24943d22010-06-08 16:52:24 +00001604 {
Greg Clayton65611552011-06-04 01:26:29 +00001605 bool handled = false;
1606 if (!reason.empty())
1607 {
1608 if (reason.compare("trace") == 0)
1609 {
1610 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1611 handled = true;
1612 }
1613 else if (reason.compare("breakpoint") == 0)
1614 {
1615 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001616 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Clayton65611552011-06-04 01:26:29 +00001617 if (bp_site_sp)
1618 {
1619 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1620 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1621 // 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 +00001622 handled = true;
Greg Clayton65611552011-06-04 01:26:29 +00001623 if (bp_site_sp->ValidForThisThread (gdb_thread))
1624 {
1625 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001626 }
1627 else
1628 {
1629 StopInfoSP invalid_stop_info_sp;
1630 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Greg Clayton65611552011-06-04 01:26:29 +00001631 }
1632 }
1633
Greg Clayton65611552011-06-04 01:26:29 +00001634 }
1635 else if (reason.compare("trap") == 0)
1636 {
1637 // Let the trap just use the standard signal stop reason below...
1638 }
1639 else if (reason.compare("watchpoint") == 0)
1640 {
1641 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1642 // TODO: locate the watchpoint somehow...
1643 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1644 handled = true;
1645 }
1646 else if (reason.compare("exception") == 0)
1647 {
1648 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1649 handled = true;
1650 }
1651 }
1652
1653 if (signo)
1654 {
1655 if (signo == SIGTRAP)
1656 {
1657 // Currently we are going to assume SIGTRAP means we are either
1658 // hitting a breakpoint or hardware single stepping.
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001659 handled = true;
Greg Clayton65611552011-06-04 01:26:29 +00001660 addr_t pc = gdb_thread->GetRegisterContext()->GetPC();
Greg Claytonf4124de2012-02-21 00:09:25 +00001661 lldb::BreakpointSiteSP bp_site_sp = gdb_thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001662
Greg Clayton65611552011-06-04 01:26:29 +00001663 if (bp_site_sp)
1664 {
1665 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1666 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1667 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1668 if (bp_site_sp->ValidForThisThread (gdb_thread))
1669 {
1670 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001671 }
1672 else
1673 {
1674 StopInfoSP invalid_stop_info_sp;
1675 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Greg Clayton65611552011-06-04 01:26:29 +00001676 }
1677 }
Jim Inghamc4bbbfc2012-07-11 21:41:19 +00001678 else
Greg Clayton65611552011-06-04 01:26:29 +00001679 {
Jim Ingham4fa015b2012-10-27 02:52:04 +00001680 // If we were stepping then assume the stop was the result of the trace. If we were
1681 // not stepping then report the SIGTRAP.
1682 // FIXME: We are still missing the case where we single step over a trap instruction.
1683 if (gdb_thread->GetTemporaryResumeState() == eStateStepping)
1684 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1685 else
1686 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo));
Greg Clayton65611552011-06-04 01:26:29 +00001687 }
1688 }
1689 if (!handled)
Greg Clayton37f962e2011-08-22 02:49:39 +00001690 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Chris Lattner24943d22010-06-08 16:52:24 +00001691 }
1692 else
1693 {
Greg Clayton643ee732010-08-04 01:40:35 +00001694 StopInfoSP invalid_stop_info_sp;
1695 gdb_thread->SetStopInfo (invalid_stop_info_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001696 }
Greg Clayton65611552011-06-04 01:26:29 +00001697
1698 if (!description.empty())
1699 {
1700 lldb::StopInfoSP stop_info_sp (gdb_thread->GetStopInfo ());
1701 if (stop_info_sp)
1702 {
1703 stop_info_sp->SetDescription (description.c_str());
Greg Clayton153ccd72011-08-10 02:10:13 +00001704 }
Greg Clayton65611552011-06-04 01:26:29 +00001705 else
1706 {
1707 gdb_thread->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1708 }
1709 }
1710 }
Chris Lattner24943d22010-06-08 16:52:24 +00001711 }
1712 return eStateStopped;
1713 }
1714 break;
1715
1716 case 'W':
1717 // process exited
1718 return eStateExited;
1719
1720 default:
1721 break;
1722 }
1723 return eStateInvalid;
1724}
1725
1726void
1727ProcessGDBRemote::RefreshStateAfterStop ()
1728{
Greg Claytonff3448e2012-04-13 02:11:32 +00001729 Mutex::Locker locker(m_thread_list.GetMutex());
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001730 m_thread_ids.clear();
1731 // Set the thread stop info. It might have a "threads" key whose value is
1732 // a list of all thread IDs in the current process, so m_thread_ids might
1733 // get set.
1734 SetThreadStopInfo (m_last_stop_packet);
1735 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1736 if (m_thread_ids.empty())
1737 {
1738 // No, we need to fetch the thread list manually
1739 UpdateThreadIDList();
1740 }
1741
Chris Lattner24943d22010-06-08 16:52:24 +00001742 // Let all threads recover from stopping and do any clean up based
1743 // on the previous thread state (if any).
1744 m_thread_list.RefreshStateAfterStop();
Greg Clayton5a9f85c2012-04-10 02:25:43 +00001745
Chris Lattner24943d22010-06-08 16:52:24 +00001746}
1747
1748Error
Jim Ingham3ae449a2010-11-17 02:32:00 +00001749ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner24943d22010-06-08 16:52:24 +00001750{
1751 Error error;
Jim Ingham3ae449a2010-11-17 02:32:00 +00001752
Greg Claytona4881d02011-01-22 07:12:45 +00001753 bool timed_out = false;
1754 Mutex::Locker locker;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001755
1756 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton20d338f2010-11-18 05:57:03 +00001757 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001758 // We are being asked to halt during an attach. We need to just close
1759 // our file handle and debugserver will go away, and we can be done...
1760 m_gdb_comm.Disconnect();
Greg Clayton20d338f2010-11-18 05:57:03 +00001761 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001762 else
1763 {
Greg Clayton05e4d972012-03-29 01:55:41 +00001764 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001765 {
1766 if (timed_out)
1767 error.SetErrorString("timed out sending interrupt packet");
1768 else
1769 error.SetErrorString("unknown error sending interrupt packet");
1770 }
Greg Clayton05e4d972012-03-29 01:55:41 +00001771
1772 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00001773 }
Chris Lattner24943d22010-06-08 16:52:24 +00001774 return error;
1775}
1776
1777Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001778ProcessGDBRemote::InterruptIfRunning
1779(
1780 bool discard_thread_plans,
1781 bool catch_stop_event,
Greg Clayton72e1c782011-01-22 23:43:18 +00001782 EventSP &stop_event_sp
1783)
Chris Lattner24943d22010-06-08 16:52:24 +00001784{
1785 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00001786
Greg Clayton2860ba92011-01-23 19:58:49 +00001787 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1788
Greg Clayton68ca8232011-01-25 02:58:48 +00001789 bool paused_private_state_thread = false;
Greg Clayton2860ba92011-01-23 19:58:49 +00001790 const bool is_running = m_gdb_comm.IsRunning();
1791 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00001792 log->Printf ("ProcessGDBRemote::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
Greg Clayton2860ba92011-01-23 19:58:49 +00001793 discard_thread_plans,
Greg Clayton68ca8232011-01-25 02:58:48 +00001794 catch_stop_event,
Greg Clayton2860ba92011-01-23 19:58:49 +00001795 is_running);
1796
Greg Clayton2860ba92011-01-23 19:58:49 +00001797 if (discard_thread_plans)
1798 {
1799 if (log)
1800 log->Printf ("ProcessGDBRemote::InterruptIfRunning() discarding all thread plans");
1801 m_thread_list.DiscardThreadPlans();
1802 }
1803 if (is_running)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001804 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001805 if (catch_stop_event)
1806 {
1807 if (log)
1808 log->Printf ("ProcessGDBRemote::InterruptIfRunning() pausing private state thread");
1809 PausePrivateStateThread();
1810 paused_private_state_thread = true;
1811 }
1812
Greg Clayton4fb400f2010-09-27 21:07:38 +00001813 bool timed_out = false;
1814 Mutex::Locker locker;
Greg Clayton72e1c782011-01-22 23:43:18 +00001815
Greg Clayton05e4d972012-03-29 01:55:41 +00001816 if (!m_gdb_comm.SendInterrupt (locker, 1, timed_out))
Greg Clayton4fb400f2010-09-27 21:07:38 +00001817 {
1818 if (timed_out)
1819 error.SetErrorString("timed out sending interrupt packet");
1820 else
1821 error.SetErrorString("unknown error sending interrupt packet");
Greg Clayton68ca8232011-01-25 02:58:48 +00001822 if (paused_private_state_thread)
Greg Clayton72e1c782011-01-22 23:43:18 +00001823 ResumePrivateStateThread();
1824 return error;
Greg Clayton4fb400f2010-09-27 21:07:38 +00001825 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001826
Greg Clayton72e1c782011-01-22 23:43:18 +00001827 if (catch_stop_event)
1828 {
Greg Clayton68ca8232011-01-25 02:58:48 +00001829 // LISTEN HERE
Greg Clayton72e1c782011-01-22 23:43:18 +00001830 TimeValue timeout_time;
1831 timeout_time = TimeValue::Now();
Greg Clayton68ca8232011-01-25 02:58:48 +00001832 timeout_time.OffsetWithSeconds(5);
1833 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
Greg Clayton2860ba92011-01-23 19:58:49 +00001834
Greg Claytonbdcb6ab2011-01-25 23:55:37 +00001835 timed_out = state == eStateInvalid;
Greg Clayton2860ba92011-01-23 19:58:49 +00001836 if (log)
1837 log->Printf ("ProcessGDBRemote::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001838
Greg Clayton2860ba92011-01-23 19:58:49 +00001839 if (timed_out)
Greg Clayton72e1c782011-01-22 23:43:18 +00001840 error.SetErrorString("unable to verify target stopped");
1841 }
1842
Greg Clayton68ca8232011-01-25 02:58:48 +00001843 if (paused_private_state_thread)
Greg Clayton2860ba92011-01-23 19:58:49 +00001844 {
1845 if (log)
1846 log->Printf ("ProcessGDBRemote::InterruptIfRunning() resuming private state thread");
Greg Clayton72e1c782011-01-22 23:43:18 +00001847 ResumePrivateStateThread();
Greg Clayton2860ba92011-01-23 19:58:49 +00001848 }
Greg Clayton4fb400f2010-09-27 21:07:38 +00001849 }
Chris Lattner24943d22010-06-08 16:52:24 +00001850 return error;
1851}
1852
Greg Clayton4fb400f2010-09-27 21:07:38 +00001853Error
Greg Clayton72e1c782011-01-22 23:43:18 +00001854ProcessGDBRemote::WillDetach ()
1855{
Greg Clayton2860ba92011-01-23 19:58:49 +00001856 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1857 if (log)
1858 log->Printf ("ProcessGDBRemote::WillDetach()");
1859
Greg Clayton72e1c782011-01-22 23:43:18 +00001860 bool discard_thread_plans = true;
1861 bool catch_stop_event = true;
Greg Clayton72e1c782011-01-22 23:43:18 +00001862 EventSP event_sp;
Jim Ingham8247e622012-06-06 00:32:39 +00001863
1864 // FIXME: InterruptIfRunning should be done in the Process base class, or better still make Halt do what is
1865 // needed. This shouldn't be a feature of a particular plugin.
1866
Greg Clayton68ca8232011-01-25 02:58:48 +00001867 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
Greg Clayton72e1c782011-01-22 23:43:18 +00001868}
1869
1870Error
Greg Clayton4fb400f2010-09-27 21:07:38 +00001871ProcessGDBRemote::DoDetach()
1872{
1873 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001874 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton4fb400f2010-09-27 21:07:38 +00001875 if (log)
1876 log->Printf ("ProcessGDBRemote::DoDetach()");
1877
1878 DisableAllBreakpointSites ();
1879
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001880 m_thread_list.DiscardThreadPlans();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001881
Greg Clayton516f0842012-04-11 00:24:49 +00001882 bool success = m_gdb_comm.Detach ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001883 if (log)
Greg Clayton4fb400f2010-09-27 21:07:38 +00001884 {
Greg Clayton516f0842012-04-11 00:24:49 +00001885 if (success)
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001886 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1887 else
1888 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet send failed");
Greg Clayton4fb400f2010-09-27 21:07:38 +00001889 }
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001890 // Sleep for one second to let the process get all detached...
Greg Clayton4fb400f2010-09-27 21:07:38 +00001891 StopAsyncThread ();
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001892
Greg Clayton3b2c41c2010-10-18 04:14:23 +00001893 SetPrivateState (eStateDetached);
1894 ResumePrivateStateThread();
1895
1896 //KillDebugserverProcess ();
Greg Clayton4fb400f2010-09-27 21:07:38 +00001897 return error;
1898}
Chris Lattner24943d22010-06-08 16:52:24 +00001899
Jim Ingham06b84492012-07-04 00:35:43 +00001900
Chris Lattner24943d22010-06-08 16:52:24 +00001901Error
1902ProcessGDBRemote::DoDestroy ()
1903{
1904 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00001905 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001906 if (log)
1907 log->Printf ("ProcessGDBRemote::DoDestroy()");
1908
Jim Ingham06b84492012-07-04 00:35:43 +00001909 // There is a bug in older iOS debugservers where they don't shut down the process
1910 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
1911 // this can cause problems with restarting. So we check to see if any of our threads are stopped
1912 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
1913 // destroy it again.
1914 //
1915 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
1916 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
1917 // the debugservers with this bug are equal. There really should be a better way to test this!
1918 //
1919 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
1920 // get called here to destroy again and we're still at a breakpoint or exception, then we should
1921 // just do the straight-forward kill.
1922 //
1923 // And of course, if we weren't able to stop the process by the time we get here, it isn't
1924 // necessary (or helpful) to do any of this.
1925
1926 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
1927 {
1928 PlatformSP platform_sp = GetTarget().GetPlatform();
1929
1930 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
1931 if (platform_sp
1932 && platform_sp->GetName()
1933 && strcmp (platform_sp->GetName(), PlatformRemoteiOS::GetShortPluginNameStatic()) == 0)
1934 {
1935 if (m_destroy_tried_resuming)
1936 {
1937 if (log)
1938 log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again.");
1939 }
1940 else
1941 {
1942 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
1943 // but we really need it to happen here and it doesn't matter if we do it twice.
1944 m_thread_list.DiscardThreadPlans();
1945 DisableAllBreakpointSites();
1946
1947 bool stop_looks_like_crash = false;
1948 ThreadList &threads = GetThreadList();
1949
1950 {
Jim Inghamc2c65142012-09-11 00:08:52 +00001951 Mutex::Locker locker(threads.GetMutex());
Jim Ingham06b84492012-07-04 00:35:43 +00001952
1953 size_t num_threads = threads.GetSize();
1954 for (size_t i = 0; i < num_threads; i++)
1955 {
1956 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1957 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason();
1958 StopReason reason = eStopReasonInvalid;
1959 if (stop_info_sp)
1960 reason = stop_info_sp->GetStopReason();
1961 if (reason == eStopReasonBreakpoint
1962 || reason == eStopReasonException)
1963 {
1964 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001965 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: %" PRId64 " stopped with reason: %s.",
Jim Ingham06b84492012-07-04 00:35:43 +00001966 thread_sp->GetID(),
1967 stop_info_sp->GetDescription());
1968 stop_looks_like_crash = true;
1969 break;
1970 }
1971 }
1972 }
1973
1974 if (stop_looks_like_crash)
1975 {
1976 if (log)
1977 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
1978 m_destroy_tried_resuming = true;
1979
1980 // If we are going to run again before killing, it would be good to suspend all the threads
1981 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
1982 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
1983 // have to run the risk of letting those threads proceed a bit.
1984
1985 {
Jim Inghamc2c65142012-09-11 00:08:52 +00001986 Mutex::Locker locker(threads.GetMutex());
Jim Ingham06b84492012-07-04 00:35:43 +00001987
1988 size_t num_threads = threads.GetSize();
1989 for (size_t i = 0; i < num_threads; i++)
1990 {
1991 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1992 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopReason();
1993 StopReason reason = eStopReasonInvalid;
1994 if (stop_info_sp)
1995 reason = stop_info_sp->GetStopReason();
1996 if (reason != eStopReasonBreakpoint
1997 && reason != eStopReasonException)
1998 {
1999 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002000 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: %" PRId64 " before running.",
Jim Ingham06b84492012-07-04 00:35:43 +00002001 thread_sp->GetID());
2002 thread_sp->SetResumeState(eStateSuspended);
2003 }
2004 }
2005 }
2006 Resume ();
2007 return Destroy();
2008 }
2009 }
2010 }
2011 }
2012
Chris Lattner24943d22010-06-08 16:52:24 +00002013 // Interrupt if our inferior is running...
Jim Ingham8247e622012-06-06 00:32:39 +00002014 int exit_status = SIGABRT;
2015 std::string exit_string;
2016
Greg Claytona4881d02011-01-22 07:12:45 +00002017 if (m_gdb_comm.IsConnected())
Chris Lattner24943d22010-06-08 16:52:24 +00002018 {
Jim Ingham8226e942011-10-28 01:11:35 +00002019 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton72e1c782011-01-22 23:43:18 +00002020 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002021
2022 StringExtractorGDBRemote response;
2023 bool send_async = true;
Filipe Cabecinhasee188ee2012-08-22 13:25:58 +00002024 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3);
2025
Greg Claytonc97bfdb2011-03-10 02:26:48 +00002026 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002027 {
2028 char packet_cmd = response.GetChar(0);
2029
2030 if (packet_cmd == 'W' || packet_cmd == 'X')
2031 {
Greg Clayton06709002011-12-06 04:51:14 +00002032 SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00002033 ClearThreadIDList ();
Jim Ingham8247e622012-06-06 00:32:39 +00002034 exit_status = response.GetHexU8();
2035 }
2036 else
2037 {
2038 if (log)
2039 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2040 exit_string.assign("got unexpected response to k packet: ");
2041 exit_string.append(response.GetStringRef());
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002042 }
2043 }
2044 else
2045 {
Jim Ingham8247e622012-06-06 00:32:39 +00002046 if (log)
2047 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2048 exit_string.assign("failed to send the k packet");
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002049 }
Filipe Cabecinhasee188ee2012-08-22 13:25:58 +00002050
2051 m_gdb_comm.SetPacketTimeout(old_packet_timeout);
Greg Clayton72e1c782011-01-22 23:43:18 +00002052 }
Jim Ingham8247e622012-06-06 00:32:39 +00002053 else
2054 {
2055 if (log)
2056 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
Jim Ingham5d90ade2012-07-27 23:57:19 +00002057 exit_string.assign ("killed or interrupted while attaching.");
Jim Ingham8247e622012-06-06 00:32:39 +00002058 }
Greg Clayton72e1c782011-01-22 23:43:18 +00002059 }
Jim Ingham8247e622012-06-06 00:32:39 +00002060 else
2061 {
2062 // If we missed setting the exit status on the way out, do it here.
2063 // NB set exit status can be called multiple times, the first one sets the status.
2064 exit_string.assign("destroying when not connected to debugserver");
2065 }
2066
2067 SetExitStatus(exit_status, exit_string.c_str());
2068
Chris Lattner24943d22010-06-08 16:52:24 +00002069 StopAsyncThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002070 KillDebugserverProcess ();
2071 return error;
2072}
2073
Chris Lattner24943d22010-06-08 16:52:24 +00002074//------------------------------------------------------------------
2075// Process Queries
2076//------------------------------------------------------------------
2077
2078bool
2079ProcessGDBRemote::IsAlive ()
2080{
Greg Clayton58e844b2010-12-08 05:08:21 +00002081 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner24943d22010-06-08 16:52:24 +00002082}
2083
Jason Molendad6b81222012-10-06 02:02:26 +00002084// For kernel debugging, we return the load address of the kernel binary as the
2085// ImageInfoAddress and we return the DynamicLoaderDarwinKernel as the GetDynamicLoader()
2086// name so the correct DynamicLoader plugin is chosen.
Chris Lattner24943d22010-06-08 16:52:24 +00002087addr_t
2088ProcessGDBRemote::GetImageInfoAddress()
2089{
Jason Molendab46937c2012-10-03 01:29:34 +00002090 if (m_kernel_load_addr != LLDB_INVALID_ADDRESS)
2091 return m_kernel_load_addr;
2092 else
2093 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner24943d22010-06-08 16:52:24 +00002094}
2095
Chris Lattner24943d22010-06-08 16:52:24 +00002096//------------------------------------------------------------------
2097// Process Memory
2098//------------------------------------------------------------------
2099size_t
2100ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2101{
2102 if (size > m_max_memory_size)
2103 {
2104 // Keep memory read sizes down to a sane limit. This function will be
2105 // called multiple times in order to complete the task by
2106 // lldb_private::Process so it is ok to do this.
2107 size = m_max_memory_size;
2108 }
2109
2110 char packet[64];
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002111 const int packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
Chris Lattner24943d22010-06-08 16:52:24 +00002112 assert (packet_len + 1 < sizeof(packet));
2113 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00002114 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00002115 {
Greg Clayton61d043b2011-03-22 04:00:09 +00002116 if (response.IsNormalResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00002117 {
2118 error.Clear();
2119 return response.GetHexBytes(buf, size, '\xdd');
2120 }
Greg Clayton61d043b2011-03-22 04:00:09 +00002121 else if (response.IsErrorResponse())
Greg Clayton49d888d2012-12-06 22:49:16 +00002122 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton61d043b2011-03-22 04:00:09 +00002123 else if (response.IsUnsupportedResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00002124 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner24943d22010-06-08 16:52:24 +00002125 else
Greg Claytonae7bebc2012-09-19 01:46:31 +00002126 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00002127 }
2128 else
2129 {
2130 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet);
2131 }
2132 return 0;
2133}
2134
2135size_t
2136ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2137{
Greg Claytonc8bc1c32011-05-16 02:35:02 +00002138 if (size > m_max_memory_size)
2139 {
2140 // Keep memory read sizes down to a sane limit. This function will be
2141 // called multiple times in order to complete the task by
2142 // lldb_private::Process so it is ok to do this.
2143 size = m_max_memory_size;
2144 }
2145
Chris Lattner24943d22010-06-08 16:52:24 +00002146 StreamString packet;
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002147 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Claytoncd548032011-02-01 01:31:41 +00002148 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner24943d22010-06-08 16:52:24 +00002149 StringExtractorGDBRemote response;
Greg Claytonc97bfdb2011-03-10 02:26:48 +00002150 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner24943d22010-06-08 16:52:24 +00002151 {
Greg Clayton61d043b2011-03-22 04:00:09 +00002152 if (response.IsOKResponse())
Chris Lattner24943d22010-06-08 16:52:24 +00002153 {
2154 error.Clear();
2155 return size;
2156 }
Greg Clayton61d043b2011-03-22 04:00:09 +00002157 else if (response.IsErrorResponse())
Greg Clayton49d888d2012-12-06 22:49:16 +00002158 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton61d043b2011-03-22 04:00:09 +00002159 else if (response.IsUnsupportedResponse())
Greg Claytonae7bebc2012-09-19 01:46:31 +00002160 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner24943d22010-06-08 16:52:24 +00002161 else
Greg Claytonae7bebc2012-09-19 01:46:31 +00002162 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 +00002163 }
2164 else
2165 {
2166 error.SetErrorStringWithFormat("failed to sent packet: '%s'", packet.GetString().c_str());
2167 }
2168 return 0;
2169}
2170
2171lldb::addr_t
2172ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2173{
Greg Clayton989816b2011-05-14 01:50:35 +00002174 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2175
Greg Clayton2f085c62011-05-15 01:25:55 +00002176 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton989816b2011-05-14 01:50:35 +00002177 switch (supported)
2178 {
2179 case eLazyBoolCalculate:
2180 case eLazyBoolYes:
2181 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2182 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2183 return allocated_addr;
2184
2185 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002186 // Call mmap() to create memory in the inferior..
2187 unsigned prot = 0;
2188 if (permissions & lldb::ePermissionsReadable)
2189 prot |= eMmapProtRead;
2190 if (permissions & lldb::ePermissionsWritable)
2191 prot |= eMmapProtWrite;
2192 if (permissions & lldb::ePermissionsExecutable)
2193 prot |= eMmapProtExec;
Greg Clayton989816b2011-05-14 01:50:35 +00002194
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002195 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2196 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2197 m_addr_to_mmap_size[allocated_addr] = size;
2198 else
2199 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton989816b2011-05-14 01:50:35 +00002200 break;
2201 }
2202
Chris Lattner24943d22010-06-08 16:52:24 +00002203 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002204 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner24943d22010-06-08 16:52:24 +00002205 else
2206 error.Clear();
2207 return allocated_addr;
2208}
2209
2210Error
Greg Claytona9385532011-11-18 07:03:08 +00002211ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2212 MemoryRegionInfo &region_info)
2213{
2214
2215 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2216 return error;
2217}
2218
2219Error
Johnny Chen7cbdcfb2012-05-23 21:09:52 +00002220ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2221{
2222
2223 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2224 return error;
2225}
2226
2227Error
Enrico Granata7de2a3b2012-07-13 23:18:48 +00002228ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2229{
2230 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2231 return error;
2232}
2233
2234Error
Chris Lattner24943d22010-06-08 16:52:24 +00002235ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2236{
2237 Error error;
Greg Clayton2f085c62011-05-15 01:25:55 +00002238 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2239
2240 switch (supported)
2241 {
2242 case eLazyBoolCalculate:
2243 // We should never be deallocating memory without allocating memory
2244 // first so we should never get eLazyBoolCalculate
2245 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2246 break;
2247
2248 case eLazyBoolYes:
2249 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002250 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00002251 break;
2252
2253 case eLazyBoolNo:
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002254 // Call munmap() to deallocate memory in the inferior..
Greg Clayton2f085c62011-05-15 01:25:55 +00002255 {
2256 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne4d623e82011-06-03 20:40:38 +00002257 if (pos != m_addr_to_mmap_size.end() &&
2258 InferiorCallMunmap(this, addr, pos->second))
2259 m_addr_to_mmap_size.erase (pos);
2260 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002261 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton2f085c62011-05-15 01:25:55 +00002262 }
2263 break;
2264 }
2265
Chris Lattner24943d22010-06-08 16:52:24 +00002266 return error;
2267}
2268
2269
2270//------------------------------------------------------------------
2271// Process STDIO
2272//------------------------------------------------------------------
Chris Lattner24943d22010-06-08 16:52:24 +00002273size_t
2274ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2275{
2276 if (m_stdio_communication.IsConnected())
2277 {
2278 ConnectionStatus status;
2279 m_stdio_communication.Write(src, src_len, status, NULL);
2280 }
2281 return 0;
2282}
2283
2284Error
2285ProcessGDBRemote::EnableBreakpoint (BreakpointSite *bp_site)
2286{
2287 Error error;
2288 assert (bp_site != NULL);
2289
Greg Claytone005f2c2010-11-06 01:53:30 +00002290 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002291 user_id_t site_id = bp_site->GetID();
2292 const addr_t addr = bp_site->GetLoadAddress();
2293 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002294 log->Printf ("ProcessGDBRemote::EnableBreakpoint (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002295
2296 if (bp_site->IsEnabled())
2297 {
2298 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002299 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 +00002300 return error;
2301 }
2302 else
2303 {
2304 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2305
2306 if (bp_site->HardwarePreferred())
2307 {
2308 // Try and set hardware breakpoint, and if that fails, fall through
2309 // and set a software breakpoint?
Greg Claytonb72d0f02011-04-12 05:54:46 +00002310 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner24943d22010-06-08 16:52:24 +00002311 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002312 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner24943d22010-06-08 16:52:24 +00002313 {
2314 bp_site->SetEnabled(true);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002315 bp_site->SetType (BreakpointSite::eHardware);
Chris Lattner24943d22010-06-08 16:52:24 +00002316 return error;
2317 }
Chris Lattner24943d22010-06-08 16:52:24 +00002318 }
2319 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002320
2321 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner24943d22010-06-08 16:52:24 +00002322 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002323 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
2324 {
2325 bp_site->SetEnabled(true);
2326 bp_site->SetType (BreakpointSite::eExternal);
2327 return error;
2328 }
Chris Lattner24943d22010-06-08 16:52:24 +00002329 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002330
2331 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner24943d22010-06-08 16:52:24 +00002332 }
2333
2334 if (log)
2335 {
2336 const char *err_string = error.AsCString();
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002337 log->Printf ("ProcessGDBRemote::EnableBreakpoint() error for breakpoint at 0x%8.8" PRIx64 ": %s",
Chris Lattner24943d22010-06-08 16:52:24 +00002338 bp_site->GetLoadAddress(),
2339 err_string ? err_string : "NULL");
2340 }
2341 // We shouldn't reach here on a successful breakpoint enable...
2342 if (error.Success())
2343 error.SetErrorToGenericError();
2344 return error;
2345}
2346
2347Error
2348ProcessGDBRemote::DisableBreakpoint (BreakpointSite *bp_site)
2349{
2350 Error error;
2351 assert (bp_site != NULL);
2352 addr_t addr = bp_site->GetLoadAddress();
2353 user_id_t site_id = bp_site->GetID();
Greg Claytone005f2c2010-11-06 01:53:30 +00002354 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002355 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002356 log->Printf ("ProcessGDBRemote::DisableBreakpoint (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002357
2358 if (bp_site->IsEnabled())
2359 {
2360 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2361
Greg Claytonb72d0f02011-04-12 05:54:46 +00002362 BreakpointSite::Type bp_type = bp_site->GetType();
2363 switch (bp_type)
Chris Lattner24943d22010-06-08 16:52:24 +00002364 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002365 case BreakpointSite::eSoftware:
2366 error = DisableSoftwareBreakpoint (bp_site);
2367 break;
2368
2369 case BreakpointSite::eHardware:
2370 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2371 error.SetErrorToGenericError();
2372 break;
2373
2374 case BreakpointSite::eExternal:
2375 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2376 error.SetErrorToGenericError();
2377 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002378 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002379 if (error.Success())
2380 bp_site->SetEnabled(false);
Chris Lattner24943d22010-06-08 16:52:24 +00002381 }
2382 else
2383 {
2384 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002385 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 +00002386 return error;
2387 }
2388
2389 if (error.Success())
2390 error.SetErrorToGenericError();
2391 return error;
2392}
2393
Johnny Chen21900fb2011-09-06 22:38:36 +00002394// Pre-requisite: wp != NULL.
2395static GDBStoppointType
Johnny Chenecd4feb2011-10-14 00:42:25 +00002396GetGDBStoppointType (Watchpoint *wp)
Johnny Chen21900fb2011-09-06 22:38:36 +00002397{
2398 assert(wp);
2399 bool watch_read = wp->WatchpointRead();
2400 bool watch_write = wp->WatchpointWrite();
2401
2402 // watch_read and watch_write cannot both be false.
2403 assert(watch_read || watch_write);
2404 if (watch_read && watch_write)
2405 return eWatchpointReadWrite;
Johnny Chen48a5e852011-09-09 20:35:15 +00002406 else if (watch_read)
Johnny Chen21900fb2011-09-06 22:38:36 +00002407 return eWatchpointRead;
Johnny Chen48a5e852011-09-09 20:35:15 +00002408 else // Must be watch_write, then.
Johnny Chen21900fb2011-09-06 22:38:36 +00002409 return eWatchpointWrite;
2410}
2411
Chris Lattner24943d22010-06-08 16:52:24 +00002412Error
Jim Ingham9c970a32012-12-18 02:03:49 +00002413ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner24943d22010-06-08 16:52:24 +00002414{
2415 Error error;
2416 if (wp)
2417 {
2418 user_id_t watchID = wp->GetID();
2419 addr_t addr = wp->GetLoadAddress();
Greg Claytone005f2c2010-11-06 01:53:30 +00002420 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002421 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002422 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner24943d22010-06-08 16:52:24 +00002423 if (wp->IsEnabled())
2424 {
2425 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002426 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 +00002427 return error;
2428 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002429
2430 GDBStoppointType type = GetGDBStoppointType(wp);
2431 // Pass down an appropriate z/Z packet...
2432 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner24943d22010-06-08 16:52:24 +00002433 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002434 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2435 {
Jim Ingham9c970a32012-12-18 02:03:49 +00002436 wp->SetEnabled(true, notify);
Johnny Chen21900fb2011-09-06 22:38:36 +00002437 return error;
2438 }
2439 else
2440 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002441 }
Johnny Chen21900fb2011-09-06 22:38:36 +00002442 else
2443 error.SetErrorString("watchpoints not supported");
Chris Lattner24943d22010-06-08 16:52:24 +00002444 }
2445 else
2446 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002447 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002448 }
2449 if (error.Success())
2450 error.SetErrorToGenericError();
2451 return error;
2452}
2453
2454Error
Jim Ingham9c970a32012-12-18 02:03:49 +00002455ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner24943d22010-06-08 16:52:24 +00002456{
2457 Error error;
2458 if (wp)
2459 {
2460 user_id_t watchID = wp->GetID();
2461
Greg Claytone005f2c2010-11-06 01:53:30 +00002462 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002463
2464 addr_t addr = wp->GetLoadAddress();
Jim Ingham9c970a32012-12-18 02:03:49 +00002465
Chris Lattner24943d22010-06-08 16:52:24 +00002466 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002467 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002468
Johnny Chen21900fb2011-09-06 22:38:36 +00002469 if (!wp->IsEnabled())
2470 {
2471 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002472 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 +00002473 // See also 'class WatchpointSentry' within StopInfo.cpp.
2474 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2475 // the watchpoint object to intelligently process this action.
Jim Ingham9c970a32012-12-18 02:03:49 +00002476 wp->SetEnabled(false, notify);
Johnny Chen21900fb2011-09-06 22:38:36 +00002477 return error;
2478 }
2479
Chris Lattner24943d22010-06-08 16:52:24 +00002480 if (wp->IsHardware())
2481 {
Johnny Chen21900fb2011-09-06 22:38:36 +00002482 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner24943d22010-06-08 16:52:24 +00002483 // Pass down an appropriate z/Z packet...
Johnny Chen21900fb2011-09-06 22:38:36 +00002484 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2485 {
Jim Ingham9c970a32012-12-18 02:03:49 +00002486 wp->SetEnabled(false, notify);
Johnny Chen21900fb2011-09-06 22:38:36 +00002487 return error;
2488 }
2489 else
2490 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner24943d22010-06-08 16:52:24 +00002491 }
2492 // TODO: clear software watchpoints if we implement them
2493 }
2494 else
2495 {
Johnny Chenecd4feb2011-10-14 00:42:25 +00002496 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner24943d22010-06-08 16:52:24 +00002497 }
2498 if (error.Success())
2499 error.SetErrorToGenericError();
2500 return error;
2501}
2502
2503void
2504ProcessGDBRemote::Clear()
2505{
2506 m_flags = 0;
2507 m_thread_list.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002508}
2509
2510Error
2511ProcessGDBRemote::DoSignal (int signo)
2512{
2513 Error error;
Greg Claytone005f2c2010-11-06 01:53:30 +00002514 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002515 if (log)
2516 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2517
2518 if (!m_gdb_comm.SendAsyncSignal (signo))
2519 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2520 return error;
2521}
2522
Chris Lattner24943d22010-06-08 16:52:24 +00002523Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002524ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)
2525{
2526 ProcessLaunchInfo launch_info;
2527 return StartDebugserverProcess(debugserver_url, launch_info);
2528}
2529
2530Error
2531ProcessGDBRemote::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 +00002532{
2533 Error error;
2534 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2535 {
2536 // If we locate debugserver, keep that located version around
2537 static FileSpec g_debugserver_file_spec;
2538
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002539 ProcessLaunchInfo debugserver_launch_info;
Chris Lattner24943d22010-06-08 16:52:24 +00002540 char debugserver_path[PATH_MAX];
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002541 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile();
Chris Lattner24943d22010-06-08 16:52:24 +00002542
2543 // Always check to see if we have an environment override for the path
2544 // to the debugserver to use and use it if we do.
2545 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2546 if (env_debugserver_path)
Greg Clayton537a7a82010-10-20 20:54:39 +00002547 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner24943d22010-06-08 16:52:24 +00002548 else
2549 debugserver_file_spec = g_debugserver_file_spec;
2550 bool debugserver_exists = debugserver_file_spec.Exists();
2551 if (!debugserver_exists)
2552 {
2553 // The debugserver binary is in the LLDB.framework/Resources
2554 // directory.
Greg Clayton24b48ff2010-10-17 22:03:32 +00002555 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner24943d22010-06-08 16:52:24 +00002556 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00002557 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002558 debugserver_exists = debugserver_file_spec.Exists();
Greg Clayton24b48ff2010-10-17 22:03:32 +00002559 if (debugserver_exists)
2560 {
2561 g_debugserver_file_spec = debugserver_file_spec;
2562 }
2563 else
2564 {
2565 g_debugserver_file_spec.Clear();
2566 debugserver_file_spec.Clear();
2567 }
Chris Lattner24943d22010-06-08 16:52:24 +00002568 }
2569 }
2570
2571 if (debugserver_exists)
2572 {
2573 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2574
2575 m_stdio_communication.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00002576
Greg Claytone005f2c2010-11-06 01:53:30 +00002577 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002578
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002579 Args &debugserver_args = debugserver_launch_info.GetArguments();
Chris Lattner24943d22010-06-08 16:52:24 +00002580 char arg_cstr[PATH_MAX];
Chris Lattner24943d22010-06-08 16:52:24 +00002581
Chris Lattner24943d22010-06-08 16:52:24 +00002582 // Start args with "debugserver /file/path -r --"
2583 debugserver_args.AppendArgument(debugserver_path);
2584 debugserver_args.AppendArgument(debugserver_url);
Greg Clayton24b48ff2010-10-17 22:03:32 +00002585 // use native registers, not the GDB registers
2586 debugserver_args.AppendArgument("--native-regs");
2587 // make debugserver run in its own session so signals generated by
2588 // special terminal key sequences (^C) don't affect debugserver
2589 debugserver_args.AppendArgument("--setsid");
Chris Lattner24943d22010-06-08 16:52:24 +00002590
Chris Lattner24943d22010-06-08 16:52:24 +00002591 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2592 if (env_debugserver_log_file)
2593 {
2594 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2595 debugserver_args.AppendArgument(arg_cstr);
2596 }
2597
2598 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2599 if (env_debugserver_log_flags)
2600 {
2601 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2602 debugserver_args.AppendArgument(arg_cstr);
2603 }
Jim Ingham2b2ac8c2012-10-03 22:31:30 +00002604// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
2605// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner24943d22010-06-08 16:52:24 +00002606
Greg Claytonb72d0f02011-04-12 05:54:46 +00002607 // We currently send down all arguments, attach pids, or attach
2608 // process names in dedicated GDB server packets, so we don't need
2609 // to pass them as arguments. This is currently because of all the
2610 // things we need to setup prior to launching: the environment,
2611 // current working dir, file actions, etc.
2612#if 0
Chris Lattner24943d22010-06-08 16:52:24 +00002613 // Now append the program arguments
Greg Claytona2f74232011-02-24 22:24:29 +00002614 if (inferior_argv)
Chris Lattner24943d22010-06-08 16:52:24 +00002615 {
Greg Claytona2f74232011-02-24 22:24:29 +00002616 // Terminate the debugserver args so we can now append the inferior args
2617 debugserver_args.AppendArgument("--");
Chris Lattner24943d22010-06-08 16:52:24 +00002618
Greg Claytona2f74232011-02-24 22:24:29 +00002619 for (int i = 0; inferior_argv[i] != NULL; ++i)
2620 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner24943d22010-06-08 16:52:24 +00002621 }
2622 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2623 {
2624 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2625 debugserver_args.AppendArgument (arg_cstr);
2626 }
2627 else if (attach_name && attach_name[0])
2628 {
2629 if (wait_for_launch)
2630 debugserver_args.AppendArgument ("--waitfor");
2631 else
2632 debugserver_args.AppendArgument ("--attach");
2633 debugserver_args.AppendArgument (attach_name);
2634 }
Chris Lattner24943d22010-06-08 16:52:24 +00002635#endif
Greg Claytonb72d0f02011-04-12 05:54:46 +00002636
2637 ProcessLaunchInfo::FileAction file_action;
2638
2639 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2640 // to "/dev/null" if we run into any problems.
2641 file_action.Close (STDIN_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002642 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002643 file_action.Close (STDOUT_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002644 debugserver_launch_info.AppendFileAction (file_action);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002645 file_action.Close (STDERR_FILENO);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002646 debugserver_launch_info.AppendFileAction (file_action);
Chris Lattner24943d22010-06-08 16:52:24 +00002647
2648 if (log)
2649 {
2650 StreamString strm;
2651 debugserver_args.Dump (&strm);
2652 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2653 }
2654
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002655 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2656 debugserver_launch_info.SetUserID(process_info.GetUserID());
Greg Clayton1c4642c2011-11-16 05:37:56 +00002657
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002658 error = Host::LaunchProcess(debugserver_launch_info);
Greg Claytone9d0df42010-07-02 01:29:13 +00002659
Greg Claytonb72d0f02011-04-12 05:54:46 +00002660 if (error.Success ())
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002661 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002662 else
Chris Lattner24943d22010-06-08 16:52:24 +00002663 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2664
2665 if (error.Fail() || log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002666 error.PutToLog(log.get(), "Host::LaunchProcess (launch_info) => pid=%" PRIu64 ", path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002667 }
2668 else
2669 {
Greg Clayton9c236732011-10-26 00:56:27 +00002670 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner24943d22010-06-08 16:52:24 +00002671 }
2672
2673 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2674 StartAsyncThread ();
2675 }
2676 return error;
2677}
2678
2679bool
2680ProcessGDBRemote::MonitorDebugserverProcess
2681(
2682 void *callback_baton,
2683 lldb::pid_t debugserver_pid,
Greg Clayton1c4642c2011-11-16 05:37:56 +00002684 bool exited, // True if the process did exit
Chris Lattner24943d22010-06-08 16:52:24 +00002685 int signo, // Zero for no signal
2686 int exit_status // Exit value of process if signal is zero
2687)
2688{
Greg Clayton1c4642c2011-11-16 05:37:56 +00002689 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2690 // and might not exist anymore, so we need to carefully try to get the
2691 // target for this process first since we have a race condition when
2692 // we are done running between getting the notice that the inferior
2693 // process has died and the debugserver that was debugging this process.
2694 // In our test suite, we are also continually running process after
2695 // process, so we must be very careful to make sure:
2696 // 1 - process object hasn't been deleted already
2697 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner24943d22010-06-08 16:52:24 +00002698
2699 // "debugserver_pid" argument passed in is the process ID for
2700 // debugserver that we are tracking...
Greg Clayton1c4642c2011-11-16 05:37:56 +00002701 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002702
Greg Clayton75ccf502010-08-21 02:22:51 +00002703 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton72e1c782011-01-22 23:43:18 +00002704
Greg Clayton1c4642c2011-11-16 05:37:56 +00002705 // Get a shared pointer to the target that has a matching process pointer.
2706 // This target could be gone, or the target could already have a new process
2707 // object inside of it
2708 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2709
Greg Clayton72e1c782011-01-22 23:43:18 +00002710 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002711 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 +00002712
Greg Clayton1c4642c2011-11-16 05:37:56 +00002713 if (target_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002714 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002715 // We found a process in a target that matches, but another thread
2716 // might be in the process of launching a new process that will
2717 // soon replace it, so get a shared pointer to the process so we
2718 // can keep it alive.
2719 ProcessSP process_sp (target_sp->GetProcessSP());
2720 // Now we have a shared pointer to the process that can't go away on us
2721 // so we now make sure it was the same as the one passed in, and also make
2722 // sure that our previous "process *" didn't get deleted and have a new
2723 // "process *" created in its place with the same pointer. To verify this
2724 // we make sure the process has our debugserver process ID. If we pass all
2725 // of these tests, then we are sure that this process is the one we were
2726 // looking for.
2727 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner24943d22010-06-08 16:52:24 +00002728 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002729 // Sleep for a half a second to make sure our inferior process has
2730 // time to set its exit status before we set it incorrectly when
2731 // both the debugserver and the inferior process shut down.
2732 usleep (500000);
2733 // If our process hasn't yet exited, debugserver might have died.
2734 // If the process did exit, the we are reaping it.
2735 const StateType state = process->GetState();
2736
2737 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2738 state != eStateInvalid &&
2739 state != eStateUnloaded &&
2740 state != eStateExited &&
2741 state != eStateDetached)
Chris Lattner24943d22010-06-08 16:52:24 +00002742 {
Greg Clayton1c4642c2011-11-16 05:37:56 +00002743 char error_str[1024];
2744 if (signo)
2745 {
2746 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2747 if (signal_cstr)
2748 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2749 else
2750 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2751 }
Chris Lattner24943d22010-06-08 16:52:24 +00002752 else
Greg Clayton1c4642c2011-11-16 05:37:56 +00002753 {
2754 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2755 }
Greg Clayton75ccf502010-08-21 02:22:51 +00002756
Greg Clayton1c4642c2011-11-16 05:37:56 +00002757 process->SetExitStatus (-1, error_str);
2758 }
2759 // Debugserver has exited we need to let our ProcessGDBRemote
2760 // know that it no longer has a debugserver instance
2761 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton75ccf502010-08-21 02:22:51 +00002762 }
Chris Lattner24943d22010-06-08 16:52:24 +00002763 }
2764 return true;
2765}
2766
2767void
2768ProcessGDBRemote::KillDebugserverProcess ()
2769{
2770 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2771 {
2772 ::kill (m_debugserver_pid, SIGINT);
2773 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2774 }
2775}
2776
2777void
2778ProcessGDBRemote::Initialize()
2779{
2780 static bool g_initialized = false;
2781
2782 if (g_initialized == false)
2783 {
2784 g_initialized = true;
2785 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2786 GetPluginDescriptionStatic(),
2787 CreateInstance);
2788
2789 Log::Callbacks log_callbacks = {
2790 ProcessGDBRemoteLog::DisableLog,
2791 ProcessGDBRemoteLog::EnableLog,
2792 ProcessGDBRemoteLog::ListLogCategories
2793 };
2794
2795 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2796 }
2797}
2798
2799bool
Chris Lattner24943d22010-06-08 16:52:24 +00002800ProcessGDBRemote::StartAsyncThread ()
2801{
Greg Claytone005f2c2010-11-06 01:53:30 +00002802 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002803
2804 if (log)
2805 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Inghama9488302012-11-01 01:15:33 +00002806
2807 Mutex::Locker start_locker(m_async_thread_state_mutex);
2808 if (m_async_thread_state == eAsyncThreadNotStarted)
2809 {
2810 // Create a thread that watches our internal state and controls which
2811 // events make it to clients (into the DCProcess event queue).
2812 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2813 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2814 {
2815 m_async_thread_state = eAsyncThreadRunning;
2816 return true;
2817 }
2818 else
2819 return false;
2820 }
2821 else
2822 {
2823 // Somebody tried to start the async thread while it was either being started or stopped. If the former, and
2824 // it started up successfully, then say all's well. Otherwise it is an error, since we aren't going to restart it.
2825 if (log)
2826 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
2827 if (m_async_thread_state == eAsyncThreadRunning)
2828 return true;
2829 else
2830 return false;
2831 }
Chris Lattner24943d22010-06-08 16:52:24 +00002832}
2833
2834void
2835ProcessGDBRemote::StopAsyncThread ()
2836{
Greg Claytone005f2c2010-11-06 01:53:30 +00002837 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002838
2839 if (log)
2840 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2841
Jim Inghama9488302012-11-01 01:15:33 +00002842 Mutex::Locker start_locker(m_async_thread_state_mutex);
2843 if (m_async_thread_state == eAsyncThreadRunning)
Chris Lattner24943d22010-06-08 16:52:24 +00002844 {
Jim Inghama9488302012-11-01 01:15:33 +00002845 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2846
2847 // This will shut down the async thread.
2848 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
2849
2850 // Stop the stdio thread
2851 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2852 {
2853 Host::ThreadJoin (m_async_thread, NULL, NULL);
2854 }
2855 m_async_thread_state = eAsyncThreadDone;
2856 }
2857 else
2858 {
2859 if (log)
2860 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
Chris Lattner24943d22010-06-08 16:52:24 +00002861 }
2862}
2863
2864
2865void *
2866ProcessGDBRemote::AsyncThread (void *arg)
2867{
2868 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2869
Greg Claytone005f2c2010-11-06 01:53:30 +00002870 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002871 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002872 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002873
2874 Listener listener ("ProcessGDBRemote::AsyncThread");
2875 EventSP event_sp;
2876 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2877 eBroadcastBitAsyncThreadShouldExit;
2878
2879 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2880 {
Greg Claytona2f74232011-02-24 22:24:29 +00002881 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2882
Chris Lattner24943d22010-06-08 16:52:24 +00002883 bool done = false;
2884 while (!done)
2885 {
2886 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002887 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002888 if (listener.WaitForEvent (NULL, event_sp))
2889 {
2890 const uint32_t event_type = event_sp->GetType();
Greg Claytona2f74232011-02-24 22:24:29 +00002891 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner24943d22010-06-08 16:52:24 +00002892 {
Greg Claytona2f74232011-02-24 22:24:29 +00002893 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002894 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 +00002895
Greg Claytona2f74232011-02-24 22:24:29 +00002896 switch (event_type)
2897 {
2898 case eBroadcastBitAsyncContinue:
Chris Lattner24943d22010-06-08 16:52:24 +00002899 {
Greg Claytona2f74232011-02-24 22:24:29 +00002900 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002901
Greg Claytona2f74232011-02-24 22:24:29 +00002902 if (continue_packet)
Chris Lattner24943d22010-06-08 16:52:24 +00002903 {
Greg Claytona2f74232011-02-24 22:24:29 +00002904 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2905 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2906 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002907 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +00002908
Greg Claytona2f74232011-02-24 22:24:29 +00002909 if (::strstr (continue_cstr, "vAttach") == NULL)
2910 process->SetPrivateState(eStateRunning);
2911 StringExtractorGDBRemote response;
2912 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner24943d22010-06-08 16:52:24 +00002913
Greg Clayton67b402c2012-05-16 02:48:06 +00002914 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
2915 // The thread ID list might be contained within the "response", or the stop reply packet that
2916 // caused the stop. So clear it now before we give the stop reply packet to the process
2917 // using the process->SetLastStopPacket()...
2918 process->ClearThreadIDList ();
2919
Greg Claytona2f74232011-02-24 22:24:29 +00002920 switch (stop_state)
2921 {
2922 case eStateStopped:
2923 case eStateCrashed:
2924 case eStateSuspended:
Greg Clayton06709002011-12-06 04:51:14 +00002925 process->SetLastStopPacket (response);
Greg Claytona2f74232011-02-24 22:24:29 +00002926 process->SetPrivateState (stop_state);
2927 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002928
Greg Claytona2f74232011-02-24 22:24:29 +00002929 case eStateExited:
Greg Clayton06709002011-12-06 04:51:14 +00002930 process->SetLastStopPacket (response);
Greg Clayton5a9f85c2012-04-10 02:25:43 +00002931 process->ClearThreadIDList();
Greg Claytona2f74232011-02-24 22:24:29 +00002932 response.SetFilePos(1);
2933 process->SetExitStatus(response.GetHexU8(), NULL);
2934 done = true;
2935 break;
2936
2937 case eStateInvalid:
2938 process->SetExitStatus(-1, "lost connection");
2939 break;
2940
2941 default:
2942 process->SetPrivateState (stop_state);
2943 break;
2944 }
Chris Lattner24943d22010-06-08 16:52:24 +00002945 }
2946 }
Greg Claytona2f74232011-02-24 22:24:29 +00002947 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002948
Greg Claytona2f74232011-02-24 22:24:29 +00002949 case eBroadcastBitAsyncThreadShouldExit:
2950 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002951 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Claytona2f74232011-02-24 22:24:29 +00002952 done = true;
2953 break;
Chris Lattner24943d22010-06-08 16:52:24 +00002954
Greg Claytona2f74232011-02-24 22:24:29 +00002955 default:
2956 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002957 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 +00002958 done = true;
2959 break;
2960 }
2961 }
2962 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2963 {
2964 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2965 {
2966 process->SetExitStatus (-1, "lost connection");
Chris Lattner24943d22010-06-08 16:52:24 +00002967 done = true;
Greg Claytona2f74232011-02-24 22:24:29 +00002968 }
Chris Lattner24943d22010-06-08 16:52:24 +00002969 }
2970 }
2971 else
2972 {
2973 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002974 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 +00002975 done = true;
2976 }
2977 }
2978 }
2979
2980 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002981 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002982
2983 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2984 return NULL;
2985}
2986
Chris Lattner24943d22010-06-08 16:52:24 +00002987const char *
2988ProcessGDBRemote::GetDispatchQueueNameForThread
2989(
2990 addr_t thread_dispatch_qaddr,
2991 std::string &dispatch_queue_name
2992)
2993{
2994 dispatch_queue_name.clear();
2995 if (thread_dispatch_qaddr != 0 && thread_dispatch_qaddr != LLDB_INVALID_ADDRESS)
2996 {
2997 // Cache the dispatch_queue_offsets_addr value so we don't always have
2998 // to look it up
2999 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
3000 {
Greg Claytonaf6e9e42010-10-12 17:33:06 +00003001 static ConstString g_dispatch_queue_offsets_symbol_name ("dispatch_queue_offsets");
3002 const Symbol *dispatch_queue_offsets_symbol = NULL;
Greg Clayton444fe992012-02-26 05:51:37 +00003003 ModuleSpec libSystem_module_spec (FileSpec("libSystem.B.dylib", false));
3004 ModuleSP module_sp(GetTarget().GetImages().FindFirstModule (libSystem_module_spec));
Greg Claytonaf6e9e42010-10-12 17:33:06 +00003005 if (module_sp)
3006 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
3007
3008 if (dispatch_queue_offsets_symbol == NULL)
3009 {
Greg Clayton444fe992012-02-26 05:51:37 +00003010 ModuleSpec libdispatch_module_spec (FileSpec("libdispatch.dylib", false));
3011 module_sp = GetTarget().GetImages().FindFirstModule (libdispatch_module_spec);
Greg Claytonaf6e9e42010-10-12 17:33:06 +00003012 if (module_sp)
3013 dispatch_queue_offsets_symbol = module_sp->FindFirstSymbolWithNameAndType (g_dispatch_queue_offsets_symbol_name, eSymbolTypeData);
3014 }
Chris Lattner24943d22010-06-08 16:52:24 +00003015 if (dispatch_queue_offsets_symbol)
Greg Clayton0c31d3d2012-03-07 21:03:09 +00003016 m_dispatch_queue_offsets_addr = dispatch_queue_offsets_symbol->GetAddress().GetLoadAddress(&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00003017
3018 if (m_dispatch_queue_offsets_addr == LLDB_INVALID_ADDRESS)
3019 return NULL;
3020 }
3021
3022 uint8_t memory_buffer[8];
Greg Clayton395fc332011-02-15 21:59:32 +00003023 DataExtractor data (memory_buffer,
3024 sizeof(memory_buffer),
3025 m_target.GetArchitecture().GetByteOrder(),
3026 m_target.GetArchitecture().GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +00003027
3028 // Excerpt from src/queue_private.h
3029 struct dispatch_queue_offsets_s
3030 {
3031 uint16_t dqo_version;
Jason Molenda9704ca22012-11-10 06:54:30 +00003032 uint16_t dqo_label; // in version 1-3, offset to string; in version 4+, offset to a pointer to a string
3033 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 +00003034 } dispatch_queue_offsets;
3035
3036
3037 Error error;
3038 if (ReadMemory (m_dispatch_queue_offsets_addr, memory_buffer, sizeof(dispatch_queue_offsets), error) == sizeof(dispatch_queue_offsets))
3039 {
3040 uint32_t data_offset = 0;
3041 if (data.GetU16(&data_offset, &dispatch_queue_offsets.dqo_version, sizeof(dispatch_queue_offsets)/sizeof(uint16_t)))
3042 {
3043 if (ReadMemory (thread_dispatch_qaddr, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
3044 {
3045 data_offset = 0;
3046 lldb::addr_t queue_addr = data.GetAddress(&data_offset);
Jason Molenda9704ca22012-11-10 06:54:30 +00003047 if (dispatch_queue_offsets.dqo_version >= 4)
3048 {
3049 // libdispatch versions 4+, pointer to dispatch name is in the
3050 // queue structure.
3051 lldb::addr_t pointer_to_label_address = queue_addr + dispatch_queue_offsets.dqo_label;
3052 if (ReadMemory (pointer_to_label_address, &memory_buffer, data.GetAddressByteSize(), error) == data.GetAddressByteSize())
3053 {
3054 data_offset = 0;
3055 lldb::addr_t label_addr = data.GetAddress(&data_offset);
3056 ReadCStringFromMemory (label_addr, dispatch_queue_name, error);
3057 }
3058 }
3059 else
3060 {
3061 // libdispatch versions 1-3, dispatch name is a fixed width char array
3062 // in the queue structure.
3063 lldb::addr_t label_addr = queue_addr + dispatch_queue_offsets.dqo_label;
3064 dispatch_queue_name.resize(dispatch_queue_offsets.dqo_label_size, '\0');
3065 size_t bytes_read = ReadMemory (label_addr, &dispatch_queue_name[0], dispatch_queue_offsets.dqo_label_size, error);
3066 if (bytes_read < dispatch_queue_offsets.dqo_label_size)
3067 dispatch_queue_name.erase (bytes_read);
3068 }
Chris Lattner24943d22010-06-08 16:52:24 +00003069 }
3070 }
3071 }
3072 }
3073 if (dispatch_queue_name.empty())
3074 return NULL;
3075 return dispatch_queue_name.c_str();
3076}
3077
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003078//uint32_t
3079//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3080//{
3081// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
3082// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
3083// if (m_local_debugserver)
3084// {
3085// return Host::ListProcessesMatchingName (name, matches, pids);
3086// }
3087// else
3088// {
3089// // FIXME: Implement talking to the remote debugserver.
3090// return 0;
3091// }
3092//
3093//}
3094//
Jim Ingham55e01d82011-01-22 01:33:44 +00003095bool
3096ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
3097 lldb_private::StoppointCallbackContext *context,
3098 lldb::user_id_t break_id,
3099 lldb::user_id_t break_loc_id)
3100{
3101 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3102 // run so I can stop it if that's what I want to do.
3103 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
3104 if (log)
3105 log->Printf("Hit New Thread Notification breakpoint.");
3106 return false;
3107}
3108
3109
3110bool
3111ProcessGDBRemote::StartNoticingNewThreads()
3112{
Jim Ingham55e01d82011-01-22 01:33:44 +00003113 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003114 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00003115 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003116 if (log && log->GetVerbose())
3117 log->Printf("Enabled noticing new thread breakpoint.");
3118 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham55e01d82011-01-22 01:33:44 +00003119 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003120 else
Jim Ingham55e01d82011-01-22 01:33:44 +00003121 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003122 PlatformSP platform_sp (m_target.GetPlatform());
3123 if (platform_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00003124 {
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003125 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3126 if (m_thread_create_bp_sp)
Jim Ingham55e01d82011-01-22 01:33:44 +00003127 {
Jim Ingham6bb73372011-10-15 00:21:37 +00003128 if (log && log->GetVerbose())
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003129 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3130 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham55e01d82011-01-22 01:33:44 +00003131 }
3132 else
3133 {
3134 if (log)
3135 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham55e01d82011-01-22 01:33:44 +00003136 }
3137 }
3138 }
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003139 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham55e01d82011-01-22 01:33:44 +00003140}
3141
3142bool
3143ProcessGDBRemote::StopNoticingNewThreads()
3144{
Jim Inghamff276fe2011-02-08 05:19:01 +00003145 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham6bb73372011-10-15 00:21:37 +00003146 if (log && log->GetVerbose())
Jim Inghamff276fe2011-02-08 05:19:01 +00003147 log->Printf ("Disabling new thread notification breakpoint.");
Greg Claytonbd5c23d2012-05-15 02:33:01 +00003148
3149 if (m_thread_create_bp_sp)
3150 m_thread_create_bp_sp->SetEnabled(false);
3151
Jim Ingham55e01d82011-01-22 01:33:44 +00003152 return true;
3153}
3154
Jason Molendab46937c2012-10-03 01:29:34 +00003155lldb_private::DynamicLoader *
3156ProcessGDBRemote::GetDynamicLoader ()
3157{
3158 if (m_dyld_ap.get() == NULL)
3159 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, m_dyld_plugin_name.empty() ? NULL : m_dyld_plugin_name.c_str()));
3160 return m_dyld_ap.get();
3161}
Jim Ingham55e01d82011-01-22 01:33:44 +00003162
Greg Clayton13193d52012-10-13 02:07:45 +00003163
Greg Claytonb8596392012-10-15 22:42:16 +00003164class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton13193d52012-10-13 02:07:45 +00003165{
3166private:
3167
3168public:
Greg Claytonb8596392012-10-15 22:42:16 +00003169 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton13193d52012-10-13 02:07:45 +00003170 CommandObjectParsed (interpreter,
Greg Claytonb8596392012-10-15 22:42:16 +00003171 "process plugin packet history",
3172 "Dumps the packet history buffer. ",
Greg Clayton13193d52012-10-13 02:07:45 +00003173 NULL)
3174 {
3175 }
3176
Greg Claytonb8596392012-10-15 22:42:16 +00003177 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton13193d52012-10-13 02:07:45 +00003178 {
3179 }
3180
3181 bool
3182 DoExecute (Args& command, CommandReturnObject &result)
3183 {
Greg Claytonb8596392012-10-15 22:42:16 +00003184 const size_t argc = command.GetArgumentCount();
3185 if (argc == 0)
3186 {
3187 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3188 if (process)
3189 {
3190 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
3191 result.SetStatus (eReturnStatusSuccessFinishResult);
3192 return true;
3193 }
3194 }
3195 else
3196 {
3197 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
3198 }
3199 result.SetStatus (eReturnStatusFailed);
3200 return false;
3201 }
3202};
3203
3204class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
3205{
3206private:
3207
3208public:
3209 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
3210 CommandObjectParsed (interpreter,
3211 "process plugin packet send",
3212 "Send a custom packet through the GDB remote protocol and print the answer. "
3213 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
3214 NULL)
3215 {
3216 }
3217
3218 ~CommandObjectProcessGDBRemotePacketSend ()
3219 {
3220 }
3221
3222 bool
3223 DoExecute (Args& command, CommandReturnObject &result)
3224 {
3225 const size_t argc = command.GetArgumentCount();
3226 if (argc == 0)
3227 {
3228 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
3229 result.SetStatus (eReturnStatusFailed);
3230 return false;
3231 }
3232
3233 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3234 if (process)
3235 {
Han Ming Ongae9cc552012-11-26 20:42:03 +00003236 for (size_t i=0; i<argc; ++ i)
Greg Claytonb8596392012-10-15 22:42:16 +00003237 {
Han Ming Ongae9cc552012-11-26 20:42:03 +00003238 const char *packet_cstr = command.GetArgumentAtIndex(0);
3239 bool send_async = true;
3240 StringExtractorGDBRemote response;
3241 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3242 result.SetStatus (eReturnStatusSuccessFinishResult);
3243 Stream &output_strm = result.GetOutputStream();
3244 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong0df19cc2013-01-18 23:11:53 +00003245 std::string &response_str = response.GetStringRef();
3246
3247 if (strcmp(packet_cstr, "qGetProfileData") == 0)
3248 {
3249 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
3250 }
3251
Han Ming Ongae9cc552012-11-26 20:42:03 +00003252 if (response_str.empty())
3253 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3254 else
3255 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Claytonb8596392012-10-15 22:42:16 +00003256 }
Greg Claytonb8596392012-10-15 22:42:16 +00003257 }
Greg Clayton13193d52012-10-13 02:07:45 +00003258 return true;
3259 }
3260};
3261
Greg Claytonb8596392012-10-15 22:42:16 +00003262class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
3263{
3264private:
3265
3266public:
3267 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
3268 CommandObjectMultiword (interpreter,
3269 "process plugin packet",
3270 "Commands that deal with GDB remote packets.",
3271 NULL)
3272 {
3273 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
3274 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
3275 }
3276
3277 ~CommandObjectProcessGDBRemotePacket ()
3278 {
3279 }
3280};
Greg Clayton13193d52012-10-13 02:07:45 +00003281
3282class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
3283{
3284public:
3285 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
3286 CommandObjectMultiword (interpreter,
3287 "process plugin",
3288 "A set of commands for operating on a ProcessGDBRemote process.",
3289 "process plugin <subcommand> [<subcommand-options>]")
3290 {
3291 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
3292 }
3293
3294 ~CommandObjectMultiwordProcessGDBRemote ()
3295 {
3296 }
3297};
3298
Greg Clayton13193d52012-10-13 02:07:45 +00003299CommandObject *
3300ProcessGDBRemote::GetPluginCommandObject()
3301{
3302 if (!m_command_sp)
3303 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
3304 return m_command_sp.get();
3305}