blob: 2acc81bb483ffdb95811565edd0d7d52b4e8309e [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
Benjamin Kramer3f69fa62015-04-03 10:55:00 +000015#include <mutex>
16
Greg Claytonf9765ac2011-07-15 03:27:12 +000017// Other libraries and framework includes
Greg Clayton07e66e32011-07-20 03:41:06 +000018#include "lldb/Core/Debugger.h"
Greg Claytonf9765ac2011-07-15 03:27:12 +000019#include "lldb/Core/PluginManager.h"
Greg Clayton1f746072012-08-29 21:13:06 +000020#include "lldb/Core/Module.h"
Jason Molenda4bd4e7e2012-09-29 04:02:01 +000021#include "lldb/Core/ModuleSpec.h"
Greg Claytonf9765ac2011-07-15 03:27:12 +000022#include "lldb/Core/State.h"
Jason Molenda4bd4e7e2012-09-29 04:02:01 +000023#include "lldb/Core/UUID.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000024#include "lldb/Host/ConnectionFileDescriptor.h"
Greg Claytonf9765ac2011-07-15 03:27:12 +000025#include "lldb/Host/Host.h"
Jason Molenda4bd4e7e2012-09-29 04:02:01 +000026#include "lldb/Host/Symbols.h"
Keno Fischer3d7162b2014-08-06 21:18:13 +000027#include "lldb/Host/Socket.h"
Zachary Turner39de3112014-09-09 20:54:56 +000028#include "lldb/Host/ThreadLauncher.h"
Greg Clayton1d19a2f2012-10-19 22:22:57 +000029#include "lldb/Interpreter/CommandInterpreter.h"
30#include "lldb/Interpreter/CommandObject.h"
31#include "lldb/Interpreter/CommandObjectMultiword.h"
32#include "lldb/Interpreter/CommandReturnObject.h"
33#include "lldb/Interpreter/OptionGroupString.h"
34#include "lldb/Interpreter/OptionGroupUInt64.h"
Ilia K41204d02015-03-04 12:05:24 +000035#include "lldb/Interpreter/OptionValueProperties.h"
Greg Clayton1f746072012-08-29 21:13:06 +000036#include "lldb/Symbol/ObjectFile.h"
Greg Clayton7925fbb2012-09-21 16:31:20 +000037#include "lldb/Target/RegisterContext.h"
Greg Clayton57508022011-07-15 16:31:38 +000038#include "lldb/Target/Target.h"
Greg Claytona63d08c2011-07-19 03:57:15 +000039#include "lldb/Target/Thread.h"
Greg Claytonf9765ac2011-07-15 03:27:12 +000040
Charles Davis510938e2013-08-27 05:04:57 +000041#define USEC_PER_SEC 1000000
42
Greg Claytonf9765ac2011-07-15 03:27:12 +000043// Project includes
44#include "ProcessKDP.h"
45#include "ProcessKDPLog.h"
Greg Claytona63d08c2011-07-19 03:57:15 +000046#include "ThreadKDP.h"
Jason Molenda5e8534e2012-10-03 01:29:34 +000047#include "Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.h"
Jason Molenda840f12c2012-10-25 00:25:13 +000048#include "Plugins/DynamicLoader/Static/DynamicLoaderStatic.h"
Greg Clayton1d19a2f2012-10-19 22:22:57 +000049#include "Utility/StringExtractor.h"
Greg Claytonf9765ac2011-07-15 03:27:12 +000050
51using namespace lldb;
52using namespace lldb_private;
53
Greg Clayton7f982402013-07-15 22:54:20 +000054namespace {
55
56 static PropertyDefinition
57 g_properties[] =
58 {
59 { "packet-timeout" , OptionValue::eTypeUInt64 , true , 5, NULL, NULL, "Specify the default packet timeout in seconds." },
60 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
61 };
62
63 enum
64 {
65 ePropertyPacketTimeout
66 };
67
68 class PluginProperties : public Properties
69 {
70 public:
71
72 static ConstString
73 GetSettingName ()
74 {
75 return ProcessKDP::GetPluginNameStatic();
76 }
77
78 PluginProperties() :
79 Properties ()
80 {
81 m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
82 m_collection_sp->Initialize(g_properties);
83 }
84
85 virtual
86 ~PluginProperties()
87 {
88 }
89
90 uint64_t
91 GetPacketTimeout()
92 {
93 const uint32_t idx = ePropertyPacketTimeout;
94 return m_collection_sp->GetPropertyAtIndexAsUInt64(NULL, idx, g_properties[idx].default_uint_value);
95 }
96 };
97
98 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
99
100 static const ProcessKDPPropertiesSP &
101 GetGlobalPluginProperties()
102 {
103 static ProcessKDPPropertiesSP g_settings_sp;
104 if (!g_settings_sp)
105 g_settings_sp.reset (new PluginProperties ());
106 return g_settings_sp;
107 }
108
109} // anonymous namespace end
110
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000111static const lldb::tid_t g_kernel_tid = 1;
112
Greg Clayton57abc5d2013-05-10 21:47:16 +0000113ConstString
Greg Claytonf9765ac2011-07-15 03:27:12 +0000114ProcessKDP::GetPluginNameStatic()
115{
Greg Clayton57abc5d2013-05-10 21:47:16 +0000116 static ConstString g_name("kdp-remote");
117 return g_name;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000118}
119
120const char *
121ProcessKDP::GetPluginDescriptionStatic()
122{
123 return "KDP Remote protocol based debugging plug-in for darwin kernel debugging.";
124}
125
126void
127ProcessKDP::Terminate()
128{
129 PluginManager::UnregisterPlugin (ProcessKDP::CreateInstance);
130}
131
132
Greg Claytonc3776bf2012-02-09 06:16:32 +0000133lldb::ProcessSP
134ProcessKDP::CreateInstance (Target &target,
135 Listener &listener,
136 const FileSpec *crash_file_path)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000137{
Greg Claytonc3776bf2012-02-09 06:16:32 +0000138 lldb::ProcessSP process_sp;
139 if (crash_file_path == NULL)
140 process_sp.reset(new ProcessKDP (target, listener));
141 return process_sp;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000142}
143
144bool
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000145ProcessKDP::CanDebug(Target &target, bool plugin_specified_by_name)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000146{
Greg Clayton596ed242011-10-21 21:41:45 +0000147 if (plugin_specified_by_name)
148 return true;
149
Greg Claytonf9765ac2011-07-15 03:27:12 +0000150 // For now we are just making sure the file exists for a given module
Greg Claytonaa149cb2011-08-11 02:48:45 +0000151 Module *exe_module = target.GetExecutableModulePointer();
152 if (exe_module)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000153 {
154 const llvm::Triple &triple_ref = target.GetArchitecture().GetTriple();
Greg Clayton70512312012-05-08 01:45:38 +0000155 switch (triple_ref.getOS())
Greg Claytonf9765ac2011-07-15 03:27:12 +0000156 {
Greg Clayton70512312012-05-08 01:45:38 +0000157 case llvm::Triple::Darwin: // Should use "macosx" for desktop and "ios" for iOS, but accept darwin just in case
158 case llvm::Triple::MacOSX: // For desktop targets
159 case llvm::Triple::IOS: // For arm targets
160 if (triple_ref.getVendor() == llvm::Triple::Apple)
161 {
162 ObjectFile *exe_objfile = exe_module->GetObjectFile();
163 if (exe_objfile->GetType() == ObjectFile::eTypeExecutable &&
164 exe_objfile->GetStrata() == ObjectFile::eStrataKernel)
165 return true;
166 }
167 break;
168
169 default:
170 break;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000171 }
172 }
Greg Clayton596ed242011-10-21 21:41:45 +0000173 return false;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000174}
175
176//----------------------------------------------------------------------
177// ProcessKDP constructor
178//----------------------------------------------------------------------
179ProcessKDP::ProcessKDP(Target& target, Listener &listener) :
180 Process (target, listener),
181 m_comm("lldb.process.kdp-remote.communication"),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000182 m_async_broadcaster (NULL, "lldb.process.kdp-remote.async-broadcaster"),
Jason Molenda5e8534e2012-10-03 01:29:34 +0000183 m_dyld_plugin_name (),
Greg Clayton1d19a2f2012-10-19 22:22:57 +0000184 m_kernel_load_addr (LLDB_INVALID_ADDRESS),
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000185 m_command_sp(),
186 m_kernel_thread_wp()
Greg Claytonf9765ac2011-07-15 03:27:12 +0000187{
Greg Clayton7925fbb2012-09-21 16:31:20 +0000188 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
189 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Greg Clayton7f982402013-07-15 22:54:20 +0000190 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
191 if (timeout_seconds > 0)
192 m_comm.SetPacketTimeout(timeout_seconds);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000193}
194
195//----------------------------------------------------------------------
196// Destructor
197//----------------------------------------------------------------------
198ProcessKDP::~ProcessKDP()
199{
200 Clear();
Greg Claytone24c4ac2011-11-17 04:46:02 +0000201 // We need to call finalize on the process before destroying ourselves
202 // to make sure all of the broadcaster cleanup goes as planned. If we
203 // destruct this class, then Process::~Process() might have problems
204 // trying to fully destroy the broadcaster.
205 Finalize();
Greg Claytonf9765ac2011-07-15 03:27:12 +0000206}
207
208//----------------------------------------------------------------------
209// PluginInterface
210//----------------------------------------------------------------------
Greg Clayton57abc5d2013-05-10 21:47:16 +0000211lldb_private::ConstString
Greg Claytonf9765ac2011-07-15 03:27:12 +0000212ProcessKDP::GetPluginName()
213{
Greg Claytonf9765ac2011-07-15 03:27:12 +0000214 return GetPluginNameStatic();
215}
216
217uint32_t
218ProcessKDP::GetPluginVersion()
219{
220 return 1;
221}
222
223Error
224ProcessKDP::WillLaunch (Module* module)
225{
226 Error error;
227 error.SetErrorString ("launching not supported in kdp-remote plug-in");
228 return error;
229}
230
231Error
232ProcessKDP::WillAttachToProcessWithID (lldb::pid_t pid)
233{
234 Error error;
235 error.SetErrorString ("attaching to a by process ID not supported in kdp-remote plug-in");
236 return error;
237}
238
239Error
240ProcessKDP::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
241{
242 Error error;
243 error.SetErrorString ("attaching to a by process name not supported in kdp-remote plug-in");
244 return error;
245}
246
247Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000248ProcessKDP::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000249{
Greg Claytonf9765ac2011-07-15 03:27:12 +0000250 Error error;
Greg Clayton7925fbb2012-09-21 16:31:20 +0000251
252 // Don't let any JIT happen when doing KDP as we can't allocate
253 // memory and we don't want to be mucking with threads that might
254 // already be handling exceptions
255 SetCanJIT(false);
256
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000257 if (remote_url == NULL || remote_url[0] == '\0')
Greg Clayton7925fbb2012-09-21 16:31:20 +0000258 {
259 error.SetErrorStringWithFormat ("invalid connection URL '%s'", remote_url);
260 return error;
261 }
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000262
Greg Clayton7b0992d2013-04-18 22:45:39 +0000263 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000264 if (conn_ap.get())
265 {
266 // Only try once for now.
267 // TODO: check if we should be retrying?
268 const uint32_t max_retry_count = 1;
269 for (uint32_t retry_count = 0; retry_count < max_retry_count; ++retry_count)
270 {
271 if (conn_ap->Connect(remote_url, &error) == eConnectionStatusSuccess)
272 break;
273 usleep (100000);
274 }
275 }
276
277 if (conn_ap->IsConnected())
278 {
Keno Fischer3d7162b2014-08-06 21:18:13 +0000279 const Socket& socket = static_cast<const Socket&>(*conn_ap->GetReadObject());
Vince Harron014bb7d2015-01-16 00:47:08 +0000280 const uint16_t reply_port = socket.GetLocalPortNumber();
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000281
282 if (reply_port != 0)
283 {
284 m_comm.SetConnection(conn_ap.release());
285
286 if (m_comm.SendRequestReattach(reply_port))
287 {
288 if (m_comm.SendRequestConnect(reply_port, reply_port, "Greetings from LLDB..."))
289 {
290 m_comm.GetVersion();
291 uint32_t cpu = m_comm.GetCPUType();
292 uint32_t sub = m_comm.GetCPUSubtype();
293 ArchSpec kernel_arch;
294 kernel_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
295 m_target.SetArchitecture(kernel_arch);
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000296
Jason Molenda840f12c2012-10-25 00:25:13 +0000297 /* Get the kernel's UUID and load address via KDP_KERNELVERSION packet. */
298 /* An EFI kdp session has neither UUID nor load address. */
299
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000300 UUID kernel_uuid = m_comm.GetUUID ();
301 addr_t kernel_load_addr = m_comm.GetLoadAddress ();
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000302
Jason Molenda840f12c2012-10-25 00:25:13 +0000303 if (m_comm.RemoteIsEFI ())
304 {
Greg Claytona1bce2e2014-07-16 21:16:27 +0000305 // Select an invalid plugin name for the dynamic loader so one doesn't get used
306 // since EFI does its own manual loading via python scripting
307 static ConstString g_none_dynamic_loader("none");
308 m_dyld_plugin_name = g_none_dynamic_loader;
309
310 if (kernel_uuid.IsValid()) {
311 // If EFI passed in a UUID= try to lookup UUID
312 // The slide will not be provided. But the UUID
313 // lookup will be used to launch EFI debug scripts
314 // from the dSYM, that can load all of the symbols.
315 ModuleSpec module_spec;
316 module_spec.GetUUID() = kernel_uuid;
317 module_spec.GetArchitecture() = m_target.GetArchitecture();
318
319 // Lookup UUID locally, before attempting dsymForUUID like action
320 module_spec.GetSymbolFileSpec() = Symbols::LocateExecutableSymbolFile(module_spec);
321 if (module_spec.GetSymbolFileSpec())
322 module_spec.GetFileSpec() = Symbols::LocateExecutableObjectFile (module_spec);
323 if (!module_spec.GetSymbolFileSpec() || !module_spec.GetSymbolFileSpec())
324 Symbols::DownloadObjectAndSymbolFile (module_spec, true);
325
326 if (module_spec.GetFileSpec().Exists())
327 {
328 ModuleSP module_sp(new Module (module_spec.GetFileSpec(), m_target.GetArchitecture()));
329 if (module_sp.get() && module_sp->MatchesModuleSpec (module_spec))
330 {
331 // Get the current target executable
332 ModuleSP exe_module_sp (m_target.GetExecutableModule ());
333
334 // Make sure you don't already have the right module loaded and they will be uniqued
335 if (exe_module_sp.get() != module_sp.get())
336 m_target.SetExecutableModule (module_sp, false);
337 }
338 }
339 }
Jason Molenda840f12c2012-10-25 00:25:13 +0000340 }
Jason Molendaca2ffa72013-05-09 23:52:21 +0000341 else if (m_comm.RemoteIsDarwinKernel ())
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000342 {
Jason Molendaca2ffa72013-05-09 23:52:21 +0000343 m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
Jason Molendaa8ea4ba2013-05-06 23:02:03 +0000344 if (kernel_load_addr != LLDB_INVALID_ADDRESS)
345 {
346 m_kernel_load_addr = kernel_load_addr;
347 }
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000348 }
349
Greg Clayton97d5cf02012-09-25 02:40:06 +0000350 // Set the thread ID
351 UpdateThreadListIfNeeded ();
Greg Claytona63d08c2011-07-19 03:57:15 +0000352 SetID (1);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000353 GetThreadList ();
Greg Claytona63d08c2011-07-19 03:57:15 +0000354 SetPrivateState (eStateStopped);
Greg Clayton07e66e32011-07-20 03:41:06 +0000355 StreamSP async_strm_sp(m_target.GetDebugger().GetAsyncOutputStream());
356 if (async_strm_sp)
357 {
Greg Clayton5b882162011-07-21 01:12:01 +0000358 const char *cstr;
359 if ((cstr = m_comm.GetKernelVersion ()) != NULL)
Greg Clayton07e66e32011-07-20 03:41:06 +0000360 {
Greg Clayton5b882162011-07-21 01:12:01 +0000361 async_strm_sp->Printf ("Version: %s\n", cstr);
Greg Clayton07e66e32011-07-20 03:41:06 +0000362 async_strm_sp->Flush();
363 }
Greg Clayton5b882162011-07-21 01:12:01 +0000364// if ((cstr = m_comm.GetImagePath ()) != NULL)
365// {
366// async_strm_sp->Printf ("Image Path: %s\n", cstr);
367// async_strm_sp->Flush();
368// }
Greg Clayton07e66e32011-07-20 03:41:06 +0000369 }
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000370 }
Greg Clayton97d5cf02012-09-25 02:40:06 +0000371 else
372 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000373 error.SetErrorString("KDP_REATTACH failed");
374 }
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000375 }
376 else
377 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000378 error.SetErrorString("KDP_REATTACH failed");
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000379 }
380 }
381 else
382 {
383 error.SetErrorString("invalid reply port from UDP connection");
384 }
385 }
386 else
387 {
388 if (error.Success())
389 error.SetErrorStringWithFormat ("failed to connect to '%s'", remote_url);
390 }
391 if (error.Fail())
392 m_comm.Disconnect();
393
Greg Claytonf9765ac2011-07-15 03:27:12 +0000394 return error;
395}
396
397//----------------------------------------------------------------------
398// Process Control
399//----------------------------------------------------------------------
400Error
Greg Clayton982c9762011-11-03 21:22:33 +0000401ProcessKDP::DoLaunch (Module *exe_module,
Jean-Daniel Dupas7782de92013-12-09 22:52:50 +0000402 ProcessLaunchInfo &launch_info)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000403{
404 Error error;
405 error.SetErrorString ("launching not supported in kdp-remote plug-in");
406 return error;
407}
408
Greg Claytonf9765ac2011-07-15 03:27:12 +0000409Error
Han Ming Ong84647042012-02-25 01:07:38 +0000410ProcessKDP::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
411{
412 Error error;
413 error.SetErrorString ("attach to process by ID is not suppported in kdp remote debugging");
414 return error;
415}
416
417Error
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +0000418ProcessKDP::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000419{
420 Error error;
421 error.SetErrorString ("attach to process by name is not suppported in kdp remote debugging");
422 return error;
423}
424
425
426void
Jim Inghambb006ce2014-08-02 00:33:35 +0000427ProcessKDP::DidAttach (ArchSpec &process_arch)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000428{
Jim Inghambb006ce2014-08-02 00:33:35 +0000429 Process::DidAttach(process_arch);
430
Greg Clayton5160ce52013-03-27 23:08:40 +0000431 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_PROCESS));
Greg Claytonf9765ac2011-07-15 03:27:12 +0000432 if (log)
Johnny Chen54cb8f82011-10-11 21:17:10 +0000433 log->Printf ("ProcessKDP::DidAttach()");
Greg Claytonf9765ac2011-07-15 03:27:12 +0000434 if (GetID() != LLDB_INVALID_PROCESS_ID)
435 {
Greg Claytonc3eefa32014-10-31 00:06:52 +0000436 uint32_t cpu = m_comm.GetCPUType();
437 if (cpu)
438 {
439 uint32_t sub = m_comm.GetCPUSubtype();
440 process_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
441 }
Greg Claytonf9765ac2011-07-15 03:27:12 +0000442 }
443}
444
Jason Molenda5e8534e2012-10-03 01:29:34 +0000445addr_t
446ProcessKDP::GetImageInfoAddress()
447{
448 return m_kernel_load_addr;
449}
450
451lldb_private::DynamicLoader *
452ProcessKDP::GetDynamicLoader ()
453{
454 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +0000455 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 +0000456 return m_dyld_ap.get();
457}
458
Greg Claytonf9765ac2011-07-15 03:27:12 +0000459Error
460ProcessKDP::WillResume ()
461{
462 return Error();
463}
464
465Error
466ProcessKDP::DoResume ()
467{
468 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +0000469 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_PROCESS));
Greg Clayton7925fbb2012-09-21 16:31:20 +0000470 // Only start the async thread if we try to do any process control
Zachary Turneracee96a2014-09-23 18:32:09 +0000471 if (!m_async_thread.IsJoinable())
Zachary Turner39de3112014-09-09 20:54:56 +0000472 StartAsyncThread();
Greg Clayton7925fbb2012-09-21 16:31:20 +0000473
Greg Clayton97d5cf02012-09-25 02:40:06 +0000474 bool resume = false;
Greg Clayton7925fbb2012-09-21 16:31:20 +0000475
Greg Clayton97d5cf02012-09-25 02:40:06 +0000476 // With KDP there is only one thread we can tell what to do
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000477 ThreadSP kernel_thread_sp (m_thread_list.FindThreadByProtocolID(g_kernel_tid));
478
Greg Clayton97d5cf02012-09-25 02:40:06 +0000479 if (kernel_thread_sp)
Greg Clayton4b1b8b32012-09-21 01:55:30 +0000480 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000481 const StateType thread_resume_state = kernel_thread_sp->GetTemporaryResumeState();
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000482
483 if (log)
484 log->Printf ("ProcessKDP::DoResume() thread_resume_state = %s", StateAsCString(thread_resume_state));
Greg Clayton7925fbb2012-09-21 16:31:20 +0000485 switch (thread_resume_state)
Greg Clayton4b1b8b32012-09-21 01:55:30 +0000486 {
Greg Clayton7925fbb2012-09-21 16:31:20 +0000487 case eStateSuspended:
488 // Nothing to do here when a thread will stay suspended
489 // we just leave the CPU mask bit set to zero for the thread
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000490 if (log)
491 log->Printf ("ProcessKDP::DoResume() = suspended???");
Greg Clayton7925fbb2012-09-21 16:31:20 +0000492 break;
493
494 case eStateStepping:
Greg Clayton1afa68e2013-04-02 20:32:37 +0000495 {
496 lldb::RegisterContextSP reg_ctx_sp (kernel_thread_sp->GetRegisterContext());
497
498 if (reg_ctx_sp)
499 {
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000500 if (log)
501 log->Printf ("ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep (true);");
Greg Clayton1afa68e2013-04-02 20:32:37 +0000502 reg_ctx_sp->HardwareSingleStep (true);
503 resume = true;
504 }
505 else
506 {
507 error.SetErrorStringWithFormat("KDP thread 0x%llx has no register context", kernel_thread_sp->GetID());
508 }
509 }
Greg Clayton97d5cf02012-09-25 02:40:06 +0000510 break;
511
Greg Clayton7925fbb2012-09-21 16:31:20 +0000512 case eStateRunning:
Greg Clayton1afa68e2013-04-02 20:32:37 +0000513 {
514 lldb::RegisterContextSP reg_ctx_sp (kernel_thread_sp->GetRegisterContext());
515
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000516 if (reg_ctx_sp)
517 {
518 if (log)
519 log->Printf ("ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep (false);");
520 reg_ctx_sp->HardwareSingleStep (false);
521 resume = true;
522 }
523 else
524 {
525 error.SetErrorStringWithFormat("KDP thread 0x%llx has no register context", kernel_thread_sp->GetID());
526 }
Greg Clayton1afa68e2013-04-02 20:32:37 +0000527 }
Greg Clayton7925fbb2012-09-21 16:31:20 +0000528 break;
Greg Clayton97d5cf02012-09-25 02:40:06 +0000529
Greg Clayton7925fbb2012-09-21 16:31:20 +0000530 default:
Greg Clayton97d5cf02012-09-25 02:40:06 +0000531 // The only valid thread resume states are listed above
Greg Clayton7925fbb2012-09-21 16:31:20 +0000532 assert (!"invalid thread resume state");
533 break;
Greg Clayton4b1b8b32012-09-21 01:55:30 +0000534 }
535 }
Greg Clayton97d5cf02012-09-25 02:40:06 +0000536
537 if (resume)
Greg Clayton7925fbb2012-09-21 16:31:20 +0000538 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000539 if (log)
540 log->Printf ("ProcessKDP::DoResume () sending resume");
Greg Clayton7925fbb2012-09-21 16:31:20 +0000541
Greg Clayton97d5cf02012-09-25 02:40:06 +0000542 if (m_comm.SendRequestResume ())
Greg Clayton7925fbb2012-09-21 16:31:20 +0000543 {
544 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue);
545 SetPrivateState(eStateRunning);
546 }
547 else
548 error.SetErrorString ("KDP resume failed");
549 }
Greg Clayton4b1b8b32012-09-21 01:55:30 +0000550 else
Greg Clayton7925fbb2012-09-21 16:31:20 +0000551 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000552 error.SetErrorString ("kernel thread is suspended");
Greg Clayton7925fbb2012-09-21 16:31:20 +0000553 }
554
Greg Claytonf9765ac2011-07-15 03:27:12 +0000555 return error;
556}
557
Greg Clayton97d5cf02012-09-25 02:40:06 +0000558lldb::ThreadSP
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000559ProcessKDP::GetKernelThread()
Greg Clayton97d5cf02012-09-25 02:40:06 +0000560{
561 // KDP only tells us about one thread/core. Any other threads will usually
562 // be the ones that are read from memory by the OS plug-ins.
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000563
564 ThreadSP thread_sp (m_kernel_thread_wp.lock());
Greg Clayton97d5cf02012-09-25 02:40:06 +0000565 if (!thread_sp)
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000566 {
567 thread_sp.reset(new ThreadKDP (*this, g_kernel_tid));
568 m_kernel_thread_wp = thread_sp;
569 }
Greg Clayton97d5cf02012-09-25 02:40:06 +0000570 return thread_sp;
571}
572
573
574
575
Greg Clayton9fc13552012-04-10 00:18:59 +0000576bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000577ProcessKDP::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000578{
579 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +0000580 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_THREAD));
Greg Claytonf9765ac2011-07-15 03:27:12 +0000581 if (log && log->GetMask().Test(KDP_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +0000582 log->Printf ("ProcessKDP::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Claytonf9765ac2011-07-15 03:27:12 +0000583
Greg Clayton39da3ef2013-04-11 22:23:34 +0000584 // Even though there is a CPU mask, it doesn't mean we can see each CPU
Greg Clayton97d5cf02012-09-25 02:40:06 +0000585 // indivudually, there is really only one. Lets call this thread 1.
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000586 ThreadSP thread_sp (old_thread_list.FindThreadByProtocolID(g_kernel_tid, false));
587 if (!thread_sp)
588 thread_sp = GetKernelThread ();
589 new_thread_list.AddThread(thread_sp);
Greg Clayton97d5cf02012-09-25 02:40:06 +0000590
Greg Clayton9fc13552012-04-10 00:18:59 +0000591 return new_thread_list.GetSize(false) > 0;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000592}
593
Greg Claytonf9765ac2011-07-15 03:27:12 +0000594void
595ProcessKDP::RefreshStateAfterStop ()
596{
597 // Let all threads recover from stopping and do any clean up based
598 // on the previous thread state (if any).
599 m_thread_list.RefreshStateAfterStop();
Greg Claytonf9765ac2011-07-15 03:27:12 +0000600}
601
602Error
603ProcessKDP::DoHalt (bool &caused_stop)
604{
605 Error error;
606
Greg Clayton97d5cf02012-09-25 02:40:06 +0000607 if (m_comm.IsRunning())
Greg Claytonf9765ac2011-07-15 03:27:12 +0000608 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000609 if (m_destroy_in_process)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000610 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000611 // If we are attemping to destroy, we need to not return an error to
612 // Halt or DoDestroy won't get called.
613 // We are also currently running, so send a process stopped event
614 SetPrivateState (eStateStopped);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000615 }
Greg Clayton97d5cf02012-09-25 02:40:06 +0000616 else
Greg Claytonf9765ac2011-07-15 03:27:12 +0000617 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000618 error.SetErrorString ("KDP cannot interrupt a running kernel");
Greg Claytonf9765ac2011-07-15 03:27:12 +0000619 }
620 }
621 return error;
622}
623
624Error
Jim Inghamacff8952013-05-02 00:27:30 +0000625ProcessKDP::DoDetach(bool keep_stopped)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000626{
627 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +0000628 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
Greg Claytonf9765ac2011-07-15 03:27:12 +0000629 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +0000630 log->Printf ("ProcessKDP::DoDetach(keep_stopped = %i)", keep_stopped);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000631
Greg Clayton97d5cf02012-09-25 02:40:06 +0000632 if (m_comm.IsRunning())
Greg Claytonf9765ac2011-07-15 03:27:12 +0000633 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000634 // We are running and we can't interrupt a running kernel, so we need
635 // to just close the connection to the kernel and hope for the best
636 }
637 else
638 {
Jim Inghamacff8952013-05-02 00:27:30 +0000639 // If we are going to keep the target stopped, then don't send the disconnect message.
640 if (!keep_stopped && m_comm.IsConnected())
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000641 {
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000642 const bool success = m_comm.SendRequestDisconnect();
Greg Clayton97d5cf02012-09-25 02:40:06 +0000643 if (log)
644 {
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000645 if (success)
646 log->PutCString ("ProcessKDP::DoDetach() detach packet sent successfully");
Greg Clayton97d5cf02012-09-25 02:40:06 +0000647 else
Jim Ingham77e82d12013-05-09 00:05:35 +0000648 log->PutCString ("ProcessKDP::DoDetach() connection channel shutdown failed");
Greg Clayton97d5cf02012-09-25 02:40:06 +0000649 }
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000650 m_comm.Disconnect ();
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000651 }
Greg Claytonf9765ac2011-07-15 03:27:12 +0000652 }
Greg Clayton97d5cf02012-09-25 02:40:06 +0000653 StopAsyncThread ();
Greg Clayton74d41932012-01-31 04:56:17 +0000654 m_comm.Clear();
Greg Claytonf9765ac2011-07-15 03:27:12 +0000655
656 SetPrivateState (eStateDetached);
657 ResumePrivateStateThread();
658
659 //KillDebugserverProcess ();
660 return error;
661}
662
663Error
664ProcessKDP::DoDestroy ()
665{
Greg Clayton7925fbb2012-09-21 16:31:20 +0000666 // For KDP there really is no difference between destroy and detach
Jim Inghamacff8952013-05-02 00:27:30 +0000667 bool keep_stopped = false;
668 return DoDetach(keep_stopped);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000669}
670
671//------------------------------------------------------------------
672// Process Queries
673//------------------------------------------------------------------
674
675bool
676ProcessKDP::IsAlive ()
677{
678 return m_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
679}
680
681//------------------------------------------------------------------
682// Process Memory
683//------------------------------------------------------------------
684size_t
685ProcessKDP::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
686{
Jason Molenda8eb32812014-05-21 23:44:02 +0000687 uint8_t *data_buffer = (uint8_t *) buf;
Greg Claytona63d08c2011-07-19 03:57:15 +0000688 if (m_comm.IsConnected())
Jason Molenda8eb32812014-05-21 23:44:02 +0000689 {
690 const size_t max_read_size = 512;
691 size_t total_bytes_read = 0;
692
693 // Read the requested amount of memory in 512 byte chunks
694 while (total_bytes_read < size)
695 {
696 size_t bytes_to_read_this_request = size - total_bytes_read;
697 if (bytes_to_read_this_request > max_read_size)
698 {
699 bytes_to_read_this_request = max_read_size;
700 }
701 size_t bytes_read = m_comm.SendRequestReadMemory (addr + total_bytes_read,
702 data_buffer + total_bytes_read,
703 bytes_to_read_this_request, error);
704 total_bytes_read += bytes_read;
705 if (error.Fail() || bytes_read == 0)
706 {
707 return total_bytes_read;
708 }
709 }
710
711 return total_bytes_read;
712 }
Greg Claytona63d08c2011-07-19 03:57:15 +0000713 error.SetErrorString ("not connected");
Greg Claytonf9765ac2011-07-15 03:27:12 +0000714 return 0;
715}
716
717size_t
718ProcessKDP::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
719{
Greg Clayton7925fbb2012-09-21 16:31:20 +0000720 if (m_comm.IsConnected())
721 return m_comm.SendRequestWriteMemory (addr, buf, size, error);
722 error.SetErrorString ("not connected");
Greg Claytonf9765ac2011-07-15 03:27:12 +0000723 return 0;
724}
725
726lldb::addr_t
727ProcessKDP::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
728{
729 error.SetErrorString ("memory allocation not suppported in kdp remote debugging");
730 return LLDB_INVALID_ADDRESS;
731}
732
733Error
734ProcessKDP::DoDeallocateMemory (lldb::addr_t addr)
735{
736 Error error;
737 error.SetErrorString ("memory deallocation not suppported in kdp remote debugging");
738 return error;
739}
740
741Error
Jim Ingham299c0c12013-02-15 02:06:30 +0000742ProcessKDP::EnableBreakpointSite (BreakpointSite *bp_site)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000743{
Greg Clayton07e66e32011-07-20 03:41:06 +0000744 if (m_comm.LocalBreakpointsAreSupported ())
745 {
746 Error error;
Greg Clayton5b882162011-07-21 01:12:01 +0000747 if (!bp_site->IsEnabled())
748 {
749 if (m_comm.SendRequestBreakpoint(true, bp_site->GetLoadAddress()))
750 {
751 bp_site->SetEnabled(true);
752 bp_site->SetType (BreakpointSite::eExternal);
753 }
754 else
755 {
756 error.SetErrorString ("KDP set breakpoint failed");
757 }
758 }
Greg Clayton07e66e32011-07-20 03:41:06 +0000759 return error;
760 }
Greg Claytonf9765ac2011-07-15 03:27:12 +0000761 return EnableSoftwareBreakpoint (bp_site);
762}
763
764Error
Jim Ingham299c0c12013-02-15 02:06:30 +0000765ProcessKDP::DisableBreakpointSite (BreakpointSite *bp_site)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000766{
Greg Clayton07e66e32011-07-20 03:41:06 +0000767 if (m_comm.LocalBreakpointsAreSupported ())
768 {
769 Error error;
Greg Clayton5b882162011-07-21 01:12:01 +0000770 if (bp_site->IsEnabled())
771 {
772 BreakpointSite::Type bp_type = bp_site->GetType();
773 if (bp_type == BreakpointSite::eExternal)
774 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000775 if (m_destroy_in_process && m_comm.IsRunning())
776 {
777 // We are trying to destroy our connection and we are running
Greg Clayton5b882162011-07-21 01:12:01 +0000778 bp_site->SetEnabled(false);
Greg Clayton97d5cf02012-09-25 02:40:06 +0000779 }
Greg Clayton5b882162011-07-21 01:12:01 +0000780 else
Greg Clayton97d5cf02012-09-25 02:40:06 +0000781 {
782 if (m_comm.SendRequestBreakpoint(false, bp_site->GetLoadAddress()))
783 bp_site->SetEnabled(false);
784 else
785 error.SetErrorString ("KDP remove breakpoint failed");
786 }
Greg Clayton5b882162011-07-21 01:12:01 +0000787 }
788 else
789 {
790 error = DisableSoftwareBreakpoint (bp_site);
791 }
792 }
Greg Clayton07e66e32011-07-20 03:41:06 +0000793 return error;
794 }
Greg Claytonf9765ac2011-07-15 03:27:12 +0000795 return DisableSoftwareBreakpoint (bp_site);
796}
797
798Error
Jim Ingham1b5792e2012-12-18 02:03:49 +0000799ProcessKDP::EnableWatchpoint (Watchpoint *wp, bool notify)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000800{
801 Error error;
802 error.SetErrorString ("watchpoints are not suppported in kdp remote debugging");
803 return error;
804}
805
806Error
Jim Ingham1b5792e2012-12-18 02:03:49 +0000807ProcessKDP::DisableWatchpoint (Watchpoint *wp, bool notify)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000808{
809 Error error;
810 error.SetErrorString ("watchpoints are not suppported in kdp remote debugging");
811 return error;
812}
813
814void
815ProcessKDP::Clear()
816{
Greg Claytonf9765ac2011-07-15 03:27:12 +0000817 m_thread_list.Clear();
818}
819
820Error
821ProcessKDP::DoSignal (int signo)
822{
823 Error error;
824 error.SetErrorString ("sending signals is not suppported in kdp remote debugging");
825 return error;
826}
827
828void
829ProcessKDP::Initialize()
830{
Davide Italianoc8d69822015-04-03 04:24:32 +0000831 static std::once_flag g_once_flag;
832
833 std::call_once(g_once_flag, []()
Greg Claytonf9765ac2011-07-15 03:27:12 +0000834 {
Greg Claytonf9765ac2011-07-15 03:27:12 +0000835 PluginManager::RegisterPlugin (GetPluginNameStatic(),
836 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +0000837 CreateInstance,
Bruce Mitchener488c89e2015-04-03 09:13:18 +0000838 DebuggerInitialize);
Davide Italianoc8d69822015-04-03 04:24:32 +0000839
Greg Claytonf9765ac2011-07-15 03:27:12 +0000840 Log::Callbacks log_callbacks = {
841 ProcessKDPLog::DisableLog,
842 ProcessKDPLog::EnableLog,
843 ProcessKDPLog::ListLogCategories
844 };
Davide Italianoc8d69822015-04-03 04:24:32 +0000845
Greg Claytonf9765ac2011-07-15 03:27:12 +0000846 Log::RegisterLogChannel (ProcessKDP::GetPluginNameStatic(), log_callbacks);
Davide Italianoc8d69822015-04-03 04:24:32 +0000847 });
Greg Claytonf9765ac2011-07-15 03:27:12 +0000848}
849
Greg Clayton7f982402013-07-15 22:54:20 +0000850void
851ProcessKDP::DebuggerInitialize (lldb_private::Debugger &debugger)
852{
853 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
854 {
855 const bool is_global_setting = true;
856 PluginManager::CreateSettingForProcessPlugin (debugger,
857 GetGlobalPluginProperties()->GetValueProperties(),
858 ConstString ("Properties for the kdp-remote process plug-in."),
859 is_global_setting);
860 }
861}
862
Greg Claytonf9765ac2011-07-15 03:27:12 +0000863bool
864ProcessKDP::StartAsyncThread ()
865{
Greg Clayton5160ce52013-03-27 23:08:40 +0000866 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
Greg Claytonf9765ac2011-07-15 03:27:12 +0000867
868 if (log)
Greg Clayton7925fbb2012-09-21 16:31:20 +0000869 log->Printf ("ProcessKDP::StartAsyncThread ()");
Zachary Turner39de3112014-09-09 20:54:56 +0000870
Zachary Turneracee96a2014-09-23 18:32:09 +0000871 if (m_async_thread.IsJoinable())
Greg Clayton7925fbb2012-09-21 16:31:20 +0000872 return true;
873
Zachary Turner39de3112014-09-09 20:54:56 +0000874 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.kdp-remote.async>", ProcessKDP::AsyncThread, this, NULL);
Zachary Turneracee96a2014-09-23 18:32:09 +0000875 return m_async_thread.IsJoinable();
Greg Claytonf9765ac2011-07-15 03:27:12 +0000876}
877
878void
879ProcessKDP::StopAsyncThread ()
880{
Greg Clayton5160ce52013-03-27 23:08:40 +0000881 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
Greg Claytonf9765ac2011-07-15 03:27:12 +0000882
883 if (log)
Greg Clayton7925fbb2012-09-21 16:31:20 +0000884 log->Printf ("ProcessKDP::StopAsyncThread ()");
Greg Claytonf9765ac2011-07-15 03:27:12 +0000885
886 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
887
888 // Stop the stdio thread
Zachary Turneracee96a2014-09-23 18:32:09 +0000889 if (m_async_thread.IsJoinable())
Zachary Turner39de3112014-09-09 20:54:56 +0000890 m_async_thread.Join(nullptr);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000891}
892
893
894void *
895ProcessKDP::AsyncThread (void *arg)
896{
897 ProcessKDP *process = (ProcessKDP*) arg;
898
Greg Clayton7925fbb2012-09-21 16:31:20 +0000899 const lldb::pid_t pid = process->GetID();
900
Greg Clayton5160ce52013-03-27 23:08:40 +0000901 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_PROCESS));
Greg Claytonf9765ac2011-07-15 03:27:12 +0000902 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000903 log->Printf ("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64 ") thread starting...", arg, pid);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000904
905 Listener listener ("ProcessKDP::AsyncThread");
906 EventSP event_sp;
907 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
908 eBroadcastBitAsyncThreadShouldExit;
909
Greg Clayton7925fbb2012-09-21 16:31:20 +0000910
Greg Claytonf9765ac2011-07-15 03:27:12 +0000911 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
912 {
Greg Claytonf9765ac2011-07-15 03:27:12 +0000913 bool done = false;
914 while (!done)
915 {
916 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000917 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...",
Greg Clayton7925fbb2012-09-21 16:31:20 +0000918 pid);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000919 if (listener.WaitForEvent (NULL, event_sp))
920 {
Greg Clayton7925fbb2012-09-21 16:31:20 +0000921 uint32_t event_type = event_sp->GetType();
922 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000923 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") Got an event of type: %d...",
Greg Clayton7925fbb2012-09-21 16:31:20 +0000924 pid,
925 event_type);
926
927 // When we are running, poll for 1 second to try and get an exception
928 // to indicate the process has stopped. If we don't get one, check to
929 // make sure no one asked us to exit
930 bool is_running = false;
931 DataExtractor exc_reply_packet;
932 do
Greg Claytonf9765ac2011-07-15 03:27:12 +0000933 {
Greg Claytonf9765ac2011-07-15 03:27:12 +0000934 switch (event_type)
935 {
Greg Clayton7925fbb2012-09-21 16:31:20 +0000936 case eBroadcastBitAsyncContinue:
Greg Claytonf9765ac2011-07-15 03:27:12 +0000937 {
Greg Clayton7925fbb2012-09-21 16:31:20 +0000938 is_running = true;
939 if (process->m_comm.WaitForPacketWithTimeoutMicroSeconds (exc_reply_packet, 1 * USEC_PER_SEC))
Greg Claytonf9765ac2011-07-15 03:27:12 +0000940 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000941 ThreadSP thread_sp (process->GetKernelThread());
Greg Clayton1afa68e2013-04-02 20:32:37 +0000942 if (thread_sp)
943 {
944 lldb::RegisterContextSP reg_ctx_sp (thread_sp->GetRegisterContext());
945 if (reg_ctx_sp)
946 reg_ctx_sp->InvalidateAllRegisters();
947 static_cast<ThreadKDP *>(thread_sp.get())->SetStopInfoFrom_KDP_EXCEPTION (exc_reply_packet);
948 }
Greg Clayton97d5cf02012-09-25 02:40:06 +0000949
Greg Clayton7925fbb2012-09-21 16:31:20 +0000950 // TODO: parse the stop reply packet
Greg Clayton97d5cf02012-09-25 02:40:06 +0000951 is_running = false;
Greg Clayton7925fbb2012-09-21 16:31:20 +0000952 process->SetPrivateState(eStateStopped);
953 }
954 else
955 {
956 // Check to see if we are supposed to exit. There is no way to
957 // interrupt a running kernel, so all we can do is wait for an
958 // exception or detach...
959 if (listener.GetNextEvent(event_sp))
960 {
961 // We got an event, go through the loop again
962 event_type = event_sp->GetType();
963 }
Greg Claytonf9765ac2011-07-15 03:27:12 +0000964 }
965 }
Greg Clayton7925fbb2012-09-21 16:31:20 +0000966 break;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000967
Greg Clayton7925fbb2012-09-21 16:31:20 +0000968 case eBroadcastBitAsyncThreadShouldExit:
969 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000970 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...",
Greg Clayton7925fbb2012-09-21 16:31:20 +0000971 pid);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000972 done = true;
Greg Clayton7925fbb2012-09-21 16:31:20 +0000973 is_running = false;
974 break;
975
976 default:
977 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000978 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") got unknown event 0x%8.8x",
Greg Clayton7925fbb2012-09-21 16:31:20 +0000979 pid,
980 event_type);
981 done = true;
982 is_running = false;
983 break;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000984 }
Greg Clayton7925fbb2012-09-21 16:31:20 +0000985 } while (is_running);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000986 }
987 else
988 {
989 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000990 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false",
Greg Clayton7925fbb2012-09-21 16:31:20 +0000991 pid);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000992 done = true;
993 }
994 }
995 }
996
997 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000998 log->Printf ("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64 ") thread exiting...",
Greg Clayton7925fbb2012-09-21 16:31:20 +0000999 arg,
1000 pid);
Zachary Turner39de3112014-09-09 20:54:56 +00001001
1002 process->m_async_thread.Reset();
Greg Claytonf9765ac2011-07-15 03:27:12 +00001003 return NULL;
1004}
1005
1006
Greg Clayton1d19a2f2012-10-19 22:22:57 +00001007class CommandObjectProcessKDPPacketSend : public CommandObjectParsed
1008{
1009private:
1010
1011 OptionGroupOptions m_option_group;
1012 OptionGroupUInt64 m_command_byte;
1013 OptionGroupString m_packet_data;
1014
1015 virtual Options *
1016 GetOptions ()
1017 {
1018 return &m_option_group;
1019 }
1020
1021
1022public:
1023 CommandObjectProcessKDPPacketSend(CommandInterpreter &interpreter) :
1024 CommandObjectParsed (interpreter,
1025 "process plugin packet send",
1026 "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. ",
1027 NULL),
1028 m_option_group (interpreter),
1029 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),
1030 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)
1031 {
1032 m_option_group.Append (&m_command_byte, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
1033 m_option_group.Append (&m_packet_data , LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
1034 m_option_group.Finalize();
1035 }
1036
1037 ~CommandObjectProcessKDPPacketSend ()
1038 {
1039 }
1040
1041 bool
1042 DoExecute (Args& command, CommandReturnObject &result)
1043 {
1044 const size_t argc = command.GetArgumentCount();
1045 if (argc == 0)
1046 {
1047 if (!m_command_byte.GetOptionValue().OptionWasSet())
1048 {
1049 result.AppendError ("the --command option must be set to a valid command byte");
1050 result.SetStatus (eReturnStatusFailed);
1051 }
1052 else
1053 {
1054 const uint64_t command_byte = m_command_byte.GetOptionValue().GetUInt64Value(0);
1055 if (command_byte > 0 && command_byte <= UINT8_MAX)
1056 {
1057 ProcessKDP *process = (ProcessKDP *)m_interpreter.GetExecutionContext().GetProcessPtr();
1058 if (process)
1059 {
1060 const StateType state = process->GetState();
1061
1062 if (StateIsStoppedState (state, true))
1063 {
1064 std::vector<uint8_t> payload_bytes;
1065 const char *ascii_hex_bytes_cstr = m_packet_data.GetOptionValue().GetCurrentValue();
1066 if (ascii_hex_bytes_cstr && ascii_hex_bytes_cstr[0])
1067 {
1068 StringExtractor extractor(ascii_hex_bytes_cstr);
1069 const size_t ascii_hex_bytes_cstr_len = extractor.GetStringRef().size();
1070 if (ascii_hex_bytes_cstr_len & 1)
1071 {
1072 result.AppendErrorWithFormat ("payload data must contain an even number of ASCII hex characters: '%s'", ascii_hex_bytes_cstr);
1073 result.SetStatus (eReturnStatusFailed);
1074 return false;
1075 }
1076 payload_bytes.resize(ascii_hex_bytes_cstr_len/2);
1077 if (extractor.GetHexBytes(&payload_bytes[0], payload_bytes.size(), '\xdd') != payload_bytes.size())
1078 {
1079 result.AppendErrorWithFormat ("payload data must only contain ASCII hex characters (no spaces or hex prefixes): '%s'", ascii_hex_bytes_cstr);
1080 result.SetStatus (eReturnStatusFailed);
1081 return false;
1082 }
1083 }
1084 Error error;
1085 DataExtractor reply;
1086 process->GetCommunication().SendRawRequest (command_byte,
1087 payload_bytes.empty() ? NULL : payload_bytes.data(),
1088 payload_bytes.size(),
1089 reply,
1090 error);
1091
1092 if (error.Success())
1093 {
1094 // Copy the binary bytes into a hex ASCII string for the result
1095 StreamString packet;
1096 packet.PutBytesAsRawHex8(reply.GetDataStart(),
1097 reply.GetByteSize(),
1098 lldb::endian::InlHostByteOrder(),
1099 lldb::endian::InlHostByteOrder());
1100 result.AppendMessage(packet.GetString().c_str());
1101 result.SetStatus (eReturnStatusSuccessFinishResult);
1102 return true;
1103 }
1104 else
1105 {
1106 const char *error_cstr = error.AsCString();
1107 if (error_cstr && error_cstr[0])
1108 result.AppendError (error_cstr);
1109 else
1110 result.AppendErrorWithFormat ("unknown error 0x%8.8x", error.GetError());
1111 result.SetStatus (eReturnStatusFailed);
1112 return false;
1113 }
1114 }
1115 else
1116 {
1117 result.AppendErrorWithFormat ("process must be stopped in order to send KDP packets, state is %s", StateAsCString (state));
1118 result.SetStatus (eReturnStatusFailed);
1119 }
1120 }
1121 else
1122 {
1123 result.AppendError ("invalid process");
1124 result.SetStatus (eReturnStatusFailed);
1125 }
1126 }
1127 else
1128 {
Daniel Malead01b2952012-11-29 21:49:15 +00001129 result.AppendErrorWithFormat ("invalid command byte 0x%" PRIx64 ", valid values are 1 - 255", command_byte);
Greg Clayton1d19a2f2012-10-19 22:22:57 +00001130 result.SetStatus (eReturnStatusFailed);
1131 }
1132 }
1133 }
1134 else
1135 {
1136 result.AppendErrorWithFormat ("'%s' takes no arguments, only options.", m_cmd_name.c_str());
1137 result.SetStatus (eReturnStatusFailed);
1138 }
1139 return false;
1140 }
1141};
1142
1143class CommandObjectProcessKDPPacket : public CommandObjectMultiword
1144{
1145private:
1146
1147public:
1148 CommandObjectProcessKDPPacket(CommandInterpreter &interpreter) :
1149 CommandObjectMultiword (interpreter,
1150 "process plugin packet",
1151 "Commands that deal with KDP remote packets.",
1152 NULL)
1153 {
1154 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessKDPPacketSend (interpreter)));
1155 }
1156
1157 ~CommandObjectProcessKDPPacket ()
1158 {
1159 }
1160};
1161
1162class CommandObjectMultiwordProcessKDP : public CommandObjectMultiword
1163{
1164public:
1165 CommandObjectMultiwordProcessKDP (CommandInterpreter &interpreter) :
1166 CommandObjectMultiword (interpreter,
1167 "process plugin",
1168 "A set of commands for operating on a ProcessKDP process.",
1169 "process plugin <subcommand> [<subcommand-options>]")
1170 {
1171 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessKDPPacket (interpreter)));
1172 }
1173
1174 ~CommandObjectMultiwordProcessKDP ()
1175 {
1176 }
1177};
1178
1179CommandObject *
1180ProcessKDP::GetPluginCommandObject()
1181{
1182 if (!m_command_sp)
1183 m_command_sp.reset (new CommandObjectMultiwordProcessKDP (GetTarget().GetDebugger().GetCommandInterpreter()));
1184 return m_command_sp.get();
1185}
1186