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