1af245d11STodd Fiala //===-- NativeProcessProtocol.cpp -------------------------------*- C++ -*-===//
2af245d11STodd Fiala //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6af245d11STodd Fiala //
7af245d11STodd Fiala //===----------------------------------------------------------------------===//
8af245d11STodd Fiala 
92fe1d0abSChaoren Lin #include "lldb/Host/common/NativeProcessProtocol.h"
10511e5cdcSTodd Fiala #include "lldb/Host/Host.h"
11be828518SPavel Labath #include "lldb/Host/common/NativeBreakpointList.h"
122fe1d0abSChaoren Lin #include "lldb/Host/common/NativeRegisterContext.h"
132fe1d0abSChaoren Lin #include "lldb/Host/common/NativeThreadProtocol.h"
14e77fce0aSTodd Fiala #include "lldb/Utility/LLDBAssert.h"
156f9e6901SZachary Turner #include "lldb/Utility/Log.h"
16d821c997SPavel Labath #include "lldb/Utility/State.h"
17b9c1b51eSKate Stone #include "lldb/lldb-enumerations.h"
18af245d11STodd Fiala 
1970795c1eSAntonio Afonso #include "llvm/Support/Process.h"
2070795c1eSAntonio Afonso 
21af245d11STodd Fiala using namespace lldb;
22af245d11STodd Fiala using namespace lldb_private;
23af245d11STodd Fiala 
24af245d11STodd Fiala // NativeProcessProtocol Members
25af245d11STodd Fiala 
2696e600fcSPavel Labath NativeProcessProtocol::NativeProcessProtocol(lldb::pid_t pid, int terminal_fd,
2796e600fcSPavel Labath                                              NativeDelegate &delegate)
2896e600fcSPavel Labath     : m_pid(pid), m_terminal_fd(terminal_fd) {
2996e600fcSPavel Labath   bool registered = RegisterNativeDelegate(delegate);
3096e600fcSPavel Labath   assert(registered);
3196e600fcSPavel Labath   (void)registered;
3296e600fcSPavel Labath }
33af245d11STodd Fiala 
3497206d57SZachary Turner lldb_private::Status NativeProcessProtocol::Interrupt() {
3597206d57SZachary Turner   Status error;
36511e5cdcSTodd Fiala #if !defined(SIGSTOP)
37511e5cdcSTodd Fiala   error.SetErrorString("local host does not support signaling");
38511e5cdcSTodd Fiala   return error;
39511e5cdcSTodd Fiala #else
40511e5cdcSTodd Fiala   return Signal(SIGSTOP);
41511e5cdcSTodd Fiala #endif
42511e5cdcSTodd Fiala }
43511e5cdcSTodd Fiala 
4497206d57SZachary Turner Status NativeProcessProtocol::IgnoreSignals(llvm::ArrayRef<int> signals) {
454a705e7eSPavel Labath   m_signals_to_ignore.clear();
464a705e7eSPavel Labath   m_signals_to_ignore.insert(signals.begin(), signals.end());
4797206d57SZachary Turner   return Status();
484a705e7eSPavel Labath }
494a705e7eSPavel Labath 
5097206d57SZachary Turner lldb_private::Status
51b9c1b51eSKate Stone NativeProcessProtocol::GetMemoryRegionInfo(lldb::addr_t load_addr,
52b9c1b51eSKate Stone                                            MemoryRegionInfo &range_info) {
53af245d11STodd Fiala   // Default: not implemented.
5497206d57SZachary Turner   return Status("not implemented");
55af245d11STodd Fiala }
56af245d11STodd Fiala 
573508fc8cSPavel Labath llvm::Optional<WaitStatus> NativeProcessProtocol::GetExitStatus() {
583508fc8cSPavel Labath   if (m_state == lldb::eStateExited)
593508fc8cSPavel Labath     return m_exit_status;
603508fc8cSPavel Labath 
613508fc8cSPavel Labath   return llvm::None;
62af245d11STodd Fiala }
63af245d11STodd Fiala 
643508fc8cSPavel Labath bool NativeProcessProtocol::SetExitStatus(WaitStatus status,
65b9c1b51eSKate Stone                                           bool bNotifyStateChange) {
66af245d11STodd Fiala   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
673508fc8cSPavel Labath   LLDB_LOG(log, "status = {0}, notify = {1}", status, bNotifyStateChange);
68af245d11STodd Fiala 
69af245d11STodd Fiala   // Exit status already set
70b9c1b51eSKate Stone   if (m_state == lldb::eStateExited) {
713508fc8cSPavel Labath     if (m_exit_status)
723508fc8cSPavel Labath       LLDB_LOG(log, "exit status already set to {0}", *m_exit_status);
733508fc8cSPavel Labath     else
743508fc8cSPavel Labath       LLDB_LOG(log, "state is exited, but status not set");
75af245d11STodd Fiala     return false;
76af245d11STodd Fiala   }
77af245d11STodd Fiala 
78af245d11STodd Fiala   m_state = lldb::eStateExited;
79af245d11STodd Fiala   m_exit_status = status;
80af245d11STodd Fiala 
81af245d11STodd Fiala   if (bNotifyStateChange)
82af245d11STodd Fiala     SynchronouslyNotifyProcessStateChanged(lldb::eStateExited);
83af245d11STodd Fiala 
84af245d11STodd Fiala   return true;
85af245d11STodd Fiala }
86af245d11STodd Fiala 
87a5be48b3SPavel Labath NativeThreadProtocol *NativeProcessProtocol::GetThreadAtIndex(uint32_t idx) {
8816ff8604SSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
89af245d11STodd Fiala   if (idx < m_threads.size())
90a5be48b3SPavel Labath     return m_threads[idx].get();
91a5be48b3SPavel Labath   return nullptr;
92af245d11STodd Fiala }
93af245d11STodd Fiala 
94a5be48b3SPavel Labath NativeThreadProtocol *
95b9c1b51eSKate Stone NativeProcessProtocol::GetThreadByIDUnlocked(lldb::tid_t tid) {
96a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
97a5be48b3SPavel Labath     if (thread->GetID() == tid)
98a5be48b3SPavel Labath       return thread.get();
99af245d11STodd Fiala   }
100a5be48b3SPavel Labath   return nullptr;
101af245d11STodd Fiala }
102af245d11STodd Fiala 
103a5be48b3SPavel Labath NativeThreadProtocol *NativeProcessProtocol::GetThreadByID(lldb::tid_t tid) {
10416ff8604SSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
105511e5cdcSTodd Fiala   return GetThreadByIDUnlocked(tid);
106511e5cdcSTodd Fiala }
107511e5cdcSTodd Fiala 
108b9c1b51eSKate Stone bool NativeProcessProtocol::IsAlive() const {
109b9c1b51eSKate Stone   return m_state != eStateDetached && m_state != eStateExited &&
110b9c1b51eSKate Stone          m_state != eStateInvalid && m_state != eStateUnloaded;
111af245d11STodd Fiala }
112af245d11STodd Fiala 
11318fe6404SChaoren Lin const NativeWatchpointList::WatchpointMap &
114b9c1b51eSKate Stone NativeProcessProtocol::GetWatchpointMap() const {
11518fe6404SChaoren Lin   return m_watchpoint_list.GetWatchpointMap();
11618fe6404SChaoren Lin }
11718fe6404SChaoren Lin 
118d5ffbad2SOmair Javaid llvm::Optional<std::pair<uint32_t, uint32_t>>
119d5ffbad2SOmair Javaid NativeProcessProtocol::GetHardwareDebugSupportInfo() const {
120af245d11STodd Fiala   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
121af245d11STodd Fiala 
122af245d11STodd Fiala   // get any thread
123a5be48b3SPavel Labath   NativeThreadProtocol *thread(
124b9c1b51eSKate Stone       const_cast<NativeProcessProtocol *>(this)->GetThreadAtIndex(0));
125a5be48b3SPavel Labath   if (!thread) {
126a5be48b3SPavel Labath     LLDB_LOG(log, "failed to find a thread to grab a NativeRegisterContext!");
127d5ffbad2SOmair Javaid     return llvm::None;
128af245d11STodd Fiala   }
129af245d11STodd Fiala 
130d37349f3SPavel Labath   NativeRegisterContext &reg_ctx = thread->GetRegisterContext();
131d37349f3SPavel Labath   return std::make_pair(reg_ctx.NumSupportedHardwareBreakpoints(),
132d37349f3SPavel Labath                         reg_ctx.NumSupportedHardwareWatchpoints());
133af245d11STodd Fiala }
134af245d11STodd Fiala 
13597206d57SZachary Turner Status NativeProcessProtocol::SetWatchpoint(lldb::addr_t addr, size_t size,
136b9c1b51eSKate Stone                                             uint32_t watch_flags,
137b9c1b51eSKate Stone                                             bool hardware) {
13805097246SAdrian Prantl   // This default implementation assumes setting the watchpoint for the process
13905097246SAdrian Prantl   // will require setting the watchpoint for each of the threads.  Furthermore,
14005097246SAdrian Prantl   // it will track watchpoints set for the process and will add them to each
14105097246SAdrian Prantl   // thread that is attached to via the (FIXME implement) OnThreadAttached ()
14205097246SAdrian Prantl   // method.
143af245d11STodd Fiala 
144af245d11STodd Fiala   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
145af245d11STodd Fiala 
146af245d11STodd Fiala   // Update the thread list
147af245d11STodd Fiala   UpdateThreads();
148af245d11STodd Fiala 
14905097246SAdrian Prantl   // Keep track of the threads we successfully set the watchpoint for.  If one
15005097246SAdrian Prantl   // of the thread watchpoint setting operations fails, back off and remove the
15105097246SAdrian Prantl   // watchpoint for all the threads that were successfully set so we get back
15205097246SAdrian Prantl   // to a consistent state.
153a5be48b3SPavel Labath   std::vector<NativeThreadProtocol *> watchpoint_established_threads;
154af245d11STodd Fiala 
15505097246SAdrian Prantl   // Tell each thread to set a watchpoint.  In the event that hardware
15605097246SAdrian Prantl   // watchpoints are requested but the SetWatchpoint fails, try to set a
15705097246SAdrian Prantl   // software watchpoint as a fallback.  It's conceivable that if there are
15805097246SAdrian Prantl   // more threads than hardware watchpoints available, some of the threads will
15905097246SAdrian Prantl   // fail to set hardware watchpoints while software ones may be available.
16016ff8604SSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
161a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
162a5be48b3SPavel Labath     assert(thread && "thread list should not have a NULL thread!");
163af245d11STodd Fiala 
16497206d57SZachary Turner     Status thread_error =
165a5be48b3SPavel Labath         thread->SetWatchpoint(addr, size, watch_flags, hardware);
166b9c1b51eSKate Stone     if (thread_error.Fail() && hardware) {
16705097246SAdrian Prantl       // Try software watchpoints since we failed on hardware watchpoint
16805097246SAdrian Prantl       // setting and we may have just run out of hardware watchpoints.
169a5be48b3SPavel Labath       thread_error = thread->SetWatchpoint(addr, size, watch_flags, false);
170a5be48b3SPavel Labath       if (thread_error.Success())
171a5be48b3SPavel Labath         LLDB_LOG(log,
172b9c1b51eSKate Stone                  "hardware watchpoint requested but software watchpoint set");
173af245d11STodd Fiala     }
174af245d11STodd Fiala 
175b9c1b51eSKate Stone     if (thread_error.Success()) {
17605097246SAdrian Prantl       // Remember that we set this watchpoint successfully in case we need to
17705097246SAdrian Prantl       // clear it later.
178a5be48b3SPavel Labath       watchpoint_established_threads.push_back(thread.get());
179b9c1b51eSKate Stone     } else {
18005097246SAdrian Prantl       // Unset the watchpoint for each thread we successfully set so that we
18105097246SAdrian Prantl       // get back to a consistent state of "not set" for the watchpoint.
182b9c1b51eSKate Stone       for (auto unwatch_thread_sp : watchpoint_established_threads) {
18397206d57SZachary Turner         Status remove_error = unwatch_thread_sp->RemoveWatchpoint(addr);
184a5be48b3SPavel Labath         if (remove_error.Fail())
185a5be48b3SPavel Labath           LLDB_LOG(log, "RemoveWatchpoint failed for pid={0}, tid={1}: {2}",
186a5be48b3SPavel Labath                    GetID(), unwatch_thread_sp->GetID(), remove_error);
187af245d11STodd Fiala       }
188af245d11STodd Fiala 
189af245d11STodd Fiala       return thread_error;
190af245d11STodd Fiala     }
191af245d11STodd Fiala   }
19218fe6404SChaoren Lin   return m_watchpoint_list.Add(addr, size, watch_flags, hardware);
193af245d11STodd Fiala }
194af245d11STodd Fiala 
19597206d57SZachary Turner Status NativeProcessProtocol::RemoveWatchpoint(lldb::addr_t addr) {
196af245d11STodd Fiala   // Update the thread list
197af245d11STodd Fiala   UpdateThreads();
198af245d11STodd Fiala 
19997206d57SZachary Turner   Status overall_error;
200af245d11STodd Fiala 
20116ff8604SSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
202a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
203a5be48b3SPavel Labath     assert(thread && "thread list should not have a NULL thread!");
204af245d11STodd Fiala 
205a5be48b3SPavel Labath     const Status thread_error = thread->RemoveWatchpoint(addr);
206b9c1b51eSKate Stone     if (thread_error.Fail()) {
20705097246SAdrian Prantl       // Keep track of the first thread error if any threads fail. We want to
20805097246SAdrian Prantl       // try to remove the watchpoint from every thread, though, even if one or
20905097246SAdrian Prantl       // more have errors.
210af245d11STodd Fiala       if (!overall_error.Fail())
211af245d11STodd Fiala         overall_error = thread_error;
212af245d11STodd Fiala     }
213af245d11STodd Fiala   }
21497206d57SZachary Turner   const Status error = m_watchpoint_list.Remove(addr);
21518fe6404SChaoren Lin   return overall_error.Fail() ? overall_error : error;
216af245d11STodd Fiala }
217af245d11STodd Fiala 
218d5ffbad2SOmair Javaid const HardwareBreakpointMap &
219d5ffbad2SOmair Javaid NativeProcessProtocol::GetHardwareBreakpointMap() const {
220d5ffbad2SOmair Javaid   return m_hw_breakpoints_map;
221d5ffbad2SOmair Javaid }
222d5ffbad2SOmair Javaid 
22397206d57SZachary Turner Status NativeProcessProtocol::SetHardwareBreakpoint(lldb::addr_t addr,
224d5ffbad2SOmair Javaid                                                     size_t size) {
22505097246SAdrian Prantl   // This default implementation assumes setting a hardware breakpoint for this
22605097246SAdrian Prantl   // process will require setting same hardware breakpoint for each of its
22705097246SAdrian Prantl   // existing threads. New thread will do the same once created.
228d5ffbad2SOmair Javaid   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
229d5ffbad2SOmair Javaid 
230d5ffbad2SOmair Javaid   // Update the thread list
231d5ffbad2SOmair Javaid   UpdateThreads();
232d5ffbad2SOmair Javaid 
233d5ffbad2SOmair Javaid   // Exit here if target does not have required hardware breakpoint capability.
234d5ffbad2SOmair Javaid   auto hw_debug_cap = GetHardwareDebugSupportInfo();
235d5ffbad2SOmair Javaid 
236d5ffbad2SOmair Javaid   if (hw_debug_cap == llvm::None || hw_debug_cap->first == 0 ||
237d5ffbad2SOmair Javaid       hw_debug_cap->first <= m_hw_breakpoints_map.size())
23897206d57SZachary Turner     return Status("Target does not have required no of hardware breakpoints");
239d5ffbad2SOmair Javaid 
240d5ffbad2SOmair Javaid   // Vector below stores all thread pointer for which we have we successfully
241d5ffbad2SOmair Javaid   // set this hardware breakpoint. If any of the current process threads fails
242d5ffbad2SOmair Javaid   // to set this hardware breakpoint then roll back and remove this breakpoint
243d5ffbad2SOmair Javaid   // for all the threads that had already set it successfully.
244a5be48b3SPavel Labath   std::vector<NativeThreadProtocol *> breakpoint_established_threads;
245d5ffbad2SOmair Javaid 
246d5ffbad2SOmair Javaid   // Request to set a hardware breakpoint for each of current process threads.
247d5ffbad2SOmair Javaid   std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
248a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
249a5be48b3SPavel Labath     assert(thread && "thread list should not have a NULL thread!");
250d5ffbad2SOmair Javaid 
251a5be48b3SPavel Labath     Status thread_error = thread->SetHardwareBreakpoint(addr, size);
252d5ffbad2SOmair Javaid     if (thread_error.Success()) {
25305097246SAdrian Prantl       // Remember that we set this breakpoint successfully in case we need to
25405097246SAdrian Prantl       // clear it later.
255a5be48b3SPavel Labath       breakpoint_established_threads.push_back(thread.get());
256d5ffbad2SOmair Javaid     } else {
25705097246SAdrian Prantl       // Unset the breakpoint for each thread we successfully set so that we
25805097246SAdrian Prantl       // get back to a consistent state of "not set" for this hardware
25905097246SAdrian Prantl       // breakpoint.
260d5ffbad2SOmair Javaid       for (auto rollback_thread_sp : breakpoint_established_threads) {
26197206d57SZachary Turner         Status remove_error =
26297206d57SZachary Turner             rollback_thread_sp->RemoveHardwareBreakpoint(addr);
263a5be48b3SPavel Labath         if (remove_error.Fail())
264a5be48b3SPavel Labath           LLDB_LOG(log,
265a5be48b3SPavel Labath                    "RemoveHardwareBreakpoint failed for pid={0}, tid={1}: {2}",
266a5be48b3SPavel Labath                    GetID(), rollback_thread_sp->GetID(), remove_error);
267d5ffbad2SOmair Javaid       }
268d5ffbad2SOmair Javaid 
269d5ffbad2SOmair Javaid       return thread_error;
270d5ffbad2SOmair Javaid     }
271d5ffbad2SOmair Javaid   }
272d5ffbad2SOmair Javaid 
273d5ffbad2SOmair Javaid   // Register new hardware breakpoint into hardware breakpoints map of current
274d5ffbad2SOmair Javaid   // process.
275d5ffbad2SOmair Javaid   m_hw_breakpoints_map[addr] = {addr, size};
276d5ffbad2SOmair Javaid 
27797206d57SZachary Turner   return Status();
278d5ffbad2SOmair Javaid }
279d5ffbad2SOmair Javaid 
28097206d57SZachary Turner Status NativeProcessProtocol::RemoveHardwareBreakpoint(lldb::addr_t addr) {
281d5ffbad2SOmair Javaid   // Update the thread list
282d5ffbad2SOmair Javaid   UpdateThreads();
283d5ffbad2SOmair Javaid 
28497206d57SZachary Turner   Status error;
285d5ffbad2SOmair Javaid 
286d5ffbad2SOmair Javaid   std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
287a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
288a5be48b3SPavel Labath     assert(thread && "thread list should not have a NULL thread!");
289a5be48b3SPavel Labath     error = thread->RemoveHardwareBreakpoint(addr);
290d5ffbad2SOmair Javaid   }
291d5ffbad2SOmair Javaid 
292d5ffbad2SOmair Javaid   // Also remove from hardware breakpoint map of current process.
293d5ffbad2SOmair Javaid   m_hw_breakpoints_map.erase(addr);
294d5ffbad2SOmair Javaid 
295d5ffbad2SOmair Javaid   return error;
296d5ffbad2SOmair Javaid }
297d5ffbad2SOmair Javaid 
298b9c1b51eSKate Stone bool NativeProcessProtocol::RegisterNativeDelegate(
299b9c1b51eSKate Stone     NativeDelegate &native_delegate) {
30016ff8604SSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(m_delegates_mutex);
301b9c1b51eSKate Stone   if (std::find(m_delegates.begin(), m_delegates.end(), &native_delegate) !=
302b9c1b51eSKate Stone       m_delegates.end())
303af245d11STodd Fiala     return false;
304af245d11STodd Fiala 
305af245d11STodd Fiala   m_delegates.push_back(&native_delegate);
306af245d11STodd Fiala   native_delegate.InitializeDelegate(this);
307af245d11STodd Fiala   return true;
308af245d11STodd Fiala }
309af245d11STodd Fiala 
310b9c1b51eSKate Stone bool NativeProcessProtocol::UnregisterNativeDelegate(
311b9c1b51eSKate Stone     NativeDelegate &native_delegate) {
31216ff8604SSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(m_delegates_mutex);
313af245d11STodd Fiala 
314af245d11STodd Fiala   const auto initial_size = m_delegates.size();
315b9c1b51eSKate Stone   m_delegates.erase(
316b9c1b51eSKate Stone       remove(m_delegates.begin(), m_delegates.end(), &native_delegate),
317b9c1b51eSKate Stone       m_delegates.end());
318af245d11STodd Fiala 
31905097246SAdrian Prantl   // We removed the delegate if the count of delegates shrank after removing
32005097246SAdrian Prantl   // all copies of the given native_delegate from the vector.
321af245d11STodd Fiala   return m_delegates.size() < initial_size;
322af245d11STodd Fiala }
323af245d11STodd Fiala 
324b9c1b51eSKate Stone void NativeProcessProtocol::SynchronouslyNotifyProcessStateChanged(
325b9c1b51eSKate Stone     lldb::StateType state) {
326af245d11STodd Fiala   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
327af245d11STodd Fiala 
32816ff8604SSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(m_delegates_mutex);
329af245d11STodd Fiala   for (auto native_delegate : m_delegates)
330af245d11STodd Fiala     native_delegate->ProcessStateChanged(this, state);
331af245d11STodd Fiala 
332b9c1b51eSKate Stone   if (log) {
333b9c1b51eSKate Stone     if (!m_delegates.empty()) {
33463e5fb76SJonas Devlieghere       LLDB_LOGF(log,
33563e5fb76SJonas Devlieghere                 "NativeProcessProtocol::%s: sent state notification [%s] "
336b9c1b51eSKate Stone                 "from process %" PRIu64,
337af245d11STodd Fiala                 __FUNCTION__, lldb_private::StateAsCString(state), GetID());
338b9c1b51eSKate Stone     } else {
33963e5fb76SJonas Devlieghere       LLDB_LOGF(log,
34063e5fb76SJonas Devlieghere                 "NativeProcessProtocol::%s: would send state notification "
341b9c1b51eSKate Stone                 "[%s] from process %" PRIu64 ", but no delegates",
342af245d11STodd Fiala                 __FUNCTION__, lldb_private::StateAsCString(state), GetID());
343af245d11STodd Fiala     }
344af245d11STodd Fiala   }
345af245d11STodd Fiala }
346af245d11STodd Fiala 
347b9c1b51eSKate Stone void NativeProcessProtocol::NotifyDidExec() {
348a9882ceeSTodd Fiala   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
34963e5fb76SJonas Devlieghere   LLDB_LOGF(log, "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 
515b075bbd9SPavel 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:
5307dd7a360SJason Molenda   case llvm::Triple::aarch64_32:
5314f545074SPavel Labath     return llvm::makeArrayRef(g_aarch64_opcode);
532f8b825f6SPavel Labath 
533f8b825f6SPavel Labath   case llvm::Triple::x86:
534f8b825f6SPavel Labath   case llvm::Triple::x86_64:
5354f545074SPavel Labath     return llvm::makeArrayRef(g_i386_opcode);
536f8b825f6SPavel Labath 
537f8b825f6SPavel Labath   case llvm::Triple::mips:
538f8b825f6SPavel Labath   case llvm::Triple::mips64:
5394f545074SPavel Labath     return llvm::makeArrayRef(g_mips64_opcode);
540f8b825f6SPavel Labath 
541f8b825f6SPavel Labath   case llvm::Triple::mipsel:
542f8b825f6SPavel Labath   case llvm::Triple::mips64el:
5434f545074SPavel Labath     return llvm::makeArrayRef(g_mips64el_opcode);
544f8b825f6SPavel Labath 
545f8b825f6SPavel Labath   case llvm::Triple::systemz:
5464f545074SPavel Labath     return llvm::makeArrayRef(g_s390x_opcode);
547f8b825f6SPavel Labath 
548f8b825f6SPavel Labath   case llvm::Triple::ppc64le:
5494f545074SPavel Labath     return llvm::makeArrayRef(g_ppc64le_opcode);
550f8b825f6SPavel Labath 
551f8b825f6SPavel Labath   default:
552f8b825f6SPavel Labath     return llvm::createStringError(llvm::inconvertibleErrorCode(),
553f8b825f6SPavel Labath                                    "CPU type not supported!");
554f8b825f6SPavel Labath   }
555f8b825f6SPavel Labath }
556f8b825f6SPavel Labath 
55799f436b0SPavel Labath size_t NativeProcessProtocol::GetSoftwareBreakpointPCOffset() {
55899f436b0SPavel Labath   switch (GetArchitecture().GetMachine()) {
55999f436b0SPavel Labath   case llvm::Triple::x86:
56099f436b0SPavel Labath   case llvm::Triple::x86_64:
56199f436b0SPavel Labath   case llvm::Triple::systemz:
56299f436b0SPavel Labath     // These architectures report increment the PC after breakpoint is hit.
56399f436b0SPavel Labath     return cantFail(GetSoftwareBreakpointTrapOpcode(0)).size();
56499f436b0SPavel Labath 
56599f436b0SPavel Labath   case llvm::Triple::arm:
56699f436b0SPavel Labath   case llvm::Triple::aarch64:
5677dd7a360SJason Molenda   case llvm::Triple::aarch64_32:
56899f436b0SPavel Labath   case llvm::Triple::mips64:
56999f436b0SPavel Labath   case llvm::Triple::mips64el:
57099f436b0SPavel Labath   case llvm::Triple::mips:
57199f436b0SPavel Labath   case llvm::Triple::mipsel:
57299f436b0SPavel Labath   case llvm::Triple::ppc64le:
57399f436b0SPavel Labath     // On these architectures the PC doesn't get updated for breakpoint hits.
57499f436b0SPavel Labath     return 0;
57599f436b0SPavel Labath 
57699f436b0SPavel Labath   default:
57799f436b0SPavel Labath     llvm_unreachable("CPU type not supported!");
57899f436b0SPavel Labath   }
57999f436b0SPavel Labath }
58099f436b0SPavel Labath 
581aef7908fSPavel Labath void NativeProcessProtocol::FixupBreakpointPCAsNeeded(
582aef7908fSPavel Labath     NativeThreadProtocol &thread) {
583aef7908fSPavel Labath   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS);
584aef7908fSPavel Labath 
585aef7908fSPavel Labath   Status error;
586aef7908fSPavel Labath 
587aef7908fSPavel Labath   // Find out the size of a breakpoint (might depend on where we are in the
588aef7908fSPavel Labath   // code).
589aef7908fSPavel Labath   NativeRegisterContext &context = thread.GetRegisterContext();
590aef7908fSPavel Labath 
591aef7908fSPavel Labath   uint32_t breakpoint_size = GetSoftwareBreakpointPCOffset();
592aef7908fSPavel Labath   LLDB_LOG(log, "breakpoint size: {0}", breakpoint_size);
593aef7908fSPavel Labath   if (breakpoint_size == 0)
594aef7908fSPavel Labath     return;
595aef7908fSPavel Labath 
596aef7908fSPavel Labath   // First try probing for a breakpoint at a software breakpoint location: PC -
597aef7908fSPavel Labath   // breakpoint size.
598aef7908fSPavel Labath   const lldb::addr_t initial_pc_addr = context.GetPCfromBreakpointLocation();
599aef7908fSPavel Labath   lldb::addr_t breakpoint_addr = initial_pc_addr;
600aef7908fSPavel Labath   // Do not allow breakpoint probe to wrap around.
601aef7908fSPavel Labath   if (breakpoint_addr >= breakpoint_size)
602aef7908fSPavel Labath     breakpoint_addr -= breakpoint_size;
603aef7908fSPavel Labath 
604be828518SPavel Labath   if (m_software_breakpoints.count(breakpoint_addr) == 0) {
605aef7908fSPavel Labath     // We didn't find one at a software probe location.  Nothing to do.
606aef7908fSPavel Labath     LLDB_LOG(log,
607be828518SPavel Labath              "pid {0} no lldb software breakpoint found at current pc with "
608aef7908fSPavel Labath              "adjustment: {1}",
609aef7908fSPavel Labath              GetID(), breakpoint_addr);
610aef7908fSPavel Labath     return;
611aef7908fSPavel Labath   }
612aef7908fSPavel Labath 
613aef7908fSPavel Labath   //
614aef7908fSPavel Labath   // We have a software breakpoint and need to adjust the PC.
615aef7908fSPavel Labath   //
616aef7908fSPavel Labath 
617aef7908fSPavel Labath   // Change the program counter.
618aef7908fSPavel Labath   LLDB_LOG(log, "pid {0} tid {1}: changing PC from {2:x} to {3:x}", GetID(),
619aef7908fSPavel Labath            thread.GetID(), initial_pc_addr, breakpoint_addr);
620aef7908fSPavel Labath 
621aef7908fSPavel Labath   error = context.SetPC(breakpoint_addr);
622aef7908fSPavel Labath   if (error.Fail()) {
623aef7908fSPavel Labath     // This can happen in case the process was killed between the time we read
624aef7908fSPavel Labath     // the PC and when we are updating it. There's nothing better to do than to
625aef7908fSPavel Labath     // swallow the error.
626aef7908fSPavel Labath     LLDB_LOG(log, "pid {0} tid {1}: failed to set PC: {2}", GetID(),
627aef7908fSPavel Labath              thread.GetID(), error);
628aef7908fSPavel Labath   }
629aef7908fSPavel Labath }
630aef7908fSPavel Labath 
63197206d57SZachary Turner Status NativeProcessProtocol::RemoveBreakpoint(lldb::addr_t addr,
632d5ffbad2SOmair Javaid                                                bool hardware) {
633d5ffbad2SOmair Javaid   if (hardware)
634d5ffbad2SOmair Javaid     return RemoveHardwareBreakpoint(addr);
635d5ffbad2SOmair Javaid   else
636be828518SPavel Labath     return RemoveSoftwareBreakpoint(addr);
637af245d11STodd Fiala }
638af245d11STodd Fiala 
6392ce26527SPavel Labath Status NativeProcessProtocol::ReadMemoryWithoutTrap(lldb::addr_t addr,
6402ce26527SPavel Labath                                                     void *buf, size_t size,
6412ce26527SPavel Labath                                                     size_t &bytes_read) {
6422ce26527SPavel Labath   Status error = ReadMemory(addr, buf, size, bytes_read);
6432ce26527SPavel Labath   if (error.Fail())
6442ce26527SPavel Labath     return error;
645be828518SPavel Labath 
646be828518SPavel Labath   auto data =
647be828518SPavel Labath       llvm::makeMutableArrayRef(static_cast<uint8_t *>(buf), bytes_read);
648be828518SPavel Labath   for (const auto &pair : m_software_breakpoints) {
649be828518SPavel Labath     lldb::addr_t bp_addr = pair.first;
650be828518SPavel Labath     auto saved_opcodes = makeArrayRef(pair.second.saved_opcodes);
651be828518SPavel Labath 
652be828518SPavel Labath     if (bp_addr + saved_opcodes.size() < addr || addr + bytes_read <= bp_addr)
653be828518SPavel Labath       continue; // Breapoint not in range, ignore
654be828518SPavel Labath 
655be828518SPavel Labath     if (bp_addr < addr) {
656be828518SPavel Labath       saved_opcodes = saved_opcodes.drop_front(addr - bp_addr);
657be828518SPavel Labath       bp_addr = addr;
658be828518SPavel Labath     }
659be828518SPavel Labath     auto bp_data = data.drop_front(bp_addr - addr);
660be828518SPavel Labath     std::copy_n(saved_opcodes.begin(),
661be828518SPavel Labath                 std::min(saved_opcodes.size(), bp_data.size()),
662be828518SPavel Labath                 bp_data.begin());
663be828518SPavel Labath   }
664be828518SPavel Labath   return Status();
665be828518SPavel Labath }
666be828518SPavel Labath 
66770795c1eSAntonio Afonso llvm::Expected<llvm::StringRef>
66870795c1eSAntonio Afonso NativeProcessProtocol::ReadCStringFromMemory(lldb::addr_t addr, char *buffer,
66970795c1eSAntonio Afonso                                              size_t max_size,
67070795c1eSAntonio Afonso                                              size_t &total_bytes_read) {
67170795c1eSAntonio Afonso   static const size_t cache_line_size =
67270795c1eSAntonio Afonso       llvm::sys::Process::getPageSizeEstimate();
67370795c1eSAntonio Afonso   size_t bytes_read = 0;
67470795c1eSAntonio Afonso   size_t bytes_left = max_size;
67570795c1eSAntonio Afonso   addr_t curr_addr = addr;
67670795c1eSAntonio Afonso   size_t string_size;
67770795c1eSAntonio Afonso   char *curr_buffer = buffer;
67870795c1eSAntonio Afonso   total_bytes_read = 0;
67970795c1eSAntonio Afonso   Status status;
68070795c1eSAntonio Afonso 
68170795c1eSAntonio Afonso   while (bytes_left > 0 && status.Success()) {
68270795c1eSAntonio Afonso     addr_t cache_line_bytes_left =
68370795c1eSAntonio Afonso         cache_line_size - (curr_addr % cache_line_size);
68470795c1eSAntonio Afonso     addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
685*65fdb342SRaphael Isemann     status = ReadMemory(curr_addr, static_cast<void *>(curr_buffer),
68670795c1eSAntonio Afonso                         bytes_to_read, bytes_read);
68770795c1eSAntonio Afonso 
68870795c1eSAntonio Afonso     if (bytes_read == 0)
68970795c1eSAntonio Afonso       break;
69070795c1eSAntonio Afonso 
69170795c1eSAntonio Afonso     void *str_end = std::memchr(curr_buffer, '\0', bytes_read);
69270795c1eSAntonio Afonso     if (str_end != nullptr) {
69370795c1eSAntonio Afonso       total_bytes_read =
694*65fdb342SRaphael Isemann           static_cast<size_t>((static_cast<char *>(str_end) - buffer + 1));
69570795c1eSAntonio Afonso       status.Clear();
69670795c1eSAntonio Afonso       break;
69770795c1eSAntonio Afonso     }
69870795c1eSAntonio Afonso 
69970795c1eSAntonio Afonso     total_bytes_read += bytes_read;
70070795c1eSAntonio Afonso     curr_buffer += bytes_read;
70170795c1eSAntonio Afonso     curr_addr += bytes_read;
70270795c1eSAntonio Afonso     bytes_left -= bytes_read;
70370795c1eSAntonio Afonso   }
70470795c1eSAntonio Afonso 
70570795c1eSAntonio Afonso   string_size = total_bytes_read - 1;
70670795c1eSAntonio Afonso 
70770795c1eSAntonio Afonso   // Make sure we return a null terminated string.
70870795c1eSAntonio Afonso   if (bytes_left == 0 && max_size > 0 && buffer[max_size - 1] != '\0') {
70970795c1eSAntonio Afonso     buffer[max_size - 1] = '\0';
71070795c1eSAntonio Afonso     total_bytes_read--;
71170795c1eSAntonio Afonso   }
71270795c1eSAntonio Afonso 
71370795c1eSAntonio Afonso   if (!status.Success())
71470795c1eSAntonio Afonso     return status.ToError();
71570795c1eSAntonio Afonso 
71670795c1eSAntonio Afonso   return llvm::StringRef(buffer, string_size);
71770795c1eSAntonio Afonso }
71870795c1eSAntonio Afonso 
719be828518SPavel Labath lldb::StateType NativeProcessProtocol::GetState() const {
720be828518SPavel Labath   std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
721be828518SPavel Labath   return m_state;
7222ce26527SPavel Labath }
7232ce26527SPavel Labath 
724b9c1b51eSKate Stone void NativeProcessProtocol::SetState(lldb::StateType state,
725b9c1b51eSKate Stone                                      bool notify_delegates) {
72616ff8604SSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
7275830aa75STamas Berghammer 
7285830aa75STamas Berghammer   if (state == m_state)
7295830aa75STamas Berghammer     return;
7305830aa75STamas Berghammer 
731af245d11STodd Fiala   m_state = state;
732af245d11STodd Fiala 
733b9c1b51eSKate Stone   if (StateIsStoppedState(state, false)) {
734af245d11STodd Fiala     ++m_stop_id;
735af245d11STodd Fiala 
736af245d11STodd Fiala     // Give process a chance to do any stop id bump processing, such as
737af245d11STodd Fiala     // clearing cached data that is invalidated each time the process runs.
73805097246SAdrian Prantl     // Note if/when we support some threads running, we'll end up needing to
73905097246SAdrian Prantl     // manage this per thread and per process.
740af245d11STodd Fiala     DoStopIDBumped(m_stop_id);
741af245d11STodd Fiala   }
742af245d11STodd Fiala 
743af245d11STodd Fiala   // Optionally notify delegates of the state change.
744af245d11STodd Fiala   if (notify_delegates)
745af245d11STodd Fiala     SynchronouslyNotifyProcessStateChanged(state);
746af245d11STodd Fiala }
747af245d11STodd Fiala 
748b9c1b51eSKate Stone uint32_t NativeProcessProtocol::GetStopID() const {
74916ff8604SSaleem Abdulrasool   std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
750af245d11STodd Fiala   return m_stop_id;
751af245d11STodd Fiala }
752af245d11STodd Fiala 
753b9c1b51eSKate Stone void NativeProcessProtocol::DoStopIDBumped(uint32_t /* newBumpId */) {
754af245d11STodd Fiala   // Default implementation does nothing.
755af245d11STodd Fiala }
7568bc34f4dSOleksiy Vyalov 
75796e600fcSPavel Labath NativeProcessProtocol::Factory::~Factory() = default;
758