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