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