blob: fd82817fd120475a260495e54abc621834f37fcf [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"
Ilia K41204d02015-03-04 12:05:24 +000033#include "lldb/Interpreter/OptionValueProperties.h"
Greg Clayton1f746072012-08-29 21:13:06 +000034#include "lldb/Symbol/ObjectFile.h"
Greg Clayton7925fbb2012-09-21 16:31:20 +000035#include "lldb/Target/RegisterContext.h"
Greg Clayton57508022011-07-15 16:31:38 +000036#include "lldb/Target/Target.h"
Greg Claytona63d08c2011-07-19 03:57:15 +000037#include "lldb/Target/Thread.h"
Greg Claytonf9765ac2011-07-15 03:27:12 +000038
Charles Davis510938e2013-08-27 05:04:57 +000039#define USEC_PER_SEC 1000000
40
Greg Claytonf9765ac2011-07-15 03:27:12 +000041// Project includes
42#include "ProcessKDP.h"
43#include "ProcessKDPLog.h"
Greg Claytona63d08c2011-07-19 03:57:15 +000044#include "ThreadKDP.h"
Jason Molenda5e8534e2012-10-03 01:29:34 +000045#include "Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.h"
Jason Molenda840f12c2012-10-25 00:25:13 +000046#include "Plugins/DynamicLoader/Static/DynamicLoaderStatic.h"
Greg Clayton1d19a2f2012-10-19 22:22:57 +000047#include "Utility/StringExtractor.h"
Greg Claytonf9765ac2011-07-15 03:27:12 +000048
49using namespace lldb;
50using namespace lldb_private;
51
Greg Clayton7f982402013-07-15 22:54:20 +000052namespace {
53
54 static PropertyDefinition
55 g_properties[] =
56 {
57 { "packet-timeout" , OptionValue::eTypeUInt64 , true , 5, NULL, NULL, "Specify the default packet timeout in seconds." },
58 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
59 };
60
61 enum
62 {
63 ePropertyPacketTimeout
64 };
65
66 class PluginProperties : public Properties
67 {
68 public:
69
70 static ConstString
71 GetSettingName ()
72 {
73 return ProcessKDP::GetPluginNameStatic();
74 }
75
76 PluginProperties() :
77 Properties ()
78 {
79 m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
80 m_collection_sp->Initialize(g_properties);
81 }
82
83 virtual
84 ~PluginProperties()
85 {
86 }
87
88 uint64_t
89 GetPacketTimeout()
90 {
91 const uint32_t idx = ePropertyPacketTimeout;
92 return m_collection_sp->GetPropertyAtIndexAsUInt64(NULL, idx, g_properties[idx].default_uint_value);
93 }
94 };
95
96 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
97
98 static const ProcessKDPPropertiesSP &
99 GetGlobalPluginProperties()
100 {
101 static ProcessKDPPropertiesSP g_settings_sp;
102 if (!g_settings_sp)
103 g_settings_sp.reset (new PluginProperties ());
104 return g_settings_sp;
105 }
106
107} // anonymous namespace end
108
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000109static const lldb::tid_t g_kernel_tid = 1;
110
Greg Clayton57abc5d2013-05-10 21:47:16 +0000111ConstString
Greg Claytonf9765ac2011-07-15 03:27:12 +0000112ProcessKDP::GetPluginNameStatic()
113{
Greg Clayton57abc5d2013-05-10 21:47:16 +0000114 static ConstString g_name("kdp-remote");
115 return g_name;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000116}
117
118const char *
119ProcessKDP::GetPluginDescriptionStatic()
120{
121 return "KDP Remote protocol based debugging plug-in for darwin kernel debugging.";
122}
123
124void
125ProcessKDP::Terminate()
126{
127 PluginManager::UnregisterPlugin (ProcessKDP::CreateInstance);
128}
129
130
Greg Claytonc3776bf2012-02-09 06:16:32 +0000131lldb::ProcessSP
132ProcessKDP::CreateInstance (Target &target,
133 Listener &listener,
134 const FileSpec *crash_file_path)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000135{
Greg Claytonc3776bf2012-02-09 06:16:32 +0000136 lldb::ProcessSP process_sp;
137 if (crash_file_path == NULL)
138 process_sp.reset(new ProcessKDP (target, listener));
139 return process_sp;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000140}
141
142bool
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000143ProcessKDP::CanDebug(Target &target, bool plugin_specified_by_name)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000144{
Greg Clayton596ed242011-10-21 21:41:45 +0000145 if (plugin_specified_by_name)
146 return true;
147
Greg Claytonf9765ac2011-07-15 03:27:12 +0000148 // For now we are just making sure the file exists for a given module
Greg Claytonaa149cb2011-08-11 02:48:45 +0000149 Module *exe_module = target.GetExecutableModulePointer();
150 if (exe_module)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000151 {
152 const llvm::Triple &triple_ref = target.GetArchitecture().GetTriple();
Greg Clayton70512312012-05-08 01:45:38 +0000153 switch (triple_ref.getOS())
Greg Claytonf9765ac2011-07-15 03:27:12 +0000154 {
Greg Clayton70512312012-05-08 01:45:38 +0000155 case llvm::Triple::Darwin: // Should use "macosx" for desktop and "ios" for iOS, but accept darwin just in case
156 case llvm::Triple::MacOSX: // For desktop targets
157 case llvm::Triple::IOS: // For arm targets
158 if (triple_ref.getVendor() == llvm::Triple::Apple)
159 {
160 ObjectFile *exe_objfile = exe_module->GetObjectFile();
161 if (exe_objfile->GetType() == ObjectFile::eTypeExecutable &&
162 exe_objfile->GetStrata() == ObjectFile::eStrataKernel)
163 return true;
164 }
165 break;
166
167 default:
168 break;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000169 }
170 }
Greg Clayton596ed242011-10-21 21:41:45 +0000171 return false;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000172}
173
174//----------------------------------------------------------------------
175// ProcessKDP constructor
176//----------------------------------------------------------------------
177ProcessKDP::ProcessKDP(Target& target, Listener &listener) :
178 Process (target, listener),
179 m_comm("lldb.process.kdp-remote.communication"),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000180 m_async_broadcaster (NULL, "lldb.process.kdp-remote.async-broadcaster"),
Jason Molenda5e8534e2012-10-03 01:29:34 +0000181 m_dyld_plugin_name (),
Greg Clayton1d19a2f2012-10-19 22:22:57 +0000182 m_kernel_load_addr (LLDB_INVALID_ADDRESS),
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000183 m_command_sp(),
184 m_kernel_thread_wp()
Greg Claytonf9765ac2011-07-15 03:27:12 +0000185{
Greg Clayton7925fbb2012-09-21 16:31:20 +0000186 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
187 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Greg Clayton7f982402013-07-15 22:54:20 +0000188 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
189 if (timeout_seconds > 0)
190 m_comm.SetPacketTimeout(timeout_seconds);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000191}
192
193//----------------------------------------------------------------------
194// Destructor
195//----------------------------------------------------------------------
196ProcessKDP::~ProcessKDP()
197{
198 Clear();
Greg Claytone24c4ac2011-11-17 04:46:02 +0000199 // We need to call finalize on the process before destroying ourselves
200 // to make sure all of the broadcaster cleanup goes as planned. If we
201 // destruct this class, then Process::~Process() might have problems
202 // trying to fully destroy the broadcaster.
203 Finalize();
Greg Claytonf9765ac2011-07-15 03:27:12 +0000204}
205
206//----------------------------------------------------------------------
207// PluginInterface
208//----------------------------------------------------------------------
Greg Clayton57abc5d2013-05-10 21:47:16 +0000209lldb_private::ConstString
Greg Claytonf9765ac2011-07-15 03:27:12 +0000210ProcessKDP::GetPluginName()
211{
Greg Claytonf9765ac2011-07-15 03:27:12 +0000212 return GetPluginNameStatic();
213}
214
215uint32_t
216ProcessKDP::GetPluginVersion()
217{
218 return 1;
219}
220
221Error
222ProcessKDP::WillLaunch (Module* module)
223{
224 Error error;
225 error.SetErrorString ("launching not supported in kdp-remote plug-in");
226 return error;
227}
228
229Error
230ProcessKDP::WillAttachToProcessWithID (lldb::pid_t pid)
231{
232 Error error;
233 error.SetErrorString ("attaching to a by process ID not supported in kdp-remote plug-in");
234 return error;
235}
236
237Error
238ProcessKDP::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
239{
240 Error error;
241 error.SetErrorString ("attaching to a by process name not supported in kdp-remote plug-in");
242 return error;
243}
244
245Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000246ProcessKDP::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000247{
Greg Claytonf9765ac2011-07-15 03:27:12 +0000248 Error error;
Greg Clayton7925fbb2012-09-21 16:31:20 +0000249
250 // Don't let any JIT happen when doing KDP as we can't allocate
251 // memory and we don't want to be mucking with threads that might
252 // already be handling exceptions
253 SetCanJIT(false);
254
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000255 if (remote_url == NULL || remote_url[0] == '\0')
Greg Clayton7925fbb2012-09-21 16:31:20 +0000256 {
257 error.SetErrorStringWithFormat ("invalid connection URL '%s'", remote_url);
258 return error;
259 }
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000260
Greg Clayton7b0992d2013-04-18 22:45:39 +0000261 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000262 if (conn_ap.get())
263 {
264 // Only try once for now.
265 // TODO: check if we should be retrying?
266 const uint32_t max_retry_count = 1;
267 for (uint32_t retry_count = 0; retry_count < max_retry_count; ++retry_count)
268 {
269 if (conn_ap->Connect(remote_url, &error) == eConnectionStatusSuccess)
270 break;
271 usleep (100000);
272 }
273 }
274
275 if (conn_ap->IsConnected())
276 {
Keno Fischer3d7162b2014-08-06 21:18:13 +0000277 const Socket& socket = static_cast<const Socket&>(*conn_ap->GetReadObject());
Vince Harron014bb7d2015-01-16 00:47:08 +0000278 const uint16_t reply_port = socket.GetLocalPortNumber();
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000279
280 if (reply_port != 0)
281 {
282 m_comm.SetConnection(conn_ap.release());
283
284 if (m_comm.SendRequestReattach(reply_port))
285 {
286 if (m_comm.SendRequestConnect(reply_port, reply_port, "Greetings from LLDB..."))
287 {
288 m_comm.GetVersion();
289 uint32_t cpu = m_comm.GetCPUType();
290 uint32_t sub = m_comm.GetCPUSubtype();
291 ArchSpec kernel_arch;
292 kernel_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
293 m_target.SetArchitecture(kernel_arch);
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000294
Jason Molenda840f12c2012-10-25 00:25:13 +0000295 /* Get the kernel's UUID and load address via KDP_KERNELVERSION packet. */
296 /* An EFI kdp session has neither UUID nor load address. */
297
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000298 UUID kernel_uuid = m_comm.GetUUID ();
299 addr_t kernel_load_addr = m_comm.GetLoadAddress ();
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000300
Jason Molenda840f12c2012-10-25 00:25:13 +0000301 if (m_comm.RemoteIsEFI ())
302 {
Greg Claytona1bce2e2014-07-16 21:16:27 +0000303 // Select an invalid plugin name for the dynamic loader so one doesn't get used
304 // since EFI does its own manual loading via python scripting
305 static ConstString g_none_dynamic_loader("none");
306 m_dyld_plugin_name = g_none_dynamic_loader;
307
308 if (kernel_uuid.IsValid()) {
309 // If EFI passed in a UUID= try to lookup UUID
310 // The slide will not be provided. But the UUID
311 // lookup will be used to launch EFI debug scripts
312 // from the dSYM, that can load all of the symbols.
313 ModuleSpec module_spec;
314 module_spec.GetUUID() = kernel_uuid;
315 module_spec.GetArchitecture() = m_target.GetArchitecture();
316
317 // Lookup UUID locally, before attempting dsymForUUID like action
318 module_spec.GetSymbolFileSpec() = Symbols::LocateExecutableSymbolFile(module_spec);
319 if (module_spec.GetSymbolFileSpec())
320 module_spec.GetFileSpec() = Symbols::LocateExecutableObjectFile (module_spec);
321 if (!module_spec.GetSymbolFileSpec() || !module_spec.GetSymbolFileSpec())
322 Symbols::DownloadObjectAndSymbolFile (module_spec, true);
323
324 if (module_spec.GetFileSpec().Exists())
325 {
326 ModuleSP module_sp(new Module (module_spec.GetFileSpec(), m_target.GetArchitecture()));
327 if (module_sp.get() && module_sp->MatchesModuleSpec (module_spec))
328 {
329 // Get the current target executable
330 ModuleSP exe_module_sp (m_target.GetExecutableModule ());
331
332 // Make sure you don't already have the right module loaded and they will be uniqued
333 if (exe_module_sp.get() != module_sp.get())
334 m_target.SetExecutableModule (module_sp, false);
335 }
336 }
337 }
Jason Molenda840f12c2012-10-25 00:25:13 +0000338 }
Jason Molendaca2ffa72013-05-09 23:52:21 +0000339 else if (m_comm.RemoteIsDarwinKernel ())
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000340 {
Jason Molendaca2ffa72013-05-09 23:52:21 +0000341 m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
Jason Molendaa8ea4ba2013-05-06 23:02:03 +0000342 if (kernel_load_addr != LLDB_INVALID_ADDRESS)
343 {
344 m_kernel_load_addr = kernel_load_addr;
345 }
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000346 }
347
Greg Clayton97d5cf02012-09-25 02:40:06 +0000348 // Set the thread ID
349 UpdateThreadListIfNeeded ();
Greg Claytona63d08c2011-07-19 03:57:15 +0000350 SetID (1);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000351 GetThreadList ();
Greg Claytona63d08c2011-07-19 03:57:15 +0000352 SetPrivateState (eStateStopped);
Greg Clayton07e66e32011-07-20 03:41:06 +0000353 StreamSP async_strm_sp(m_target.GetDebugger().GetAsyncOutputStream());
354 if (async_strm_sp)
355 {
Greg Clayton5b882162011-07-21 01:12:01 +0000356 const char *cstr;
357 if ((cstr = m_comm.GetKernelVersion ()) != NULL)
Greg Clayton07e66e32011-07-20 03:41:06 +0000358 {
Greg Clayton5b882162011-07-21 01:12:01 +0000359 async_strm_sp->Printf ("Version: %s\n", cstr);
Greg Clayton07e66e32011-07-20 03:41:06 +0000360 async_strm_sp->Flush();
361 }
Greg Clayton5b882162011-07-21 01:12:01 +0000362// if ((cstr = m_comm.GetImagePath ()) != NULL)
363// {
364// async_strm_sp->Printf ("Image Path: %s\n", cstr);
365// async_strm_sp->Flush();
366// }
Greg Clayton07e66e32011-07-20 03:41:06 +0000367 }
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000368 }
Greg Clayton97d5cf02012-09-25 02:40:06 +0000369 else
370 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000371 error.SetErrorString("KDP_REATTACH failed");
372 }
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000373 }
374 else
375 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000376 error.SetErrorString("KDP_REATTACH failed");
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000377 }
378 }
379 else
380 {
381 error.SetErrorString("invalid reply port from UDP connection");
382 }
383 }
384 else
385 {
386 if (error.Success())
387 error.SetErrorStringWithFormat ("failed to connect to '%s'", remote_url);
388 }
389 if (error.Fail())
390 m_comm.Disconnect();
391
Greg Claytonf9765ac2011-07-15 03:27:12 +0000392 return error;
393}
394
395//----------------------------------------------------------------------
396// Process Control
397//----------------------------------------------------------------------
398Error
Greg Clayton982c9762011-11-03 21:22:33 +0000399ProcessKDP::DoLaunch (Module *exe_module,
Jean-Daniel Dupas7782de92013-12-09 22:52:50 +0000400 ProcessLaunchInfo &launch_info)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000401{
402 Error error;
403 error.SetErrorString ("launching not supported in kdp-remote plug-in");
404 return error;
405}
406
407
408Error
409ProcessKDP::DoAttachToProcessWithID (lldb::pid_t attach_pid)
410{
411 Error error;
412 error.SetErrorString ("attach to process by ID is not suppported in kdp remote debugging");
413 return error;
414}
415
Greg Claytonf9765ac2011-07-15 03:27:12 +0000416Error
Han Ming Ong84647042012-02-25 01:07:38 +0000417ProcessKDP::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
418{
419 Error error;
420 error.SetErrorString ("attach to process by ID is not suppported in kdp remote debugging");
421 return error;
422}
423
424Error
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +0000425ProcessKDP::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000426{
427 Error error;
428 error.SetErrorString ("attach to process by name is not suppported in kdp remote debugging");
429 return error;
430}
431
432
433void
Jim Inghambb006ce2014-08-02 00:33:35 +0000434ProcessKDP::DidAttach (ArchSpec &process_arch)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000435{
Jim Inghambb006ce2014-08-02 00:33:35 +0000436 Process::DidAttach(process_arch);
437
Greg Clayton5160ce52013-03-27 23:08:40 +0000438 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_PROCESS));
Greg Claytonf9765ac2011-07-15 03:27:12 +0000439 if (log)
Johnny Chen54cb8f82011-10-11 21:17:10 +0000440 log->Printf ("ProcessKDP::DidAttach()");
Greg Claytonf9765ac2011-07-15 03:27:12 +0000441 if (GetID() != LLDB_INVALID_PROCESS_ID)
442 {
Greg Claytonc3eefa32014-10-31 00:06:52 +0000443 uint32_t cpu = m_comm.GetCPUType();
444 if (cpu)
445 {
446 uint32_t sub = m_comm.GetCPUSubtype();
447 process_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
448 }
Greg Claytonf9765ac2011-07-15 03:27:12 +0000449 }
450}
451
Jason Molenda5e8534e2012-10-03 01:29:34 +0000452addr_t
453ProcessKDP::GetImageInfoAddress()
454{
455 return m_kernel_load_addr;
456}
457
458lldb_private::DynamicLoader *
459ProcessKDP::GetDynamicLoader ()
460{
461 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +0000462 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 +0000463 return m_dyld_ap.get();
464}
465
Greg Claytonf9765ac2011-07-15 03:27:12 +0000466Error
467ProcessKDP::WillResume ()
468{
469 return Error();
470}
471
472Error
473ProcessKDP::DoResume ()
474{
475 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +0000476 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_PROCESS));
Greg Clayton7925fbb2012-09-21 16:31:20 +0000477 // Only start the async thread if we try to do any process control
Zachary Turneracee96a2014-09-23 18:32:09 +0000478 if (!m_async_thread.IsJoinable())
Zachary Turner39de3112014-09-09 20:54:56 +0000479 StartAsyncThread();
Greg Clayton7925fbb2012-09-21 16:31:20 +0000480
Greg Clayton97d5cf02012-09-25 02:40:06 +0000481 bool resume = false;
Greg Clayton7925fbb2012-09-21 16:31:20 +0000482
Greg Clayton97d5cf02012-09-25 02:40:06 +0000483 // With KDP there is only one thread we can tell what to do
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000484 ThreadSP kernel_thread_sp (m_thread_list.FindThreadByProtocolID(g_kernel_tid));
485
Greg Clayton97d5cf02012-09-25 02:40:06 +0000486 if (kernel_thread_sp)
Greg Clayton4b1b8b32012-09-21 01:55:30 +0000487 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000488 const StateType thread_resume_state = kernel_thread_sp->GetTemporaryResumeState();
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000489
490 if (log)
491 log->Printf ("ProcessKDP::DoResume() thread_resume_state = %s", StateAsCString(thread_resume_state));
Greg Clayton7925fbb2012-09-21 16:31:20 +0000492 switch (thread_resume_state)
Greg Clayton4b1b8b32012-09-21 01:55:30 +0000493 {
Greg Clayton7925fbb2012-09-21 16:31:20 +0000494 case eStateSuspended:
495 // Nothing to do here when a thread will stay suspended
496 // we just leave the CPU mask bit set to zero for the thread
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000497 if (log)
498 log->Printf ("ProcessKDP::DoResume() = suspended???");
Greg Clayton7925fbb2012-09-21 16:31:20 +0000499 break;
500
501 case eStateStepping:
Greg Clayton1afa68e2013-04-02 20:32:37 +0000502 {
503 lldb::RegisterContextSP reg_ctx_sp (kernel_thread_sp->GetRegisterContext());
504
505 if (reg_ctx_sp)
506 {
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000507 if (log)
508 log->Printf ("ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep (true);");
Greg Clayton1afa68e2013-04-02 20:32:37 +0000509 reg_ctx_sp->HardwareSingleStep (true);
510 resume = true;
511 }
512 else
513 {
514 error.SetErrorStringWithFormat("KDP thread 0x%llx has no register context", kernel_thread_sp->GetID());
515 }
516 }
Greg Clayton97d5cf02012-09-25 02:40:06 +0000517 break;
518
Greg Clayton7925fbb2012-09-21 16:31:20 +0000519 case eStateRunning:
Greg Clayton1afa68e2013-04-02 20:32:37 +0000520 {
521 lldb::RegisterContextSP reg_ctx_sp (kernel_thread_sp->GetRegisterContext());
522
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000523 if (reg_ctx_sp)
524 {
525 if (log)
526 log->Printf ("ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep (false);");
527 reg_ctx_sp->HardwareSingleStep (false);
528 resume = true;
529 }
530 else
531 {
532 error.SetErrorStringWithFormat("KDP thread 0x%llx has no register context", kernel_thread_sp->GetID());
533 }
Greg Clayton1afa68e2013-04-02 20:32:37 +0000534 }
Greg Clayton7925fbb2012-09-21 16:31:20 +0000535 break;
Greg Clayton97d5cf02012-09-25 02:40:06 +0000536
Greg Clayton7925fbb2012-09-21 16:31:20 +0000537 default:
Greg Clayton97d5cf02012-09-25 02:40:06 +0000538 // The only valid thread resume states are listed above
Greg Clayton7925fbb2012-09-21 16:31:20 +0000539 assert (!"invalid thread resume state");
540 break;
Greg Clayton4b1b8b32012-09-21 01:55:30 +0000541 }
542 }
Greg Clayton97d5cf02012-09-25 02:40:06 +0000543
544 if (resume)
Greg Clayton7925fbb2012-09-21 16:31:20 +0000545 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000546 if (log)
547 log->Printf ("ProcessKDP::DoResume () sending resume");
Greg Clayton7925fbb2012-09-21 16:31:20 +0000548
Greg Clayton97d5cf02012-09-25 02:40:06 +0000549 if (m_comm.SendRequestResume ())
Greg Clayton7925fbb2012-09-21 16:31:20 +0000550 {
551 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue);
552 SetPrivateState(eStateRunning);
553 }
554 else
555 error.SetErrorString ("KDP resume failed");
556 }
Greg Clayton4b1b8b32012-09-21 01:55:30 +0000557 else
Greg Clayton7925fbb2012-09-21 16:31:20 +0000558 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000559 error.SetErrorString ("kernel thread is suspended");
Greg Clayton7925fbb2012-09-21 16:31:20 +0000560 }
561
Greg Claytonf9765ac2011-07-15 03:27:12 +0000562 return error;
563}
564
Greg Clayton97d5cf02012-09-25 02:40:06 +0000565lldb::ThreadSP
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000566ProcessKDP::GetKernelThread()
Greg Clayton97d5cf02012-09-25 02:40:06 +0000567{
568 // KDP only tells us about one thread/core. Any other threads will usually
569 // be the ones that are read from memory by the OS plug-ins.
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000570
571 ThreadSP thread_sp (m_kernel_thread_wp.lock());
Greg Clayton97d5cf02012-09-25 02:40:06 +0000572 if (!thread_sp)
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000573 {
574 thread_sp.reset(new ThreadKDP (*this, g_kernel_tid));
575 m_kernel_thread_wp = thread_sp;
576 }
Greg Clayton97d5cf02012-09-25 02:40:06 +0000577 return thread_sp;
578}
579
580
581
582
Greg Clayton9fc13552012-04-10 00:18:59 +0000583bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000584ProcessKDP::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000585{
586 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +0000587 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_THREAD));
Greg Claytonf9765ac2011-07-15 03:27:12 +0000588 if (log && log->GetMask().Test(KDP_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +0000589 log->Printf ("ProcessKDP::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Claytonf9765ac2011-07-15 03:27:12 +0000590
Greg Clayton39da3ef2013-04-11 22:23:34 +0000591 // Even though there is a CPU mask, it doesn't mean we can see each CPU
Greg Clayton97d5cf02012-09-25 02:40:06 +0000592 // indivudually, there is really only one. Lets call this thread 1.
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000593 ThreadSP thread_sp (old_thread_list.FindThreadByProtocolID(g_kernel_tid, false));
594 if (!thread_sp)
595 thread_sp = GetKernelThread ();
596 new_thread_list.AddThread(thread_sp);
Greg Clayton97d5cf02012-09-25 02:40:06 +0000597
Greg Clayton9fc13552012-04-10 00:18:59 +0000598 return new_thread_list.GetSize(false) > 0;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000599}
600
Greg Claytonf9765ac2011-07-15 03:27:12 +0000601void
602ProcessKDP::RefreshStateAfterStop ()
603{
604 // Let all threads recover from stopping and do any clean up based
605 // on the previous thread state (if any).
606 m_thread_list.RefreshStateAfterStop();
Greg Claytonf9765ac2011-07-15 03:27:12 +0000607}
608
609Error
610ProcessKDP::DoHalt (bool &caused_stop)
611{
612 Error error;
613
Greg Clayton97d5cf02012-09-25 02:40:06 +0000614 if (m_comm.IsRunning())
Greg Claytonf9765ac2011-07-15 03:27:12 +0000615 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000616 if (m_destroy_in_process)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000617 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000618 // If we are attemping to destroy, we need to not return an error to
619 // Halt or DoDestroy won't get called.
620 // We are also currently running, so send a process stopped event
621 SetPrivateState (eStateStopped);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000622 }
Greg Clayton97d5cf02012-09-25 02:40:06 +0000623 else
Greg Claytonf9765ac2011-07-15 03:27:12 +0000624 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000625 error.SetErrorString ("KDP cannot interrupt a running kernel");
Greg Claytonf9765ac2011-07-15 03:27:12 +0000626 }
627 }
628 return error;
629}
630
631Error
Jim Inghamacff8952013-05-02 00:27:30 +0000632ProcessKDP::DoDetach(bool keep_stopped)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000633{
634 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +0000635 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
Greg Claytonf9765ac2011-07-15 03:27:12 +0000636 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +0000637 log->Printf ("ProcessKDP::DoDetach(keep_stopped = %i)", keep_stopped);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000638
Greg Clayton97d5cf02012-09-25 02:40:06 +0000639 if (m_comm.IsRunning())
Greg Claytonf9765ac2011-07-15 03:27:12 +0000640 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000641 // We are running and we can't interrupt a running kernel, so we need
642 // to just close the connection to the kernel and hope for the best
643 }
644 else
645 {
Jim Inghamacff8952013-05-02 00:27:30 +0000646 // If we are going to keep the target stopped, then don't send the disconnect message.
647 if (!keep_stopped && m_comm.IsConnected())
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000648 {
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000649 const bool success = m_comm.SendRequestDisconnect();
Greg Clayton97d5cf02012-09-25 02:40:06 +0000650 if (log)
651 {
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000652 if (success)
653 log->PutCString ("ProcessKDP::DoDetach() detach packet sent successfully");
Greg Clayton97d5cf02012-09-25 02:40:06 +0000654 else
Jim Ingham77e82d12013-05-09 00:05:35 +0000655 log->PutCString ("ProcessKDP::DoDetach() connection channel shutdown failed");
Greg Clayton97d5cf02012-09-25 02:40:06 +0000656 }
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000657 m_comm.Disconnect ();
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000658 }
Greg Claytonf9765ac2011-07-15 03:27:12 +0000659 }
Greg Clayton97d5cf02012-09-25 02:40:06 +0000660 StopAsyncThread ();
Greg Clayton74d41932012-01-31 04:56:17 +0000661 m_comm.Clear();
Greg Claytonf9765ac2011-07-15 03:27:12 +0000662
663 SetPrivateState (eStateDetached);
664 ResumePrivateStateThread();
665
666 //KillDebugserverProcess ();
667 return error;
668}
669
670Error
671ProcessKDP::DoDestroy ()
672{
Greg Clayton7925fbb2012-09-21 16:31:20 +0000673 // For KDP there really is no difference between destroy and detach
Jim Inghamacff8952013-05-02 00:27:30 +0000674 bool keep_stopped = false;
675 return DoDetach(keep_stopped);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000676}
677
678//------------------------------------------------------------------
679// Process Queries
680//------------------------------------------------------------------
681
682bool
683ProcessKDP::IsAlive ()
684{
685 return m_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
686}
687
688//------------------------------------------------------------------
689// Process Memory
690//------------------------------------------------------------------
691size_t
692ProcessKDP::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
693{
Jason Molenda8eb32812014-05-21 23:44:02 +0000694 uint8_t *data_buffer = (uint8_t *) buf;
Greg Claytona63d08c2011-07-19 03:57:15 +0000695 if (m_comm.IsConnected())
Jason Molenda8eb32812014-05-21 23:44:02 +0000696 {
697 const size_t max_read_size = 512;
698 size_t total_bytes_read = 0;
699
700 // Read the requested amount of memory in 512 byte chunks
701 while (total_bytes_read < size)
702 {
703 size_t bytes_to_read_this_request = size - total_bytes_read;
704 if (bytes_to_read_this_request > max_read_size)
705 {
706 bytes_to_read_this_request = max_read_size;
707 }
708 size_t bytes_read = m_comm.SendRequestReadMemory (addr + total_bytes_read,
709 data_buffer + total_bytes_read,
710 bytes_to_read_this_request, error);
711 total_bytes_read += bytes_read;
712 if (error.Fail() || bytes_read == 0)
713 {
714 return total_bytes_read;
715 }
716 }
717
718 return total_bytes_read;
719 }
Greg Claytona63d08c2011-07-19 03:57:15 +0000720 error.SetErrorString ("not connected");
Greg Claytonf9765ac2011-07-15 03:27:12 +0000721 return 0;
722}
723
724size_t
725ProcessKDP::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
726{
Greg Clayton7925fbb2012-09-21 16:31:20 +0000727 if (m_comm.IsConnected())
728 return m_comm.SendRequestWriteMemory (addr, buf, size, error);
729 error.SetErrorString ("not connected");
Greg Claytonf9765ac2011-07-15 03:27:12 +0000730 return 0;
731}
732
733lldb::addr_t
734ProcessKDP::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
735{
736 error.SetErrorString ("memory allocation not suppported in kdp remote debugging");
737 return LLDB_INVALID_ADDRESS;
738}
739
740Error
741ProcessKDP::DoDeallocateMemory (lldb::addr_t addr)
742{
743 Error error;
744 error.SetErrorString ("memory deallocation not suppported in kdp remote debugging");
745 return error;
746}
747
748Error
Jim Ingham299c0c12013-02-15 02:06:30 +0000749ProcessKDP::EnableBreakpointSite (BreakpointSite *bp_site)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000750{
Greg Clayton07e66e32011-07-20 03:41:06 +0000751 if (m_comm.LocalBreakpointsAreSupported ())
752 {
753 Error error;
Greg Clayton5b882162011-07-21 01:12:01 +0000754 if (!bp_site->IsEnabled())
755 {
756 if (m_comm.SendRequestBreakpoint(true, bp_site->GetLoadAddress()))
757 {
758 bp_site->SetEnabled(true);
759 bp_site->SetType (BreakpointSite::eExternal);
760 }
761 else
762 {
763 error.SetErrorString ("KDP set breakpoint failed");
764 }
765 }
Greg Clayton07e66e32011-07-20 03:41:06 +0000766 return error;
767 }
Greg Claytonf9765ac2011-07-15 03:27:12 +0000768 return EnableSoftwareBreakpoint (bp_site);
769}
770
771Error
Jim Ingham299c0c12013-02-15 02:06:30 +0000772ProcessKDP::DisableBreakpointSite (BreakpointSite *bp_site)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000773{
Greg Clayton07e66e32011-07-20 03:41:06 +0000774 if (m_comm.LocalBreakpointsAreSupported ())
775 {
776 Error error;
Greg Clayton5b882162011-07-21 01:12:01 +0000777 if (bp_site->IsEnabled())
778 {
779 BreakpointSite::Type bp_type = bp_site->GetType();
780 if (bp_type == BreakpointSite::eExternal)
781 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000782 if (m_destroy_in_process && m_comm.IsRunning())
783 {
784 // We are trying to destroy our connection and we are running
Greg Clayton5b882162011-07-21 01:12:01 +0000785 bp_site->SetEnabled(false);
Greg Clayton97d5cf02012-09-25 02:40:06 +0000786 }
Greg Clayton5b882162011-07-21 01:12:01 +0000787 else
Greg Clayton97d5cf02012-09-25 02:40:06 +0000788 {
789 if (m_comm.SendRequestBreakpoint(false, bp_site->GetLoadAddress()))
790 bp_site->SetEnabled(false);
791 else
792 error.SetErrorString ("KDP remove breakpoint failed");
793 }
Greg Clayton5b882162011-07-21 01:12:01 +0000794 }
795 else
796 {
797 error = DisableSoftwareBreakpoint (bp_site);
798 }
799 }
Greg Clayton07e66e32011-07-20 03:41:06 +0000800 return error;
801 }
Greg Claytonf9765ac2011-07-15 03:27:12 +0000802 return DisableSoftwareBreakpoint (bp_site);
803}
804
805Error
Jim Ingham1b5792e2012-12-18 02:03:49 +0000806ProcessKDP::EnableWatchpoint (Watchpoint *wp, bool notify)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000807{
808 Error error;
809 error.SetErrorString ("watchpoints are not suppported in kdp remote debugging");
810 return error;
811}
812
813Error
Jim Ingham1b5792e2012-12-18 02:03:49 +0000814ProcessKDP::DisableWatchpoint (Watchpoint *wp, bool notify)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000815{
816 Error error;
817 error.SetErrorString ("watchpoints are not suppported in kdp remote debugging");
818 return error;
819}
820
821void
822ProcessKDP::Clear()
823{
Greg Claytonf9765ac2011-07-15 03:27:12 +0000824 m_thread_list.Clear();
825}
826
827Error
828ProcessKDP::DoSignal (int signo)
829{
830 Error error;
831 error.SetErrorString ("sending signals is not suppported in kdp remote debugging");
832 return error;
833}
834
835void
836ProcessKDP::Initialize()
837{
838 static bool g_initialized = false;
839
840 if (g_initialized == false)
841 {
842 g_initialized = true;
843 PluginManager::RegisterPlugin (GetPluginNameStatic(),
844 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +0000845 CreateInstance,
846 DebuggerInitialize);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000847
848 Log::Callbacks log_callbacks = {
849 ProcessKDPLog::DisableLog,
850 ProcessKDPLog::EnableLog,
851 ProcessKDPLog::ListLogCategories
852 };
853
854 Log::RegisterLogChannel (ProcessKDP::GetPluginNameStatic(), log_callbacks);
855 }
856}
857
Greg Clayton7f982402013-07-15 22:54:20 +0000858void
859ProcessKDP::DebuggerInitialize (lldb_private::Debugger &debugger)
860{
861 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
862 {
863 const bool is_global_setting = true;
864 PluginManager::CreateSettingForProcessPlugin (debugger,
865 GetGlobalPluginProperties()->GetValueProperties(),
866 ConstString ("Properties for the kdp-remote process plug-in."),
867 is_global_setting);
868 }
869}
870
Greg Claytonf9765ac2011-07-15 03:27:12 +0000871bool
872ProcessKDP::StartAsyncThread ()
873{
Greg Clayton5160ce52013-03-27 23:08:40 +0000874 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
Greg Claytonf9765ac2011-07-15 03:27:12 +0000875
876 if (log)
Greg Clayton7925fbb2012-09-21 16:31:20 +0000877 log->Printf ("ProcessKDP::StartAsyncThread ()");
Zachary Turner39de3112014-09-09 20:54:56 +0000878
Zachary Turneracee96a2014-09-23 18:32:09 +0000879 if (m_async_thread.IsJoinable())
Greg Clayton7925fbb2012-09-21 16:31:20 +0000880 return true;
881
Zachary Turner39de3112014-09-09 20:54:56 +0000882 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.kdp-remote.async>", ProcessKDP::AsyncThread, this, NULL);
Zachary Turneracee96a2014-09-23 18:32:09 +0000883 return m_async_thread.IsJoinable();
Greg Claytonf9765ac2011-07-15 03:27:12 +0000884}
885
886void
887ProcessKDP::StopAsyncThread ()
888{
Greg Clayton5160ce52013-03-27 23:08:40 +0000889 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
Greg Claytonf9765ac2011-07-15 03:27:12 +0000890
891 if (log)
Greg Clayton7925fbb2012-09-21 16:31:20 +0000892 log->Printf ("ProcessKDP::StopAsyncThread ()");
Greg Claytonf9765ac2011-07-15 03:27:12 +0000893
894 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
895
896 // Stop the stdio thread
Zachary Turneracee96a2014-09-23 18:32:09 +0000897 if (m_async_thread.IsJoinable())
Zachary Turner39de3112014-09-09 20:54:56 +0000898 m_async_thread.Join(nullptr);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000899}
900
901
902void *
903ProcessKDP::AsyncThread (void *arg)
904{
905 ProcessKDP *process = (ProcessKDP*) arg;
906
Greg Clayton7925fbb2012-09-21 16:31:20 +0000907 const lldb::pid_t pid = process->GetID();
908
Greg Clayton5160ce52013-03-27 23:08:40 +0000909 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_PROCESS));
Greg Claytonf9765ac2011-07-15 03:27:12 +0000910 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000911 log->Printf ("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64 ") thread starting...", arg, pid);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000912
913 Listener listener ("ProcessKDP::AsyncThread");
914 EventSP event_sp;
915 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
916 eBroadcastBitAsyncThreadShouldExit;
917
Greg Clayton7925fbb2012-09-21 16:31:20 +0000918
Greg Claytonf9765ac2011-07-15 03:27:12 +0000919 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
920 {
Greg Claytonf9765ac2011-07-15 03:27:12 +0000921 bool done = false;
922 while (!done)
923 {
924 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000925 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...",
Greg Clayton7925fbb2012-09-21 16:31:20 +0000926 pid);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000927 if (listener.WaitForEvent (NULL, event_sp))
928 {
Greg Clayton7925fbb2012-09-21 16:31:20 +0000929 uint32_t event_type = event_sp->GetType();
930 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000931 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") Got an event of type: %d...",
Greg Clayton7925fbb2012-09-21 16:31:20 +0000932 pid,
933 event_type);
934
935 // When we are running, poll for 1 second to try and get an exception
936 // to indicate the process has stopped. If we don't get one, check to
937 // make sure no one asked us to exit
938 bool is_running = false;
939 DataExtractor exc_reply_packet;
940 do
Greg Claytonf9765ac2011-07-15 03:27:12 +0000941 {
Greg Claytonf9765ac2011-07-15 03:27:12 +0000942 switch (event_type)
943 {
Greg Clayton7925fbb2012-09-21 16:31:20 +0000944 case eBroadcastBitAsyncContinue:
Greg Claytonf9765ac2011-07-15 03:27:12 +0000945 {
Greg Clayton7925fbb2012-09-21 16:31:20 +0000946 is_running = true;
947 if (process->m_comm.WaitForPacketWithTimeoutMicroSeconds (exc_reply_packet, 1 * USEC_PER_SEC))
Greg Claytonf9765ac2011-07-15 03:27:12 +0000948 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000949 ThreadSP thread_sp (process->GetKernelThread());
Greg Clayton1afa68e2013-04-02 20:32:37 +0000950 if (thread_sp)
951 {
952 lldb::RegisterContextSP reg_ctx_sp (thread_sp->GetRegisterContext());
953 if (reg_ctx_sp)
954 reg_ctx_sp->InvalidateAllRegisters();
955 static_cast<ThreadKDP *>(thread_sp.get())->SetStopInfoFrom_KDP_EXCEPTION (exc_reply_packet);
956 }
Greg Clayton97d5cf02012-09-25 02:40:06 +0000957
Greg Clayton7925fbb2012-09-21 16:31:20 +0000958 // TODO: parse the stop reply packet
Greg Clayton97d5cf02012-09-25 02:40:06 +0000959 is_running = false;
Greg Clayton7925fbb2012-09-21 16:31:20 +0000960 process->SetPrivateState(eStateStopped);
961 }
962 else
963 {
964 // Check to see if we are supposed to exit. There is no way to
965 // interrupt a running kernel, so all we can do is wait for an
966 // exception or detach...
967 if (listener.GetNextEvent(event_sp))
968 {
969 // We got an event, go through the loop again
970 event_type = event_sp->GetType();
971 }
Greg Claytonf9765ac2011-07-15 03:27:12 +0000972 }
973 }
Greg Clayton7925fbb2012-09-21 16:31:20 +0000974 break;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000975
Greg Clayton7925fbb2012-09-21 16:31:20 +0000976 case eBroadcastBitAsyncThreadShouldExit:
977 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000978 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...",
Greg Clayton7925fbb2012-09-21 16:31:20 +0000979 pid);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000980 done = true;
Greg Clayton7925fbb2012-09-21 16:31:20 +0000981 is_running = false;
982 break;
983
984 default:
985 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000986 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") got unknown event 0x%8.8x",
Greg Clayton7925fbb2012-09-21 16:31:20 +0000987 pid,
988 event_type);
989 done = true;
990 is_running = false;
991 break;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000992 }
Greg Clayton7925fbb2012-09-21 16:31:20 +0000993 } while (is_running);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000994 }
995 else
996 {
997 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000998 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false",
Greg Clayton7925fbb2012-09-21 16:31:20 +0000999 pid);
Greg Claytonf9765ac2011-07-15 03:27:12 +00001000 done = true;
1001 }
1002 }
1003 }
1004
1005 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001006 log->Printf ("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64 ") thread exiting...",
Greg Clayton7925fbb2012-09-21 16:31:20 +00001007 arg,
1008 pid);
Zachary Turner39de3112014-09-09 20:54:56 +00001009
1010 process->m_async_thread.Reset();
Greg Claytonf9765ac2011-07-15 03:27:12 +00001011 return NULL;
1012}
1013
1014
Greg Clayton1d19a2f2012-10-19 22:22:57 +00001015class CommandObjectProcessKDPPacketSend : public CommandObjectParsed
1016{
1017private:
1018
1019 OptionGroupOptions m_option_group;
1020 OptionGroupUInt64 m_command_byte;
1021 OptionGroupString m_packet_data;
1022
1023 virtual Options *
1024 GetOptions ()
1025 {
1026 return &m_option_group;
1027 }
1028
1029
1030public:
1031 CommandObjectProcessKDPPacketSend(CommandInterpreter &interpreter) :
1032 CommandObjectParsed (interpreter,
1033 "process plugin packet send",
1034 "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. ",
1035 NULL),
1036 m_option_group (interpreter),
1037 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),
1038 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)
1039 {
1040 m_option_group.Append (&m_command_byte, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
1041 m_option_group.Append (&m_packet_data , LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
1042 m_option_group.Finalize();
1043 }
1044
1045 ~CommandObjectProcessKDPPacketSend ()
1046 {
1047 }
1048
1049 bool
1050 DoExecute (Args& command, CommandReturnObject &result)
1051 {
1052 const size_t argc = command.GetArgumentCount();
1053 if (argc == 0)
1054 {
1055 if (!m_command_byte.GetOptionValue().OptionWasSet())
1056 {
1057 result.AppendError ("the --command option must be set to a valid command byte");
1058 result.SetStatus (eReturnStatusFailed);
1059 }
1060 else
1061 {
1062 const uint64_t command_byte = m_command_byte.GetOptionValue().GetUInt64Value(0);
1063 if (command_byte > 0 && command_byte <= UINT8_MAX)
1064 {
1065 ProcessKDP *process = (ProcessKDP *)m_interpreter.GetExecutionContext().GetProcessPtr();
1066 if (process)
1067 {
1068 const StateType state = process->GetState();
1069
1070 if (StateIsStoppedState (state, true))
1071 {
1072 std::vector<uint8_t> payload_bytes;
1073 const char *ascii_hex_bytes_cstr = m_packet_data.GetOptionValue().GetCurrentValue();
1074 if (ascii_hex_bytes_cstr && ascii_hex_bytes_cstr[0])
1075 {
1076 StringExtractor extractor(ascii_hex_bytes_cstr);
1077 const size_t ascii_hex_bytes_cstr_len = extractor.GetStringRef().size();
1078 if (ascii_hex_bytes_cstr_len & 1)
1079 {
1080 result.AppendErrorWithFormat ("payload data must contain an even number of ASCII hex characters: '%s'", ascii_hex_bytes_cstr);
1081 result.SetStatus (eReturnStatusFailed);
1082 return false;
1083 }
1084 payload_bytes.resize(ascii_hex_bytes_cstr_len/2);
1085 if (extractor.GetHexBytes(&payload_bytes[0], payload_bytes.size(), '\xdd') != payload_bytes.size())
1086 {
1087 result.AppendErrorWithFormat ("payload data must only contain ASCII hex characters (no spaces or hex prefixes): '%s'", ascii_hex_bytes_cstr);
1088 result.SetStatus (eReturnStatusFailed);
1089 return false;
1090 }
1091 }
1092 Error error;
1093 DataExtractor reply;
1094 process->GetCommunication().SendRawRequest (command_byte,
1095 payload_bytes.empty() ? NULL : payload_bytes.data(),
1096 payload_bytes.size(),
1097 reply,
1098 error);
1099
1100 if (error.Success())
1101 {
1102 // Copy the binary bytes into a hex ASCII string for the result
1103 StreamString packet;
1104 packet.PutBytesAsRawHex8(reply.GetDataStart(),
1105 reply.GetByteSize(),
1106 lldb::endian::InlHostByteOrder(),
1107 lldb::endian::InlHostByteOrder());
1108 result.AppendMessage(packet.GetString().c_str());
1109 result.SetStatus (eReturnStatusSuccessFinishResult);
1110 return true;
1111 }
1112 else
1113 {
1114 const char *error_cstr = error.AsCString();
1115 if (error_cstr && error_cstr[0])
1116 result.AppendError (error_cstr);
1117 else
1118 result.AppendErrorWithFormat ("unknown error 0x%8.8x", error.GetError());
1119 result.SetStatus (eReturnStatusFailed);
1120 return false;
1121 }
1122 }
1123 else
1124 {
1125 result.AppendErrorWithFormat ("process must be stopped in order to send KDP packets, state is %s", StateAsCString (state));
1126 result.SetStatus (eReturnStatusFailed);
1127 }
1128 }
1129 else
1130 {
1131 result.AppendError ("invalid process");
1132 result.SetStatus (eReturnStatusFailed);
1133 }
1134 }
1135 else
1136 {
Daniel Malead01b2952012-11-29 21:49:15 +00001137 result.AppendErrorWithFormat ("invalid command byte 0x%" PRIx64 ", valid values are 1 - 255", command_byte);
Greg Clayton1d19a2f2012-10-19 22:22:57 +00001138 result.SetStatus (eReturnStatusFailed);
1139 }
1140 }
1141 }
1142 else
1143 {
1144 result.AppendErrorWithFormat ("'%s' takes no arguments, only options.", m_cmd_name.c_str());
1145 result.SetStatus (eReturnStatusFailed);
1146 }
1147 return false;
1148 }
1149};
1150
1151class CommandObjectProcessKDPPacket : public CommandObjectMultiword
1152{
1153private:
1154
1155public:
1156 CommandObjectProcessKDPPacket(CommandInterpreter &interpreter) :
1157 CommandObjectMultiword (interpreter,
1158 "process plugin packet",
1159 "Commands that deal with KDP remote packets.",
1160 NULL)
1161 {
1162 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessKDPPacketSend (interpreter)));
1163 }
1164
1165 ~CommandObjectProcessKDPPacket ()
1166 {
1167 }
1168};
1169
1170class CommandObjectMultiwordProcessKDP : public CommandObjectMultiword
1171{
1172public:
1173 CommandObjectMultiwordProcessKDP (CommandInterpreter &interpreter) :
1174 CommandObjectMultiword (interpreter,
1175 "process plugin",
1176 "A set of commands for operating on a ProcessKDP process.",
1177 "process plugin <subcommand> [<subcommand-options>]")
1178 {
1179 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessKDPPacket (interpreter)));
1180 }
1181
1182 ~CommandObjectMultiwordProcessKDP ()
1183 {
1184 }
1185};
1186
1187CommandObject *
1188ProcessKDP::GetPluginCommandObject()
1189{
1190 if (!m_command_sp)
1191 m_command_sp.reset (new CommandObjectMultiwordProcessKDP (GetTarget().GetDebugger().GetCommandInterpreter()));
1192 return m_command_sp.get();
1193}
1194