blob: 20bd1cc794fb9dd59f15fc37a69e5bf6509e27ee [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
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#include "lldb/Target/Process.h"
11
12#include "lldb/lldb-private-log.h"
13
14#include "lldb/Breakpoint/StoppointCallbackContext.h"
15#include "lldb/Breakpoint/BreakpointLocation.h"
16#include "lldb/Core/Event.h"
17#include "lldb/Core/Debugger.h"
18#include "lldb/Core/Log.h"
19#include "lldb/Core/PluginManager.h"
20#include "lldb/Core/State.h"
21#include "lldb/Host/Host.h"
22#include "lldb/Target/ABI.h"
23#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000024#include "lldb/Target/StopInfo.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000025#include "lldb/Target/Target.h"
26#include "lldb/Target/TargetList.h"
27#include "lldb/Target/Thread.h"
28#include "lldb/Target/ThreadPlan.h"
29
30using namespace lldb;
31using namespace lldb_private;
32
33Process*
34Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener)
35{
36 ProcessCreateInstance create_callback = NULL;
37 if (plugin_name)
38 {
39 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
40 if (create_callback)
41 {
42 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
43 if (debugger_ap->CanDebug(target))
44 return debugger_ap.release();
45 }
46 }
47 else
48 {
Greg Claytonc982c762010-07-09 20:39:50 +000049 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +000050 {
Greg Claytonc982c762010-07-09 20:39:50 +000051 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
52 if (debugger_ap->CanDebug(target))
53 return debugger_ap.release();
Chris Lattner30fdc8d2010-06-08 16:52:24 +000054 }
55 }
56 return NULL;
57}
58
59
60//----------------------------------------------------------------------
61// Process constructor
62//----------------------------------------------------------------------
63Process::Process(Target &target, Listener &listener) :
64 UserID (LLDB_INVALID_PROCESS_ID),
65 Broadcaster ("Process"),
66 m_target (target),
67 m_section_load_info (),
68 m_public_state (eStateUnloaded),
69 m_private_state (eStateUnloaded),
70 m_private_state_broadcaster ("lldb.process.internal_state_broadcaster"),
71 m_private_state_control_broadcaster ("lldb.process.internal_state_control_broadcaster"),
72 m_private_state_listener ("lldb.process.internal_state_listener"),
73 m_private_state_control_wait(),
74 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
75 m_stop_id (0),
76 m_thread_index_id (0),
77 m_exit_status (-1),
78 m_exit_string (),
79 m_thread_list (this),
80 m_notifications (),
81 m_listener(listener),
82 m_unix_signals (),
Sean Callanan2235f322010-08-11 03:57:18 +000083 m_objc_object_printer(*this),
84 m_persistent_vars()
Chris Lattner30fdc8d2010-06-08 16:52:24 +000085{
86 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT);
87 if (log)
88 log->Printf ("%p Process::Process()", this);
89
90 listener.StartListeningForEvents (this,
91 eBroadcastBitStateChanged |
92 eBroadcastBitInterrupt |
93 eBroadcastBitSTDOUT |
94 eBroadcastBitSTDERR);
95
96 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
97 eBroadcastBitStateChanged);
98
99 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
100 eBroadcastInternalStateControlStop |
101 eBroadcastInternalStateControlPause |
102 eBroadcastInternalStateControlResume);
103}
104
105//----------------------------------------------------------------------
106// Destructor
107//----------------------------------------------------------------------
108Process::~Process()
109{
110 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT);
111 if (log)
112 log->Printf ("%p Process::~Process()", this);
113 StopPrivateStateThread();
114}
115
116void
117Process::Finalize()
118{
119 // Do any cleanup needed prior to being destructed... Subclasses
120 // that override this method should call this superclass method as well.
121}
122
123void
124Process::RegisterNotificationCallbacks (const Notifications& callbacks)
125{
126 m_notifications.push_back(callbacks);
127 if (callbacks.initialize != NULL)
128 callbacks.initialize (callbacks.baton, this);
129}
130
131bool
132Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
133{
134 std::vector<Notifications>::iterator pos, end = m_notifications.end();
135 for (pos = m_notifications.begin(); pos != end; ++pos)
136 {
137 if (pos->baton == callbacks.baton &&
138 pos->initialize == callbacks.initialize &&
139 pos->process_state_changed == callbacks.process_state_changed)
140 {
141 m_notifications.erase(pos);
142 return true;
143 }
144 }
145 return false;
146}
147
148void
149Process::SynchronouslyNotifyStateChanged (StateType state)
150{
151 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
152 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
153 {
154 if (notification_pos->process_state_changed)
155 notification_pos->process_state_changed (notification_pos->baton, this, state);
156 }
157}
158
159// FIXME: We need to do some work on events before the general Listener sees them.
160// For instance if we are continuing from a breakpoint, we need to ensure that we do
161// the little "insert real insn, step & stop" trick. But we can't do that when the
162// event is delivered by the broadcaster - since that is done on the thread that is
163// waiting for new events, so if we needed more than one event for our handling, we would
164// stall. So instead we do it when we fetch the event off of the queue.
165//
166
167StateType
168Process::GetNextEvent (EventSP &event_sp)
169{
170 StateType state = eStateInvalid;
171
172 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
173 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
174
175 return state;
176}
177
178
179StateType
180Process::WaitForProcessToStop (const TimeValue *timeout)
181{
182 StateType match_states[] = { eStateStopped, eStateCrashed, eStateDetached, eStateExited, eStateUnloaded };
183 return WaitForState (timeout, match_states, sizeof(match_states) / sizeof(StateType));
184}
185
186
187StateType
188Process::WaitForState
189(
190 const TimeValue *timeout,
191 const StateType *match_states, const uint32_t num_match_states
192)
193{
194 EventSP event_sp;
195 uint32_t i;
196 StateType state = eStateUnloaded;
197 while (state != eStateInvalid)
198 {
199 state = WaitForStateChangedEvents (timeout, event_sp);
200
201 for (i=0; i<num_match_states; ++i)
202 {
203 if (match_states[i] == state)
204 return state;
205 }
206 }
207 return state;
208}
209
210StateType
211Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
212{
213 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
214
215 if (log)
216 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
217
218 StateType state = eStateInvalid;
219 if (m_listener.WaitForEventForBroadcasterWithType(timeout,
220 this,
221 eBroadcastBitStateChanged,
222 event_sp))
223 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
224
225 if (log)
226 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
227 __FUNCTION__,
228 timeout,
229 StateAsCString(state));
230 return state;
231}
232
233Event *
234Process::PeekAtStateChangedEvents ()
235{
236 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
237
238 if (log)
239 log->Printf ("Process::%s...", __FUNCTION__);
240
241 Event *event_ptr;
242 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType(this,
243 eBroadcastBitStateChanged);
244 if (log)
245 {
246 if (event_ptr)
247 {
248 log->Printf ("Process::%s (event_ptr) => %s",
249 __FUNCTION__,
250 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
251 }
252 else
253 {
254 log->Printf ("Process::%s no events found",
255 __FUNCTION__);
256 }
257 }
258 return event_ptr;
259}
260
261StateType
262Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
263{
264 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
265
266 if (log)
267 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
268
269 StateType state = eStateInvalid;
270 if (m_private_state_listener.WaitForEventForBroadcasterWithType(timeout,
271 &m_private_state_broadcaster,
272 eBroadcastBitStateChanged,
273 event_sp))
274 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
275
276 // This is a bit of a hack, but when we wait here we could very well return
277 // to the command-line, and that could disable the log, which would render the
278 // log we got above invalid.
279 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
280 if (log)
281 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
282 return state;
283}
284
285bool
286Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
287{
288 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
289
290 if (log)
291 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
292
293 if (control_only)
294 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
295 else
296 return m_private_state_listener.WaitForEvent(timeout, event_sp);
297}
298
299bool
300Process::IsRunning () const
301{
302 return StateIsRunningState (m_public_state.GetValue());
303}
304
305int
306Process::GetExitStatus ()
307{
308 if (m_public_state.GetValue() == eStateExited)
309 return m_exit_status;
310 return -1;
311}
312
313const char *
314Process::GetExitDescription ()
315{
316 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
317 return m_exit_string.c_str();
318 return NULL;
319}
320
321void
322Process::SetExitStatus (int status, const char *cstr)
323{
324 m_exit_status = status;
325 if (cstr)
326 m_exit_string = cstr;
327 else
328 m_exit_string.clear();
329
330 SetPrivateState (eStateExited);
331}
332
333// This static callback can be used to watch for local child processes on
334// the current host. The the child process exits, the process will be
335// found in the global target list (we want to be completely sure that the
336// lldb_private::Process doesn't go away before we can deliver the signal.
337bool
338Process::SetProcessExitStatus
339(
340 void *callback_baton,
341 lldb::pid_t pid,
342 int signo, // Zero for no signal
343 int exit_status // Exit value of process if signal is zero
344)
345{
346 if (signo == 0 || exit_status)
347 {
Greg Clayton66111032010-06-23 01:19:29 +0000348 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000349 if (target_sp)
350 {
351 ProcessSP process_sp (target_sp->GetProcessSP());
352 if (process_sp)
353 {
354 const char *signal_cstr = NULL;
355 if (signo)
356 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
357
358 process_sp->SetExitStatus (exit_status, signal_cstr);
359 }
360 }
361 return true;
362 }
363 return false;
364}
365
366
367uint32_t
368Process::GetNextThreadIndexID ()
369{
370 return ++m_thread_index_id;
371}
372
373StateType
374Process::GetState()
375{
376 // If any other threads access this we will need a mutex for it
377 return m_public_state.GetValue ();
378}
379
380void
381Process::SetPublicState (StateType new_state)
382{
383 Log *log = lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE);
384 if (log)
385 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
386 m_public_state.SetValue (new_state);
387}
388
389StateType
390Process::GetPrivateState ()
391{
392 return m_private_state.GetValue();
393}
394
395void
396Process::SetPrivateState (StateType new_state)
397{
398 Log *log = lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE);
399 bool state_changed = false;
400
401 if (log)
402 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
403
404 Mutex::Locker locker(m_private_state.GetMutex());
405
406 const StateType old_state = m_private_state.GetValueNoLock ();
407 state_changed = old_state != new_state;
408 if (state_changed)
409 {
410 m_private_state.SetValueNoLock (new_state);
411 if (StateIsStoppedState(new_state))
412 {
413 m_stop_id++;
414 if (log)
415 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_stop_id);
416 }
417 // Use our target to get a shared pointer to ourselves...
418 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
419 }
420 else
421 {
422 if (log)
423 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state), StateAsCString(old_state));
424 }
425}
426
427
428uint32_t
429Process::GetStopID() const
430{
431 return m_stop_id;
432}
433
434addr_t
435Process::GetImageInfoAddress()
436{
437 return LLDB_INVALID_ADDRESS;
438}
439
440DynamicLoader *
441Process::GetDynamicLoader()
442{
443 return NULL;
444}
445
446const ABI *
447Process::GetABI()
448{
449 ConstString& triple = m_target_triple;
450
451 if (triple.IsEmpty())
452 return NULL;
453
454 if (m_abi_sp.get() == NULL)
455 {
456 m_abi_sp.reset(ABI::FindPlugin(triple));
457 }
458
459 return m_abi_sp.get();
460}
461
462BreakpointSiteList &
463Process::GetBreakpointSiteList()
464{
465 return m_breakpoint_site_list;
466}
467
468const BreakpointSiteList &
469Process::GetBreakpointSiteList() const
470{
471 return m_breakpoint_site_list;
472}
473
474
475void
476Process::DisableAllBreakpointSites ()
477{
478 m_breakpoint_site_list.SetEnabledForAll (false);
479}
480
481Error
482Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
483{
484 Error error (DisableBreakpointSiteByID (break_id));
485
486 if (error.Success())
487 m_breakpoint_site_list.Remove(break_id);
488
489 return error;
490}
491
492Error
493Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
494{
495 Error error;
496 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
497 if (bp_site_sp)
498 {
499 if (bp_site_sp->IsEnabled())
500 error = DisableBreakpoint (bp_site_sp.get());
501 }
502 else
503 {
504 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
505 }
506
507 return error;
508}
509
510Error
511Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
512{
513 Error error;
514 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
515 if (bp_site_sp)
516 {
517 if (!bp_site_sp->IsEnabled())
518 error = EnableBreakpoint (bp_site_sp.get());
519 }
520 else
521 {
522 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
523 }
524 return error;
525}
526
Stephen Wilson50bd94f2010-07-17 00:56:13 +0000527lldb::break_id_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000528Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware)
529{
530 const addr_t load_addr = owner->GetAddress().GetLoadAddress (this);
531 if (load_addr != LLDB_INVALID_ADDRESS)
532 {
533 BreakpointSiteSP bp_site_sp;
534
535 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
536 // create a new breakpoint site and add it.
537
538 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
539
540 if (bp_site_sp)
541 {
542 bp_site_sp->AddOwner (owner);
543 owner->SetBreakpointSite (bp_site_sp);
544 return bp_site_sp->GetID();
545 }
546 else
547 {
548 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
549 if (bp_site_sp)
550 {
551 if (EnableBreakpoint (bp_site_sp.get()).Success())
552 {
553 owner->SetBreakpointSite (bp_site_sp);
554 return m_breakpoint_site_list.Add (bp_site_sp);
555 }
556 }
557 }
558 }
559 // We failed to enable the breakpoint
560 return LLDB_INVALID_BREAK_ID;
561
562}
563
564void
565Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
566{
567 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
568 if (num_owners == 0)
569 {
570 DisableBreakpoint(bp_site_sp.get());
571 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
572 }
573}
574
575
576size_t
577Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
578{
579 size_t bytes_removed = 0;
580 addr_t intersect_addr;
581 size_t intersect_size;
582 size_t opcode_offset;
583 size_t idx;
584 BreakpointSiteSP bp;
585
586 for (idx = 0; (bp = m_breakpoint_site_list.GetByIndex(idx)) != NULL; ++idx)
587 {
588 if (bp->GetType() == BreakpointSite::eSoftware)
589 {
590 if (bp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
591 {
592 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
593 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
594 assert(opcode_offset + intersect_size <= bp->GetByteSize());
595 size_t buf_offset = intersect_addr - bp_addr;
596 ::memcpy(buf + buf_offset, bp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
597 }
598 }
599 }
600 return bytes_removed;
601}
602
603
604Error
605Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
606{
607 Error error;
608 assert (bp_site != NULL);
609 Log *log = lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS);
610 const addr_t bp_addr = bp_site->GetLoadAddress();
611 if (log)
612 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
613 if (bp_site->IsEnabled())
614 {
615 if (log)
616 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
617 return error;
618 }
619
620 if (bp_addr == LLDB_INVALID_ADDRESS)
621 {
622 error.SetErrorString("BreakpointSite contains an invalid load address.");
623 return error;
624 }
625 // Ask the lldb::Process subclass to fill in the correct software breakpoint
626 // trap for the breakpoint site
627 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
628
629 if (bp_opcode_size == 0)
630 {
631 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx.\n", bp_addr);
632 }
633 else
634 {
635 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
636
637 if (bp_opcode_bytes == NULL)
638 {
639 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
640 return error;
641 }
642
643 // Save the original opcode by reading it
644 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
645 {
646 // Write a software breakpoint in place of the original opcode
647 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
648 {
649 uint8_t verify_bp_opcode_bytes[64];
650 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
651 {
652 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
653 {
654 bp_site->SetEnabled(true);
655 bp_site->SetType (BreakpointSite::eSoftware);
656 if (log)
657 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
658 bp_site->GetID(),
659 (uint64_t)bp_addr);
660 }
661 else
662 error.SetErrorString("Failed to verify the breakpoint trap in memory.");
663 }
664 else
665 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
666 }
667 else
668 error.SetErrorString("Unable to write breakpoint trap to memory.");
669 }
670 else
671 error.SetErrorString("Unable to read memory at breakpoint address.");
672 }
673 if (log)
674 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
675 bp_site->GetID(),
676 (uint64_t)bp_addr,
677 error.AsCString());
678 return error;
679}
680
681Error
682Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
683{
684 Error error;
685 assert (bp_site != NULL);
686 Log *log = lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS);
687 addr_t bp_addr = bp_site->GetLoadAddress();
688 lldb::user_id_t breakID = bp_site->GetID();
689 if (log)
690 log->Printf ("ProcessMacOSX::DisableBreakpoint (breakID = %d) addr = 0x%llx", breakID, (uint64_t)bp_addr);
691
692 if (bp_site->IsHardware())
693 {
694 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
695 }
696 else if (bp_site->IsEnabled())
697 {
698 const size_t break_op_size = bp_site->GetByteSize();
699 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
700 if (break_op_size > 0)
701 {
702 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +0000703 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +0000704 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000705 bool break_op_found = false;
706
707 // Read the breakpoint opcode
708 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
709 {
710 bool verify = false;
711 // Make sure we have the a breakpoint opcode exists at this address
712 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
713 {
714 break_op_found = true;
715 // We found a valid breakpoint opcode at this address, now restore
716 // the saved opcode.
717 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
718 {
719 verify = true;
720 }
721 else
722 error.SetErrorString("Memory write failed when restoring original opcode.");
723 }
724 else
725 {
726 error.SetErrorString("Original breakpoint trap is no longer in memory.");
727 // Set verify to true and so we can check if the original opcode has already been restored
728 verify = true;
729 }
730
731 if (verify)
732 {
Greg Claytonc982c762010-07-09 20:39:50 +0000733 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +0000734 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000735 // Verify that our original opcode made it back to the inferior
736 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
737 {
738 // compare the memory we just read with the original opcode
739 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
740 {
741 // SUCCESS
742 bp_site->SetEnabled(false);
743 if (log)
744 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
745 return error;
746 }
747 else
748 {
749 if (break_op_found)
750 error.SetErrorString("Failed to restore original opcode.");
751 }
752 }
753 else
754 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
755 }
756 }
757 else
758 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
759 }
760 }
761 else
762 {
763 if (log)
764 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
765 return error;
766 }
767
768 if (log)
769 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
770 bp_site->GetID(),
771 (uint64_t)bp_addr,
772 error.AsCString());
773 return error;
774
775}
776
777
778size_t
779Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
780{
781 if (buf == NULL || size == 0)
782 return 0;
783
784 size_t bytes_read = 0;
785 uint8_t *bytes = (uint8_t *)buf;
786
787 while (bytes_read < size)
788 {
789 const size_t curr_size = size - bytes_read;
790 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
791 bytes + bytes_read,
792 curr_size,
793 error);
794 bytes_read += curr_bytes_read;
795 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
796 break;
797 }
798
799 // Replace any software breakpoint opcodes that fall into this range back
800 // into "buf" before we return
801 if (bytes_read > 0)
802 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
803 return bytes_read;
804}
805
806size_t
807Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
808{
809 size_t bytes_written = 0;
810 const uint8_t *bytes = (const uint8_t *)buf;
811
812 while (bytes_written < size)
813 {
814 const size_t curr_size = size - bytes_written;
815 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
816 bytes + bytes_written,
817 curr_size,
818 error);
819 bytes_written += curr_bytes_written;
820 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
821 break;
822 }
823 return bytes_written;
824}
825
826size_t
827Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
828{
829 if (buf == NULL || size == 0)
830 return 0;
831 // We need to write any data that would go where any current software traps
832 // (enabled software breakpoints) any software traps (breakpoints) that we
833 // may have placed in our tasks memory.
834
835 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
836 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
837
838 if (iter == end || iter->second->GetLoadAddress() > addr + size)
839 return DoWriteMemory(addr, buf, size, error);
840
841 BreakpointSiteList::collection::const_iterator pos;
842 size_t bytes_written = 0;
Greg Claytonc982c762010-07-09 20:39:50 +0000843 addr_t intersect_addr = 0;
844 size_t intersect_size = 0;
845 size_t opcode_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000846 const uint8_t *ubuf = (const uint8_t *)buf;
847
848 for (pos = iter; pos != end; ++pos)
849 {
850 BreakpointSiteSP bp;
851 bp = pos->second;
852
853 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
854 assert(addr <= intersect_addr && intersect_addr < addr + size);
855 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
856 assert(opcode_offset + intersect_size <= bp->GetByteSize());
857
858 // Check for bytes before this breakpoint
859 const addr_t curr_addr = addr + bytes_written;
860 if (intersect_addr > curr_addr)
861 {
862 // There are some bytes before this breakpoint that we need to
863 // just write to memory
864 size_t curr_size = intersect_addr - curr_addr;
865 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
866 ubuf + bytes_written,
867 curr_size,
868 error);
869 bytes_written += curr_bytes_written;
870 if (curr_bytes_written != curr_size)
871 {
872 // We weren't able to write all of the requested bytes, we
873 // are done looping and will return the number of bytes that
874 // we have written so far.
875 break;
876 }
877 }
878
879 // Now write any bytes that would cover up any software breakpoints
880 // directly into the breakpoint opcode buffer
881 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
882 bytes_written += intersect_size;
883 }
884
885 // Write any remaining bytes after the last breakpoint if we have any left
886 if (bytes_written < size)
887 bytes_written += WriteMemoryPrivate (addr + bytes_written,
888 ubuf + bytes_written,
889 size - bytes_written,
890 error);
891
892 return bytes_written;
893}
894
895addr_t
896Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
897{
898 // Fixme: we should track the blocks we've allocated, and clean them up...
899 // We could even do our own allocator here if that ends up being more efficient.
900 return DoAllocateMemory (size, permissions, error);
901}
902
903Error
904Process::DeallocateMemory (addr_t ptr)
905{
906 return DoDeallocateMemory (ptr);
907}
908
909
910Error
911Process::EnableWatchpoint (WatchpointLocation *watchpoint)
912{
913 Error error;
914 error.SetErrorString("watchpoints are not supported");
915 return error;
916}
917
918Error
919Process::DisableWatchpoint (WatchpointLocation *watchpoint)
920{
921 Error error;
922 error.SetErrorString("watchpoints are not supported");
923 return error;
924}
925
926StateType
927Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
928{
929 StateType state;
930 // Now wait for the process to launch and return control to us, and then
931 // call DidLaunch:
932 while (1)
933 {
934 // FIXME: Might want to put a timeout in here:
935 state = WaitForStateChangedEventsPrivate (NULL, event_sp);
936 if (state == eStateStopped || state == eStateCrashed || state == eStateExited)
937 break;
938 else
939 HandlePrivateEvent (event_sp);
940 }
941 return state;
942}
943
944Error
945Process::Launch
946(
947 char const *argv[],
948 char const *envp[],
949 const char *stdin_path,
950 const char *stdout_path,
951 const char *stderr_path
952)
953{
954 Error error;
955 m_target_triple.Clear();
956 m_abi_sp.reset();
957
958 Module *exe_module = m_target.GetExecutableModule().get();
959 if (exe_module)
960 {
961 char exec_file_path[PATH_MAX];
962 exe_module->GetFileSpec().GetPath(exec_file_path, sizeof(exec_file_path));
963 if (exe_module->GetFileSpec().Exists())
964 {
965 error = WillLaunch (exe_module);
966 if (error.Success())
967 {
968 // The args coming in should not contain the application name, the
969 // lldb_private::Process class will add this in case the executable
970 // gets resolved to a different file than was given on the command
971 // line (like when an applicaiton bundle is specified and will
972 // resolve to the contained exectuable file, or the file given was
973 // a symlink or other file system link that resolves to a different
974 // file).
975
976 // Get the resolved exectuable path
977
978 // Make a new argument vector
979 std::vector<const char *> exec_path_plus_argv;
980 // Append the resolved executable path
981 exec_path_plus_argv.push_back (exec_file_path);
982
983 // Push all args if there are any
984 if (argv)
985 {
986 for (int i = 0; argv[i]; ++i)
987 exec_path_plus_argv.push_back(argv[i]);
988 }
989
990 // Push a NULL to terminate the args.
991 exec_path_plus_argv.push_back(NULL);
992
993 // Now launch using these arguments.
Greg Clayton471b31c2010-07-20 22:52:08 +0000994 error = DoLaunch (exe_module,
995 exec_path_plus_argv.empty() ? NULL : &exec_path_plus_argv.front(),
996 envp,
997 stdin_path,
998 stdout_path,
999 stderr_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001000
1001 if (error.Fail())
1002 {
1003 if (GetID() != LLDB_INVALID_PROCESS_ID)
1004 {
1005 SetID (LLDB_INVALID_PROCESS_ID);
1006 const char *error_string = error.AsCString();
1007 if (error_string == NULL)
1008 error_string = "launch failed";
1009 SetExitStatus (-1, error_string);
1010 }
1011 }
1012 else
1013 {
1014 EventSP event_sp;
1015 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1016
1017 if (state == eStateStopped || state == eStateCrashed)
1018 {
1019 DidLaunch ();
1020
1021 // This delays passing the stopped event to listeners till DidLaunch gets
1022 // a chance to complete...
1023 HandlePrivateEvent (event_sp);
1024 StartPrivateStateThread ();
1025 }
1026 else if (state == eStateExited)
1027 {
1028 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1029 // not likely to work, and return an invalid pid.
1030 HandlePrivateEvent (event_sp);
1031 }
1032 }
1033 }
1034 }
1035 else
1036 {
1037 error.SetErrorStringWithFormat("File doesn't exist: '%s'.\n", exec_file_path);
1038 }
1039 }
1040 return error;
1041}
1042
1043Error
1044Process::CompleteAttach ()
1045{
1046 Error error;
1047 EventSP event_sp;
1048 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1049 if (state == eStateStopped || state == eStateCrashed)
1050 {
1051 DidAttach ();
Jim Ingham5aee1622010-08-09 23:31:02 +00001052 // Figure out which one is the executable, and set that in our target:
1053 ModuleList &modules = GetTarget().GetImages();
1054
1055 size_t num_modules = modules.GetSize();
1056 for (int i = 0; i < num_modules; i++)
1057 {
1058 ModuleSP module_sp = modules.GetModuleAtIndex(i);
1059 if (module_sp->IsExecutable())
1060 {
1061 ModuleSP exec_module = GetTarget().GetExecutableModule();
1062 if (!exec_module || exec_module != module_sp)
1063 {
1064
1065 GetTarget().SetExecutableModule (module_sp, false);
1066 }
1067 break;
1068 }
1069 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001070
1071 // This delays passing the stopped event to listeners till DidLaunch gets
1072 // a chance to complete...
1073 HandlePrivateEvent(event_sp);
1074 StartPrivateStateThread();
1075 }
1076 else
1077 {
1078 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1079 // not likely to work, and return an invalid pid.
1080 if (state == eStateExited)
1081 HandlePrivateEvent (event_sp);
1082 error.SetErrorStringWithFormat("invalid state after attach: %s",
1083 lldb_private::StateAsCString(state));
1084 }
1085 return error;
1086}
1087
1088Error
1089Process::Attach (lldb::pid_t attach_pid)
1090{
1091
1092 m_target_triple.Clear();
1093 m_abi_sp.reset();
1094
Jim Ingham5aee1622010-08-09 23:31:02 +00001095 // Find the process and its architecture. Make sure it matches the architecture
1096 // of the current Target, and if not adjust it.
1097
1098 ArchSpec attach_spec = GetArchSpecForExistingProcess (attach_pid);
1099 if (attach_spec != GetTarget().GetArchitecture())
1100 {
1101 // Set the architecture on the target.
1102 GetTarget().SetArchitecture(attach_spec);
1103 }
1104
Greg Claytonc982c762010-07-09 20:39:50 +00001105 Error error (WillAttachToProcessWithID(attach_pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001106 if (error.Success())
1107 {
Greg Claytonc982c762010-07-09 20:39:50 +00001108 error = DoAttachToProcessWithID (attach_pid);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001109 if (error.Success())
1110 {
1111 error = CompleteAttach();
1112 }
1113 else
1114 {
1115 if (GetID() != LLDB_INVALID_PROCESS_ID)
1116 {
1117 SetID (LLDB_INVALID_PROCESS_ID);
1118 const char *error_string = error.AsCString();
1119 if (error_string == NULL)
1120 error_string = "attach failed";
1121
1122 SetExitStatus(-1, error_string);
1123 }
1124 }
1125 }
1126 return error;
1127}
1128
1129Error
1130Process::Attach (const char *process_name, bool wait_for_launch)
1131{
1132 m_target_triple.Clear();
1133 m_abi_sp.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00001134
1135 // Find the process and its architecture. Make sure it matches the architecture
1136 // of the current Target, and if not adjust it.
1137
Jim Ingham2ecb7422010-08-17 21:54:19 +00001138 if (!wait_for_launch)
Jim Ingham5aee1622010-08-09 23:31:02 +00001139 {
Jim Ingham2ecb7422010-08-17 21:54:19 +00001140 ArchSpec attach_spec = GetArchSpecForExistingProcess (process_name);
1141 if (attach_spec != GetTarget().GetArchitecture())
1142 {
1143 // Set the architecture on the target.
1144 GetTarget().SetArchitecture(attach_spec);
1145 }
Jim Ingham5aee1622010-08-09 23:31:02 +00001146 }
Jim Ingham2ecb7422010-08-17 21:54:19 +00001147
Greg Claytonc982c762010-07-09 20:39:50 +00001148 Error error (WillAttachToProcessWithName(process_name, wait_for_launch));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001149 if (error.Success())
1150 {
1151 StartPrivateStateThread();
Greg Claytonc982c762010-07-09 20:39:50 +00001152 error = DoAttachToProcessWithName (process_name, wait_for_launch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001153 if (error.Fail())
1154 {
1155 if (GetID() != LLDB_INVALID_PROCESS_ID)
1156 {
1157 SetID (LLDB_INVALID_PROCESS_ID);
1158 const char *error_string = error.AsCString();
1159 if (error_string == NULL)
1160 error_string = "attach failed";
1161
1162 SetExitStatus(-1, error_string);
1163 }
1164 }
1165 else
1166 {
1167 error = CompleteAttach();
1168 }
1169 }
1170 return error;
1171}
1172
1173Error
1174Process::Resume ()
1175{
1176 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
1177 if (log)
1178 log->Printf("Process::Resume() m_stop_id = %u", m_stop_id);
1179
1180 Error error (WillResume());
1181 // Tell the process it is about to resume before the thread list
1182 if (error.Success())
1183 {
1184 // Now let the thread list know we are about to resume to it
1185 // can let all of our threads know that they are about to be
1186 // resumed. Threads will each be called with
1187 // Thread::WillResume(StateType) where StateType contains the state
1188 // that they are supposed to have when the process is resumed
1189 // (suspended/running/stepping). Threads should also check
1190 // their resume signal in lldb::Thread::GetResumeSignal()
1191 // to see if they are suppoed to start back up with a signal.
1192 if (m_thread_list.WillResume())
1193 {
1194 error = DoResume();
1195 if (error.Success())
1196 {
1197 DidResume();
1198 m_thread_list.DidResume();
1199 }
1200 }
1201 else
1202 {
1203 error.SetErrorStringWithFormat("thread list returned flase after WillResume");
1204 }
1205 }
1206 return error;
1207}
1208
1209Error
1210Process::Halt ()
1211{
1212 Error error (WillHalt());
1213
1214 if (error.Success())
1215 {
1216 error = DoHalt();
1217 if (error.Success())
1218 DidHalt();
1219 }
1220 return error;
1221}
1222
1223Error
1224Process::Detach ()
1225{
1226 Error error (WillDetach());
1227
1228 if (error.Success())
1229 {
1230 DisableAllBreakpointSites();
1231 error = DoDetach();
1232 if (error.Success())
1233 {
1234 DidDetach();
1235 StopPrivateStateThread();
1236 }
1237 }
1238 return error;
1239}
1240
1241Error
1242Process::Destroy ()
1243{
1244 Error error (WillDestroy());
1245 if (error.Success())
1246 {
1247 DisableAllBreakpointSites();
1248 error = DoDestroy();
1249 if (error.Success())
1250 {
1251 DidDestroy();
1252 StopPrivateStateThread();
1253 }
1254 }
1255 return error;
1256}
1257
1258Error
1259Process::Signal (int signal)
1260{
1261 Error error (WillSignal());
1262 if (error.Success())
1263 {
1264 error = DoSignal(signal);
1265 if (error.Success())
1266 DidSignal();
1267 }
1268 return error;
1269}
1270
1271UnixSignals &
1272Process::GetUnixSignals ()
1273{
1274 return m_unix_signals;
1275}
1276
1277Target &
1278Process::GetTarget ()
1279{
1280 return m_target;
1281}
1282
1283const Target &
1284Process::GetTarget () const
1285{
1286 return m_target;
1287}
1288
1289uint32_t
1290Process::GetAddressByteSize()
1291{
1292 return m_target.GetArchitecture().GetAddressByteSize();
1293}
1294
1295bool
1296Process::ShouldBroadcastEvent (Event *event_ptr)
1297{
1298 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
1299 bool return_value = true;
1300 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS);
1301
1302 switch (state)
1303 {
1304 case eStateAttaching:
1305 case eStateLaunching:
1306 case eStateDetached:
1307 case eStateExited:
1308 case eStateUnloaded:
1309 // These events indicate changes in the state of the debugging session, always report them.
1310 return_value = true;
1311 break;
1312 case eStateInvalid:
1313 // We stopped for no apparent reason, don't report it.
1314 return_value = false;
1315 break;
1316 case eStateRunning:
1317 case eStateStepping:
1318 // If we've started the target running, we handle the cases where we
1319 // are already running and where there is a transition from stopped to
1320 // running differently.
1321 // running -> running: Automatically suppress extra running events
1322 // stopped -> running: Report except when there is one or more no votes
1323 // and no yes votes.
1324 SynchronouslyNotifyStateChanged (state);
1325 switch (m_public_state.GetValue())
1326 {
1327 case eStateRunning:
1328 case eStateStepping:
1329 // We always suppress multiple runnings with no PUBLIC stop in between.
1330 return_value = false;
1331 break;
1332 default:
1333 // TODO: make this work correctly. For now always report
1334 // run if we aren't running so we don't miss any runnning
1335 // events. If I run the lldb/test/thread/a.out file and
1336 // break at main.cpp:58, run and hit the breakpoints on
1337 // multiple threads, then somehow during the stepping over
1338 // of all breakpoints no run gets reported.
1339 return_value = true;
1340
1341 // This is a transition from stop to run.
1342 switch (m_thread_list.ShouldReportRun (event_ptr))
1343 {
1344 case eVoteYes:
1345 case eVoteNoOpinion:
1346 return_value = true;
1347 break;
1348 case eVoteNo:
1349 return_value = false;
1350 break;
1351 }
1352 break;
1353 }
1354 break;
1355 case eStateStopped:
1356 case eStateCrashed:
1357 case eStateSuspended:
1358 {
1359 // We've stopped. First see if we're going to restart the target.
1360 // If we are going to stop, then we always broadcast the event.
1361 // If we aren't going to stop, let the thread plans decide if we're going to report this event.
Jim Inghamb01e7422010-06-19 04:45:32 +00001362 // If no thread has an opinion, we don't report it.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001363 if (state != eStateInvalid)
1364 {
1365
1366 RefreshStateAfterStop ();
1367
1368 if (m_thread_list.ShouldStop (event_ptr) == false)
1369 {
1370 switch (m_thread_list.ShouldReportStop (event_ptr))
1371 {
1372 case eVoteYes:
1373 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
1374 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001375 case eVoteNo:
1376 return_value = false;
1377 break;
1378 }
1379
1380 if (log)
1381 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process", event_ptr, StateAsCString(state));
1382 Resume ();
1383 }
1384 else
1385 {
1386 return_value = true;
1387 SynchronouslyNotifyStateChanged (state);
1388 }
1389 }
1390 }
1391 }
1392
1393 if (log)
1394 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
1395 return return_value;
1396}
1397
1398//------------------------------------------------------------------
1399// Thread Queries
1400//------------------------------------------------------------------
1401
1402ThreadList &
1403Process::GetThreadList ()
1404{
1405 return m_thread_list;
1406}
1407
1408const ThreadList &
1409Process::GetThreadList () const
1410{
1411 return m_thread_list;
1412}
1413
1414
1415bool
1416Process::StartPrivateStateThread ()
1417{
1418 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS);
1419
1420 if (log)
1421 log->Printf ("Process::%s ( )", __FUNCTION__);
1422
1423 // Create a thread that watches our internal state and controls which
1424 // events make it to clients (into the DCProcess event queue).
1425 m_private_state_thread = Host::ThreadCreate ("<lldb.process.internal-state>", Process::PrivateStateThread, this, NULL);
1426 return m_private_state_thread != LLDB_INVALID_HOST_THREAD;
1427}
1428
1429void
1430Process::PausePrivateStateThread ()
1431{
1432 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
1433}
1434
1435void
1436Process::ResumePrivateStateThread ()
1437{
1438 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
1439}
1440
1441void
1442Process::StopPrivateStateThread ()
1443{
1444 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
1445}
1446
1447void
1448Process::ControlPrivateStateThread (uint32_t signal)
1449{
1450 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS);
1451
1452 assert (signal == eBroadcastInternalStateControlStop ||
1453 signal == eBroadcastInternalStateControlPause ||
1454 signal == eBroadcastInternalStateControlResume);
1455
1456 if (log)
1457 log->Printf ("Process::%s ( ) - signal: %d", __FUNCTION__, signal);
1458
1459 // Signal the private state thread
1460 if (m_private_state_thread != LLDB_INVALID_HOST_THREAD)
1461 {
1462 TimeValue timeout_time;
1463 bool timed_out;
1464
1465 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
1466
1467 timeout_time = TimeValue::Now();
1468 timeout_time.OffsetWithSeconds(2);
1469 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
1470 m_private_state_control_wait.SetValue (false, eBroadcastNever);
1471
1472 if (signal == eBroadcastInternalStateControlStop)
1473 {
1474 if (timed_out)
1475 Host::ThreadCancel (m_private_state_thread, NULL);
1476
1477 thread_result_t result = NULL;
1478 Host::ThreadJoin (m_private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00001479 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001480 }
1481 }
1482}
1483
1484void
1485Process::HandlePrivateEvent (EventSP &event_sp)
1486{
1487 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
1488 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1489 // See if we should broadcast this state to external clients?
1490 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
1491 if (log)
1492 log->Printf ("Process::%s (arg = %p, pid = %i) got event '%s' broadcast = %s", __FUNCTION__, this, GetID(), StateAsCString(internal_state), should_broadcast ? "yes" : "no");
1493
1494 if (should_broadcast)
1495 {
1496 if (log)
1497 {
1498 log->Printf ("\tChanging public state from: %s to %s", StateAsCString(GetState ()), StateAsCString (internal_state));
1499 }
1500 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
1501 BroadcastEvent (event_sp);
1502 }
1503 else
1504 {
1505 if (log)
1506 {
1507 log->Printf ("\tNot changing public state with event: %s", StateAsCString (internal_state));
1508 }
1509 }
1510}
1511
1512void *
1513Process::PrivateStateThread (void *arg)
1514{
1515 Process *proc = static_cast<Process*> (arg);
1516 void *result = proc->RunPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001517 return result;
1518}
1519
1520void *
1521Process::RunPrivateStateThread ()
1522{
1523 bool control_only = false;
1524 m_private_state_control_wait.SetValue (false, eBroadcastNever);
1525
1526 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
1527 if (log)
1528 log->Printf ("Process::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, this, GetID());
1529
1530 bool exit_now = false;
1531 while (!exit_now)
1532 {
1533 EventSP event_sp;
1534 WaitForEventsPrivate (NULL, event_sp, control_only);
1535 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
1536 {
1537 switch (event_sp->GetType())
1538 {
1539 case eBroadcastInternalStateControlStop:
1540 exit_now = true;
1541 continue; // Go to next loop iteration so we exit without
1542 break; // doing any internal state managment below
1543
1544 case eBroadcastInternalStateControlPause:
1545 control_only = true;
1546 break;
1547
1548 case eBroadcastInternalStateControlResume:
1549 control_only = false;
1550 break;
1551 }
1552 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
1553 }
1554
1555
1556 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1557
1558 if (internal_state != eStateInvalid)
1559 {
1560 HandlePrivateEvent (event_sp);
1561 }
1562
1563 if (internal_state == eStateInvalid || internal_state == eStateExited)
1564 break;
1565 }
1566
1567 if (log)
1568 log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID());
1569
Greg Claytonbe77e3b2010-08-19 21:50:06 +00001570 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001571 return NULL;
1572}
1573
1574addr_t
1575Process::GetSectionLoadAddress (const Section *section) const
1576{
1577 // TODO: add support for the same section having multiple load addresses
1578 addr_t section_load_addr = LLDB_INVALID_ADDRESS;
1579 if (m_section_load_info.GetFirstKeyForValue (section, section_load_addr))
1580 return section_load_addr;
1581 return LLDB_INVALID_ADDRESS;
1582}
1583
1584bool
1585Process::SectionLoaded (const Section *section, addr_t load_addr)
1586{
1587 Log *log = lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_SHLIB | LIBLLDB_LOG_VERBOSE);
1588
1589 if (log)
1590 log->Printf ("Process::%s (section = %p (%s.%s), load_addr = 0x%16.16llx)",
1591 __FUNCTION__,
1592 section,
1593 section->GetModule()->GetFileSpec().GetFilename().AsCString(),
1594 section->GetName().AsCString(),
1595 load_addr);
1596
1597
1598 const Section *existing_section = NULL;
1599 Mutex::Locker locker(m_section_load_info.GetMutex());
1600
1601 if (m_section_load_info.GetValueForKeyNoLock (load_addr, existing_section))
1602 {
1603 if (existing_section == section)
1604 return false; // No change
1605 }
1606 m_section_load_info.SetValueForKeyNoLock (load_addr, section);
1607 return true; // Changed
1608}
1609
1610size_t
1611Process::SectionUnloaded (const Section *section)
1612{
1613 Log *log = lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_SHLIB | LIBLLDB_LOG_VERBOSE);
1614
1615 if (log)
1616 log->Printf ("Process::%s (section = %p (%s.%s))",
1617 __FUNCTION__,
1618 section,
1619 section->GetModule()->GetFileSpec().GetFilename().AsCString(),
1620 section->GetName().AsCString());
1621
1622 Mutex::Locker locker(m_section_load_info.GetMutex());
1623
1624 size_t unload_count = 0;
1625 addr_t section_load_addr;
1626 while (m_section_load_info.GetFirstKeyForValueNoLock (section, section_load_addr))
1627 {
1628 unload_count += m_section_load_info.EraseNoLock (section_load_addr);
1629 }
1630 return unload_count;
1631}
1632
1633bool
1634Process::SectionUnloaded (const Section *section, addr_t load_addr)
1635{
1636 Log *log = lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_SHLIB | LIBLLDB_LOG_VERBOSE);
1637
1638 if (log)
1639 log->Printf ("Process::%s (section = %p (%s.%s), load_addr = 0x%16.16llx)",
1640 __FUNCTION__,
1641 section,
1642 section->GetModule()->GetFileSpec().GetFilename().AsCString(),
1643 section->GetName().AsCString(),
1644 load_addr);
1645
1646 return m_section_load_info.Erase (load_addr) == 1;
1647}
1648
1649
1650bool
1651Process::ResolveLoadAddress (addr_t load_addr, Address &so_addr) const
1652{
1653 addr_t section_load_addr = LLDB_INVALID_ADDRESS;
1654 const Section *section = NULL;
1655
1656 // First find the top level section that this load address exists in
1657 if (m_section_load_info.LowerBound (load_addr, section_load_addr, section, true))
1658 {
1659 addr_t offset = load_addr - section_load_addr;
1660 if (offset < section->GetByteSize())
1661 {
1662 // We have found the top level section, now we need to find the
1663 // deepest child section.
1664 return section->ResolveContainedAddress (offset, so_addr);
1665 }
1666 }
1667 so_addr.Clear();
1668 return false;
1669}
1670
1671//------------------------------------------------------------------
1672// Process Event Data
1673//------------------------------------------------------------------
1674
1675Process::ProcessEventData::ProcessEventData () :
1676 EventData (),
1677 m_process_sp (),
1678 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00001679 m_restarted (false),
1680 m_update_state (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001681{
1682}
1683
1684Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
1685 EventData (),
1686 m_process_sp (process_sp),
1687 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00001688 m_restarted (false),
1689 m_update_state (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001690{
1691}
1692
1693Process::ProcessEventData::~ProcessEventData()
1694{
1695}
1696
1697const ConstString &
1698Process::ProcessEventData::GetFlavorString ()
1699{
1700 static ConstString g_flavor ("Process::ProcessEventData");
1701 return g_flavor;
1702}
1703
1704const ConstString &
1705Process::ProcessEventData::GetFlavor () const
1706{
1707 return ProcessEventData::GetFlavorString ();
1708}
1709
1710const ProcessSP &
1711Process::ProcessEventData::GetProcessSP () const
1712{
1713 return m_process_sp;
1714}
1715
1716StateType
1717Process::ProcessEventData::GetState () const
1718{
1719 return m_state;
1720}
1721
1722bool
1723Process::ProcessEventData::GetRestarted () const
1724{
1725 return m_restarted;
1726}
1727
1728void
1729Process::ProcessEventData::SetRestarted (bool new_value)
1730{
1731 m_restarted = new_value;
1732}
1733
1734void
1735Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
1736{
1737 // This function gets called twice for each event, once when the event gets pulled
1738 // off of the private process event queue, and once when it gets pulled off of
1739 // the public event queue. m_update_state is used to distinguish these
1740 // two cases; it is false when we're just pulling it off for private handling,
1741 // and we don't want to do the breakpoint command handling then.
1742
1743 if (!m_update_state)
1744 return;
1745
1746 m_process_sp->SetPublicState (m_state);
1747
1748 // If we're stopped and haven't restarted, then do the breakpoint commands here:
1749 if (m_state == eStateStopped && ! m_restarted)
1750 {
1751 int num_threads = m_process_sp->GetThreadList().GetSize();
1752 int idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00001753
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001754 for (idx = 0; idx < num_threads; ++idx)
1755 {
1756 lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx);
1757
Greg Claytonf4b47e12010-08-04 01:40:35 +00001758 StopInfo *stop_info = thread_sp->GetStopInfo ();
1759 if (stop_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001760 {
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00001761 stop_info->PerformAction(event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001762 }
1763 }
Greg Claytonf4b47e12010-08-04 01:40:35 +00001764
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00001765 // The stop action might restart the target. If it does, then we want to mark that in the
1766 // event so that whoever is receiving it will know to wait for the running event and reflect
1767 // that state appropriately.
1768
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001769 if (m_process_sp->GetPrivateState() == eStateRunning)
1770 SetRestarted(true);
1771 }
1772}
1773
1774void
1775Process::ProcessEventData::Dump (Stream *s) const
1776{
1777 if (m_process_sp)
1778 s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID());
1779
1780 s->Printf("state = %s", StateAsCString(GetState()));;
1781}
1782
1783const Process::ProcessEventData *
1784Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
1785{
1786 if (event_ptr)
1787 {
1788 const EventData *event_data = event_ptr->GetData();
1789 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
1790 return static_cast <const ProcessEventData *> (event_ptr->GetData());
1791 }
1792 return NULL;
1793}
1794
1795ProcessSP
1796Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
1797{
1798 ProcessSP process_sp;
1799 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
1800 if (data)
1801 process_sp = data->GetProcessSP();
1802 return process_sp;
1803}
1804
1805StateType
1806Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
1807{
1808 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
1809 if (data == NULL)
1810 return eStateInvalid;
1811 else
1812 return data->GetState();
1813}
1814
1815bool
1816Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
1817{
1818 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
1819 if (data == NULL)
1820 return false;
1821 else
1822 return data->GetRestarted();
1823}
1824
1825void
1826Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
1827{
1828 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
1829 if (data != NULL)
1830 data->SetRestarted(new_value);
1831}
1832
1833bool
1834Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
1835{
1836 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
1837 if (data)
1838 {
1839 data->SetUpdateStateOnRemoval();
1840 return true;
1841 }
1842 return false;
1843}
1844
1845void
1846Process::ProcessEventData::SetUpdateStateOnRemoval()
1847{
1848 m_update_state = true;
1849}
1850
1851Target *
1852Process::CalculateTarget ()
1853{
1854 return &m_target;
1855}
1856
1857Process *
1858Process::CalculateProcess ()
1859{
1860 return this;
1861}
1862
1863Thread *
1864Process::CalculateThread ()
1865{
1866 return NULL;
1867}
1868
1869StackFrame *
1870Process::CalculateStackFrame ()
1871{
1872 return NULL;
1873}
1874
1875void
1876Process::Calculate (ExecutionContext &exe_ctx)
1877{
1878 exe_ctx.target = &m_target;
1879 exe_ctx.process = this;
1880 exe_ctx.thread = NULL;
1881 exe_ctx.frame = NULL;
1882}
1883
1884lldb::ProcessSP
1885Process::GetSP ()
1886{
1887 return GetTarget().GetProcessSP();
1888}
1889
Sean Callanan2235f322010-08-11 03:57:18 +00001890ClangPersistentVariables &
1891Process::GetPersistentVariables()
1892{
1893 return m_persistent_vars;
1894}
1895
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001896ObjCObjectPrinter &
1897Process::GetObjCObjectPrinter()
1898{
1899 return m_objc_object_printer;
1900}
1901
Jim Ingham5aee1622010-08-09 23:31:02 +00001902uint32_t
1903Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
1904{
1905 return 0;
1906}
1907
1908ArchSpec
1909Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
1910{
1911 return Host::GetArchSpecForExistingProcess (pid);
1912}
1913
1914ArchSpec
1915Process::GetArchSpecForExistingProcess (const char *process_name)
1916{
1917 return Host::GetArchSpecForExistingProcess (process_name);
1918}
1919
1920