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