blob: f99bb2c0e9f2216fdb6d09e191f7e284eefa35cd [file] [log] [blame]
Greg Clayton59ec5122011-07-15 18:02:58 +00001//===-- ProcessKDP.cpp ------------------------------------------*- C++ -*-===//
Greg Claytonf9765ac2011-07-15 03:27:12 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10// C Includes
11#include <errno.h>
12#include <stdlib.h>
13
14// C++ Includes
Benjamin Kramer3f69fa62015-04-03 10:55:00 +000015#include <mutex>
16
Greg Claytonf9765ac2011-07-15 03:27:12 +000017// Other libraries and framework includes
Greg Clayton07e66e32011-07-20 03:41:06 +000018#include "lldb/Core/Debugger.h"
Greg Claytonf9765ac2011-07-15 03:27:12 +000019#include "lldb/Core/PluginManager.h"
Greg Clayton1f746072012-08-29 21:13:06 +000020#include "lldb/Core/Module.h"
Jason Molenda4bd4e7e2012-09-29 04:02:01 +000021#include "lldb/Core/ModuleSpec.h"
Greg Claytonf9765ac2011-07-15 03:27:12 +000022#include "lldb/Core/State.h"
Jason Molenda4bd4e7e2012-09-29 04:02:01 +000023#include "lldb/Core/UUID.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000024#include "lldb/Host/ConnectionFileDescriptor.h"
Greg Claytonf9765ac2011-07-15 03:27:12 +000025#include "lldb/Host/Host.h"
Jason Molenda4bd4e7e2012-09-29 04:02:01 +000026#include "lldb/Host/Symbols.h"
Zachary Turner39de3112014-09-09 20:54:56 +000027#include "lldb/Host/ThreadLauncher.h"
Oleksiy Vyalove98628c2015-10-15 23:54:09 +000028#include "lldb/Host/common/TCPSocket.h"
Greg Clayton1d19a2f2012-10-19 22:22:57 +000029#include "lldb/Interpreter/CommandInterpreter.h"
30#include "lldb/Interpreter/CommandObject.h"
31#include "lldb/Interpreter/CommandObjectMultiword.h"
32#include "lldb/Interpreter/CommandReturnObject.h"
33#include "lldb/Interpreter/OptionGroupString.h"
34#include "lldb/Interpreter/OptionGroupUInt64.h"
Ilia K41204d02015-03-04 12:05:24 +000035#include "lldb/Interpreter/OptionValueProperties.h"
Greg Clayton1f746072012-08-29 21:13:06 +000036#include "lldb/Symbol/ObjectFile.h"
Greg Clayton7925fbb2012-09-21 16:31:20 +000037#include "lldb/Target/RegisterContext.h"
Greg Clayton57508022011-07-15 16:31:38 +000038#include "lldb/Target/Target.h"
Greg Claytona63d08c2011-07-19 03:57:15 +000039#include "lldb/Target/Thread.h"
Bruce Mitchener45788152015-07-07 23:59:01 +000040#include "lldb/Utility/StringExtractor.h"
Greg Claytonf9765ac2011-07-15 03:27:12 +000041
Charles Davis510938e2013-08-27 05:04:57 +000042#define USEC_PER_SEC 1000000
43
Greg Claytonf9765ac2011-07-15 03:27:12 +000044// Project includes
45#include "ProcessKDP.h"
46#include "ProcessKDPLog.h"
Greg Claytona63d08c2011-07-19 03:57:15 +000047#include "ThreadKDP.h"
Jason Molenda5e8534e2012-10-03 01:29:34 +000048#include "Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.h"
Jason Molenda840f12c2012-10-25 00:25:13 +000049#include "Plugins/DynamicLoader/Static/DynamicLoaderStatic.h"
Greg Claytonf9765ac2011-07-15 03:27:12 +000050
51using namespace lldb;
52using namespace lldb_private;
53
Greg Clayton7f982402013-07-15 22:54:20 +000054namespace {
55
56 static PropertyDefinition
57 g_properties[] =
58 {
59 { "packet-timeout" , OptionValue::eTypeUInt64 , true , 5, NULL, NULL, "Specify the default packet timeout in seconds." },
60 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
61 };
62
63 enum
64 {
65 ePropertyPacketTimeout
66 };
67
68 class PluginProperties : public Properties
69 {
70 public:
71
72 static ConstString
73 GetSettingName ()
74 {
75 return ProcessKDP::GetPluginNameStatic();
76 }
77
78 PluginProperties() :
79 Properties ()
80 {
81 m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
82 m_collection_sp->Initialize(g_properties);
83 }
84
85 virtual
86 ~PluginProperties()
87 {
88 }
89
90 uint64_t
91 GetPacketTimeout()
92 {
93 const uint32_t idx = ePropertyPacketTimeout;
94 return m_collection_sp->GetPropertyAtIndexAsUInt64(NULL, idx, g_properties[idx].default_uint_value);
95 }
96 };
97
98 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
99
100 static const ProcessKDPPropertiesSP &
101 GetGlobalPluginProperties()
102 {
103 static ProcessKDPPropertiesSP g_settings_sp;
104 if (!g_settings_sp)
105 g_settings_sp.reset (new PluginProperties ());
106 return g_settings_sp;
107 }
108
109} // anonymous namespace end
110
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000111static const lldb::tid_t g_kernel_tid = 1;
112
Greg Clayton57abc5d2013-05-10 21:47:16 +0000113ConstString
Greg Claytonf9765ac2011-07-15 03:27:12 +0000114ProcessKDP::GetPluginNameStatic()
115{
Greg Clayton57abc5d2013-05-10 21:47:16 +0000116 static ConstString g_name("kdp-remote");
117 return g_name;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000118}
119
120const char *
121ProcessKDP::GetPluginDescriptionStatic()
122{
123 return "KDP Remote protocol based debugging plug-in for darwin kernel debugging.";
124}
125
126void
127ProcessKDP::Terminate()
128{
129 PluginManager::UnregisterPlugin (ProcessKDP::CreateInstance);
130}
131
132
Greg Claytonc3776bf2012-02-09 06:16:32 +0000133lldb::ProcessSP
Jim Ingham5a3bb642015-09-01 22:56:59 +0000134ProcessKDP::CreateInstance (TargetSP target_sp,
Jim Ingham583bbb12016-03-07 21:50:25 +0000135 ListenerSP listener_sp,
Greg Claytonc3776bf2012-02-09 06:16:32 +0000136 const FileSpec *crash_file_path)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000137{
Greg Claytonc3776bf2012-02-09 06:16:32 +0000138 lldb::ProcessSP process_sp;
139 if (crash_file_path == NULL)
Jim Ingham583bbb12016-03-07 21:50:25 +0000140 process_sp.reset(new ProcessKDP (target_sp, listener_sp));
Greg Claytonc3776bf2012-02-09 06:16:32 +0000141 return process_sp;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000142}
143
144bool
Jim Ingham5a3bb642015-09-01 22:56:59 +0000145ProcessKDP::CanDebug(TargetSP target_sp, bool plugin_specified_by_name)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000146{
Greg Clayton596ed242011-10-21 21:41:45 +0000147 if (plugin_specified_by_name)
148 return true;
149
Greg Claytonf9765ac2011-07-15 03:27:12 +0000150 // For now we are just making sure the file exists for a given module
Jim Ingham5a3bb642015-09-01 22:56:59 +0000151 Module *exe_module = target_sp->GetExecutableModulePointer();
Greg Claytonaa149cb2011-08-11 02:48:45 +0000152 if (exe_module)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000153 {
Jim Ingham5a3bb642015-09-01 22:56:59 +0000154 const llvm::Triple &triple_ref = target_sp->GetArchitecture().GetTriple();
Greg Clayton70512312012-05-08 01:45:38 +0000155 switch (triple_ref.getOS())
Greg Claytonf9765ac2011-07-15 03:27:12 +0000156 {
Greg Clayton70512312012-05-08 01:45:38 +0000157 case llvm::Triple::Darwin: // Should use "macosx" for desktop and "ios" for iOS, but accept darwin just in case
158 case llvm::Triple::MacOSX: // For desktop targets
159 case llvm::Triple::IOS: // For arm targets
Jason Molendaa814f702015-11-05 23:03:44 +0000160 case llvm::Triple::TvOS:
161 case llvm::Triple::WatchOS:
Greg Clayton70512312012-05-08 01:45:38 +0000162 if (triple_ref.getVendor() == llvm::Triple::Apple)
163 {
164 ObjectFile *exe_objfile = exe_module->GetObjectFile();
165 if (exe_objfile->GetType() == ObjectFile::eTypeExecutable &&
166 exe_objfile->GetStrata() == ObjectFile::eStrataKernel)
167 return true;
168 }
169 break;
170
171 default:
172 break;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000173 }
174 }
Greg Clayton596ed242011-10-21 21:41:45 +0000175 return false;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000176}
177
178//----------------------------------------------------------------------
179// ProcessKDP constructor
180//----------------------------------------------------------------------
Jim Ingham583bbb12016-03-07 21:50:25 +0000181ProcessKDP::ProcessKDP(TargetSP target_sp, ListenerSP listener_sp) :
182 Process (target_sp, listener_sp),
Greg Claytonf9765ac2011-07-15 03:27:12 +0000183 m_comm("lldb.process.kdp-remote.communication"),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000184 m_async_broadcaster (NULL, "lldb.process.kdp-remote.async-broadcaster"),
Jason Molenda5e8534e2012-10-03 01:29:34 +0000185 m_dyld_plugin_name (),
Greg Clayton1d19a2f2012-10-19 22:22:57 +0000186 m_kernel_load_addr (LLDB_INVALID_ADDRESS),
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000187 m_command_sp(),
188 m_kernel_thread_wp()
Greg Claytonf9765ac2011-07-15 03:27:12 +0000189{
Greg Clayton7925fbb2012-09-21 16:31:20 +0000190 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
191 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Greg Clayton7f982402013-07-15 22:54:20 +0000192 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
193 if (timeout_seconds > 0)
194 m_comm.SetPacketTimeout(timeout_seconds);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000195}
196
197//----------------------------------------------------------------------
198// Destructor
199//----------------------------------------------------------------------
200ProcessKDP::~ProcessKDP()
201{
202 Clear();
Greg Claytone24c4ac2011-11-17 04:46:02 +0000203 // We need to call finalize on the process before destroying ourselves
204 // to make sure all of the broadcaster cleanup goes as planned. If we
205 // destruct this class, then Process::~Process() might have problems
206 // trying to fully destroy the broadcaster.
207 Finalize();
Greg Claytonf9765ac2011-07-15 03:27:12 +0000208}
209
210//----------------------------------------------------------------------
211// PluginInterface
212//----------------------------------------------------------------------
Greg Clayton57abc5d2013-05-10 21:47:16 +0000213lldb_private::ConstString
Greg Claytonf9765ac2011-07-15 03:27:12 +0000214ProcessKDP::GetPluginName()
215{
Greg Claytonf9765ac2011-07-15 03:27:12 +0000216 return GetPluginNameStatic();
217}
218
219uint32_t
220ProcessKDP::GetPluginVersion()
221{
222 return 1;
223}
224
225Error
226ProcessKDP::WillLaunch (Module* module)
227{
228 Error error;
229 error.SetErrorString ("launching not supported in kdp-remote plug-in");
230 return error;
231}
232
233Error
234ProcessKDP::WillAttachToProcessWithID (lldb::pid_t pid)
235{
236 Error error;
237 error.SetErrorString ("attaching to a by process ID not supported in kdp-remote plug-in");
238 return error;
239}
240
241Error
242ProcessKDP::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
243{
244 Error error;
245 error.SetErrorString ("attaching to a by process name not supported in kdp-remote plug-in");
246 return error;
247}
248
Greg Claytona3706882015-10-28 23:26:59 +0000249bool
250ProcessKDP::GetHostArchitecture(ArchSpec &arch)
251{
252 uint32_t cpu = m_comm.GetCPUType();
253 if (cpu)
254 {
255 uint32_t sub = m_comm.GetCPUSubtype();
256 arch.SetArchitecture(eArchTypeMachO, cpu, sub);
257 // Leave architecture vendor as unspecified unknown
258 arch.GetTriple().setVendor(llvm::Triple::UnknownVendor);
259 arch.GetTriple().setVendorName(llvm::StringRef());
260 return true;
261 }
262 arch.Clear();
263 return false;
264}
265
Greg Claytonf9765ac2011-07-15 03:27:12 +0000266Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000267ProcessKDP::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000268{
Greg Claytonf9765ac2011-07-15 03:27:12 +0000269 Error error;
Greg Clayton7925fbb2012-09-21 16:31:20 +0000270
271 // Don't let any JIT happen when doing KDP as we can't allocate
272 // memory and we don't want to be mucking with threads that might
273 // already be handling exceptions
274 SetCanJIT(false);
275
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000276 if (remote_url == NULL || remote_url[0] == '\0')
Greg Clayton7925fbb2012-09-21 16:31:20 +0000277 {
278 error.SetErrorStringWithFormat ("invalid connection URL '%s'", remote_url);
279 return error;
280 }
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000281
Greg Clayton7b0992d2013-04-18 22:45:39 +0000282 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000283 if (conn_ap.get())
284 {
285 // Only try once for now.
286 // TODO: check if we should be retrying?
287 const uint32_t max_retry_count = 1;
288 for (uint32_t retry_count = 0; retry_count < max_retry_count; ++retry_count)
289 {
290 if (conn_ap->Connect(remote_url, &error) == eConnectionStatusSuccess)
291 break;
292 usleep (100000);
293 }
294 }
295
296 if (conn_ap->IsConnected())
297 {
Oleksiy Vyalove98628c2015-10-15 23:54:09 +0000298 const TCPSocket& socket = static_cast<const TCPSocket&>(*conn_ap->GetReadObject());
Vince Harron014bb7d2015-01-16 00:47:08 +0000299 const uint16_t reply_port = socket.GetLocalPortNumber();
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000300
301 if (reply_port != 0)
302 {
303 m_comm.SetConnection(conn_ap.release());
304
305 if (m_comm.SendRequestReattach(reply_port))
306 {
307 if (m_comm.SendRequestConnect(reply_port, reply_port, "Greetings from LLDB..."))
308 {
309 m_comm.GetVersion();
Greg Claytona3706882015-10-28 23:26:59 +0000310
Jim Ingham5a3bb642015-09-01 22:56:59 +0000311 Target &target = GetTarget();
Greg Claytona3706882015-10-28 23:26:59 +0000312 ArchSpec kernel_arch;
313 // The host architecture
314 GetHostArchitecture(kernel_arch);
315 ArchSpec target_arch = target.GetArchitecture();
316 // Merge in any unspecified stuff into the target architecture in
317 // case the target arch isn't set at all or incompletely.
318 target_arch.MergeFrom(kernel_arch);
319 target.SetArchitecture(target_arch);
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000320
Jason Molenda840f12c2012-10-25 00:25:13 +0000321 /* Get the kernel's UUID and load address via KDP_KERNELVERSION packet. */
322 /* An EFI kdp session has neither UUID nor load address. */
323
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000324 UUID kernel_uuid = m_comm.GetUUID ();
325 addr_t kernel_load_addr = m_comm.GetLoadAddress ();
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000326
Jason Molenda840f12c2012-10-25 00:25:13 +0000327 if (m_comm.RemoteIsEFI ())
328 {
Greg Claytona1bce2e2014-07-16 21:16:27 +0000329 // Select an invalid plugin name for the dynamic loader so one doesn't get used
330 // since EFI does its own manual loading via python scripting
331 static ConstString g_none_dynamic_loader("none");
332 m_dyld_plugin_name = g_none_dynamic_loader;
333
334 if (kernel_uuid.IsValid()) {
335 // If EFI passed in a UUID= try to lookup UUID
336 // The slide will not be provided. But the UUID
337 // lookup will be used to launch EFI debug scripts
338 // from the dSYM, that can load all of the symbols.
339 ModuleSpec module_spec;
340 module_spec.GetUUID() = kernel_uuid;
Jim Ingham5a3bb642015-09-01 22:56:59 +0000341 module_spec.GetArchitecture() = target.GetArchitecture();
Greg Claytona1bce2e2014-07-16 21:16:27 +0000342
343 // Lookup UUID locally, before attempting dsymForUUID like action
344 module_spec.GetSymbolFileSpec() = Symbols::LocateExecutableSymbolFile(module_spec);
345 if (module_spec.GetSymbolFileSpec())
Jason Molenda8825c5c2015-10-08 21:48:35 +0000346 {
347 ModuleSpec executable_module_spec = Symbols::LocateExecutableObjectFile (module_spec);
348 if (executable_module_spec.GetFileSpec().Exists())
349 {
350 module_spec.GetFileSpec() = executable_module_spec.GetFileSpec();
351 }
352 }
Greg Claytona1bce2e2014-07-16 21:16:27 +0000353 if (!module_spec.GetSymbolFileSpec() || !module_spec.GetSymbolFileSpec())
354 Symbols::DownloadObjectAndSymbolFile (module_spec, true);
355
356 if (module_spec.GetFileSpec().Exists())
357 {
Greg Claytona3706882015-10-28 23:26:59 +0000358 ModuleSP module_sp(new Module (module_spec));
359 if (module_sp.get() && module_sp->GetObjectFile())
Greg Claytona1bce2e2014-07-16 21:16:27 +0000360 {
361 // Get the current target executable
Jim Ingham5a3bb642015-09-01 22:56:59 +0000362 ModuleSP exe_module_sp (target.GetExecutableModule ());
Greg Claytona1bce2e2014-07-16 21:16:27 +0000363
364 // Make sure you don't already have the right module loaded and they will be uniqued
365 if (exe_module_sp.get() != module_sp.get())
Jim Ingham5a3bb642015-09-01 22:56:59 +0000366 target.SetExecutableModule (module_sp, false);
Greg Claytona1bce2e2014-07-16 21:16:27 +0000367 }
368 }
369 }
Jason Molenda840f12c2012-10-25 00:25:13 +0000370 }
Jason Molendaca2ffa72013-05-09 23:52:21 +0000371 else if (m_comm.RemoteIsDarwinKernel ())
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000372 {
Jason Molendaca2ffa72013-05-09 23:52:21 +0000373 m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
Jason Molendaa8ea4ba2013-05-06 23:02:03 +0000374 if (kernel_load_addr != LLDB_INVALID_ADDRESS)
375 {
376 m_kernel_load_addr = kernel_load_addr;
377 }
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000378 }
379
Greg Clayton97d5cf02012-09-25 02:40:06 +0000380 // Set the thread ID
381 UpdateThreadListIfNeeded ();
Greg Claytona63d08c2011-07-19 03:57:15 +0000382 SetID (1);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000383 GetThreadList ();
Greg Claytona63d08c2011-07-19 03:57:15 +0000384 SetPrivateState (eStateStopped);
Jim Ingham5a3bb642015-09-01 22:56:59 +0000385 StreamSP async_strm_sp(target.GetDebugger().GetAsyncOutputStream());
Greg Clayton07e66e32011-07-20 03:41:06 +0000386 if (async_strm_sp)
387 {
Greg Clayton5b882162011-07-21 01:12:01 +0000388 const char *cstr;
389 if ((cstr = m_comm.GetKernelVersion ()) != NULL)
Greg Clayton07e66e32011-07-20 03:41:06 +0000390 {
Greg Clayton5b882162011-07-21 01:12:01 +0000391 async_strm_sp->Printf ("Version: %s\n", cstr);
Greg Clayton07e66e32011-07-20 03:41:06 +0000392 async_strm_sp->Flush();
393 }
Greg Clayton5b882162011-07-21 01:12:01 +0000394// if ((cstr = m_comm.GetImagePath ()) != NULL)
395// {
396// async_strm_sp->Printf ("Image Path: %s\n", cstr);
397// async_strm_sp->Flush();
398// }
Greg Clayton07e66e32011-07-20 03:41:06 +0000399 }
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000400 }
Greg Clayton97d5cf02012-09-25 02:40:06 +0000401 else
402 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000403 error.SetErrorString("KDP_REATTACH failed");
404 }
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000405 }
406 else
407 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000408 error.SetErrorString("KDP_REATTACH failed");
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000409 }
410 }
411 else
412 {
413 error.SetErrorString("invalid reply port from UDP connection");
414 }
415 }
416 else
417 {
418 if (error.Success())
419 error.SetErrorStringWithFormat ("failed to connect to '%s'", remote_url);
420 }
421 if (error.Fail())
422 m_comm.Disconnect();
423
Greg Claytonf9765ac2011-07-15 03:27:12 +0000424 return error;
425}
426
427//----------------------------------------------------------------------
428// Process Control
429//----------------------------------------------------------------------
430Error
Greg Clayton982c9762011-11-03 21:22:33 +0000431ProcessKDP::DoLaunch (Module *exe_module,
Jean-Daniel Dupas7782de92013-12-09 22:52:50 +0000432 ProcessLaunchInfo &launch_info)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000433{
434 Error error;
435 error.SetErrorString ("launching not supported in kdp-remote plug-in");
436 return error;
437}
438
Greg Claytonf9765ac2011-07-15 03:27:12 +0000439Error
Han Ming Ong84647042012-02-25 01:07:38 +0000440ProcessKDP::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
441{
442 Error error;
443 error.SetErrorString ("attach to process by ID is not suppported in kdp remote debugging");
444 return error;
445}
446
447Error
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +0000448ProcessKDP::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000449{
450 Error error;
451 error.SetErrorString ("attach to process by name is not suppported in kdp remote debugging");
452 return error;
453}
454
455
456void
Jim Inghambb006ce2014-08-02 00:33:35 +0000457ProcessKDP::DidAttach (ArchSpec &process_arch)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000458{
Jim Inghambb006ce2014-08-02 00:33:35 +0000459 Process::DidAttach(process_arch);
460
Greg Clayton5160ce52013-03-27 23:08:40 +0000461 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_PROCESS));
Greg Claytonf9765ac2011-07-15 03:27:12 +0000462 if (log)
Johnny Chen54cb8f82011-10-11 21:17:10 +0000463 log->Printf ("ProcessKDP::DidAttach()");
Greg Claytonf9765ac2011-07-15 03:27:12 +0000464 if (GetID() != LLDB_INVALID_PROCESS_ID)
465 {
Greg Claytona3706882015-10-28 23:26:59 +0000466 GetHostArchitecture(process_arch);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000467 }
468}
469
Jason Molenda5e8534e2012-10-03 01:29:34 +0000470addr_t
471ProcessKDP::GetImageInfoAddress()
472{
473 return m_kernel_load_addr;
474}
475
476lldb_private::DynamicLoader *
477ProcessKDP::GetDynamicLoader ()
478{
479 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +0000480 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, m_dyld_plugin_name.IsEmpty() ? NULL : m_dyld_plugin_name.GetCString()));
Jason Molenda5e8534e2012-10-03 01:29:34 +0000481 return m_dyld_ap.get();
482}
483
Greg Claytonf9765ac2011-07-15 03:27:12 +0000484Error
485ProcessKDP::WillResume ()
486{
487 return Error();
488}
489
490Error
491ProcessKDP::DoResume ()
492{
493 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +0000494 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_PROCESS));
Greg Clayton7925fbb2012-09-21 16:31:20 +0000495 // Only start the async thread if we try to do any process control
Zachary Turneracee96a2014-09-23 18:32:09 +0000496 if (!m_async_thread.IsJoinable())
Zachary Turner39de3112014-09-09 20:54:56 +0000497 StartAsyncThread();
Greg Clayton7925fbb2012-09-21 16:31:20 +0000498
Greg Clayton97d5cf02012-09-25 02:40:06 +0000499 bool resume = false;
Greg Clayton7925fbb2012-09-21 16:31:20 +0000500
Greg Clayton97d5cf02012-09-25 02:40:06 +0000501 // With KDP there is only one thread we can tell what to do
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000502 ThreadSP kernel_thread_sp (m_thread_list.FindThreadByProtocolID(g_kernel_tid));
503
Greg Clayton97d5cf02012-09-25 02:40:06 +0000504 if (kernel_thread_sp)
Greg Clayton4b1b8b32012-09-21 01:55:30 +0000505 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000506 const StateType thread_resume_state = kernel_thread_sp->GetTemporaryResumeState();
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000507
508 if (log)
509 log->Printf ("ProcessKDP::DoResume() thread_resume_state = %s", StateAsCString(thread_resume_state));
Greg Clayton7925fbb2012-09-21 16:31:20 +0000510 switch (thread_resume_state)
Greg Clayton4b1b8b32012-09-21 01:55:30 +0000511 {
Greg Clayton7925fbb2012-09-21 16:31:20 +0000512 case eStateSuspended:
513 // Nothing to do here when a thread will stay suspended
514 // we just leave the CPU mask bit set to zero for the thread
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000515 if (log)
516 log->Printf ("ProcessKDP::DoResume() = suspended???");
Greg Clayton7925fbb2012-09-21 16:31:20 +0000517 break;
518
519 case eStateStepping:
Greg Clayton1afa68e2013-04-02 20:32:37 +0000520 {
521 lldb::RegisterContextSP reg_ctx_sp (kernel_thread_sp->GetRegisterContext());
522
523 if (reg_ctx_sp)
524 {
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000525 if (log)
526 log->Printf ("ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep (true);");
Greg Clayton1afa68e2013-04-02 20:32:37 +0000527 reg_ctx_sp->HardwareSingleStep (true);
528 resume = true;
529 }
530 else
531 {
532 error.SetErrorStringWithFormat("KDP thread 0x%llx has no register context", kernel_thread_sp->GetID());
533 }
534 }
Greg Clayton97d5cf02012-09-25 02:40:06 +0000535 break;
536
Greg Clayton7925fbb2012-09-21 16:31:20 +0000537 case eStateRunning:
Greg Clayton1afa68e2013-04-02 20:32:37 +0000538 {
539 lldb::RegisterContextSP reg_ctx_sp (kernel_thread_sp->GetRegisterContext());
540
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000541 if (reg_ctx_sp)
542 {
543 if (log)
544 log->Printf ("ProcessKDP::DoResume () reg_ctx_sp->HardwareSingleStep (false);");
545 reg_ctx_sp->HardwareSingleStep (false);
546 resume = true;
547 }
548 else
549 {
550 error.SetErrorStringWithFormat("KDP thread 0x%llx has no register context", kernel_thread_sp->GetID());
551 }
Greg Clayton1afa68e2013-04-02 20:32:37 +0000552 }
Greg Clayton7925fbb2012-09-21 16:31:20 +0000553 break;
Greg Clayton97d5cf02012-09-25 02:40:06 +0000554
Greg Clayton7925fbb2012-09-21 16:31:20 +0000555 default:
Greg Clayton97d5cf02012-09-25 02:40:06 +0000556 // The only valid thread resume states are listed above
Greg Clayton7925fbb2012-09-21 16:31:20 +0000557 assert (!"invalid thread resume state");
558 break;
Greg Clayton4b1b8b32012-09-21 01:55:30 +0000559 }
560 }
Greg Clayton97d5cf02012-09-25 02:40:06 +0000561
562 if (resume)
Greg Clayton7925fbb2012-09-21 16:31:20 +0000563 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000564 if (log)
565 log->Printf ("ProcessKDP::DoResume () sending resume");
Greg Clayton7925fbb2012-09-21 16:31:20 +0000566
Greg Clayton97d5cf02012-09-25 02:40:06 +0000567 if (m_comm.SendRequestResume ())
Greg Clayton7925fbb2012-09-21 16:31:20 +0000568 {
569 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue);
570 SetPrivateState(eStateRunning);
571 }
572 else
573 error.SetErrorString ("KDP resume failed");
574 }
Greg Clayton4b1b8b32012-09-21 01:55:30 +0000575 else
Greg Clayton7925fbb2012-09-21 16:31:20 +0000576 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000577 error.SetErrorString ("kernel thread is suspended");
Greg Clayton7925fbb2012-09-21 16:31:20 +0000578 }
579
Greg Claytonf9765ac2011-07-15 03:27:12 +0000580 return error;
581}
582
Greg Clayton97d5cf02012-09-25 02:40:06 +0000583lldb::ThreadSP
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000584ProcessKDP::GetKernelThread()
Greg Clayton97d5cf02012-09-25 02:40:06 +0000585{
586 // KDP only tells us about one thread/core. Any other threads will usually
587 // be the ones that are read from memory by the OS plug-ins.
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000588
589 ThreadSP thread_sp (m_kernel_thread_wp.lock());
Greg Clayton97d5cf02012-09-25 02:40:06 +0000590 if (!thread_sp)
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000591 {
592 thread_sp.reset(new ThreadKDP (*this, g_kernel_tid));
593 m_kernel_thread_wp = thread_sp;
594 }
Greg Clayton97d5cf02012-09-25 02:40:06 +0000595 return thread_sp;
596}
597
598
599
600
Greg Clayton9fc13552012-04-10 00:18:59 +0000601bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000602ProcessKDP::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000603{
604 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +0000605 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_THREAD));
Greg Claytonf9765ac2011-07-15 03:27:12 +0000606 if (log && log->GetMask().Test(KDP_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +0000607 log->Printf ("ProcessKDP::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Claytonf9765ac2011-07-15 03:27:12 +0000608
Greg Clayton39da3ef2013-04-11 22:23:34 +0000609 // Even though there is a CPU mask, it doesn't mean we can see each CPU
Bruce Mitchenera868c132015-07-02 18:48:40 +0000610 // individually, there is really only one. Lets call this thread 1.
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000611 ThreadSP thread_sp (old_thread_list.FindThreadByProtocolID(g_kernel_tid, false));
612 if (!thread_sp)
613 thread_sp = GetKernelThread ();
614 new_thread_list.AddThread(thread_sp);
Greg Clayton97d5cf02012-09-25 02:40:06 +0000615
Greg Clayton9fc13552012-04-10 00:18:59 +0000616 return new_thread_list.GetSize(false) > 0;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000617}
618
Greg Claytonf9765ac2011-07-15 03:27:12 +0000619void
620ProcessKDP::RefreshStateAfterStop ()
621{
622 // Let all threads recover from stopping and do any clean up based
623 // on the previous thread state (if any).
624 m_thread_list.RefreshStateAfterStop();
Greg Claytonf9765ac2011-07-15 03:27:12 +0000625}
626
627Error
628ProcessKDP::DoHalt (bool &caused_stop)
629{
630 Error error;
631
Greg Clayton97d5cf02012-09-25 02:40:06 +0000632 if (m_comm.IsRunning())
Greg Claytonf9765ac2011-07-15 03:27:12 +0000633 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000634 if (m_destroy_in_process)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000635 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000636 // If we are attemping to destroy, we need to not return an error to
637 // Halt or DoDestroy won't get called.
638 // We are also currently running, so send a process stopped event
639 SetPrivateState (eStateStopped);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000640 }
Greg Clayton97d5cf02012-09-25 02:40:06 +0000641 else
Greg Claytonf9765ac2011-07-15 03:27:12 +0000642 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000643 error.SetErrorString ("KDP cannot interrupt a running kernel");
Greg Claytonf9765ac2011-07-15 03:27:12 +0000644 }
645 }
646 return error;
647}
648
649Error
Jim Inghamacff8952013-05-02 00:27:30 +0000650ProcessKDP::DoDetach(bool keep_stopped)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000651{
652 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +0000653 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
Greg Claytonf9765ac2011-07-15 03:27:12 +0000654 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +0000655 log->Printf ("ProcessKDP::DoDetach(keep_stopped = %i)", keep_stopped);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000656
Greg Clayton97d5cf02012-09-25 02:40:06 +0000657 if (m_comm.IsRunning())
Greg Claytonf9765ac2011-07-15 03:27:12 +0000658 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000659 // We are running and we can't interrupt a running kernel, so we need
660 // to just close the connection to the kernel and hope for the best
661 }
662 else
663 {
Jim Inghamacff8952013-05-02 00:27:30 +0000664 // If we are going to keep the target stopped, then don't send the disconnect message.
665 if (!keep_stopped && m_comm.IsConnected())
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000666 {
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000667 const bool success = m_comm.SendRequestDisconnect();
Greg Clayton97d5cf02012-09-25 02:40:06 +0000668 if (log)
669 {
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000670 if (success)
671 log->PutCString ("ProcessKDP::DoDetach() detach packet sent successfully");
Greg Clayton97d5cf02012-09-25 02:40:06 +0000672 else
Jim Ingham77e82d12013-05-09 00:05:35 +0000673 log->PutCString ("ProcessKDP::DoDetach() connection channel shutdown failed");
Greg Clayton97d5cf02012-09-25 02:40:06 +0000674 }
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000675 m_comm.Disconnect ();
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000676 }
Greg Claytonf9765ac2011-07-15 03:27:12 +0000677 }
Greg Clayton97d5cf02012-09-25 02:40:06 +0000678 StopAsyncThread ();
Greg Clayton74d41932012-01-31 04:56:17 +0000679 m_comm.Clear();
Greg Claytonf9765ac2011-07-15 03:27:12 +0000680
681 SetPrivateState (eStateDetached);
682 ResumePrivateStateThread();
683
684 //KillDebugserverProcess ();
685 return error;
686}
687
688Error
689ProcessKDP::DoDestroy ()
690{
Greg Clayton7925fbb2012-09-21 16:31:20 +0000691 // For KDP there really is no difference between destroy and detach
Jim Inghamacff8952013-05-02 00:27:30 +0000692 bool keep_stopped = false;
693 return DoDetach(keep_stopped);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000694}
695
696//------------------------------------------------------------------
697// Process Queries
698//------------------------------------------------------------------
699
700bool
701ProcessKDP::IsAlive ()
702{
Jason Molendaa814f702015-11-05 23:03:44 +0000703 return m_comm.IsConnected() && Process::IsAlive();
Greg Claytonf9765ac2011-07-15 03:27:12 +0000704}
705
706//------------------------------------------------------------------
707// Process Memory
708//------------------------------------------------------------------
709size_t
710ProcessKDP::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
711{
Jason Molenda8eb32812014-05-21 23:44:02 +0000712 uint8_t *data_buffer = (uint8_t *) buf;
Greg Claytona63d08c2011-07-19 03:57:15 +0000713 if (m_comm.IsConnected())
Jason Molenda8eb32812014-05-21 23:44:02 +0000714 {
715 const size_t max_read_size = 512;
716 size_t total_bytes_read = 0;
717
718 // Read the requested amount of memory in 512 byte chunks
719 while (total_bytes_read < size)
720 {
721 size_t bytes_to_read_this_request = size - total_bytes_read;
722 if (bytes_to_read_this_request > max_read_size)
723 {
724 bytes_to_read_this_request = max_read_size;
725 }
726 size_t bytes_read = m_comm.SendRequestReadMemory (addr + total_bytes_read,
727 data_buffer + total_bytes_read,
728 bytes_to_read_this_request, error);
729 total_bytes_read += bytes_read;
730 if (error.Fail() || bytes_read == 0)
731 {
732 return total_bytes_read;
733 }
734 }
735
736 return total_bytes_read;
737 }
Greg Claytona63d08c2011-07-19 03:57:15 +0000738 error.SetErrorString ("not connected");
Greg Claytonf9765ac2011-07-15 03:27:12 +0000739 return 0;
740}
741
742size_t
743ProcessKDP::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
744{
Greg Clayton7925fbb2012-09-21 16:31:20 +0000745 if (m_comm.IsConnected())
746 return m_comm.SendRequestWriteMemory (addr, buf, size, error);
747 error.SetErrorString ("not connected");
Greg Claytonf9765ac2011-07-15 03:27:12 +0000748 return 0;
749}
750
751lldb::addr_t
752ProcessKDP::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
753{
754 error.SetErrorString ("memory allocation not suppported in kdp remote debugging");
755 return LLDB_INVALID_ADDRESS;
756}
757
758Error
759ProcessKDP::DoDeallocateMemory (lldb::addr_t addr)
760{
761 Error error;
762 error.SetErrorString ("memory deallocation not suppported in kdp remote debugging");
763 return error;
764}
765
766Error
Jim Ingham299c0c12013-02-15 02:06:30 +0000767ProcessKDP::EnableBreakpointSite (BreakpointSite *bp_site)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000768{
Greg Clayton07e66e32011-07-20 03:41:06 +0000769 if (m_comm.LocalBreakpointsAreSupported ())
770 {
771 Error error;
Greg Clayton5b882162011-07-21 01:12:01 +0000772 if (!bp_site->IsEnabled())
773 {
774 if (m_comm.SendRequestBreakpoint(true, bp_site->GetLoadAddress()))
775 {
776 bp_site->SetEnabled(true);
777 bp_site->SetType (BreakpointSite::eExternal);
778 }
779 else
780 {
781 error.SetErrorString ("KDP set breakpoint failed");
782 }
783 }
Greg Clayton07e66e32011-07-20 03:41:06 +0000784 return error;
785 }
Greg Claytonf9765ac2011-07-15 03:27:12 +0000786 return EnableSoftwareBreakpoint (bp_site);
787}
788
789Error
Jim Ingham299c0c12013-02-15 02:06:30 +0000790ProcessKDP::DisableBreakpointSite (BreakpointSite *bp_site)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000791{
Greg Clayton07e66e32011-07-20 03:41:06 +0000792 if (m_comm.LocalBreakpointsAreSupported ())
793 {
794 Error error;
Greg Clayton5b882162011-07-21 01:12:01 +0000795 if (bp_site->IsEnabled())
796 {
797 BreakpointSite::Type bp_type = bp_site->GetType();
798 if (bp_type == BreakpointSite::eExternal)
799 {
Greg Clayton97d5cf02012-09-25 02:40:06 +0000800 if (m_destroy_in_process && m_comm.IsRunning())
801 {
802 // We are trying to destroy our connection and we are running
Greg Clayton5b882162011-07-21 01:12:01 +0000803 bp_site->SetEnabled(false);
Greg Clayton97d5cf02012-09-25 02:40:06 +0000804 }
Greg Clayton5b882162011-07-21 01:12:01 +0000805 else
Greg Clayton97d5cf02012-09-25 02:40:06 +0000806 {
807 if (m_comm.SendRequestBreakpoint(false, bp_site->GetLoadAddress()))
808 bp_site->SetEnabled(false);
809 else
810 error.SetErrorString ("KDP remove breakpoint failed");
811 }
Greg Clayton5b882162011-07-21 01:12:01 +0000812 }
813 else
814 {
815 error = DisableSoftwareBreakpoint (bp_site);
816 }
817 }
Greg Clayton07e66e32011-07-20 03:41:06 +0000818 return error;
819 }
Greg Claytonf9765ac2011-07-15 03:27:12 +0000820 return DisableSoftwareBreakpoint (bp_site);
821}
822
823Error
Jim Ingham1b5792e2012-12-18 02:03:49 +0000824ProcessKDP::EnableWatchpoint (Watchpoint *wp, bool notify)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000825{
826 Error error;
827 error.SetErrorString ("watchpoints are not suppported in kdp remote debugging");
828 return error;
829}
830
831Error
Jim Ingham1b5792e2012-12-18 02:03:49 +0000832ProcessKDP::DisableWatchpoint (Watchpoint *wp, bool notify)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000833{
834 Error error;
835 error.SetErrorString ("watchpoints are not suppported in kdp remote debugging");
836 return error;
837}
838
839void
840ProcessKDP::Clear()
841{
Greg Claytonf9765ac2011-07-15 03:27:12 +0000842 m_thread_list.Clear();
843}
844
845Error
846ProcessKDP::DoSignal (int signo)
847{
848 Error error;
849 error.SetErrorString ("sending signals is not suppported in kdp remote debugging");
850 return error;
851}
852
853void
854ProcessKDP::Initialize()
855{
Davide Italianoc8d69822015-04-03 04:24:32 +0000856 static std::once_flag g_once_flag;
857
858 std::call_once(g_once_flag, []()
Greg Claytonf9765ac2011-07-15 03:27:12 +0000859 {
Greg Claytonf9765ac2011-07-15 03:27:12 +0000860 PluginManager::RegisterPlugin (GetPluginNameStatic(),
861 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +0000862 CreateInstance,
Bruce Mitchener488c89e2015-04-03 09:13:18 +0000863 DebuggerInitialize);
Davide Italianoc8d69822015-04-03 04:24:32 +0000864
Greg Claytonf9765ac2011-07-15 03:27:12 +0000865 Log::Callbacks log_callbacks = {
866 ProcessKDPLog::DisableLog,
867 ProcessKDPLog::EnableLog,
868 ProcessKDPLog::ListLogCategories
869 };
Davide Italianoc8d69822015-04-03 04:24:32 +0000870
Greg Claytonf9765ac2011-07-15 03:27:12 +0000871 Log::RegisterLogChannel (ProcessKDP::GetPluginNameStatic(), log_callbacks);
Davide Italianoc8d69822015-04-03 04:24:32 +0000872 });
Greg Claytonf9765ac2011-07-15 03:27:12 +0000873}
874
Greg Clayton7f982402013-07-15 22:54:20 +0000875void
876ProcessKDP::DebuggerInitialize (lldb_private::Debugger &debugger)
877{
878 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
879 {
880 const bool is_global_setting = true;
881 PluginManager::CreateSettingForProcessPlugin (debugger,
882 GetGlobalPluginProperties()->GetValueProperties(),
883 ConstString ("Properties for the kdp-remote process plug-in."),
884 is_global_setting);
885 }
886}
887
Greg Claytonf9765ac2011-07-15 03:27:12 +0000888bool
889ProcessKDP::StartAsyncThread ()
890{
Greg Clayton5160ce52013-03-27 23:08:40 +0000891 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
Greg Claytonf9765ac2011-07-15 03:27:12 +0000892
893 if (log)
Greg Clayton7925fbb2012-09-21 16:31:20 +0000894 log->Printf ("ProcessKDP::StartAsyncThread ()");
Zachary Turner39de3112014-09-09 20:54:56 +0000895
Zachary Turneracee96a2014-09-23 18:32:09 +0000896 if (m_async_thread.IsJoinable())
Greg Clayton7925fbb2012-09-21 16:31:20 +0000897 return true;
898
Zachary Turner39de3112014-09-09 20:54:56 +0000899 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.kdp-remote.async>", ProcessKDP::AsyncThread, this, NULL);
Zachary Turneracee96a2014-09-23 18:32:09 +0000900 return m_async_thread.IsJoinable();
Greg Claytonf9765ac2011-07-15 03:27:12 +0000901}
902
903void
904ProcessKDP::StopAsyncThread ()
905{
Greg Clayton5160ce52013-03-27 23:08:40 +0000906 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
Greg Claytonf9765ac2011-07-15 03:27:12 +0000907
908 if (log)
Greg Clayton7925fbb2012-09-21 16:31:20 +0000909 log->Printf ("ProcessKDP::StopAsyncThread ()");
Greg Claytonf9765ac2011-07-15 03:27:12 +0000910
911 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
912
913 // Stop the stdio thread
Zachary Turneracee96a2014-09-23 18:32:09 +0000914 if (m_async_thread.IsJoinable())
Zachary Turner39de3112014-09-09 20:54:56 +0000915 m_async_thread.Join(nullptr);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000916}
917
918
919void *
920ProcessKDP::AsyncThread (void *arg)
921{
922 ProcessKDP *process = (ProcessKDP*) arg;
923
Greg Clayton7925fbb2012-09-21 16:31:20 +0000924 const lldb::pid_t pid = process->GetID();
925
Greg Clayton5160ce52013-03-27 23:08:40 +0000926 Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_PROCESS));
Greg Claytonf9765ac2011-07-15 03:27:12 +0000927 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000928 log->Printf ("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64 ") thread starting...", arg, pid);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000929
Jim Ingham583bbb12016-03-07 21:50:25 +0000930 ListenerSP listener_sp (Listener::MakeListener("ProcessKDP::AsyncThread"));
Greg Claytonf9765ac2011-07-15 03:27:12 +0000931 EventSP event_sp;
932 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
933 eBroadcastBitAsyncThreadShouldExit;
934
Greg Clayton7925fbb2012-09-21 16:31:20 +0000935
Jim Ingham583bbb12016-03-07 21:50:25 +0000936 if (listener_sp->StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
Greg Claytonf9765ac2011-07-15 03:27:12 +0000937 {
Greg Claytonf9765ac2011-07-15 03:27:12 +0000938 bool done = false;
939 while (!done)
940 {
941 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000942 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...",
Greg Clayton7925fbb2012-09-21 16:31:20 +0000943 pid);
Jim Ingham583bbb12016-03-07 21:50:25 +0000944 if (listener_sp->WaitForEvent (NULL, event_sp))
Greg Claytonf9765ac2011-07-15 03:27:12 +0000945 {
Greg Clayton7925fbb2012-09-21 16:31:20 +0000946 uint32_t event_type = event_sp->GetType();
947 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000948 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") Got an event of type: %d...",
Greg Clayton7925fbb2012-09-21 16:31:20 +0000949 pid,
950 event_type);
951
952 // When we are running, poll for 1 second to try and get an exception
953 // to indicate the process has stopped. If we don't get one, check to
954 // make sure no one asked us to exit
955 bool is_running = false;
956 DataExtractor exc_reply_packet;
957 do
Greg Claytonf9765ac2011-07-15 03:27:12 +0000958 {
Greg Claytonf9765ac2011-07-15 03:27:12 +0000959 switch (event_type)
960 {
Greg Clayton7925fbb2012-09-21 16:31:20 +0000961 case eBroadcastBitAsyncContinue:
Greg Claytonf9765ac2011-07-15 03:27:12 +0000962 {
Greg Clayton7925fbb2012-09-21 16:31:20 +0000963 is_running = true;
964 if (process->m_comm.WaitForPacketWithTimeoutMicroSeconds (exc_reply_packet, 1 * USEC_PER_SEC))
Greg Claytonf9765ac2011-07-15 03:27:12 +0000965 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000966 ThreadSP thread_sp (process->GetKernelThread());
Greg Clayton1afa68e2013-04-02 20:32:37 +0000967 if (thread_sp)
968 {
969 lldb::RegisterContextSP reg_ctx_sp (thread_sp->GetRegisterContext());
970 if (reg_ctx_sp)
971 reg_ctx_sp->InvalidateAllRegisters();
972 static_cast<ThreadKDP *>(thread_sp.get())->SetStopInfoFrom_KDP_EXCEPTION (exc_reply_packet);
973 }
Greg Clayton97d5cf02012-09-25 02:40:06 +0000974
Greg Clayton7925fbb2012-09-21 16:31:20 +0000975 // TODO: parse the stop reply packet
Greg Clayton97d5cf02012-09-25 02:40:06 +0000976 is_running = false;
Greg Clayton7925fbb2012-09-21 16:31:20 +0000977 process->SetPrivateState(eStateStopped);
978 }
979 else
980 {
981 // Check to see if we are supposed to exit. There is no way to
982 // interrupt a running kernel, so all we can do is wait for an
983 // exception or detach...
Jim Ingham583bbb12016-03-07 21:50:25 +0000984 if (listener_sp->GetNextEvent(event_sp))
Greg Clayton7925fbb2012-09-21 16:31:20 +0000985 {
986 // We got an event, go through the loop again
987 event_type = event_sp->GetType();
988 }
Greg Claytonf9765ac2011-07-15 03:27:12 +0000989 }
990 }
Greg Clayton7925fbb2012-09-21 16:31:20 +0000991 break;
Greg Claytonf9765ac2011-07-15 03:27:12 +0000992
Greg Clayton7925fbb2012-09-21 16:31:20 +0000993 case eBroadcastBitAsyncThreadShouldExit:
994 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000995 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...",
Greg Clayton7925fbb2012-09-21 16:31:20 +0000996 pid);
Greg Claytonf9765ac2011-07-15 03:27:12 +0000997 done = true;
Greg Clayton7925fbb2012-09-21 16:31:20 +0000998 is_running = false;
999 break;
1000
1001 default:
1002 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001003 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") got unknown event 0x%8.8x",
Greg Clayton7925fbb2012-09-21 16:31:20 +00001004 pid,
1005 event_type);
1006 done = true;
1007 is_running = false;
1008 break;
Greg Claytonf9765ac2011-07-15 03:27:12 +00001009 }
Greg Clayton7925fbb2012-09-21 16:31:20 +00001010 } while (is_running);
Greg Claytonf9765ac2011-07-15 03:27:12 +00001011 }
1012 else
1013 {
1014 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001015 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false",
Greg Clayton7925fbb2012-09-21 16:31:20 +00001016 pid);
Greg Claytonf9765ac2011-07-15 03:27:12 +00001017 done = true;
1018 }
1019 }
1020 }
1021
1022 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001023 log->Printf ("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64 ") thread exiting...",
Greg Clayton7925fbb2012-09-21 16:31:20 +00001024 arg,
1025 pid);
Zachary Turner39de3112014-09-09 20:54:56 +00001026
1027 process->m_async_thread.Reset();
Greg Claytonf9765ac2011-07-15 03:27:12 +00001028 return NULL;
1029}
1030
1031
Greg Clayton1d19a2f2012-10-19 22:22:57 +00001032class CommandObjectProcessKDPPacketSend : public CommandObjectParsed
1033{
1034private:
1035
1036 OptionGroupOptions m_option_group;
1037 OptionGroupUInt64 m_command_byte;
1038 OptionGroupString m_packet_data;
1039
1040 virtual Options *
1041 GetOptions ()
1042 {
1043 return &m_option_group;
1044 }
1045
1046
1047public:
1048 CommandObjectProcessKDPPacketSend(CommandInterpreter &interpreter) :
1049 CommandObjectParsed (interpreter,
1050 "process plugin packet send",
1051 "Send a custom packet through the KDP protocol by specifying the command byte and the packet payload data. A packet will be sent with a correct header and payload, and the raw result bytes will be displayed as a string value. ",
1052 NULL),
1053 m_option_group (interpreter),
1054 m_command_byte(LLDB_OPT_SET_1, true , "command", 'c', 0, eArgTypeNone, "Specify the command byte to use when sending the KDP request packet.", 0),
1055 m_packet_data (LLDB_OPT_SET_1, false, "payload", 'p', 0, eArgTypeNone, "Specify packet payload bytes as a hex ASCII string with no spaces or hex prefixes.", NULL)
1056 {
1057 m_option_group.Append (&m_command_byte, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
1058 m_option_group.Append (&m_packet_data , LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
1059 m_option_group.Finalize();
1060 }
1061
1062 ~CommandObjectProcessKDPPacketSend ()
1063 {
1064 }
1065
1066 bool
1067 DoExecute (Args& command, CommandReturnObject &result)
1068 {
1069 const size_t argc = command.GetArgumentCount();
1070 if (argc == 0)
1071 {
1072 if (!m_command_byte.GetOptionValue().OptionWasSet())
1073 {
1074 result.AppendError ("the --command option must be set to a valid command byte");
1075 result.SetStatus (eReturnStatusFailed);
1076 }
1077 else
1078 {
1079 const uint64_t command_byte = m_command_byte.GetOptionValue().GetUInt64Value(0);
1080 if (command_byte > 0 && command_byte <= UINT8_MAX)
1081 {
1082 ProcessKDP *process = (ProcessKDP *)m_interpreter.GetExecutionContext().GetProcessPtr();
1083 if (process)
1084 {
1085 const StateType state = process->GetState();
1086
1087 if (StateIsStoppedState (state, true))
1088 {
1089 std::vector<uint8_t> payload_bytes;
1090 const char *ascii_hex_bytes_cstr = m_packet_data.GetOptionValue().GetCurrentValue();
1091 if (ascii_hex_bytes_cstr && ascii_hex_bytes_cstr[0])
1092 {
1093 StringExtractor extractor(ascii_hex_bytes_cstr);
1094 const size_t ascii_hex_bytes_cstr_len = extractor.GetStringRef().size();
1095 if (ascii_hex_bytes_cstr_len & 1)
1096 {
1097 result.AppendErrorWithFormat ("payload data must contain an even number of ASCII hex characters: '%s'", ascii_hex_bytes_cstr);
1098 result.SetStatus (eReturnStatusFailed);
1099 return false;
1100 }
1101 payload_bytes.resize(ascii_hex_bytes_cstr_len/2);
1102 if (extractor.GetHexBytes(&payload_bytes[0], payload_bytes.size(), '\xdd') != payload_bytes.size())
1103 {
1104 result.AppendErrorWithFormat ("payload data must only contain ASCII hex characters (no spaces or hex prefixes): '%s'", ascii_hex_bytes_cstr);
1105 result.SetStatus (eReturnStatusFailed);
1106 return false;
1107 }
1108 }
1109 Error error;
1110 DataExtractor reply;
1111 process->GetCommunication().SendRawRequest (command_byte,
1112 payload_bytes.empty() ? NULL : payload_bytes.data(),
1113 payload_bytes.size(),
1114 reply,
1115 error);
1116
1117 if (error.Success())
1118 {
1119 // Copy the binary bytes into a hex ASCII string for the result
1120 StreamString packet;
1121 packet.PutBytesAsRawHex8(reply.GetDataStart(),
1122 reply.GetByteSize(),
Bruce Mitchener9ccb9702015-11-07 04:40:13 +00001123 endian::InlHostByteOrder(),
1124 endian::InlHostByteOrder());
Greg Clayton1d19a2f2012-10-19 22:22:57 +00001125 result.AppendMessage(packet.GetString().c_str());
1126 result.SetStatus (eReturnStatusSuccessFinishResult);
1127 return true;
1128 }
1129 else
1130 {
1131 const char *error_cstr = error.AsCString();
1132 if (error_cstr && error_cstr[0])
1133 result.AppendError (error_cstr);
1134 else
1135 result.AppendErrorWithFormat ("unknown error 0x%8.8x", error.GetError());
1136 result.SetStatus (eReturnStatusFailed);
1137 return false;
1138 }
1139 }
1140 else
1141 {
1142 result.AppendErrorWithFormat ("process must be stopped in order to send KDP packets, state is %s", StateAsCString (state));
1143 result.SetStatus (eReturnStatusFailed);
1144 }
1145 }
1146 else
1147 {
1148 result.AppendError ("invalid process");
1149 result.SetStatus (eReturnStatusFailed);
1150 }
1151 }
1152 else
1153 {
Daniel Malead01b2952012-11-29 21:49:15 +00001154 result.AppendErrorWithFormat ("invalid command byte 0x%" PRIx64 ", valid values are 1 - 255", command_byte);
Greg Clayton1d19a2f2012-10-19 22:22:57 +00001155 result.SetStatus (eReturnStatusFailed);
1156 }
1157 }
1158 }
1159 else
1160 {
1161 result.AppendErrorWithFormat ("'%s' takes no arguments, only options.", m_cmd_name.c_str());
1162 result.SetStatus (eReturnStatusFailed);
1163 }
1164 return false;
1165 }
1166};
1167
1168class CommandObjectProcessKDPPacket : public CommandObjectMultiword
1169{
1170private:
1171
1172public:
1173 CommandObjectProcessKDPPacket(CommandInterpreter &interpreter) :
1174 CommandObjectMultiword (interpreter,
1175 "process plugin packet",
1176 "Commands that deal with KDP remote packets.",
1177 NULL)
1178 {
1179 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessKDPPacketSend (interpreter)));
1180 }
1181
1182 ~CommandObjectProcessKDPPacket ()
1183 {
1184 }
1185};
1186
1187class CommandObjectMultiwordProcessKDP : public CommandObjectMultiword
1188{
1189public:
1190 CommandObjectMultiwordProcessKDP (CommandInterpreter &interpreter) :
1191 CommandObjectMultiword (interpreter,
1192 "process plugin",
1193 "A set of commands for operating on a ProcessKDP process.",
1194 "process plugin <subcommand> [<subcommand-options>]")
1195 {
1196 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessKDPPacket (interpreter)));
1197 }
1198
1199 ~CommandObjectMultiwordProcessKDP ()
1200 {
1201 }
1202};
1203
1204CommandObject *
1205ProcessKDP::GetPluginCommandObject()
1206{
1207 if (!m_command_sp)
1208 m_command_sp.reset (new CommandObjectMultiwordProcessKDP (GetTarget().GetDebugger().GetCommandInterpreter()));
1209 return m_command_sp.get();
1210}
1211