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