blob: bc738d748a1545f73b9f98c312715bfccac8764d [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"
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"
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
Charles Davis510938e2013-08-27 05:04:57 +000042#define USEC_PER_SEC 1000000
43
Greg Claytonf9765ac2011-07-15 03:27:12 +000044// Project includes
Kate Stoneb9c1b512016-09-06 20:57:50 +000045#include "Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.h"
46#include "Plugins/DynamicLoader/Static/DynamicLoaderStatic.h"
Greg Claytonf9765ac2011-07-15 03:27:12 +000047#include "ProcessKDP.h"
48#include "ProcessKDPLog.h"
Greg Claytona63d08c2011-07-19 03:57:15 +000049#include "ThreadKDP.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
Kate Stoneb9c1b512016-09-06 20:57:50 +000056static PropertyDefinition g_properties[] = {
57 {"packet-timeout", OptionValue::eTypeUInt64, true, 5, NULL, NULL,
58 "Specify the default packet timeout in seconds."},
59 {NULL, OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL}};
Greg Clayton7f982402013-07-15 22:54:20 +000060
Kate Stoneb9c1b512016-09-06 20:57:50 +000061enum { ePropertyPacketTimeout };
Greg Clayton7f982402013-07-15 22:54:20 +000062
Kate Stoneb9c1b512016-09-06 20:57:50 +000063class PluginProperties : public Properties {
64public:
65 static ConstString GetSettingName() {
66 return ProcessKDP::GetPluginNameStatic();
67 }
Greg Clayton7f982402013-07-15 22:54:20 +000068
Kate Stoneb9c1b512016-09-06 20:57:50 +000069 PluginProperties() : Properties() {
70 m_collection_sp.reset(new OptionValueProperties(GetSettingName()));
71 m_collection_sp->Initialize(g_properties);
72 }
Greg Clayton7f982402013-07-15 22:54:20 +000073
Kate Stoneb9c1b512016-09-06 20:57:50 +000074 virtual ~PluginProperties() {}
75
76 uint64_t GetPacketTimeout() {
77 const uint32_t idx = ePropertyPacketTimeout;
78 return m_collection_sp->GetPropertyAtIndexAsUInt64(
79 NULL, idx, g_properties[idx].default_uint_value);
80 }
81};
82
83typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
84
85static const ProcessKDPPropertiesSP &GetGlobalPluginProperties() {
86 static ProcessKDPPropertiesSP g_settings_sp;
87 if (!g_settings_sp)
88 g_settings_sp.reset(new PluginProperties());
89 return g_settings_sp;
90}
91
Greg Clayton7f982402013-07-15 22:54:20 +000092} // anonymous namespace end
93
Andrew Kaylorba4e61d2013-05-07 18:35:34 +000094static const lldb::tid_t g_kernel_tid = 1;
95
Kate Stoneb9c1b512016-09-06 20:57:50 +000096ConstString ProcessKDP::GetPluginNameStatic() {
97 static ConstString g_name("kdp-remote");
98 return g_name;
Greg Claytonf9765ac2011-07-15 03:27:12 +000099}
100
Kate Stoneb9c1b512016-09-06 20:57:50 +0000101const char *ProcessKDP::GetPluginDescriptionStatic() {
102 return "KDP Remote protocol based debugging plug-in for darwin kernel "
103 "debugging.";
Greg Claytonf9765ac2011-07-15 03:27:12 +0000104}
105
Kate Stoneb9c1b512016-09-06 20:57:50 +0000106void ProcessKDP::Terminate() {
107 PluginManager::UnregisterPlugin(ProcessKDP::CreateInstance);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000108}
109
Kate Stoneb9c1b512016-09-06 20:57:50 +0000110lldb::ProcessSP ProcessKDP::CreateInstance(TargetSP target_sp,
111 ListenerSP listener_sp,
112 const FileSpec *crash_file_path) {
113 lldb::ProcessSP process_sp;
114 if (crash_file_path == NULL)
115 process_sp.reset(new ProcessKDP(target_sp, listener_sp));
116 return process_sp;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000117}
118
Kate Stoneb9c1b512016-09-06 20:57:50 +0000119bool ProcessKDP::CanDebug(TargetSP target_sp, bool plugin_specified_by_name) {
120 if (plugin_specified_by_name)
121 return true;
Greg Clayton596ed242011-10-21 21:41:45 +0000122
Kate Stoneb9c1b512016-09-06 20:57:50 +0000123 // For now we are just making sure the file exists for a given module
124 Module *exe_module = target_sp->GetExecutableModulePointer();
125 if (exe_module) {
126 const llvm::Triple &triple_ref = target_sp->GetArchitecture().GetTriple();
127 switch (triple_ref.getOS()) {
128 case llvm::Triple::Darwin: // Should use "macosx" for desktop and "ios" for
129 // iOS, but accept darwin just in case
130 case llvm::Triple::MacOSX: // For desktop targets
131 case llvm::Triple::IOS: // For arm targets
132 case llvm::Triple::TvOS:
133 case llvm::Triple::WatchOS:
134 if (triple_ref.getVendor() == llvm::Triple::Apple) {
135 ObjectFile *exe_objfile = exe_module->GetObjectFile();
136 if (exe_objfile->GetType() == ObjectFile::eTypeExecutable &&
137 exe_objfile->GetStrata() == ObjectFile::eStrataKernel)
138 return true;
139 }
140 break;
Greg Clayton70512312012-05-08 01:45:38 +0000141
Kate Stoneb9c1b512016-09-06 20:57:50 +0000142 default:
143 break;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000144 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000145 }
146 return false;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000147}
148
149//----------------------------------------------------------------------
150// ProcessKDP constructor
151//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000152ProcessKDP::ProcessKDP(TargetSP target_sp, ListenerSP listener_sp)
153 : Process(target_sp, listener_sp),
154 m_comm("lldb.process.kdp-remote.communication"),
155 m_async_broadcaster(NULL, "lldb.process.kdp-remote.async-broadcaster"),
156 m_dyld_plugin_name(), m_kernel_load_addr(LLDB_INVALID_ADDRESS),
157 m_command_sp(), m_kernel_thread_wp() {
158 m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadShouldExit,
159 "async thread should exit");
160 m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue,
161 "async thread continue");
162 const uint64_t timeout_seconds =
163 GetGlobalPluginProperties()->GetPacketTimeout();
164 if (timeout_seconds > 0)
Pavel Labath5cddd602016-11-02 10:13:54 +0000165 m_comm.SetPacketTimeout(std::chrono::seconds(timeout_seconds));
Greg Claytonf9765ac2011-07-15 03:27:12 +0000166}
167
168//----------------------------------------------------------------------
169// Destructor
170//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000171ProcessKDP::~ProcessKDP() {
172 Clear();
173 // We need to call finalize on the process before destroying ourselves
174 // to make sure all of the broadcaster cleanup goes as planned. If we
175 // destruct this class, then Process::~Process() might have problems
176 // trying to fully destroy the broadcaster.
177 Finalize();
Greg Claytonf9765ac2011-07-15 03:27:12 +0000178}
179
180//----------------------------------------------------------------------
181// PluginInterface
182//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000183lldb_private::ConstString ProcessKDP::GetPluginName() {
184 return GetPluginNameStatic();
Greg Claytonf9765ac2011-07-15 03:27:12 +0000185}
186
Kate Stoneb9c1b512016-09-06 20:57:50 +0000187uint32_t ProcessKDP::GetPluginVersion() { return 1; }
188
189Error ProcessKDP::WillLaunch(Module *module) {
190 Error error;
191 error.SetErrorString("launching not supported in kdp-remote plug-in");
192 return error;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000193}
194
Kate Stoneb9c1b512016-09-06 20:57:50 +0000195Error ProcessKDP::WillAttachToProcessWithID(lldb::pid_t pid) {
196 Error error;
197 error.SetErrorString(
198 "attaching to a by process ID not supported in kdp-remote plug-in");
199 return error;
200}
201
202Error ProcessKDP::WillAttachToProcessWithName(const char *process_name,
203 bool wait_for_launch) {
204 Error error;
205 error.SetErrorString(
206 "attaching to a by process name not supported in kdp-remote plug-in");
207 return error;
208}
209
210bool ProcessKDP::GetHostArchitecture(ArchSpec &arch) {
211 uint32_t cpu = m_comm.GetCPUType();
212 if (cpu) {
213 uint32_t sub = m_comm.GetCPUSubtype();
214 arch.SetArchitecture(eArchTypeMachO, cpu, sub);
215 // Leave architecture vendor as unspecified unknown
216 arch.GetTriple().setVendor(llvm::Triple::UnknownVendor);
217 arch.GetTriple().setVendorName(llvm::StringRef());
218 return true;
219 }
220 arch.Clear();
221 return false;
222}
223
224Error ProcessKDP::DoConnectRemote(Stream *strm, const char *remote_url) {
225 Error error;
226
227 // Don't let any JIT happen when doing KDP as we can't allocate
228 // memory and we don't want to be mucking with threads that might
229 // already be handling exceptions
230 SetCanJIT(false);
231
232 if (remote_url == NULL || remote_url[0] == '\0') {
233 error.SetErrorStringWithFormat("invalid connection URL '%s'", remote_url);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000234 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000235 }
Greg Claytonf9765ac2011-07-15 03:27:12 +0000236
Kate Stoneb9c1b512016-09-06 20:57:50 +0000237 std::unique_ptr<ConnectionFileDescriptor> conn_ap(
238 new ConnectionFileDescriptor());
239 if (conn_ap.get()) {
240 // Only try once for now.
241 // TODO: check if we should be retrying?
242 const uint32_t max_retry_count = 1;
243 for (uint32_t retry_count = 0; retry_count < max_retry_count;
244 ++retry_count) {
245 if (conn_ap->Connect(remote_url, &error) == eConnectionStatusSuccess)
246 break;
247 usleep(100000);
Greg Claytona3706882015-10-28 23:26:59 +0000248 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000249 }
Greg Claytona3706882015-10-28 23:26:59 +0000250
Kate Stoneb9c1b512016-09-06 20:57:50 +0000251 if (conn_ap->IsConnected()) {
252 const TCPSocket &socket =
253 static_cast<const TCPSocket &>(*conn_ap->GetReadObject());
254 const uint16_t reply_port = socket.GetLocalPortNumber();
Greg Clayton7925fbb2012-09-21 16:31:20 +0000255
Kate Stoneb9c1b512016-09-06 20:57:50 +0000256 if (reply_port != 0) {
257 m_comm.SetConnection(conn_ap.release());
Greg Clayton7925fbb2012-09-21 16:31:20 +0000258
Kate Stoneb9c1b512016-09-06 20:57:50 +0000259 if (m_comm.SendRequestReattach(reply_port)) {
260 if (m_comm.SendRequestConnect(reply_port, reply_port,
261 "Greetings from LLDB...")) {
262 m_comm.GetVersion();
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000263
Kate Stoneb9c1b512016-09-06 20:57:50 +0000264 Target &target = GetTarget();
265 ArchSpec kernel_arch;
266 // The host architecture
267 GetHostArchitecture(kernel_arch);
268 ArchSpec target_arch = target.GetArchitecture();
269 // Merge in any unspecified stuff into the target architecture in
270 // case the target arch isn't set at all or incompletely.
271 target_arch.MergeFrom(kernel_arch);
272 target.SetArchitecture(target_arch);
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000273
Kate Stoneb9c1b512016-09-06 20:57:50 +0000274 /* Get the kernel's UUID and load address via KDP_KERNELVERSION
275 * packet. */
276 /* An EFI kdp session has neither UUID nor load address. */
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000277
Kate Stoneb9c1b512016-09-06 20:57:50 +0000278 UUID kernel_uuid = m_comm.GetUUID();
279 addr_t kernel_load_addr = m_comm.GetLoadAddress();
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000280
Kate Stoneb9c1b512016-09-06 20:57:50 +0000281 if (m_comm.RemoteIsEFI()) {
282 // Select an invalid plugin name for the dynamic loader so one
283 // doesn't get used
284 // since EFI does its own manual loading via python scripting
285 static ConstString g_none_dynamic_loader("none");
286 m_dyld_plugin_name = g_none_dynamic_loader;
Greg Claytona3706882015-10-28 23:26:59 +0000287
Kate Stoneb9c1b512016-09-06 20:57:50 +0000288 if (kernel_uuid.IsValid()) {
289 // If EFI passed in a UUID= try to lookup UUID
290 // The slide will not be provided. But the UUID
291 // lookup will be used to launch EFI debug scripts
292 // from the dSYM, that can load all of the symbols.
293 ModuleSpec module_spec;
294 module_spec.GetUUID() = kernel_uuid;
295 module_spec.GetArchitecture() = target.GetArchitecture();
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000296
Kate Stoneb9c1b512016-09-06 20:57:50 +0000297 // Lookup UUID locally, before attempting dsymForUUID like action
298 module_spec.GetSymbolFileSpec() =
299 Symbols::LocateExecutableSymbolFile(module_spec);
300 if (module_spec.GetSymbolFileSpec()) {
301 ModuleSpec executable_module_spec =
302 Symbols::LocateExecutableObjectFile(module_spec);
303 if (executable_module_spec.GetFileSpec().Exists()) {
304 module_spec.GetFileSpec() =
305 executable_module_spec.GetFileSpec();
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000306 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000307 }
308 if (!module_spec.GetSymbolFileSpec() ||
309 !module_spec.GetSymbolFileSpec())
310 Symbols::DownloadObjectAndSymbolFile(module_spec, true);
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000311
Kate Stoneb9c1b512016-09-06 20:57:50 +0000312 if (module_spec.GetFileSpec().Exists()) {
313 ModuleSP module_sp(new Module(module_spec));
314 if (module_sp.get() && module_sp->GetObjectFile()) {
315 // Get the current target executable
316 ModuleSP exe_module_sp(target.GetExecutableModule());
317
318 // Make sure you don't already have the right module loaded
319 // and they will be uniqued
320 if (exe_module_sp.get() != module_sp.get())
321 target.SetExecutableModule(module_sp, false);
322 }
323 }
324 }
325 } else if (m_comm.RemoteIsDarwinKernel()) {
326 m_dyld_plugin_name =
327 DynamicLoaderDarwinKernel::GetPluginNameStatic();
328 if (kernel_load_addr != LLDB_INVALID_ADDRESS) {
329 m_kernel_load_addr = kernel_load_addr;
330 }
331 }
332
333 // Set the thread ID
334 UpdateThreadListIfNeeded();
335 SetID(1);
336 GetThreadList();
337 SetPrivateState(eStateStopped);
338 StreamSP async_strm_sp(target.GetDebugger().GetAsyncOutputStream());
339 if (async_strm_sp) {
340 const char *cstr;
341 if ((cstr = m_comm.GetKernelVersion()) != NULL) {
342 async_strm_sp->Printf("Version: %s\n", cstr);
343 async_strm_sp->Flush();
344 }
345 // if ((cstr = m_comm.GetImagePath ()) != NULL)
346 // {
347 // async_strm_sp->Printf ("Image Path:
348 // %s\n", cstr);
349 // async_strm_sp->Flush();
350 // }
351 }
352 } else {
353 error.SetErrorString("KDP_REATTACH failed");
354 }
355 } else {
356 error.SetErrorString("KDP_REATTACH failed");
357 }
358 } else {
359 error.SetErrorString("invalid reply port from UDP connection");
360 }
361 } else {
362 if (error.Success())
363 error.SetErrorStringWithFormat("failed to connect to '%s'", remote_url);
364 }
365 if (error.Fail())
366 m_comm.Disconnect();
367
368 return error;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000369}
370
371//----------------------------------------------------------------------
372// Process Control
373//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000374Error ProcessKDP::DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info) {
375 Error error;
376 error.SetErrorString("launching not supported in kdp-remote plug-in");
377 return error;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000378}
379
Kate Stoneb9c1b512016-09-06 20:57:50 +0000380Error ProcessKDP::DoAttachToProcessWithID(
381 lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) {
382 Error error;
383 error.SetErrorString(
384 "attach to process by ID is not suppported in kdp remote debugging");
385 return error;
Han Ming Ong84647042012-02-25 01:07:38 +0000386}
387
Kate Stoneb9c1b512016-09-06 20:57:50 +0000388Error ProcessKDP::DoAttachToProcessWithName(
389 const char *process_name, const ProcessAttachInfo &attach_info) {
390 Error error;
391 error.SetErrorString(
392 "attach to process by name is not suppported in kdp remote debugging");
393 return error;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000394}
395
Kate Stoneb9c1b512016-09-06 20:57:50 +0000396void ProcessKDP::DidAttach(ArchSpec &process_arch) {
397 Process::DidAttach(process_arch);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000398
Kate Stoneb9c1b512016-09-06 20:57:50 +0000399 Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
400 if (log)
401 log->Printf("ProcessKDP::DidAttach()");
402 if (GetID() != LLDB_INVALID_PROCESS_ID) {
403 GetHostArchitecture(process_arch);
404 }
405}
406
407addr_t ProcessKDP::GetImageInfoAddress() { return m_kernel_load_addr; }
408
409lldb_private::DynamicLoader *ProcessKDP::GetDynamicLoader() {
410 if (m_dyld_ap.get() == NULL)
411 m_dyld_ap.reset(DynamicLoader::FindPlugin(
412 this,
413 m_dyld_plugin_name.IsEmpty() ? NULL : m_dyld_plugin_name.GetCString()));
414 return m_dyld_ap.get();
415}
416
Mehdi Aminic1edf562016-11-11 04:29:25 +0000417Error ProcessKDP::WillResume() { return Error(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000418
419Error ProcessKDP::DoResume() {
420 Error error;
421 Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
422 // Only start the async thread if we try to do any process control
423 if (!m_async_thread.IsJoinable())
424 StartAsyncThread();
425
426 bool resume = false;
427
428 // With KDP there is only one thread we can tell what to do
429 ThreadSP kernel_thread_sp(m_thread_list.FindThreadByProtocolID(g_kernel_tid));
430
431 if (kernel_thread_sp) {
432 const StateType thread_resume_state =
433 kernel_thread_sp->GetTemporaryResumeState();
434
Greg Claytonf9765ac2011-07-15 03:27:12 +0000435 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000436 log->Printf("ProcessKDP::DoResume() thread_resume_state = %s",
437 StateAsCString(thread_resume_state));
438 switch (thread_resume_state) {
439 case eStateSuspended:
440 // Nothing to do here when a thread will stay suspended
441 // we just leave the CPU mask bit set to zero for the thread
442 if (log)
443 log->Printf("ProcessKDP::DoResume() = suspended???");
444 break;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000445
Kate Stoneb9c1b512016-09-06 20:57:50 +0000446 case eStateStepping: {
447 lldb::RegisterContextSP reg_ctx_sp(
448 kernel_thread_sp->GetRegisterContext());
Jason Molenda5e8534e2012-10-03 01:29:34 +0000449
Kate Stoneb9c1b512016-09-06 20:57:50 +0000450 if (reg_ctx_sp) {
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000451 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000452 log->Printf(
453 "ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep (true);");
454 reg_ctx_sp->HardwareSingleStep(true);
455 resume = true;
456 } else {
457 error.SetErrorStringWithFormat(
458 "KDP thread 0x%llx has no register context",
459 kernel_thread_sp->GetID());
460 }
461 } break;
Greg Clayton1afa68e2013-04-02 20:32:37 +0000462
Kate Stoneb9c1b512016-09-06 20:57:50 +0000463 case eStateRunning: {
464 lldb::RegisterContextSP reg_ctx_sp(
465 kernel_thread_sp->GetRegisterContext());
Greg Clayton97d5cf02012-09-25 02:40:06 +0000466
Kate Stoneb9c1b512016-09-06 20:57:50 +0000467 if (reg_ctx_sp) {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000468 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000469 log->Printf("ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep "
470 "(false);");
471 reg_ctx_sp->HardwareSingleStep(false);
472 resume = true;
473 } else {
474 error.SetErrorStringWithFormat(
475 "KDP thread 0x%llx has no register context",
476 kernel_thread_sp->GetID());
477 }
478 } break;
479
480 default:
481 // The only valid thread resume states are listed above
482 assert(!"invalid thread resume state");
483 break;
Greg Clayton7925fbb2012-09-21 16:31:20 +0000484 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000485 }
Greg Claytonf9765ac2011-07-15 03:27:12 +0000486
Kate Stoneb9c1b512016-09-06 20:57:50 +0000487 if (resume) {
Greg Claytonf9765ac2011-07-15 03:27:12 +0000488 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000489 log->Printf("ProcessKDP::DoResume () sending resume");
490
491 if (m_comm.SendRequestResume()) {
492 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue);
493 SetPrivateState(eStateRunning);
494 } else
495 error.SetErrorString("KDP resume failed");
496 } else {
497 error.SetErrorString("kernel thread is suspended");
498 }
499
500 return error;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000501}
502
Kate Stoneb9c1b512016-09-06 20:57:50 +0000503lldb::ThreadSP ProcessKDP::GetKernelThread() {
504 // KDP only tells us about one thread/core. Any other threads will usually
505 // be the ones that are read from memory by the OS plug-ins.
506
507 ThreadSP thread_sp(m_kernel_thread_wp.lock());
508 if (!thread_sp) {
509 thread_sp.reset(new ThreadKDP(*this, g_kernel_tid));
510 m_kernel_thread_wp = thread_sp;
511 }
512 return thread_sp;
513}
514
515bool ProcessKDP::UpdateThreadList(ThreadList &old_thread_list,
516 ThreadList &new_thread_list) {
517 // locker will keep a mutex locked until it goes out of scope
518 Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_THREAD));
519 if (log && log->GetMask().Test(KDP_LOG_VERBOSE))
520 log->Printf("ProcessKDP::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
521
522 // Even though there is a CPU mask, it doesn't mean we can see each CPU
523 // individually, there is really only one. Lets call this thread 1.
524 ThreadSP thread_sp(
525 old_thread_list.FindThreadByProtocolID(g_kernel_tid, false));
526 if (!thread_sp)
527 thread_sp = GetKernelThread();
528 new_thread_list.AddThread(thread_sp);
529
530 return new_thread_list.GetSize(false) > 0;
531}
532
533void ProcessKDP::RefreshStateAfterStop() {
534 // Let all threads recover from stopping and do any clean up based
535 // on the previous thread state (if any).
536 m_thread_list.RefreshStateAfterStop();
537}
538
539Error ProcessKDP::DoHalt(bool &caused_stop) {
540 Error error;
541
542 if (m_comm.IsRunning()) {
543 if (m_destroy_in_process) {
544 // If we are attemping to destroy, we need to not return an error to
545 // Halt or DoDestroy won't get called.
546 // We are also currently running, so send a process stopped event
547 SetPrivateState(eStateStopped);
548 } else {
549 error.SetErrorString("KDP cannot interrupt a running kernel");
550 }
551 }
552 return error;
553}
554
555Error ProcessKDP::DoDetach(bool keep_stopped) {
556 Error error;
557 Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
558 if (log)
559 log->Printf("ProcessKDP::DoDetach(keep_stopped = %i)", keep_stopped);
560
561 if (m_comm.IsRunning()) {
562 // We are running and we can't interrupt a running kernel, so we need
563 // to just close the connection to the kernel and hope for the best
564 } else {
565 // If we are going to keep the target stopped, then don't send the
566 // disconnect message.
567 if (!keep_stopped && m_comm.IsConnected()) {
568 const bool success = m_comm.SendRequestDisconnect();
569 if (log) {
570 if (success)
571 log->PutCString(
572 "ProcessKDP::DoDetach() detach packet sent successfully");
573 else
574 log->PutCString(
575 "ProcessKDP::DoDetach() connection channel shutdown failed");
576 }
577 m_comm.Disconnect();
578 }
579 }
580 StopAsyncThread();
581 m_comm.Clear();
582
583 SetPrivateState(eStateDetached);
584 ResumePrivateStateThread();
585
586 // KillDebugserverProcess ();
587 return error;
588}
589
590Error ProcessKDP::DoDestroy() {
591 // For KDP there really is no difference between destroy and detach
592 bool keep_stopped = false;
593 return DoDetach(keep_stopped);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000594}
595
596//------------------------------------------------------------------
597// Process Queries
598//------------------------------------------------------------------
599
Kate Stoneb9c1b512016-09-06 20:57:50 +0000600bool ProcessKDP::IsAlive() {
601 return m_comm.IsConnected() && Process::IsAlive();
Greg Claytonf9765ac2011-07-15 03:27:12 +0000602}
603
604//------------------------------------------------------------------
605// Process Memory
606//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000607size_t ProcessKDP::DoReadMemory(addr_t addr, void *buf, size_t size,
608 Error &error) {
609 uint8_t *data_buffer = (uint8_t *)buf;
610 if (m_comm.IsConnected()) {
611 const size_t max_read_size = 512;
612 size_t total_bytes_read = 0;
Jason Molenda8eb32812014-05-21 23:44:02 +0000613
Kate Stoneb9c1b512016-09-06 20:57:50 +0000614 // Read the requested amount of memory in 512 byte chunks
615 while (total_bytes_read < size) {
616 size_t bytes_to_read_this_request = size - total_bytes_read;
617 if (bytes_to_read_this_request > max_read_size) {
618 bytes_to_read_this_request = max_read_size;
619 }
620 size_t bytes_read = m_comm.SendRequestReadMemory(
621 addr + total_bytes_read, data_buffer + total_bytes_read,
622 bytes_to_read_this_request, error);
623 total_bytes_read += bytes_read;
624 if (error.Fail() || bytes_read == 0) {
Jason Molenda8eb32812014-05-21 23:44:02 +0000625 return total_bytes_read;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000626 }
Jason Molenda8eb32812014-05-21 23:44:02 +0000627 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000628
629 return total_bytes_read;
630 }
631 error.SetErrorString("not connected");
632 return 0;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000633}
634
Kate Stoneb9c1b512016-09-06 20:57:50 +0000635size_t ProcessKDP::DoWriteMemory(addr_t addr, const void *buf, size_t size,
636 Error &error) {
637 if (m_comm.IsConnected())
638 return m_comm.SendRequestWriteMemory(addr, buf, size, error);
639 error.SetErrorString("not connected");
640 return 0;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000641}
642
Kate Stoneb9c1b512016-09-06 20:57:50 +0000643lldb::addr_t ProcessKDP::DoAllocateMemory(size_t size, uint32_t permissions,
644 Error &error) {
645 error.SetErrorString(
646 "memory allocation not suppported in kdp remote debugging");
647 return LLDB_INVALID_ADDRESS;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000648}
649
Kate Stoneb9c1b512016-09-06 20:57:50 +0000650Error ProcessKDP::DoDeallocateMemory(lldb::addr_t addr) {
651 Error error;
652 error.SetErrorString(
653 "memory deallocation not suppported in kdp remote debugging");
654 return error;
655}
656
657Error ProcessKDP::EnableBreakpointSite(BreakpointSite *bp_site) {
658 if (m_comm.LocalBreakpointsAreSupported()) {
Greg Claytonf9765ac2011-07-15 03:27:12 +0000659 Error error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000660 if (!bp_site->IsEnabled()) {
661 if (m_comm.SendRequestBreakpoint(true, bp_site->GetLoadAddress())) {
662 bp_site->SetEnabled(true);
663 bp_site->SetType(BreakpointSite::eExternal);
664 } else {
665 error.SetErrorString("KDP set breakpoint failed");
666 }
667 }
Greg Claytonf9765ac2011-07-15 03:27:12 +0000668 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000669 }
670 return EnableSoftwareBreakpoint(bp_site);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000671}
672
Kate Stoneb9c1b512016-09-06 20:57:50 +0000673Error ProcessKDP::DisableBreakpointSite(BreakpointSite *bp_site) {
674 if (m_comm.LocalBreakpointsAreSupported()) {
675 Error error;
676 if (bp_site->IsEnabled()) {
677 BreakpointSite::Type bp_type = bp_site->GetType();
678 if (bp_type == BreakpointSite::eExternal) {
679 if (m_destroy_in_process && m_comm.IsRunning()) {
680 // We are trying to destroy our connection and we are running
681 bp_site->SetEnabled(false);
682 } else {
683 if (m_comm.SendRequestBreakpoint(false, bp_site->GetLoadAddress()))
684 bp_site->SetEnabled(false);
685 else
686 error.SetErrorString("KDP remove breakpoint failed");
Greg Clayton5b882162011-07-21 01:12:01 +0000687 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000688 } else {
689 error = DisableSoftwareBreakpoint(bp_site);
690 }
Greg Clayton07e66e32011-07-20 03:41:06 +0000691 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000692 return error;
693 }
694 return DisableSoftwareBreakpoint(bp_site);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000695}
696
Kate Stoneb9c1b512016-09-06 20:57:50 +0000697Error ProcessKDP::EnableWatchpoint(Watchpoint *wp, bool notify) {
698 Error error;
699 error.SetErrorString(
700 "watchpoints are not suppported in kdp remote debugging");
701 return error;
702}
703
704Error ProcessKDP::DisableWatchpoint(Watchpoint *wp, bool notify) {
705 Error error;
706 error.SetErrorString(
707 "watchpoints are not suppported in kdp remote debugging");
708 return error;
709}
710
711void ProcessKDP::Clear() { m_thread_list.Clear(); }
712
713Error ProcessKDP::DoSignal(int signo) {
714 Error error;
715 error.SetErrorString(
716 "sending signals is not suppported in kdp remote debugging");
717 return error;
718}
719
720void ProcessKDP::Initialize() {
721 static std::once_flag g_once_flag;
722
723 std::call_once(g_once_flag, []() {
724 PluginManager::RegisterPlugin(GetPluginNameStatic(),
725 GetPluginDescriptionStatic(), CreateInstance,
726 DebuggerInitialize);
727
728 Log::Callbacks log_callbacks = {ProcessKDPLog::DisableLog,
729 ProcessKDPLog::EnableLog,
730 ProcessKDPLog::ListLogCategories};
731
732 Log::RegisterLogChannel(ProcessKDP::GetPluginNameStatic(), log_callbacks);
733 });
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 }
956 Error error;
957 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}