blob: 584a62ce963d5f29c01c761c5a9af41578da177a [file] [log] [blame]
Greg Clayton59ec5122011-07-15 18:02:58 +00001//===-- ProcessKDP.cpp ------------------------------------------*- C++ -*-===//
Greg Claytonf9765ac2011-07-15 03:27:12 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10// C Includes
11#include <errno.h>
12#include <stdlib.h>
13
14// C++ Includes
15// Other libraries and framework includes
Greg Clayton07e66e32011-07-20 03:41:06 +000016#include "lldb/Core/Debugger.h"
Greg Claytonf9765ac2011-07-15 03:27:12 +000017#include "lldb/Core/PluginManager.h"
Greg Clayton1f746072012-08-29 21:13:06 +000018#include "lldb/Core/Module.h"
Jason Molenda4bd4e7e2012-09-29 04:02:01 +000019#include "lldb/Core/ModuleSpec.h"
Greg Claytonf9765ac2011-07-15 03:27:12 +000020#include "lldb/Core/State.h"
Jason Molenda4bd4e7e2012-09-29 04:02:01 +000021#include "lldb/Core/UUID.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000022#include "lldb/Host/ConnectionFileDescriptor.h"
Greg Claytonf9765ac2011-07-15 03:27:12 +000023#include "lldb/Host/Host.h"
Jason Molenda4bd4e7e2012-09-29 04:02:01 +000024#include "lldb/Host/Symbols.h"
Keno Fischer3d7162b2014-08-06 21:18:13 +000025#include "lldb/Host/Socket.h"
Zachary Turner39de3112014-09-09 20:54:56 +000026#include "lldb/Host/ThreadLauncher.h"
Greg Clayton1d19a2f2012-10-19 22:22:57 +000027#include "lldb/Interpreter/CommandInterpreter.h"
28#include "lldb/Interpreter/CommandObject.h"
29#include "lldb/Interpreter/CommandObjectMultiword.h"
30#include "lldb/Interpreter/CommandReturnObject.h"
31#include "lldb/Interpreter/OptionGroupString.h"
32#include "lldb/Interpreter/OptionGroupUInt64.h"
Greg Clayton1f746072012-08-29 21:13:06 +000033#include "lldb/Symbol/ObjectFile.h"
Greg Clayton7925fbb2012-09-21 16:31:20 +000034#include "lldb/Target/RegisterContext.h"
Greg Clayton57508022011-07-15 16:31:38 +000035#include "lldb/Target/Target.h"
Greg Claytona63d08c2011-07-19 03:57:15 +000036#include "lldb/Target/Thread.h"
Greg Claytonf9765ac2011-07-15 03:27:12 +000037
Charles Davis510938e2013-08-27 05:04:57 +000038#define USEC_PER_SEC 1000000
39
Greg Claytonf9765ac2011-07-15 03:27:12 +000040// Project includes
41#include "ProcessKDP.h"
42#include "ProcessKDPLog.h"
Greg Claytona63d08c2011-07-19 03:57:15 +000043#include "ThreadKDP.h"
Jason Molenda5e8534e2012-10-03 01:29:34 +000044#include "Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.h"
Jason Molenda840f12c2012-10-25 00:25:13 +000045#include "Plugins/DynamicLoader/Static/DynamicLoaderStatic.h"
Greg Clayton1d19a2f2012-10-19 22:22:57 +000046#include "Utility/StringExtractor.h"
Greg Claytonf9765ac2011-07-15 03:27:12 +000047
48using namespace lldb;
49using namespace lldb_private;
50
Greg Clayton7f982402013-07-15 22:54:20 +000051namespace {
52
53 static PropertyDefinition
54 g_properties[] =
55 {
56 { "packet-timeout" , OptionValue::eTypeUInt64 , true , 5, NULL, NULL, "Specify the default packet timeout in seconds." },
57 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
58 };
59
60 enum
61 {
62 ePropertyPacketTimeout
63 };
64
65 class PluginProperties : public Properties
66 {
67 public:
68
69 static ConstString
70 GetSettingName ()
71 {
72 return ProcessKDP::GetPluginNameStatic();
73 }
74
75 PluginProperties() :
76 Properties ()
77 {
78 m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
79 m_collection_sp->Initialize(g_properties);
80 }
81
82 virtual
83 ~PluginProperties()
84 {
85 }
86
87 uint64_t
88 GetPacketTimeout()
89 {
90 const uint32_t idx = ePropertyPacketTimeout;
91 return m_collection_sp->GetPropertyAtIndexAsUInt64(NULL, idx, g_properties[idx].default_uint_value);
92 }
93 };
94
95 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
96
97 static const ProcessKDPPropertiesSP &
98 GetGlobalPluginProperties()
99 {
100 static ProcessKDPPropertiesSP g_settings_sp;
101 if (!g_settings_sp)
102 g_settings_sp.reset (new PluginProperties ());
103 return g_settings_sp;
104 }
105
106} // anonymous namespace end
107
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000108static const lldb::tid_t g_kernel_tid = 1;
109
Greg Clayton57abc5d2013-05-10 21:47:16 +0000110ConstString
Greg Claytonf9765ac2011-07-15 03:27:12 +0000111ProcessKDP::GetPluginNameStatic()
112{
Greg Clayton57abc5d2013-05-10 21:47:16 +0000113 static ConstString g_name("kdp-remote");
114 return g_name;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000115}
116
117const char *
118ProcessKDP::GetPluginDescriptionStatic()
119{
120 return "KDP Remote protocol based debugging plug-in for darwin kernel debugging.";
121}
122
123void
124ProcessKDP::Terminate()
125{
126 PluginManager::UnregisterPlugin (ProcessKDP::CreateInstance);
127}
128
129
Greg Claytonc3776bf2012-02-09 06:16:32 +0000130lldb::ProcessSP
131ProcessKDP::CreateInstance (Target &target,
132 Listener &listener,
133 const FileSpec *crash_file_path)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000134{
Greg Claytonc3776bf2012-02-09 06:16:32 +0000135 lldb::ProcessSP process_sp;
136 if (crash_file_path == NULL)
137 process_sp.reset(new ProcessKDP (target, listener));
138 return process_sp;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000139}
140
141bool
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000142ProcessKDP::CanDebug(Target &target, bool plugin_specified_by_name)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000143{
Greg Clayton596ed242011-10-21 21:41:45 +0000144 if (plugin_specified_by_name)
145 return true;
146
Greg Claytonf9765ac2011-07-15 03:27:12 +0000147 // For now we are just making sure the file exists for a given module
Greg Claytonaa149cb2011-08-11 02:48:45 +0000148 Module *exe_module = target.GetExecutableModulePointer();
149 if (exe_module)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000150 {
151 const llvm::Triple &triple_ref = target.GetArchitecture().GetTriple();
Greg Clayton70512312012-05-08 01:45:38 +0000152 switch (triple_ref.getOS())
Greg Claytonf9765ac2011-07-15 03:27:12 +0000153 {
Greg Clayton70512312012-05-08 01:45:38 +0000154 case llvm::Triple::Darwin: // Should use "macosx" for desktop and "ios" for iOS, but accept darwin just in case
155 case llvm::Triple::MacOSX: // For desktop targets
156 case llvm::Triple::IOS: // For arm targets
157 if (triple_ref.getVendor() == llvm::Triple::Apple)
158 {
159 ObjectFile *exe_objfile = exe_module->GetObjectFile();
160 if (exe_objfile->GetType() == ObjectFile::eTypeExecutable &&
161 exe_objfile->GetStrata() == ObjectFile::eStrataKernel)
162 return true;
163 }
164 break;
165
166 default:
167 break;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000168 }
169 }
Greg Clayton596ed242011-10-21 21:41:45 +0000170 return false;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000171}
172
173//----------------------------------------------------------------------
174// ProcessKDP constructor
175//----------------------------------------------------------------------
176ProcessKDP::ProcessKDP(Target& target, Listener &listener) :
177 Process (target, listener),
178 m_comm("lldb.process.kdp-remote.communication"),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000179 m_async_broadcaster (NULL, "lldb.process.kdp-remote.async-broadcaster"),
Jason Molenda5e8534e2012-10-03 01:29:34 +0000180 m_dyld_plugin_name (),
Greg Clayton1d19a2f2012-10-19 22:22:57 +0000181 m_kernel_load_addr (LLDB_INVALID_ADDRESS),
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000182 m_command_sp(),
183 m_kernel_thread_wp()
Greg Claytonf9765ac2011-07-15 03:27:12 +0000184{
Greg Clayton7925fbb2012-09-21 16:31:20 +0000185 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
186 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Greg Clayton7f982402013-07-15 22:54:20 +0000187 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
188 if (timeout_seconds > 0)
189 m_comm.SetPacketTimeout(timeout_seconds);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000190}
191
192//----------------------------------------------------------------------
193// Destructor
194//----------------------------------------------------------------------
195ProcessKDP::~ProcessKDP()
196{
197 Clear();
Greg Claytone24c4ac2011-11-17 04:46:02 +0000198 // We need to call finalize on the process before destroying ourselves
199 // to make sure all of the broadcaster cleanup goes as planned. If we
200 // destruct this class, then Process::~Process() might have problems
201 // trying to fully destroy the broadcaster.
202 Finalize();
Greg Claytonf9765ac2011-07-15 03:27:12 +0000203}
204
205//----------------------------------------------------------------------
206// PluginInterface
207//----------------------------------------------------------------------
Greg Clayton57abc5d2013-05-10 21:47:16 +0000208lldb_private::ConstString
Greg Claytonf9765ac2011-07-15 03:27:12 +0000209ProcessKDP::GetPluginName()
210{
Greg Claytonf9765ac2011-07-15 03:27:12 +0000211 return GetPluginNameStatic();
212}
213
214uint32_t
215ProcessKDP::GetPluginVersion()
216{
217 return 1;
218}
219
220Error
221ProcessKDP::WillLaunch (Module* module)
222{
223 Error error;
224 error.SetErrorString ("launching not supported in kdp-remote plug-in");
225 return error;
226}
227
228Error
229ProcessKDP::WillAttachToProcessWithID (lldb::pid_t pid)
230{
231 Error error;
232 error.SetErrorString ("attaching to a by process ID not supported in kdp-remote plug-in");
233 return error;
234}
235
236Error
237ProcessKDP::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
238{
239 Error error;
240 error.SetErrorString ("attaching to a by process name not supported in kdp-remote plug-in");
241 return error;
242}
243
244Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000245ProcessKDP::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000246{
Greg Claytonf9765ac2011-07-15 03:27:12 +0000247 Error error;
Greg Clayton7925fbb2012-09-21 16:31:20 +0000248
249 // Don't let any JIT happen when doing KDP as we can't allocate
250 // memory and we don't want to be mucking with threads that might
251 // already be handling exceptions
252 SetCanJIT(false);
253
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000254 if (remote_url == NULL || remote_url[0] == '\0')
Greg Clayton7925fbb2012-09-21 16:31:20 +0000255 {
256 error.SetErrorStringWithFormat ("invalid connection URL '%s'", remote_url);
257 return error;
258 }
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000259
Greg Clayton7b0992d2013-04-18 22:45:39 +0000260 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000261 if (conn_ap.get())
262 {
263 // Only try once for now.
264 // TODO: check if we should be retrying?
265 const uint32_t max_retry_count = 1;
266 for (uint32_t retry_count = 0; retry_count < max_retry_count; ++retry_count)
267 {
268 if (conn_ap->Connect(remote_url, &error) == eConnectionStatusSuccess)
269 break;
270 usleep (100000);
271 }
272 }
273
274 if (conn_ap->IsConnected())
275 {
Keno Fischer3d7162b2014-08-06 21:18:13 +0000276 const Socket& socket = static_cast<const Socket&>(*conn_ap->GetReadObject());
277 const uint16_t reply_port = socket.GetPortNumber();
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000278
279 if (reply_port != 0)
280 {
281 m_comm.SetConnection(conn_ap.release());
282
283 if (m_comm.SendRequestReattach(reply_port))
284 {
285 if (m_comm.SendRequestConnect(reply_port, reply_port, "Greetings from LLDB..."))
286 {
287 m_comm.GetVersion();
288 uint32_t cpu = m_comm.GetCPUType();
289 uint32_t sub = m_comm.GetCPUSubtype();
290 ArchSpec kernel_arch;
291 kernel_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
292 m_target.SetArchitecture(kernel_arch);
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000293
Jason Molenda840f12c2012-10-25 00:25:13 +0000294 /* Get the kernel's UUID and load address via KDP_KERNELVERSION packet. */
295 /* An EFI kdp session has neither UUID nor load address. */
296
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000297 UUID kernel_uuid = m_comm.GetUUID ();
298 addr_t kernel_load_addr = m_comm.GetLoadAddress ();
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000299
Jason Molenda840f12c2012-10-25 00:25:13 +0000300 if (m_comm.RemoteIsEFI ())
301 {
Greg Claytona1bce2e2014-07-16 21:16:27 +0000302 // Select an invalid plugin name for the dynamic loader so one doesn't get used
303 // since EFI does its own manual loading via python scripting
304 static ConstString g_none_dynamic_loader("none");
305 m_dyld_plugin_name = g_none_dynamic_loader;
306
307 if (kernel_uuid.IsValid()) {
308 // If EFI passed in a UUID= try to lookup UUID
309 // The slide will not be provided. But the UUID
310 // lookup will be used to launch EFI debug scripts
311 // from the dSYM, that can load all of the symbols.
312 ModuleSpec module_spec;
313 module_spec.GetUUID() = kernel_uuid;
314 module_spec.GetArchitecture() = m_target.GetArchitecture();
315
316 // Lookup UUID locally, before attempting dsymForUUID like action
317 module_spec.GetSymbolFileSpec() = Symbols::LocateExecutableSymbolFile(module_spec);
318 if (module_spec.GetSymbolFileSpec())
319 module_spec.GetFileSpec() = Symbols::LocateExecutableObjectFile (module_spec);
320 if (!module_spec.GetSymbolFileSpec() || !module_spec.GetSymbolFileSpec())
321 Symbols::DownloadObjectAndSymbolFile (module_spec, true);
322
323 if (module_spec.GetFileSpec().Exists())
324 {
325 ModuleSP module_sp(new Module (module_spec.GetFileSpec(), m_target.GetArchitecture()));
326 if (module_sp.get() && module_sp->MatchesModuleSpec (module_spec))
327 {
328 // Get the current target executable
329 ModuleSP exe_module_sp (m_target.GetExecutableModule ());
330
331 // Make sure you don't already have the right module loaded and they will be uniqued
332 if (exe_module_sp.get() != module_sp.get())
333 m_target.SetExecutableModule (module_sp, false);
334 }
335 }
336 }
Jason Molenda840f12c2012-10-25 00:25:13 +0000337 }
Jason Molendaca2ffa72013-05-09 23:52:21 +0000338 else if (m_comm.RemoteIsDarwinKernel ())
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000339 {
Jason Molendaca2ffa72013-05-09 23:52:21 +0000340 m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
Jason Molendaa8ea4ba2013-05-06 23:02:03 +0000341 if (kernel_load_addr != LLDB_INVALID_ADDRESS)
342 {
343 m_kernel_load_addr = kernel_load_addr;
344 }
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000345 }
346
Greg Clayton97d5cf02012-09-25 02:40:06 +0000347 // Set the thread ID
348 UpdateThreadListIfNeeded ();
Greg Claytona63d08c2011-07-19 03:57:15 +0000349 SetID (1);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000350 GetThreadList ();
Greg Claytona63d08c2011-07-19 03:57:15 +0000351 SetPrivateState (eStateStopped);
Greg Clayton07e66e32011-07-20 03:41:06 +0000352 StreamSP async_strm_sp(m_target.GetDebugger().GetAsyncOutputStream());
353 if (async_strm_sp)
354 {
Greg Clayton5b882162011-07-21 01:12:01 +0000355 const char *cstr;
356 if ((cstr = m_comm.GetKernelVersion ()) != NULL)
Greg Clayton07e66e32011-07-20 03:41:06 +0000357 {
Greg Clayton5b882162011-07-21 01:12:01 +0000358 async_strm_sp->Printf ("Version: %s\n", cstr);
Greg Clayton07e66e32011-07-20 03:41:06 +0000359 async_strm_sp->Flush();
360 }
Greg Clayton5b882162011-07-21 01:12:01 +0000361// if ((cstr = m_comm.GetImagePath ()) != NULL)
362// {
363// async_strm_sp->Printf ("Image Path: %s\n", cstr);
364// async_strm_sp->Flush();
365// }
Greg Clayton07e66e32011-07-20 03:41:06 +0000366 }
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000367 }
Greg Clayton97d5cf02012-09-25 02:40:06 +0000368 else
369 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000370 error.SetErrorString("KDP_REATTACH failed");
371 }
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000372 }
373 else
374 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000375 error.SetErrorString("KDP_REATTACH failed");
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000376 }
377 }
378 else
379 {
380 error.SetErrorString("invalid reply port from UDP connection");
381 }
382 }
383 else
384 {
385 if (error.Success())
386 error.SetErrorStringWithFormat ("failed to connect to '%s'", remote_url);
387 }
388 if (error.Fail())
389 m_comm.Disconnect();
390
Greg Claytonf9765ac2011-07-15 03:27:12 +0000391 return error;
392}
393
394//----------------------------------------------------------------------
395// Process Control
396//----------------------------------------------------------------------
397Error
Greg Clayton982c9762011-11-03 21:22:33 +0000398ProcessKDP::DoLaunch (Module *exe_module,
Jean-Daniel Dupas7782de92013-12-09 22:52:50 +0000399 ProcessLaunchInfo &launch_info)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000400{
401 Error error;
402 error.SetErrorString ("launching not supported in kdp-remote plug-in");
403 return error;
404}
405
406
407Error
408ProcessKDP::DoAttachToProcessWithID (lldb::pid_t attach_pid)
409{
410 Error error;
411 error.SetErrorString ("attach to process by ID is not suppported in kdp remote debugging");
412 return error;
413}
414
Greg Claytonf9765ac2011-07-15 03:27:12 +0000415Error
Han Ming Ong84647042012-02-25 01:07:38 +0000416ProcessKDP::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
417{
418 Error error;
419 error.SetErrorString ("attach to process by ID is not suppported in kdp remote debugging");
420 return error;
421}
422
423Error
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +0000424ProcessKDP::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000425{
426 Error error;
427 error.SetErrorString ("attach to process by name is not suppported in kdp remote debugging");
428 return error;
429}
430
431
432void
Jim Inghambb006ce2014-08-02 00:33:35 +0000433ProcessKDP::DidAttach (ArchSpec &process_arch)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000434{
Jim Inghambb006ce2014-08-02 00:33:35 +0000435 Process::DidAttach(process_arch);
436
Greg Clayton5160ce52013-03-27 23:08:40 +0000437 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_PROCESS));
Greg Claytonf9765ac2011-07-15 03:27:12 +0000438 if (log)
Johnny Chen54cb8f82011-10-11 21:17:10 +0000439 log->Printf ("ProcessKDP::DidAttach()");
Greg Claytonf9765ac2011-07-15 03:27:12 +0000440 if (GetID() != LLDB_INVALID_PROCESS_ID)
441 {
442 // TODO: figure out the register context that we will use
443 }
444}
445
Jason Molenda5e8534e2012-10-03 01:29:34 +0000446addr_t
447ProcessKDP::GetImageInfoAddress()
448{
449 return m_kernel_load_addr;
450}
451
452lldb_private::DynamicLoader *
453ProcessKDP::GetDynamicLoader ()
454{
455 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +0000456 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, m_dyld_plugin_name.IsEmpty() ? NULL : m_dyld_plugin_name.GetCString()));
Jason Molenda5e8534e2012-10-03 01:29:34 +0000457 return m_dyld_ap.get();
458}
459
Greg Claytonf9765ac2011-07-15 03:27:12 +0000460Error
461ProcessKDP::WillResume ()
462{
463 return Error();
464}
465
466Error
467ProcessKDP::DoResume ()
468{
469 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +0000470 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_PROCESS));
Greg Clayton7925fbb2012-09-21 16:31:20 +0000471 // Only start the async thread if we try to do any process control
Zachary Turneracee96a2014-09-23 18:32:09 +0000472 if (!m_async_thread.IsJoinable())
Zachary Turner39de3112014-09-09 20:54:56 +0000473 StartAsyncThread();
Greg Clayton7925fbb2012-09-21 16:31:20 +0000474
Greg Clayton97d5cf02012-09-25 02:40:06 +0000475 bool resume = false;
Greg Clayton7925fbb2012-09-21 16:31:20 +0000476
Greg Clayton97d5cf02012-09-25 02:40:06 +0000477 // With KDP there is only one thread we can tell what to do
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000478 ThreadSP kernel_thread_sp (m_thread_list.FindThreadByProtocolID(g_kernel_tid));
479
Greg Clayton97d5cf02012-09-25 02:40:06 +0000480 if (kernel_thread_sp)
Greg Clayton4b1b8b32012-09-21 01:55:30 +0000481 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000482 const StateType thread_resume_state = kernel_thread_sp->GetTemporaryResumeState();
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000483
484 if (log)
485 log->Printf ("ProcessKDP::DoResume() thread_resume_state = %s", StateAsCString(thread_resume_state));
Greg Clayton7925fbb2012-09-21 16:31:20 +0000486 switch (thread_resume_state)
Greg Clayton4b1b8b32012-09-21 01:55:30 +0000487 {
Greg Clayton7925fbb2012-09-21 16:31:20 +0000488 case eStateSuspended:
489 // Nothing to do here when a thread will stay suspended
490 // we just leave the CPU mask bit set to zero for the thread
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000491 if (log)
492 log->Printf ("ProcessKDP::DoResume() = suspended???");
Greg Clayton7925fbb2012-09-21 16:31:20 +0000493 break;
494
495 case eStateStepping:
Greg Clayton1afa68e2013-04-02 20:32:37 +0000496 {
497 lldb::RegisterContextSP reg_ctx_sp (kernel_thread_sp->GetRegisterContext());
498
499 if (reg_ctx_sp)
500 {
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000501 if (log)
502 log->Printf ("ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep (true);");
Greg Clayton1afa68e2013-04-02 20:32:37 +0000503 reg_ctx_sp->HardwareSingleStep (true);
504 resume = true;
505 }
506 else
507 {
508 error.SetErrorStringWithFormat("KDP thread 0x%llx has no register context", kernel_thread_sp->GetID());
509 }
510 }
Greg Clayton97d5cf02012-09-25 02:40:06 +0000511 break;
512
Greg Clayton7925fbb2012-09-21 16:31:20 +0000513 case eStateRunning:
Greg Clayton1afa68e2013-04-02 20:32:37 +0000514 {
515 lldb::RegisterContextSP reg_ctx_sp (kernel_thread_sp->GetRegisterContext());
516
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000517 if (reg_ctx_sp)
518 {
519 if (log)
520 log->Printf ("ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep (false);");
521 reg_ctx_sp->HardwareSingleStep (false);
522 resume = true;
523 }
524 else
525 {
526 error.SetErrorStringWithFormat("KDP thread 0x%llx has no register context", kernel_thread_sp->GetID());
527 }
Greg Clayton1afa68e2013-04-02 20:32:37 +0000528 }
Greg Clayton7925fbb2012-09-21 16:31:20 +0000529 break;
Greg Clayton97d5cf02012-09-25 02:40:06 +0000530
Greg Clayton7925fbb2012-09-21 16:31:20 +0000531 default:
Greg Clayton97d5cf02012-09-25 02:40:06 +0000532 // The only valid thread resume states are listed above
Greg Clayton7925fbb2012-09-21 16:31:20 +0000533 assert (!"invalid thread resume state");
534 break;
Greg Clayton4b1b8b32012-09-21 01:55:30 +0000535 }
536 }
Greg Clayton97d5cf02012-09-25 02:40:06 +0000537
538 if (resume)
Greg Clayton7925fbb2012-09-21 16:31:20 +0000539 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000540 if (log)
541 log->Printf ("ProcessKDP::DoResume () sending resume");
Greg Clayton7925fbb2012-09-21 16:31:20 +0000542
Greg Clayton97d5cf02012-09-25 02:40:06 +0000543 if (m_comm.SendRequestResume ())
Greg Clayton7925fbb2012-09-21 16:31:20 +0000544 {
545 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue);
546 SetPrivateState(eStateRunning);
547 }
548 else
549 error.SetErrorString ("KDP resume failed");
550 }
Greg Clayton4b1b8b32012-09-21 01:55:30 +0000551 else
Greg Clayton7925fbb2012-09-21 16:31:20 +0000552 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000553 error.SetErrorString ("kernel thread is suspended");
Greg Clayton7925fbb2012-09-21 16:31:20 +0000554 }
555
Greg Claytonf9765ac2011-07-15 03:27:12 +0000556 return error;
557}
558
Greg Clayton97d5cf02012-09-25 02:40:06 +0000559lldb::ThreadSP
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000560ProcessKDP::GetKernelThread()
Greg Clayton97d5cf02012-09-25 02:40:06 +0000561{
562 // KDP only tells us about one thread/core. Any other threads will usually
563 // be the ones that are read from memory by the OS plug-ins.
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000564
565 ThreadSP thread_sp (m_kernel_thread_wp.lock());
Greg Clayton97d5cf02012-09-25 02:40:06 +0000566 if (!thread_sp)
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000567 {
568 thread_sp.reset(new ThreadKDP (*this, g_kernel_tid));
569 m_kernel_thread_wp = thread_sp;
570 }
Greg Clayton97d5cf02012-09-25 02:40:06 +0000571 return thread_sp;
572}
573
574
575
576
Greg Clayton9fc13552012-04-10 00:18:59 +0000577bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000578ProcessKDP::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000579{
580 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +0000581 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_THREAD));
Greg Claytonf9765ac2011-07-15 03:27:12 +0000582 if (log && log->GetMask().Test(KDP_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +0000583 log->Printf ("ProcessKDP::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Claytonf9765ac2011-07-15 03:27:12 +0000584
Greg Clayton39da3ef2013-04-11 22:23:34 +0000585 // Even though there is a CPU mask, it doesn't mean we can see each CPU
Greg Clayton97d5cf02012-09-25 02:40:06 +0000586 // indivudually, there is really only one. Lets call this thread 1.
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000587 ThreadSP thread_sp (old_thread_list.FindThreadByProtocolID(g_kernel_tid, false));
588 if (!thread_sp)
589 thread_sp = GetKernelThread ();
590 new_thread_list.AddThread(thread_sp);
Greg Clayton97d5cf02012-09-25 02:40:06 +0000591
Greg Clayton9fc13552012-04-10 00:18:59 +0000592 return new_thread_list.GetSize(false) > 0;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000593}
594
Greg Claytonf9765ac2011-07-15 03:27:12 +0000595void
596ProcessKDP::RefreshStateAfterStop ()
597{
598 // Let all threads recover from stopping and do any clean up based
599 // on the previous thread state (if any).
600 m_thread_list.RefreshStateAfterStop();
Greg Claytonf9765ac2011-07-15 03:27:12 +0000601}
602
603Error
604ProcessKDP::DoHalt (bool &caused_stop)
605{
606 Error error;
607
Greg Clayton97d5cf02012-09-25 02:40:06 +0000608 if (m_comm.IsRunning())
Greg Claytonf9765ac2011-07-15 03:27:12 +0000609 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000610 if (m_destroy_in_process)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000611 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000612 // If we are attemping to destroy, we need to not return an error to
613 // Halt or DoDestroy won't get called.
614 // We are also currently running, so send a process stopped event
615 SetPrivateState (eStateStopped);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000616 }
Greg Clayton97d5cf02012-09-25 02:40:06 +0000617 else
Greg Claytonf9765ac2011-07-15 03:27:12 +0000618 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000619 error.SetErrorString ("KDP cannot interrupt a running kernel");
Greg Claytonf9765ac2011-07-15 03:27:12 +0000620 }
621 }
622 return error;
623}
624
625Error
Jim Inghamacff8952013-05-02 00:27:30 +0000626ProcessKDP::DoDetach(bool keep_stopped)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000627{
628 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +0000629 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
Greg Claytonf9765ac2011-07-15 03:27:12 +0000630 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +0000631 log->Printf ("ProcessKDP::DoDetach(keep_stopped = %i)", keep_stopped);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000632
Greg Clayton97d5cf02012-09-25 02:40:06 +0000633 if (m_comm.IsRunning())
Greg Claytonf9765ac2011-07-15 03:27:12 +0000634 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000635 // We are running and we can't interrupt a running kernel, so we need
636 // to just close the connection to the kernel and hope for the best
637 }
638 else
639 {
Jim Inghamacff8952013-05-02 00:27:30 +0000640 // If we are going to keep the target stopped, then don't send the disconnect message.
641 if (!keep_stopped && m_comm.IsConnected())
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000642 {
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000643 const bool success = m_comm.SendRequestDisconnect();
Greg Clayton97d5cf02012-09-25 02:40:06 +0000644 if (log)
645 {
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000646 if (success)
647 log->PutCString ("ProcessKDP::DoDetach() detach packet sent successfully");
Greg Clayton97d5cf02012-09-25 02:40:06 +0000648 else
Jim Ingham77e82d12013-05-09 00:05:35 +0000649 log->PutCString ("ProcessKDP::DoDetach() connection channel shutdown failed");
Greg Clayton97d5cf02012-09-25 02:40:06 +0000650 }
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000651 m_comm.Disconnect ();
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000652 }
Greg Claytonf9765ac2011-07-15 03:27:12 +0000653 }
Greg Clayton97d5cf02012-09-25 02:40:06 +0000654 StopAsyncThread ();
Greg Clayton74d41932012-01-31 04:56:17 +0000655 m_comm.Clear();
Greg Claytonf9765ac2011-07-15 03:27:12 +0000656
657 SetPrivateState (eStateDetached);
658 ResumePrivateStateThread();
659
660 //KillDebugserverProcess ();
661 return error;
662}
663
664Error
665ProcessKDP::DoDestroy ()
666{
Greg Clayton7925fbb2012-09-21 16:31:20 +0000667 // For KDP there really is no difference between destroy and detach
Jim Inghamacff8952013-05-02 00:27:30 +0000668 bool keep_stopped = false;
669 return DoDetach(keep_stopped);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000670}
671
672//------------------------------------------------------------------
673// Process Queries
674//------------------------------------------------------------------
675
676bool
677ProcessKDP::IsAlive ()
678{
679 return m_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
680}
681
682//------------------------------------------------------------------
683// Process Memory
684//------------------------------------------------------------------
685size_t
686ProcessKDP::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
687{
Jason Molenda8eb32812014-05-21 23:44:02 +0000688 uint8_t *data_buffer = (uint8_t *) buf;
Greg Claytona63d08c2011-07-19 03:57:15 +0000689 if (m_comm.IsConnected())
Jason Molenda8eb32812014-05-21 23:44:02 +0000690 {
691 const size_t max_read_size = 512;
692 size_t total_bytes_read = 0;
693
694 // Read the requested amount of memory in 512 byte chunks
695 while (total_bytes_read < size)
696 {
697 size_t bytes_to_read_this_request = size - total_bytes_read;
698 if (bytes_to_read_this_request > max_read_size)
699 {
700 bytes_to_read_this_request = max_read_size;
701 }
702 size_t bytes_read = m_comm.SendRequestReadMemory (addr + total_bytes_read,
703 data_buffer + total_bytes_read,
704 bytes_to_read_this_request, error);
705 total_bytes_read += bytes_read;
706 if (error.Fail() || bytes_read == 0)
707 {
708 return total_bytes_read;
709 }
710 }
711
712 return total_bytes_read;
713 }
Greg Claytona63d08c2011-07-19 03:57:15 +0000714 error.SetErrorString ("not connected");
Greg Claytonf9765ac2011-07-15 03:27:12 +0000715 return 0;
716}
717
718size_t
719ProcessKDP::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
720{
Greg Clayton7925fbb2012-09-21 16:31:20 +0000721 if (m_comm.IsConnected())
722 return m_comm.SendRequestWriteMemory (addr, buf, size, error);
723 error.SetErrorString ("not connected");
Greg Claytonf9765ac2011-07-15 03:27:12 +0000724 return 0;
725}
726
727lldb::addr_t
728ProcessKDP::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
729{
730 error.SetErrorString ("memory allocation not suppported in kdp remote debugging");
731 return LLDB_INVALID_ADDRESS;
732}
733
734Error
735ProcessKDP::DoDeallocateMemory (lldb::addr_t addr)
736{
737 Error error;
738 error.SetErrorString ("memory deallocation not suppported in kdp remote debugging");
739 return error;
740}
741
742Error
Jim Ingham299c0c12013-02-15 02:06:30 +0000743ProcessKDP::EnableBreakpointSite (BreakpointSite *bp_site)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000744{
Greg Clayton07e66e32011-07-20 03:41:06 +0000745 if (m_comm.LocalBreakpointsAreSupported ())
746 {
747 Error error;
Greg Clayton5b882162011-07-21 01:12:01 +0000748 if (!bp_site->IsEnabled())
749 {
750 if (m_comm.SendRequestBreakpoint(true, bp_site->GetLoadAddress()))
751 {
752 bp_site->SetEnabled(true);
753 bp_site->SetType (BreakpointSite::eExternal);
754 }
755 else
756 {
757 error.SetErrorString ("KDP set breakpoint failed");
758 }
759 }
Greg Clayton07e66e32011-07-20 03:41:06 +0000760 return error;
761 }
Greg Claytonf9765ac2011-07-15 03:27:12 +0000762 return EnableSoftwareBreakpoint (bp_site);
763}
764
765Error
Jim Ingham299c0c12013-02-15 02:06:30 +0000766ProcessKDP::DisableBreakpointSite (BreakpointSite *bp_site)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000767{
Greg Clayton07e66e32011-07-20 03:41:06 +0000768 if (m_comm.LocalBreakpointsAreSupported ())
769 {
770 Error error;
Greg Clayton5b882162011-07-21 01:12:01 +0000771 if (bp_site->IsEnabled())
772 {
773 BreakpointSite::Type bp_type = bp_site->GetType();
774 if (bp_type == BreakpointSite::eExternal)
775 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000776 if (m_destroy_in_process && m_comm.IsRunning())
777 {
778 // We are trying to destroy our connection and we are running
Greg Clayton5b882162011-07-21 01:12:01 +0000779 bp_site->SetEnabled(false);
Greg Clayton97d5cf02012-09-25 02:40:06 +0000780 }
Greg Clayton5b882162011-07-21 01:12:01 +0000781 else
Greg Clayton97d5cf02012-09-25 02:40:06 +0000782 {
783 if (m_comm.SendRequestBreakpoint(false, bp_site->GetLoadAddress()))
784 bp_site->SetEnabled(false);
785 else
786 error.SetErrorString ("KDP remove breakpoint failed");
787 }
Greg Clayton5b882162011-07-21 01:12:01 +0000788 }
789 else
790 {
791 error = DisableSoftwareBreakpoint (bp_site);
792 }
793 }
Greg Clayton07e66e32011-07-20 03:41:06 +0000794 return error;
795 }
Greg Claytonf9765ac2011-07-15 03:27:12 +0000796 return DisableSoftwareBreakpoint (bp_site);
797}
798
799Error
Jim Ingham1b5792e2012-12-18 02:03:49 +0000800ProcessKDP::EnableWatchpoint (Watchpoint *wp, bool notify)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000801{
802 Error error;
803 error.SetErrorString ("watchpoints are not suppported in kdp remote debugging");
804 return error;
805}
806
807Error
Jim Ingham1b5792e2012-12-18 02:03:49 +0000808ProcessKDP::DisableWatchpoint (Watchpoint *wp, bool notify)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000809{
810 Error error;
811 error.SetErrorString ("watchpoints are not suppported in kdp remote debugging");
812 return error;
813}
814
815void
816ProcessKDP::Clear()
817{
Greg Claytonf9765ac2011-07-15 03:27:12 +0000818 m_thread_list.Clear();
819}
820
821Error
822ProcessKDP::DoSignal (int signo)
823{
824 Error error;
825 error.SetErrorString ("sending signals is not suppported in kdp remote debugging");
826 return error;
827}
828
829void
830ProcessKDP::Initialize()
831{
832 static bool g_initialized = false;
833
834 if (g_initialized == false)
835 {
836 g_initialized = true;
837 PluginManager::RegisterPlugin (GetPluginNameStatic(),
838 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +0000839 CreateInstance,
840 DebuggerInitialize);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000841
842 Log::Callbacks log_callbacks = {
843 ProcessKDPLog::DisableLog,
844 ProcessKDPLog::EnableLog,
845 ProcessKDPLog::ListLogCategories
846 };
847
848 Log::RegisterLogChannel (ProcessKDP::GetPluginNameStatic(), log_callbacks);
849 }
850}
851
Greg Clayton7f982402013-07-15 22:54:20 +0000852void
853ProcessKDP::DebuggerInitialize (lldb_private::Debugger &debugger)
854{
855 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
856 {
857 const bool is_global_setting = true;
858 PluginManager::CreateSettingForProcessPlugin (debugger,
859 GetGlobalPluginProperties()->GetValueProperties(),
860 ConstString ("Properties for the kdp-remote process plug-in."),
861 is_global_setting);
862 }
863}
864
Greg Claytonf9765ac2011-07-15 03:27:12 +0000865bool
866ProcessKDP::StartAsyncThread ()
867{
Greg Clayton5160ce52013-03-27 23:08:40 +0000868 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
Greg Claytonf9765ac2011-07-15 03:27:12 +0000869
870 if (log)
Greg Clayton7925fbb2012-09-21 16:31:20 +0000871 log->Printf ("ProcessKDP::StartAsyncThread ()");
Zachary Turner39de3112014-09-09 20:54:56 +0000872
Zachary Turneracee96a2014-09-23 18:32:09 +0000873 if (m_async_thread.IsJoinable())
Greg Clayton7925fbb2012-09-21 16:31:20 +0000874 return true;
875
Zachary Turner39de3112014-09-09 20:54:56 +0000876 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.kdp-remote.async>", ProcessKDP::AsyncThread, this, NULL);
Zachary Turneracee96a2014-09-23 18:32:09 +0000877 return m_async_thread.IsJoinable();
Greg Claytonf9765ac2011-07-15 03:27:12 +0000878}
879
880void
881ProcessKDP::StopAsyncThread ()
882{
Greg Clayton5160ce52013-03-27 23:08:40 +0000883 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
Greg Claytonf9765ac2011-07-15 03:27:12 +0000884
885 if (log)
Greg Clayton7925fbb2012-09-21 16:31:20 +0000886 log->Printf ("ProcessKDP::StopAsyncThread ()");
Greg Claytonf9765ac2011-07-15 03:27:12 +0000887
888 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
889
890 // Stop the stdio thread
Zachary Turneracee96a2014-09-23 18:32:09 +0000891 if (m_async_thread.IsJoinable())
Zachary Turner39de3112014-09-09 20:54:56 +0000892 m_async_thread.Join(nullptr);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000893}
894
895
896void *
897ProcessKDP::AsyncThread (void *arg)
898{
899 ProcessKDP *process = (ProcessKDP*) arg;
900
Greg Clayton7925fbb2012-09-21 16:31:20 +0000901 const lldb::pid_t pid = process->GetID();
902
Greg Clayton5160ce52013-03-27 23:08:40 +0000903 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_PROCESS));
Greg Claytonf9765ac2011-07-15 03:27:12 +0000904 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000905 log->Printf ("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64 ") thread starting...", arg, pid);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000906
907 Listener listener ("ProcessKDP::AsyncThread");
908 EventSP event_sp;
909 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
910 eBroadcastBitAsyncThreadShouldExit;
911
Greg Clayton7925fbb2012-09-21 16:31:20 +0000912
Greg Claytonf9765ac2011-07-15 03:27:12 +0000913 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
914 {
Greg Claytonf9765ac2011-07-15 03:27:12 +0000915 bool done = false;
916 while (!done)
917 {
918 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000919 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...",
Greg Clayton7925fbb2012-09-21 16:31:20 +0000920 pid);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000921 if (listener.WaitForEvent (NULL, event_sp))
922 {
Greg Clayton7925fbb2012-09-21 16:31:20 +0000923 uint32_t event_type = event_sp->GetType();
924 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000925 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") Got an event of type: %d...",
Greg Clayton7925fbb2012-09-21 16:31:20 +0000926 pid,
927 event_type);
928
929 // When we are running, poll for 1 second to try and get an exception
930 // to indicate the process has stopped. If we don't get one, check to
931 // make sure no one asked us to exit
932 bool is_running = false;
933 DataExtractor exc_reply_packet;
934 do
Greg Claytonf9765ac2011-07-15 03:27:12 +0000935 {
Greg Claytonf9765ac2011-07-15 03:27:12 +0000936 switch (event_type)
937 {
Greg Clayton7925fbb2012-09-21 16:31:20 +0000938 case eBroadcastBitAsyncContinue:
Greg Claytonf9765ac2011-07-15 03:27:12 +0000939 {
Greg Clayton7925fbb2012-09-21 16:31:20 +0000940 is_running = true;
941 if (process->m_comm.WaitForPacketWithTimeoutMicroSeconds (exc_reply_packet, 1 * USEC_PER_SEC))
Greg Claytonf9765ac2011-07-15 03:27:12 +0000942 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000943 ThreadSP thread_sp (process->GetKernelThread());
Greg Clayton1afa68e2013-04-02 20:32:37 +0000944 if (thread_sp)
945 {
946 lldb::RegisterContextSP reg_ctx_sp (thread_sp->GetRegisterContext());
947 if (reg_ctx_sp)
948 reg_ctx_sp->InvalidateAllRegisters();
949 static_cast<ThreadKDP *>(thread_sp.get())->SetStopInfoFrom_KDP_EXCEPTION (exc_reply_packet);
950 }
Greg Clayton97d5cf02012-09-25 02:40:06 +0000951
Greg Clayton7925fbb2012-09-21 16:31:20 +0000952 // TODO: parse the stop reply packet
Greg Clayton97d5cf02012-09-25 02:40:06 +0000953 is_running = false;
Greg Clayton7925fbb2012-09-21 16:31:20 +0000954 process->SetPrivateState(eStateStopped);
955 }
956 else
957 {
958 // Check to see if we are supposed to exit. There is no way to
959 // interrupt a running kernel, so all we can do is wait for an
960 // exception or detach...
961 if (listener.GetNextEvent(event_sp))
962 {
963 // We got an event, go through the loop again
964 event_type = event_sp->GetType();
965 }
Greg Claytonf9765ac2011-07-15 03:27:12 +0000966 }
967 }
Greg Clayton7925fbb2012-09-21 16:31:20 +0000968 break;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000969
Greg Clayton7925fbb2012-09-21 16:31:20 +0000970 case eBroadcastBitAsyncThreadShouldExit:
971 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000972 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...",
Greg Clayton7925fbb2012-09-21 16:31:20 +0000973 pid);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000974 done = true;
Greg Clayton7925fbb2012-09-21 16:31:20 +0000975 is_running = false;
976 break;
977
978 default:
979 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000980 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") got unknown event 0x%8.8x",
Greg Clayton7925fbb2012-09-21 16:31:20 +0000981 pid,
982 event_type);
983 done = true;
984 is_running = false;
985 break;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000986 }
Greg Clayton7925fbb2012-09-21 16:31:20 +0000987 } while (is_running);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000988 }
989 else
990 {
991 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000992 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false",
Greg Clayton7925fbb2012-09-21 16:31:20 +0000993 pid);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000994 done = true;
995 }
996 }
997 }
998
999 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001000 log->Printf ("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64 ") thread exiting...",
Greg Clayton7925fbb2012-09-21 16:31:20 +00001001 arg,
1002 pid);
Zachary Turner39de3112014-09-09 20:54:56 +00001003
1004 process->m_async_thread.Reset();
Greg Claytonf9765ac2011-07-15 03:27:12 +00001005 return NULL;
1006}
1007
1008
Greg Clayton1d19a2f2012-10-19 22:22:57 +00001009class CommandObjectProcessKDPPacketSend : public CommandObjectParsed
1010{
1011private:
1012
1013 OptionGroupOptions m_option_group;
1014 OptionGroupUInt64 m_command_byte;
1015 OptionGroupString m_packet_data;
1016
1017 virtual Options *
1018 GetOptions ()
1019 {
1020 return &m_option_group;
1021 }
1022
1023
1024public:
1025 CommandObjectProcessKDPPacketSend(CommandInterpreter &interpreter) :
1026 CommandObjectParsed (interpreter,
1027 "process plugin packet send",
1028 "Send a custom packet through the KDP protocol by specifying the command byte and the packet payload data. A packet will be sent with a correct header and payload, and the raw result bytes will be displayed as a string value. ",
1029 NULL),
1030 m_option_group (interpreter),
1031 m_command_byte(LLDB_OPT_SET_1, true , "command", 'c', 0, eArgTypeNone, "Specify the command byte to use when sending the KDP request packet.", 0),
1032 m_packet_data (LLDB_OPT_SET_1, false, "payload", 'p', 0, eArgTypeNone, "Specify packet payload bytes as a hex ASCII string with no spaces or hex prefixes.", NULL)
1033 {
1034 m_option_group.Append (&m_command_byte, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
1035 m_option_group.Append (&m_packet_data , LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
1036 m_option_group.Finalize();
1037 }
1038
1039 ~CommandObjectProcessKDPPacketSend ()
1040 {
1041 }
1042
1043 bool
1044 DoExecute (Args& command, CommandReturnObject &result)
1045 {
1046 const size_t argc = command.GetArgumentCount();
1047 if (argc == 0)
1048 {
1049 if (!m_command_byte.GetOptionValue().OptionWasSet())
1050 {
1051 result.AppendError ("the --command option must be set to a valid command byte");
1052 result.SetStatus (eReturnStatusFailed);
1053 }
1054 else
1055 {
1056 const uint64_t command_byte = m_command_byte.GetOptionValue().GetUInt64Value(0);
1057 if (command_byte > 0 && command_byte <= UINT8_MAX)
1058 {
1059 ProcessKDP *process = (ProcessKDP *)m_interpreter.GetExecutionContext().GetProcessPtr();
1060 if (process)
1061 {
1062 const StateType state = process->GetState();
1063
1064 if (StateIsStoppedState (state, true))
1065 {
1066 std::vector<uint8_t> payload_bytes;
1067 const char *ascii_hex_bytes_cstr = m_packet_data.GetOptionValue().GetCurrentValue();
1068 if (ascii_hex_bytes_cstr && ascii_hex_bytes_cstr[0])
1069 {
1070 StringExtractor extractor(ascii_hex_bytes_cstr);
1071 const size_t ascii_hex_bytes_cstr_len = extractor.GetStringRef().size();
1072 if (ascii_hex_bytes_cstr_len & 1)
1073 {
1074 result.AppendErrorWithFormat ("payload data must contain an even number of ASCII hex characters: '%s'", ascii_hex_bytes_cstr);
1075 result.SetStatus (eReturnStatusFailed);
1076 return false;
1077 }
1078 payload_bytes.resize(ascii_hex_bytes_cstr_len/2);
1079 if (extractor.GetHexBytes(&payload_bytes[0], payload_bytes.size(), '\xdd') != payload_bytes.size())
1080 {
1081 result.AppendErrorWithFormat ("payload data must only contain ASCII hex characters (no spaces or hex prefixes): '%s'", ascii_hex_bytes_cstr);
1082 result.SetStatus (eReturnStatusFailed);
1083 return false;
1084 }
1085 }
1086 Error error;
1087 DataExtractor reply;
1088 process->GetCommunication().SendRawRequest (command_byte,
1089 payload_bytes.empty() ? NULL : payload_bytes.data(),
1090 payload_bytes.size(),
1091 reply,
1092 error);
1093
1094 if (error.Success())
1095 {
1096 // Copy the binary bytes into a hex ASCII string for the result
1097 StreamString packet;
1098 packet.PutBytesAsRawHex8(reply.GetDataStart(),
1099 reply.GetByteSize(),
1100 lldb::endian::InlHostByteOrder(),
1101 lldb::endian::InlHostByteOrder());
1102 result.AppendMessage(packet.GetString().c_str());
1103 result.SetStatus (eReturnStatusSuccessFinishResult);
1104 return true;
1105 }
1106 else
1107 {
1108 const char *error_cstr = error.AsCString();
1109 if (error_cstr && error_cstr[0])
1110 result.AppendError (error_cstr);
1111 else
1112 result.AppendErrorWithFormat ("unknown error 0x%8.8x", error.GetError());
1113 result.SetStatus (eReturnStatusFailed);
1114 return false;
1115 }
1116 }
1117 else
1118 {
1119 result.AppendErrorWithFormat ("process must be stopped in order to send KDP packets, state is %s", StateAsCString (state));
1120 result.SetStatus (eReturnStatusFailed);
1121 }
1122 }
1123 else
1124 {
1125 result.AppendError ("invalid process");
1126 result.SetStatus (eReturnStatusFailed);
1127 }
1128 }
1129 else
1130 {
Daniel Malead01b2952012-11-29 21:49:15 +00001131 result.AppendErrorWithFormat ("invalid command byte 0x%" PRIx64 ", valid values are 1 - 255", command_byte);
Greg Clayton1d19a2f2012-10-19 22:22:57 +00001132 result.SetStatus (eReturnStatusFailed);
1133 }
1134 }
1135 }
1136 else
1137 {
1138 result.AppendErrorWithFormat ("'%s' takes no arguments, only options.", m_cmd_name.c_str());
1139 result.SetStatus (eReturnStatusFailed);
1140 }
1141 return false;
1142 }
1143};
1144
1145class CommandObjectProcessKDPPacket : public CommandObjectMultiword
1146{
1147private:
1148
1149public:
1150 CommandObjectProcessKDPPacket(CommandInterpreter &interpreter) :
1151 CommandObjectMultiword (interpreter,
1152 "process plugin packet",
1153 "Commands that deal with KDP remote packets.",
1154 NULL)
1155 {
1156 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessKDPPacketSend (interpreter)));
1157 }
1158
1159 ~CommandObjectProcessKDPPacket ()
1160 {
1161 }
1162};
1163
1164class CommandObjectMultiwordProcessKDP : public CommandObjectMultiword
1165{
1166public:
1167 CommandObjectMultiwordProcessKDP (CommandInterpreter &interpreter) :
1168 CommandObjectMultiword (interpreter,
1169 "process plugin",
1170 "A set of commands for operating on a ProcessKDP process.",
1171 "process plugin <subcommand> [<subcommand-options>]")
1172 {
1173 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessKDPPacket (interpreter)));
1174 }
1175
1176 ~CommandObjectMultiwordProcessKDP ()
1177 {
1178 }
1179};
1180
1181CommandObject *
1182ProcessKDP::GetPluginCommandObject()
1183{
1184 if (!m_command_sp)
1185 m_command_sp.reset (new CommandObjectMultiwordProcessKDP (GetTarget().GetDebugger().GetCommandInterpreter()));
1186 return m_command_sp.get();
1187}
1188