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   NotifyTracersProcessStateChanged(state);
316 
317   LLDB_LOG(log, "sent state notification [{0}] from process {1}", state,
318            GetID());
319 }
320 
321 void NativeProcessProtocol::NotifyDidExec() {
322   Log *log = GetLog(LLDBLog::Process);
323   LLDB_LOG(log, "process {0} exec()ed", GetID());
324 
325   m_software_breakpoints.clear();
326 
327   m_delegate.DidExec(this);
328 }
329 
330 Status NativeProcessProtocol::SetSoftwareBreakpoint(lldb::addr_t addr,
331                                                     uint32_t size_hint) {
332   Log *log = GetLog(LLDBLog::Breakpoints);
333   LLDB_LOG(log, "addr = {0:x}, size_hint = {1}", addr, size_hint);
334 
335   auto it = m_software_breakpoints.find(addr);
336   if (it != m_software_breakpoints.end()) {
337     ++it->second.ref_count;
338     return Status();
339   }
340   auto expected_bkpt = EnableSoftwareBreakpoint(addr, size_hint);
341   if (!expected_bkpt)
342     return Status(expected_bkpt.takeError());
343 
344   m_software_breakpoints.emplace(addr, std::move(*expected_bkpt));
345   return Status();
346 }
347 
348 Status NativeProcessProtocol::RemoveSoftwareBreakpoint(lldb::addr_t addr) {
349   Log *log = GetLog(LLDBLog::Breakpoints);
350   LLDB_LOG(log, "addr = {0:x}", addr);
351   auto it = m_software_breakpoints.find(addr);
352   if (it == m_software_breakpoints.end())
353     return Status("Breakpoint not found.");
354   assert(it->second.ref_count > 0);
355   if (--it->second.ref_count > 0)
356     return Status();
357 
358   // This is the last reference. Let's remove the breakpoint.
359   Status error;
360 
361   // Clear a software breakpoint instruction
362   llvm::SmallVector<uint8_t, 4> curr_break_op(
363       it->second.breakpoint_opcodes.size(), 0);
364 
365   // Read the breakpoint opcode
366   size_t bytes_read = 0;
367   error =
368       ReadMemory(addr, curr_break_op.data(), curr_break_op.size(), bytes_read);
369   if (error.Fail() || bytes_read < curr_break_op.size()) {
370     return Status("addr=0x%" PRIx64
371                   ": tried to read %zu bytes but only read %zu",
372                   addr, curr_break_op.size(), bytes_read);
373   }
374   const auto &saved = it->second.saved_opcodes;
375   // Make sure the breakpoint opcode exists at this address
376   if (makeArrayRef(curr_break_op) != it->second.breakpoint_opcodes) {
377     if (curr_break_op != it->second.saved_opcodes)
378       return Status("Original breakpoint trap is no longer in memory.");
379     LLDB_LOG(log,
380              "Saved opcodes ({0:@[x]}) have already been restored at {1:x}.",
381              llvm::make_range(saved.begin(), saved.end()), addr);
382   } else {
383     // We found a valid breakpoint opcode at this address, now restore the
384     // saved opcode.
385     size_t bytes_written = 0;
386     error = WriteMemory(addr, saved.data(), saved.size(), bytes_written);
387     if (error.Fail() || bytes_written < saved.size()) {
388       return Status("addr=0x%" PRIx64
389                     ": tried to write %zu bytes but only wrote %zu",
390                     addr, saved.size(), bytes_written);
391     }
392 
393     // Verify that our original opcode made it back to the inferior
394     llvm::SmallVector<uint8_t, 4> verify_opcode(saved.size(), 0);
395     size_t verify_bytes_read = 0;
396     error = ReadMemory(addr, verify_opcode.data(), verify_opcode.size(),
397                        verify_bytes_read);
398     if (error.Fail() || verify_bytes_read < verify_opcode.size()) {
399       return Status("addr=0x%" PRIx64
400                     ": tried to read %zu verification bytes but only read %zu",
401                     addr, verify_opcode.size(), verify_bytes_read);
402     }
403     if (verify_opcode != saved)
404       LLDB_LOG(log, "Restoring bytes at {0:x}: {1:@[x]}", addr,
405                llvm::make_range(saved.begin(), saved.end()));
406   }
407 
408   m_software_breakpoints.erase(it);
409   return Status();
410 }
411 
412 llvm::Expected<NativeProcessProtocol::SoftwareBreakpoint>
413 NativeProcessProtocol::EnableSoftwareBreakpoint(lldb::addr_t addr,
414                                                 uint32_t size_hint) {
415   Log *log = GetLog(LLDBLog::Breakpoints);
416 
417   auto expected_trap = GetSoftwareBreakpointTrapOpcode(size_hint);
418   if (!expected_trap)
419     return expected_trap.takeError();
420 
421   llvm::SmallVector<uint8_t, 4> saved_opcode_bytes(expected_trap->size(), 0);
422   // Save the original opcodes by reading them so we can restore later.
423   size_t bytes_read = 0;
424   Status error = ReadMemory(addr, saved_opcode_bytes.data(),
425                             saved_opcode_bytes.size(), bytes_read);
426   if (error.Fail())
427     return error.ToError();
428 
429   // Ensure we read as many bytes as we expected.
430   if (bytes_read != saved_opcode_bytes.size()) {
431     return llvm::createStringError(
432         llvm::inconvertibleErrorCode(),
433         "Failed to read memory while attempting to set breakpoint: attempted "
434         "to read {0} bytes but only read {1}.",
435         saved_opcode_bytes.size(), bytes_read);
436   }
437 
438   LLDB_LOG(
439       log, "Overwriting bytes at {0:x}: {1:@[x]}", addr,
440       llvm::make_range(saved_opcode_bytes.begin(), saved_opcode_bytes.end()));
441 
442   // Write a software breakpoint in place of the original opcode.
443   size_t bytes_written = 0;
444   error = WriteMemory(addr, expected_trap->data(), expected_trap->size(),
445                       bytes_written);
446   if (error.Fail())
447     return error.ToError();
448 
449   // Ensure we wrote as many bytes as we expected.
450   if (bytes_written != expected_trap->size()) {
451     return llvm::createStringError(
452         llvm::inconvertibleErrorCode(),
453         "Failed write memory while attempting to set "
454         "breakpoint: attempted to write {0} bytes but only wrote {1}",
455         expected_trap->size(), bytes_written);
456   }
457 
458   llvm::SmallVector<uint8_t, 4> verify_bp_opcode_bytes(expected_trap->size(),
459                                                        0);
460   size_t verify_bytes_read = 0;
461   error = ReadMemory(addr, verify_bp_opcode_bytes.data(),
462                      verify_bp_opcode_bytes.size(), verify_bytes_read);
463   if (error.Fail())
464     return error.ToError();
465 
466   // Ensure we read as many verification bytes as we expected.
467   if (verify_bytes_read != verify_bp_opcode_bytes.size()) {
468     return llvm::createStringError(
469         llvm::inconvertibleErrorCode(),
470         "Failed to read memory while "
471         "attempting to verify breakpoint: attempted to read {0} bytes "
472         "but only read {1}",
473         verify_bp_opcode_bytes.size(), verify_bytes_read);
474   }
475 
476   if (llvm::makeArrayRef(verify_bp_opcode_bytes.data(), verify_bytes_read) !=
477       *expected_trap) {
478     return llvm::createStringError(
479         llvm::inconvertibleErrorCode(),
480         "Verification of software breakpoint "
481         "writing failed - trap opcodes not successfully read back "
482         "after writing when setting breakpoint at {0:x}",
483         addr);
484   }
485 
486   LLDB_LOG(log, "addr = {0:x}: SUCCESS", addr);
487   return SoftwareBreakpoint{1, saved_opcode_bytes, *expected_trap};
488 }
489 
490 llvm::Expected<llvm::ArrayRef<uint8_t>>
491 NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_t size_hint) {
492   static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
493   static const uint8_t g_i386_opcode[] = {0xCC};
494   static const uint8_t g_mips64_opcode[] = {0x00, 0x00, 0x00, 0x0d};
495   static const uint8_t g_mips64el_opcode[] = {0x0d, 0x00, 0x00, 0x00};
496   static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
497   static const uint8_t g_ppc_opcode[] = {0x7f, 0xe0, 0x00, 0x08}; // trap
498   static const uint8_t g_ppcle_opcode[] = {0x08, 0x00, 0xe0, 0x7f}; // trap
499 
500   switch (GetArchitecture().GetMachine()) {
501   case llvm::Triple::aarch64:
502   case llvm::Triple::aarch64_32:
503     return llvm::makeArrayRef(g_aarch64_opcode);
504 
505   case llvm::Triple::x86:
506   case llvm::Triple::x86_64:
507     return llvm::makeArrayRef(g_i386_opcode);
508 
509   case llvm::Triple::mips:
510   case llvm::Triple::mips64:
511     return llvm::makeArrayRef(g_mips64_opcode);
512 
513   case llvm::Triple::mipsel:
514   case llvm::Triple::mips64el:
515     return llvm::makeArrayRef(g_mips64el_opcode);
516 
517   case llvm::Triple::systemz:
518     return llvm::makeArrayRef(g_s390x_opcode);
519 
520   case llvm::Triple::ppc:
521   case llvm::Triple::ppc64:
522     return llvm::makeArrayRef(g_ppc_opcode);
523 
524   case llvm::Triple::ppc64le:
525     return llvm::makeArrayRef(g_ppcle_opcode);
526 
527   default:
528     return llvm::createStringError(llvm::inconvertibleErrorCode(),
529                                    "CPU type not supported!");
530   }
531 }
532 
533 size_t NativeProcessProtocol::GetSoftwareBreakpointPCOffset() {
534   switch (GetArchitecture().GetMachine()) {
535   case llvm::Triple::x86:
536   case llvm::Triple::x86_64:
537   case llvm::Triple::systemz:
538     // These architectures report increment the PC after breakpoint is hit.
539     return cantFail(GetSoftwareBreakpointTrapOpcode(0)).size();
540 
541   case llvm::Triple::arm:
542   case llvm::Triple::aarch64:
543   case llvm::Triple::aarch64_32:
544   case llvm::Triple::mips64:
545   case llvm::Triple::mips64el:
546   case llvm::Triple::mips:
547   case llvm::Triple::mipsel:
548   case llvm::Triple::ppc:
549   case llvm::Triple::ppc64:
550   case llvm::Triple::ppc64le:
551     // On these architectures the PC doesn't get updated for breakpoint hits.
552     return 0;
553 
554   default:
555     llvm_unreachable("CPU type not supported!");
556   }
557 }
558 
559 void NativeProcessProtocol::FixupBreakpointPCAsNeeded(
560     NativeThreadProtocol &thread) {
561   Log *log = GetLog(LLDBLog::Breakpoints);
562 
563   Status error;
564 
565   // Find out the size of a breakpoint (might depend on where we are in the
566   // code).
567   NativeRegisterContext &context = thread.GetRegisterContext();
568 
569   uint32_t breakpoint_size = GetSoftwareBreakpointPCOffset();
570   LLDB_LOG(log, "breakpoint size: {0}", breakpoint_size);
571   if (breakpoint_size == 0)
572     return;
573 
574   // First try probing for a breakpoint at a software breakpoint location: PC -
575   // breakpoint size.
576   const lldb::addr_t initial_pc_addr = context.GetPCfromBreakpointLocation();
577   lldb::addr_t breakpoint_addr = initial_pc_addr;
578   // Do not allow breakpoint probe to wrap around.
579   if (breakpoint_addr >= breakpoint_size)
580     breakpoint_addr -= breakpoint_size;
581 
582   if (m_software_breakpoints.count(breakpoint_addr) == 0) {
583     // We didn't find one at a software probe location.  Nothing to do.
584     LLDB_LOG(log,
585              "pid {0} no lldb software breakpoint found at current pc with "
586              "adjustment: {1}",
587              GetID(), breakpoint_addr);
588     return;
589   }
590 
591   //
592   // We have a software breakpoint and need to adjust the PC.
593   //
594 
595   // Change the program counter.
596   LLDB_LOG(log, "pid {0} tid {1}: changing PC from {2:x} to {3:x}", GetID(),
597            thread.GetID(), initial_pc_addr, breakpoint_addr);
598 
599   error = context.SetPC(breakpoint_addr);
600   if (error.Fail()) {
601     // This can happen in case the process was killed between the time we read
602     // the PC and when we are updating it. There's nothing better to do than to
603     // swallow the error.
604     LLDB_LOG(log, "pid {0} tid {1}: failed to set PC: {2}", GetID(),
605              thread.GetID(), error);
606   }
607 }
608 
609 Status NativeProcessProtocol::RemoveBreakpoint(lldb::addr_t addr,
610                                                bool hardware) {
611   if (hardware)
612     return RemoveHardwareBreakpoint(addr);
613   else
614     return RemoveSoftwareBreakpoint(addr);
615 }
616 
617 Status NativeProcessProtocol::ReadMemoryWithoutTrap(lldb::addr_t addr,
618                                                     void *buf, size_t size,
619                                                     size_t &bytes_read) {
620   Status error = ReadMemory(addr, buf, size, bytes_read);
621   if (error.Fail())
622     return error;
623 
624   auto data =
625       llvm::makeMutableArrayRef(static_cast<uint8_t *>(buf), bytes_read);
626   for (const auto &pair : m_software_breakpoints) {
627     lldb::addr_t bp_addr = pair.first;
628     auto saved_opcodes = makeArrayRef(pair.second.saved_opcodes);
629 
630     if (bp_addr + saved_opcodes.size() < addr || addr + bytes_read <= bp_addr)
631       continue; // Breakpoint not in range, ignore
632 
633     if (bp_addr < addr) {
634       saved_opcodes = saved_opcodes.drop_front(addr - bp_addr);
635       bp_addr = addr;
636     }
637     auto bp_data = data.drop_front(bp_addr - addr);
638     std::copy_n(saved_opcodes.begin(),
639                 std::min(saved_opcodes.size(), bp_data.size()),
640                 bp_data.begin());
641   }
642   return Status();
643 }
644 
645 llvm::Expected<llvm::StringRef>
646 NativeProcessProtocol::ReadCStringFromMemory(lldb::addr_t addr, char *buffer,
647                                              size_t max_size,
648                                              size_t &total_bytes_read) {
649   static const size_t cache_line_size =
650       llvm::sys::Process::getPageSizeEstimate();
651   size_t bytes_read = 0;
652   size_t bytes_left = max_size;
653   addr_t curr_addr = addr;
654   size_t string_size;
655   char *curr_buffer = buffer;
656   total_bytes_read = 0;
657   Status status;
658 
659   while (bytes_left > 0 && status.Success()) {
660     addr_t cache_line_bytes_left =
661         cache_line_size - (curr_addr % cache_line_size);
662     addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
663     status = ReadMemory(curr_addr, static_cast<void *>(curr_buffer),
664                         bytes_to_read, bytes_read);
665 
666     if (bytes_read == 0)
667       break;
668 
669     void *str_end = std::memchr(curr_buffer, '\0', bytes_read);
670     if (str_end != nullptr) {
671       total_bytes_read =
672           static_cast<size_t>((static_cast<char *>(str_end) - buffer + 1));
673       status.Clear();
674       break;
675     }
676 
677     total_bytes_read += bytes_read;
678     curr_buffer += bytes_read;
679     curr_addr += bytes_read;
680     bytes_left -= bytes_read;
681   }
682 
683   string_size = total_bytes_read - 1;
684 
685   // Make sure we return a null terminated string.
686   if (bytes_left == 0 && max_size > 0 && buffer[max_size - 1] != '\0') {
687     buffer[max_size - 1] = '\0';
688     total_bytes_read--;
689   }
690 
691   if (!status.Success())
692     return status.ToError();
693 
694   return llvm::StringRef(buffer, string_size);
695 }
696 
697 lldb::StateType NativeProcessProtocol::GetState() const {
698   std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
699   return m_state;
700 }
701 
702 void NativeProcessProtocol::SetState(lldb::StateType state,
703                                      bool notify_delegates) {
704   std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
705 
706   if (state == m_state)
707     return;
708 
709   m_state = state;
710 
711   if (StateIsStoppedState(state, false)) {
712     ++m_stop_id;
713 
714     // Give process a chance to do any stop id bump processing, such as
715     // clearing cached data that is invalidated each time the process runs.
716     // Note if/when we support some threads running, we'll end up needing to
717     // manage this per thread and per process.
718     DoStopIDBumped(m_stop_id);
719   }
720 
721   // Optionally notify delegates of the state change.
722   if (notify_delegates)
723     SynchronouslyNotifyProcessStateChanged(state);
724 }
725 
726 uint32_t NativeProcessProtocol::GetStopID() const {
727   std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
728   return m_stop_id;
729 }
730 
731 void NativeProcessProtocol::DoStopIDBumped(uint32_t /* newBumpId */) {
732   // Default implementation does nothing.
733 }
734 
735 NativeProcessProtocol::Factory::~Factory() = default;
736