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