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