blob: f01f1ace583cb76bf9fdfa0e066764a5f1191534 [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 Clayton1f746072012-08-29 21:13:06 +000019#include "lldb/Core/Module.h"
Jason Molenda4bd4e7e2012-09-29 04:02:01 +000020#include "lldb/Core/ModuleSpec.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000021#include "lldb/Core/PluginManager.h"
Greg Claytonf9765ac2011-07-15 03:27:12 +000022#include "lldb/Core/State.h"
Zachary Turner0e1d52a2017-03-04 01:28:55 +000023#include "lldb/Utility/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"
Zachary Turner39de3112014-09-09 20:54:56 +000027#include "lldb/Host/ThreadLauncher.h"
Oleksiy Vyalove98628c2015-10-15 23:54:09 +000028#include "lldb/Host/common/TCPSocket.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"
Bruce Mitchener45788152015-07-07 23:59:01 +000040#include "lldb/Utility/StringExtractor.h"
Greg Claytonf9765ac2011-07-15 03:27:12 +000041
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000042#include "llvm/Support/Threading.h"
43
Charles Davis510938e2013-08-27 05:04:57 +000044#define USEC_PER_SEC 1000000
45
Greg Claytonf9765ac2011-07-15 03:27:12 +000046// Project includes
Kate Stoneb9c1b512016-09-06 20:57:50 +000047#include "Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.h"
48#include "Plugins/DynamicLoader/Static/DynamicLoaderStatic.h"
Greg Claytonf9765ac2011-07-15 03:27:12 +000049#include "ProcessKDP.h"
50#include "ProcessKDPLog.h"
Greg Claytona63d08c2011-07-19 03:57:15 +000051#include "ThreadKDP.h"
Greg Claytonf9765ac2011-07-15 03:27:12 +000052
53using namespace lldb;
54using namespace lldb_private;
55
Greg Clayton7f982402013-07-15 22:54:20 +000056namespace {
57
Kate Stoneb9c1b512016-09-06 20:57:50 +000058static PropertyDefinition g_properties[] = {
59 {"packet-timeout", OptionValue::eTypeUInt64, true, 5, NULL, NULL,
60 "Specify the default packet timeout in seconds."},
61 {NULL, OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL}};
Greg Clayton7f982402013-07-15 22:54:20 +000062
Kate Stoneb9c1b512016-09-06 20:57:50 +000063enum { ePropertyPacketTimeout };
Greg Clayton7f982402013-07-15 22:54:20 +000064
Kate Stoneb9c1b512016-09-06 20:57:50 +000065class PluginProperties : public Properties {
66public:
67 static ConstString GetSettingName() {
68 return ProcessKDP::GetPluginNameStatic();
69 }
Greg Clayton7f982402013-07-15 22:54:20 +000070
Kate Stoneb9c1b512016-09-06 20:57:50 +000071 PluginProperties() : Properties() {
72 m_collection_sp.reset(new OptionValueProperties(GetSettingName()));
73 m_collection_sp->Initialize(g_properties);
74 }
Greg Clayton7f982402013-07-15 22:54:20 +000075
Kate Stoneb9c1b512016-09-06 20:57:50 +000076 virtual ~PluginProperties() {}
77
78 uint64_t GetPacketTimeout() {
79 const uint32_t idx = ePropertyPacketTimeout;
80 return m_collection_sp->GetPropertyAtIndexAsUInt64(
81 NULL, idx, g_properties[idx].default_uint_value);
82 }
83};
84
85typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
86
87static const ProcessKDPPropertiesSP &GetGlobalPluginProperties() {
88 static ProcessKDPPropertiesSP g_settings_sp;
89 if (!g_settings_sp)
90 g_settings_sp.reset(new PluginProperties());
91 return g_settings_sp;
92}
93
Greg Clayton7f982402013-07-15 22:54:20 +000094} // anonymous namespace end
95
Andrew Kaylorba4e61d2013-05-07 18:35:34 +000096static const lldb::tid_t g_kernel_tid = 1;
97
Kate Stoneb9c1b512016-09-06 20:57:50 +000098ConstString ProcessKDP::GetPluginNameStatic() {
99 static ConstString g_name("kdp-remote");
100 return g_name;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000101}
102
Kate Stoneb9c1b512016-09-06 20:57:50 +0000103const char *ProcessKDP::GetPluginDescriptionStatic() {
104 return "KDP Remote protocol based debugging plug-in for darwin kernel "
105 "debugging.";
Greg Claytonf9765ac2011-07-15 03:27:12 +0000106}
107
Kate Stoneb9c1b512016-09-06 20:57:50 +0000108void ProcessKDP::Terminate() {
109 PluginManager::UnregisterPlugin(ProcessKDP::CreateInstance);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000110}
111
Kate Stoneb9c1b512016-09-06 20:57:50 +0000112lldb::ProcessSP ProcessKDP::CreateInstance(TargetSP target_sp,
113 ListenerSP listener_sp,
114 const FileSpec *crash_file_path) {
115 lldb::ProcessSP process_sp;
116 if (crash_file_path == NULL)
117 process_sp.reset(new ProcessKDP(target_sp, listener_sp));
118 return process_sp;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000119}
120
Kate Stoneb9c1b512016-09-06 20:57:50 +0000121bool ProcessKDP::CanDebug(TargetSP target_sp, bool plugin_specified_by_name) {
122 if (plugin_specified_by_name)
123 return true;
Greg Clayton596ed242011-10-21 21:41:45 +0000124
Kate Stoneb9c1b512016-09-06 20:57:50 +0000125 // For now we are just making sure the file exists for a given module
126 Module *exe_module = target_sp->GetExecutableModulePointer();
127 if (exe_module) {
128 const llvm::Triple &triple_ref = target_sp->GetArchitecture().GetTriple();
129 switch (triple_ref.getOS()) {
130 case llvm::Triple::Darwin: // Should use "macosx" for desktop and "ios" for
131 // iOS, but accept darwin just in case
132 case llvm::Triple::MacOSX: // For desktop targets
133 case llvm::Triple::IOS: // For arm targets
134 case llvm::Triple::TvOS:
135 case llvm::Triple::WatchOS:
136 if (triple_ref.getVendor() == llvm::Triple::Apple) {
137 ObjectFile *exe_objfile = exe_module->GetObjectFile();
138 if (exe_objfile->GetType() == ObjectFile::eTypeExecutable &&
139 exe_objfile->GetStrata() == ObjectFile::eStrataKernel)
140 return true;
141 }
142 break;
Greg Clayton70512312012-05-08 01:45:38 +0000143
Kate Stoneb9c1b512016-09-06 20:57:50 +0000144 default:
145 break;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000146 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000147 }
148 return false;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000149}
150
151//----------------------------------------------------------------------
152// ProcessKDP constructor
153//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000154ProcessKDP::ProcessKDP(TargetSP target_sp, ListenerSP listener_sp)
155 : Process(target_sp, listener_sp),
156 m_comm("lldb.process.kdp-remote.communication"),
157 m_async_broadcaster(NULL, "lldb.process.kdp-remote.async-broadcaster"),
158 m_dyld_plugin_name(), m_kernel_load_addr(LLDB_INVALID_ADDRESS),
159 m_command_sp(), m_kernel_thread_wp() {
160 m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadShouldExit,
161 "async thread should exit");
162 m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue,
163 "async thread continue");
164 const uint64_t timeout_seconds =
165 GetGlobalPluginProperties()->GetPacketTimeout();
166 if (timeout_seconds > 0)
Pavel Labath5cddd602016-11-02 10:13:54 +0000167 m_comm.SetPacketTimeout(std::chrono::seconds(timeout_seconds));
Greg Claytonf9765ac2011-07-15 03:27:12 +0000168}
169
170//----------------------------------------------------------------------
171// Destructor
172//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000173ProcessKDP::~ProcessKDP() {
174 Clear();
175 // We need to call finalize on the process before destroying ourselves
176 // to make sure all of the broadcaster cleanup goes as planned. If we
177 // destruct this class, then Process::~Process() might have problems
178 // trying to fully destroy the broadcaster.
179 Finalize();
Greg Claytonf9765ac2011-07-15 03:27:12 +0000180}
181
182//----------------------------------------------------------------------
183// PluginInterface
184//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000185lldb_private::ConstString ProcessKDP::GetPluginName() {
186 return GetPluginNameStatic();
Greg Claytonf9765ac2011-07-15 03:27:12 +0000187}
188
Kate Stoneb9c1b512016-09-06 20:57:50 +0000189uint32_t ProcessKDP::GetPluginVersion() { return 1; }
190
Zachary Turner97206d52017-05-12 04:51:55 +0000191Status ProcessKDP::WillLaunch(Module *module) {
192 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000193 error.SetErrorString("launching not supported in kdp-remote plug-in");
194 return error;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000195}
196
Zachary Turner97206d52017-05-12 04:51:55 +0000197Status ProcessKDP::WillAttachToProcessWithID(lldb::pid_t pid) {
198 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000199 error.SetErrorString(
200 "attaching to a by process ID not supported in kdp-remote plug-in");
201 return error;
202}
203
Zachary Turner97206d52017-05-12 04:51:55 +0000204Status ProcessKDP::WillAttachToProcessWithName(const char *process_name,
205 bool wait_for_launch) {
206 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000207 error.SetErrorString(
208 "attaching to a by process name not supported in kdp-remote plug-in");
209 return error;
210}
211
212bool ProcessKDP::GetHostArchitecture(ArchSpec &arch) {
213 uint32_t cpu = m_comm.GetCPUType();
214 if (cpu) {
215 uint32_t sub = m_comm.GetCPUSubtype();
216 arch.SetArchitecture(eArchTypeMachO, cpu, sub);
217 // Leave architecture vendor as unspecified unknown
218 arch.GetTriple().setVendor(llvm::Triple::UnknownVendor);
219 arch.GetTriple().setVendorName(llvm::StringRef());
220 return true;
221 }
222 arch.Clear();
223 return false;
224}
225
Zachary Turner97206d52017-05-12 04:51:55 +0000226Status ProcessKDP::DoConnectRemote(Stream *strm, llvm::StringRef remote_url) {
227 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000228
229 // Don't let any JIT happen when doing KDP as we can't allocate
230 // memory and we don't want to be mucking with threads that might
231 // already be handling exceptions
232 SetCanJIT(false);
233
Greg Clayton3ce7e992016-12-07 23:51:49 +0000234 if (remote_url.empty()) {
235 error.SetErrorStringWithFormat("empty connection URL");
Greg Claytonf9765ac2011-07-15 03:27:12 +0000236 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000237 }
Greg Claytonf9765ac2011-07-15 03:27:12 +0000238
Kate Stoneb9c1b512016-09-06 20:57:50 +0000239 std::unique_ptr<ConnectionFileDescriptor> conn_ap(
240 new ConnectionFileDescriptor());
241 if (conn_ap.get()) {
242 // Only try once for now.
243 // TODO: check if we should be retrying?
244 const uint32_t max_retry_count = 1;
245 for (uint32_t retry_count = 0; retry_count < max_retry_count;
246 ++retry_count) {
247 if (conn_ap->Connect(remote_url, &error) == eConnectionStatusSuccess)
248 break;
249 usleep(100000);
Greg Claytona3706882015-10-28 23:26:59 +0000250 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000251 }
Greg Claytona3706882015-10-28 23:26:59 +0000252
Kate Stoneb9c1b512016-09-06 20:57:50 +0000253 if (conn_ap->IsConnected()) {
254 const TCPSocket &socket =
255 static_cast<const TCPSocket &>(*conn_ap->GetReadObject());
256 const uint16_t reply_port = socket.GetLocalPortNumber();
Greg Clayton7925fbb2012-09-21 16:31:20 +0000257
Kate Stoneb9c1b512016-09-06 20:57:50 +0000258 if (reply_port != 0) {
259 m_comm.SetConnection(conn_ap.release());
Greg Clayton7925fbb2012-09-21 16:31:20 +0000260
Kate Stoneb9c1b512016-09-06 20:57:50 +0000261 if (m_comm.SendRequestReattach(reply_port)) {
262 if (m_comm.SendRequestConnect(reply_port, reply_port,
263 "Greetings from LLDB...")) {
264 m_comm.GetVersion();
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000265
Kate Stoneb9c1b512016-09-06 20:57:50 +0000266 Target &target = GetTarget();
267 ArchSpec kernel_arch;
268 // The host architecture
269 GetHostArchitecture(kernel_arch);
270 ArchSpec target_arch = target.GetArchitecture();
271 // Merge in any unspecified stuff into the target architecture in
272 // case the target arch isn't set at all or incompletely.
273 target_arch.MergeFrom(kernel_arch);
274 target.SetArchitecture(target_arch);
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000275
Kate Stoneb9c1b512016-09-06 20:57:50 +0000276 /* Get the kernel's UUID and load address via KDP_KERNELVERSION
277 * packet. */
278 /* An EFI kdp session has neither UUID nor load address. */
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000279
Kate Stoneb9c1b512016-09-06 20:57:50 +0000280 UUID kernel_uuid = m_comm.GetUUID();
281 addr_t kernel_load_addr = m_comm.GetLoadAddress();
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000282
Kate Stoneb9c1b512016-09-06 20:57:50 +0000283 if (m_comm.RemoteIsEFI()) {
284 // Select an invalid plugin name for the dynamic loader so one
285 // doesn't get used
286 // since EFI does its own manual loading via python scripting
287 static ConstString g_none_dynamic_loader("none");
288 m_dyld_plugin_name = g_none_dynamic_loader;
Greg Claytona3706882015-10-28 23:26:59 +0000289
Kate Stoneb9c1b512016-09-06 20:57:50 +0000290 if (kernel_uuid.IsValid()) {
291 // If EFI passed in a UUID= try to lookup UUID
292 // The slide will not be provided. But the UUID
293 // lookup will be used to launch EFI debug scripts
294 // from the dSYM, that can load all of the symbols.
295 ModuleSpec module_spec;
296 module_spec.GetUUID() = kernel_uuid;
297 module_spec.GetArchitecture() = target.GetArchitecture();
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000298
Kate Stoneb9c1b512016-09-06 20:57:50 +0000299 // Lookup UUID locally, before attempting dsymForUUID like action
300 module_spec.GetSymbolFileSpec() =
301 Symbols::LocateExecutableSymbolFile(module_spec);
302 if (module_spec.GetSymbolFileSpec()) {
303 ModuleSpec executable_module_spec =
304 Symbols::LocateExecutableObjectFile(module_spec);
305 if (executable_module_spec.GetFileSpec().Exists()) {
306 module_spec.GetFileSpec() =
307 executable_module_spec.GetFileSpec();
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000308 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000309 }
310 if (!module_spec.GetSymbolFileSpec() ||
311 !module_spec.GetSymbolFileSpec())
312 Symbols::DownloadObjectAndSymbolFile(module_spec, true);
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000313
Kate Stoneb9c1b512016-09-06 20:57:50 +0000314 if (module_spec.GetFileSpec().Exists()) {
315 ModuleSP module_sp(new Module(module_spec));
316 if (module_sp.get() && module_sp->GetObjectFile()) {
317 // Get the current target executable
318 ModuleSP exe_module_sp(target.GetExecutableModule());
319
320 // Make sure you don't already have the right module loaded
321 // and they will be uniqued
322 if (exe_module_sp.get() != module_sp.get())
323 target.SetExecutableModule(module_sp, false);
324 }
325 }
326 }
327 } else if (m_comm.RemoteIsDarwinKernel()) {
328 m_dyld_plugin_name =
329 DynamicLoaderDarwinKernel::GetPluginNameStatic();
330 if (kernel_load_addr != LLDB_INVALID_ADDRESS) {
331 m_kernel_load_addr = kernel_load_addr;
332 }
333 }
334
335 // Set the thread ID
336 UpdateThreadListIfNeeded();
337 SetID(1);
338 GetThreadList();
339 SetPrivateState(eStateStopped);
340 StreamSP async_strm_sp(target.GetDebugger().GetAsyncOutputStream());
341 if (async_strm_sp) {
342 const char *cstr;
343 if ((cstr = m_comm.GetKernelVersion()) != NULL) {
344 async_strm_sp->Printf("Version: %s\n", cstr);
345 async_strm_sp->Flush();
346 }
347 // if ((cstr = m_comm.GetImagePath ()) != NULL)
348 // {
349 // async_strm_sp->Printf ("Image Path:
350 // %s\n", cstr);
351 // async_strm_sp->Flush();
352 // }
353 }
354 } else {
355 error.SetErrorString("KDP_REATTACH failed");
356 }
357 } else {
358 error.SetErrorString("KDP_REATTACH failed");
359 }
360 } else {
361 error.SetErrorString("invalid reply port from UDP connection");
362 }
363 } else {
364 if (error.Success())
Greg Clayton3ce7e992016-12-07 23:51:49 +0000365 error.SetErrorStringWithFormat("failed to connect to '%s'",
366 remote_url.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000367 }
368 if (error.Fail())
369 m_comm.Disconnect();
370
371 return error;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000372}
373
374//----------------------------------------------------------------------
375// Process Control
376//----------------------------------------------------------------------
Zachary Turner97206d52017-05-12 04:51:55 +0000377Status ProcessKDP::DoLaunch(Module *exe_module,
378 ProcessLaunchInfo &launch_info) {
379 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000380 error.SetErrorString("launching not supported in kdp-remote plug-in");
381 return error;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000382}
383
Zachary Turner97206d52017-05-12 04:51:55 +0000384Status
385ProcessKDP::DoAttachToProcessWithID(lldb::pid_t attach_pid,
386 const ProcessAttachInfo &attach_info) {
387 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000388 error.SetErrorString(
389 "attach to process by ID is not suppported in kdp remote debugging");
390 return error;
Han Ming Ong84647042012-02-25 01:07:38 +0000391}
392
Zachary Turner97206d52017-05-12 04:51:55 +0000393Status
394ProcessKDP::DoAttachToProcessWithName(const char *process_name,
395 const ProcessAttachInfo &attach_info) {
396 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000397 error.SetErrorString(
398 "attach to process by name is not suppported in kdp remote debugging");
399 return error;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000400}
401
Kate Stoneb9c1b512016-09-06 20:57:50 +0000402void ProcessKDP::DidAttach(ArchSpec &process_arch) {
403 Process::DidAttach(process_arch);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000404
Kate Stoneb9c1b512016-09-06 20:57:50 +0000405 Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
406 if (log)
407 log->Printf("ProcessKDP::DidAttach()");
408 if (GetID() != LLDB_INVALID_PROCESS_ID) {
409 GetHostArchitecture(process_arch);
410 }
411}
412
413addr_t ProcessKDP::GetImageInfoAddress() { return m_kernel_load_addr; }
414
415lldb_private::DynamicLoader *ProcessKDP::GetDynamicLoader() {
416 if (m_dyld_ap.get() == NULL)
417 m_dyld_ap.reset(DynamicLoader::FindPlugin(
418 this,
419 m_dyld_plugin_name.IsEmpty() ? NULL : m_dyld_plugin_name.GetCString()));
420 return m_dyld_ap.get();
421}
422
Zachary Turner97206d52017-05-12 04:51:55 +0000423Status ProcessKDP::WillResume() { return Status(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000424
Zachary Turner97206d52017-05-12 04:51:55 +0000425Status ProcessKDP::DoResume() {
426 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000427 Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
428 // Only start the async thread if we try to do any process control
429 if (!m_async_thread.IsJoinable())
430 StartAsyncThread();
431
432 bool resume = false;
433
434 // With KDP there is only one thread we can tell what to do
435 ThreadSP kernel_thread_sp(m_thread_list.FindThreadByProtocolID(g_kernel_tid));
436
437 if (kernel_thread_sp) {
438 const StateType thread_resume_state =
439 kernel_thread_sp->GetTemporaryResumeState();
440
Greg Claytonf9765ac2011-07-15 03:27:12 +0000441 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000442 log->Printf("ProcessKDP::DoResume() thread_resume_state = %s",
443 StateAsCString(thread_resume_state));
444 switch (thread_resume_state) {
445 case eStateSuspended:
446 // Nothing to do here when a thread will stay suspended
447 // we just leave the CPU mask bit set to zero for the thread
448 if (log)
449 log->Printf("ProcessKDP::DoResume() = suspended???");
450 break;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000451
Kate Stoneb9c1b512016-09-06 20:57:50 +0000452 case eStateStepping: {
453 lldb::RegisterContextSP reg_ctx_sp(
454 kernel_thread_sp->GetRegisterContext());
Jason Molenda5e8534e2012-10-03 01:29:34 +0000455
Kate Stoneb9c1b512016-09-06 20:57:50 +0000456 if (reg_ctx_sp) {
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000457 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000458 log->Printf(
459 "ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep (true);");
460 reg_ctx_sp->HardwareSingleStep(true);
461 resume = true;
462 } else {
463 error.SetErrorStringWithFormat(
464 "KDP thread 0x%llx has no register context",
465 kernel_thread_sp->GetID());
466 }
467 } break;
Greg Clayton1afa68e2013-04-02 20:32:37 +0000468
Kate Stoneb9c1b512016-09-06 20:57:50 +0000469 case eStateRunning: {
470 lldb::RegisterContextSP reg_ctx_sp(
471 kernel_thread_sp->GetRegisterContext());
Greg Clayton97d5cf02012-09-25 02:40:06 +0000472
Kate Stoneb9c1b512016-09-06 20:57:50 +0000473 if (reg_ctx_sp) {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000474 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000475 log->Printf("ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep "
476 "(false);");
477 reg_ctx_sp->HardwareSingleStep(false);
478 resume = true;
479 } else {
480 error.SetErrorStringWithFormat(
481 "KDP thread 0x%llx has no register context",
482 kernel_thread_sp->GetID());
483 }
484 } break;
485
486 default:
487 // The only valid thread resume states are listed above
David Blaikiea322f362017-01-06 00:38:06 +0000488 llvm_unreachable("invalid thread resume state");
Greg Clayton7925fbb2012-09-21 16:31:20 +0000489 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000490 }
Greg Claytonf9765ac2011-07-15 03:27:12 +0000491
Kate Stoneb9c1b512016-09-06 20:57:50 +0000492 if (resume) {
Greg Claytonf9765ac2011-07-15 03:27:12 +0000493 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000494 log->Printf("ProcessKDP::DoResume () sending resume");
495
496 if (m_comm.SendRequestResume()) {
497 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue);
498 SetPrivateState(eStateRunning);
499 } else
500 error.SetErrorString("KDP resume failed");
501 } else {
502 error.SetErrorString("kernel thread is suspended");
503 }
504
505 return error;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000506}
507
Kate Stoneb9c1b512016-09-06 20:57:50 +0000508lldb::ThreadSP ProcessKDP::GetKernelThread() {
509 // KDP only tells us about one thread/core. Any other threads will usually
510 // be the ones that are read from memory by the OS plug-ins.
511
512 ThreadSP thread_sp(m_kernel_thread_wp.lock());
513 if (!thread_sp) {
514 thread_sp.reset(new ThreadKDP(*this, g_kernel_tid));
515 m_kernel_thread_wp = thread_sp;
516 }
517 return thread_sp;
518}
519
520bool ProcessKDP::UpdateThreadList(ThreadList &old_thread_list,
521 ThreadList &new_thread_list) {
522 // locker will keep a mutex locked until it goes out of scope
523 Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_THREAD));
Pavel Labath250858a2017-02-06 21:46:22 +0000524 LLDB_LOGV(log, "pid = {0}", GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000525
526 // Even though there is a CPU mask, it doesn't mean we can see each CPU
527 // individually, there is really only one. Lets call this thread 1.
528 ThreadSP thread_sp(
529 old_thread_list.FindThreadByProtocolID(g_kernel_tid, false));
530 if (!thread_sp)
531 thread_sp = GetKernelThread();
532 new_thread_list.AddThread(thread_sp);
533
534 return new_thread_list.GetSize(false) > 0;
535}
536
537void ProcessKDP::RefreshStateAfterStop() {
538 // Let all threads recover from stopping and do any clean up based
539 // on the previous thread state (if any).
540 m_thread_list.RefreshStateAfterStop();
541}
542
Zachary Turner97206d52017-05-12 04:51:55 +0000543Status ProcessKDP::DoHalt(bool &caused_stop) {
544 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000545
546 if (m_comm.IsRunning()) {
547 if (m_destroy_in_process) {
548 // If we are attemping to destroy, we need to not return an error to
549 // Halt or DoDestroy won't get called.
550 // We are also currently running, so send a process stopped event
551 SetPrivateState(eStateStopped);
552 } else {
553 error.SetErrorString("KDP cannot interrupt a running kernel");
554 }
555 }
556 return error;
557}
558
Zachary Turner97206d52017-05-12 04:51:55 +0000559Status ProcessKDP::DoDetach(bool keep_stopped) {
560 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000561 Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
562 if (log)
563 log->Printf("ProcessKDP::DoDetach(keep_stopped = %i)", keep_stopped);
564
565 if (m_comm.IsRunning()) {
566 // We are running and we can't interrupt a running kernel, so we need
567 // to just close the connection to the kernel and hope for the best
568 } else {
569 // If we are going to keep the target stopped, then don't send the
570 // disconnect message.
571 if (!keep_stopped && m_comm.IsConnected()) {
572 const bool success = m_comm.SendRequestDisconnect();
573 if (log) {
574 if (success)
575 log->PutCString(
576 "ProcessKDP::DoDetach() detach packet sent successfully");
577 else
578 log->PutCString(
579 "ProcessKDP::DoDetach() connection channel shutdown failed");
580 }
581 m_comm.Disconnect();
582 }
583 }
584 StopAsyncThread();
585 m_comm.Clear();
586
587 SetPrivateState(eStateDetached);
588 ResumePrivateStateThread();
589
590 // KillDebugserverProcess ();
591 return error;
592}
593
Zachary Turner97206d52017-05-12 04:51:55 +0000594Status ProcessKDP::DoDestroy() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000595 // For KDP there really is no difference between destroy and detach
596 bool keep_stopped = false;
597 return DoDetach(keep_stopped);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000598}
599
600//------------------------------------------------------------------
601// Process Queries
602//------------------------------------------------------------------
603
Kate Stoneb9c1b512016-09-06 20:57:50 +0000604bool ProcessKDP::IsAlive() {
605 return m_comm.IsConnected() && Process::IsAlive();
Greg Claytonf9765ac2011-07-15 03:27:12 +0000606}
607
608//------------------------------------------------------------------
609// Process Memory
610//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000611size_t ProcessKDP::DoReadMemory(addr_t addr, void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +0000612 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000613 uint8_t *data_buffer = (uint8_t *)buf;
614 if (m_comm.IsConnected()) {
615 const size_t max_read_size = 512;
616 size_t total_bytes_read = 0;
Jason Molenda8eb32812014-05-21 23:44:02 +0000617
Kate Stoneb9c1b512016-09-06 20:57:50 +0000618 // Read the requested amount of memory in 512 byte chunks
619 while (total_bytes_read < size) {
620 size_t bytes_to_read_this_request = size - total_bytes_read;
621 if (bytes_to_read_this_request > max_read_size) {
622 bytes_to_read_this_request = max_read_size;
623 }
624 size_t bytes_read = m_comm.SendRequestReadMemory(
625 addr + total_bytes_read, data_buffer + total_bytes_read,
626 bytes_to_read_this_request, error);
627 total_bytes_read += bytes_read;
628 if (error.Fail() || bytes_read == 0) {
Jason Molenda8eb32812014-05-21 23:44:02 +0000629 return total_bytes_read;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000630 }
Jason Molenda8eb32812014-05-21 23:44:02 +0000631 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000632
633 return total_bytes_read;
634 }
635 error.SetErrorString("not connected");
636 return 0;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000637}
638
Kate Stoneb9c1b512016-09-06 20:57:50 +0000639size_t ProcessKDP::DoWriteMemory(addr_t addr, const void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +0000640 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000641 if (m_comm.IsConnected())
642 return m_comm.SendRequestWriteMemory(addr, buf, size, error);
643 error.SetErrorString("not connected");
644 return 0;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000645}
646
Kate Stoneb9c1b512016-09-06 20:57:50 +0000647lldb::addr_t ProcessKDP::DoAllocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +0000648 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000649 error.SetErrorString(
650 "memory allocation not suppported in kdp remote debugging");
651 return LLDB_INVALID_ADDRESS;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000652}
653
Zachary Turner97206d52017-05-12 04:51:55 +0000654Status ProcessKDP::DoDeallocateMemory(lldb::addr_t addr) {
655 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000656 error.SetErrorString(
657 "memory deallocation not suppported in kdp remote debugging");
658 return error;
659}
660
Zachary Turner97206d52017-05-12 04:51:55 +0000661Status ProcessKDP::EnableBreakpointSite(BreakpointSite *bp_site) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000662 if (m_comm.LocalBreakpointsAreSupported()) {
Zachary Turner97206d52017-05-12 04:51:55 +0000663 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000664 if (!bp_site->IsEnabled()) {
665 if (m_comm.SendRequestBreakpoint(true, bp_site->GetLoadAddress())) {
666 bp_site->SetEnabled(true);
667 bp_site->SetType(BreakpointSite::eExternal);
668 } else {
669 error.SetErrorString("KDP set breakpoint failed");
670 }
671 }
Greg Claytonf9765ac2011-07-15 03:27:12 +0000672 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000673 }
674 return EnableSoftwareBreakpoint(bp_site);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000675}
676
Zachary Turner97206d52017-05-12 04:51:55 +0000677Status ProcessKDP::DisableBreakpointSite(BreakpointSite *bp_site) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000678 if (m_comm.LocalBreakpointsAreSupported()) {
Zachary Turner97206d52017-05-12 04:51:55 +0000679 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000680 if (bp_site->IsEnabled()) {
681 BreakpointSite::Type bp_type = bp_site->GetType();
682 if (bp_type == BreakpointSite::eExternal) {
683 if (m_destroy_in_process && m_comm.IsRunning()) {
684 // We are trying to destroy our connection and we are running
685 bp_site->SetEnabled(false);
686 } else {
687 if (m_comm.SendRequestBreakpoint(false, bp_site->GetLoadAddress()))
688 bp_site->SetEnabled(false);
689 else
690 error.SetErrorString("KDP remove breakpoint failed");
Greg Clayton5b882162011-07-21 01:12:01 +0000691 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000692 } else {
693 error = DisableSoftwareBreakpoint(bp_site);
694 }
Greg Clayton07e66e32011-07-20 03:41:06 +0000695 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000696 return error;
697 }
698 return DisableSoftwareBreakpoint(bp_site);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000699}
700
Zachary Turner97206d52017-05-12 04:51:55 +0000701Status ProcessKDP::EnableWatchpoint(Watchpoint *wp, bool notify) {
702 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000703 error.SetErrorString(
704 "watchpoints are not suppported in kdp remote debugging");
705 return error;
706}
707
Zachary Turner97206d52017-05-12 04:51:55 +0000708Status ProcessKDP::DisableWatchpoint(Watchpoint *wp, bool notify) {
709 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000710 error.SetErrorString(
711 "watchpoints are not suppported in kdp remote debugging");
712 return error;
713}
714
715void ProcessKDP::Clear() { m_thread_list.Clear(); }
716
Zachary Turner97206d52017-05-12 04:51:55 +0000717Status ProcessKDP::DoSignal(int signo) {
718 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000719 error.SetErrorString(
720 "sending signals is not suppported in kdp remote debugging");
721 return error;
722}
723
724void ProcessKDP::Initialize() {
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +0000725 static llvm::once_flag g_once_flag;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000726
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +0000727 llvm::call_once(g_once_flag, []() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000728 PluginManager::RegisterPlugin(GetPluginNameStatic(),
729 GetPluginDescriptionStatic(), CreateInstance,
730 DebuggerInitialize);
731
Pavel Labath7b35b782017-02-17 15:08:08 +0000732 ProcessKDPLog::Initialize();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000733 });
734}
735
736void ProcessKDP::DebuggerInitialize(lldb_private::Debugger &debugger) {
737 if (!PluginManager::GetSettingForProcessPlugin(
738 debugger, PluginProperties::GetSettingName())) {
739 const bool is_global_setting = true;
740 PluginManager::CreateSettingForProcessPlugin(
741 debugger, GetGlobalPluginProperties()->GetValueProperties(),
742 ConstString("Properties for the kdp-remote process plug-in."),
743 is_global_setting);
744 }
745}
746
747bool ProcessKDP::StartAsyncThread() {
748 Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
749
750 if (log)
751 log->Printf("ProcessKDP::StartAsyncThread ()");
752
753 if (m_async_thread.IsJoinable())
754 return true;
755
756 m_async_thread = ThreadLauncher::LaunchThread(
757 "<lldb.process.kdp-remote.async>", ProcessKDP::AsyncThread, this, NULL);
758 return m_async_thread.IsJoinable();
759}
760
761void ProcessKDP::StopAsyncThread() {
762 Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
763
764 if (log)
765 log->Printf("ProcessKDP::StopAsyncThread ()");
766
767 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
768
769 // Stop the stdio thread
770 if (m_async_thread.IsJoinable())
771 m_async_thread.Join(nullptr);
772}
773
774void *ProcessKDP::AsyncThread(void *arg) {
775 ProcessKDP *process = (ProcessKDP *)arg;
776
777 const lldb::pid_t pid = process->GetID();
778
779 Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
780 if (log)
781 log->Printf("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64
782 ") thread starting...",
783 arg, pid);
784
785 ListenerSP listener_sp(Listener::MakeListener("ProcessKDP::AsyncThread"));
786 EventSP event_sp;
787 const uint32_t desired_event_mask =
788 eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
789
790 if (listener_sp->StartListeningForEvents(&process->m_async_broadcaster,
791 desired_event_mask) ==
792 desired_event_mask) {
793 bool done = false;
794 while (!done) {
795 if (log)
796 log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
797 ") listener.WaitForEvent (NULL, event_sp)...",
798 pid);
Pavel Labathfafff0c2016-11-30 11:09:47 +0000799 if (listener_sp->GetEvent(event_sp, llvm::None)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000800 uint32_t event_type = event_sp->GetType();
801 if (log)
802 log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
803 ") Got an event of type: %d...",
804 pid, event_type);
805
806 // When we are running, poll for 1 second to try and get an exception
807 // to indicate the process has stopped. If we don't get one, check to
808 // make sure no one asked us to exit
809 bool is_running = false;
810 DataExtractor exc_reply_packet;
811 do {
812 switch (event_type) {
813 case eBroadcastBitAsyncContinue: {
814 is_running = true;
815 if (process->m_comm.WaitForPacketWithTimeoutMicroSeconds(
816 exc_reply_packet, 1 * USEC_PER_SEC)) {
817 ThreadSP thread_sp(process->GetKernelThread());
818 if (thread_sp) {
819 lldb::RegisterContextSP reg_ctx_sp(
820 thread_sp->GetRegisterContext());
821 if (reg_ctx_sp)
822 reg_ctx_sp->InvalidateAllRegisters();
823 static_cast<ThreadKDP *>(thread_sp.get())
824 ->SetStopInfoFrom_KDP_EXCEPTION(exc_reply_packet);
825 }
826
827 // TODO: parse the stop reply packet
828 is_running = false;
829 process->SetPrivateState(eStateStopped);
830 } else {
831 // Check to see if we are supposed to exit. There is no way to
832 // interrupt a running kernel, so all we can do is wait for an
833 // exception or detach...
Pavel Labathfafff0c2016-11-30 11:09:47 +0000834 if (listener_sp->GetEvent(event_sp,
835 std::chrono::microseconds(0))) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000836 // We got an event, go through the loop again
837 event_type = event_sp->GetType();
838 }
Greg Clayton5b882162011-07-21 01:12:01 +0000839 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000840 } break;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000841
Kate Stoneb9c1b512016-09-06 20:57:50 +0000842 case eBroadcastBitAsyncThreadShouldExit:
Greg Claytonf9765ac2011-07-15 03:27:12 +0000843 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000844 log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
845 ") got eBroadcastBitAsyncThreadShouldExit...",
846 pid);
847 done = true;
848 is_running = false;
849 break;
Greg Clayton97d5cf02012-09-25 02:40:06 +0000850
Kate Stoneb9c1b512016-09-06 20:57:50 +0000851 default:
852 if (log)
853 log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
854 ") got unknown event 0x%8.8x",
855 pid, event_type);
856 done = true;
857 is_running = false;
858 break;
859 }
860 } while (is_running);
861 } else {
862 if (log)
863 log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
864 ") listener.WaitForEvent (NULL, event_sp) => false",
865 pid);
866 done = true;
867 }
Greg Claytonf9765ac2011-07-15 03:27:12 +0000868 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000869 }
Zachary Turner39de3112014-09-09 20:54:56 +0000870
Kate Stoneb9c1b512016-09-06 20:57:50 +0000871 if (log)
872 log->Printf("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64
873 ") thread exiting...",
874 arg, pid);
875
876 process->m_async_thread.Reset();
877 return NULL;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000878}
879
Kate Stoneb9c1b512016-09-06 20:57:50 +0000880class CommandObjectProcessKDPPacketSend : public CommandObjectParsed {
Greg Clayton1d19a2f2012-10-19 22:22:57 +0000881private:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000882 OptionGroupOptions m_option_group;
883 OptionGroupUInt64 m_command_byte;
884 OptionGroupString m_packet_data;
885
886 virtual Options *GetOptions() { return &m_option_group; }
Greg Clayton1d19a2f2012-10-19 22:22:57 +0000887
888public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000889 CommandObjectProcessKDPPacketSend(CommandInterpreter &interpreter)
890 : CommandObjectParsed(interpreter, "process plugin packet send",
891 "Send a custom packet through the KDP protocol by "
892 "specifying the command byte and the packet "
893 "payload data. A packet will be sent with a "
894 "correct header and payload, and the raw result "
895 "bytes will be displayed as a string value. ",
896 NULL),
Todd Fialae1cfbc72016-08-11 23:51:28 +0000897 m_option_group(),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000898 m_command_byte(LLDB_OPT_SET_1, true, "command", 'c', 0, eArgTypeNone,
899 "Specify the command byte to use when sending the KDP "
900 "request packet.",
901 0),
902 m_packet_data(LLDB_OPT_SET_1, false, "payload", 'p', 0, eArgTypeNone,
903 "Specify packet payload bytes as a hex ASCII string with "
904 "no spaces or hex prefixes.",
905 NULL) {
906 m_option_group.Append(&m_command_byte, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
907 m_option_group.Append(&m_packet_data, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
908 m_option_group.Finalize();
909 }
910
911 ~CommandObjectProcessKDPPacketSend() {}
912
913 bool DoExecute(Args &command, CommandReturnObject &result) {
914 const size_t argc = command.GetArgumentCount();
915 if (argc == 0) {
916 if (!m_command_byte.GetOptionValue().OptionWasSet()) {
917 result.AppendError(
918 "the --command option must be set to a valid command byte");
919 result.SetStatus(eReturnStatusFailed);
920 } else {
921 const uint64_t command_byte =
922 m_command_byte.GetOptionValue().GetUInt64Value(0);
923 if (command_byte > 0 && command_byte <= UINT8_MAX) {
924 ProcessKDP *process =
925 (ProcessKDP *)m_interpreter.GetExecutionContext().GetProcessPtr();
926 if (process) {
927 const StateType state = process->GetState();
928
929 if (StateIsStoppedState(state, true)) {
930 std::vector<uint8_t> payload_bytes;
931 const char *ascii_hex_bytes_cstr =
932 m_packet_data.GetOptionValue().GetCurrentValue();
933 if (ascii_hex_bytes_cstr && ascii_hex_bytes_cstr[0]) {
934 StringExtractor extractor(ascii_hex_bytes_cstr);
935 const size_t ascii_hex_bytes_cstr_len =
936 extractor.GetStringRef().size();
937 if (ascii_hex_bytes_cstr_len & 1) {
938 result.AppendErrorWithFormat("payload data must contain an "
939 "even number of ASCII hex "
940 "characters: '%s'",
941 ascii_hex_bytes_cstr);
942 result.SetStatus(eReturnStatusFailed);
943 return false;
Greg Clayton1d19a2f2012-10-19 22:22:57 +0000944 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000945 payload_bytes.resize(ascii_hex_bytes_cstr_len / 2);
946 if (extractor.GetHexBytes(payload_bytes, '\xdd') !=
947 payload_bytes.size()) {
948 result.AppendErrorWithFormat("payload data must only contain "
949 "ASCII hex characters (no "
950 "spaces or hex prefixes): '%s'",
951 ascii_hex_bytes_cstr);
952 result.SetStatus(eReturnStatusFailed);
953 return false;
954 }
955 }
Zachary Turner97206d52017-05-12 04:51:55 +0000956 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000957 DataExtractor reply;
958 process->GetCommunication().SendRawRequest(
959 command_byte,
960 payload_bytes.empty() ? NULL : payload_bytes.data(),
961 payload_bytes.size(), reply, error);
962
963 if (error.Success()) {
964 // Copy the binary bytes into a hex ASCII string for the result
965 StreamString packet;
966 packet.PutBytesAsRawHex8(
967 reply.GetDataStart(), reply.GetByteSize(),
968 endian::InlHostByteOrder(), endian::InlHostByteOrder());
Zachary Turnerc1564272016-11-16 21:15:24 +0000969 result.AppendMessage(packet.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000970 result.SetStatus(eReturnStatusSuccessFinishResult);
971 return true;
972 } else {
973 const char *error_cstr = error.AsCString();
974 if (error_cstr && error_cstr[0])
975 result.AppendError(error_cstr);
Greg Clayton1d19a2f2012-10-19 22:22:57 +0000976 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000977 result.AppendErrorWithFormat("unknown error 0x%8.8x",
978 error.GetError());
979 result.SetStatus(eReturnStatusFailed);
980 return false;
981 }
982 } else {
983 result.AppendErrorWithFormat("process must be stopped in order "
984 "to send KDP packets, state is %s",
985 StateAsCString(state));
986 result.SetStatus(eReturnStatusFailed);
Greg Clayton1d19a2f2012-10-19 22:22:57 +0000987 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000988 } else {
989 result.AppendError("invalid process");
990 result.SetStatus(eReturnStatusFailed);
991 }
992 } else {
993 result.AppendErrorWithFormat("invalid command byte 0x%" PRIx64
994 ", valid values are 1 - 255",
995 command_byte);
996 result.SetStatus(eReturnStatusFailed);
Greg Clayton1d19a2f2012-10-19 22:22:57 +0000997 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000998 }
999 } else {
1000 result.AppendErrorWithFormat("'%s' takes no arguments, only options.",
1001 m_cmd_name.c_str());
1002 result.SetStatus(eReturnStatusFailed);
Greg Clayton1d19a2f2012-10-19 22:22:57 +00001003 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001004 return false;
1005 }
Greg Clayton1d19a2f2012-10-19 22:22:57 +00001006};
1007
Kate Stoneb9c1b512016-09-06 20:57:50 +00001008class CommandObjectProcessKDPPacket : public CommandObjectMultiword {
Greg Clayton1d19a2f2012-10-19 22:22:57 +00001009private:
Greg Clayton1d19a2f2012-10-19 22:22:57 +00001010public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001011 CommandObjectProcessKDPPacket(CommandInterpreter &interpreter)
1012 : CommandObjectMultiword(interpreter, "process plugin packet",
1013 "Commands that deal with KDP remote packets.",
1014 NULL) {
1015 LoadSubCommand(
1016 "send",
1017 CommandObjectSP(new CommandObjectProcessKDPPacketSend(interpreter)));
1018 }
1019
1020 ~CommandObjectProcessKDPPacket() {}
Greg Clayton1d19a2f2012-10-19 22:22:57 +00001021};
1022
Kate Stoneb9c1b512016-09-06 20:57:50 +00001023class CommandObjectMultiwordProcessKDP : public CommandObjectMultiword {
Greg Clayton1d19a2f2012-10-19 22:22:57 +00001024public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001025 CommandObjectMultiwordProcessKDP(CommandInterpreter &interpreter)
1026 : CommandObjectMultiword(
1027 interpreter, "process plugin",
1028 "Commands for operating on a ProcessKDP process.",
1029 "process plugin <subcommand> [<subcommand-options>]") {
1030 LoadSubCommand("packet", CommandObjectSP(new CommandObjectProcessKDPPacket(
1031 interpreter)));
1032 }
1033
1034 ~CommandObjectMultiwordProcessKDP() {}
Greg Clayton1d19a2f2012-10-19 22:22:57 +00001035};
1036
Kate Stoneb9c1b512016-09-06 20:57:50 +00001037CommandObject *ProcessKDP::GetPluginCommandObject() {
1038 if (!m_command_sp)
1039 m_command_sp.reset(new CommandObjectMultiwordProcessKDP(
1040 GetTarget().GetDebugger().GetCommandInterpreter()));
1041 return m_command_sp.get();
Greg Clayton1d19a2f2012-10-19 22:22:57 +00001042}