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