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