blob: 93c59dd613a0f64998365aa4edb8b98c317f742d [file] [log] [blame]
Greg Clayton59ec5122011-07-15 18:02:58 +00001//===-- ProcessKDP.cpp ------------------------------------------*- C++ -*-===//
Greg Claytonf9765ac2011-07-15 03:27:12 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Greg Claytonf9765ac2011-07-15 03:27:12 +00006//
7//===----------------------------------------------------------------------===//
8
Greg Claytonf9765ac2011-07-15 03:27:12 +00009#include <errno.h>
10#include <stdlib.h>
11
Jonas Devlieghere796ac802019-02-11 23:13:08 +000012#include <memory>
Benjamin Kramer3f69fa62015-04-03 10:55:00 +000013#include <mutex>
14
Greg Clayton07e66e32011-07-20 03:41:06 +000015#include "lldb/Core/Debugger.h"
Greg Clayton1f746072012-08-29 21:13:06 +000016#include "lldb/Core/Module.h"
Jason Molenda4bd4e7e2012-09-29 04:02:01 +000017#include "lldb/Core/ModuleSpec.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000018#include "lldb/Core/PluginManager.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000019#include "lldb/Host/ConnectionFileDescriptor.h"
Greg Claytonf9765ac2011-07-15 03:27:12 +000020#include "lldb/Host/Host.h"
Jason Molenda4bd4e7e2012-09-29 04:02:01 +000021#include "lldb/Host/Symbols.h"
Zachary Turner39de3112014-09-09 20:54:56 +000022#include "lldb/Host/ThreadLauncher.h"
Oleksiy Vyalove98628c2015-10-15 23:54:09 +000023#include "lldb/Host/common/TCPSocket.h"
Greg Clayton1d19a2f2012-10-19 22:22:57 +000024#include "lldb/Interpreter/CommandInterpreter.h"
25#include "lldb/Interpreter/CommandObject.h"
26#include "lldb/Interpreter/CommandObjectMultiword.h"
27#include "lldb/Interpreter/CommandReturnObject.h"
28#include "lldb/Interpreter/OptionGroupString.h"
29#include "lldb/Interpreter/OptionGroupUInt64.h"
Ilia K41204d02015-03-04 12:05:24 +000030#include "lldb/Interpreter/OptionValueProperties.h"
Greg Clayton1f746072012-08-29 21:13:06 +000031#include "lldb/Symbol/ObjectFile.h"
Greg Clayton7925fbb2012-09-21 16:31:20 +000032#include "lldb/Target/RegisterContext.h"
Greg Clayton57508022011-07-15 16:31:38 +000033#include "lldb/Target/Target.h"
Greg Claytona63d08c2011-07-19 03:57:15 +000034#include "lldb/Target/Thread.h"
Pavel Labathd821c992018-08-07 11:07:21 +000035#include "lldb/Utility/State.h"
Bruce Mitchener45788152015-07-07 23:59:01 +000036#include "lldb/Utility/StringExtractor.h"
Pavel Labathd821c992018-08-07 11:07:21 +000037#include "lldb/Utility/UUID.h"
Greg Claytonf9765ac2011-07-15 03:27:12 +000038
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000039#include "llvm/Support/Threading.h"
40
Charles Davis510938e2013-08-27 05:04:57 +000041#define USEC_PER_SEC 1000000
42
Kate Stoneb9c1b512016-09-06 20:57:50 +000043#include "Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.h"
44#include "Plugins/DynamicLoader/Static/DynamicLoaderStatic.h"
Greg Claytonf9765ac2011-07-15 03:27:12 +000045#include "ProcessKDP.h"
46#include "ProcessKDPLog.h"
Greg Claytona63d08c2011-07-19 03:57:15 +000047#include "ThreadKDP.h"
Greg Claytonf9765ac2011-07-15 03:27:12 +000048
49using namespace lldb;
50using namespace lldb_private;
51
Greg Clayton7f982402013-07-15 22:54:20 +000052namespace {
53
Tatyana Krasnukhae40db052018-09-27 07:11:58 +000054static constexpr PropertyDefinition g_properties[] = {
Tatyana Krasnukhaf929e2b2018-09-26 20:31:39 +000055 {"packet-timeout", OptionValue::eTypeUInt64, true, 5, NULL, {},
Tatyana Krasnukhae40db052018-09-27 07:11:58 +000056 "Specify the default packet timeout in seconds."}};
Greg Clayton7f982402013-07-15 22:54:20 +000057
Kate Stoneb9c1b512016-09-06 20:57:50 +000058enum { ePropertyPacketTimeout };
Greg Clayton7f982402013-07-15 22:54:20 +000059
Kate Stoneb9c1b512016-09-06 20:57:50 +000060class PluginProperties : public Properties {
61public:
62 static ConstString GetSettingName() {
63 return ProcessKDP::GetPluginNameStatic();
64 }
Greg Clayton7f982402013-07-15 22:54:20 +000065
Kate Stoneb9c1b512016-09-06 20:57:50 +000066 PluginProperties() : Properties() {
Jonas Devlieghere796ac802019-02-11 23:13:08 +000067 m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
Kate Stoneb9c1b512016-09-06 20:57:50 +000068 m_collection_sp->Initialize(g_properties);
69 }
Greg Clayton7f982402013-07-15 22:54:20 +000070
Kate Stoneb9c1b512016-09-06 20:57:50 +000071 virtual ~PluginProperties() {}
72
73 uint64_t GetPacketTimeout() {
74 const uint32_t idx = ePropertyPacketTimeout;
75 return m_collection_sp->GetPropertyAtIndexAsUInt64(
76 NULL, idx, g_properties[idx].default_uint_value);
77 }
78};
79
80typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
81
82static const ProcessKDPPropertiesSP &GetGlobalPluginProperties() {
83 static ProcessKDPPropertiesSP g_settings_sp;
84 if (!g_settings_sp)
Jonas Devlieghere796ac802019-02-11 23:13:08 +000085 g_settings_sp = std::make_shared<PluginProperties>();
Kate Stoneb9c1b512016-09-06 20:57:50 +000086 return g_settings_sp;
87}
88
Greg Clayton7f982402013-07-15 22:54:20 +000089} // anonymous namespace end
90
Andrew Kaylorba4e61d2013-05-07 18:35:34 +000091static const lldb::tid_t g_kernel_tid = 1;
92
Kate Stoneb9c1b512016-09-06 20:57:50 +000093ConstString ProcessKDP::GetPluginNameStatic() {
94 static ConstString g_name("kdp-remote");
95 return g_name;
Greg Claytonf9765ac2011-07-15 03:27:12 +000096}
97
Kate Stoneb9c1b512016-09-06 20:57:50 +000098const char *ProcessKDP::GetPluginDescriptionStatic() {
99 return "KDP Remote protocol based debugging plug-in for darwin kernel "
100 "debugging.";
Greg Claytonf9765ac2011-07-15 03:27:12 +0000101}
102
Kate Stoneb9c1b512016-09-06 20:57:50 +0000103void ProcessKDP::Terminate() {
104 PluginManager::UnregisterPlugin(ProcessKDP::CreateInstance);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000105}
106
Kate Stoneb9c1b512016-09-06 20:57:50 +0000107lldb::ProcessSP ProcessKDP::CreateInstance(TargetSP target_sp,
108 ListenerSP listener_sp,
109 const FileSpec *crash_file_path) {
110 lldb::ProcessSP process_sp;
111 if (crash_file_path == NULL)
Jonas Devlieghere796ac802019-02-11 23:13:08 +0000112 process_sp = std::make_shared<ProcessKDP>(target_sp, listener_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000113 return process_sp;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000114}
115
Kate Stoneb9c1b512016-09-06 20:57:50 +0000116bool ProcessKDP::CanDebug(TargetSP target_sp, bool plugin_specified_by_name) {
117 if (plugin_specified_by_name)
118 return true;
Greg Clayton596ed242011-10-21 21:41:45 +0000119
Kate Stoneb9c1b512016-09-06 20:57:50 +0000120 // For now we are just making sure the file exists for a given module
121 Module *exe_module = target_sp->GetExecutableModulePointer();
122 if (exe_module) {
123 const llvm::Triple &triple_ref = target_sp->GetArchitecture().GetTriple();
124 switch (triple_ref.getOS()) {
125 case llvm::Triple::Darwin: // Should use "macosx" for desktop and "ios" for
126 // iOS, but accept darwin just in case
127 case llvm::Triple::MacOSX: // For desktop targets
128 case llvm::Triple::IOS: // For arm targets
129 case llvm::Triple::TvOS:
130 case llvm::Triple::WatchOS:
131 if (triple_ref.getVendor() == llvm::Triple::Apple) {
132 ObjectFile *exe_objfile = exe_module->GetObjectFile();
133 if (exe_objfile->GetType() == ObjectFile::eTypeExecutable &&
134 exe_objfile->GetStrata() == ObjectFile::eStrataKernel)
135 return true;
136 }
137 break;
Greg Clayton70512312012-05-08 01:45:38 +0000138
Kate Stoneb9c1b512016-09-06 20:57:50 +0000139 default:
140 break;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000141 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000142 }
143 return false;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000144}
145
146//----------------------------------------------------------------------
147// ProcessKDP constructor
148//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000149ProcessKDP::ProcessKDP(TargetSP target_sp, ListenerSP listener_sp)
150 : Process(target_sp, listener_sp),
151 m_comm("lldb.process.kdp-remote.communication"),
152 m_async_broadcaster(NULL, "lldb.process.kdp-remote.async-broadcaster"),
153 m_dyld_plugin_name(), m_kernel_load_addr(LLDB_INVALID_ADDRESS),
154 m_command_sp(), m_kernel_thread_wp() {
155 m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadShouldExit,
156 "async thread should exit");
157 m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue,
158 "async thread continue");
159 const uint64_t timeout_seconds =
160 GetGlobalPluginProperties()->GetPacketTimeout();
161 if (timeout_seconds > 0)
Pavel Labath5cddd602016-11-02 10:13:54 +0000162 m_comm.SetPacketTimeout(std::chrono::seconds(timeout_seconds));
Greg Claytonf9765ac2011-07-15 03:27:12 +0000163}
164
165//----------------------------------------------------------------------
166// Destructor
167//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000168ProcessKDP::~ProcessKDP() {
169 Clear();
Adrian Prantl05097242018-04-30 16:49:04 +0000170 // We need to call finalize on the process before destroying ourselves to
171 // make sure all of the broadcaster cleanup goes as planned. If we destruct
172 // this class, then Process::~Process() might have problems trying to fully
173 // destroy the broadcaster.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000174 Finalize();
Greg Claytonf9765ac2011-07-15 03:27:12 +0000175}
176
177//----------------------------------------------------------------------
178// PluginInterface
179//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000180lldb_private::ConstString ProcessKDP::GetPluginName() {
181 return GetPluginNameStatic();
Greg Claytonf9765ac2011-07-15 03:27:12 +0000182}
183
Kate Stoneb9c1b512016-09-06 20:57:50 +0000184uint32_t ProcessKDP::GetPluginVersion() { return 1; }
185
Zachary Turner97206d52017-05-12 04:51:55 +0000186Status ProcessKDP::WillLaunch(Module *module) {
187 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000188 error.SetErrorString("launching not supported in kdp-remote plug-in");
189 return error;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000190}
191
Zachary Turner97206d52017-05-12 04:51:55 +0000192Status ProcessKDP::WillAttachToProcessWithID(lldb::pid_t pid) {
193 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000194 error.SetErrorString(
195 "attaching to a by process ID not supported in kdp-remote plug-in");
196 return error;
197}
198
Zachary Turner97206d52017-05-12 04:51:55 +0000199Status ProcessKDP::WillAttachToProcessWithName(const char *process_name,
200 bool wait_for_launch) {
201 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000202 error.SetErrorString(
203 "attaching to a by process name not supported in kdp-remote plug-in");
204 return error;
205}
206
207bool ProcessKDP::GetHostArchitecture(ArchSpec &arch) {
208 uint32_t cpu = m_comm.GetCPUType();
209 if (cpu) {
210 uint32_t sub = m_comm.GetCPUSubtype();
211 arch.SetArchitecture(eArchTypeMachO, cpu, sub);
212 // Leave architecture vendor as unspecified unknown
213 arch.GetTriple().setVendor(llvm::Triple::UnknownVendor);
214 arch.GetTriple().setVendorName(llvm::StringRef());
215 return true;
216 }
217 arch.Clear();
218 return false;
219}
220
Zachary Turner97206d52017-05-12 04:51:55 +0000221Status ProcessKDP::DoConnectRemote(Stream *strm, llvm::StringRef remote_url) {
222 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000223
Adrian Prantl05097242018-04-30 16:49:04 +0000224 // Don't let any JIT happen when doing KDP as we can't allocate memory and we
225 // don't want to be mucking with threads that might already be handling
226 // exceptions
Kate Stoneb9c1b512016-09-06 20:57:50 +0000227 SetCanJIT(false);
228
Greg Clayton3ce7e992016-12-07 23:51:49 +0000229 if (remote_url.empty()) {
230 error.SetErrorStringWithFormat("empty connection URL");
Greg Claytonf9765ac2011-07-15 03:27:12 +0000231 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000232 }
Greg Claytonf9765ac2011-07-15 03:27:12 +0000233
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000234 std::unique_ptr<ConnectionFileDescriptor> conn_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000235 new ConnectionFileDescriptor());
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000236 if (conn_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000237 // Only try once for now.
238 // TODO: check if we should be retrying?
239 const uint32_t max_retry_count = 1;
240 for (uint32_t retry_count = 0; retry_count < max_retry_count;
241 ++retry_count) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000242 if (conn_up->Connect(remote_url, &error) == eConnectionStatusSuccess)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000243 break;
244 usleep(100000);
Greg Claytona3706882015-10-28 23:26:59 +0000245 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000246 }
Greg Claytona3706882015-10-28 23:26:59 +0000247
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000248 if (conn_up->IsConnected()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000249 const TCPSocket &socket =
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000250 static_cast<const TCPSocket &>(*conn_up->GetReadObject());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000251 const uint16_t reply_port = socket.GetLocalPortNumber();
Greg Clayton7925fbb2012-09-21 16:31:20 +0000252
Kate Stoneb9c1b512016-09-06 20:57:50 +0000253 if (reply_port != 0) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000254 m_comm.SetConnection(conn_up.release());
Greg Clayton7925fbb2012-09-21 16:31:20 +0000255
Kate Stoneb9c1b512016-09-06 20:57:50 +0000256 if (m_comm.SendRequestReattach(reply_port)) {
257 if (m_comm.SendRequestConnect(reply_port, reply_port,
258 "Greetings from LLDB...")) {
259 m_comm.GetVersion();
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000260
Kate Stoneb9c1b512016-09-06 20:57:50 +0000261 Target &target = GetTarget();
262 ArchSpec kernel_arch;
263 // The host architecture
264 GetHostArchitecture(kernel_arch);
265 ArchSpec target_arch = target.GetArchitecture();
266 // Merge in any unspecified stuff into the target architecture in
267 // case the target arch isn't set at all or incompletely.
268 target_arch.MergeFrom(kernel_arch);
269 target.SetArchitecture(target_arch);
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000270
Kate Stoneb9c1b512016-09-06 20:57:50 +0000271 /* Get the kernel's UUID and load address via KDP_KERNELVERSION
272 * packet. */
273 /* An EFI kdp session has neither UUID nor load address. */
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000274
Kate Stoneb9c1b512016-09-06 20:57:50 +0000275 UUID kernel_uuid = m_comm.GetUUID();
276 addr_t kernel_load_addr = m_comm.GetLoadAddress();
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000277
Kate Stoneb9c1b512016-09-06 20:57:50 +0000278 if (m_comm.RemoteIsEFI()) {
279 // Select an invalid plugin name for the dynamic loader so one
Adrian Prantl05097242018-04-30 16:49:04 +0000280 // doesn't get used since EFI does its own manual loading via
281 // python scripting
Kate Stoneb9c1b512016-09-06 20:57:50 +0000282 static ConstString g_none_dynamic_loader("none");
283 m_dyld_plugin_name = g_none_dynamic_loader;
Greg Claytona3706882015-10-28 23:26:59 +0000284
Kate Stoneb9c1b512016-09-06 20:57:50 +0000285 if (kernel_uuid.IsValid()) {
Adrian Prantl05097242018-04-30 16:49:04 +0000286 // If EFI passed in a UUID= try to lookup UUID The slide will not
287 // be provided. But the UUID lookup will be used to launch EFI
288 // debug scripts from the dSYM, that can load all of the symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000289 ModuleSpec module_spec;
290 module_spec.GetUUID() = kernel_uuid;
291 module_spec.GetArchitecture() = target.GetArchitecture();
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000292
Kate Stoneb9c1b512016-09-06 20:57:50 +0000293 // Lookup UUID locally, before attempting dsymForUUID like action
294 module_spec.GetSymbolFileSpec() =
295 Symbols::LocateExecutableSymbolFile(module_spec);
296 if (module_spec.GetSymbolFileSpec()) {
297 ModuleSpec executable_module_spec =
298 Symbols::LocateExecutableObjectFile(module_spec);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +0000299 if (FileSystem::Instance().Exists(
300 executable_module_spec.GetFileSpec())) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000301 module_spec.GetFileSpec() =
302 executable_module_spec.GetFileSpec();
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000303 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000304 }
305 if (!module_spec.GetSymbolFileSpec() ||
306 !module_spec.GetSymbolFileSpec())
307 Symbols::DownloadObjectAndSymbolFile(module_spec, true);
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000308
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +0000309 if (FileSystem::Instance().Exists(module_spec.GetFileSpec())) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000310 ModuleSP module_sp(new Module(module_spec));
311 if (module_sp.get() && module_sp->GetObjectFile()) {
312 // Get the current target executable
313 ModuleSP exe_module_sp(target.GetExecutableModule());
314
315 // Make sure you don't already have the right module loaded
316 // and they will be uniqued
317 if (exe_module_sp.get() != module_sp.get())
Jonas Devliegheref9a07e92018-09-20 09:09:05 +0000318 target.SetExecutableModule(module_sp, eLoadDependentsNo);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000319 }
320 }
321 }
322 } else if (m_comm.RemoteIsDarwinKernel()) {
323 m_dyld_plugin_name =
324 DynamicLoaderDarwinKernel::GetPluginNameStatic();
325 if (kernel_load_addr != LLDB_INVALID_ADDRESS) {
326 m_kernel_load_addr = kernel_load_addr;
327 }
328 }
329
330 // Set the thread ID
331 UpdateThreadListIfNeeded();
332 SetID(1);
333 GetThreadList();
334 SetPrivateState(eStateStopped);
335 StreamSP async_strm_sp(target.GetDebugger().GetAsyncOutputStream());
336 if (async_strm_sp) {
337 const char *cstr;
338 if ((cstr = m_comm.GetKernelVersion()) != NULL) {
339 async_strm_sp->Printf("Version: %s\n", cstr);
340 async_strm_sp->Flush();
341 }
342 // if ((cstr = m_comm.GetImagePath ()) != NULL)
343 // {
344 // async_strm_sp->Printf ("Image Path:
345 // %s\n", cstr);
346 // async_strm_sp->Flush();
347 // }
348 }
349 } else {
350 error.SetErrorString("KDP_REATTACH failed");
351 }
352 } else {
353 error.SetErrorString("KDP_REATTACH failed");
354 }
355 } else {
356 error.SetErrorString("invalid reply port from UDP connection");
357 }
358 } else {
359 if (error.Success())
Greg Clayton3ce7e992016-12-07 23:51:49 +0000360 error.SetErrorStringWithFormat("failed to connect to '%s'",
361 remote_url.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000362 }
363 if (error.Fail())
364 m_comm.Disconnect();
365
366 return error;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000367}
368
369//----------------------------------------------------------------------
370// Process Control
371//----------------------------------------------------------------------
Zachary Turner97206d52017-05-12 04:51:55 +0000372Status ProcessKDP::DoLaunch(Module *exe_module,
373 ProcessLaunchInfo &launch_info) {
374 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000375 error.SetErrorString("launching not supported in kdp-remote plug-in");
376 return error;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000377}
378
Zachary Turner97206d52017-05-12 04:51:55 +0000379Status
380ProcessKDP::DoAttachToProcessWithID(lldb::pid_t attach_pid,
381 const ProcessAttachInfo &attach_info) {
382 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000383 error.SetErrorString(
Bruce Mitchener4ebdee02018-05-29 09:10:46 +0000384 "attach to process by ID is not supported in kdp remote debugging");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000385 return error;
Han Ming Ong84647042012-02-25 01:07:38 +0000386}
387
Zachary Turner97206d52017-05-12 04:51:55 +0000388Status
389ProcessKDP::DoAttachToProcessWithName(const char *process_name,
390 const ProcessAttachInfo &attach_info) {
391 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000392 error.SetErrorString(
Bruce Mitchener4ebdee02018-05-29 09:10:46 +0000393 "attach to process by name is not supported in kdp remote debugging");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000394 return error;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000395}
396
Kate Stoneb9c1b512016-09-06 20:57:50 +0000397void ProcessKDP::DidAttach(ArchSpec &process_arch) {
398 Process::DidAttach(process_arch);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000399
Kate Stoneb9c1b512016-09-06 20:57:50 +0000400 Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
401 if (log)
402 log->Printf("ProcessKDP::DidAttach()");
403 if (GetID() != LLDB_INVALID_PROCESS_ID) {
404 GetHostArchitecture(process_arch);
405 }
406}
407
408addr_t ProcessKDP::GetImageInfoAddress() { return m_kernel_load_addr; }
409
410lldb_private::DynamicLoader *ProcessKDP::GetDynamicLoader() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000411 if (m_dyld_up.get() == NULL)
412 m_dyld_up.reset(DynamicLoader::FindPlugin(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000413 this,
414 m_dyld_plugin_name.IsEmpty() ? NULL : m_dyld_plugin_name.GetCString()));
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000415 return m_dyld_up.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000416}
417
Zachary Turner97206d52017-05-12 04:51:55 +0000418Status ProcessKDP::WillResume() { return Status(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000419
Zachary Turner97206d52017-05-12 04:51:55 +0000420Status ProcessKDP::DoResume() {
421 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000422 Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
423 // Only start the async thread if we try to do any process control
424 if (!m_async_thread.IsJoinable())
425 StartAsyncThread();
426
427 bool resume = false;
428
429 // With KDP there is only one thread we can tell what to do
430 ThreadSP kernel_thread_sp(m_thread_list.FindThreadByProtocolID(g_kernel_tid));
431
432 if (kernel_thread_sp) {
433 const StateType thread_resume_state =
434 kernel_thread_sp->GetTemporaryResumeState();
435
Greg Claytonf9765ac2011-07-15 03:27:12 +0000436 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000437 log->Printf("ProcessKDP::DoResume() thread_resume_state = %s",
438 StateAsCString(thread_resume_state));
439 switch (thread_resume_state) {
440 case eStateSuspended:
Adrian Prantl05097242018-04-30 16:49:04 +0000441 // Nothing to do here when a thread will stay suspended we just leave the
442 // CPU mask bit set to zero for the thread
Kate Stoneb9c1b512016-09-06 20:57:50 +0000443 if (log)
444 log->Printf("ProcessKDP::DoResume() = suspended???");
445 break;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000446
Kate Stoneb9c1b512016-09-06 20:57:50 +0000447 case eStateStepping: {
448 lldb::RegisterContextSP reg_ctx_sp(
449 kernel_thread_sp->GetRegisterContext());
Jason Molenda5e8534e2012-10-03 01:29:34 +0000450
Kate Stoneb9c1b512016-09-06 20:57:50 +0000451 if (reg_ctx_sp) {
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000452 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000453 log->Printf(
454 "ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep (true);");
455 reg_ctx_sp->HardwareSingleStep(true);
456 resume = true;
457 } else {
458 error.SetErrorStringWithFormat(
459 "KDP thread 0x%llx has no register context",
460 kernel_thread_sp->GetID());
461 }
462 } break;
Greg Clayton1afa68e2013-04-02 20:32:37 +0000463
Kate Stoneb9c1b512016-09-06 20:57:50 +0000464 case eStateRunning: {
465 lldb::RegisterContextSP reg_ctx_sp(
466 kernel_thread_sp->GetRegisterContext());
Greg Clayton97d5cf02012-09-25 02:40:06 +0000467
Kate Stoneb9c1b512016-09-06 20:57:50 +0000468 if (reg_ctx_sp) {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000469 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000470 log->Printf("ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep "
471 "(false);");
472 reg_ctx_sp->HardwareSingleStep(false);
473 resume = true;
474 } else {
475 error.SetErrorStringWithFormat(
476 "KDP thread 0x%llx has no register context",
477 kernel_thread_sp->GetID());
478 }
479 } break;
480
481 default:
482 // The only valid thread resume states are listed above
David Blaikiea322f362017-01-06 00:38:06 +0000483 llvm_unreachable("invalid thread resume state");
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) {
Jonas Devlieghere796ac802019-02-11 23:13:08 +0000509 thread_sp = std::make_shared<ThreadKDP>(*this, g_kernel_tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000510 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));
Pavel Labath250858a2017-02-06 21:46:22 +0000519 LLDB_LOGV(log, "pid = {0}", GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000520
521 // Even though there is a CPU mask, it doesn't mean we can see each CPU
522 // individually, there is really only one. Lets call this thread 1.
523 ThreadSP thread_sp(
524 old_thread_list.FindThreadByProtocolID(g_kernel_tid, false));
525 if (!thread_sp)
526 thread_sp = GetKernelThread();
527 new_thread_list.AddThread(thread_sp);
528
529 return new_thread_list.GetSize(false) > 0;
530}
531
532void ProcessKDP::RefreshStateAfterStop() {
Adrian Prantl05097242018-04-30 16:49:04 +0000533 // Let all threads recover from stopping and do any clean up based on the
534 // previous thread state (if any).
Kate Stoneb9c1b512016-09-06 20:57:50 +0000535 m_thread_list.RefreshStateAfterStop();
536}
537
Zachary Turner97206d52017-05-12 04:51:55 +0000538Status ProcessKDP::DoHalt(bool &caused_stop) {
539 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000540
541 if (m_comm.IsRunning()) {
542 if (m_destroy_in_process) {
Bruce Mitchener4ebdee02018-05-29 09:10:46 +0000543 // If we are attempting to destroy, we need to not return an error to Halt
Adrian Prantl05097242018-04-30 16:49:04 +0000544 // or DoDestroy won't get called. We are also currently running, so send
545 // a process stopped event
Kate Stoneb9c1b512016-09-06 20:57:50 +0000546 SetPrivateState(eStateStopped);
547 } else {
548 error.SetErrorString("KDP cannot interrupt a running kernel");
549 }
550 }
551 return error;
552}
553
Zachary Turner97206d52017-05-12 04:51:55 +0000554Status ProcessKDP::DoDetach(bool keep_stopped) {
555 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000556 Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
557 if (log)
558 log->Printf("ProcessKDP::DoDetach(keep_stopped = %i)", keep_stopped);
559
560 if (m_comm.IsRunning()) {
Adrian Prantl05097242018-04-30 16:49:04 +0000561 // We are running and we can't interrupt a running kernel, so we need to
562 // just close the connection to the kernel and hope for the best
Kate Stoneb9c1b512016-09-06 20:57:50 +0000563 } else {
564 // If we are going to keep the target stopped, then don't send the
565 // disconnect message.
566 if (!keep_stopped && m_comm.IsConnected()) {
567 const bool success = m_comm.SendRequestDisconnect();
568 if (log) {
569 if (success)
570 log->PutCString(
571 "ProcessKDP::DoDetach() detach packet sent successfully");
572 else
573 log->PutCString(
574 "ProcessKDP::DoDetach() connection channel shutdown failed");
575 }
576 m_comm.Disconnect();
577 }
578 }
579 StopAsyncThread();
580 m_comm.Clear();
581
582 SetPrivateState(eStateDetached);
583 ResumePrivateStateThread();
584
585 // KillDebugserverProcess ();
586 return error;
587}
588
Zachary Turner97206d52017-05-12 04:51:55 +0000589Status ProcessKDP::DoDestroy() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000590 // For KDP there really is no difference between destroy and detach
591 bool keep_stopped = false;
592 return DoDetach(keep_stopped);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000593}
594
595//------------------------------------------------------------------
596// Process Queries
597//------------------------------------------------------------------
598
Kate Stoneb9c1b512016-09-06 20:57:50 +0000599bool ProcessKDP::IsAlive() {
600 return m_comm.IsConnected() && Process::IsAlive();
Greg Claytonf9765ac2011-07-15 03:27:12 +0000601}
602
603//------------------------------------------------------------------
604// Process Memory
605//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000606size_t ProcessKDP::DoReadMemory(addr_t addr, void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +0000607 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000608 uint8_t *data_buffer = (uint8_t *)buf;
609 if (m_comm.IsConnected()) {
610 const size_t max_read_size = 512;
611 size_t total_bytes_read = 0;
Jason Molenda8eb32812014-05-21 23:44:02 +0000612
Kate Stoneb9c1b512016-09-06 20:57:50 +0000613 // Read the requested amount of memory in 512 byte chunks
614 while (total_bytes_read < size) {
615 size_t bytes_to_read_this_request = size - total_bytes_read;
616 if (bytes_to_read_this_request > max_read_size) {
617 bytes_to_read_this_request = max_read_size;
618 }
619 size_t bytes_read = m_comm.SendRequestReadMemory(
620 addr + total_bytes_read, data_buffer + total_bytes_read,
621 bytes_to_read_this_request, error);
622 total_bytes_read += bytes_read;
623 if (error.Fail() || bytes_read == 0) {
Jason Molenda8eb32812014-05-21 23:44:02 +0000624 return total_bytes_read;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000625 }
Jason Molenda8eb32812014-05-21 23:44:02 +0000626 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000627
628 return total_bytes_read;
629 }
630 error.SetErrorString("not connected");
631 return 0;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000632}
633
Kate Stoneb9c1b512016-09-06 20:57:50 +0000634size_t ProcessKDP::DoWriteMemory(addr_t addr, const void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +0000635 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000636 if (m_comm.IsConnected())
637 return m_comm.SendRequestWriteMemory(addr, buf, size, error);
638 error.SetErrorString("not connected");
639 return 0;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000640}
641
Kate Stoneb9c1b512016-09-06 20:57:50 +0000642lldb::addr_t ProcessKDP::DoAllocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +0000643 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000644 error.SetErrorString(
Bruce Mitchener4ebdee02018-05-29 09:10:46 +0000645 "memory allocation not supported in kdp remote debugging");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000646 return LLDB_INVALID_ADDRESS;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000647}
648
Zachary Turner97206d52017-05-12 04:51:55 +0000649Status ProcessKDP::DoDeallocateMemory(lldb::addr_t addr) {
650 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000651 error.SetErrorString(
Bruce Mitchener4ebdee02018-05-29 09:10:46 +0000652 "memory deallocation not supported in kdp remote debugging");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000653 return error;
654}
655
Zachary Turner97206d52017-05-12 04:51:55 +0000656Status ProcessKDP::EnableBreakpointSite(BreakpointSite *bp_site) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000657 if (m_comm.LocalBreakpointsAreSupported()) {
Zachary Turner97206d52017-05-12 04:51:55 +0000658 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000659 if (!bp_site->IsEnabled()) {
660 if (m_comm.SendRequestBreakpoint(true, bp_site->GetLoadAddress())) {
661 bp_site->SetEnabled(true);
662 bp_site->SetType(BreakpointSite::eExternal);
663 } else {
664 error.SetErrorString("KDP set breakpoint failed");
665 }
666 }
Greg Claytonf9765ac2011-07-15 03:27:12 +0000667 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000668 }
669 return EnableSoftwareBreakpoint(bp_site);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000670}
671
Zachary Turner97206d52017-05-12 04:51:55 +0000672Status ProcessKDP::DisableBreakpointSite(BreakpointSite *bp_site) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000673 if (m_comm.LocalBreakpointsAreSupported()) {
Zachary Turner97206d52017-05-12 04:51:55 +0000674 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000675 if (bp_site->IsEnabled()) {
676 BreakpointSite::Type bp_type = bp_site->GetType();
677 if (bp_type == BreakpointSite::eExternal) {
678 if (m_destroy_in_process && m_comm.IsRunning()) {
679 // We are trying to destroy our connection and we are running
680 bp_site->SetEnabled(false);
681 } else {
682 if (m_comm.SendRequestBreakpoint(false, bp_site->GetLoadAddress()))
683 bp_site->SetEnabled(false);
684 else
685 error.SetErrorString("KDP remove breakpoint failed");
Greg Clayton5b882162011-07-21 01:12:01 +0000686 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000687 } else {
688 error = DisableSoftwareBreakpoint(bp_site);
689 }
Greg Clayton07e66e32011-07-20 03:41:06 +0000690 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000691 return error;
692 }
693 return DisableSoftwareBreakpoint(bp_site);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000694}
695
Zachary Turner97206d52017-05-12 04:51:55 +0000696Status ProcessKDP::EnableWatchpoint(Watchpoint *wp, bool notify) {
697 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000698 error.SetErrorString(
Bruce Mitchener4ebdee02018-05-29 09:10:46 +0000699 "watchpoints are not supported in kdp remote debugging");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000700 return error;
701}
702
Zachary Turner97206d52017-05-12 04:51:55 +0000703Status ProcessKDP::DisableWatchpoint(Watchpoint *wp, bool notify) {
704 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000705 error.SetErrorString(
Bruce Mitchener4ebdee02018-05-29 09:10:46 +0000706 "watchpoints are not supported in kdp remote debugging");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000707 return error;
708}
709
710void ProcessKDP::Clear() { m_thread_list.Clear(); }
711
Zachary Turner97206d52017-05-12 04:51:55 +0000712Status ProcessKDP::DoSignal(int signo) {
713 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000714 error.SetErrorString(
Bruce Mitchener4ebdee02018-05-29 09:10:46 +0000715 "sending signals is not supported in kdp remote debugging");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000716 return error;
717}
718
719void ProcessKDP::Initialize() {
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +0000720 static llvm::once_flag g_once_flag;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000721
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +0000722 llvm::call_once(g_once_flag, []() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000723 PluginManager::RegisterPlugin(GetPluginNameStatic(),
724 GetPluginDescriptionStatic(), CreateInstance,
725 DebuggerInitialize);
726
Pavel Labath7b35b782017-02-17 15:08:08 +0000727 ProcessKDPLog::Initialize();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000728 });
729}
730
731void ProcessKDP::DebuggerInitialize(lldb_private::Debugger &debugger) {
732 if (!PluginManager::GetSettingForProcessPlugin(
733 debugger, PluginProperties::GetSettingName())) {
734 const bool is_global_setting = true;
735 PluginManager::CreateSettingForProcessPlugin(
736 debugger, GetGlobalPluginProperties()->GetValueProperties(),
737 ConstString("Properties for the kdp-remote process plug-in."),
738 is_global_setting);
739 }
740}
741
742bool ProcessKDP::StartAsyncThread() {
743 Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
744
745 if (log)
746 log->Printf("ProcessKDP::StartAsyncThread ()");
747
748 if (m_async_thread.IsJoinable())
749 return true;
750
751 m_async_thread = ThreadLauncher::LaunchThread(
752 "<lldb.process.kdp-remote.async>", ProcessKDP::AsyncThread, this, NULL);
753 return m_async_thread.IsJoinable();
754}
755
756void ProcessKDP::StopAsyncThread() {
757 Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
758
759 if (log)
760 log->Printf("ProcessKDP::StopAsyncThread ()");
761
762 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
763
764 // Stop the stdio thread
765 if (m_async_thread.IsJoinable())
766 m_async_thread.Join(nullptr);
767}
768
769void *ProcessKDP::AsyncThread(void *arg) {
770 ProcessKDP *process = (ProcessKDP *)arg;
771
772 const lldb::pid_t pid = process->GetID();
773
774 Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
775 if (log)
776 log->Printf("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64
777 ") thread starting...",
778 arg, pid);
779
780 ListenerSP listener_sp(Listener::MakeListener("ProcessKDP::AsyncThread"));
781 EventSP event_sp;
782 const uint32_t desired_event_mask =
783 eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
784
785 if (listener_sp->StartListeningForEvents(&process->m_async_broadcaster,
786 desired_event_mask) ==
787 desired_event_mask) {
788 bool done = false;
789 while (!done) {
790 if (log)
791 log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
792 ") listener.WaitForEvent (NULL, event_sp)...",
793 pid);
Pavel Labathfafff0c2016-11-30 11:09:47 +0000794 if (listener_sp->GetEvent(event_sp, llvm::None)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000795 uint32_t event_type = event_sp->GetType();
796 if (log)
797 log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
798 ") Got an event of type: %d...",
799 pid, event_type);
800
801 // When we are running, poll for 1 second to try and get an exception
802 // to indicate the process has stopped. If we don't get one, check to
803 // make sure no one asked us to exit
804 bool is_running = false;
805 DataExtractor exc_reply_packet;
806 do {
807 switch (event_type) {
808 case eBroadcastBitAsyncContinue: {
809 is_running = true;
810 if (process->m_comm.WaitForPacketWithTimeoutMicroSeconds(
811 exc_reply_packet, 1 * USEC_PER_SEC)) {
812 ThreadSP thread_sp(process->GetKernelThread());
813 if (thread_sp) {
814 lldb::RegisterContextSP reg_ctx_sp(
815 thread_sp->GetRegisterContext());
816 if (reg_ctx_sp)
817 reg_ctx_sp->InvalidateAllRegisters();
818 static_cast<ThreadKDP *>(thread_sp.get())
819 ->SetStopInfoFrom_KDP_EXCEPTION(exc_reply_packet);
820 }
821
822 // TODO: parse the stop reply packet
823 is_running = false;
824 process->SetPrivateState(eStateStopped);
825 } else {
826 // Check to see if we are supposed to exit. There is no way to
827 // interrupt a running kernel, so all we can do is wait for an
828 // exception or detach...
Pavel Labathfafff0c2016-11-30 11:09:47 +0000829 if (listener_sp->GetEvent(event_sp,
830 std::chrono::microseconds(0))) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000831 // We got an event, go through the loop again
832 event_type = event_sp->GetType();
833 }
Greg Clayton5b882162011-07-21 01:12:01 +0000834 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000835 } break;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000836
Kate Stoneb9c1b512016-09-06 20:57:50 +0000837 case eBroadcastBitAsyncThreadShouldExit:
Greg Claytonf9765ac2011-07-15 03:27:12 +0000838 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000839 log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
840 ") got eBroadcastBitAsyncThreadShouldExit...",
841 pid);
842 done = true;
843 is_running = false;
844 break;
Greg Clayton97d5cf02012-09-25 02:40:06 +0000845
Kate Stoneb9c1b512016-09-06 20:57:50 +0000846 default:
847 if (log)
848 log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
849 ") got unknown event 0x%8.8x",
850 pid, event_type);
851 done = true;
852 is_running = false;
853 break;
854 }
855 } while (is_running);
856 } else {
857 if (log)
858 log->Printf("ProcessKDP::AsyncThread (pid = %" PRIu64
859 ") listener.WaitForEvent (NULL, event_sp) => false",
860 pid);
861 done = true;
862 }
Greg Claytonf9765ac2011-07-15 03:27:12 +0000863 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000864 }
Zachary Turner39de3112014-09-09 20:54:56 +0000865
Kate Stoneb9c1b512016-09-06 20:57:50 +0000866 if (log)
867 log->Printf("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64
868 ") thread exiting...",
869 arg, pid);
870
871 process->m_async_thread.Reset();
872 return NULL;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000873}
874
Kate Stoneb9c1b512016-09-06 20:57:50 +0000875class CommandObjectProcessKDPPacketSend : public CommandObjectParsed {
Greg Clayton1d19a2f2012-10-19 22:22:57 +0000876private:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000877 OptionGroupOptions m_option_group;
878 OptionGroupUInt64 m_command_byte;
879 OptionGroupString m_packet_data;
880
881 virtual Options *GetOptions() { return &m_option_group; }
Greg Clayton1d19a2f2012-10-19 22:22:57 +0000882
883public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000884 CommandObjectProcessKDPPacketSend(CommandInterpreter &interpreter)
885 : CommandObjectParsed(interpreter, "process plugin packet send",
886 "Send a custom packet through the KDP protocol by "
887 "specifying the command byte and the packet "
888 "payload data. A packet will be sent with a "
889 "correct header and payload, and the raw result "
890 "bytes will be displayed as a string value. ",
891 NULL),
Todd Fialae1cfbc72016-08-11 23:51:28 +0000892 m_option_group(),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000893 m_command_byte(LLDB_OPT_SET_1, true, "command", 'c', 0, eArgTypeNone,
894 "Specify the command byte to use when sending the KDP "
895 "request packet.",
896 0),
897 m_packet_data(LLDB_OPT_SET_1, false, "payload", 'p', 0, eArgTypeNone,
898 "Specify packet payload bytes as a hex ASCII string with "
899 "no spaces or hex prefixes.",
900 NULL) {
901 m_option_group.Append(&m_command_byte, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
902 m_option_group.Append(&m_packet_data, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
903 m_option_group.Finalize();
904 }
905
906 ~CommandObjectProcessKDPPacketSend() {}
907
908 bool DoExecute(Args &command, CommandReturnObject &result) {
909 const size_t argc = command.GetArgumentCount();
910 if (argc == 0) {
911 if (!m_command_byte.GetOptionValue().OptionWasSet()) {
912 result.AppendError(
913 "the --command option must be set to a valid command byte");
914 result.SetStatus(eReturnStatusFailed);
915 } else {
916 const uint64_t command_byte =
917 m_command_byte.GetOptionValue().GetUInt64Value(0);
918 if (command_byte > 0 && command_byte <= UINT8_MAX) {
919 ProcessKDP *process =
920 (ProcessKDP *)m_interpreter.GetExecutionContext().GetProcessPtr();
921 if (process) {
922 const StateType state = process->GetState();
923
924 if (StateIsStoppedState(state, true)) {
925 std::vector<uint8_t> payload_bytes;
926 const char *ascii_hex_bytes_cstr =
927 m_packet_data.GetOptionValue().GetCurrentValue();
928 if (ascii_hex_bytes_cstr && ascii_hex_bytes_cstr[0]) {
929 StringExtractor extractor(ascii_hex_bytes_cstr);
930 const size_t ascii_hex_bytes_cstr_len =
931 extractor.GetStringRef().size();
932 if (ascii_hex_bytes_cstr_len & 1) {
933 result.AppendErrorWithFormat("payload data must contain an "
934 "even number of ASCII hex "
935 "characters: '%s'",
936 ascii_hex_bytes_cstr);
937 result.SetStatus(eReturnStatusFailed);
938 return false;
Greg Clayton1d19a2f2012-10-19 22:22:57 +0000939 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000940 payload_bytes.resize(ascii_hex_bytes_cstr_len / 2);
941 if (extractor.GetHexBytes(payload_bytes, '\xdd') !=
942 payload_bytes.size()) {
943 result.AppendErrorWithFormat("payload data must only contain "
944 "ASCII hex characters (no "
945 "spaces or hex prefixes): '%s'",
946 ascii_hex_bytes_cstr);
947 result.SetStatus(eReturnStatusFailed);
948 return false;
949 }
950 }
Zachary Turner97206d52017-05-12 04:51:55 +0000951 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000952 DataExtractor reply;
953 process->GetCommunication().SendRawRequest(
954 command_byte,
955 payload_bytes.empty() ? NULL : payload_bytes.data(),
956 payload_bytes.size(), reply, error);
957
958 if (error.Success()) {
959 // Copy the binary bytes into a hex ASCII string for the result
960 StreamString packet;
961 packet.PutBytesAsRawHex8(
962 reply.GetDataStart(), reply.GetByteSize(),
963 endian::InlHostByteOrder(), endian::InlHostByteOrder());
Zachary Turnerc1564272016-11-16 21:15:24 +0000964 result.AppendMessage(packet.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000965 result.SetStatus(eReturnStatusSuccessFinishResult);
966 return true;
967 } else {
968 const char *error_cstr = error.AsCString();
969 if (error_cstr && error_cstr[0])
970 result.AppendError(error_cstr);
Greg Clayton1d19a2f2012-10-19 22:22:57 +0000971 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000972 result.AppendErrorWithFormat("unknown error 0x%8.8x",
973 error.GetError());
974 result.SetStatus(eReturnStatusFailed);
975 return false;
976 }
977 } else {
978 result.AppendErrorWithFormat("process must be stopped in order "
979 "to send KDP packets, state is %s",
980 StateAsCString(state));
981 result.SetStatus(eReturnStatusFailed);
Greg Clayton1d19a2f2012-10-19 22:22:57 +0000982 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000983 } else {
984 result.AppendError("invalid process");
985 result.SetStatus(eReturnStatusFailed);
986 }
987 } else {
988 result.AppendErrorWithFormat("invalid command byte 0x%" PRIx64
989 ", valid values are 1 - 255",
990 command_byte);
991 result.SetStatus(eReturnStatusFailed);
Greg Clayton1d19a2f2012-10-19 22:22:57 +0000992 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000993 }
994 } else {
995 result.AppendErrorWithFormat("'%s' takes no arguments, only options.",
996 m_cmd_name.c_str());
997 result.SetStatus(eReturnStatusFailed);
Greg Clayton1d19a2f2012-10-19 22:22:57 +0000998 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000999 return false;
1000 }
Greg Clayton1d19a2f2012-10-19 22:22:57 +00001001};
1002
Kate Stoneb9c1b512016-09-06 20:57:50 +00001003class CommandObjectProcessKDPPacket : public CommandObjectMultiword {
Greg Clayton1d19a2f2012-10-19 22:22:57 +00001004private:
Greg Clayton1d19a2f2012-10-19 22:22:57 +00001005public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001006 CommandObjectProcessKDPPacket(CommandInterpreter &interpreter)
1007 : CommandObjectMultiword(interpreter, "process plugin packet",
1008 "Commands that deal with KDP remote packets.",
1009 NULL) {
1010 LoadSubCommand(
1011 "send",
1012 CommandObjectSP(new CommandObjectProcessKDPPacketSend(interpreter)));
1013 }
1014
1015 ~CommandObjectProcessKDPPacket() {}
Greg Clayton1d19a2f2012-10-19 22:22:57 +00001016};
1017
Kate Stoneb9c1b512016-09-06 20:57:50 +00001018class CommandObjectMultiwordProcessKDP : public CommandObjectMultiword {
Greg Clayton1d19a2f2012-10-19 22:22:57 +00001019public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001020 CommandObjectMultiwordProcessKDP(CommandInterpreter &interpreter)
1021 : CommandObjectMultiword(
1022 interpreter, "process plugin",
1023 "Commands for operating on a ProcessKDP process.",
1024 "process plugin <subcommand> [<subcommand-options>]") {
1025 LoadSubCommand("packet", CommandObjectSP(new CommandObjectProcessKDPPacket(
1026 interpreter)));
1027 }
1028
1029 ~CommandObjectMultiwordProcessKDP() {}
Greg Clayton1d19a2f2012-10-19 22:22:57 +00001030};
1031
Kate Stoneb9c1b512016-09-06 20:57:50 +00001032CommandObject *ProcessKDP::GetPluginCommandObject() {
1033 if (!m_command_sp)
Jonas Devlieghere796ac802019-02-11 23:13:08 +00001034 m_command_sp = std::make_shared<CommandObjectMultiwordProcessKDP>(
1035 GetTarget().GetDebugger().GetCommandInterpreter());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001036 return m_command_sp.get();
Greg Clayton1d19a2f2012-10-19 22:22:57 +00001037}