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