blob: 11ba38e6b897ec18edb5643f1cbac4af80d8f890 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/Target/Process.h"
11
12#include "lldb/lldb-private-log.h"
13
14#include "lldb/Breakpoint/StoppointCallbackContext.h"
15#include "lldb/Breakpoint/BreakpointLocation.h"
16#include "lldb/Core/Event.h"
17#include "lldb/Core/Debugger.h"
18#include "lldb/Core/Log.h"
19#include "lldb/Core/PluginManager.h"
20#include "lldb/Core/State.h"
21#include "lldb/Host/Host.h"
22#include "lldb/Target/ABI.h"
23#include "lldb/Target/RegisterContext.h"
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 Claytonc982c762010-07-09 20:39:50 +000048 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +000049 {
Greg Claytonc982c762010-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 Lattner30fdc8d2010-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 Clayton66111032010-06-23 01:19:29 +0000346 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-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
Stephen Wilson50bd94f2010-07-17 00:56:13 +0000525lldb::break_id_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000526Process::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 Claytonc982c762010-07-09 20:39:50 +0000701 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +0000702 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-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 Claytonc982c762010-07-09 20:39:50 +0000731 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +0000732 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-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 Claytonc982c762010-07-09 20:39:50 +0000841 addr_t intersect_addr = 0;
842 size_t intersect_size = 0;
843 size_t opcode_offset = 0;
Chris Lattner30fdc8d2010-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.
Greg Clayton471b31c2010-07-20 22:52:08 +0000992 error = DoLaunch (exe_module,
993 exec_path_plus_argv.empty() ? NULL : &exec_path_plus_argv.front(),
994 envp,
995 stdin_path,
996 stdout_path,
997 stderr_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000998
999 if (error.Fail())
1000 {
1001 if (GetID() != LLDB_INVALID_PROCESS_ID)
1002 {
1003 SetID (LLDB_INVALID_PROCESS_ID);
1004 const char *error_string = error.AsCString();
1005 if (error_string == NULL)
1006 error_string = "launch failed";
1007 SetExitStatus (-1, error_string);
1008 }
1009 }
1010 else
1011 {
1012 EventSP event_sp;
1013 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1014
1015 if (state == eStateStopped || state == eStateCrashed)
1016 {
1017 DidLaunch ();
1018
1019 // This delays passing the stopped event to listeners till DidLaunch gets
1020 // a chance to complete...
1021 HandlePrivateEvent (event_sp);
1022 StartPrivateStateThread ();
1023 }
1024 else if (state == eStateExited)
1025 {
1026 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1027 // not likely to work, and return an invalid pid.
1028 HandlePrivateEvent (event_sp);
1029 }
1030 }
1031 }
1032 }
1033 else
1034 {
1035 error.SetErrorStringWithFormat("File doesn't exist: '%s'.\n", exec_file_path);
1036 }
1037 }
1038 return error;
1039}
1040
1041Error
1042Process::CompleteAttach ()
1043{
1044 Error error;
1045 EventSP event_sp;
1046 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
1047 if (state == eStateStopped || state == eStateCrashed)
1048 {
1049 DidAttach ();
1050
1051 // This delays passing the stopped event to listeners till DidLaunch gets
1052 // a chance to complete...
1053 HandlePrivateEvent(event_sp);
1054 StartPrivateStateThread();
1055 }
1056 else
1057 {
1058 // We exited while trying to launch somehow. Don't call DidLaunch as that's
1059 // not likely to work, and return an invalid pid.
1060 if (state == eStateExited)
1061 HandlePrivateEvent (event_sp);
1062 error.SetErrorStringWithFormat("invalid state after attach: %s",
1063 lldb_private::StateAsCString(state));
1064 }
1065 return error;
1066}
1067
1068Error
1069Process::Attach (lldb::pid_t attach_pid)
1070{
1071
1072 m_target_triple.Clear();
1073 m_abi_sp.reset();
1074
Greg Claytonc982c762010-07-09 20:39:50 +00001075 Error error (WillAttachToProcessWithID(attach_pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001076 if (error.Success())
1077 {
Greg Claytonc982c762010-07-09 20:39:50 +00001078 error = DoAttachToProcessWithID (attach_pid);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001079 if (error.Success())
1080 {
1081 error = CompleteAttach();
1082 }
1083 else
1084 {
1085 if (GetID() != LLDB_INVALID_PROCESS_ID)
1086 {
1087 SetID (LLDB_INVALID_PROCESS_ID);
1088 const char *error_string = error.AsCString();
1089 if (error_string == NULL)
1090 error_string = "attach failed";
1091
1092 SetExitStatus(-1, error_string);
1093 }
1094 }
1095 }
1096 return error;
1097}
1098
1099Error
1100Process::Attach (const char *process_name, bool wait_for_launch)
1101{
1102 m_target_triple.Clear();
1103 m_abi_sp.reset();
1104
Greg Claytonc982c762010-07-09 20:39:50 +00001105 Error error (WillAttachToProcessWithName(process_name, wait_for_launch));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001106 if (error.Success())
1107 {
1108 StartPrivateStateThread();
Greg Claytonc982c762010-07-09 20:39:50 +00001109 error = DoAttachToProcessWithName (process_name, wait_for_launch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001110 if (error.Fail())
1111 {
1112 if (GetID() != LLDB_INVALID_PROCESS_ID)
1113 {
1114 SetID (LLDB_INVALID_PROCESS_ID);
1115 const char *error_string = error.AsCString();
1116 if (error_string == NULL)
1117 error_string = "attach failed";
1118
1119 SetExitStatus(-1, error_string);
1120 }
1121 }
1122 else
1123 {
1124 error = CompleteAttach();
1125 }
1126 }
1127 return error;
1128}
1129
1130Error
1131Process::Resume ()
1132{
1133 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
1134 if (log)
1135 log->Printf("Process::Resume() m_stop_id = %u", m_stop_id);
1136
1137 Error error (WillResume());
1138 // Tell the process it is about to resume before the thread list
1139 if (error.Success())
1140 {
1141 // Now let the thread list know we are about to resume to it
1142 // can let all of our threads know that they are about to be
1143 // resumed. Threads will each be called with
1144 // Thread::WillResume(StateType) where StateType contains the state
1145 // that they are supposed to have when the process is resumed
1146 // (suspended/running/stepping). Threads should also check
1147 // their resume signal in lldb::Thread::GetResumeSignal()
1148 // to see if they are suppoed to start back up with a signal.
1149 if (m_thread_list.WillResume())
1150 {
1151 error = DoResume();
1152 if (error.Success())
1153 {
1154 DidResume();
1155 m_thread_list.DidResume();
1156 }
1157 }
1158 else
1159 {
1160 error.SetErrorStringWithFormat("thread list returned flase after WillResume");
1161 }
1162 }
1163 return error;
1164}
1165
1166Error
1167Process::Halt ()
1168{
1169 Error error (WillHalt());
1170
1171 if (error.Success())
1172 {
1173 error = DoHalt();
1174 if (error.Success())
1175 DidHalt();
1176 }
1177 return error;
1178}
1179
1180Error
1181Process::Detach ()
1182{
1183 Error error (WillDetach());
1184
1185 if (error.Success())
1186 {
1187 DisableAllBreakpointSites();
1188 error = DoDetach();
1189 if (error.Success())
1190 {
1191 DidDetach();
1192 StopPrivateStateThread();
1193 }
1194 }
1195 return error;
1196}
1197
1198Error
1199Process::Destroy ()
1200{
1201 Error error (WillDestroy());
1202 if (error.Success())
1203 {
1204 DisableAllBreakpointSites();
1205 error = DoDestroy();
1206 if (error.Success())
1207 {
1208 DidDestroy();
1209 StopPrivateStateThread();
1210 }
1211 }
1212 return error;
1213}
1214
1215Error
1216Process::Signal (int signal)
1217{
1218 Error error (WillSignal());
1219 if (error.Success())
1220 {
1221 error = DoSignal(signal);
1222 if (error.Success())
1223 DidSignal();
1224 }
1225 return error;
1226}
1227
1228UnixSignals &
1229Process::GetUnixSignals ()
1230{
1231 return m_unix_signals;
1232}
1233
1234Target &
1235Process::GetTarget ()
1236{
1237 return m_target;
1238}
1239
1240const Target &
1241Process::GetTarget () const
1242{
1243 return m_target;
1244}
1245
1246uint32_t
1247Process::GetAddressByteSize()
1248{
1249 return m_target.GetArchitecture().GetAddressByteSize();
1250}
1251
1252bool
1253Process::ShouldBroadcastEvent (Event *event_ptr)
1254{
1255 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
1256 bool return_value = true;
1257 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS);
1258
1259 switch (state)
1260 {
1261 case eStateAttaching:
1262 case eStateLaunching:
1263 case eStateDetached:
1264 case eStateExited:
1265 case eStateUnloaded:
1266 // These events indicate changes in the state of the debugging session, always report them.
1267 return_value = true;
1268 break;
1269 case eStateInvalid:
1270 // We stopped for no apparent reason, don't report it.
1271 return_value = false;
1272 break;
1273 case eStateRunning:
1274 case eStateStepping:
1275 // If we've started the target running, we handle the cases where we
1276 // are already running and where there is a transition from stopped to
1277 // running differently.
1278 // running -> running: Automatically suppress extra running events
1279 // stopped -> running: Report except when there is one or more no votes
1280 // and no yes votes.
1281 SynchronouslyNotifyStateChanged (state);
1282 switch (m_public_state.GetValue())
1283 {
1284 case eStateRunning:
1285 case eStateStepping:
1286 // We always suppress multiple runnings with no PUBLIC stop in between.
1287 return_value = false;
1288 break;
1289 default:
1290 // TODO: make this work correctly. For now always report
1291 // run if we aren't running so we don't miss any runnning
1292 // events. If I run the lldb/test/thread/a.out file and
1293 // break at main.cpp:58, run and hit the breakpoints on
1294 // multiple threads, then somehow during the stepping over
1295 // of all breakpoints no run gets reported.
1296 return_value = true;
1297
1298 // This is a transition from stop to run.
1299 switch (m_thread_list.ShouldReportRun (event_ptr))
1300 {
1301 case eVoteYes:
1302 case eVoteNoOpinion:
1303 return_value = true;
1304 break;
1305 case eVoteNo:
1306 return_value = false;
1307 break;
1308 }
1309 break;
1310 }
1311 break;
1312 case eStateStopped:
1313 case eStateCrashed:
1314 case eStateSuspended:
1315 {
1316 // We've stopped. First see if we're going to restart the target.
1317 // If we are going to stop, then we always broadcast the event.
1318 // If we aren't going to stop, let the thread plans decide if we're going to report this event.
Jim Inghamb01e7422010-06-19 04:45:32 +00001319 // If no thread has an opinion, we don't report it.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001320 if (state != eStateInvalid)
1321 {
1322
1323 RefreshStateAfterStop ();
1324
1325 if (m_thread_list.ShouldStop (event_ptr) == false)
1326 {
1327 switch (m_thread_list.ShouldReportStop (event_ptr))
1328 {
1329 case eVoteYes:
1330 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
1331 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001332 case eVoteNo:
1333 return_value = false;
1334 break;
1335 }
1336
1337 if (log)
1338 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process", event_ptr, StateAsCString(state));
1339 Resume ();
1340 }
1341 else
1342 {
1343 return_value = true;
1344 SynchronouslyNotifyStateChanged (state);
1345 }
1346 }
1347 }
1348 }
1349
1350 if (log)
1351 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
1352 return return_value;
1353}
1354
1355//------------------------------------------------------------------
1356// Thread Queries
1357//------------------------------------------------------------------
1358
1359ThreadList &
1360Process::GetThreadList ()
1361{
1362 return m_thread_list;
1363}
1364
1365const ThreadList &
1366Process::GetThreadList () const
1367{
1368 return m_thread_list;
1369}
1370
1371
1372bool
1373Process::StartPrivateStateThread ()
1374{
1375 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS);
1376
1377 if (log)
1378 log->Printf ("Process::%s ( )", __FUNCTION__);
1379
1380 // Create a thread that watches our internal state and controls which
1381 // events make it to clients (into the DCProcess event queue).
1382 m_private_state_thread = Host::ThreadCreate ("<lldb.process.internal-state>", Process::PrivateStateThread, this, NULL);
1383 return m_private_state_thread != LLDB_INVALID_HOST_THREAD;
1384}
1385
1386void
1387Process::PausePrivateStateThread ()
1388{
1389 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
1390}
1391
1392void
1393Process::ResumePrivateStateThread ()
1394{
1395 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
1396}
1397
1398void
1399Process::StopPrivateStateThread ()
1400{
1401 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
1402}
1403
1404void
1405Process::ControlPrivateStateThread (uint32_t signal)
1406{
1407 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS);
1408
1409 assert (signal == eBroadcastInternalStateControlStop ||
1410 signal == eBroadcastInternalStateControlPause ||
1411 signal == eBroadcastInternalStateControlResume);
1412
1413 if (log)
1414 log->Printf ("Process::%s ( ) - signal: %d", __FUNCTION__, signal);
1415
1416 // Signal the private state thread
1417 if (m_private_state_thread != LLDB_INVALID_HOST_THREAD)
1418 {
1419 TimeValue timeout_time;
1420 bool timed_out;
1421
1422 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
1423
1424 timeout_time = TimeValue::Now();
1425 timeout_time.OffsetWithSeconds(2);
1426 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
1427 m_private_state_control_wait.SetValue (false, eBroadcastNever);
1428
1429 if (signal == eBroadcastInternalStateControlStop)
1430 {
1431 if (timed_out)
1432 Host::ThreadCancel (m_private_state_thread, NULL);
1433
1434 thread_result_t result = NULL;
1435 Host::ThreadJoin (m_private_state_thread, &result, NULL);
1436 }
1437 }
1438}
1439
1440void
1441Process::HandlePrivateEvent (EventSP &event_sp)
1442{
1443 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
1444 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1445 // See if we should broadcast this state to external clients?
1446 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
1447 if (log)
1448 log->Printf ("Process::%s (arg = %p, pid = %i) got event '%s' broadcast = %s", __FUNCTION__, this, GetID(), StateAsCString(internal_state), should_broadcast ? "yes" : "no");
1449
1450 if (should_broadcast)
1451 {
1452 if (log)
1453 {
1454 log->Printf ("\tChanging public state from: %s to %s", StateAsCString(GetState ()), StateAsCString (internal_state));
1455 }
1456 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
1457 BroadcastEvent (event_sp);
1458 }
1459 else
1460 {
1461 if (log)
1462 {
1463 log->Printf ("\tNot changing public state with event: %s", StateAsCString (internal_state));
1464 }
1465 }
1466}
1467
1468void *
1469Process::PrivateStateThread (void *arg)
1470{
1471 Process *proc = static_cast<Process*> (arg);
1472 void *result = proc->RunPrivateStateThread ();
1473 proc->m_private_state_thread = LLDB_INVALID_HOST_THREAD;
1474 return result;
1475}
1476
1477void *
1478Process::RunPrivateStateThread ()
1479{
1480 bool control_only = false;
1481 m_private_state_control_wait.SetValue (false, eBroadcastNever);
1482
1483 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
1484 if (log)
1485 log->Printf ("Process::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, this, GetID());
1486
1487 bool exit_now = false;
1488 while (!exit_now)
1489 {
1490 EventSP event_sp;
1491 WaitForEventsPrivate (NULL, event_sp, control_only);
1492 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
1493 {
1494 switch (event_sp->GetType())
1495 {
1496 case eBroadcastInternalStateControlStop:
1497 exit_now = true;
1498 continue; // Go to next loop iteration so we exit without
1499 break; // doing any internal state managment below
1500
1501 case eBroadcastInternalStateControlPause:
1502 control_only = true;
1503 break;
1504
1505 case eBroadcastInternalStateControlResume:
1506 control_only = false;
1507 break;
1508 }
1509 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
1510 }
1511
1512
1513 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1514
1515 if (internal_state != eStateInvalid)
1516 {
1517 HandlePrivateEvent (event_sp);
1518 }
1519
1520 if (internal_state == eStateInvalid || internal_state == eStateExited)
1521 break;
1522 }
1523
1524 if (log)
1525 log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID());
1526
1527 return NULL;
1528}
1529
1530addr_t
1531Process::GetSectionLoadAddress (const Section *section) const
1532{
1533 // TODO: add support for the same section having multiple load addresses
1534 addr_t section_load_addr = LLDB_INVALID_ADDRESS;
1535 if (m_section_load_info.GetFirstKeyForValue (section, section_load_addr))
1536 return section_load_addr;
1537 return LLDB_INVALID_ADDRESS;
1538}
1539
1540bool
1541Process::SectionLoaded (const Section *section, addr_t load_addr)
1542{
1543 Log *log = lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_SHLIB | LIBLLDB_LOG_VERBOSE);
1544
1545 if (log)
1546 log->Printf ("Process::%s (section = %p (%s.%s), load_addr = 0x%16.16llx)",
1547 __FUNCTION__,
1548 section,
1549 section->GetModule()->GetFileSpec().GetFilename().AsCString(),
1550 section->GetName().AsCString(),
1551 load_addr);
1552
1553
1554 const Section *existing_section = NULL;
1555 Mutex::Locker locker(m_section_load_info.GetMutex());
1556
1557 if (m_section_load_info.GetValueForKeyNoLock (load_addr, existing_section))
1558 {
1559 if (existing_section == section)
1560 return false; // No change
1561 }
1562 m_section_load_info.SetValueForKeyNoLock (load_addr, section);
1563 return true; // Changed
1564}
1565
1566size_t
1567Process::SectionUnloaded (const Section *section)
1568{
1569 Log *log = lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_SHLIB | LIBLLDB_LOG_VERBOSE);
1570
1571 if (log)
1572 log->Printf ("Process::%s (section = %p (%s.%s))",
1573 __FUNCTION__,
1574 section,
1575 section->GetModule()->GetFileSpec().GetFilename().AsCString(),
1576 section->GetName().AsCString());
1577
1578 Mutex::Locker locker(m_section_load_info.GetMutex());
1579
1580 size_t unload_count = 0;
1581 addr_t section_load_addr;
1582 while (m_section_load_info.GetFirstKeyForValueNoLock (section, section_load_addr))
1583 {
1584 unload_count += m_section_load_info.EraseNoLock (section_load_addr);
1585 }
1586 return unload_count;
1587}
1588
1589bool
1590Process::SectionUnloaded (const Section *section, addr_t load_addr)
1591{
1592 Log *log = lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_SHLIB | LIBLLDB_LOG_VERBOSE);
1593
1594 if (log)
1595 log->Printf ("Process::%s (section = %p (%s.%s), load_addr = 0x%16.16llx)",
1596 __FUNCTION__,
1597 section,
1598 section->GetModule()->GetFileSpec().GetFilename().AsCString(),
1599 section->GetName().AsCString(),
1600 load_addr);
1601
1602 return m_section_load_info.Erase (load_addr) == 1;
1603}
1604
1605
1606bool
1607Process::ResolveLoadAddress (addr_t load_addr, Address &so_addr) const
1608{
1609 addr_t section_load_addr = LLDB_INVALID_ADDRESS;
1610 const Section *section = NULL;
1611
1612 // First find the top level section that this load address exists in
1613 if (m_section_load_info.LowerBound (load_addr, section_load_addr, section, true))
1614 {
1615 addr_t offset = load_addr - section_load_addr;
1616 if (offset < section->GetByteSize())
1617 {
1618 // We have found the top level section, now we need to find the
1619 // deepest child section.
1620 return section->ResolveContainedAddress (offset, so_addr);
1621 }
1622 }
1623 so_addr.Clear();
1624 return false;
1625}
1626
1627//------------------------------------------------------------------
1628// Process Event Data
1629//------------------------------------------------------------------
1630
1631Process::ProcessEventData::ProcessEventData () :
1632 EventData (),
1633 m_process_sp (),
1634 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00001635 m_restarted (false),
1636 m_update_state (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001637{
1638}
1639
1640Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
1641 EventData (),
1642 m_process_sp (process_sp),
1643 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00001644 m_restarted (false),
1645 m_update_state (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001646{
1647}
1648
1649Process::ProcessEventData::~ProcessEventData()
1650{
1651}
1652
1653const ConstString &
1654Process::ProcessEventData::GetFlavorString ()
1655{
1656 static ConstString g_flavor ("Process::ProcessEventData");
1657 return g_flavor;
1658}
1659
1660const ConstString &
1661Process::ProcessEventData::GetFlavor () const
1662{
1663 return ProcessEventData::GetFlavorString ();
1664}
1665
1666const ProcessSP &
1667Process::ProcessEventData::GetProcessSP () const
1668{
1669 return m_process_sp;
1670}
1671
1672StateType
1673Process::ProcessEventData::GetState () const
1674{
1675 return m_state;
1676}
1677
1678bool
1679Process::ProcessEventData::GetRestarted () const
1680{
1681 return m_restarted;
1682}
1683
1684void
1685Process::ProcessEventData::SetRestarted (bool new_value)
1686{
1687 m_restarted = new_value;
1688}
1689
1690void
1691Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
1692{
1693 // This function gets called twice for each event, once when the event gets pulled
1694 // off of the private process event queue, and once when it gets pulled off of
1695 // the public event queue. m_update_state is used to distinguish these
1696 // two cases; it is false when we're just pulling it off for private handling,
1697 // and we don't want to do the breakpoint command handling then.
1698
1699 if (!m_update_state)
1700 return;
1701
1702 m_process_sp->SetPublicState (m_state);
1703
1704 // If we're stopped and haven't restarted, then do the breakpoint commands here:
1705 if (m_state == eStateStopped && ! m_restarted)
1706 {
1707 int num_threads = m_process_sp->GetThreadList().GetSize();
1708 int idx;
1709
1710 for (idx = 0; idx < num_threads; ++idx)
1711 {
1712 lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx);
1713
1714 Thread::StopInfo stop_info;
1715 if (thread_sp->GetStopInfo(&stop_info))
1716 {
1717 StopReason reason = stop_info.GetStopReason();
1718 if (reason == eStopReasonBreakpoint)
1719 {
1720 BreakpointSiteSP bp_site_sp;
1721 // Look up the breakpoint site in the stop info, but the breakpoint
1722 // might be a temporary one that's been deleted between the time we
1723 // hit the breakpoint and now, if so there's nothing to do.
1724
1725 bp_site_sp = m_process_sp->GetBreakpointSiteList().FindByID (stop_info.GetBreakpointSiteID());
1726 if (bp_site_sp)
1727 {
1728 size_t num_owners = bp_site_sp->GetNumberOfOwners();
1729 for (size_t j = 0; j < num_owners; j++)
1730 {
1731 lldb::BreakpointLocationSP bp_loc_sp = bp_site_sp->GetOwnerAtIndex(j);
1732 StoppointCallbackContext context (event_ptr,
1733 m_process_sp.get(),
1734 thread_sp.get(),
1735 thread_sp->GetStackFrameAtIndex(0).get(),
1736 false);
1737 bp_loc_sp->InvokeCallback (&context);
1738 }
1739 }
1740 else
1741 {
1742 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
1743
1744 if (log)
1745 log->Printf ("Process::%s could not find breakpoint site id: %d...", __FUNCTION__, stop_info.GetBreakpointSiteID());
1746 }
1747
1748 }
1749 }
1750 }
1751 if (m_process_sp->GetPrivateState() == eStateRunning)
1752 SetRestarted(true);
1753 }
1754}
1755
1756void
1757Process::ProcessEventData::Dump (Stream *s) const
1758{
1759 if (m_process_sp)
1760 s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID());
1761
1762 s->Printf("state = %s", StateAsCString(GetState()));;
1763}
1764
1765const Process::ProcessEventData *
1766Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
1767{
1768 if (event_ptr)
1769 {
1770 const EventData *event_data = event_ptr->GetData();
1771 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
1772 return static_cast <const ProcessEventData *> (event_ptr->GetData());
1773 }
1774 return NULL;
1775}
1776
1777ProcessSP
1778Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
1779{
1780 ProcessSP process_sp;
1781 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
1782 if (data)
1783 process_sp = data->GetProcessSP();
1784 return process_sp;
1785}
1786
1787StateType
1788Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
1789{
1790 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
1791 if (data == NULL)
1792 return eStateInvalid;
1793 else
1794 return data->GetState();
1795}
1796
1797bool
1798Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
1799{
1800 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
1801 if (data == NULL)
1802 return false;
1803 else
1804 return data->GetRestarted();
1805}
1806
1807void
1808Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
1809{
1810 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
1811 if (data != NULL)
1812 data->SetRestarted(new_value);
1813}
1814
1815bool
1816Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
1817{
1818 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
1819 if (data)
1820 {
1821 data->SetUpdateStateOnRemoval();
1822 return true;
1823 }
1824 return false;
1825}
1826
1827void
1828Process::ProcessEventData::SetUpdateStateOnRemoval()
1829{
1830 m_update_state = true;
1831}
1832
1833Target *
1834Process::CalculateTarget ()
1835{
1836 return &m_target;
1837}
1838
1839Process *
1840Process::CalculateProcess ()
1841{
1842 return this;
1843}
1844
1845Thread *
1846Process::CalculateThread ()
1847{
1848 return NULL;
1849}
1850
1851StackFrame *
1852Process::CalculateStackFrame ()
1853{
1854 return NULL;
1855}
1856
1857void
1858Process::Calculate (ExecutionContext &exe_ctx)
1859{
1860 exe_ctx.target = &m_target;
1861 exe_ctx.process = this;
1862 exe_ctx.thread = NULL;
1863 exe_ctx.frame = NULL;
1864}
1865
1866lldb::ProcessSP
1867Process::GetSP ()
1868{
1869 return GetTarget().GetProcessSP();
1870}
1871
1872ObjCObjectPrinter &
1873Process::GetObjCObjectPrinter()
1874{
1875 return m_objc_object_printer;
1876}
1877