blob: f19ebc2587443a916132223b6606a7058e99fe46 [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"
Zachary Turner93a66fc2014-10-06 21:22:36 +000022#include "lldb/Host/ConnectionFileDescriptor.h"
Greg Claytonf9765ac2011-07-15 03:27:12 +000023#include "lldb/Host/Host.h"
Jason Molenda4bd4e7e2012-09-29 04:02:01 +000024#include "lldb/Host/Symbols.h"
Zachary Turner39de3112014-09-09 20:54:56 +000025#include "lldb/Host/ThreadLauncher.h"
Oleksiy Vyalove98628c2015-10-15 23:54:09 +000026#include "lldb/Host/common/TCPSocket.h"
Greg Clayton1d19a2f2012-10-19 22:22:57 +000027#include "lldb/Interpreter/CommandInterpreter.h"
28#include "lldb/Interpreter/CommandObject.h"
29#include "lldb/Interpreter/CommandObjectMultiword.h"
30#include "lldb/Interpreter/CommandReturnObject.h"
31#include "lldb/Interpreter/OptionGroupString.h"
32#include "lldb/Interpreter/OptionGroupUInt64.h"
Ilia K41204d02015-03-04 12:05:24 +000033#include "lldb/Interpreter/OptionValueProperties.h"
Greg Clayton1f746072012-08-29 21:13:06 +000034#include "lldb/Symbol/ObjectFile.h"
Greg Clayton7925fbb2012-09-21 16:31:20 +000035#include "lldb/Target/RegisterContext.h"
Greg Clayton57508022011-07-15 16:31:38 +000036#include "lldb/Target/Target.h"
Greg Claytona63d08c2011-07-19 03:57:15 +000037#include "lldb/Target/Thread.h"
Pavel Labathd821c992018-08-07 11:07:21 +000038#include "lldb/Utility/State.h"
Bruce Mitchener45788152015-07-07 23:59:01 +000039#include "lldb/Utility/StringExtractor.h"
Pavel Labathd821c992018-08-07 11:07:21 +000040#include "lldb/Utility/UUID.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[] = {
Tatyana Krasnukhaf929e2b2018-09-26 20:31:39 +000059 {"packet-timeout", OptionValue::eTypeUInt64, true, 5, NULL, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +000060 "Specify the default packet timeout in seconds."},
Tatyana Krasnukhaf929e2b2018-09-26 20:31:39 +000061 {NULL, OptionValue::eTypeInvalid, false, 0, 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();
Adrian Prantl05097242018-04-30 16:49:04 +0000175 // We need to call finalize on the process before destroying ourselves to
176 // make sure all of the broadcaster cleanup goes as planned. If we destruct
177 // this class, then Process::~Process() might have problems trying to fully
178 // destroy the broadcaster.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000179 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
Adrian Prantl05097242018-04-30 16:49:04 +0000229 // Don't let any JIT happen when doing KDP as we can't allocate memory and we
230 // don't want to be mucking with threads that might already be handling
231 // exceptions
Kate Stoneb9c1b512016-09-06 20:57:50 +0000232 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
Adrian Prantl05097242018-04-30 16:49:04 +0000285 // doesn't get used since EFI does its own manual loading via
286 // python scripting
Kate Stoneb9c1b512016-09-06 20:57:50 +0000287 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()) {
Adrian Prantl05097242018-04-30 16:49:04 +0000291 // If EFI passed in a UUID= try to lookup UUID The slide will not
292 // be provided. But the UUID lookup will be used to launch EFI
293 // debug scripts from the dSYM, that can load all of the symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000294 ModuleSpec module_spec;
295 module_spec.GetUUID() = kernel_uuid;
296 module_spec.GetArchitecture() = target.GetArchitecture();
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000297
Kate Stoneb9c1b512016-09-06 20:57:50 +0000298 // Lookup UUID locally, before attempting dsymForUUID like action
299 module_spec.GetSymbolFileSpec() =
300 Symbols::LocateExecutableSymbolFile(module_spec);
301 if (module_spec.GetSymbolFileSpec()) {
302 ModuleSpec executable_module_spec =
303 Symbols::LocateExecutableObjectFile(module_spec);
304 if (executable_module_spec.GetFileSpec().Exists()) {
305 module_spec.GetFileSpec() =
306 executable_module_spec.GetFileSpec();
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000307 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000308 }
309 if (!module_spec.GetSymbolFileSpec() ||
310 !module_spec.GetSymbolFileSpec())
311 Symbols::DownloadObjectAndSymbolFile(module_spec, true);
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000312
Kate Stoneb9c1b512016-09-06 20:57:50 +0000313 if (module_spec.GetFileSpec().Exists()) {
314 ModuleSP module_sp(new Module(module_spec));
315 if (module_sp.get() && module_sp->GetObjectFile()) {
316 // Get the current target executable
317 ModuleSP exe_module_sp(target.GetExecutableModule());
318
319 // Make sure you don't already have the right module loaded
320 // and they will be uniqued
321 if (exe_module_sp.get() != module_sp.get())
Jonas Devliegheref9a07e92018-09-20 09:09:05 +0000322 target.SetExecutableModule(module_sp, eLoadDependentsNo);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000323 }
324 }
325 }
326 } else if (m_comm.RemoteIsDarwinKernel()) {
327 m_dyld_plugin_name =
328 DynamicLoaderDarwinKernel::GetPluginNameStatic();
329 if (kernel_load_addr != LLDB_INVALID_ADDRESS) {
330 m_kernel_load_addr = kernel_load_addr;
331 }
332 }
333
334 // Set the thread ID
335 UpdateThreadListIfNeeded();
336 SetID(1);
337 GetThreadList();
338 SetPrivateState(eStateStopped);
339 StreamSP async_strm_sp(target.GetDebugger().GetAsyncOutputStream());
340 if (async_strm_sp) {
341 const char *cstr;
342 if ((cstr = m_comm.GetKernelVersion()) != NULL) {
343 async_strm_sp->Printf("Version: %s\n", cstr);
344 async_strm_sp->Flush();
345 }
346 // if ((cstr = m_comm.GetImagePath ()) != NULL)
347 // {
348 // async_strm_sp->Printf ("Image Path:
349 // %s\n", cstr);
350 // async_strm_sp->Flush();
351 // }
352 }
353 } else {
354 error.SetErrorString("KDP_REATTACH failed");
355 }
356 } else {
357 error.SetErrorString("KDP_REATTACH failed");
358 }
359 } else {
360 error.SetErrorString("invalid reply port from UDP connection");
361 }
362 } else {
363 if (error.Success())
Greg Clayton3ce7e992016-12-07 23:51:49 +0000364 error.SetErrorStringWithFormat("failed to connect to '%s'",
365 remote_url.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000366 }
367 if (error.Fail())
368 m_comm.Disconnect();
369
370 return error;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000371}
372
373//----------------------------------------------------------------------
374// Process Control
375//----------------------------------------------------------------------
Zachary Turner97206d52017-05-12 04:51:55 +0000376Status ProcessKDP::DoLaunch(Module *exe_module,
377 ProcessLaunchInfo &launch_info) {
378 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000379 error.SetErrorString("launching not supported in kdp-remote plug-in");
380 return error;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000381}
382
Zachary Turner97206d52017-05-12 04:51:55 +0000383Status
384ProcessKDP::DoAttachToProcessWithID(lldb::pid_t attach_pid,
385 const ProcessAttachInfo &attach_info) {
386 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000387 error.SetErrorString(
Bruce Mitchener4ebdee02018-05-29 09:10:46 +0000388 "attach to process by ID is not supported in kdp remote debugging");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000389 return error;
Han Ming Ong84647042012-02-25 01:07:38 +0000390}
391
Zachary Turner97206d52017-05-12 04:51:55 +0000392Status
393ProcessKDP::DoAttachToProcessWithName(const char *process_name,
394 const ProcessAttachInfo &attach_info) {
395 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000396 error.SetErrorString(
Bruce Mitchener4ebdee02018-05-29 09:10:46 +0000397 "attach to process by name is not supported in kdp remote debugging");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000398 return error;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000399}
400
Kate Stoneb9c1b512016-09-06 20:57:50 +0000401void ProcessKDP::DidAttach(ArchSpec &process_arch) {
402 Process::DidAttach(process_arch);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000403
Kate Stoneb9c1b512016-09-06 20:57:50 +0000404 Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
405 if (log)
406 log->Printf("ProcessKDP::DidAttach()");
407 if (GetID() != LLDB_INVALID_PROCESS_ID) {
408 GetHostArchitecture(process_arch);
409 }
410}
411
412addr_t ProcessKDP::GetImageInfoAddress() { return m_kernel_load_addr; }
413
414lldb_private::DynamicLoader *ProcessKDP::GetDynamicLoader() {
415 if (m_dyld_ap.get() == NULL)
416 m_dyld_ap.reset(DynamicLoader::FindPlugin(
417 this,
418 m_dyld_plugin_name.IsEmpty() ? NULL : m_dyld_plugin_name.GetCString()));
419 return m_dyld_ap.get();
420}
421
Zachary Turner97206d52017-05-12 04:51:55 +0000422Status ProcessKDP::WillResume() { return Status(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000423
Zachary Turner97206d52017-05-12 04:51:55 +0000424Status ProcessKDP::DoResume() {
425 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000426 Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
427 // Only start the async thread if we try to do any process control
428 if (!m_async_thread.IsJoinable())
429 StartAsyncThread();
430
431 bool resume = false;
432
433 // With KDP there is only one thread we can tell what to do
434 ThreadSP kernel_thread_sp(m_thread_list.FindThreadByProtocolID(g_kernel_tid));
435
436 if (kernel_thread_sp) {
437 const StateType thread_resume_state =
438 kernel_thread_sp->GetTemporaryResumeState();
439
Greg Claytonf9765ac2011-07-15 03:27:12 +0000440 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000441 log->Printf("ProcessKDP::DoResume() thread_resume_state = %s",
442 StateAsCString(thread_resume_state));
443 switch (thread_resume_state) {
444 case eStateSuspended:
Adrian Prantl05097242018-04-30 16:49:04 +0000445 // Nothing to do here when a thread will stay suspended we just leave the
446 // CPU mask bit set to zero for the thread
Kate Stoneb9c1b512016-09-06 20:57:50 +0000447 if (log)
448 log->Printf("ProcessKDP::DoResume() = suspended???");
449 break;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000450
Kate Stoneb9c1b512016-09-06 20:57:50 +0000451 case eStateStepping: {
452 lldb::RegisterContextSP reg_ctx_sp(
453 kernel_thread_sp->GetRegisterContext());
Jason Molenda5e8534e2012-10-03 01:29:34 +0000454
Kate Stoneb9c1b512016-09-06 20:57:50 +0000455 if (reg_ctx_sp) {
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000456 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000457 log->Printf(
458 "ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep (true);");
459 reg_ctx_sp->HardwareSingleStep(true);
460 resume = true;
461 } else {
462 error.SetErrorStringWithFormat(
463 "KDP thread 0x%llx has no register context",
464 kernel_thread_sp->GetID());
465 }
466 } break;
Greg Clayton1afa68e2013-04-02 20:32:37 +0000467
Kate Stoneb9c1b512016-09-06 20:57:50 +0000468 case eStateRunning: {
469 lldb::RegisterContextSP reg_ctx_sp(
470 kernel_thread_sp->GetRegisterContext());
Greg Clayton97d5cf02012-09-25 02:40:06 +0000471
Kate Stoneb9c1b512016-09-06 20:57:50 +0000472 if (reg_ctx_sp) {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000473 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000474 log->Printf("ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep "
475 "(false);");
476 reg_ctx_sp->HardwareSingleStep(false);
477 resume = true;
478 } else {
479 error.SetErrorStringWithFormat(
480 "KDP thread 0x%llx has no register context",
481 kernel_thread_sp->GetID());
482 }
483 } break;
484
485 default:
486 // The only valid thread resume states are listed above
David Blaikiea322f362017-01-06 00:38:06 +0000487 llvm_unreachable("invalid thread resume state");
Greg Clayton7925fbb2012-09-21 16:31:20 +0000488 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000489 }
Greg Claytonf9765ac2011-07-15 03:27:12 +0000490
Kate Stoneb9c1b512016-09-06 20:57:50 +0000491 if (resume) {
Greg Claytonf9765ac2011-07-15 03:27:12 +0000492 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000493 log->Printf("ProcessKDP::DoResume () sending resume");
494
495 if (m_comm.SendRequestResume()) {
496 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue);
497 SetPrivateState(eStateRunning);
498 } else
499 error.SetErrorString("KDP resume failed");
500 } else {
501 error.SetErrorString("kernel thread is suspended");
502 }
503
504 return error;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000505}
506
Kate Stoneb9c1b512016-09-06 20:57:50 +0000507lldb::ThreadSP ProcessKDP::GetKernelThread() {
508 // KDP only tells us about one thread/core. Any other threads will usually
509 // be the ones that are read from memory by the OS plug-ins.
510
511 ThreadSP thread_sp(m_kernel_thread_wp.lock());
512 if (!thread_sp) {
513 thread_sp.reset(new ThreadKDP(*this, g_kernel_tid));
514 m_kernel_thread_wp = thread_sp;
515 }
516 return thread_sp;
517}
518
519bool ProcessKDP::UpdateThreadList(ThreadList &old_thread_list,
520 ThreadList &new_thread_list) {
521 // locker will keep a mutex locked until it goes out of scope
522 Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_THREAD));
Pavel Labath250858a2017-02-06 21:46:22 +0000523 LLDB_LOGV(log, "pid = {0}", GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000524
525 // Even though there is a CPU mask, it doesn't mean we can see each CPU
526 // individually, there is really only one. Lets call this thread 1.
527 ThreadSP thread_sp(
528 old_thread_list.FindThreadByProtocolID(g_kernel_tid, false));
529 if (!thread_sp)
530 thread_sp = GetKernelThread();
531 new_thread_list.AddThread(thread_sp);
532
533 return new_thread_list.GetSize(false) > 0;
534}
535
536void ProcessKDP::RefreshStateAfterStop() {
Adrian Prantl05097242018-04-30 16:49:04 +0000537 // Let all threads recover from stopping and do any clean up based on the
538 // previous thread state (if any).
Kate Stoneb9c1b512016-09-06 20:57:50 +0000539 m_thread_list.RefreshStateAfterStop();
540}
541
Zachary Turner97206d52017-05-12 04:51:55 +0000542Status ProcessKDP::DoHalt(bool &caused_stop) {
543 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000544
545 if (m_comm.IsRunning()) {
546 if (m_destroy_in_process) {
Bruce Mitchener4ebdee02018-05-29 09:10:46 +0000547 // If we are attempting to destroy, we need to not return an error to Halt
Adrian Prantl05097242018-04-30 16:49:04 +0000548 // or DoDestroy won't get called. We are also currently running, so send
549 // a process stopped event
Kate Stoneb9c1b512016-09-06 20:57:50 +0000550 SetPrivateState(eStateStopped);
551 } else {
552 error.SetErrorString("KDP cannot interrupt a running kernel");
553 }
554 }
555 return error;
556}
557
Zachary Turner97206d52017-05-12 04:51:55 +0000558Status ProcessKDP::DoDetach(bool keep_stopped) {
559 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000560 Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
561 if (log)
562 log->Printf("ProcessKDP::DoDetach(keep_stopped = %i)", keep_stopped);
563
564 if (m_comm.IsRunning()) {
Adrian Prantl05097242018-04-30 16:49:04 +0000565 // We are running and we can't interrupt a running kernel, so we need to
566 // just close the connection to the kernel and hope for the best
Kate Stoneb9c1b512016-09-06 20:57:50 +0000567 } else {
568 // If we are going to keep the target stopped, then don't send the
569 // disconnect message.
570 if (!keep_stopped && m_comm.IsConnected()) {
571 const bool success = m_comm.SendRequestDisconnect();
572 if (log) {
573 if (success)
574 log->PutCString(
575 "ProcessKDP::DoDetach() detach packet sent successfully");
576 else
577 log->PutCString(
578 "ProcessKDP::DoDetach() connection channel shutdown failed");
579 }
580 m_comm.Disconnect();
581 }
582 }
583 StopAsyncThread();
584 m_comm.Clear();
585
586 SetPrivateState(eStateDetached);
587 ResumePrivateStateThread();
588
589 // KillDebugserverProcess ();
590 return error;
591}
592
Zachary Turner97206d52017-05-12 04:51:55 +0000593Status ProcessKDP::DoDestroy() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000594 // For KDP there really is no difference between destroy and detach
595 bool keep_stopped = false;
596 return DoDetach(keep_stopped);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000597}
598
599//------------------------------------------------------------------
600// Process Queries
601//------------------------------------------------------------------
602
Kate Stoneb9c1b512016-09-06 20:57:50 +0000603bool ProcessKDP::IsAlive() {
604 return m_comm.IsConnected() && Process::IsAlive();
Greg Claytonf9765ac2011-07-15 03:27:12 +0000605}
606
607//------------------------------------------------------------------
608// Process Memory
609//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000610size_t ProcessKDP::DoReadMemory(addr_t addr, void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +0000611 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000612 uint8_t *data_buffer = (uint8_t *)buf;
613 if (m_comm.IsConnected()) {
614 const size_t max_read_size = 512;
615 size_t total_bytes_read = 0;
Jason Molenda8eb32812014-05-21 23:44:02 +0000616
Kate Stoneb9c1b512016-09-06 20:57:50 +0000617 // Read the requested amount of memory in 512 byte chunks
618 while (total_bytes_read < size) {
619 size_t bytes_to_read_this_request = size - total_bytes_read;
620 if (bytes_to_read_this_request > max_read_size) {
621 bytes_to_read_this_request = max_read_size;
622 }
623 size_t bytes_read = m_comm.SendRequestReadMemory(
624 addr + total_bytes_read, data_buffer + total_bytes_read,
625 bytes_to_read_this_request, error);
626 total_bytes_read += bytes_read;
627 if (error.Fail() || bytes_read == 0) {
Jason Molenda8eb32812014-05-21 23:44:02 +0000628 return total_bytes_read;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000629 }
Jason Molenda8eb32812014-05-21 23:44:02 +0000630 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000631
632 return total_bytes_read;
633 }
634 error.SetErrorString("not connected");
635 return 0;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000636}
637
Kate Stoneb9c1b512016-09-06 20:57:50 +0000638size_t ProcessKDP::DoWriteMemory(addr_t addr, const void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +0000639 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000640 if (m_comm.IsConnected())
641 return m_comm.SendRequestWriteMemory(addr, buf, size, error);
642 error.SetErrorString("not connected");
643 return 0;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000644}
645
Kate Stoneb9c1b512016-09-06 20:57:50 +0000646lldb::addr_t ProcessKDP::DoAllocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +0000647 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000648 error.SetErrorString(
Bruce Mitchener4ebdee02018-05-29 09:10:46 +0000649 "memory allocation not supported in kdp remote debugging");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000650 return LLDB_INVALID_ADDRESS;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000651}
652
Zachary Turner97206d52017-05-12 04:51:55 +0000653Status ProcessKDP::DoDeallocateMemory(lldb::addr_t addr) {
654 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000655 error.SetErrorString(
Bruce Mitchener4ebdee02018-05-29 09:10:46 +0000656 "memory deallocation not supported in kdp remote debugging");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000657 return error;
658}
659
Zachary Turner97206d52017-05-12 04:51:55 +0000660Status ProcessKDP::EnableBreakpointSite(BreakpointSite *bp_site) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000661 if (m_comm.LocalBreakpointsAreSupported()) {
Zachary Turner97206d52017-05-12 04:51:55 +0000662 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000663 if (!bp_site->IsEnabled()) {
664 if (m_comm.SendRequestBreakpoint(true, bp_site->GetLoadAddress())) {
665 bp_site->SetEnabled(true);
666 bp_site->SetType(BreakpointSite::eExternal);
667 } else {
668 error.SetErrorString("KDP set breakpoint failed");
669 }
670 }
Greg Claytonf9765ac2011-07-15 03:27:12 +0000671 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000672 }
673 return EnableSoftwareBreakpoint(bp_site);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000674}
675
Zachary Turner97206d52017-05-12 04:51:55 +0000676Status ProcessKDP::DisableBreakpointSite(BreakpointSite *bp_site) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000677 if (m_comm.LocalBreakpointsAreSupported()) {
Zachary Turner97206d52017-05-12 04:51:55 +0000678 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000679 if (bp_site->IsEnabled()) {
680 BreakpointSite::Type bp_type = bp_site->GetType();
681 if (bp_type == BreakpointSite::eExternal) {
682 if (m_destroy_in_process && m_comm.IsRunning()) {
683 // We are trying to destroy our connection and we are running
684 bp_site->SetEnabled(false);
685 } else {
686 if (m_comm.SendRequestBreakpoint(false, bp_site->GetLoadAddress()))
687 bp_site->SetEnabled(false);
688 else
689 error.SetErrorString("KDP remove breakpoint failed");
Greg Clayton5b882162011-07-21 01:12:01 +0000690 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000691 } else {
692 error = DisableSoftwareBreakpoint(bp_site);
693 }
Greg Clayton07e66e32011-07-20 03:41:06 +0000694 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000695 return error;
696 }
697 return DisableSoftwareBreakpoint(bp_site);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000698}
699
Zachary Turner97206d52017-05-12 04:51:55 +0000700Status ProcessKDP::EnableWatchpoint(Watchpoint *wp, bool notify) {
701 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000702 error.SetErrorString(
Bruce Mitchener4ebdee02018-05-29 09:10:46 +0000703 "watchpoints are not supported in kdp remote debugging");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000704 return error;
705}
706
Zachary Turner97206d52017-05-12 04:51:55 +0000707Status ProcessKDP::DisableWatchpoint(Watchpoint *wp, bool notify) {
708 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000709 error.SetErrorString(
Bruce Mitchener4ebdee02018-05-29 09:10:46 +0000710 "watchpoints are not supported in kdp remote debugging");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000711 return error;
712}
713
714void ProcessKDP::Clear() { m_thread_list.Clear(); }
715
Zachary Turner97206d52017-05-12 04:51:55 +0000716Status ProcessKDP::DoSignal(int signo) {
717 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000718 error.SetErrorString(
Bruce Mitchener4ebdee02018-05-29 09:10:46 +0000719 "sending signals is not supported in kdp remote debugging");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000720 return error;
721}
722
723void ProcessKDP::Initialize() {
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +0000724 static llvm::once_flag g_once_flag;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000725
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +0000726 llvm::call_once(g_once_flag, []() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000727 PluginManager::RegisterPlugin(GetPluginNameStatic(),
728 GetPluginDescriptionStatic(), CreateInstance,
729 DebuggerInitialize);
730
Pavel Labath7b35b782017-02-17 15:08:08 +0000731 ProcessKDPLog::Initialize();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000732 });
733}
734
735void ProcessKDP::DebuggerInitialize(lldb_private::Debugger &debugger) {
736 if (!PluginManager::GetSettingForProcessPlugin(
737 debugger, PluginProperties::GetSettingName())) {
738 const bool is_global_setting = true;
739 PluginManager::CreateSettingForProcessPlugin(
740 debugger, GetGlobalPluginProperties()->GetValueProperties(),
741 ConstString("Properties for the kdp-remote process plug-in."),
742 is_global_setting);
743 }
744}
745
746bool ProcessKDP::StartAsyncThread() {
747 Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
748
749 if (log)
750 log->Printf("ProcessKDP::StartAsyncThread ()");
751
752 if (m_async_thread.IsJoinable())
753 return true;
754
755 m_async_thread = ThreadLauncher::LaunchThread(
756 "<lldb.process.kdp-remote.async>", ProcessKDP::AsyncThread, this, NULL);
757 return m_async_thread.IsJoinable();
758}
759
760void ProcessKDP::StopAsyncThread() {
761 Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
762
763 if (log)
764 log->Printf("ProcessKDP::StopAsyncThread ()");
765
766 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
767
768 // Stop the stdio thread
769 if (m_async_thread.IsJoinable())
770 m_async_thread.Join(nullptr);
771}
772
773void *ProcessKDP::AsyncThread(void *arg) {
774 ProcessKDP *process = (ProcessKDP *)arg;
775
776 const lldb::pid_t pid = process->GetID();
777
778 Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
779 if (log)
780 log->Printf("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64
781 ") thread starting...",
782 arg, pid);
783
784 ListenerSP listener_sp(Listener::MakeListener("ProcessKDP::AsyncThread"));
785 EventSP event_sp;
786 const uint32_t desired_event_mask =
787 eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
788
789 if (listener_sp->StartListeningForEvents(&process->m_async_broadcaster,
790 desired_event_mask) ==
791 desired_event_mask) {
792 bool done = false;
793 while (!done) {
794 if (log)
795 log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
796 ") listener.WaitForEvent (NULL, event_sp)...",
797 pid);
Pavel Labathfafff0c2016-11-30 11:09:47 +0000798 if (listener_sp->GetEvent(event_sp, llvm::None)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000799 uint32_t event_type = event_sp->GetType();
800 if (log)
801 log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
802 ") Got an event of type: %d...",
803 pid, event_type);
804
805 // When we are running, poll for 1 second to try and get an exception
806 // to indicate the process has stopped. If we don't get one, check to
807 // make sure no one asked us to exit
808 bool is_running = false;
809 DataExtractor exc_reply_packet;
810 do {
811 switch (event_type) {
812 case eBroadcastBitAsyncContinue: {
813 is_running = true;
814 if (process->m_comm.WaitForPacketWithTimeoutMicroSeconds(
815 exc_reply_packet, 1 * USEC_PER_SEC)) {
816 ThreadSP thread_sp(process->GetKernelThread());
817 if (thread_sp) {
818 lldb::RegisterContextSP reg_ctx_sp(
819 thread_sp->GetRegisterContext());
820 if (reg_ctx_sp)
821 reg_ctx_sp->InvalidateAllRegisters();
822 static_cast<ThreadKDP *>(thread_sp.get())
823 ->SetStopInfoFrom_KDP_EXCEPTION(exc_reply_packet);
824 }
825
826 // TODO: parse the stop reply packet
827 is_running = false;
828 process->SetPrivateState(eStateStopped);
829 } else {
830 // Check to see if we are supposed to exit. There is no way to
831 // interrupt a running kernel, so all we can do is wait for an
832 // exception or detach...
Pavel Labathfafff0c2016-11-30 11:09:47 +0000833 if (listener_sp->GetEvent(event_sp,
834 std::chrono::microseconds(0))) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000835 // We got an event, go through the loop again
836 event_type = event_sp->GetType();
837 }
Greg Clayton5b882162011-07-21 01:12:01 +0000838 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000839 } break;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000840
Kate Stoneb9c1b512016-09-06 20:57:50 +0000841 case eBroadcastBitAsyncThreadShouldExit:
Greg Claytonf9765ac2011-07-15 03:27:12 +0000842 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000843 log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
844 ") got eBroadcastBitAsyncThreadShouldExit...",
845 pid);
846 done = true;
847 is_running = false;
848 break;
Greg Clayton97d5cf02012-09-25 02:40:06 +0000849
Kate Stoneb9c1b512016-09-06 20:57:50 +0000850 default:
851 if (log)
852 log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
853 ") got unknown event 0x%8.8x",
854 pid, event_type);
855 done = true;
856 is_running = false;
857 break;
858 }
859 } while (is_running);
860 } else {
861 if (log)
862 log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
863 ") listener.WaitForEvent (NULL, event_sp) => false",
864 pid);
865 done = true;
866 }
Greg Claytonf9765ac2011-07-15 03:27:12 +0000867 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000868 }
Zachary Turner39de3112014-09-09 20:54:56 +0000869
Kate Stoneb9c1b512016-09-06 20:57:50 +0000870 if (log)
871 log->Printf("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64
872 ") thread exiting...",
873 arg, pid);
874
875 process->m_async_thread.Reset();
876 return NULL;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000877}
878
Kate Stoneb9c1b512016-09-06 20:57:50 +0000879class CommandObjectProcessKDPPacketSend : public CommandObjectParsed {
Greg Clayton1d19a2f2012-10-19 22:22:57 +0000880private:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000881 OptionGroupOptions m_option_group;
882 OptionGroupUInt64 m_command_byte;
883 OptionGroupString m_packet_data;
884
885 virtual Options *GetOptions() { return &m_option_group; }
Greg Clayton1d19a2f2012-10-19 22:22:57 +0000886
887public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000888 CommandObjectProcessKDPPacketSend(CommandInterpreter &interpreter)
889 : CommandObjectParsed(interpreter, "process plugin packet send",
890 "Send a custom packet through the KDP protocol by "
891 "specifying the command byte and the packet "
892 "payload data. A packet will be sent with a "
893 "correct header and payload, and the raw result "
894 "bytes will be displayed as a string value. ",
895 NULL),
Todd Fialae1cfbc72016-08-11 23:51:28 +0000896 m_option_group(),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000897 m_command_byte(LLDB_OPT_SET_1, true, "command", 'c', 0, eArgTypeNone,
898 "Specify the command byte to use when sending the KDP "
899 "request packet.",
900 0),
901 m_packet_data(LLDB_OPT_SET_1, false, "payload", 'p', 0, eArgTypeNone,
902 "Specify packet payload bytes as a hex ASCII string with "
903 "no spaces or hex prefixes.",
904 NULL) {
905 m_option_group.Append(&m_command_byte, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
906 m_option_group.Append(&m_packet_data, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
907 m_option_group.Finalize();
908 }
909
910 ~CommandObjectProcessKDPPacketSend() {}
911
912 bool DoExecute(Args &command, CommandReturnObject &result) {
913 const size_t argc = command.GetArgumentCount();
914 if (argc == 0) {
915 if (!m_command_byte.GetOptionValue().OptionWasSet()) {
916 result.AppendError(
917 "the --command option must be set to a valid command byte");
918 result.SetStatus(eReturnStatusFailed);
919 } else {
920 const uint64_t command_byte =
921 m_command_byte.GetOptionValue().GetUInt64Value(0);
922 if (command_byte > 0 && command_byte <= UINT8_MAX) {
923 ProcessKDP *process =
924 (ProcessKDP *)m_interpreter.GetExecutionContext().GetProcessPtr();
925 if (process) {
926 const StateType state = process->GetState();
927
928 if (StateIsStoppedState(state, true)) {
929 std::vector<uint8_t> payload_bytes;
930 const char *ascii_hex_bytes_cstr =
931 m_packet_data.GetOptionValue().GetCurrentValue();
932 if (ascii_hex_bytes_cstr && ascii_hex_bytes_cstr[0]) {
933 StringExtractor extractor(ascii_hex_bytes_cstr);
934 const size_t ascii_hex_bytes_cstr_len =
935 extractor.GetStringRef().size();
936 if (ascii_hex_bytes_cstr_len & 1) {
937 result.AppendErrorWithFormat("payload data must contain an "
938 "even number of ASCII hex "
939 "characters: '%s'",
940 ascii_hex_bytes_cstr);
941 result.SetStatus(eReturnStatusFailed);
942 return false;
Greg Clayton1d19a2f2012-10-19 22:22:57 +0000943 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000944 payload_bytes.resize(ascii_hex_bytes_cstr_len / 2);
945 if (extractor.GetHexBytes(payload_bytes, '\xdd') !=
946 payload_bytes.size()) {
947 result.AppendErrorWithFormat("payload data must only contain "
948 "ASCII hex characters (no "
949 "spaces or hex prefixes): '%s'",
950 ascii_hex_bytes_cstr);
951 result.SetStatus(eReturnStatusFailed);
952 return false;
953 }
954 }
Zachary Turner97206d52017-05-12 04:51:55 +0000955 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000956 DataExtractor reply;
957 process->GetCommunication().SendRawRequest(
958 command_byte,
959 payload_bytes.empty() ? NULL : payload_bytes.data(),
960 payload_bytes.size(), reply, error);
961
962 if (error.Success()) {
963 // Copy the binary bytes into a hex ASCII string for the result
964 StreamString packet;
965 packet.PutBytesAsRawHex8(
966 reply.GetDataStart(), reply.GetByteSize(),
967 endian::InlHostByteOrder(), endian::InlHostByteOrder());
Zachary Turnerc1564272016-11-16 21:15:24 +0000968 result.AppendMessage(packet.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000969 result.SetStatus(eReturnStatusSuccessFinishResult);
970 return true;
971 } else {
972 const char *error_cstr = error.AsCString();
973 if (error_cstr && error_cstr[0])
974 result.AppendError(error_cstr);
Greg Clayton1d19a2f2012-10-19 22:22:57 +0000975 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000976 result.AppendErrorWithFormat("unknown error 0x%8.8x",
977 error.GetError());
978 result.SetStatus(eReturnStatusFailed);
979 return false;
980 }
981 } else {
982 result.AppendErrorWithFormat("process must be stopped in order "
983 "to send KDP packets, state is %s",
984 StateAsCString(state));
985 result.SetStatus(eReturnStatusFailed);
Greg Clayton1d19a2f2012-10-19 22:22:57 +0000986 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000987 } else {
988 result.AppendError("invalid process");
989 result.SetStatus(eReturnStatusFailed);
990 }
991 } else {
992 result.AppendErrorWithFormat("invalid command byte 0x%" PRIx64
993 ", valid values are 1 - 255",
994 command_byte);
995 result.SetStatus(eReturnStatusFailed);
Greg Clayton1d19a2f2012-10-19 22:22:57 +0000996 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000997 }
998 } else {
999 result.AppendErrorWithFormat("'%s' takes no arguments, only options.",
1000 m_cmd_name.c_str());
1001 result.SetStatus(eReturnStatusFailed);
Greg Clayton1d19a2f2012-10-19 22:22:57 +00001002 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001003 return false;
1004 }
Greg Clayton1d19a2f2012-10-19 22:22:57 +00001005};
1006
Kate Stoneb9c1b512016-09-06 20:57:50 +00001007class CommandObjectProcessKDPPacket : public CommandObjectMultiword {
Greg Clayton1d19a2f2012-10-19 22:22:57 +00001008private:
Greg Clayton1d19a2f2012-10-19 22:22:57 +00001009public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001010 CommandObjectProcessKDPPacket(CommandInterpreter &interpreter)
1011 : CommandObjectMultiword(interpreter, "process plugin packet",
1012 "Commands that deal with KDP remote packets.",
1013 NULL) {
1014 LoadSubCommand(
1015 "send",
1016 CommandObjectSP(new CommandObjectProcessKDPPacketSend(interpreter)));
1017 }
1018
1019 ~CommandObjectProcessKDPPacket() {}
Greg Clayton1d19a2f2012-10-19 22:22:57 +00001020};
1021
Kate Stoneb9c1b512016-09-06 20:57:50 +00001022class CommandObjectMultiwordProcessKDP : public CommandObjectMultiword {
Greg Clayton1d19a2f2012-10-19 22:22:57 +00001023public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001024 CommandObjectMultiwordProcessKDP(CommandInterpreter &interpreter)
1025 : CommandObjectMultiword(
1026 interpreter, "process plugin",
1027 "Commands for operating on a ProcessKDP process.",
1028 "process plugin <subcommand> [<subcommand-options>]") {
1029 LoadSubCommand("packet", CommandObjectSP(new CommandObjectProcessKDPPacket(
1030 interpreter)));
1031 }
1032
1033 ~CommandObjectMultiwordProcessKDP() {}
Greg Clayton1d19a2f2012-10-19 22:22:57 +00001034};
1035
Kate Stoneb9c1b512016-09-06 20:57:50 +00001036CommandObject *ProcessKDP::GetPluginCommandObject() {
1037 if (!m_command_sp)
1038 m_command_sp.reset(new CommandObjectMultiwordProcessKDP(
1039 GetTarget().GetDebugger().GetCommandInterpreter()));
1040 return m_command_sp.get();
Greg Clayton1d19a2f2012-10-19 22:22:57 +00001041}