blob: 9e199c143349ad3627287395034074ac602de3a4 [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
16#include "lldb/Core/PluginManager.h"
17#include "lldb/Core/State.h"
18#include "lldb/Host/Host.h"
Greg Clayton1e5b0212011-07-15 16:31:38 +000019#include "lldb/Target/Target.h"
Greg Clayton363be3f2011-07-15 03:27:12 +000020
21// Project includes
22#include "ProcessKDP.h"
23#include "ProcessKDPLog.h"
24//#include "ThreadKDP.h"
25#include "StopInfoMachException.h"
26
27using namespace lldb;
28using namespace lldb_private;
29
30const char *
31ProcessKDP::GetPluginNameStatic()
32{
33 return "kdp-remote";
34}
35
36const char *
37ProcessKDP::GetPluginDescriptionStatic()
38{
39 return "KDP Remote protocol based debugging plug-in for darwin kernel debugging.";
40}
41
42void
43ProcessKDP::Terminate()
44{
45 PluginManager::UnregisterPlugin (ProcessKDP::CreateInstance);
46}
47
48
49Process*
50ProcessKDP::CreateInstance (Target &target, Listener &listener)
51{
52 return new ProcessKDP (target, listener);
53}
54
55bool
56ProcessKDP::CanDebug(Target &target)
57{
58 // For now we are just making sure the file exists for a given module
59 ModuleSP exe_module_sp(target.GetExecutableModule());
60 if (exe_module_sp.get())
61 {
62 const llvm::Triple &triple_ref = target.GetArchitecture().GetTriple();
63 if (triple_ref.getOS() == llvm::Triple::Darwin &&
64 triple_ref.getVendor() == llvm::Triple::Apple)
65 {
66
67 ObjectFile *exe_objfile = exe_module_sp->GetObjectFile();
68 if (exe_objfile->GetType() == ObjectFile::eTypeExecutable &&
69 exe_objfile->GetStrata() == ObjectFile::eStrataKernel)
70 return true;
71 }
72 }
73 return false;
74}
75
76//----------------------------------------------------------------------
77// ProcessKDP constructor
78//----------------------------------------------------------------------
79ProcessKDP::ProcessKDP(Target& target, Listener &listener) :
80 Process (target, listener),
81 m_comm("lldb.process.kdp-remote.communication"),
82 m_async_broadcaster ("lldb.process.kdp-remote.async-broadcaster"),
83 m_async_thread (LLDB_INVALID_HOST_THREAD)
84{
85// m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
86// m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
87}
88
89//----------------------------------------------------------------------
90// Destructor
91//----------------------------------------------------------------------
92ProcessKDP::~ProcessKDP()
93{
94 Clear();
95}
96
97//----------------------------------------------------------------------
98// PluginInterface
99//----------------------------------------------------------------------
100const char *
101ProcessKDP::GetPluginName()
102{
103 return "Process debugging plug-in that uses the Darwin KDP remote protocol";
104}
105
106const char *
107ProcessKDP::GetShortPluginName()
108{
109 return GetPluginNameStatic();
110}
111
112uint32_t
113ProcessKDP::GetPluginVersion()
114{
115 return 1;
116}
117
118Error
119ProcessKDP::WillLaunch (Module* module)
120{
121 Error error;
122 error.SetErrorString ("launching not supported in kdp-remote plug-in");
123 return error;
124}
125
126Error
127ProcessKDP::WillAttachToProcessWithID (lldb::pid_t pid)
128{
129 Error error;
130 error.SetErrorString ("attaching to a by process ID not supported in kdp-remote plug-in");
131 return error;
132}
133
134Error
135ProcessKDP::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
136{
137 Error error;
138 error.SetErrorString ("attaching to a by process name not supported in kdp-remote plug-in");
139 return error;
140}
141
142Error
143ProcessKDP::DoConnectRemote (const char *remote_url)
144{
145 // TODO: fill in the remote connection to the remote KDP here!
146 Error error;
147 error.SetErrorString ("attaching to a by process name not supported in kdp-remote plug-in");
148 return error;
149}
150
151//----------------------------------------------------------------------
152// Process Control
153//----------------------------------------------------------------------
154Error
155ProcessKDP::DoLaunch (Module* module,
156 char const *argv[],
157 char const *envp[],
158 uint32_t launch_flags,
159 const char *stdin_path,
160 const char *stdout_path,
161 const char *stderr_path,
162 const char *working_dir)
163{
164 Error error;
165 error.SetErrorString ("launching not supported in kdp-remote plug-in");
166 return error;
167}
168
169
170Error
171ProcessKDP::DoAttachToProcessWithID (lldb::pid_t attach_pid)
172{
173 Error error;
174 error.SetErrorString ("attach to process by ID is not suppported in kdp remote debugging");
175 return error;
176}
177
178size_t
179ProcessKDP::AttachInputReaderCallback (void *baton,
180 InputReader *reader,
181 lldb::InputReaderAction notification,
182 const char *bytes,
183 size_t bytes_len)
184{
185 if (notification == eInputReaderGotToken)
186 {
187// ProcessKDP *process = (ProcessKDP *)baton;
188// if (process->m_waiting_for_attach)
189// process->m_waiting_for_attach = false;
190 reader->SetIsDone(true);
191 return 1;
192 }
193 return 0;
194}
195
196Error
197ProcessKDP::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch)
198{
199 Error error;
200 error.SetErrorString ("attach to process by name is not suppported in kdp remote debugging");
201 return error;
202}
203
204
205void
206ProcessKDP::DidAttach ()
207{
208 LogSP log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_PROCESS));
209 if (log)
210 log->Printf ("ProcessKDP::DidLaunch()");
211 if (GetID() != LLDB_INVALID_PROCESS_ID)
212 {
213 // TODO: figure out the register context that we will use
214 }
215}
216
217Error
218ProcessKDP::WillResume ()
219{
220 return Error();
221}
222
223Error
224ProcessKDP::DoResume ()
225{
226 Error error;
227 error.SetErrorString ("ProcessKDP::DoResume () is not implemented yet");
228 return error;
229}
230
231uint32_t
232ProcessKDP::UpdateThreadListIfNeeded ()
233{
234 // locker will keep a mutex locked until it goes out of scope
235 LogSP log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_THREAD));
236 if (log && log->GetMask().Test(KDP_LOG_VERBOSE))
237 log->Printf ("ProcessKDP::%s (pid = %i)", __FUNCTION__, GetID());
238
239 Mutex::Locker locker (m_thread_list.GetMutex ());
240 // TODO: get the thread list here!
241 const uint32_t stop_id = GetStopID();
242 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
243 {
244 // Update the thread list's stop id immediately so we don't recurse into this function.
245// ThreadList curr_thread_list (this);
246// curr_thread_list.SetStopID(stop_id);
247//
248// std::vector<lldb::tid_t> thread_ids;
249// bool sequence_mutex_unavailable = false;
250// const size_t num_thread_ids = m_comm.GetCurrentThreadIDs (thread_ids, sequence_mutex_unavailable);
251// if (num_thread_ids > 0)
252// {
253// for (size_t i=0; i<num_thread_ids; ++i)
254// {
255// tid_t tid = thread_ids[i];
256// ThreadSP thread_sp (GetThreadList().FindThreadByID (tid, false));
257// if (!thread_sp)
258// thread_sp.reset (new ThreadGDBRemote (*this, tid));
259// curr_thread_list.AddThread(thread_sp);
260// }
261// }
262//
263// if (sequence_mutex_unavailable == false)
264// {
265// m_thread_list = curr_thread_list;
266// SetThreadStopInfo (m_last_stop_packet);
267// }
268 }
269 return GetThreadList().GetSize(false);
270}
271
272
273StateType
274ProcessKDP::SetThreadStopInfo (StringExtractor& stop_packet)
275{
276 // TODO: figure out why we stopped given the packet that tells us we stopped...
277 return eStateStopped;
278}
279
280void
281ProcessKDP::RefreshStateAfterStop ()
282{
283 // Let all threads recover from stopping and do any clean up based
284 // on the previous thread state (if any).
285 m_thread_list.RefreshStateAfterStop();
286 //SetThreadStopInfo (m_last_stop_packet);
287}
288
289Error
290ProcessKDP::DoHalt (bool &caused_stop)
291{
292 Error error;
293
294// bool timed_out = false;
295 Mutex::Locker locker;
296
297 if (m_public_state.GetValue() == eStateAttaching)
298 {
299 // We are being asked to halt during an attach. We need to just close
300 // our file handle and debugserver will go away, and we can be done...
301 m_comm.Disconnect();
302 }
303 else
304 {
305 // TODO: add the ability to halt a running kernel
306 error.SetErrorString ("halt not supported in kdp-remote plug-in");
307// if (!m_comm.SendInterrupt (locker, 2, caused_stop, timed_out))
308// {
309// if (timed_out)
310// error.SetErrorString("timed out sending interrupt packet");
311// else
312// error.SetErrorString("unknown error sending interrupt packet");
313// }
314 }
315 return error;
316}
317
318Error
319ProcessKDP::InterruptIfRunning (bool discard_thread_plans,
320 bool catch_stop_event,
321 EventSP &stop_event_sp)
322{
323 Error error;
324
325 LogSP log (ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
326
327 bool paused_private_state_thread = false;
328 const bool is_running = m_comm.IsRunning();
329 if (log)
330 log->Printf ("ProcessKDP::InterruptIfRunning(discard_thread_plans=%i, catch_stop_event=%i) is_running=%i",
331 discard_thread_plans,
332 catch_stop_event,
333 is_running);
334
335 if (discard_thread_plans)
336 {
337 if (log)
338 log->Printf ("ProcessKDP::InterruptIfRunning() discarding all thread plans");
339 m_thread_list.DiscardThreadPlans();
340 }
341 if (is_running)
342 {
343 if (catch_stop_event)
344 {
345 if (log)
346 log->Printf ("ProcessKDP::InterruptIfRunning() pausing private state thread");
347 PausePrivateStateThread();
348 paused_private_state_thread = true;
349 }
350
351 bool timed_out = false;
352// bool sent_interrupt = false;
353 Mutex::Locker locker;
354
355 // TODO: implement halt in CommunicationKDP
356// if (!m_comm.SendInterrupt (locker, 1, sent_interrupt, timed_out))
357// {
358// if (timed_out)
359// error.SetErrorString("timed out sending interrupt packet");
360// else
361// error.SetErrorString("unknown error sending interrupt packet");
362// if (paused_private_state_thread)
363// ResumePrivateStateThread();
364// return error;
365// }
366
367 if (catch_stop_event)
368 {
369 // LISTEN HERE
370 TimeValue timeout_time;
371 timeout_time = TimeValue::Now();
372 timeout_time.OffsetWithSeconds(5);
373 StateType state = WaitForStateChangedEventsPrivate (&timeout_time, stop_event_sp);
374
375 timed_out = state == eStateInvalid;
376 if (log)
377 log->Printf ("ProcessKDP::InterruptIfRunning() catch stop event: state = %s, timed-out=%i", StateAsCString(state), timed_out);
378
379 if (timed_out)
380 error.SetErrorString("unable to verify target stopped");
381 }
382
383 if (paused_private_state_thread)
384 {
385 if (log)
386 log->Printf ("ProcessKDP::InterruptIfRunning() resuming private state thread");
387 ResumePrivateStateThread();
388 }
389 }
390 return error;
391}
392
393Error
394ProcessKDP::WillDetach ()
395{
396 LogSP log (ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
397 if (log)
398 log->Printf ("ProcessKDP::WillDetach()");
399
400 bool discard_thread_plans = true;
401 bool catch_stop_event = true;
402 EventSP event_sp;
403 return InterruptIfRunning (discard_thread_plans, catch_stop_event, event_sp);
404}
405
406Error
407ProcessKDP::DoDetach()
408{
409 Error error;
410 LogSP log (ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
411 if (log)
412 log->Printf ("ProcessKDP::DoDetach()");
413
414 DisableAllBreakpointSites ();
415
416 m_thread_list.DiscardThreadPlans();
417
Greg Clayton1e5b0212011-07-15 16:31:38 +0000418 size_t response_size = m_comm.Disconnect ();
Greg Clayton363be3f2011-07-15 03:27:12 +0000419 if (log)
420 {
421 if (response_size)
422 log->PutCString ("ProcessKDP::DoDetach() detach packet sent successfully");
423 else
424 log->PutCString ("ProcessKDP::DoDetach() detach packet send failed");
425 }
426 // Sleep for one second to let the process get all detached...
427 StopAsyncThread ();
428
429 m_comm.StopReadThread();
430 m_comm.Disconnect(); // Disconnect from the debug server.
431
432 SetPrivateState (eStateDetached);
433 ResumePrivateStateThread();
434
435 //KillDebugserverProcess ();
436 return error;
437}
438
439Error
440ProcessKDP::DoDestroy ()
441{
442 Error error;
443 LogSP log (ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
444 if (log)
445 log->Printf ("ProcessKDP::DoDestroy()");
446
447 // Interrupt if our inferior is running...
448 if (m_comm.IsConnected())
449 {
450 if (m_public_state.GetValue() == eStateAttaching)
451 {
452 // We are being asked to halt during an attach. We need to just close
453 // our file handle and debugserver will go away, and we can be done...
454 m_comm.Disconnect();
455 }
456 else
457 {
458
459 StringExtractor response;
460 // TODO: Send kill packet?
461 SetExitStatus(SIGABRT, NULL);
462 }
463 }
464 StopAsyncThread ();
465 m_comm.StopReadThread();
466 m_comm.Disconnect(); // Disconnect from the debug server.
467 return error;
468}
469
470//------------------------------------------------------------------
471// Process Queries
472//------------------------------------------------------------------
473
474bool
475ProcessKDP::IsAlive ()
476{
477 return m_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
478}
479
480//------------------------------------------------------------------
481// Process Memory
482//------------------------------------------------------------------
483size_t
484ProcessKDP::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
485{
486 error.SetErrorString ("ProcessKDP::DoReadMemory not implemented");
487 return 0;
488}
489
490size_t
491ProcessKDP::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
492{
493 error.SetErrorString ("ProcessKDP::DoReadMemory not implemented");
494 return 0;
495}
496
497lldb::addr_t
498ProcessKDP::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
499{
500 error.SetErrorString ("memory allocation not suppported in kdp remote debugging");
501 return LLDB_INVALID_ADDRESS;
502}
503
504Error
505ProcessKDP::DoDeallocateMemory (lldb::addr_t addr)
506{
507 Error error;
508 error.SetErrorString ("memory deallocation not suppported in kdp remote debugging");
509 return error;
510}
511
512Error
513ProcessKDP::EnableBreakpoint (BreakpointSite *bp_site)
514{
515 return EnableSoftwareBreakpoint (bp_site);
516}
517
518Error
519ProcessKDP::DisableBreakpoint (BreakpointSite *bp_site)
520{
521 return DisableSoftwareBreakpoint (bp_site);
522}
523
524Error
525ProcessKDP::EnableWatchpoint (WatchpointLocation *wp)
526{
527 Error error;
528 error.SetErrorString ("watchpoints are not suppported in kdp remote debugging");
529 return error;
530}
531
532Error
533ProcessKDP::DisableWatchpoint (WatchpointLocation *wp)
534{
535 Error error;
536 error.SetErrorString ("watchpoints are not suppported in kdp remote debugging");
537 return error;
538}
539
540void
541ProcessKDP::Clear()
542{
543 Mutex::Locker locker (m_thread_list.GetMutex ());
544 m_thread_list.Clear();
545}
546
547Error
548ProcessKDP::DoSignal (int signo)
549{
550 Error error;
551 error.SetErrorString ("sending signals is not suppported in kdp remote debugging");
552 return error;
553}
554
555void
556ProcessKDP::Initialize()
557{
558 static bool g_initialized = false;
559
560 if (g_initialized == false)
561 {
562 g_initialized = true;
563 PluginManager::RegisterPlugin (GetPluginNameStatic(),
564 GetPluginDescriptionStatic(),
565 CreateInstance);
566
567 Log::Callbacks log_callbacks = {
568 ProcessKDPLog::DisableLog,
569 ProcessKDPLog::EnableLog,
570 ProcessKDPLog::ListLogCategories
571 };
572
573 Log::RegisterLogChannel (ProcessKDP::GetPluginNameStatic(), log_callbacks);
574 }
575}
576
577bool
578ProcessKDP::StartAsyncThread ()
579{
580 LogSP log (ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
581
582 if (log)
583 log->Printf ("ProcessKDP::%s ()", __FUNCTION__);
584
585 // Create a thread that watches our internal state and controls which
586 // events make it to clients (into the DCProcess event queue).
587 m_async_thread = Host::ThreadCreate ("<lldb.process.kdp-remote.async>", ProcessKDP::AsyncThread, this, NULL);
588 return IS_VALID_LLDB_HOST_THREAD(m_async_thread);
589}
590
591void
592ProcessKDP::StopAsyncThread ()
593{
594 LogSP log (ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PROCESS));
595
596 if (log)
597 log->Printf ("ProcessKDP::%s ()", __FUNCTION__);
598
599 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
600
601 // Stop the stdio thread
602 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
603 {
604 Host::ThreadJoin (m_async_thread, NULL, NULL);
605 }
606}
607
608
609void *
610ProcessKDP::AsyncThread (void *arg)
611{
612 ProcessKDP *process = (ProcessKDP*) arg;
613
614 LogSP log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_PROCESS));
615 if (log)
616 log->Printf ("ProcessKDP::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, arg, process->GetID());
617
618 Listener listener ("ProcessKDP::AsyncThread");
619 EventSP event_sp;
620 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
621 eBroadcastBitAsyncThreadShouldExit;
622
623 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
624 {
625 listener.StartListeningForEvents (&process->m_comm, Communication::eBroadcastBitReadThreadDidExit);
626
627 bool done = false;
628 while (!done)
629 {
630 if (log)
631 log->Printf ("ProcessKDP::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
632 if (listener.WaitForEvent (NULL, event_sp))
633 {
634 const uint32_t event_type = event_sp->GetType();
635 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
636 {
637 if (log)
638 log->Printf ("ProcessKDP::%s (arg = %p, pid = %i) Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
639
640 switch (event_type)
641 {
642 case eBroadcastBitAsyncContinue:
643 {
644 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
645
646 if (continue_packet)
647 {
648 // TODO: do continue support here
649
650// const char *continue_cstr = (const char *)continue_packet->GetBytes ();
651// const size_t continue_cstr_len = continue_packet->GetByteSize ();
652// if (log)
653// log->Printf ("ProcessKDP::%s (arg = %p, pid = %i) got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
654//
655// if (::strstr (continue_cstr, "vAttach") == NULL)
656// process->SetPrivateState(eStateRunning);
657// StringExtractor response;
658// StateType stop_state = process->GetCommunication().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
659//
660// switch (stop_state)
661// {
662// case eStateStopped:
663// case eStateCrashed:
664// case eStateSuspended:
665// process->m_last_stop_packet = response;
666// process->SetPrivateState (stop_state);
667// break;
668//
669// case eStateExited:
670// process->m_last_stop_packet = response;
671// response.SetFilePos(1);
672// process->SetExitStatus(response.GetHexU8(), NULL);
673// done = true;
674// break;
675//
676// case eStateInvalid:
677// process->SetExitStatus(-1, "lost connection");
678// break;
679//
680// default:
681// process->SetPrivateState (stop_state);
682// break;
683// }
684 }
685 }
686 break;
687
688 case eBroadcastBitAsyncThreadShouldExit:
689 if (log)
690 log->Printf ("ProcessKDP::%s (arg = %p, pid = %i) got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
691 done = true;
692 break;
693
694 default:
695 if (log)
696 log->Printf ("ProcessKDP::%s (arg = %p, pid = %i) got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
697 done = true;
698 break;
699 }
700 }
701 else if (event_sp->BroadcasterIs (&process->m_comm))
702 {
703 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
704 {
705 process->SetExitStatus (-1, "lost connection");
706 done = true;
707 }
708 }
709 }
710 else
711 {
712 if (log)
713 log->Printf ("ProcessKDP::%s (arg = %p, pid = %i) listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
714 done = true;
715 }
716 }
717 }
718
719 if (log)
720 log->Printf ("ProcessKDP::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, arg, process->GetID());
721
722 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
723 return NULL;
724}
725
726