blob: 7d33ccec68a37d1f116a4edeee4730bf673555b1 [file] [log] [blame]
Greg Clayton269f91e2011-07-15 18:02:58 +00001//===-- ProcessKDP.cpp ------------------------------------------*- C++ -*-===//
Greg Clayton363be3f2011-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
15// Other libraries and framework includes
Greg Clayton8d2ea282011-07-17 20:36:25 +000016#include "lldb/Core/ConnectionFileDescriptor.h"
Greg Clayton234981a2011-07-20 03:41:06 +000017#include "lldb/Core/Debugger.h"
Greg Clayton363be3f2011-07-15 03:27:12 +000018#include "lldb/Core/PluginManager.h"
Greg Clayton49ce8962012-08-29 21:13:06 +000019#include "lldb/Core/Module.h"
Jason Molendafac2e622012-09-29 04:02:01 +000020#include "lldb/Core/ModuleSpec.h"
Greg Clayton363be3f2011-07-15 03:27:12 +000021#include "lldb/Core/State.h"
Jason Molendafac2e622012-09-29 04:02:01 +000022#include "lldb/Core/UUID.h"
Greg Clayton363be3f2011-07-15 03:27:12 +000023#include "lldb/Host/Host.h"
Jason Molendafac2e622012-09-29 04:02:01 +000024#include "lldb/Host/Symbols.h"
Greg Clayton307c7fd2012-10-19 22:22:57 +000025#include "lldb/Interpreter/CommandInterpreter.h"
26#include "lldb/Interpreter/CommandObject.h"
27#include "lldb/Interpreter/CommandObjectMultiword.h"
28#include "lldb/Interpreter/CommandReturnObject.h"
29#include "lldb/Interpreter/OptionGroupString.h"
30#include "lldb/Interpreter/OptionGroupUInt64.h"
Greg Clayton49ce8962012-08-29 21:13:06 +000031#include "lldb/Symbol/ObjectFile.h"
Greg Claytone76f8c42012-09-21 16:31:20 +000032#include "lldb/Target/RegisterContext.h"
Greg Clayton1e5b0212011-07-15 16:31:38 +000033#include "lldb/Target/Target.h"
Greg Clayton0fa51242011-07-19 03:57:15 +000034#include "lldb/Target/Thread.h"
Greg Clayton363be3f2011-07-15 03:27:12 +000035
36// Project includes
37#include "ProcessKDP.h"
38#include "ProcessKDPLog.h"
Greg Clayton0fa51242011-07-19 03:57:15 +000039#include "ThreadKDP.h"
Jason Molendab46937c2012-10-03 01:29:34 +000040#include "Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.h"
Jason Molendad06bb502012-10-25 00:25:13 +000041#include "Plugins/DynamicLoader/Static/DynamicLoaderStatic.h"
Greg Clayton307c7fd2012-10-19 22:22:57 +000042#include "Utility/StringExtractor.h"
Greg Clayton363be3f2011-07-15 03:27:12 +000043
44using namespace lldb;
45using namespace lldb_private;
46
47const char *
48ProcessKDP::GetPluginNameStatic()
49{
50 return "kdp-remote";
51}
52
53const char *
54ProcessKDP::GetPluginDescriptionStatic()
55{
56 return "KDP Remote protocol based debugging plug-in for darwin kernel debugging.";
57}
58
59void
60ProcessKDP::Terminate()
61{
62 PluginManager::UnregisterPlugin (ProcessKDP::CreateInstance);
63}
64
65
Greg Clayton46c9a352012-02-09 06:16:32 +000066lldb::ProcessSP
67ProcessKDP::CreateInstance (Target &target,
68 Listener &listener,
69 const FileSpec *crash_file_path)
Greg Clayton363be3f2011-07-15 03:27:12 +000070{
Greg Clayton46c9a352012-02-09 06:16:32 +000071 lldb::ProcessSP process_sp;
72 if (crash_file_path == NULL)
73 process_sp.reset(new ProcessKDP (target, listener));
74 return process_sp;
Greg Clayton363be3f2011-07-15 03:27:12 +000075}
76
77bool
Greg Clayton8d2ea282011-07-17 20:36:25 +000078ProcessKDP::CanDebug(Target &target, bool plugin_specified_by_name)
Greg Clayton363be3f2011-07-15 03:27:12 +000079{
Greg Clayton61ddf562011-10-21 21:41:45 +000080 if (plugin_specified_by_name)
81 return true;
82
Greg Clayton363be3f2011-07-15 03:27:12 +000083 // For now we are just making sure the file exists for a given module
Greg Clayton5beb99d2011-08-11 02:48:45 +000084 Module *exe_module = target.GetExecutableModulePointer();
85 if (exe_module)
Greg Clayton363be3f2011-07-15 03:27:12 +000086 {
87 const llvm::Triple &triple_ref = target.GetArchitecture().GetTriple();
Greg Claytonb170aee2012-05-08 01:45:38 +000088 switch (triple_ref.getOS())
Greg Clayton363be3f2011-07-15 03:27:12 +000089 {
Greg Claytonb170aee2012-05-08 01:45:38 +000090 case llvm::Triple::Darwin: // Should use "macosx" for desktop and "ios" for iOS, but accept darwin just in case
91 case llvm::Triple::MacOSX: // For desktop targets
92 case llvm::Triple::IOS: // For arm targets
93 if (triple_ref.getVendor() == llvm::Triple::Apple)
94 {
95 ObjectFile *exe_objfile = exe_module->GetObjectFile();
96 if (exe_objfile->GetType() == ObjectFile::eTypeExecutable &&
97 exe_objfile->GetStrata() == ObjectFile::eStrataKernel)
98 return true;
99 }
100 break;
101
102 default:
103 break;
Greg Clayton363be3f2011-07-15 03:27:12 +0000104 }
105 }
Greg Clayton61ddf562011-10-21 21:41:45 +0000106 return false;
Greg Clayton363be3f2011-07-15 03:27:12 +0000107}
108
109//----------------------------------------------------------------------
110// ProcessKDP constructor
111//----------------------------------------------------------------------
112ProcessKDP::ProcessKDP(Target& target, Listener &listener) :
113 Process (target, listener),
114 m_comm("lldb.process.kdp-remote.communication"),
Jim Ingham5a15e692012-02-16 06:50:00 +0000115 m_async_broadcaster (NULL, "lldb.process.kdp-remote.async-broadcaster"),
Greg Clayton3acaa922012-09-25 02:40:06 +0000116 m_async_thread (LLDB_INVALID_HOST_THREAD),
Jason Molendab46937c2012-10-03 01:29:34 +0000117 m_destroy_in_process (false),
118 m_dyld_plugin_name (),
Greg Clayton307c7fd2012-10-19 22:22:57 +0000119 m_kernel_load_addr (LLDB_INVALID_ADDRESS),
120 m_command_sp()
Greg Clayton363be3f2011-07-15 03:27:12 +0000121{
Greg Claytone76f8c42012-09-21 16:31:20 +0000122 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
123 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Greg Clayton363be3f2011-07-15 03:27:12 +0000124}
125
126//----------------------------------------------------------------------
127// Destructor
128//----------------------------------------------------------------------
129ProcessKDP::~ProcessKDP()
130{
131 Clear();
Greg Claytonffa43a62011-11-17 04:46:02 +0000132 // We need to call finalize on the process before destroying ourselves
133 // to make sure all of the broadcaster cleanup goes as planned. If we
134 // destruct this class, then Process::~Process() might have problems
135 // trying to fully destroy the broadcaster.
136 Finalize();
Greg Clayton363be3f2011-07-15 03:27:12 +0000137}
138
139//----------------------------------------------------------------------
140// PluginInterface
141//----------------------------------------------------------------------
142const char *
143ProcessKDP::GetPluginName()
144{
145 return "Process debugging plug-in that uses the Darwin KDP remote protocol";
146}
147
148const char *
149ProcessKDP::GetShortPluginName()
150{
151 return GetPluginNameStatic();
152}
153
154uint32_t
155ProcessKDP::GetPluginVersion()
156{
157 return 1;
158}
159
160Error
161ProcessKDP::WillLaunch (Module* module)
162{
163 Error error;
164 error.SetErrorString ("launching not supported in kdp-remote plug-in");
165 return error;
166}
167
168Error
169ProcessKDP::WillAttachToProcessWithID (lldb::pid_t pid)
170{
171 Error error;
172 error.SetErrorString ("attaching to a by process ID not supported in kdp-remote plug-in");
173 return error;
174}
175
176Error
177ProcessKDP::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
178{
179 Error error;
180 error.SetErrorString ("attaching to a by process name not supported in kdp-remote plug-in");
181 return error;
182}
183
184Error
Jason Molendafac2e622012-09-29 04:02:01 +0000185ProcessKDP::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Clayton363be3f2011-07-15 03:27:12 +0000186{
Greg Clayton363be3f2011-07-15 03:27:12 +0000187 Error error;
Greg Claytone76f8c42012-09-21 16:31:20 +0000188
189 // Don't let any JIT happen when doing KDP as we can't allocate
190 // memory and we don't want to be mucking with threads that might
191 // already be handling exceptions
192 SetCanJIT(false);
193
Greg Clayton8d2ea282011-07-17 20:36:25 +0000194 if (remote_url == NULL || remote_url[0] == '\0')
Greg Claytone76f8c42012-09-21 16:31:20 +0000195 {
196 error.SetErrorStringWithFormat ("invalid connection URL '%s'", remote_url);
197 return error;
198 }
Greg Clayton8d2ea282011-07-17 20:36:25 +0000199
200 std::auto_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
201 if (conn_ap.get())
202 {
203 // Only try once for now.
204 // TODO: check if we should be retrying?
205 const uint32_t max_retry_count = 1;
206 for (uint32_t retry_count = 0; retry_count < max_retry_count; ++retry_count)
207 {
208 if (conn_ap->Connect(remote_url, &error) == eConnectionStatusSuccess)
209 break;
210 usleep (100000);
211 }
212 }
213
214 if (conn_ap->IsConnected())
215 {
216 const uint16_t reply_port = conn_ap->GetReadPort ();
217
218 if (reply_port != 0)
219 {
220 m_comm.SetConnection(conn_ap.release());
221
222 if (m_comm.SendRequestReattach(reply_port))
223 {
224 if (m_comm.SendRequestConnect(reply_port, reply_port, "Greetings from LLDB..."))
225 {
226 m_comm.GetVersion();
227 uint32_t cpu = m_comm.GetCPUType();
228 uint32_t sub = m_comm.GetCPUSubtype();
229 ArchSpec kernel_arch;
230 kernel_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
231 m_target.SetArchitecture(kernel_arch);
Jason Molendafac2e622012-09-29 04:02:01 +0000232
Jason Molendad06bb502012-10-25 00:25:13 +0000233 /* Get the kernel's UUID and load address via KDP_KERNELVERSION packet. */
234 /* An EFI kdp session has neither UUID nor load address. */
235
Jason Molendafac2e622012-09-29 04:02:01 +0000236 UUID kernel_uuid = m_comm.GetUUID ();
237 addr_t kernel_load_addr = m_comm.GetLoadAddress ();
Jason Molendafac2e622012-09-29 04:02:01 +0000238
Jason Molendad06bb502012-10-25 00:25:13 +0000239 if (m_comm.RemoteIsEFI ())
240 {
241 m_dyld_plugin_name = DynamicLoaderStatic::GetPluginNameStatic();
242 }
243 else if (kernel_load_addr != LLDB_INVALID_ADDRESS)
Jason Molendafac2e622012-09-29 04:02:01 +0000244 {
Jason Molendab46937c2012-10-03 01:29:34 +0000245 m_kernel_load_addr = kernel_load_addr;
246 m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
Jason Molendafac2e622012-09-29 04:02:01 +0000247 }
248
Greg Clayton3acaa922012-09-25 02:40:06 +0000249 // Set the thread ID
250 UpdateThreadListIfNeeded ();
Greg Clayton0fa51242011-07-19 03:57:15 +0000251 SetID (1);
Greg Clayton37f962e2011-08-22 02:49:39 +0000252 GetThreadList ();
Greg Clayton0fa51242011-07-19 03:57:15 +0000253 SetPrivateState (eStateStopped);
Greg Clayton234981a2011-07-20 03:41:06 +0000254 StreamSP async_strm_sp(m_target.GetDebugger().GetAsyncOutputStream());
255 if (async_strm_sp)
256 {
Greg Clayton7b139222011-07-21 01:12:01 +0000257 const char *cstr;
258 if ((cstr = m_comm.GetKernelVersion ()) != NULL)
Greg Clayton234981a2011-07-20 03:41:06 +0000259 {
Greg Clayton7b139222011-07-21 01:12:01 +0000260 async_strm_sp->Printf ("Version: %s\n", cstr);
Greg Clayton234981a2011-07-20 03:41:06 +0000261 async_strm_sp->Flush();
262 }
Greg Clayton7b139222011-07-21 01:12:01 +0000263// if ((cstr = m_comm.GetImagePath ()) != NULL)
264// {
265// async_strm_sp->Printf ("Image Path: %s\n", cstr);
266// async_strm_sp->Flush();
267// }
Greg Clayton234981a2011-07-20 03:41:06 +0000268 }
Greg Clayton8d2ea282011-07-17 20:36:25 +0000269 }
Greg Clayton3acaa922012-09-25 02:40:06 +0000270 else
271 {
Greg Clayton3acaa922012-09-25 02:40:06 +0000272 error.SetErrorString("KDP_REATTACH failed");
273 }
Greg Clayton8d2ea282011-07-17 20:36:25 +0000274 }
275 else
276 {
Greg Clayton3acaa922012-09-25 02:40:06 +0000277 error.SetErrorString("KDP_REATTACH failed");
Greg Clayton8d2ea282011-07-17 20:36:25 +0000278 }
279 }
280 else
281 {
282 error.SetErrorString("invalid reply port from UDP connection");
283 }
284 }
285 else
286 {
287 if (error.Success())
288 error.SetErrorStringWithFormat ("failed to connect to '%s'", remote_url);
289 }
290 if (error.Fail())
291 m_comm.Disconnect();
292
Greg Clayton363be3f2011-07-15 03:27:12 +0000293 return error;
294}
295
296//----------------------------------------------------------------------
297// Process Control
298//----------------------------------------------------------------------
299Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000300ProcessKDP::DoLaunch (Module *exe_module,
301 const ProcessLaunchInfo &launch_info)
Greg Clayton363be3f2011-07-15 03:27:12 +0000302{
303 Error error;
304 error.SetErrorString ("launching not supported in kdp-remote plug-in");
305 return error;
306}
307
308
309Error
310ProcessKDP::DoAttachToProcessWithID (lldb::pid_t attach_pid)
311{
312 Error error;
313 error.SetErrorString ("attach to process by ID is not suppported in kdp remote debugging");
314 return error;
315}
316
Greg Clayton363be3f2011-07-15 03:27:12 +0000317Error
Han Ming Ongd1040dd2012-02-25 01:07:38 +0000318ProcessKDP::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
319{
320 Error error;
321 error.SetErrorString ("attach to process by ID is not suppported in kdp remote debugging");
322 return error;
323}
324
325Error
326ProcessKDP::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
Greg Clayton363be3f2011-07-15 03:27:12 +0000327{
328 Error error;
329 error.SetErrorString ("attach to process by name is not suppported in kdp remote debugging");
330 return error;
331}
332
333
334void
335ProcessKDP::DidAttach ()
336{
337 LogSP log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_PROCESS));
338 if (log)
Johnny Chen01df0572011-10-11 21:17:10 +0000339 log->Printf ("ProcessKDP::DidAttach()");
Greg Clayton363be3f2011-07-15 03:27:12 +0000340 if (GetID() != LLDB_INVALID_PROCESS_ID)
341 {
342 // TODO: figure out the register context that we will use
343 }
344}
345
Jason Molendab46937c2012-10-03 01:29:34 +0000346addr_t
347ProcessKDP::GetImageInfoAddress()
348{
349 return m_kernel_load_addr;
350}
351
352lldb_private::DynamicLoader *
353ProcessKDP::GetDynamicLoader ()
354{
355 if (m_dyld_ap.get() == NULL)
356 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, m_dyld_plugin_name.empty() ? NULL : m_dyld_plugin_name.c_str()));
357 return m_dyld_ap.get();
358}
359
Greg Clayton363be3f2011-07-15 03:27:12 +0000360Error
361ProcessKDP::WillResume ()
362{
363 return Error();
364}
365
366Error
367ProcessKDP::DoResume ()
368{
369 Error error;
Greg Claytone76f8c42012-09-21 16:31:20 +0000370 LogSP log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_PROCESS));
371 // Only start the async thread if we try to do any process control
372 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
373 StartAsyncThread ();
374
Greg Clayton3acaa922012-09-25 02:40:06 +0000375 bool resume = false;
Greg Claytone76f8c42012-09-21 16:31:20 +0000376
Greg Clayton3acaa922012-09-25 02:40:06 +0000377 // With KDP there is only one thread we can tell what to do
378 ThreadSP kernel_thread_sp (GetKernelThread(m_thread_list, m_thread_list));
379 if (kernel_thread_sp)
Greg Claytonea636012012-09-21 01:55:30 +0000380 {
Greg Clayton3acaa922012-09-25 02:40:06 +0000381 const StateType thread_resume_state = kernel_thread_sp->GetTemporaryResumeState();
Greg Claytone76f8c42012-09-21 16:31:20 +0000382 switch (thread_resume_state)
Greg Claytonea636012012-09-21 01:55:30 +0000383 {
Greg Claytone76f8c42012-09-21 16:31:20 +0000384 case eStateSuspended:
385 // Nothing to do here when a thread will stay suspended
386 // we just leave the CPU mask bit set to zero for the thread
387 break;
388
389 case eStateStepping:
Greg Clayton3acaa922012-09-25 02:40:06 +0000390 kernel_thread_sp->GetRegisterContext()->HardwareSingleStep (true);
391 resume = true;
392 break;
393
Greg Claytone76f8c42012-09-21 16:31:20 +0000394 case eStateRunning:
Greg Clayton3acaa922012-09-25 02:40:06 +0000395 kernel_thread_sp->GetRegisterContext()->HardwareSingleStep (false);
396 resume = true;
Greg Claytone76f8c42012-09-21 16:31:20 +0000397 break;
Greg Clayton3acaa922012-09-25 02:40:06 +0000398
Greg Claytone76f8c42012-09-21 16:31:20 +0000399 default:
Greg Clayton3acaa922012-09-25 02:40:06 +0000400 // The only valid thread resume states are listed above
Greg Claytone76f8c42012-09-21 16:31:20 +0000401 assert (!"invalid thread resume state");
402 break;
Greg Claytonea636012012-09-21 01:55:30 +0000403 }
404 }
Greg Clayton3acaa922012-09-25 02:40:06 +0000405
406 if (resume)
Greg Claytone76f8c42012-09-21 16:31:20 +0000407 {
Greg Clayton3acaa922012-09-25 02:40:06 +0000408 if (log)
409 log->Printf ("ProcessKDP::DoResume () sending resume");
Greg Claytone76f8c42012-09-21 16:31:20 +0000410
Greg Clayton3acaa922012-09-25 02:40:06 +0000411 if (m_comm.SendRequestResume ())
Greg Claytone76f8c42012-09-21 16:31:20 +0000412 {
413 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue);
414 SetPrivateState(eStateRunning);
415 }
416 else
417 error.SetErrorString ("KDP resume failed");
418 }
Greg Claytonea636012012-09-21 01:55:30 +0000419 else
Greg Claytone76f8c42012-09-21 16:31:20 +0000420 {
Greg Clayton3acaa922012-09-25 02:40:06 +0000421 error.SetErrorString ("kernel thread is suspended");
Greg Claytone76f8c42012-09-21 16:31:20 +0000422 }
423
Greg Clayton363be3f2011-07-15 03:27:12 +0000424 return error;
425}
426
Greg Clayton3acaa922012-09-25 02:40:06 +0000427lldb::ThreadSP
428ProcessKDP::GetKernelThread(ThreadList &old_thread_list, ThreadList &new_thread_list)
429{
430 // KDP only tells us about one thread/core. Any other threads will usually
431 // be the ones that are read from memory by the OS plug-ins.
432 const lldb::tid_t kernel_tid = 1;
433 ThreadSP thread_sp (old_thread_list.FindThreadByID (kernel_tid, false));
434 if (!thread_sp)
435 {
Jim Ingham94a5d0d2012-10-10 18:32:14 +0000436 thread_sp.reset(new ThreadKDP (*this, kernel_tid));
Greg Clayton3acaa922012-09-25 02:40:06 +0000437 new_thread_list.AddThread(thread_sp);
438 }
439 return thread_sp;
440}
441
442
443
444
Greg Claytonae932352012-04-10 00:18:59 +0000445bool
Greg Clayton37f962e2011-08-22 02:49:39 +0000446ProcessKDP::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Greg Clayton363be3f2011-07-15 03:27:12 +0000447{
448 // locker will keep a mutex locked until it goes out of scope
449 LogSP log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_THREAD));
450 if (log && log->GetMask().Test(KDP_LOG_VERBOSE))
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000451 log->Printf ("ProcessKDP::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton363be3f2011-07-15 03:27:12 +0000452
Greg Clayton3acaa922012-09-25 02:40:06 +0000453 // Even though there is a CPU mask, it doesn't mean to can see each CPU
454 // indivudually, there is really only one. Lets call this thread 1.
455 GetKernelThread (old_thread_list, new_thread_list);
456
Greg Claytonae932352012-04-10 00:18:59 +0000457 return new_thread_list.GetSize(false) > 0;
Greg Clayton363be3f2011-07-15 03:27:12 +0000458}
459
Greg Clayton363be3f2011-07-15 03:27:12 +0000460void
461ProcessKDP::RefreshStateAfterStop ()
462{
463 // Let all threads recover from stopping and do any clean up based
464 // on the previous thread state (if any).
465 m_thread_list.RefreshStateAfterStop();
Greg Clayton363be3f2011-07-15 03:27:12 +0000466}
467
468Error
469ProcessKDP::DoHalt (bool &caused_stop)
470{
471 Error error;
472
Greg Clayton3acaa922012-09-25 02:40:06 +0000473 if (m_comm.IsRunning())
Greg Clayton363be3f2011-07-15 03:27:12 +0000474 {
Greg Clayton3acaa922012-09-25 02:40:06 +0000475 if (m_destroy_in_process)
Greg Clayton363be3f2011-07-15 03:27:12 +0000476 {
Greg Clayton3acaa922012-09-25 02:40:06 +0000477 // If we are attemping to destroy, we need to not return an error to
478 // Halt or DoDestroy won't get called.
479 // We are also currently running, so send a process stopped event
480 SetPrivateState (eStateStopped);
Greg Clayton363be3f2011-07-15 03:27:12 +0000481 }
Greg Clayton3acaa922012-09-25 02:40:06 +0000482 else
Greg Clayton363be3f2011-07-15 03:27:12 +0000483 {
Greg Clayton3acaa922012-09-25 02:40:06 +0000484 error.SetErrorString ("KDP cannot interrupt a running kernel");
Greg Clayton363be3f2011-07-15 03:27:12 +0000485 }
486 }
487 return error;
488}
489
490Error
Greg Clayton363be3f2011-07-15 03:27:12 +0000491ProcessKDP::DoDetach()
492{
493 Error error;
494 LogSP log (ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
495 if (log)
496 log->Printf ("ProcessKDP::DoDetach()");
497
Greg Clayton3acaa922012-09-25 02:40:06 +0000498 if (m_comm.IsRunning())
Greg Clayton363be3f2011-07-15 03:27:12 +0000499 {
Greg Clayton3acaa922012-09-25 02:40:06 +0000500 // We are running and we can't interrupt a running kernel, so we need
501 // to just close the connection to the kernel and hope for the best
502 }
503 else
504 {
505 DisableAllBreakpointSites ();
506
507 m_thread_list.DiscardThreadPlans();
508
509 if (m_comm.IsConnected())
Greg Clayton8d2ea282011-07-17 20:36:25 +0000510 {
Greg Clayton3acaa922012-09-25 02:40:06 +0000511
512 m_comm.SendRequestDisconnect();
513
514 size_t response_size = m_comm.Disconnect ();
515 if (log)
516 {
517 if (response_size)
518 log->PutCString ("ProcessKDP::DoDetach() detach packet sent successfully");
519 else
520 log->PutCString ("ProcessKDP::DoDetach() detach packet send failed");
521 }
Greg Clayton8d2ea282011-07-17 20:36:25 +0000522 }
Greg Clayton363be3f2011-07-15 03:27:12 +0000523 }
Greg Clayton3acaa922012-09-25 02:40:06 +0000524 StopAsyncThread ();
Greg Claytondb9d6f42012-01-31 04:56:17 +0000525 m_comm.Clear();
Greg Clayton363be3f2011-07-15 03:27:12 +0000526
527 SetPrivateState (eStateDetached);
528 ResumePrivateStateThread();
529
530 //KillDebugserverProcess ();
531 return error;
532}
533
534Error
Greg Clayton3acaa922012-09-25 02:40:06 +0000535ProcessKDP::WillDestroy ()
536{
537 Error error;
538 m_destroy_in_process = true;
539 return error;
540}
541
542Error
Greg Clayton363be3f2011-07-15 03:27:12 +0000543ProcessKDP::DoDestroy ()
544{
Greg Claytone76f8c42012-09-21 16:31:20 +0000545 // For KDP there really is no difference between destroy and detach
546 return DoDetach();
Greg Clayton363be3f2011-07-15 03:27:12 +0000547}
548
549//------------------------------------------------------------------
550// Process Queries
551//------------------------------------------------------------------
552
553bool
554ProcessKDP::IsAlive ()
555{
556 return m_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
557}
558
559//------------------------------------------------------------------
560// Process Memory
561//------------------------------------------------------------------
562size_t
563ProcessKDP::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
564{
Greg Clayton0fa51242011-07-19 03:57:15 +0000565 if (m_comm.IsConnected())
566 return m_comm.SendRequestReadMemory (addr, buf, size, error);
567 error.SetErrorString ("not connected");
Greg Clayton363be3f2011-07-15 03:27:12 +0000568 return 0;
569}
570
571size_t
572ProcessKDP::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
573{
Greg Claytone76f8c42012-09-21 16:31:20 +0000574 if (m_comm.IsConnected())
575 return m_comm.SendRequestWriteMemory (addr, buf, size, error);
576 error.SetErrorString ("not connected");
Greg Clayton363be3f2011-07-15 03:27:12 +0000577 return 0;
578}
579
580lldb::addr_t
581ProcessKDP::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
582{
583 error.SetErrorString ("memory allocation not suppported in kdp remote debugging");
584 return LLDB_INVALID_ADDRESS;
585}
586
587Error
588ProcessKDP::DoDeallocateMemory (lldb::addr_t addr)
589{
590 Error error;
591 error.SetErrorString ("memory deallocation not suppported in kdp remote debugging");
592 return error;
593}
594
595Error
596ProcessKDP::EnableBreakpoint (BreakpointSite *bp_site)
597{
Greg Clayton234981a2011-07-20 03:41:06 +0000598 if (m_comm.LocalBreakpointsAreSupported ())
599 {
600 Error error;
Greg Clayton7b139222011-07-21 01:12:01 +0000601 if (!bp_site->IsEnabled())
602 {
603 if (m_comm.SendRequestBreakpoint(true, bp_site->GetLoadAddress()))
604 {
605 bp_site->SetEnabled(true);
606 bp_site->SetType (BreakpointSite::eExternal);
607 }
608 else
609 {
610 error.SetErrorString ("KDP set breakpoint failed");
611 }
612 }
Greg Clayton234981a2011-07-20 03:41:06 +0000613 return error;
614 }
Greg Clayton363be3f2011-07-15 03:27:12 +0000615 return EnableSoftwareBreakpoint (bp_site);
616}
617
618Error
619ProcessKDP::DisableBreakpoint (BreakpointSite *bp_site)
620{
Greg Clayton234981a2011-07-20 03:41:06 +0000621 if (m_comm.LocalBreakpointsAreSupported ())
622 {
623 Error error;
Greg Clayton7b139222011-07-21 01:12:01 +0000624 if (bp_site->IsEnabled())
625 {
626 BreakpointSite::Type bp_type = bp_site->GetType();
627 if (bp_type == BreakpointSite::eExternal)
628 {
Greg Clayton3acaa922012-09-25 02:40:06 +0000629 if (m_destroy_in_process && m_comm.IsRunning())
630 {
631 // We are trying to destroy our connection and we are running
Greg Clayton7b139222011-07-21 01:12:01 +0000632 bp_site->SetEnabled(false);
Greg Clayton3acaa922012-09-25 02:40:06 +0000633 }
Greg Clayton7b139222011-07-21 01:12:01 +0000634 else
Greg Clayton3acaa922012-09-25 02:40:06 +0000635 {
636 if (m_comm.SendRequestBreakpoint(false, bp_site->GetLoadAddress()))
637 bp_site->SetEnabled(false);
638 else
639 error.SetErrorString ("KDP remove breakpoint failed");
640 }
Greg Clayton7b139222011-07-21 01:12:01 +0000641 }
642 else
643 {
644 error = DisableSoftwareBreakpoint (bp_site);
645 }
646 }
Greg Clayton234981a2011-07-20 03:41:06 +0000647 return error;
648 }
Greg Clayton363be3f2011-07-15 03:27:12 +0000649 return DisableSoftwareBreakpoint (bp_site);
650}
651
652Error
Jim Ingham9c970a32012-12-18 02:03:49 +0000653ProcessKDP::EnableWatchpoint (Watchpoint *wp, bool notify)
Greg Clayton363be3f2011-07-15 03:27:12 +0000654{
655 Error error;
656 error.SetErrorString ("watchpoints are not suppported in kdp remote debugging");
657 return error;
658}
659
660Error
Jim Ingham9c970a32012-12-18 02:03:49 +0000661ProcessKDP::DisableWatchpoint (Watchpoint *wp, bool notify)
Greg Clayton363be3f2011-07-15 03:27:12 +0000662{
663 Error error;
664 error.SetErrorString ("watchpoints are not suppported in kdp remote debugging");
665 return error;
666}
667
668void
669ProcessKDP::Clear()
670{
Greg Clayton363be3f2011-07-15 03:27:12 +0000671 m_thread_list.Clear();
672}
673
674Error
675ProcessKDP::DoSignal (int signo)
676{
677 Error error;
678 error.SetErrorString ("sending signals is not suppported in kdp remote debugging");
679 return error;
680}
681
682void
683ProcessKDP::Initialize()
684{
685 static bool g_initialized = false;
686
687 if (g_initialized == false)
688 {
689 g_initialized = true;
690 PluginManager::RegisterPlugin (GetPluginNameStatic(),
691 GetPluginDescriptionStatic(),
692 CreateInstance);
693
694 Log::Callbacks log_callbacks = {
695 ProcessKDPLog::DisableLog,
696 ProcessKDPLog::EnableLog,
697 ProcessKDPLog::ListLogCategories
698 };
699
700 Log::RegisterLogChannel (ProcessKDP::GetPluginNameStatic(), log_callbacks);
701 }
702}
703
704bool
705ProcessKDP::StartAsyncThread ()
706{
707 LogSP log (ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
708
709 if (log)
Greg Claytone76f8c42012-09-21 16:31:20 +0000710 log->Printf ("ProcessKDP::StartAsyncThread ()");
Greg Clayton363be3f2011-07-15 03:27:12 +0000711
Greg Claytone76f8c42012-09-21 16:31:20 +0000712 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
713 return true;
714
Greg Clayton363be3f2011-07-15 03:27:12 +0000715 m_async_thread = Host::ThreadCreate ("<lldb.process.kdp-remote.async>", ProcessKDP::AsyncThread, this, NULL);
716 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
717}
718
719void
720ProcessKDP::StopAsyncThread ()
721{
722 LogSP log (ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
723
724 if (log)
Greg Claytone76f8c42012-09-21 16:31:20 +0000725 log->Printf ("ProcessKDP::StopAsyncThread ()");
Greg Clayton363be3f2011-07-15 03:27:12 +0000726
727 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
728
729 // Stop the stdio thread
730 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
731 {
732 Host::ThreadJoin (m_async_thread, NULL, NULL);
Greg Claytone76f8c42012-09-21 16:31:20 +0000733 m_async_thread = LLDB_INVALID_HOST_THREAD;
Greg Clayton363be3f2011-07-15 03:27:12 +0000734 }
735}
736
737
738void *
739ProcessKDP::AsyncThread (void *arg)
740{
741 ProcessKDP *process = (ProcessKDP*) arg;
742
Greg Claytone76f8c42012-09-21 16:31:20 +0000743 const lldb::pid_t pid = process->GetID();
744
Greg Clayton363be3f2011-07-15 03:27:12 +0000745 LogSP log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_PROCESS));
746 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000747 log->Printf ("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64 ") thread starting...", arg, pid);
Greg Clayton363be3f2011-07-15 03:27:12 +0000748
749 Listener listener ("ProcessKDP::AsyncThread");
750 EventSP event_sp;
751 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
752 eBroadcastBitAsyncThreadShouldExit;
753
Greg Claytone76f8c42012-09-21 16:31:20 +0000754
Greg Clayton363be3f2011-07-15 03:27:12 +0000755 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
756 {
Greg Clayton363be3f2011-07-15 03:27:12 +0000757 bool done = false;
758 while (!done)
759 {
760 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000761 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...",
Greg Claytone76f8c42012-09-21 16:31:20 +0000762 pid);
Greg Clayton363be3f2011-07-15 03:27:12 +0000763 if (listener.WaitForEvent (NULL, event_sp))
764 {
Greg Claytone76f8c42012-09-21 16:31:20 +0000765 uint32_t event_type = event_sp->GetType();
766 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000767 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") Got an event of type: %d...",
Greg Claytone76f8c42012-09-21 16:31:20 +0000768 pid,
769 event_type);
770
771 // When we are running, poll for 1 second to try and get an exception
772 // to indicate the process has stopped. If we don't get one, check to
773 // make sure no one asked us to exit
774 bool is_running = false;
775 DataExtractor exc_reply_packet;
776 do
Greg Clayton363be3f2011-07-15 03:27:12 +0000777 {
Greg Clayton363be3f2011-07-15 03:27:12 +0000778 switch (event_type)
779 {
Greg Claytone76f8c42012-09-21 16:31:20 +0000780 case eBroadcastBitAsyncContinue:
Greg Clayton363be3f2011-07-15 03:27:12 +0000781 {
Greg Claytone76f8c42012-09-21 16:31:20 +0000782 is_running = true;
783 if (process->m_comm.WaitForPacketWithTimeoutMicroSeconds (exc_reply_packet, 1 * USEC_PER_SEC))
Greg Clayton363be3f2011-07-15 03:27:12 +0000784 {
Greg Clayton3acaa922012-09-25 02:40:06 +0000785 ThreadSP thread_sp (process->GetKernelThread(process->GetThreadList(), process->GetThreadList()));
786 thread_sp->GetRegisterContext()->InvalidateAllRegisters();
787 static_cast<ThreadKDP *>(thread_sp.get())->SetStopInfoFrom_KDP_EXCEPTION (exc_reply_packet);
788
Greg Claytone76f8c42012-09-21 16:31:20 +0000789 // TODO: parse the stop reply packet
Greg Clayton3acaa922012-09-25 02:40:06 +0000790 is_running = false;
Greg Claytone76f8c42012-09-21 16:31:20 +0000791 process->SetPrivateState(eStateStopped);
792 }
793 else
794 {
795 // Check to see if we are supposed to exit. There is no way to
796 // interrupt a running kernel, so all we can do is wait for an
797 // exception or detach...
798 if (listener.GetNextEvent(event_sp))
799 {
800 // We got an event, go through the loop again
801 event_type = event_sp->GetType();
802 }
Greg Clayton363be3f2011-07-15 03:27:12 +0000803 }
804 }
Greg Claytone76f8c42012-09-21 16:31:20 +0000805 break;
Greg Clayton363be3f2011-07-15 03:27:12 +0000806
Greg Claytone76f8c42012-09-21 16:31:20 +0000807 case eBroadcastBitAsyncThreadShouldExit:
808 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000809 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...",
Greg Claytone76f8c42012-09-21 16:31:20 +0000810 pid);
Greg Clayton363be3f2011-07-15 03:27:12 +0000811 done = true;
Greg Claytone76f8c42012-09-21 16:31:20 +0000812 is_running = false;
813 break;
814
815 default:
816 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000817 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") got unknown event 0x%8.8x",
Greg Claytone76f8c42012-09-21 16:31:20 +0000818 pid,
819 event_type);
820 done = true;
821 is_running = false;
822 break;
Greg Clayton363be3f2011-07-15 03:27:12 +0000823 }
Greg Claytone76f8c42012-09-21 16:31:20 +0000824 } while (is_running);
Greg Clayton363be3f2011-07-15 03:27:12 +0000825 }
826 else
827 {
828 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000829 log->Printf ("ProcessKDP::AsyncThread (pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false",
Greg Claytone76f8c42012-09-21 16:31:20 +0000830 pid);
Greg Clayton363be3f2011-07-15 03:27:12 +0000831 done = true;
832 }
833 }
834 }
835
836 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000837 log->Printf ("ProcessKDP::AsyncThread (arg = %p, pid = %" PRIu64 ") thread exiting...",
Greg Claytone76f8c42012-09-21 16:31:20 +0000838 arg,
839 pid);
Greg Clayton363be3f2011-07-15 03:27:12 +0000840
841 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
842 return NULL;
843}
844
845
Greg Clayton307c7fd2012-10-19 22:22:57 +0000846class CommandObjectProcessKDPPacketSend : public CommandObjectParsed
847{
848private:
849
850 OptionGroupOptions m_option_group;
851 OptionGroupUInt64 m_command_byte;
852 OptionGroupString m_packet_data;
853
854 virtual Options *
855 GetOptions ()
856 {
857 return &m_option_group;
858 }
859
860
861public:
862 CommandObjectProcessKDPPacketSend(CommandInterpreter &interpreter) :
863 CommandObjectParsed (interpreter,
864 "process plugin packet send",
865 "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. ",
866 NULL),
867 m_option_group (interpreter),
868 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),
869 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)
870 {
871 m_option_group.Append (&m_command_byte, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
872 m_option_group.Append (&m_packet_data , LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
873 m_option_group.Finalize();
874 }
875
876 ~CommandObjectProcessKDPPacketSend ()
877 {
878 }
879
880 bool
881 DoExecute (Args& command, CommandReturnObject &result)
882 {
883 const size_t argc = command.GetArgumentCount();
884 if (argc == 0)
885 {
886 if (!m_command_byte.GetOptionValue().OptionWasSet())
887 {
888 result.AppendError ("the --command option must be set to a valid command byte");
889 result.SetStatus (eReturnStatusFailed);
890 }
891 else
892 {
893 const uint64_t command_byte = m_command_byte.GetOptionValue().GetUInt64Value(0);
894 if (command_byte > 0 && command_byte <= UINT8_MAX)
895 {
896 ProcessKDP *process = (ProcessKDP *)m_interpreter.GetExecutionContext().GetProcessPtr();
897 if (process)
898 {
899 const StateType state = process->GetState();
900
901 if (StateIsStoppedState (state, true))
902 {
903 std::vector<uint8_t> payload_bytes;
904 const char *ascii_hex_bytes_cstr = m_packet_data.GetOptionValue().GetCurrentValue();
905 if (ascii_hex_bytes_cstr && ascii_hex_bytes_cstr[0])
906 {
907 StringExtractor extractor(ascii_hex_bytes_cstr);
908 const size_t ascii_hex_bytes_cstr_len = extractor.GetStringRef().size();
909 if (ascii_hex_bytes_cstr_len & 1)
910 {
911 result.AppendErrorWithFormat ("payload data must contain an even number of ASCII hex characters: '%s'", ascii_hex_bytes_cstr);
912 result.SetStatus (eReturnStatusFailed);
913 return false;
914 }
915 payload_bytes.resize(ascii_hex_bytes_cstr_len/2);
916 if (extractor.GetHexBytes(&payload_bytes[0], payload_bytes.size(), '\xdd') != payload_bytes.size())
917 {
918 result.AppendErrorWithFormat ("payload data must only contain ASCII hex characters (no spaces or hex prefixes): '%s'", ascii_hex_bytes_cstr);
919 result.SetStatus (eReturnStatusFailed);
920 return false;
921 }
922 }
923 Error error;
924 DataExtractor reply;
925 process->GetCommunication().SendRawRequest (command_byte,
926 payload_bytes.empty() ? NULL : payload_bytes.data(),
927 payload_bytes.size(),
928 reply,
929 error);
930
931 if (error.Success())
932 {
933 // Copy the binary bytes into a hex ASCII string for the result
934 StreamString packet;
935 packet.PutBytesAsRawHex8(reply.GetDataStart(),
936 reply.GetByteSize(),
937 lldb::endian::InlHostByteOrder(),
938 lldb::endian::InlHostByteOrder());
939 result.AppendMessage(packet.GetString().c_str());
940 result.SetStatus (eReturnStatusSuccessFinishResult);
941 return true;
942 }
943 else
944 {
945 const char *error_cstr = error.AsCString();
946 if (error_cstr && error_cstr[0])
947 result.AppendError (error_cstr);
948 else
949 result.AppendErrorWithFormat ("unknown error 0x%8.8x", error.GetError());
950 result.SetStatus (eReturnStatusFailed);
951 return false;
952 }
953 }
954 else
955 {
956 result.AppendErrorWithFormat ("process must be stopped in order to send KDP packets, state is %s", StateAsCString (state));
957 result.SetStatus (eReturnStatusFailed);
958 }
959 }
960 else
961 {
962 result.AppendError ("invalid process");
963 result.SetStatus (eReturnStatusFailed);
964 }
965 }
966 else
967 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000968 result.AppendErrorWithFormat ("invalid command byte 0x%" PRIx64 ", valid values are 1 - 255", command_byte);
Greg Clayton307c7fd2012-10-19 22:22:57 +0000969 result.SetStatus (eReturnStatusFailed);
970 }
971 }
972 }
973 else
974 {
975 result.AppendErrorWithFormat ("'%s' takes no arguments, only options.", m_cmd_name.c_str());
976 result.SetStatus (eReturnStatusFailed);
977 }
978 return false;
979 }
980};
981
982class CommandObjectProcessKDPPacket : public CommandObjectMultiword
983{
984private:
985
986public:
987 CommandObjectProcessKDPPacket(CommandInterpreter &interpreter) :
988 CommandObjectMultiword (interpreter,
989 "process plugin packet",
990 "Commands that deal with KDP remote packets.",
991 NULL)
992 {
993 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessKDPPacketSend (interpreter)));
994 }
995
996 ~CommandObjectProcessKDPPacket ()
997 {
998 }
999};
1000
1001class CommandObjectMultiwordProcessKDP : public CommandObjectMultiword
1002{
1003public:
1004 CommandObjectMultiwordProcessKDP (CommandInterpreter &interpreter) :
1005 CommandObjectMultiword (interpreter,
1006 "process plugin",
1007 "A set of commands for operating on a ProcessKDP process.",
1008 "process plugin <subcommand> [<subcommand-options>]")
1009 {
1010 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessKDPPacket (interpreter)));
1011 }
1012
1013 ~CommandObjectMultiwordProcessKDP ()
1014 {
1015 }
1016};
1017
1018CommandObject *
1019ProcessKDP::GetPluginCommandObject()
1020{
1021 if (!m_command_sp)
1022 m_command_sp.reset (new CommandObjectMultiwordProcessKDP (GetTarget().GetDebugger().GetCommandInterpreter()));
1023 return m_command_sp.get();
1024}
1025