1af245d11STodd Fiala //===-- NativeProcessProtocol.cpp -------------------------------*- C++ -*-===//
2af245d11STodd Fiala //
3af245d11STodd Fiala //                     The LLVM Compiler Infrastructure
4af245d11STodd Fiala //
5af245d11STodd Fiala // This file is distributed under the University of Illinois Open Source
6af245d11STodd Fiala // License. See LICENSE.TXT for details.
7af245d11STodd Fiala //
8af245d11STodd Fiala //===----------------------------------------------------------------------===//
9af245d11STodd Fiala 
102fe1d0abSChaoren Lin #include "lldb/Host/common/NativeProcessProtocol.h"
11511e5cdcSTodd Fiala #include "lldb/Host/Host.h"
12be828518SPavel Labath #include "lldb/Host/common/NativeBreakpointList.h"
132fe1d0abSChaoren Lin #include "lldb/Host/common/NativeRegisterContext.h"
142fe1d0abSChaoren Lin #include "lldb/Host/common/NativeThreadProtocol.h"
15e77fce0aSTodd Fiala #include "lldb/Utility/LLDBAssert.h"
166f9e6901SZachary Turner #include "lldb/Utility/Log.h"
17d821c997SPavel Labath #include "lldb/Utility/State.h"
18b9c1b51eSKate Stone #include "lldb/lldb-enumerations.h"
19af245d11STodd Fiala 
20af245d11STodd Fiala using namespace lldb;
21af245d11STodd Fiala using namespace lldb_private;
22af245d11STodd Fiala 
23af245d11STodd Fiala // -----------------------------------------------------------------------------
24af245d11STodd Fiala // NativeProcessProtocol Members
25af245d11STodd Fiala // -----------------------------------------------------------------------------
26af245d11STodd Fiala 
2796e600fcSPavel Labath NativeProcessProtocol::NativeProcessProtocol(lldb::pid_t pid, int terminal_fd,
2896e600fcSPavel Labath                                              NativeDelegate &delegate)
2996e600fcSPavel Labath     : m_pid(pid), m_terminal_fd(terminal_fd) {
3096e600fcSPavel Labath   bool registered = RegisterNativeDelegate(delegate);
3196e600fcSPavel Labath   assert(registered);
3296e600fcSPavel Labath   (void)registered;
3396e600fcSPavel Labath }
34af245d11STodd Fiala 
3597206d57SZachary Turner lldb_private::Status NativeProcessProtocol::Interrupt() {
3697206d57SZachary Turner   Status error;
37511e5cdcSTodd Fiala #if !defined(SIGSTOP)
38511e5cdcSTodd Fiala   error.SetErrorString("local host does not support signaling");
39511e5cdcSTodd Fiala   return error;
40511e5cdcSTodd Fiala #else
41511e5cdcSTodd Fiala   return Signal(SIGSTOP);
42511e5cdcSTodd Fiala #endif
43511e5cdcSTodd Fiala }
44511e5cdcSTodd Fiala 
4597206d57SZachary Turner Status NativeProcessProtocol::IgnoreSignals(llvm::ArrayRef<int> signals) {
464a705e7eSPavel Labath   m_signals_to_ignore.clear();
474a705e7eSPavel Labath   m_signals_to_ignore.insert(signals.begin(), signals.end());
4897206d57SZachary Turner   return Status();
494a705e7eSPavel Labath }
504a705e7eSPavel Labath 
5197206d57SZachary Turner lldb_private::Status
52b9c1b51eSKate Stone NativeProcessProtocol::GetMemoryRegionInfo(lldb::addr_t load_addr,
53b9c1b51eSKate Stone                                            MemoryRegionInfo &range_info) {
54af245d11STodd Fiala   // Default: not implemented.
5597206d57SZachary Turner   return Status("not implemented");
56af245d11STodd Fiala }
57af245d11STodd Fiala 
583508fc8cSPavel Labath llvm::Optional<WaitStatus> NativeProcessProtocol::GetExitStatus() {
593508fc8cSPavel Labath   if (m_state == lldb::eStateExited)
603508fc8cSPavel Labath     return m_exit_status;
613508fc8cSPavel Labath 
623508fc8cSPavel Labath   return llvm::None;
63af245d11STodd Fiala }
64af245d11STodd Fiala 
653508fc8cSPavel Labath bool NativeProcessProtocol::SetExitStatus(WaitStatus status,
66b9c1b51eSKate Stone                                           bool bNotifyStateChange) {
67af245d11STodd Fiala   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
683508fc8cSPavel Labath   LLDB_LOG(log, "status = {0}, notify = {1}", status, bNotifyStateChange);
69af245d11STodd Fiala 
70af245d11STodd Fiala   // Exit status already set
71b9c1b51eSKate Stone   if (m_state == lldb::eStateExited) {
723508fc8cSPavel Labath     if (m_exit_status)
733508fc8cSPavel Labath       LLDB_LOG(log, "exit status already set to {0}", *m_exit_status);
743508fc8cSPavel Labath     else
753508fc8cSPavel Labath       LLDB_LOG(log, "state is exited, but status not set");
76af245d11STodd Fiala     return false;
77af245d11STodd Fiala   }
78af245d11STodd Fiala 
79af245d11STodd Fiala   m_state = lldb::eStateExited;
80af245d11STodd Fiala   m_exit_status = status;
81af245d11STodd Fiala 
82af245d11STodd Fiala   if (bNotifyStateChange)
83af245d11STodd Fiala     SynchronouslyNotifyProcessStateChanged(lldb::eStateExited);
84af245d11STodd Fiala 
85af245d11STodd Fiala   return true;
86af245d11STodd Fiala }
87af245d11STodd Fiala 
88a5be48b3SPavel Labath NativeThreadProtocol *NativeProcessProtocol::GetThreadAtIndex(uint32_t idx) {
8916ff8604SSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
90af245d11STodd Fiala   if (idx < m_threads.size())
91a5be48b3SPavel Labath     return m_threads[idx].get();
92a5be48b3SPavel Labath   return nullptr;
93af245d11STodd Fiala }
94af245d11STodd Fiala 
95a5be48b3SPavel Labath NativeThreadProtocol *
96b9c1b51eSKate Stone NativeProcessProtocol::GetThreadByIDUnlocked(lldb::tid_t tid) {
97a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
98a5be48b3SPavel Labath     if (thread->GetID() == tid)
99a5be48b3SPavel Labath       return thread.get();
100af245d11STodd Fiala   }
101a5be48b3SPavel Labath   return nullptr;
102af245d11STodd Fiala }
103af245d11STodd Fiala 
104a5be48b3SPavel Labath NativeThreadProtocol *NativeProcessProtocol::GetThreadByID(lldb::tid_t tid) {
10516ff8604SSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
106511e5cdcSTodd Fiala   return GetThreadByIDUnlocked(tid);
107511e5cdcSTodd Fiala }
108511e5cdcSTodd Fiala 
109b9c1b51eSKate Stone bool NativeProcessProtocol::IsAlive() const {
110b9c1b51eSKate Stone   return m_state != eStateDetached && m_state != eStateExited &&
111b9c1b51eSKate Stone          m_state != eStateInvalid && m_state != eStateUnloaded;
112af245d11STodd Fiala }
113af245d11STodd Fiala 
11418fe6404SChaoren Lin const NativeWatchpointList::WatchpointMap &
115b9c1b51eSKate Stone NativeProcessProtocol::GetWatchpointMap() const {
11618fe6404SChaoren Lin   return m_watchpoint_list.GetWatchpointMap();
11718fe6404SChaoren Lin }
11818fe6404SChaoren Lin 
119d5ffbad2SOmair Javaid llvm::Optional<std::pair<uint32_t, uint32_t>>
120d5ffbad2SOmair Javaid NativeProcessProtocol::GetHardwareDebugSupportInfo() const {
121af245d11STodd Fiala   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
122af245d11STodd Fiala 
123af245d11STodd Fiala   // get any thread
124a5be48b3SPavel Labath   NativeThreadProtocol *thread(
125b9c1b51eSKate Stone       const_cast<NativeProcessProtocol *>(this)->GetThreadAtIndex(0));
126a5be48b3SPavel Labath   if (!thread) {
127a5be48b3SPavel Labath     LLDB_LOG(log, "failed to find a thread to grab a NativeRegisterContext!");
128d5ffbad2SOmair Javaid     return llvm::None;
129af245d11STodd Fiala   }
130af245d11STodd Fiala 
131d37349f3SPavel Labath   NativeRegisterContext &reg_ctx = thread->GetRegisterContext();
132d37349f3SPavel Labath   return std::make_pair(reg_ctx.NumSupportedHardwareBreakpoints(),
133d37349f3SPavel Labath                         reg_ctx.NumSupportedHardwareWatchpoints());
134af245d11STodd Fiala }
135af245d11STodd Fiala 
13697206d57SZachary Turner Status NativeProcessProtocol::SetWatchpoint(lldb::addr_t addr, size_t size,
137b9c1b51eSKate Stone                                             uint32_t watch_flags,
138b9c1b51eSKate Stone                                             bool hardware) {
13905097246SAdrian Prantl   // This default implementation assumes setting the watchpoint for the process
14005097246SAdrian Prantl   // will require setting the watchpoint for each of the threads.  Furthermore,
14105097246SAdrian Prantl   // it will track watchpoints set for the process and will add them to each
14205097246SAdrian Prantl   // thread that is attached to via the (FIXME implement) OnThreadAttached ()
14305097246SAdrian Prantl   // method.
144af245d11STodd Fiala 
145af245d11STodd Fiala   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
146af245d11STodd Fiala 
147af245d11STodd Fiala   // Update the thread list
148af245d11STodd Fiala   UpdateThreads();
149af245d11STodd Fiala 
15005097246SAdrian Prantl   // Keep track of the threads we successfully set the watchpoint for.  If one
15105097246SAdrian Prantl   // of the thread watchpoint setting operations fails, back off and remove the
15205097246SAdrian Prantl   // watchpoint for all the threads that were successfully set so we get back
15305097246SAdrian Prantl   // to a consistent state.
154a5be48b3SPavel Labath   std::vector<NativeThreadProtocol *> watchpoint_established_threads;
155af245d11STodd Fiala 
15605097246SAdrian Prantl   // Tell each thread to set a watchpoint.  In the event that hardware
15705097246SAdrian Prantl   // watchpoints are requested but the SetWatchpoint fails, try to set a
15805097246SAdrian Prantl   // software watchpoint as a fallback.  It's conceivable that if there are
15905097246SAdrian Prantl   // more threads than hardware watchpoints available, some of the threads will
16005097246SAdrian Prantl   // fail to set hardware watchpoints while software ones may be available.
16116ff8604SSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
162a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
163a5be48b3SPavel Labath     assert(thread && "thread list should not have a NULL thread!");
164af245d11STodd Fiala 
16597206d57SZachary Turner     Status thread_error =
166a5be48b3SPavel Labath         thread->SetWatchpoint(addr, size, watch_flags, hardware);
167b9c1b51eSKate Stone     if (thread_error.Fail() && hardware) {
16805097246SAdrian Prantl       // Try software watchpoints since we failed on hardware watchpoint
16905097246SAdrian Prantl       // setting and we may have just run out of hardware watchpoints.
170a5be48b3SPavel Labath       thread_error = thread->SetWatchpoint(addr, size, watch_flags, false);
171a5be48b3SPavel Labath       if (thread_error.Success())
172a5be48b3SPavel Labath         LLDB_LOG(log,
173b9c1b51eSKate Stone                  "hardware watchpoint requested but software watchpoint set");
174af245d11STodd Fiala     }
175af245d11STodd Fiala 
176b9c1b51eSKate Stone     if (thread_error.Success()) {
17705097246SAdrian Prantl       // Remember that we set this watchpoint successfully in case we need to
17805097246SAdrian Prantl       // clear it later.
179a5be48b3SPavel Labath       watchpoint_established_threads.push_back(thread.get());
180b9c1b51eSKate Stone     } else {
18105097246SAdrian Prantl       // Unset the watchpoint for each thread we successfully set so that we
18205097246SAdrian Prantl       // get back to a consistent state of "not set" for the watchpoint.
183b9c1b51eSKate Stone       for (auto unwatch_thread_sp : watchpoint_established_threads) {
18497206d57SZachary Turner         Status remove_error = unwatch_thread_sp->RemoveWatchpoint(addr);
185a5be48b3SPavel Labath         if (remove_error.Fail())
186a5be48b3SPavel Labath           LLDB_LOG(log, "RemoveWatchpoint failed for pid={0}, tid={1}: {2}",
187a5be48b3SPavel Labath                    GetID(), unwatch_thread_sp->GetID(), remove_error);
188af245d11STodd Fiala       }
189af245d11STodd Fiala 
190af245d11STodd Fiala       return thread_error;
191af245d11STodd Fiala     }
192af245d11STodd Fiala   }
19318fe6404SChaoren Lin   return m_watchpoint_list.Add(addr, size, watch_flags, hardware);
194af245d11STodd Fiala }
195af245d11STodd Fiala 
19697206d57SZachary Turner Status NativeProcessProtocol::RemoveWatchpoint(lldb::addr_t addr) {
197af245d11STodd Fiala   // Update the thread list
198af245d11STodd Fiala   UpdateThreads();
199af245d11STodd Fiala 
20097206d57SZachary Turner   Status overall_error;
201af245d11STodd Fiala 
20216ff8604SSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
203a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
204a5be48b3SPavel Labath     assert(thread && "thread list should not have a NULL thread!");
205af245d11STodd Fiala 
206a5be48b3SPavel Labath     const Status thread_error = thread->RemoveWatchpoint(addr);
207b9c1b51eSKate Stone     if (thread_error.Fail()) {
20805097246SAdrian Prantl       // Keep track of the first thread error if any threads fail. We want to
20905097246SAdrian Prantl       // try to remove the watchpoint from every thread, though, even if one or
21005097246SAdrian Prantl       // more have errors.
211af245d11STodd Fiala       if (!overall_error.Fail())
212af245d11STodd Fiala         overall_error = thread_error;
213af245d11STodd Fiala     }
214af245d11STodd Fiala   }
21597206d57SZachary Turner   const Status error = m_watchpoint_list.Remove(addr);
21618fe6404SChaoren Lin   return overall_error.Fail() ? overall_error : error;
217af245d11STodd Fiala }
218af245d11STodd Fiala 
219d5ffbad2SOmair Javaid const HardwareBreakpointMap &
220d5ffbad2SOmair Javaid NativeProcessProtocol::GetHardwareBreakpointMap() const {
221d5ffbad2SOmair Javaid   return m_hw_breakpoints_map;
222d5ffbad2SOmair Javaid }
223d5ffbad2SOmair Javaid 
22497206d57SZachary Turner Status NativeProcessProtocol::SetHardwareBreakpoint(lldb::addr_t addr,
225d5ffbad2SOmair Javaid                                                     size_t size) {
22605097246SAdrian Prantl   // This default implementation assumes setting a hardware breakpoint for this
22705097246SAdrian Prantl   // process will require setting same hardware breakpoint for each of its
22805097246SAdrian Prantl   // existing threads. New thread will do the same once created.
229d5ffbad2SOmair Javaid   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
230d5ffbad2SOmair Javaid 
231d5ffbad2SOmair Javaid   // Update the thread list
232d5ffbad2SOmair Javaid   UpdateThreads();
233d5ffbad2SOmair Javaid 
234d5ffbad2SOmair Javaid   // Exit here if target does not have required hardware breakpoint capability.
235d5ffbad2SOmair Javaid   auto hw_debug_cap = GetHardwareDebugSupportInfo();
236d5ffbad2SOmair Javaid 
237d5ffbad2SOmair Javaid   if (hw_debug_cap == llvm::None || hw_debug_cap->first == 0 ||
238d5ffbad2SOmair Javaid       hw_debug_cap->first <= m_hw_breakpoints_map.size())
23997206d57SZachary Turner     return Status("Target does not have required no of hardware breakpoints");
240d5ffbad2SOmair Javaid 
241d5ffbad2SOmair Javaid   // Vector below stores all thread pointer for which we have we successfully
242d5ffbad2SOmair Javaid   // set this hardware breakpoint. If any of the current process threads fails
243d5ffbad2SOmair Javaid   // to set this hardware breakpoint then roll back and remove this breakpoint
244d5ffbad2SOmair Javaid   // for all the threads that had already set it successfully.
245a5be48b3SPavel Labath   std::vector<NativeThreadProtocol *> breakpoint_established_threads;
246d5ffbad2SOmair Javaid 
247d5ffbad2SOmair Javaid   // Request to set a hardware breakpoint for each of current process threads.
248d5ffbad2SOmair Javaid   std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
249a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
250a5be48b3SPavel Labath     assert(thread && "thread list should not have a NULL thread!");
251d5ffbad2SOmair Javaid 
252a5be48b3SPavel Labath     Status thread_error = thread->SetHardwareBreakpoint(addr, size);
253d5ffbad2SOmair Javaid     if (thread_error.Success()) {
25405097246SAdrian Prantl       // Remember that we set this breakpoint successfully in case we need to
25505097246SAdrian Prantl       // clear it later.
256a5be48b3SPavel Labath       breakpoint_established_threads.push_back(thread.get());
257d5ffbad2SOmair Javaid     } else {
25805097246SAdrian Prantl       // Unset the breakpoint for each thread we successfully set so that we
25905097246SAdrian Prantl       // get back to a consistent state of "not set" for this hardware
26005097246SAdrian Prantl       // breakpoint.
261d5ffbad2SOmair Javaid       for (auto rollback_thread_sp : breakpoint_established_threads) {
26297206d57SZachary Turner         Status remove_error =
26397206d57SZachary Turner             rollback_thread_sp->RemoveHardwareBreakpoint(addr);
264a5be48b3SPavel Labath         if (remove_error.Fail())
265a5be48b3SPavel Labath           LLDB_LOG(log,
266a5be48b3SPavel Labath                    "RemoveHardwareBreakpoint failed for pid={0}, tid={1}: {2}",
267a5be48b3SPavel Labath                    GetID(), rollback_thread_sp->GetID(), remove_error);
268d5ffbad2SOmair Javaid       }
269d5ffbad2SOmair Javaid 
270d5ffbad2SOmair Javaid       return thread_error;
271d5ffbad2SOmair Javaid     }
272d5ffbad2SOmair Javaid   }
273d5ffbad2SOmair Javaid 
274d5ffbad2SOmair Javaid   // Register new hardware breakpoint into hardware breakpoints map of current
275d5ffbad2SOmair Javaid   // process.
276d5ffbad2SOmair Javaid   m_hw_breakpoints_map[addr] = {addr, size};
277d5ffbad2SOmair Javaid 
27897206d57SZachary Turner   return Status();
279d5ffbad2SOmair Javaid }
280d5ffbad2SOmair Javaid 
28197206d57SZachary Turner Status NativeProcessProtocol::RemoveHardwareBreakpoint(lldb::addr_t addr) {
282d5ffbad2SOmair Javaid   // Update the thread list
283d5ffbad2SOmair Javaid   UpdateThreads();
284d5ffbad2SOmair Javaid 
28597206d57SZachary Turner   Status error;
286d5ffbad2SOmair Javaid 
287d5ffbad2SOmair Javaid   std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
288a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
289a5be48b3SPavel Labath     assert(thread && "thread list should not have a NULL thread!");
290a5be48b3SPavel Labath     error = thread->RemoveHardwareBreakpoint(addr);
291d5ffbad2SOmair Javaid   }
292d5ffbad2SOmair Javaid 
293d5ffbad2SOmair Javaid   // Also remove from hardware breakpoint map of current process.
294d5ffbad2SOmair Javaid   m_hw_breakpoints_map.erase(addr);
295d5ffbad2SOmair Javaid 
296d5ffbad2SOmair Javaid   return error;
297d5ffbad2SOmair Javaid }
298d5ffbad2SOmair Javaid 
299b9c1b51eSKate Stone bool NativeProcessProtocol::RegisterNativeDelegate(
300b9c1b51eSKate Stone     NativeDelegate &native_delegate) {
30116ff8604SSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(m_delegates_mutex);
302b9c1b51eSKate Stone   if (std::find(m_delegates.begin(), m_delegates.end(), &native_delegate) !=
303b9c1b51eSKate Stone       m_delegates.end())
304af245d11STodd Fiala     return false;
305af245d11STodd Fiala 
306af245d11STodd Fiala   m_delegates.push_back(&native_delegate);
307af245d11STodd Fiala   native_delegate.InitializeDelegate(this);
308af245d11STodd Fiala   return true;
309af245d11STodd Fiala }
310af245d11STodd Fiala 
311b9c1b51eSKate Stone bool NativeProcessProtocol::UnregisterNativeDelegate(
312b9c1b51eSKate Stone     NativeDelegate &native_delegate) {
31316ff8604SSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(m_delegates_mutex);
314af245d11STodd Fiala 
315af245d11STodd Fiala   const auto initial_size = m_delegates.size();
316b9c1b51eSKate Stone   m_delegates.erase(
317b9c1b51eSKate Stone       remove(m_delegates.begin(), m_delegates.end(), &native_delegate),
318b9c1b51eSKate Stone       m_delegates.end());
319af245d11STodd Fiala 
32005097246SAdrian Prantl   // We removed the delegate if the count of delegates shrank after removing
32105097246SAdrian Prantl   // all copies of the given native_delegate from the vector.
322af245d11STodd Fiala   return m_delegates.size() < initial_size;
323af245d11STodd Fiala }
324af245d11STodd Fiala 
325b9c1b51eSKate Stone void NativeProcessProtocol::SynchronouslyNotifyProcessStateChanged(
326b9c1b51eSKate Stone     lldb::StateType state) {
327af245d11STodd Fiala   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
328af245d11STodd Fiala 
32916ff8604SSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(m_delegates_mutex);
330af245d11STodd Fiala   for (auto native_delegate : m_delegates)
331af245d11STodd Fiala     native_delegate->ProcessStateChanged(this, state);
332af245d11STodd Fiala 
333b9c1b51eSKate Stone   if (log) {
334b9c1b51eSKate Stone     if (!m_delegates.empty()) {
335b9c1b51eSKate Stone       log->Printf("NativeProcessProtocol::%s: sent state notification [%s] "
336b9c1b51eSKate Stone                   "from process %" PRIu64,
337af245d11STodd Fiala                   __FUNCTION__, lldb_private::StateAsCString(state), GetID());
338b9c1b51eSKate Stone     } else {
339b9c1b51eSKate Stone       log->Printf("NativeProcessProtocol::%s: would send state notification "
340b9c1b51eSKate Stone                   "[%s] from process %" PRIu64 ", but no delegates",
341af245d11STodd Fiala                   __FUNCTION__, lldb_private::StateAsCString(state), GetID());
342af245d11STodd Fiala     }
343af245d11STodd Fiala   }
344af245d11STodd Fiala }
345af245d11STodd Fiala 
346b9c1b51eSKate Stone void NativeProcessProtocol::NotifyDidExec() {
347a9882ceeSTodd Fiala   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
348a9882ceeSTodd Fiala   if (log)
349b9c1b51eSKate Stone     log->Printf("NativeProcessProtocol::%s - preparing to call delegates",
350b9c1b51eSKate Stone                 __FUNCTION__);
351a9882ceeSTodd Fiala 
352a9882ceeSTodd Fiala   {
35316ff8604SSaleem Abdulrasool     std::lock_guard<std::recursive_mutex> guard(m_delegates_mutex);
354a9882ceeSTodd Fiala     for (auto native_delegate : m_delegates)
355a9882ceeSTodd Fiala       native_delegate->DidExec(this);
356a9882ceeSTodd Fiala   }
357a9882ceeSTodd Fiala }
358a9882ceeSTodd Fiala 
35997206d57SZachary Turner Status NativeProcessProtocol::SetSoftwareBreakpoint(lldb::addr_t addr,
360b9c1b51eSKate Stone                                                     uint32_t size_hint) {
361af245d11STodd Fiala   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
362be828518SPavel Labath   LLDB_LOG(log, "addr = {0:x}, size_hint = {1}", addr, size_hint);
363af245d11STodd Fiala 
364be828518SPavel Labath   auto it = m_software_breakpoints.find(addr);
365be828518SPavel Labath   if (it != m_software_breakpoints.end()) {
366be828518SPavel Labath     ++it->second.ref_count;
367be828518SPavel Labath     return Status();
368be828518SPavel Labath   }
369be828518SPavel Labath   auto expected_bkpt = EnableSoftwareBreakpoint(addr, size_hint);
370be828518SPavel Labath   if (!expected_bkpt)
371be828518SPavel Labath     return Status(expected_bkpt.takeError());
372be828518SPavel Labath 
373be828518SPavel Labath   m_software_breakpoints.emplace(addr, std::move(*expected_bkpt));
374be828518SPavel Labath   return Status();
375be828518SPavel Labath }
376be828518SPavel Labath 
377be828518SPavel Labath Status NativeProcessProtocol::RemoveSoftwareBreakpoint(lldb::addr_t addr) {
378be828518SPavel Labath   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
379be828518SPavel Labath   LLDB_LOG(log, "addr = {0:x}", addr);
380be828518SPavel Labath   auto it = m_software_breakpoints.find(addr);
381be828518SPavel Labath   if (it == m_software_breakpoints.end())
382be828518SPavel Labath     return Status("Breakpoint not found.");
383be828518SPavel Labath   assert(it->second.ref_count > 0);
384be828518SPavel Labath   if (--it->second.ref_count > 0)
385be828518SPavel Labath     return Status();
386be828518SPavel Labath 
387be828518SPavel Labath   // This is the last reference. Let's remove the breakpoint.
388be828518SPavel Labath   Status error;
389be828518SPavel Labath 
390be828518SPavel Labath   // Clear a software breakpoint instruction
391be828518SPavel Labath   llvm::SmallVector<uint8_t, 4> curr_break_op(
392be828518SPavel Labath       it->second.breakpoint_opcodes.size(), 0);
393be828518SPavel Labath 
394be828518SPavel Labath   // Read the breakpoint opcode
395be828518SPavel Labath   size_t bytes_read = 0;
396be828518SPavel Labath   error =
397be828518SPavel Labath       ReadMemory(addr, curr_break_op.data(), curr_break_op.size(), bytes_read);
398be828518SPavel Labath   if (error.Fail() || bytes_read < curr_break_op.size()) {
399be828518SPavel Labath     return Status("addr=0x%" PRIx64
400be828518SPavel Labath                   ": tried to read %zu bytes but only read %zu",
401be828518SPavel Labath                   addr, curr_break_op.size(), bytes_read);
402be828518SPavel Labath   }
403be828518SPavel Labath   const auto &saved = it->second.saved_opcodes;
404be828518SPavel Labath   // Make sure the breakpoint opcode exists at this address
405be828518SPavel Labath   if (makeArrayRef(curr_break_op) != it->second.breakpoint_opcodes) {
406be828518SPavel Labath     if (curr_break_op != it->second.saved_opcodes)
407be828518SPavel Labath       return Status("Original breakpoint trap is no longer in memory.");
408be828518SPavel Labath     LLDB_LOG(log,
409be828518SPavel Labath              "Saved opcodes ({0:@[x]}) have already been restored at {1:x}.",
410be828518SPavel Labath              llvm::make_range(saved.begin(), saved.end()), addr);
411be828518SPavel Labath   } else {
412be828518SPavel Labath     // We found a valid breakpoint opcode at this address, now restore the
413be828518SPavel Labath     // saved opcode.
414be828518SPavel Labath     size_t bytes_written = 0;
415be828518SPavel Labath     error = WriteMemory(addr, saved.data(), saved.size(), bytes_written);
416be828518SPavel Labath     if (error.Fail() || bytes_written < saved.size()) {
417be828518SPavel Labath       return Status("addr=0x%" PRIx64
418be828518SPavel Labath                     ": tried to write %zu bytes but only wrote %zu",
419be828518SPavel Labath                     addr, saved.size(), bytes_written);
420be828518SPavel Labath     }
421be828518SPavel Labath 
422be828518SPavel Labath     // Verify that our original opcode made it back to the inferior
423be828518SPavel Labath     llvm::SmallVector<uint8_t, 4> verify_opcode(saved.size(), 0);
424be828518SPavel Labath     size_t verify_bytes_read = 0;
425be828518SPavel Labath     error = ReadMemory(addr, verify_opcode.data(), verify_opcode.size(),
426be828518SPavel Labath                        verify_bytes_read);
427be828518SPavel Labath     if (error.Fail() || verify_bytes_read < verify_opcode.size()) {
428be828518SPavel Labath       return Status("addr=0x%" PRIx64
429be828518SPavel Labath                     ": tried to read %zu verification bytes but only read %zu",
430be828518SPavel Labath                     addr, verify_opcode.size(), verify_bytes_read);
431be828518SPavel Labath     }
432be828518SPavel Labath     if (verify_opcode != saved)
433be828518SPavel Labath       LLDB_LOG(log, "Restoring bytes at {0:x}: {1:@[x]}", addr,
434be828518SPavel Labath                llvm::make_range(saved.begin(), saved.end()));
435be828518SPavel Labath   }
436be828518SPavel Labath 
437be828518SPavel Labath   m_software_breakpoints.erase(it);
438be828518SPavel Labath   return Status();
439be828518SPavel Labath }
440be828518SPavel Labath 
441be828518SPavel Labath llvm::Expected<NativeProcessProtocol::SoftwareBreakpoint>
442be828518SPavel Labath NativeProcessProtocol::EnableSoftwareBreakpoint(lldb::addr_t addr,
443be828518SPavel Labath                                                 uint32_t size_hint) {
444be828518SPavel Labath   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
445be828518SPavel Labath 
446be828518SPavel Labath   auto expected_trap = GetSoftwareBreakpointTrapOpcode(size_hint);
447be828518SPavel Labath   if (!expected_trap)
448be828518SPavel Labath     return expected_trap.takeError();
449be828518SPavel Labath 
450be828518SPavel Labath   llvm::SmallVector<uint8_t, 4> saved_opcode_bytes(expected_trap->size(), 0);
451be828518SPavel Labath   // Save the original opcodes by reading them so we can restore later.
452be828518SPavel Labath   size_t bytes_read = 0;
453be828518SPavel Labath   Status error = ReadMemory(addr, saved_opcode_bytes.data(),
454be828518SPavel Labath                             saved_opcode_bytes.size(), bytes_read);
455be828518SPavel Labath   if (error.Fail())
456be828518SPavel Labath     return error.ToError();
457be828518SPavel Labath 
458be828518SPavel Labath   // Ensure we read as many bytes as we expected.
459be828518SPavel Labath   if (bytes_read != saved_opcode_bytes.size()) {
460be828518SPavel Labath     return llvm::createStringError(
461be828518SPavel Labath         llvm::inconvertibleErrorCode(),
462be828518SPavel Labath         "Failed to read memory while attempting to set breakpoint: attempted "
463be828518SPavel Labath         "to read {0} bytes but only read {1}.",
464be828518SPavel Labath         saved_opcode_bytes.size(), bytes_read);
465be828518SPavel Labath   }
466be828518SPavel Labath 
467be828518SPavel Labath   LLDB_LOG(
468be828518SPavel Labath       log, "Overwriting bytes at {0:x}: {1:@[x]}", addr,
469be828518SPavel Labath       llvm::make_range(saved_opcode_bytes.begin(), saved_opcode_bytes.end()));
470be828518SPavel Labath 
471be828518SPavel Labath   // Write a software breakpoint in place of the original opcode.
472be828518SPavel Labath   size_t bytes_written = 0;
473be828518SPavel Labath   error = WriteMemory(addr, expected_trap->data(), expected_trap->size(),
474be828518SPavel Labath                       bytes_written);
475be828518SPavel Labath   if (error.Fail())
476be828518SPavel Labath     return error.ToError();
477be828518SPavel Labath 
478be828518SPavel Labath   // Ensure we wrote as many bytes as we expected.
479be828518SPavel Labath   if (bytes_written != expected_trap->size()) {
480be828518SPavel Labath     return llvm::createStringError(
481be828518SPavel Labath         llvm::inconvertibleErrorCode(),
482be828518SPavel Labath         "Failed write memory while attempting to set "
483be828518SPavel Labath         "breakpoint: attempted to write {0} bytes but only wrote {1}",
484be828518SPavel Labath         expected_trap->size(), bytes_written);
485be828518SPavel Labath   }
486be828518SPavel Labath 
487be828518SPavel Labath   llvm::SmallVector<uint8_t, 4> verify_bp_opcode_bytes(expected_trap->size(),
488be828518SPavel Labath                                                        0);
489be828518SPavel Labath   size_t verify_bytes_read = 0;
490be828518SPavel Labath   error = ReadMemory(addr, verify_bp_opcode_bytes.data(),
491be828518SPavel Labath                      verify_bp_opcode_bytes.size(), verify_bytes_read);
492be828518SPavel Labath   if (error.Fail())
493be828518SPavel Labath     return error.ToError();
494be828518SPavel Labath 
495be828518SPavel Labath   // Ensure we read as many verification bytes as we expected.
496be828518SPavel Labath   if (verify_bytes_read != verify_bp_opcode_bytes.size()) {
497be828518SPavel Labath     return llvm::createStringError(
498be828518SPavel Labath         llvm::inconvertibleErrorCode(),
499be828518SPavel Labath         "Failed to read memory while "
500be828518SPavel Labath         "attempting to verify breakpoint: attempted to read {0} bytes "
501be828518SPavel Labath         "but only read {1}",
502be828518SPavel Labath         verify_bp_opcode_bytes.size(), verify_bytes_read);
503be828518SPavel Labath   }
504be828518SPavel Labath 
505be828518SPavel Labath   if (llvm::makeArrayRef(verify_bp_opcode_bytes.data(), verify_bytes_read) !=
506be828518SPavel Labath       *expected_trap) {
507be828518SPavel Labath     return llvm::createStringError(
508be828518SPavel Labath         llvm::inconvertibleErrorCode(),
509be828518SPavel Labath         "Verification of software breakpoint "
510be828518SPavel Labath         "writing failed - trap opcodes not successfully read back "
511be828518SPavel Labath         "after writing when setting breakpoint at {0:x}",
512be828518SPavel Labath         addr);
513be828518SPavel Labath   }
514be828518SPavel Labath 
515*b075bbd9SPavel Labath   LLDB_LOG(log, "addr = {0:x}: SUCCESS", addr);
516be828518SPavel Labath   return SoftwareBreakpoint{1, saved_opcode_bytes, *expected_trap};
517af245d11STodd Fiala }
518af245d11STodd Fiala 
519f8b825f6SPavel Labath llvm::Expected<llvm::ArrayRef<uint8_t>>
520f8b825f6SPavel Labath NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_t size_hint) {
521f8b825f6SPavel Labath   static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
522f8b825f6SPavel Labath   static const uint8_t g_i386_opcode[] = {0xCC};
523f8b825f6SPavel Labath   static const uint8_t g_mips64_opcode[] = {0x00, 0x00, 0x00, 0x0d};
524f8b825f6SPavel Labath   static const uint8_t g_mips64el_opcode[] = {0x0d, 0x00, 0x00, 0x00};
525f8b825f6SPavel Labath   static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
526f8b825f6SPavel Labath   static const uint8_t g_ppc64le_opcode[] = {0x08, 0x00, 0xe0, 0x7f}; // trap
527f8b825f6SPavel Labath 
528f8b825f6SPavel Labath   switch (GetArchitecture().GetMachine()) {
529f8b825f6SPavel Labath   case llvm::Triple::aarch64:
5304f545074SPavel Labath     return llvm::makeArrayRef(g_aarch64_opcode);
531f8b825f6SPavel Labath 
532f8b825f6SPavel Labath   case llvm::Triple::x86:
533f8b825f6SPavel Labath   case llvm::Triple::x86_64:
5344f545074SPavel Labath     return llvm::makeArrayRef(g_i386_opcode);
535f8b825f6SPavel Labath 
536f8b825f6SPavel Labath   case llvm::Triple::mips:
537f8b825f6SPavel Labath   case llvm::Triple::mips64:
5384f545074SPavel Labath     return llvm::makeArrayRef(g_mips64_opcode);
539f8b825f6SPavel Labath 
540f8b825f6SPavel Labath   case llvm::Triple::mipsel:
541f8b825f6SPavel Labath   case llvm::Triple::mips64el:
5424f545074SPavel Labath     return llvm::makeArrayRef(g_mips64el_opcode);
543f8b825f6SPavel Labath 
544f8b825f6SPavel Labath   case llvm::Triple::systemz:
5454f545074SPavel Labath     return llvm::makeArrayRef(g_s390x_opcode);
546f8b825f6SPavel Labath 
547f8b825f6SPavel Labath   case llvm::Triple::ppc64le:
5484f545074SPavel Labath     return llvm::makeArrayRef(g_ppc64le_opcode);
549f8b825f6SPavel Labath 
550f8b825f6SPavel Labath   default:
551f8b825f6SPavel Labath     return llvm::createStringError(llvm::inconvertibleErrorCode(),
552f8b825f6SPavel Labath                                    "CPU type not supported!");
553f8b825f6SPavel Labath   }
554f8b825f6SPavel Labath }
555f8b825f6SPavel Labath 
55699f436b0SPavel Labath size_t NativeProcessProtocol::GetSoftwareBreakpointPCOffset() {
55799f436b0SPavel Labath   switch (GetArchitecture().GetMachine()) {
55899f436b0SPavel Labath   case llvm::Triple::x86:
55999f436b0SPavel Labath   case llvm::Triple::x86_64:
56099f436b0SPavel Labath   case llvm::Triple::systemz:
56199f436b0SPavel Labath     // These architectures report increment the PC after breakpoint is hit.
56299f436b0SPavel Labath     return cantFail(GetSoftwareBreakpointTrapOpcode(0)).size();
56399f436b0SPavel Labath 
56499f436b0SPavel Labath   case llvm::Triple::arm:
56599f436b0SPavel Labath   case llvm::Triple::aarch64:
56699f436b0SPavel Labath   case llvm::Triple::mips64:
56799f436b0SPavel Labath   case llvm::Triple::mips64el:
56899f436b0SPavel Labath   case llvm::Triple::mips:
56999f436b0SPavel Labath   case llvm::Triple::mipsel:
57099f436b0SPavel Labath   case llvm::Triple::ppc64le:
57199f436b0SPavel Labath     // On these architectures the PC doesn't get updated for breakpoint hits.
57299f436b0SPavel Labath     return 0;
57399f436b0SPavel Labath 
57499f436b0SPavel Labath   default:
57599f436b0SPavel Labath     llvm_unreachable("CPU type not supported!");
57699f436b0SPavel Labath   }
57799f436b0SPavel Labath }
57899f436b0SPavel Labath 
579aef7908fSPavel Labath void NativeProcessProtocol::FixupBreakpointPCAsNeeded(
580aef7908fSPavel Labath     NativeThreadProtocol &thread) {
581aef7908fSPavel Labath   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS);
582aef7908fSPavel Labath 
583aef7908fSPavel Labath   Status error;
584aef7908fSPavel Labath 
585aef7908fSPavel Labath   // Find out the size of a breakpoint (might depend on where we are in the
586aef7908fSPavel Labath   // code).
587aef7908fSPavel Labath   NativeRegisterContext &context = thread.GetRegisterContext();
588aef7908fSPavel Labath 
589aef7908fSPavel Labath   uint32_t breakpoint_size = GetSoftwareBreakpointPCOffset();
590aef7908fSPavel Labath   LLDB_LOG(log, "breakpoint size: {0}", breakpoint_size);
591aef7908fSPavel Labath   if (breakpoint_size == 0)
592aef7908fSPavel Labath     return;
593aef7908fSPavel Labath 
594aef7908fSPavel Labath   // First try probing for a breakpoint at a software breakpoint location: PC -
595aef7908fSPavel Labath   // breakpoint size.
596aef7908fSPavel Labath   const lldb::addr_t initial_pc_addr = context.GetPCfromBreakpointLocation();
597aef7908fSPavel Labath   lldb::addr_t breakpoint_addr = initial_pc_addr;
598aef7908fSPavel Labath   // Do not allow breakpoint probe to wrap around.
599aef7908fSPavel Labath   if (breakpoint_addr >= breakpoint_size)
600aef7908fSPavel Labath     breakpoint_addr -= breakpoint_size;
601aef7908fSPavel Labath 
602be828518SPavel Labath   if (m_software_breakpoints.count(breakpoint_addr) == 0) {
603aef7908fSPavel Labath     // We didn't find one at a software probe location.  Nothing to do.
604aef7908fSPavel Labath     LLDB_LOG(log,
605be828518SPavel Labath              "pid {0} no lldb software breakpoint found at current pc with "
606aef7908fSPavel Labath              "adjustment: {1}",
607aef7908fSPavel Labath              GetID(), breakpoint_addr);
608aef7908fSPavel Labath     return;
609aef7908fSPavel Labath   }
610aef7908fSPavel Labath 
611aef7908fSPavel Labath   //
612aef7908fSPavel Labath   // We have a software breakpoint and need to adjust the PC.
613aef7908fSPavel Labath   //
614aef7908fSPavel Labath 
615aef7908fSPavel Labath   // Change the program counter.
616aef7908fSPavel Labath   LLDB_LOG(log, "pid {0} tid {1}: changing PC from {2:x} to {3:x}", GetID(),
617aef7908fSPavel Labath            thread.GetID(), initial_pc_addr, breakpoint_addr);
618aef7908fSPavel Labath 
619aef7908fSPavel Labath   error = context.SetPC(breakpoint_addr);
620aef7908fSPavel Labath   if (error.Fail()) {
621aef7908fSPavel Labath     // This can happen in case the process was killed between the time we read
622aef7908fSPavel Labath     // the PC and when we are updating it. There's nothing better to do than to
623aef7908fSPavel Labath     // swallow the error.
624aef7908fSPavel Labath     LLDB_LOG(log, "pid {0} tid {1}: failed to set PC: {2}", GetID(),
625aef7908fSPavel Labath              thread.GetID(), error);
626aef7908fSPavel Labath   }
627aef7908fSPavel Labath }
628aef7908fSPavel Labath 
62997206d57SZachary Turner Status NativeProcessProtocol::RemoveBreakpoint(lldb::addr_t addr,
630d5ffbad2SOmair Javaid                                                bool hardware) {
631d5ffbad2SOmair Javaid   if (hardware)
632d5ffbad2SOmair Javaid     return RemoveHardwareBreakpoint(addr);
633d5ffbad2SOmair Javaid   else
634be828518SPavel Labath     return RemoveSoftwareBreakpoint(addr);
635af245d11STodd Fiala }
636af245d11STodd Fiala 
6372ce26527SPavel Labath Status NativeProcessProtocol::ReadMemoryWithoutTrap(lldb::addr_t addr,
6382ce26527SPavel Labath                                                     void *buf, size_t size,
6392ce26527SPavel Labath                                                     size_t &bytes_read) {
6402ce26527SPavel Labath   Status error = ReadMemory(addr, buf, size, bytes_read);
6412ce26527SPavel Labath   if (error.Fail())
6422ce26527SPavel Labath     return error;
643be828518SPavel Labath 
644be828518SPavel Labath   auto data =
645be828518SPavel Labath       llvm::makeMutableArrayRef(static_cast<uint8_t *>(buf), bytes_read);
646be828518SPavel Labath   for (const auto &pair : m_software_breakpoints) {
647be828518SPavel Labath     lldb::addr_t bp_addr = pair.first;
648be828518SPavel Labath     auto saved_opcodes = makeArrayRef(pair.second.saved_opcodes);
649be828518SPavel Labath 
650be828518SPavel Labath     if (bp_addr + saved_opcodes.size() < addr || addr + bytes_read <= bp_addr)
651be828518SPavel Labath       continue; // Breapoint not in range, ignore
652be828518SPavel Labath 
653be828518SPavel Labath     if (bp_addr < addr) {
654be828518SPavel Labath       saved_opcodes = saved_opcodes.drop_front(addr - bp_addr);
655be828518SPavel Labath       bp_addr = addr;
656be828518SPavel Labath     }
657be828518SPavel Labath     auto bp_data = data.drop_front(bp_addr - addr);
658be828518SPavel Labath     std::copy_n(saved_opcodes.begin(),
659be828518SPavel Labath                 std::min(saved_opcodes.size(), bp_data.size()),
660be828518SPavel Labath                 bp_data.begin());
661be828518SPavel Labath   }
662be828518SPavel Labath   return Status();
663be828518SPavel Labath }
664be828518SPavel Labath 
665be828518SPavel Labath lldb::StateType NativeProcessProtocol::GetState() const {
666be828518SPavel Labath   std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
667be828518SPavel Labath   return m_state;
6682ce26527SPavel Labath }
6692ce26527SPavel Labath 
670b9c1b51eSKate Stone void NativeProcessProtocol::SetState(lldb::StateType state,
671b9c1b51eSKate Stone                                      bool notify_delegates) {
67216ff8604SSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
6735830aa75STamas Berghammer 
6745830aa75STamas Berghammer   if (state == m_state)
6755830aa75STamas Berghammer     return;
6765830aa75STamas Berghammer 
677af245d11STodd Fiala   m_state = state;
678af245d11STodd Fiala 
679b9c1b51eSKate Stone   if (StateIsStoppedState(state, false)) {
680af245d11STodd Fiala     ++m_stop_id;
681af245d11STodd Fiala 
682af245d11STodd Fiala     // Give process a chance to do any stop id bump processing, such as
683af245d11STodd Fiala     // clearing cached data that is invalidated each time the process runs.
68405097246SAdrian Prantl     // Note if/when we support some threads running, we'll end up needing to
68505097246SAdrian Prantl     // manage this per thread and per process.
686af245d11STodd Fiala     DoStopIDBumped(m_stop_id);
687af245d11STodd Fiala   }
688af245d11STodd Fiala 
689af245d11STodd Fiala   // Optionally notify delegates of the state change.
690af245d11STodd Fiala   if (notify_delegates)
691af245d11STodd Fiala     SynchronouslyNotifyProcessStateChanged(state);
692af245d11STodd Fiala }
693af245d11STodd Fiala 
694b9c1b51eSKate Stone uint32_t NativeProcessProtocol::GetStopID() const {
69516ff8604SSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
696af245d11STodd Fiala   return m_stop_id;
697af245d11STodd Fiala }
698af245d11STodd Fiala 
699b9c1b51eSKate Stone void NativeProcessProtocol::DoStopIDBumped(uint32_t /* newBumpId */) {
700af245d11STodd Fiala   // Default implementation does nothing.
701af245d11STodd Fiala }
7028bc34f4dSOleksiy Vyalov 
70396e600fcSPavel Labath NativeProcessProtocol::Factory::~Factory() = default;
704