180814287SRaphael Isemann //===-- NativeProcessProtocol.cpp -----------------------------------------===// 2af245d11STodd Fiala // 32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6af245d11STodd Fiala // 7af245d11STodd Fiala //===----------------------------------------------------------------------===// 8af245d11STodd Fiala 92fe1d0abSChaoren Lin #include "lldb/Host/common/NativeProcessProtocol.h" 10511e5cdcSTodd Fiala #include "lldb/Host/Host.h" 11be828518SPavel Labath #include "lldb/Host/common/NativeBreakpointList.h" 122fe1d0abSChaoren Lin #include "lldb/Host/common/NativeRegisterContext.h" 132fe1d0abSChaoren Lin #include "lldb/Host/common/NativeThreadProtocol.h" 14e77fce0aSTodd Fiala #include "lldb/Utility/LLDBAssert.h" 15c34698a8SPavel Labath #include "lldb/Utility/LLDBLog.h" 166f9e6901SZachary Turner #include "lldb/Utility/Log.h" 17d821c997SPavel Labath #include "lldb/Utility/State.h" 18b9c1b51eSKate Stone #include "lldb/lldb-enumerations.h" 19af245d11STodd Fiala 2070795c1eSAntonio Afonso #include "llvm/Support/Process.h" 2170795c1eSAntonio Afonso 22af245d11STodd Fiala using namespace lldb; 23af245d11STodd Fiala using namespace lldb_private; 24af245d11STodd Fiala 25af245d11STodd Fiala // NativeProcessProtocol Members 26af245d11STodd Fiala 2796e600fcSPavel Labath NativeProcessProtocol::NativeProcessProtocol(lldb::pid_t pid, int terminal_fd, 2896e600fcSPavel Labath NativeDelegate &delegate) 29c9cf394fSPavel Labath : m_pid(pid), m_delegate(delegate), m_terminal_fd(terminal_fd) { 30c9cf394fSPavel Labath delegate.InitializeDelegate(this); 3196e600fcSPavel Labath } 32af245d11STodd Fiala 3397206d57SZachary Turner lldb_private::Status NativeProcessProtocol::Interrupt() { 3497206d57SZachary Turner Status error; 35511e5cdcSTodd Fiala #if !defined(SIGSTOP) 36511e5cdcSTodd Fiala error.SetErrorString("local host does not support signaling"); 37511e5cdcSTodd Fiala return error; 38511e5cdcSTodd Fiala #else 39511e5cdcSTodd Fiala return Signal(SIGSTOP); 40511e5cdcSTodd Fiala #endif 41511e5cdcSTodd Fiala } 42511e5cdcSTodd Fiala 4397206d57SZachary Turner Status NativeProcessProtocol::IgnoreSignals(llvm::ArrayRef<int> signals) { 444a705e7eSPavel Labath m_signals_to_ignore.clear(); 454a705e7eSPavel Labath m_signals_to_ignore.insert(signals.begin(), signals.end()); 4697206d57SZachary Turner return Status(); 474a705e7eSPavel Labath } 484a705e7eSPavel Labath 4997206d57SZachary Turner lldb_private::Status 50b9c1b51eSKate Stone NativeProcessProtocol::GetMemoryRegionInfo(lldb::addr_t load_addr, 51b9c1b51eSKate Stone MemoryRegionInfo &range_info) { 52af245d11STodd Fiala // Default: not implemented. 5397206d57SZachary Turner return Status("not implemented"); 54af245d11STodd Fiala } 55af245d11STodd Fiala 56da2e614fSDavid Spickett lldb_private::Status 57da2e614fSDavid Spickett NativeProcessProtocol::ReadMemoryTags(int32_t type, lldb::addr_t addr, 58da2e614fSDavid Spickett size_t len, std::vector<uint8_t> &tags) { 59da2e614fSDavid Spickett return Status("not implemented"); 60da2e614fSDavid Spickett } 61da2e614fSDavid Spickett 627d27230dSDavid Spickett lldb_private::Status 637d27230dSDavid Spickett NativeProcessProtocol::WriteMemoryTags(int32_t type, lldb::addr_t addr, 647d27230dSDavid Spickett size_t len, 657d27230dSDavid Spickett const std::vector<uint8_t> &tags) { 667d27230dSDavid Spickett return Status("not implemented"); 677d27230dSDavid Spickett } 687d27230dSDavid Spickett 693508fc8cSPavel Labath llvm::Optional<WaitStatus> NativeProcessProtocol::GetExitStatus() { 703508fc8cSPavel Labath if (m_state == lldb::eStateExited) 713508fc8cSPavel Labath return m_exit_status; 723508fc8cSPavel Labath 733508fc8cSPavel Labath return llvm::None; 74af245d11STodd Fiala } 75af245d11STodd Fiala 763508fc8cSPavel Labath bool NativeProcessProtocol::SetExitStatus(WaitStatus status, 77b9c1b51eSKate Stone bool bNotifyStateChange) { 78a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process); 793508fc8cSPavel Labath LLDB_LOG(log, "status = {0}, notify = {1}", status, bNotifyStateChange); 80af245d11STodd Fiala 81af245d11STodd Fiala // Exit status already set 82b9c1b51eSKate Stone if (m_state == lldb::eStateExited) { 833508fc8cSPavel Labath if (m_exit_status) 843508fc8cSPavel Labath LLDB_LOG(log, "exit status already set to {0}", *m_exit_status); 853508fc8cSPavel Labath else 863508fc8cSPavel Labath LLDB_LOG(log, "state is exited, but status not set"); 87af245d11STodd Fiala return false; 88af245d11STodd Fiala } 89af245d11STodd Fiala 90af245d11STodd Fiala m_state = lldb::eStateExited; 91af245d11STodd Fiala m_exit_status = status; 92af245d11STodd Fiala 93af245d11STodd Fiala if (bNotifyStateChange) 94af245d11STodd Fiala SynchronouslyNotifyProcessStateChanged(lldb::eStateExited); 95af245d11STodd Fiala 96af245d11STodd Fiala return true; 97af245d11STodd Fiala } 98af245d11STodd Fiala 99a5be48b3SPavel Labath NativeThreadProtocol *NativeProcessProtocol::GetThreadAtIndex(uint32_t idx) { 10016ff8604SSaleem Abdulrasool std::lock_guard<std::recursive_mutex> guard(m_threads_mutex); 101af245d11STodd Fiala if (idx < m_threads.size()) 102a5be48b3SPavel Labath return m_threads[idx].get(); 103a5be48b3SPavel Labath return nullptr; 104af245d11STodd Fiala } 105af245d11STodd Fiala 106a5be48b3SPavel Labath NativeThreadProtocol * 107b9c1b51eSKate Stone NativeProcessProtocol::GetThreadByIDUnlocked(lldb::tid_t tid) { 108a5be48b3SPavel Labath for (const auto &thread : m_threads) { 109a5be48b3SPavel Labath if (thread->GetID() == tid) 110a5be48b3SPavel Labath return thread.get(); 111af245d11STodd Fiala } 112a5be48b3SPavel Labath return nullptr; 113af245d11STodd Fiala } 114af245d11STodd Fiala 115a5be48b3SPavel Labath NativeThreadProtocol *NativeProcessProtocol::GetThreadByID(lldb::tid_t tid) { 11616ff8604SSaleem Abdulrasool std::lock_guard<std::recursive_mutex> guard(m_threads_mutex); 117511e5cdcSTodd Fiala return GetThreadByIDUnlocked(tid); 118511e5cdcSTodd Fiala } 119511e5cdcSTodd Fiala 120b9c1b51eSKate Stone bool NativeProcessProtocol::IsAlive() const { 121b9c1b51eSKate Stone return m_state != eStateDetached && m_state != eStateExited && 122b9c1b51eSKate Stone m_state != eStateInvalid && m_state != eStateUnloaded; 123af245d11STodd Fiala } 124af245d11STodd Fiala 12518fe6404SChaoren Lin const NativeWatchpointList::WatchpointMap & 126b9c1b51eSKate Stone NativeProcessProtocol::GetWatchpointMap() const { 12718fe6404SChaoren Lin return m_watchpoint_list.GetWatchpointMap(); 12818fe6404SChaoren Lin } 12918fe6404SChaoren Lin 130d5ffbad2SOmair Javaid llvm::Optional<std::pair<uint32_t, uint32_t>> 131d5ffbad2SOmair Javaid NativeProcessProtocol::GetHardwareDebugSupportInfo() const { 132a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process); 133af245d11STodd Fiala 134af245d11STodd Fiala // get any thread 135a5be48b3SPavel Labath NativeThreadProtocol *thread( 136b9c1b51eSKate Stone const_cast<NativeProcessProtocol *>(this)->GetThreadAtIndex(0)); 137a5be48b3SPavel Labath if (!thread) { 138a5be48b3SPavel Labath LLDB_LOG(log, "failed to find a thread to grab a NativeRegisterContext!"); 139d5ffbad2SOmair Javaid return llvm::None; 140af245d11STodd Fiala } 141af245d11STodd Fiala 142d37349f3SPavel Labath NativeRegisterContext ®_ctx = thread->GetRegisterContext(); 143d37349f3SPavel Labath return std::make_pair(reg_ctx.NumSupportedHardwareBreakpoints(), 144d37349f3SPavel Labath reg_ctx.NumSupportedHardwareWatchpoints()); 145af245d11STodd Fiala } 146af245d11STodd Fiala 14797206d57SZachary Turner Status NativeProcessProtocol::SetWatchpoint(lldb::addr_t addr, size_t size, 148b9c1b51eSKate Stone uint32_t watch_flags, 149b9c1b51eSKate Stone bool hardware) { 15005097246SAdrian Prantl // This default implementation assumes setting the watchpoint for the process 15105097246SAdrian Prantl // will require setting the watchpoint for each of the threads. Furthermore, 15205097246SAdrian Prantl // it will track watchpoints set for the process and will add them to each 15305097246SAdrian Prantl // thread that is attached to via the (FIXME implement) OnThreadAttached () 15405097246SAdrian Prantl // method. 155af245d11STodd Fiala 156a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process); 157af245d11STodd Fiala 158af245d11STodd Fiala // Update the thread list 159af245d11STodd Fiala UpdateThreads(); 160af245d11STodd Fiala 16105097246SAdrian Prantl // Keep track of the threads we successfully set the watchpoint for. If one 16205097246SAdrian Prantl // of the thread watchpoint setting operations fails, back off and remove the 16305097246SAdrian Prantl // watchpoint for all the threads that were successfully set so we get back 16405097246SAdrian Prantl // to a consistent state. 165a5be48b3SPavel Labath std::vector<NativeThreadProtocol *> watchpoint_established_threads; 166af245d11STodd Fiala 16705097246SAdrian Prantl // Tell each thread to set a watchpoint. In the event that hardware 16805097246SAdrian Prantl // watchpoints are requested but the SetWatchpoint fails, try to set a 16905097246SAdrian Prantl // software watchpoint as a fallback. It's conceivable that if there are 17005097246SAdrian Prantl // more threads than hardware watchpoints available, some of the threads will 17105097246SAdrian Prantl // fail to set hardware watchpoints while software ones may be available. 17216ff8604SSaleem Abdulrasool std::lock_guard<std::recursive_mutex> guard(m_threads_mutex); 173a5be48b3SPavel Labath for (const auto &thread : m_threads) { 174a5be48b3SPavel Labath assert(thread && "thread list should not have a NULL thread!"); 175af245d11STodd Fiala 17697206d57SZachary Turner Status thread_error = 177a5be48b3SPavel Labath thread->SetWatchpoint(addr, size, watch_flags, hardware); 178b9c1b51eSKate Stone if (thread_error.Fail() && hardware) { 17905097246SAdrian Prantl // Try software watchpoints since we failed on hardware watchpoint 18005097246SAdrian Prantl // setting and we may have just run out of hardware watchpoints. 181a5be48b3SPavel Labath thread_error = thread->SetWatchpoint(addr, size, watch_flags, false); 182a5be48b3SPavel Labath if (thread_error.Success()) 183a5be48b3SPavel Labath LLDB_LOG(log, 184b9c1b51eSKate Stone "hardware watchpoint requested but software watchpoint set"); 185af245d11STodd Fiala } 186af245d11STodd Fiala 187b9c1b51eSKate Stone if (thread_error.Success()) { 18805097246SAdrian Prantl // Remember that we set this watchpoint successfully in case we need to 18905097246SAdrian Prantl // clear it later. 190a5be48b3SPavel Labath watchpoint_established_threads.push_back(thread.get()); 191b9c1b51eSKate Stone } else { 19205097246SAdrian Prantl // Unset the watchpoint for each thread we successfully set so that we 19305097246SAdrian Prantl // get back to a consistent state of "not set" for the watchpoint. 194b9c1b51eSKate Stone for (auto unwatch_thread_sp : watchpoint_established_threads) { 19597206d57SZachary Turner Status remove_error = unwatch_thread_sp->RemoveWatchpoint(addr); 196a5be48b3SPavel Labath if (remove_error.Fail()) 197a5be48b3SPavel Labath LLDB_LOG(log, "RemoveWatchpoint failed for pid={0}, tid={1}: {2}", 198a5be48b3SPavel Labath GetID(), unwatch_thread_sp->GetID(), remove_error); 199af245d11STodd Fiala } 200af245d11STodd Fiala 201af245d11STodd Fiala return thread_error; 202af245d11STodd Fiala } 203af245d11STodd Fiala } 20418fe6404SChaoren Lin return m_watchpoint_list.Add(addr, size, watch_flags, hardware); 205af245d11STodd Fiala } 206af245d11STodd Fiala 20797206d57SZachary Turner Status NativeProcessProtocol::RemoveWatchpoint(lldb::addr_t addr) { 208af245d11STodd Fiala // Update the thread list 209af245d11STodd Fiala UpdateThreads(); 210af245d11STodd Fiala 21197206d57SZachary Turner Status overall_error; 212af245d11STodd Fiala 21316ff8604SSaleem Abdulrasool std::lock_guard<std::recursive_mutex> guard(m_threads_mutex); 214a5be48b3SPavel Labath for (const auto &thread : m_threads) { 215a5be48b3SPavel Labath assert(thread && "thread list should not have a NULL thread!"); 216af245d11STodd Fiala 217a5be48b3SPavel Labath const Status thread_error = thread->RemoveWatchpoint(addr); 218b9c1b51eSKate Stone if (thread_error.Fail()) { 21905097246SAdrian Prantl // Keep track of the first thread error if any threads fail. We want to 22005097246SAdrian Prantl // try to remove the watchpoint from every thread, though, even if one or 22105097246SAdrian Prantl // more have errors. 222af245d11STodd Fiala if (!overall_error.Fail()) 223af245d11STodd Fiala overall_error = thread_error; 224af245d11STodd Fiala } 225af245d11STodd Fiala } 22697206d57SZachary Turner const Status error = m_watchpoint_list.Remove(addr); 22718fe6404SChaoren Lin return overall_error.Fail() ? overall_error : error; 228af245d11STodd Fiala } 229af245d11STodd Fiala 230d5ffbad2SOmair Javaid const HardwareBreakpointMap & 231d5ffbad2SOmair Javaid NativeProcessProtocol::GetHardwareBreakpointMap() const { 232d5ffbad2SOmair Javaid return m_hw_breakpoints_map; 233d5ffbad2SOmair Javaid } 234d5ffbad2SOmair Javaid 23597206d57SZachary Turner Status NativeProcessProtocol::SetHardwareBreakpoint(lldb::addr_t addr, 236d5ffbad2SOmair Javaid size_t size) { 23705097246SAdrian Prantl // This default implementation assumes setting a hardware breakpoint for this 23805097246SAdrian Prantl // process will require setting same hardware breakpoint for each of its 23905097246SAdrian Prantl // existing threads. New thread will do the same once created. 240a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process); 241d5ffbad2SOmair Javaid 242d5ffbad2SOmair Javaid // Update the thread list 243d5ffbad2SOmair Javaid UpdateThreads(); 244d5ffbad2SOmair Javaid 245d5ffbad2SOmair Javaid // Exit here if target does not have required hardware breakpoint capability. 246d5ffbad2SOmair Javaid auto hw_debug_cap = GetHardwareDebugSupportInfo(); 247d5ffbad2SOmair Javaid 248d5ffbad2SOmair Javaid if (hw_debug_cap == llvm::None || hw_debug_cap->first == 0 || 249d5ffbad2SOmair Javaid hw_debug_cap->first <= m_hw_breakpoints_map.size()) 25097206d57SZachary Turner return Status("Target does not have required no of hardware breakpoints"); 251d5ffbad2SOmair Javaid 252d5ffbad2SOmair Javaid // Vector below stores all thread pointer for which we have we successfully 253d5ffbad2SOmair Javaid // set this hardware breakpoint. If any of the current process threads fails 254d5ffbad2SOmair Javaid // to set this hardware breakpoint then roll back and remove this breakpoint 255d5ffbad2SOmair Javaid // for all the threads that had already set it successfully. 256a5be48b3SPavel Labath std::vector<NativeThreadProtocol *> breakpoint_established_threads; 257d5ffbad2SOmair Javaid 258d5ffbad2SOmair Javaid // Request to set a hardware breakpoint for each of current process threads. 259d5ffbad2SOmair Javaid std::lock_guard<std::recursive_mutex> guard(m_threads_mutex); 260a5be48b3SPavel Labath for (const auto &thread : m_threads) { 261a5be48b3SPavel Labath assert(thread && "thread list should not have a NULL thread!"); 262d5ffbad2SOmair Javaid 263a5be48b3SPavel Labath Status thread_error = thread->SetHardwareBreakpoint(addr, size); 264d5ffbad2SOmair Javaid if (thread_error.Success()) { 26505097246SAdrian Prantl // Remember that we set this breakpoint successfully in case we need to 26605097246SAdrian Prantl // clear it later. 267a5be48b3SPavel Labath breakpoint_established_threads.push_back(thread.get()); 268d5ffbad2SOmair Javaid } else { 26905097246SAdrian Prantl // Unset the breakpoint for each thread we successfully set so that we 27005097246SAdrian Prantl // get back to a consistent state of "not set" for this hardware 27105097246SAdrian Prantl // breakpoint. 272d5ffbad2SOmair Javaid for (auto rollback_thread_sp : breakpoint_established_threads) { 27397206d57SZachary Turner Status remove_error = 27497206d57SZachary Turner rollback_thread_sp->RemoveHardwareBreakpoint(addr); 275a5be48b3SPavel Labath if (remove_error.Fail()) 276a5be48b3SPavel Labath LLDB_LOG(log, 277a5be48b3SPavel Labath "RemoveHardwareBreakpoint failed for pid={0}, tid={1}: {2}", 278a5be48b3SPavel Labath GetID(), rollback_thread_sp->GetID(), remove_error); 279d5ffbad2SOmair Javaid } 280d5ffbad2SOmair Javaid 281d5ffbad2SOmair Javaid return thread_error; 282d5ffbad2SOmair Javaid } 283d5ffbad2SOmair Javaid } 284d5ffbad2SOmair Javaid 285d5ffbad2SOmair Javaid // Register new hardware breakpoint into hardware breakpoints map of current 286d5ffbad2SOmair Javaid // process. 287d5ffbad2SOmair Javaid m_hw_breakpoints_map[addr] = {addr, size}; 288d5ffbad2SOmair Javaid 28997206d57SZachary Turner return Status(); 290d5ffbad2SOmair Javaid } 291d5ffbad2SOmair Javaid 29297206d57SZachary Turner Status NativeProcessProtocol::RemoveHardwareBreakpoint(lldb::addr_t addr) { 293d5ffbad2SOmair Javaid // Update the thread list 294d5ffbad2SOmair Javaid UpdateThreads(); 295d5ffbad2SOmair Javaid 29697206d57SZachary Turner Status error; 297d5ffbad2SOmair Javaid 298d5ffbad2SOmair Javaid std::lock_guard<std::recursive_mutex> guard(m_threads_mutex); 299a5be48b3SPavel Labath for (const auto &thread : m_threads) { 300a5be48b3SPavel Labath assert(thread && "thread list should not have a NULL thread!"); 301a5be48b3SPavel Labath error = thread->RemoveHardwareBreakpoint(addr); 302d5ffbad2SOmair Javaid } 303d5ffbad2SOmair Javaid 304d5ffbad2SOmair Javaid // Also remove from hardware breakpoint map of current process. 305d5ffbad2SOmair Javaid m_hw_breakpoints_map.erase(addr); 306d5ffbad2SOmair Javaid 307d5ffbad2SOmair Javaid return error; 308d5ffbad2SOmair Javaid } 309d5ffbad2SOmair Javaid 310b9c1b51eSKate Stone void NativeProcessProtocol::SynchronouslyNotifyProcessStateChanged( 311b9c1b51eSKate Stone lldb::StateType state) { 312a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process); 313af245d11STodd Fiala 314c9cf394fSPavel Labath m_delegate.ProcessStateChanged(this, state); 3151637545fSWalter Erquinigo NotifyTracersProcessStateChanged(state); 316af245d11STodd Fiala 317c9cf394fSPavel Labath LLDB_LOG(log, "sent state notification [{0}] from process {1}", state, 318c9cf394fSPavel Labath GetID()); 319af245d11STodd Fiala } 320af245d11STodd Fiala 321b9c1b51eSKate Stone void NativeProcessProtocol::NotifyDidExec() { 322a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process); 323c9cf394fSPavel Labath LLDB_LOG(log, "process {0} exec()ed", GetID()); 324a9882ceeSTodd Fiala 325*cf2c8e41SPavel Labath m_software_breakpoints.clear(); 326*cf2c8e41SPavel Labath 327c9cf394fSPavel Labath m_delegate.DidExec(this); 328a9882ceeSTodd Fiala } 329a9882ceeSTodd Fiala 33097206d57SZachary Turner Status NativeProcessProtocol::SetSoftwareBreakpoint(lldb::addr_t addr, 331b9c1b51eSKate Stone uint32_t size_hint) { 332a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Breakpoints); 333be828518SPavel Labath LLDB_LOG(log, "addr = {0:x}, size_hint = {1}", addr, size_hint); 334af245d11STodd Fiala 335be828518SPavel Labath auto it = m_software_breakpoints.find(addr); 336be828518SPavel Labath if (it != m_software_breakpoints.end()) { 337be828518SPavel Labath ++it->second.ref_count; 338be828518SPavel Labath return Status(); 339be828518SPavel Labath } 340be828518SPavel Labath auto expected_bkpt = EnableSoftwareBreakpoint(addr, size_hint); 341be828518SPavel Labath if (!expected_bkpt) 342be828518SPavel Labath return Status(expected_bkpt.takeError()); 343be828518SPavel Labath 344be828518SPavel Labath m_software_breakpoints.emplace(addr, std::move(*expected_bkpt)); 345be828518SPavel Labath return Status(); 346be828518SPavel Labath } 347be828518SPavel Labath 348be828518SPavel Labath Status NativeProcessProtocol::RemoveSoftwareBreakpoint(lldb::addr_t addr) { 349a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Breakpoints); 350be828518SPavel Labath LLDB_LOG(log, "addr = {0:x}", addr); 351be828518SPavel Labath auto it = m_software_breakpoints.find(addr); 352be828518SPavel Labath if (it == m_software_breakpoints.end()) 353be828518SPavel Labath return Status("Breakpoint not found."); 354be828518SPavel Labath assert(it->second.ref_count > 0); 355be828518SPavel Labath if (--it->second.ref_count > 0) 356be828518SPavel Labath return Status(); 357be828518SPavel Labath 358be828518SPavel Labath // This is the last reference. Let's remove the breakpoint. 359be828518SPavel Labath Status error; 360be828518SPavel Labath 361be828518SPavel Labath // Clear a software breakpoint instruction 362be828518SPavel Labath llvm::SmallVector<uint8_t, 4> curr_break_op( 363be828518SPavel Labath it->second.breakpoint_opcodes.size(), 0); 364be828518SPavel Labath 365be828518SPavel Labath // Read the breakpoint opcode 366be828518SPavel Labath size_t bytes_read = 0; 367be828518SPavel Labath error = 368be828518SPavel Labath ReadMemory(addr, curr_break_op.data(), curr_break_op.size(), bytes_read); 369be828518SPavel Labath if (error.Fail() || bytes_read < curr_break_op.size()) { 370be828518SPavel Labath return Status("addr=0x%" PRIx64 371be828518SPavel Labath ": tried to read %zu bytes but only read %zu", 372be828518SPavel Labath addr, curr_break_op.size(), bytes_read); 373be828518SPavel Labath } 374be828518SPavel Labath const auto &saved = it->second.saved_opcodes; 375be828518SPavel Labath // Make sure the breakpoint opcode exists at this address 376be828518SPavel Labath if (makeArrayRef(curr_break_op) != it->second.breakpoint_opcodes) { 377be828518SPavel Labath if (curr_break_op != it->second.saved_opcodes) 378be828518SPavel Labath return Status("Original breakpoint trap is no longer in memory."); 379be828518SPavel Labath LLDB_LOG(log, 380be828518SPavel Labath "Saved opcodes ({0:@[x]}) have already been restored at {1:x}.", 381be828518SPavel Labath llvm::make_range(saved.begin(), saved.end()), addr); 382be828518SPavel Labath } else { 383be828518SPavel Labath // We found a valid breakpoint opcode at this address, now restore the 384be828518SPavel Labath // saved opcode. 385be828518SPavel Labath size_t bytes_written = 0; 386be828518SPavel Labath error = WriteMemory(addr, saved.data(), saved.size(), bytes_written); 387be828518SPavel Labath if (error.Fail() || bytes_written < saved.size()) { 388be828518SPavel Labath return Status("addr=0x%" PRIx64 389be828518SPavel Labath ": tried to write %zu bytes but only wrote %zu", 390be828518SPavel Labath addr, saved.size(), bytes_written); 391be828518SPavel Labath } 392be828518SPavel Labath 393be828518SPavel Labath // Verify that our original opcode made it back to the inferior 394be828518SPavel Labath llvm::SmallVector<uint8_t, 4> verify_opcode(saved.size(), 0); 395be828518SPavel Labath size_t verify_bytes_read = 0; 396be828518SPavel Labath error = ReadMemory(addr, verify_opcode.data(), verify_opcode.size(), 397be828518SPavel Labath verify_bytes_read); 398be828518SPavel Labath if (error.Fail() || verify_bytes_read < verify_opcode.size()) { 399be828518SPavel Labath return Status("addr=0x%" PRIx64 400be828518SPavel Labath ": tried to read %zu verification bytes but only read %zu", 401be828518SPavel Labath addr, verify_opcode.size(), verify_bytes_read); 402be828518SPavel Labath } 403be828518SPavel Labath if (verify_opcode != saved) 404be828518SPavel Labath LLDB_LOG(log, "Restoring bytes at {0:x}: {1:@[x]}", addr, 405be828518SPavel Labath llvm::make_range(saved.begin(), saved.end())); 406be828518SPavel Labath } 407be828518SPavel Labath 408be828518SPavel Labath m_software_breakpoints.erase(it); 409be828518SPavel Labath return Status(); 410be828518SPavel Labath } 411be828518SPavel Labath 412be828518SPavel Labath llvm::Expected<NativeProcessProtocol::SoftwareBreakpoint> 413be828518SPavel Labath NativeProcessProtocol::EnableSoftwareBreakpoint(lldb::addr_t addr, 414be828518SPavel Labath uint32_t size_hint) { 415a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Breakpoints); 416be828518SPavel Labath 417be828518SPavel Labath auto expected_trap = GetSoftwareBreakpointTrapOpcode(size_hint); 418be828518SPavel Labath if (!expected_trap) 419be828518SPavel Labath return expected_trap.takeError(); 420be828518SPavel Labath 421be828518SPavel Labath llvm::SmallVector<uint8_t, 4> saved_opcode_bytes(expected_trap->size(), 0); 422be828518SPavel Labath // Save the original opcodes by reading them so we can restore later. 423be828518SPavel Labath size_t bytes_read = 0; 424be828518SPavel Labath Status error = ReadMemory(addr, saved_opcode_bytes.data(), 425be828518SPavel Labath saved_opcode_bytes.size(), bytes_read); 426be828518SPavel Labath if (error.Fail()) 427be828518SPavel Labath return error.ToError(); 428be828518SPavel Labath 429be828518SPavel Labath // Ensure we read as many bytes as we expected. 430be828518SPavel Labath if (bytes_read != saved_opcode_bytes.size()) { 431be828518SPavel Labath return llvm::createStringError( 432be828518SPavel Labath llvm::inconvertibleErrorCode(), 433be828518SPavel Labath "Failed to read memory while attempting to set breakpoint: attempted " 434be828518SPavel Labath "to read {0} bytes but only read {1}.", 435be828518SPavel Labath saved_opcode_bytes.size(), bytes_read); 436be828518SPavel Labath } 437be828518SPavel Labath 438be828518SPavel Labath LLDB_LOG( 439be828518SPavel Labath log, "Overwriting bytes at {0:x}: {1:@[x]}", addr, 440be828518SPavel Labath llvm::make_range(saved_opcode_bytes.begin(), saved_opcode_bytes.end())); 441be828518SPavel Labath 442be828518SPavel Labath // Write a software breakpoint in place of the original opcode. 443be828518SPavel Labath size_t bytes_written = 0; 444be828518SPavel Labath error = WriteMemory(addr, expected_trap->data(), expected_trap->size(), 445be828518SPavel Labath bytes_written); 446be828518SPavel Labath if (error.Fail()) 447be828518SPavel Labath return error.ToError(); 448be828518SPavel Labath 449be828518SPavel Labath // Ensure we wrote as many bytes as we expected. 450be828518SPavel Labath if (bytes_written != expected_trap->size()) { 451be828518SPavel Labath return llvm::createStringError( 452be828518SPavel Labath llvm::inconvertibleErrorCode(), 453be828518SPavel Labath "Failed write memory while attempting to set " 454be828518SPavel Labath "breakpoint: attempted to write {0} bytes but only wrote {1}", 455be828518SPavel Labath expected_trap->size(), bytes_written); 456be828518SPavel Labath } 457be828518SPavel Labath 458be828518SPavel Labath llvm::SmallVector<uint8_t, 4> verify_bp_opcode_bytes(expected_trap->size(), 459be828518SPavel Labath 0); 460be828518SPavel Labath size_t verify_bytes_read = 0; 461be828518SPavel Labath error = ReadMemory(addr, verify_bp_opcode_bytes.data(), 462be828518SPavel Labath verify_bp_opcode_bytes.size(), verify_bytes_read); 463be828518SPavel Labath if (error.Fail()) 464be828518SPavel Labath return error.ToError(); 465be828518SPavel Labath 466be828518SPavel Labath // Ensure we read as many verification bytes as we expected. 467be828518SPavel Labath if (verify_bytes_read != verify_bp_opcode_bytes.size()) { 468be828518SPavel Labath return llvm::createStringError( 469be828518SPavel Labath llvm::inconvertibleErrorCode(), 470be828518SPavel Labath "Failed to read memory while " 471be828518SPavel Labath "attempting to verify breakpoint: attempted to read {0} bytes " 472be828518SPavel Labath "but only read {1}", 473be828518SPavel Labath verify_bp_opcode_bytes.size(), verify_bytes_read); 474be828518SPavel Labath } 475be828518SPavel Labath 476be828518SPavel Labath if (llvm::makeArrayRef(verify_bp_opcode_bytes.data(), verify_bytes_read) != 477be828518SPavel Labath *expected_trap) { 478be828518SPavel Labath return llvm::createStringError( 479be828518SPavel Labath llvm::inconvertibleErrorCode(), 480be828518SPavel Labath "Verification of software breakpoint " 481be828518SPavel Labath "writing failed - trap opcodes not successfully read back " 482be828518SPavel Labath "after writing when setting breakpoint at {0:x}", 483be828518SPavel Labath addr); 484be828518SPavel Labath } 485be828518SPavel Labath 486b075bbd9SPavel Labath LLDB_LOG(log, "addr = {0:x}: SUCCESS", addr); 487be828518SPavel Labath return SoftwareBreakpoint{1, saved_opcode_bytes, *expected_trap}; 488af245d11STodd Fiala } 489af245d11STodd Fiala 490f8b825f6SPavel Labath llvm::Expected<llvm::ArrayRef<uint8_t>> 491f8b825f6SPavel Labath NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_t size_hint) { 492f8b825f6SPavel Labath static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4}; 493f8b825f6SPavel Labath static const uint8_t g_i386_opcode[] = {0xCC}; 494f8b825f6SPavel Labath static const uint8_t g_mips64_opcode[] = {0x00, 0x00, 0x00, 0x0d}; 495f8b825f6SPavel Labath static const uint8_t g_mips64el_opcode[] = {0x0d, 0x00, 0x00, 0x00}; 496f8b825f6SPavel Labath static const uint8_t g_s390x_opcode[] = {0x00, 0x01}; 497bd03f6dfSMichał Górny static const uint8_t g_ppc_opcode[] = {0x7f, 0xe0, 0x00, 0x08}; // trap 498bd03f6dfSMichał Górny static const uint8_t g_ppcle_opcode[] = {0x08, 0x00, 0xe0, 0x7f}; // trap 499f8b825f6SPavel Labath 500f8b825f6SPavel Labath switch (GetArchitecture().GetMachine()) { 501f8b825f6SPavel Labath case llvm::Triple::aarch64: 5027dd7a360SJason Molenda case llvm::Triple::aarch64_32: 5034f545074SPavel Labath return llvm::makeArrayRef(g_aarch64_opcode); 504f8b825f6SPavel Labath 505f8b825f6SPavel Labath case llvm::Triple::x86: 506f8b825f6SPavel Labath case llvm::Triple::x86_64: 5074f545074SPavel Labath return llvm::makeArrayRef(g_i386_opcode); 508f8b825f6SPavel Labath 509f8b825f6SPavel Labath case llvm::Triple::mips: 510f8b825f6SPavel Labath case llvm::Triple::mips64: 5114f545074SPavel Labath return llvm::makeArrayRef(g_mips64_opcode); 512f8b825f6SPavel Labath 513f8b825f6SPavel Labath case llvm::Triple::mipsel: 514f8b825f6SPavel Labath case llvm::Triple::mips64el: 5154f545074SPavel Labath return llvm::makeArrayRef(g_mips64el_opcode); 516f8b825f6SPavel Labath 517f8b825f6SPavel Labath case llvm::Triple::systemz: 5184f545074SPavel Labath return llvm::makeArrayRef(g_s390x_opcode); 519f8b825f6SPavel Labath 520bd03f6dfSMichał Górny case llvm::Triple::ppc: 521bd03f6dfSMichał Górny case llvm::Triple::ppc64: 522bd03f6dfSMichał Górny return llvm::makeArrayRef(g_ppc_opcode); 523bd03f6dfSMichał Górny 524f8b825f6SPavel Labath case llvm::Triple::ppc64le: 525bd03f6dfSMichał Górny return llvm::makeArrayRef(g_ppcle_opcode); 526f8b825f6SPavel Labath 527f8b825f6SPavel Labath default: 528f8b825f6SPavel Labath return llvm::createStringError(llvm::inconvertibleErrorCode(), 529f8b825f6SPavel Labath "CPU type not supported!"); 530f8b825f6SPavel Labath } 531f8b825f6SPavel Labath } 532f8b825f6SPavel Labath 53399f436b0SPavel Labath size_t NativeProcessProtocol::GetSoftwareBreakpointPCOffset() { 53499f436b0SPavel Labath switch (GetArchitecture().GetMachine()) { 53599f436b0SPavel Labath case llvm::Triple::x86: 53699f436b0SPavel Labath case llvm::Triple::x86_64: 53799f436b0SPavel Labath case llvm::Triple::systemz: 53899f436b0SPavel Labath // These architectures report increment the PC after breakpoint is hit. 53999f436b0SPavel Labath return cantFail(GetSoftwareBreakpointTrapOpcode(0)).size(); 54099f436b0SPavel Labath 54199f436b0SPavel Labath case llvm::Triple::arm: 54299f436b0SPavel Labath case llvm::Triple::aarch64: 5437dd7a360SJason Molenda case llvm::Triple::aarch64_32: 54499f436b0SPavel Labath case llvm::Triple::mips64: 54599f436b0SPavel Labath case llvm::Triple::mips64el: 54699f436b0SPavel Labath case llvm::Triple::mips: 54799f436b0SPavel Labath case llvm::Triple::mipsel: 548bd03f6dfSMichał Górny case llvm::Triple::ppc: 549bd03f6dfSMichał Górny case llvm::Triple::ppc64: 55099f436b0SPavel Labath case llvm::Triple::ppc64le: 55199f436b0SPavel Labath // On these architectures the PC doesn't get updated for breakpoint hits. 55299f436b0SPavel Labath return 0; 55399f436b0SPavel Labath 55499f436b0SPavel Labath default: 55599f436b0SPavel Labath llvm_unreachable("CPU type not supported!"); 55699f436b0SPavel Labath } 55799f436b0SPavel Labath } 55899f436b0SPavel Labath 559aef7908fSPavel Labath void NativeProcessProtocol::FixupBreakpointPCAsNeeded( 560aef7908fSPavel Labath NativeThreadProtocol &thread) { 561a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Breakpoints); 562aef7908fSPavel Labath 563aef7908fSPavel Labath Status error; 564aef7908fSPavel Labath 565aef7908fSPavel Labath // Find out the size of a breakpoint (might depend on where we are in the 566aef7908fSPavel Labath // code). 567aef7908fSPavel Labath NativeRegisterContext &context = thread.GetRegisterContext(); 568aef7908fSPavel Labath 569aef7908fSPavel Labath uint32_t breakpoint_size = GetSoftwareBreakpointPCOffset(); 570aef7908fSPavel Labath LLDB_LOG(log, "breakpoint size: {0}", breakpoint_size); 571aef7908fSPavel Labath if (breakpoint_size == 0) 572aef7908fSPavel Labath return; 573aef7908fSPavel Labath 574aef7908fSPavel Labath // First try probing for a breakpoint at a software breakpoint location: PC - 575aef7908fSPavel Labath // breakpoint size. 576aef7908fSPavel Labath const lldb::addr_t initial_pc_addr = context.GetPCfromBreakpointLocation(); 577aef7908fSPavel Labath lldb::addr_t breakpoint_addr = initial_pc_addr; 578aef7908fSPavel Labath // Do not allow breakpoint probe to wrap around. 579aef7908fSPavel Labath if (breakpoint_addr >= breakpoint_size) 580aef7908fSPavel Labath breakpoint_addr -= breakpoint_size; 581aef7908fSPavel Labath 582be828518SPavel Labath if (m_software_breakpoints.count(breakpoint_addr) == 0) { 583aef7908fSPavel Labath // We didn't find one at a software probe location. Nothing to do. 584aef7908fSPavel Labath LLDB_LOG(log, 585be828518SPavel Labath "pid {0} no lldb software breakpoint found at current pc with " 586aef7908fSPavel Labath "adjustment: {1}", 587aef7908fSPavel Labath GetID(), breakpoint_addr); 588aef7908fSPavel Labath return; 589aef7908fSPavel Labath } 590aef7908fSPavel Labath 591aef7908fSPavel Labath // 592aef7908fSPavel Labath // We have a software breakpoint and need to adjust the PC. 593aef7908fSPavel Labath // 594aef7908fSPavel Labath 595aef7908fSPavel Labath // Change the program counter. 596aef7908fSPavel Labath LLDB_LOG(log, "pid {0} tid {1}: changing PC from {2:x} to {3:x}", GetID(), 597aef7908fSPavel Labath thread.GetID(), initial_pc_addr, breakpoint_addr); 598aef7908fSPavel Labath 599aef7908fSPavel Labath error = context.SetPC(breakpoint_addr); 600aef7908fSPavel Labath if (error.Fail()) { 601aef7908fSPavel Labath // This can happen in case the process was killed between the time we read 602aef7908fSPavel Labath // the PC and when we are updating it. There's nothing better to do than to 603aef7908fSPavel Labath // swallow the error. 604aef7908fSPavel Labath LLDB_LOG(log, "pid {0} tid {1}: failed to set PC: {2}", GetID(), 605aef7908fSPavel Labath thread.GetID(), error); 606aef7908fSPavel Labath } 607aef7908fSPavel Labath } 608aef7908fSPavel Labath 60997206d57SZachary Turner Status NativeProcessProtocol::RemoveBreakpoint(lldb::addr_t addr, 610d5ffbad2SOmair Javaid bool hardware) { 611d5ffbad2SOmair Javaid if (hardware) 612d5ffbad2SOmair Javaid return RemoveHardwareBreakpoint(addr); 613d5ffbad2SOmair Javaid else 614be828518SPavel Labath return RemoveSoftwareBreakpoint(addr); 615af245d11STodd Fiala } 616af245d11STodd Fiala 6172ce26527SPavel Labath Status NativeProcessProtocol::ReadMemoryWithoutTrap(lldb::addr_t addr, 6182ce26527SPavel Labath void *buf, size_t size, 6192ce26527SPavel Labath size_t &bytes_read) { 6202ce26527SPavel Labath Status error = ReadMemory(addr, buf, size, bytes_read); 6212ce26527SPavel Labath if (error.Fail()) 6222ce26527SPavel Labath return error; 623be828518SPavel Labath 624be828518SPavel Labath auto data = 625be828518SPavel Labath llvm::makeMutableArrayRef(static_cast<uint8_t *>(buf), bytes_read); 626be828518SPavel Labath for (const auto &pair : m_software_breakpoints) { 627be828518SPavel Labath lldb::addr_t bp_addr = pair.first; 628be828518SPavel Labath auto saved_opcodes = makeArrayRef(pair.second.saved_opcodes); 629be828518SPavel Labath 630be828518SPavel Labath if (bp_addr + saved_opcodes.size() < addr || addr + bytes_read <= bp_addr) 631e9264b74SKazuaki Ishizaki continue; // Breakpoint not in range, ignore 632be828518SPavel Labath 633be828518SPavel Labath if (bp_addr < addr) { 634be828518SPavel Labath saved_opcodes = saved_opcodes.drop_front(addr - bp_addr); 635be828518SPavel Labath bp_addr = addr; 636be828518SPavel Labath } 637be828518SPavel Labath auto bp_data = data.drop_front(bp_addr - addr); 638be828518SPavel Labath std::copy_n(saved_opcodes.begin(), 639be828518SPavel Labath std::min(saved_opcodes.size(), bp_data.size()), 640be828518SPavel Labath bp_data.begin()); 641be828518SPavel Labath } 642be828518SPavel Labath return Status(); 643be828518SPavel Labath } 644be828518SPavel Labath 64570795c1eSAntonio Afonso llvm::Expected<llvm::StringRef> 64670795c1eSAntonio Afonso NativeProcessProtocol::ReadCStringFromMemory(lldb::addr_t addr, char *buffer, 64770795c1eSAntonio Afonso size_t max_size, 64870795c1eSAntonio Afonso size_t &total_bytes_read) { 64970795c1eSAntonio Afonso static const size_t cache_line_size = 65070795c1eSAntonio Afonso llvm::sys::Process::getPageSizeEstimate(); 65170795c1eSAntonio Afonso size_t bytes_read = 0; 65270795c1eSAntonio Afonso size_t bytes_left = max_size; 65370795c1eSAntonio Afonso addr_t curr_addr = addr; 65470795c1eSAntonio Afonso size_t string_size; 65570795c1eSAntonio Afonso char *curr_buffer = buffer; 65670795c1eSAntonio Afonso total_bytes_read = 0; 65770795c1eSAntonio Afonso Status status; 65870795c1eSAntonio Afonso 65970795c1eSAntonio Afonso while (bytes_left > 0 && status.Success()) { 66070795c1eSAntonio Afonso addr_t cache_line_bytes_left = 66170795c1eSAntonio Afonso cache_line_size - (curr_addr % cache_line_size); 66270795c1eSAntonio Afonso addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left); 66365fdb342SRaphael Isemann status = ReadMemory(curr_addr, static_cast<void *>(curr_buffer), 66470795c1eSAntonio Afonso bytes_to_read, bytes_read); 66570795c1eSAntonio Afonso 66670795c1eSAntonio Afonso if (bytes_read == 0) 66770795c1eSAntonio Afonso break; 66870795c1eSAntonio Afonso 66970795c1eSAntonio Afonso void *str_end = std::memchr(curr_buffer, '\0', bytes_read); 67070795c1eSAntonio Afonso if (str_end != nullptr) { 67170795c1eSAntonio Afonso total_bytes_read = 67265fdb342SRaphael Isemann static_cast<size_t>((static_cast<char *>(str_end) - buffer + 1)); 67370795c1eSAntonio Afonso status.Clear(); 67470795c1eSAntonio Afonso break; 67570795c1eSAntonio Afonso } 67670795c1eSAntonio Afonso 67770795c1eSAntonio Afonso total_bytes_read += bytes_read; 67870795c1eSAntonio Afonso curr_buffer += bytes_read; 67970795c1eSAntonio Afonso curr_addr += bytes_read; 68070795c1eSAntonio Afonso bytes_left -= bytes_read; 68170795c1eSAntonio Afonso } 68270795c1eSAntonio Afonso 68370795c1eSAntonio Afonso string_size = total_bytes_read - 1; 68470795c1eSAntonio Afonso 68570795c1eSAntonio Afonso // Make sure we return a null terminated string. 68670795c1eSAntonio Afonso if (bytes_left == 0 && max_size > 0 && buffer[max_size - 1] != '\0') { 68770795c1eSAntonio Afonso buffer[max_size - 1] = '\0'; 68870795c1eSAntonio Afonso total_bytes_read--; 68970795c1eSAntonio Afonso } 69070795c1eSAntonio Afonso 69170795c1eSAntonio Afonso if (!status.Success()) 69270795c1eSAntonio Afonso return status.ToError(); 69370795c1eSAntonio Afonso 69470795c1eSAntonio Afonso return llvm::StringRef(buffer, string_size); 69570795c1eSAntonio Afonso } 69670795c1eSAntonio Afonso 697be828518SPavel Labath lldb::StateType NativeProcessProtocol::GetState() const { 698be828518SPavel Labath std::lock_guard<std::recursive_mutex> guard(m_state_mutex); 699be828518SPavel Labath return m_state; 7002ce26527SPavel Labath } 7012ce26527SPavel Labath 702b9c1b51eSKate Stone void NativeProcessProtocol::SetState(lldb::StateType state, 703b9c1b51eSKate Stone bool notify_delegates) { 70416ff8604SSaleem Abdulrasool std::lock_guard<std::recursive_mutex> guard(m_state_mutex); 7055830aa75STamas Berghammer 7065830aa75STamas Berghammer if (state == m_state) 7075830aa75STamas Berghammer return; 7085830aa75STamas Berghammer 709af245d11STodd Fiala m_state = state; 710af245d11STodd Fiala 711b9c1b51eSKate Stone if (StateIsStoppedState(state, false)) { 712af245d11STodd Fiala ++m_stop_id; 713af245d11STodd Fiala 714af245d11STodd Fiala // Give process a chance to do any stop id bump processing, such as 715af245d11STodd Fiala // clearing cached data that is invalidated each time the process runs. 71605097246SAdrian Prantl // Note if/when we support some threads running, we'll end up needing to 71705097246SAdrian Prantl // manage this per thread and per process. 718af245d11STodd Fiala DoStopIDBumped(m_stop_id); 719af245d11STodd Fiala } 720af245d11STodd Fiala 721af245d11STodd Fiala // Optionally notify delegates of the state change. 722af245d11STodd Fiala if (notify_delegates) 723af245d11STodd Fiala SynchronouslyNotifyProcessStateChanged(state); 724af245d11STodd Fiala } 725af245d11STodd Fiala 726b9c1b51eSKate Stone uint32_t NativeProcessProtocol::GetStopID() const { 72716ff8604SSaleem Abdulrasool std::lock_guard<std::recursive_mutex> guard(m_state_mutex); 728af245d11STodd Fiala return m_stop_id; 729af245d11STodd Fiala } 730af245d11STodd Fiala 731b9c1b51eSKate Stone void NativeProcessProtocol::DoStopIDBumped(uint32_t /* newBumpId */) { 732af245d11STodd Fiala // Default implementation does nothing. 733af245d11STodd Fiala } 7348bc34f4dSOleksiy Vyalov 73596e600fcSPavel Labath NativeProcessProtocol::Factory::~Factory() = default; 736