xref: /freebsd/contrib/llvm-project/lldb/source/Host/common/NativeProcessProtocol.cpp (revision 3e8eb5c7f4909209c042403ddee340b2ee7003a5)
1 //===-- NativeProcessProtocol.cpp -----------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "lldb/Host/common/NativeProcessProtocol.h"
10 #include "lldb/Host/Host.h"
11 #include "lldb/Host/common/NativeBreakpointList.h"
12 #include "lldb/Host/common/NativeRegisterContext.h"
13 #include "lldb/Host/common/NativeThreadProtocol.h"
14 #include "lldb/Utility/LLDBAssert.h"
15 #include "lldb/Utility/Log.h"
16 #include "lldb/Utility/State.h"
17 #include "lldb/lldb-enumerations.h"
18 
19 #include "llvm/Support/Process.h"
20 
21 using namespace lldb;
22 using namespace lldb_private;
23 
24 // NativeProcessProtocol Members
25 
26 NativeProcessProtocol::NativeProcessProtocol(lldb::pid_t pid, int terminal_fd,
27                                              NativeDelegate &delegate)
28     : m_pid(pid), m_delegate(delegate), m_terminal_fd(terminal_fd) {
29   delegate.InitializeDelegate(this);
30 }
31 
32 lldb_private::Status NativeProcessProtocol::Interrupt() {
33   Status error;
34 #if !defined(SIGSTOP)
35   error.SetErrorString("local host does not support signaling");
36   return error;
37 #else
38   return Signal(SIGSTOP);
39 #endif
40 }
41 
42 Status NativeProcessProtocol::IgnoreSignals(llvm::ArrayRef<int> signals) {
43   m_signals_to_ignore.clear();
44   m_signals_to_ignore.insert(signals.begin(), signals.end());
45   return Status();
46 }
47 
48 lldb_private::Status
49 NativeProcessProtocol::GetMemoryRegionInfo(lldb::addr_t load_addr,
50                                            MemoryRegionInfo &range_info) {
51   // Default: not implemented.
52   return Status("not implemented");
53 }
54 
55 lldb_private::Status
56 NativeProcessProtocol::ReadMemoryTags(int32_t type, lldb::addr_t addr,
57                                       size_t len, std::vector<uint8_t> &tags) {
58   return Status("not implemented");
59 }
60 
61 lldb_private::Status
62 NativeProcessProtocol::WriteMemoryTags(int32_t type, lldb::addr_t addr,
63                                        size_t len,
64                                        const std::vector<uint8_t> &tags) {
65   return Status("not implemented");
66 }
67 
68 llvm::Optional<WaitStatus> NativeProcessProtocol::GetExitStatus() {
69   if (m_state == lldb::eStateExited)
70     return m_exit_status;
71 
72   return llvm::None;
73 }
74 
75 bool NativeProcessProtocol::SetExitStatus(WaitStatus status,
76                                           bool bNotifyStateChange) {
77   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
78   LLDB_LOG(log, "status = {0}, notify = {1}", status, bNotifyStateChange);
79 
80   // Exit status already set
81   if (m_state == lldb::eStateExited) {
82     if (m_exit_status)
83       LLDB_LOG(log, "exit status already set to {0}", *m_exit_status);
84     else
85       LLDB_LOG(log, "state is exited, but status not set");
86     return false;
87   }
88 
89   m_state = lldb::eStateExited;
90   m_exit_status = status;
91 
92   if (bNotifyStateChange)
93     SynchronouslyNotifyProcessStateChanged(lldb::eStateExited);
94 
95   return true;
96 }
97 
98 NativeThreadProtocol *NativeProcessProtocol::GetThreadAtIndex(uint32_t idx) {
99   std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
100   if (idx < m_threads.size())
101     return m_threads[idx].get();
102   return nullptr;
103 }
104 
105 NativeThreadProtocol *
106 NativeProcessProtocol::GetThreadByIDUnlocked(lldb::tid_t tid) {
107   for (const auto &thread : m_threads) {
108     if (thread->GetID() == tid)
109       return thread.get();
110   }
111   return nullptr;
112 }
113 
114 NativeThreadProtocol *NativeProcessProtocol::GetThreadByID(lldb::tid_t tid) {
115   std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
116   return GetThreadByIDUnlocked(tid);
117 }
118 
119 bool NativeProcessProtocol::IsAlive() const {
120   return m_state != eStateDetached && m_state != eStateExited &&
121          m_state != eStateInvalid && m_state != eStateUnloaded;
122 }
123 
124 const NativeWatchpointList::WatchpointMap &
125 NativeProcessProtocol::GetWatchpointMap() const {
126   return m_watchpoint_list.GetWatchpointMap();
127 }
128 
129 llvm::Optional<std::pair<uint32_t, uint32_t>>
130 NativeProcessProtocol::GetHardwareDebugSupportInfo() const {
131   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
132 
133   // get any thread
134   NativeThreadProtocol *thread(
135       const_cast<NativeProcessProtocol *>(this)->GetThreadAtIndex(0));
136   if (!thread) {
137     LLDB_LOG(log, "failed to find a thread to grab a NativeRegisterContext!");
138     return llvm::None;
139   }
140 
141   NativeRegisterContext &reg_ctx = thread->GetRegisterContext();
142   return std::make_pair(reg_ctx.NumSupportedHardwareBreakpoints(),
143                         reg_ctx.NumSupportedHardwareWatchpoints());
144 }
145 
146 Status NativeProcessProtocol::SetWatchpoint(lldb::addr_t addr, size_t size,
147                                             uint32_t watch_flags,
148                                             bool hardware) {
149   // This default implementation assumes setting the watchpoint for the process
150   // will require setting the watchpoint for each of the threads.  Furthermore,
151   // it will track watchpoints set for the process and will add them to each
152   // thread that is attached to via the (FIXME implement) OnThreadAttached ()
153   // method.
154 
155   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
156 
157   // Update the thread list
158   UpdateThreads();
159 
160   // Keep track of the threads we successfully set the watchpoint for.  If one
161   // of the thread watchpoint setting operations fails, back off and remove the
162   // watchpoint for all the threads that were successfully set so we get back
163   // to a consistent state.
164   std::vector<NativeThreadProtocol *> watchpoint_established_threads;
165 
166   // Tell each thread to set a watchpoint.  In the event that hardware
167   // watchpoints are requested but the SetWatchpoint fails, try to set a
168   // software watchpoint as a fallback.  It's conceivable that if there are
169   // more threads than hardware watchpoints available, some of the threads will
170   // fail to set hardware watchpoints while software ones may be available.
171   std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
172   for (const auto &thread : m_threads) {
173     assert(thread && "thread list should not have a NULL thread!");
174 
175     Status thread_error =
176         thread->SetWatchpoint(addr, size, watch_flags, hardware);
177     if (thread_error.Fail() && hardware) {
178       // Try software watchpoints since we failed on hardware watchpoint
179       // setting and we may have just run out of hardware watchpoints.
180       thread_error = thread->SetWatchpoint(addr, size, watch_flags, false);
181       if (thread_error.Success())
182         LLDB_LOG(log,
183                  "hardware watchpoint requested but software watchpoint set");
184     }
185 
186     if (thread_error.Success()) {
187       // Remember that we set this watchpoint successfully in case we need to
188       // clear it later.
189       watchpoint_established_threads.push_back(thread.get());
190     } else {
191       // Unset the watchpoint for each thread we successfully set so that we
192       // get back to a consistent state of "not set" for the watchpoint.
193       for (auto unwatch_thread_sp : watchpoint_established_threads) {
194         Status remove_error = unwatch_thread_sp->RemoveWatchpoint(addr);
195         if (remove_error.Fail())
196           LLDB_LOG(log, "RemoveWatchpoint failed for pid={0}, tid={1}: {2}",
197                    GetID(), unwatch_thread_sp->GetID(), remove_error);
198       }
199 
200       return thread_error;
201     }
202   }
203   return m_watchpoint_list.Add(addr, size, watch_flags, hardware);
204 }
205 
206 Status NativeProcessProtocol::RemoveWatchpoint(lldb::addr_t addr) {
207   // Update the thread list
208   UpdateThreads();
209 
210   Status overall_error;
211 
212   std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
213   for (const auto &thread : m_threads) {
214     assert(thread && "thread list should not have a NULL thread!");
215 
216     const Status thread_error = thread->RemoveWatchpoint(addr);
217     if (thread_error.Fail()) {
218       // Keep track of the first thread error if any threads fail. We want to
219       // try to remove the watchpoint from every thread, though, even if one or
220       // more have errors.
221       if (!overall_error.Fail())
222         overall_error = thread_error;
223     }
224   }
225   const Status error = m_watchpoint_list.Remove(addr);
226   return overall_error.Fail() ? overall_error : error;
227 }
228 
229 const HardwareBreakpointMap &
230 NativeProcessProtocol::GetHardwareBreakpointMap() const {
231   return m_hw_breakpoints_map;
232 }
233 
234 Status NativeProcessProtocol::SetHardwareBreakpoint(lldb::addr_t addr,
235                                                     size_t size) {
236   // This default implementation assumes setting a hardware breakpoint for this
237   // process will require setting same hardware breakpoint for each of its
238   // existing threads. New thread will do the same once created.
239   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
240 
241   // Update the thread list
242   UpdateThreads();
243 
244   // Exit here if target does not have required hardware breakpoint capability.
245   auto hw_debug_cap = GetHardwareDebugSupportInfo();
246 
247   if (hw_debug_cap == llvm::None || hw_debug_cap->first == 0 ||
248       hw_debug_cap->first <= m_hw_breakpoints_map.size())
249     return Status("Target does not have required no of hardware breakpoints");
250 
251   // Vector below stores all thread pointer for which we have we successfully
252   // set this hardware breakpoint. If any of the current process threads fails
253   // to set this hardware breakpoint then roll back and remove this breakpoint
254   // for all the threads that had already set it successfully.
255   std::vector<NativeThreadProtocol *> breakpoint_established_threads;
256 
257   // Request to set a hardware breakpoint for each of current process threads.
258   std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
259   for (const auto &thread : m_threads) {
260     assert(thread && "thread list should not have a NULL thread!");
261 
262     Status thread_error = thread->SetHardwareBreakpoint(addr, size);
263     if (thread_error.Success()) {
264       // Remember that we set this breakpoint successfully in case we need to
265       // clear it later.
266       breakpoint_established_threads.push_back(thread.get());
267     } else {
268       // Unset the breakpoint for each thread we successfully set so that we
269       // get back to a consistent state of "not set" for this hardware
270       // breakpoint.
271       for (auto rollback_thread_sp : breakpoint_established_threads) {
272         Status remove_error =
273             rollback_thread_sp->RemoveHardwareBreakpoint(addr);
274         if (remove_error.Fail())
275           LLDB_LOG(log,
276                    "RemoveHardwareBreakpoint failed for pid={0}, tid={1}: {2}",
277                    GetID(), rollback_thread_sp->GetID(), remove_error);
278       }
279 
280       return thread_error;
281     }
282   }
283 
284   // Register new hardware breakpoint into hardware breakpoints map of current
285   // process.
286   m_hw_breakpoints_map[addr] = {addr, size};
287 
288   return Status();
289 }
290 
291 Status NativeProcessProtocol::RemoveHardwareBreakpoint(lldb::addr_t addr) {
292   // Update the thread list
293   UpdateThreads();
294 
295   Status error;
296 
297   std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
298   for (const auto &thread : m_threads) {
299     assert(thread && "thread list should not have a NULL thread!");
300     error = thread->RemoveHardwareBreakpoint(addr);
301   }
302 
303   // Also remove from hardware breakpoint map of current process.
304   m_hw_breakpoints_map.erase(addr);
305 
306   return error;
307 }
308 
309 void NativeProcessProtocol::SynchronouslyNotifyProcessStateChanged(
310     lldb::StateType state) {
311   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
312 
313   m_delegate.ProcessStateChanged(this, state);
314 
315   LLDB_LOG(log, "sent state notification [{0}] from process {1}", state,
316            GetID());
317 }
318 
319 void NativeProcessProtocol::NotifyDidExec() {
320   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
321   LLDB_LOG(log, "process {0} exec()ed", GetID());
322 
323   m_delegate.DidExec(this);
324 }
325 
326 Status NativeProcessProtocol::SetSoftwareBreakpoint(lldb::addr_t addr,
327                                                     uint32_t size_hint) {
328   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
329   LLDB_LOG(log, "addr = {0:x}, size_hint = {1}", addr, size_hint);
330 
331   auto it = m_software_breakpoints.find(addr);
332   if (it != m_software_breakpoints.end()) {
333     ++it->second.ref_count;
334     return Status();
335   }
336   auto expected_bkpt = EnableSoftwareBreakpoint(addr, size_hint);
337   if (!expected_bkpt)
338     return Status(expected_bkpt.takeError());
339 
340   m_software_breakpoints.emplace(addr, std::move(*expected_bkpt));
341   return Status();
342 }
343 
344 Status NativeProcessProtocol::RemoveSoftwareBreakpoint(lldb::addr_t addr) {
345   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
346   LLDB_LOG(log, "addr = {0:x}", addr);
347   auto it = m_software_breakpoints.find(addr);
348   if (it == m_software_breakpoints.end())
349     return Status("Breakpoint not found.");
350   assert(it->second.ref_count > 0);
351   if (--it->second.ref_count > 0)
352     return Status();
353 
354   // This is the last reference. Let's remove the breakpoint.
355   Status error;
356 
357   // Clear a software breakpoint instruction
358   llvm::SmallVector<uint8_t, 4> curr_break_op(
359       it->second.breakpoint_opcodes.size(), 0);
360 
361   // Read the breakpoint opcode
362   size_t bytes_read = 0;
363   error =
364       ReadMemory(addr, curr_break_op.data(), curr_break_op.size(), bytes_read);
365   if (error.Fail() || bytes_read < curr_break_op.size()) {
366     return Status("addr=0x%" PRIx64
367                   ": tried to read %zu bytes but only read %zu",
368                   addr, curr_break_op.size(), bytes_read);
369   }
370   const auto &saved = it->second.saved_opcodes;
371   // Make sure the breakpoint opcode exists at this address
372   if (makeArrayRef(curr_break_op) != it->second.breakpoint_opcodes) {
373     if (curr_break_op != it->second.saved_opcodes)
374       return Status("Original breakpoint trap is no longer in memory.");
375     LLDB_LOG(log,
376              "Saved opcodes ({0:@[x]}) have already been restored at {1:x}.",
377              llvm::make_range(saved.begin(), saved.end()), addr);
378   } else {
379     // We found a valid breakpoint opcode at this address, now restore the
380     // saved opcode.
381     size_t bytes_written = 0;
382     error = WriteMemory(addr, saved.data(), saved.size(), bytes_written);
383     if (error.Fail() || bytes_written < saved.size()) {
384       return Status("addr=0x%" PRIx64
385                     ": tried to write %zu bytes but only wrote %zu",
386                     addr, saved.size(), bytes_written);
387     }
388 
389     // Verify that our original opcode made it back to the inferior
390     llvm::SmallVector<uint8_t, 4> verify_opcode(saved.size(), 0);
391     size_t verify_bytes_read = 0;
392     error = ReadMemory(addr, verify_opcode.data(), verify_opcode.size(),
393                        verify_bytes_read);
394     if (error.Fail() || verify_bytes_read < verify_opcode.size()) {
395       return Status("addr=0x%" PRIx64
396                     ": tried to read %zu verification bytes but only read %zu",
397                     addr, verify_opcode.size(), verify_bytes_read);
398     }
399     if (verify_opcode != saved)
400       LLDB_LOG(log, "Restoring bytes at {0:x}: {1:@[x]}", addr,
401                llvm::make_range(saved.begin(), saved.end()));
402   }
403 
404   m_software_breakpoints.erase(it);
405   return Status();
406 }
407 
408 llvm::Expected<NativeProcessProtocol::SoftwareBreakpoint>
409 NativeProcessProtocol::EnableSoftwareBreakpoint(lldb::addr_t addr,
410                                                 uint32_t size_hint) {
411   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
412 
413   auto expected_trap = GetSoftwareBreakpointTrapOpcode(size_hint);
414   if (!expected_trap)
415     return expected_trap.takeError();
416 
417   llvm::SmallVector<uint8_t, 4> saved_opcode_bytes(expected_trap->size(), 0);
418   // Save the original opcodes by reading them so we can restore later.
419   size_t bytes_read = 0;
420   Status error = ReadMemory(addr, saved_opcode_bytes.data(),
421                             saved_opcode_bytes.size(), bytes_read);
422   if (error.Fail())
423     return error.ToError();
424 
425   // Ensure we read as many bytes as we expected.
426   if (bytes_read != saved_opcode_bytes.size()) {
427     return llvm::createStringError(
428         llvm::inconvertibleErrorCode(),
429         "Failed to read memory while attempting to set breakpoint: attempted "
430         "to read {0} bytes but only read {1}.",
431         saved_opcode_bytes.size(), bytes_read);
432   }
433 
434   LLDB_LOG(
435       log, "Overwriting bytes at {0:x}: {1:@[x]}", addr,
436       llvm::make_range(saved_opcode_bytes.begin(), saved_opcode_bytes.end()));
437 
438   // Write a software breakpoint in place of the original opcode.
439   size_t bytes_written = 0;
440   error = WriteMemory(addr, expected_trap->data(), expected_trap->size(),
441                       bytes_written);
442   if (error.Fail())
443     return error.ToError();
444 
445   // Ensure we wrote as many bytes as we expected.
446   if (bytes_written != expected_trap->size()) {
447     return llvm::createStringError(
448         llvm::inconvertibleErrorCode(),
449         "Failed write memory while attempting to set "
450         "breakpoint: attempted to write {0} bytes but only wrote {1}",
451         expected_trap->size(), bytes_written);
452   }
453 
454   llvm::SmallVector<uint8_t, 4> verify_bp_opcode_bytes(expected_trap->size(),
455                                                        0);
456   size_t verify_bytes_read = 0;
457   error = ReadMemory(addr, verify_bp_opcode_bytes.data(),
458                      verify_bp_opcode_bytes.size(), verify_bytes_read);
459   if (error.Fail())
460     return error.ToError();
461 
462   // Ensure we read as many verification bytes as we expected.
463   if (verify_bytes_read != verify_bp_opcode_bytes.size()) {
464     return llvm::createStringError(
465         llvm::inconvertibleErrorCode(),
466         "Failed to read memory while "
467         "attempting to verify breakpoint: attempted to read {0} bytes "
468         "but only read {1}",
469         verify_bp_opcode_bytes.size(), verify_bytes_read);
470   }
471 
472   if (llvm::makeArrayRef(verify_bp_opcode_bytes.data(), verify_bytes_read) !=
473       *expected_trap) {
474     return llvm::createStringError(
475         llvm::inconvertibleErrorCode(),
476         "Verification of software breakpoint "
477         "writing failed - trap opcodes not successfully read back "
478         "after writing when setting breakpoint at {0:x}",
479         addr);
480   }
481 
482   LLDB_LOG(log, "addr = {0:x}: SUCCESS", addr);
483   return SoftwareBreakpoint{1, saved_opcode_bytes, *expected_trap};
484 }
485 
486 llvm::Expected<llvm::ArrayRef<uint8_t>>
487 NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_t size_hint) {
488   static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
489   static const uint8_t g_i386_opcode[] = {0xCC};
490   static const uint8_t g_mips64_opcode[] = {0x00, 0x00, 0x00, 0x0d};
491   static const uint8_t g_mips64el_opcode[] = {0x0d, 0x00, 0x00, 0x00};
492   static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
493   static const uint8_t g_ppc_opcode[] = {0x7f, 0xe0, 0x00, 0x08}; // trap
494   static const uint8_t g_ppcle_opcode[] = {0x08, 0x00, 0xe0, 0x7f}; // trap
495 
496   switch (GetArchitecture().GetMachine()) {
497   case llvm::Triple::aarch64:
498   case llvm::Triple::aarch64_32:
499     return llvm::makeArrayRef(g_aarch64_opcode);
500 
501   case llvm::Triple::x86:
502   case llvm::Triple::x86_64:
503     return llvm::makeArrayRef(g_i386_opcode);
504 
505   case llvm::Triple::mips:
506   case llvm::Triple::mips64:
507     return llvm::makeArrayRef(g_mips64_opcode);
508 
509   case llvm::Triple::mipsel:
510   case llvm::Triple::mips64el:
511     return llvm::makeArrayRef(g_mips64el_opcode);
512 
513   case llvm::Triple::systemz:
514     return llvm::makeArrayRef(g_s390x_opcode);
515 
516   case llvm::Triple::ppc:
517   case llvm::Triple::ppc64:
518     return llvm::makeArrayRef(g_ppc_opcode);
519 
520   case llvm::Triple::ppc64le:
521     return llvm::makeArrayRef(g_ppcle_opcode);
522 
523   default:
524     return llvm::createStringError(llvm::inconvertibleErrorCode(),
525                                    "CPU type not supported!");
526   }
527 }
528 
529 size_t NativeProcessProtocol::GetSoftwareBreakpointPCOffset() {
530   switch (GetArchitecture().GetMachine()) {
531   case llvm::Triple::x86:
532   case llvm::Triple::x86_64:
533   case llvm::Triple::systemz:
534     // These architectures report increment the PC after breakpoint is hit.
535     return cantFail(GetSoftwareBreakpointTrapOpcode(0)).size();
536 
537   case llvm::Triple::arm:
538   case llvm::Triple::aarch64:
539   case llvm::Triple::aarch64_32:
540   case llvm::Triple::mips64:
541   case llvm::Triple::mips64el:
542   case llvm::Triple::mips:
543   case llvm::Triple::mipsel:
544   case llvm::Triple::ppc:
545   case llvm::Triple::ppc64:
546   case llvm::Triple::ppc64le:
547     // On these architectures the PC doesn't get updated for breakpoint hits.
548     return 0;
549 
550   default:
551     llvm_unreachable("CPU type not supported!");
552   }
553 }
554 
555 void NativeProcessProtocol::FixupBreakpointPCAsNeeded(
556     NativeThreadProtocol &thread) {
557   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS);
558 
559   Status error;
560 
561   // Find out the size of a breakpoint (might depend on where we are in the
562   // code).
563   NativeRegisterContext &context = thread.GetRegisterContext();
564 
565   uint32_t breakpoint_size = GetSoftwareBreakpointPCOffset();
566   LLDB_LOG(log, "breakpoint size: {0}", breakpoint_size);
567   if (breakpoint_size == 0)
568     return;
569 
570   // First try probing for a breakpoint at a software breakpoint location: PC -
571   // breakpoint size.
572   const lldb::addr_t initial_pc_addr = context.GetPCfromBreakpointLocation();
573   lldb::addr_t breakpoint_addr = initial_pc_addr;
574   // Do not allow breakpoint probe to wrap around.
575   if (breakpoint_addr >= breakpoint_size)
576     breakpoint_addr -= breakpoint_size;
577 
578   if (m_software_breakpoints.count(breakpoint_addr) == 0) {
579     // We didn't find one at a software probe location.  Nothing to do.
580     LLDB_LOG(log,
581              "pid {0} no lldb software breakpoint found at current pc with "
582              "adjustment: {1}",
583              GetID(), breakpoint_addr);
584     return;
585   }
586 
587   //
588   // We have a software breakpoint and need to adjust the PC.
589   //
590 
591   // Change the program counter.
592   LLDB_LOG(log, "pid {0} tid {1}: changing PC from {2:x} to {3:x}", GetID(),
593            thread.GetID(), initial_pc_addr, breakpoint_addr);
594 
595   error = context.SetPC(breakpoint_addr);
596   if (error.Fail()) {
597     // This can happen in case the process was killed between the time we read
598     // the PC and when we are updating it. There's nothing better to do than to
599     // swallow the error.
600     LLDB_LOG(log, "pid {0} tid {1}: failed to set PC: {2}", GetID(),
601              thread.GetID(), error);
602   }
603 }
604 
605 Status NativeProcessProtocol::RemoveBreakpoint(lldb::addr_t addr,
606                                                bool hardware) {
607   if (hardware)
608     return RemoveHardwareBreakpoint(addr);
609   else
610     return RemoveSoftwareBreakpoint(addr);
611 }
612 
613 Status NativeProcessProtocol::ReadMemoryWithoutTrap(lldb::addr_t addr,
614                                                     void *buf, size_t size,
615                                                     size_t &bytes_read) {
616   Status error = ReadMemory(addr, buf, size, bytes_read);
617   if (error.Fail())
618     return error;
619 
620   auto data =
621       llvm::makeMutableArrayRef(static_cast<uint8_t *>(buf), bytes_read);
622   for (const auto &pair : m_software_breakpoints) {
623     lldb::addr_t bp_addr = pair.first;
624     auto saved_opcodes = makeArrayRef(pair.second.saved_opcodes);
625 
626     if (bp_addr + saved_opcodes.size() < addr || addr + bytes_read <= bp_addr)
627       continue; // Breakpoint not in range, ignore
628 
629     if (bp_addr < addr) {
630       saved_opcodes = saved_opcodes.drop_front(addr - bp_addr);
631       bp_addr = addr;
632     }
633     auto bp_data = data.drop_front(bp_addr - addr);
634     std::copy_n(saved_opcodes.begin(),
635                 std::min(saved_opcodes.size(), bp_data.size()),
636                 bp_data.begin());
637   }
638   return Status();
639 }
640 
641 llvm::Expected<llvm::StringRef>
642 NativeProcessProtocol::ReadCStringFromMemory(lldb::addr_t addr, char *buffer,
643                                              size_t max_size,
644                                              size_t &total_bytes_read) {
645   static const size_t cache_line_size =
646       llvm::sys::Process::getPageSizeEstimate();
647   size_t bytes_read = 0;
648   size_t bytes_left = max_size;
649   addr_t curr_addr = addr;
650   size_t string_size;
651   char *curr_buffer = buffer;
652   total_bytes_read = 0;
653   Status status;
654 
655   while (bytes_left > 0 && status.Success()) {
656     addr_t cache_line_bytes_left =
657         cache_line_size - (curr_addr % cache_line_size);
658     addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
659     status = ReadMemory(curr_addr, static_cast<void *>(curr_buffer),
660                         bytes_to_read, bytes_read);
661 
662     if (bytes_read == 0)
663       break;
664 
665     void *str_end = std::memchr(curr_buffer, '\0', bytes_read);
666     if (str_end != nullptr) {
667       total_bytes_read =
668           static_cast<size_t>((static_cast<char *>(str_end) - buffer + 1));
669       status.Clear();
670       break;
671     }
672 
673     total_bytes_read += bytes_read;
674     curr_buffer += bytes_read;
675     curr_addr += bytes_read;
676     bytes_left -= bytes_read;
677   }
678 
679   string_size = total_bytes_read - 1;
680 
681   // Make sure we return a null terminated string.
682   if (bytes_left == 0 && max_size > 0 && buffer[max_size - 1] != '\0') {
683     buffer[max_size - 1] = '\0';
684     total_bytes_read--;
685   }
686 
687   if (!status.Success())
688     return status.ToError();
689 
690   return llvm::StringRef(buffer, string_size);
691 }
692 
693 lldb::StateType NativeProcessProtocol::GetState() const {
694   std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
695   return m_state;
696 }
697 
698 void NativeProcessProtocol::SetState(lldb::StateType state,
699                                      bool notify_delegates) {
700   std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
701 
702   if (state == m_state)
703     return;
704 
705   m_state = state;
706 
707   if (StateIsStoppedState(state, false)) {
708     ++m_stop_id;
709 
710     // Give process a chance to do any stop id bump processing, such as
711     // clearing cached data that is invalidated each time the process runs.
712     // Note if/when we support some threads running, we'll end up needing to
713     // manage this per thread and per process.
714     DoStopIDBumped(m_stop_id);
715   }
716 
717   // Optionally notify delegates of the state change.
718   if (notify_delegates)
719     SynchronouslyNotifyProcessStateChanged(state);
720 }
721 
722 uint32_t NativeProcessProtocol::GetStopID() const {
723   std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
724   return m_stop_id;
725 }
726 
727 void NativeProcessProtocol::DoStopIDBumped(uint32_t /* newBumpId */) {
728   // Default implementation does nothing.
729 }
730 
731 NativeProcessProtocol::Factory::~Factory() = default;
732