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); 315*1637545fSWalter 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 325c9cf394fSPavel Labath m_delegate.DidExec(this); 326a9882ceeSTodd Fiala } 327a9882ceeSTodd Fiala 32897206d57SZachary Turner Status NativeProcessProtocol::SetSoftwareBreakpoint(lldb::addr_t addr, 329b9c1b51eSKate Stone uint32_t size_hint) { 330a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Breakpoints); 331be828518SPavel Labath LLDB_LOG(log, "addr = {0:x}, size_hint = {1}", addr, size_hint); 332af245d11STodd Fiala 333be828518SPavel Labath auto it = m_software_breakpoints.find(addr); 334be828518SPavel Labath if (it != m_software_breakpoints.end()) { 335be828518SPavel Labath ++it->second.ref_count; 336be828518SPavel Labath return Status(); 337be828518SPavel Labath } 338be828518SPavel Labath auto expected_bkpt = EnableSoftwareBreakpoint(addr, size_hint); 339be828518SPavel Labath if (!expected_bkpt) 340be828518SPavel Labath return Status(expected_bkpt.takeError()); 341be828518SPavel Labath 342be828518SPavel Labath m_software_breakpoints.emplace(addr, std::move(*expected_bkpt)); 343be828518SPavel Labath return Status(); 344be828518SPavel Labath } 345be828518SPavel Labath 346be828518SPavel Labath Status NativeProcessProtocol::RemoveSoftwareBreakpoint(lldb::addr_t addr) { 347a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Breakpoints); 348be828518SPavel Labath LLDB_LOG(log, "addr = {0:x}", addr); 349be828518SPavel Labath auto it = m_software_breakpoints.find(addr); 350be828518SPavel Labath if (it == m_software_breakpoints.end()) 351be828518SPavel Labath return Status("Breakpoint not found."); 352be828518SPavel Labath assert(it->second.ref_count > 0); 353be828518SPavel Labath if (--it->second.ref_count > 0) 354be828518SPavel Labath return Status(); 355be828518SPavel Labath 356be828518SPavel Labath // This is the last reference. Let's remove the breakpoint. 357be828518SPavel Labath Status error; 358be828518SPavel Labath 359be828518SPavel Labath // Clear a software breakpoint instruction 360be828518SPavel Labath llvm::SmallVector<uint8_t, 4> curr_break_op( 361be828518SPavel Labath it->second.breakpoint_opcodes.size(), 0); 362be828518SPavel Labath 363be828518SPavel Labath // Read the breakpoint opcode 364be828518SPavel Labath size_t bytes_read = 0; 365be828518SPavel Labath error = 366be828518SPavel Labath ReadMemory(addr, curr_break_op.data(), curr_break_op.size(), bytes_read); 367be828518SPavel Labath if (error.Fail() || bytes_read < curr_break_op.size()) { 368be828518SPavel Labath return Status("addr=0x%" PRIx64 369be828518SPavel Labath ": tried to read %zu bytes but only read %zu", 370be828518SPavel Labath addr, curr_break_op.size(), bytes_read); 371be828518SPavel Labath } 372be828518SPavel Labath const auto &saved = it->second.saved_opcodes; 373be828518SPavel Labath // Make sure the breakpoint opcode exists at this address 374be828518SPavel Labath if (makeArrayRef(curr_break_op) != it->second.breakpoint_opcodes) { 375be828518SPavel Labath if (curr_break_op != it->second.saved_opcodes) 376be828518SPavel Labath return Status("Original breakpoint trap is no longer in memory."); 377be828518SPavel Labath LLDB_LOG(log, 378be828518SPavel Labath "Saved opcodes ({0:@[x]}) have already been restored at {1:x}.", 379be828518SPavel Labath llvm::make_range(saved.begin(), saved.end()), addr); 380be828518SPavel Labath } else { 381be828518SPavel Labath // We found a valid breakpoint opcode at this address, now restore the 382be828518SPavel Labath // saved opcode. 383be828518SPavel Labath size_t bytes_written = 0; 384be828518SPavel Labath error = WriteMemory(addr, saved.data(), saved.size(), bytes_written); 385be828518SPavel Labath if (error.Fail() || bytes_written < saved.size()) { 386be828518SPavel Labath return Status("addr=0x%" PRIx64 387be828518SPavel Labath ": tried to write %zu bytes but only wrote %zu", 388be828518SPavel Labath addr, saved.size(), bytes_written); 389be828518SPavel Labath } 390be828518SPavel Labath 391be828518SPavel Labath // Verify that our original opcode made it back to the inferior 392be828518SPavel Labath llvm::SmallVector<uint8_t, 4> verify_opcode(saved.size(), 0); 393be828518SPavel Labath size_t verify_bytes_read = 0; 394be828518SPavel Labath error = ReadMemory(addr, verify_opcode.data(), verify_opcode.size(), 395be828518SPavel Labath verify_bytes_read); 396be828518SPavel Labath if (error.Fail() || verify_bytes_read < verify_opcode.size()) { 397be828518SPavel Labath return Status("addr=0x%" PRIx64 398be828518SPavel Labath ": tried to read %zu verification bytes but only read %zu", 399be828518SPavel Labath addr, verify_opcode.size(), verify_bytes_read); 400be828518SPavel Labath } 401be828518SPavel Labath if (verify_opcode != saved) 402be828518SPavel Labath LLDB_LOG(log, "Restoring bytes at {0:x}: {1:@[x]}", addr, 403be828518SPavel Labath llvm::make_range(saved.begin(), saved.end())); 404be828518SPavel Labath } 405be828518SPavel Labath 406be828518SPavel Labath m_software_breakpoints.erase(it); 407be828518SPavel Labath return Status(); 408be828518SPavel Labath } 409be828518SPavel Labath 410be828518SPavel Labath llvm::Expected<NativeProcessProtocol::SoftwareBreakpoint> 411be828518SPavel Labath NativeProcessProtocol::EnableSoftwareBreakpoint(lldb::addr_t addr, 412be828518SPavel Labath uint32_t size_hint) { 413a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Breakpoints); 414be828518SPavel Labath 415be828518SPavel Labath auto expected_trap = GetSoftwareBreakpointTrapOpcode(size_hint); 416be828518SPavel Labath if (!expected_trap) 417be828518SPavel Labath return expected_trap.takeError(); 418be828518SPavel Labath 419be828518SPavel Labath llvm::SmallVector<uint8_t, 4> saved_opcode_bytes(expected_trap->size(), 0); 420be828518SPavel Labath // Save the original opcodes by reading them so we can restore later. 421be828518SPavel Labath size_t bytes_read = 0; 422be828518SPavel Labath Status error = ReadMemory(addr, saved_opcode_bytes.data(), 423be828518SPavel Labath saved_opcode_bytes.size(), bytes_read); 424be828518SPavel Labath if (error.Fail()) 425be828518SPavel Labath return error.ToError(); 426be828518SPavel Labath 427be828518SPavel Labath // Ensure we read as many bytes as we expected. 428be828518SPavel Labath if (bytes_read != saved_opcode_bytes.size()) { 429be828518SPavel Labath return llvm::createStringError( 430be828518SPavel Labath llvm::inconvertibleErrorCode(), 431be828518SPavel Labath "Failed to read memory while attempting to set breakpoint: attempted " 432be828518SPavel Labath "to read {0} bytes but only read {1}.", 433be828518SPavel Labath saved_opcode_bytes.size(), bytes_read); 434be828518SPavel Labath } 435be828518SPavel Labath 436be828518SPavel Labath LLDB_LOG( 437be828518SPavel Labath log, "Overwriting bytes at {0:x}: {1:@[x]}", addr, 438be828518SPavel Labath llvm::make_range(saved_opcode_bytes.begin(), saved_opcode_bytes.end())); 439be828518SPavel Labath 440be828518SPavel Labath // Write a software breakpoint in place of the original opcode. 441be828518SPavel Labath size_t bytes_written = 0; 442be828518SPavel Labath error = WriteMemory(addr, expected_trap->data(), expected_trap->size(), 443be828518SPavel Labath bytes_written); 444be828518SPavel Labath if (error.Fail()) 445be828518SPavel Labath return error.ToError(); 446be828518SPavel Labath 447be828518SPavel Labath // Ensure we wrote as many bytes as we expected. 448be828518SPavel Labath if (bytes_written != expected_trap->size()) { 449be828518SPavel Labath return llvm::createStringError( 450be828518SPavel Labath llvm::inconvertibleErrorCode(), 451be828518SPavel Labath "Failed write memory while attempting to set " 452be828518SPavel Labath "breakpoint: attempted to write {0} bytes but only wrote {1}", 453be828518SPavel Labath expected_trap->size(), bytes_written); 454be828518SPavel Labath } 455be828518SPavel Labath 456be828518SPavel Labath llvm::SmallVector<uint8_t, 4> verify_bp_opcode_bytes(expected_trap->size(), 457be828518SPavel Labath 0); 458be828518SPavel Labath size_t verify_bytes_read = 0; 459be828518SPavel Labath error = ReadMemory(addr, verify_bp_opcode_bytes.data(), 460be828518SPavel Labath verify_bp_opcode_bytes.size(), verify_bytes_read); 461be828518SPavel Labath if (error.Fail()) 462be828518SPavel Labath return error.ToError(); 463be828518SPavel Labath 464be828518SPavel Labath // Ensure we read as many verification bytes as we expected. 465be828518SPavel Labath if (verify_bytes_read != verify_bp_opcode_bytes.size()) { 466be828518SPavel Labath return llvm::createStringError( 467be828518SPavel Labath llvm::inconvertibleErrorCode(), 468be828518SPavel Labath "Failed to read memory while " 469be828518SPavel Labath "attempting to verify breakpoint: attempted to read {0} bytes " 470be828518SPavel Labath "but only read {1}", 471be828518SPavel Labath verify_bp_opcode_bytes.size(), verify_bytes_read); 472be828518SPavel Labath } 473be828518SPavel Labath 474be828518SPavel Labath if (llvm::makeArrayRef(verify_bp_opcode_bytes.data(), verify_bytes_read) != 475be828518SPavel Labath *expected_trap) { 476be828518SPavel Labath return llvm::createStringError( 477be828518SPavel Labath llvm::inconvertibleErrorCode(), 478be828518SPavel Labath "Verification of software breakpoint " 479be828518SPavel Labath "writing failed - trap opcodes not successfully read back " 480be828518SPavel Labath "after writing when setting breakpoint at {0:x}", 481be828518SPavel Labath addr); 482be828518SPavel Labath } 483be828518SPavel Labath 484b075bbd9SPavel Labath LLDB_LOG(log, "addr = {0:x}: SUCCESS", addr); 485be828518SPavel Labath return SoftwareBreakpoint{1, saved_opcode_bytes, *expected_trap}; 486af245d11STodd Fiala } 487af245d11STodd Fiala 488f8b825f6SPavel Labath llvm::Expected<llvm::ArrayRef<uint8_t>> 489f8b825f6SPavel Labath NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_t size_hint) { 490f8b825f6SPavel Labath static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4}; 491f8b825f6SPavel Labath static const uint8_t g_i386_opcode[] = {0xCC}; 492f8b825f6SPavel Labath static const uint8_t g_mips64_opcode[] = {0x00, 0x00, 0x00, 0x0d}; 493f8b825f6SPavel Labath static const uint8_t g_mips64el_opcode[] = {0x0d, 0x00, 0x00, 0x00}; 494f8b825f6SPavel Labath static const uint8_t g_s390x_opcode[] = {0x00, 0x01}; 495bd03f6dfSMichał Górny static const uint8_t g_ppc_opcode[] = {0x7f, 0xe0, 0x00, 0x08}; // trap 496bd03f6dfSMichał Górny static const uint8_t g_ppcle_opcode[] = {0x08, 0x00, 0xe0, 0x7f}; // trap 497f8b825f6SPavel Labath 498f8b825f6SPavel Labath switch (GetArchitecture().GetMachine()) { 499f8b825f6SPavel Labath case llvm::Triple::aarch64: 5007dd7a360SJason Molenda case llvm::Triple::aarch64_32: 5014f545074SPavel Labath return llvm::makeArrayRef(g_aarch64_opcode); 502f8b825f6SPavel Labath 503f8b825f6SPavel Labath case llvm::Triple::x86: 504f8b825f6SPavel Labath case llvm::Triple::x86_64: 5054f545074SPavel Labath return llvm::makeArrayRef(g_i386_opcode); 506f8b825f6SPavel Labath 507f8b825f6SPavel Labath case llvm::Triple::mips: 508f8b825f6SPavel Labath case llvm::Triple::mips64: 5094f545074SPavel Labath return llvm::makeArrayRef(g_mips64_opcode); 510f8b825f6SPavel Labath 511f8b825f6SPavel Labath case llvm::Triple::mipsel: 512f8b825f6SPavel Labath case llvm::Triple::mips64el: 5134f545074SPavel Labath return llvm::makeArrayRef(g_mips64el_opcode); 514f8b825f6SPavel Labath 515f8b825f6SPavel Labath case llvm::Triple::systemz: 5164f545074SPavel Labath return llvm::makeArrayRef(g_s390x_opcode); 517f8b825f6SPavel Labath 518bd03f6dfSMichał Górny case llvm::Triple::ppc: 519bd03f6dfSMichał Górny case llvm::Triple::ppc64: 520bd03f6dfSMichał Górny return llvm::makeArrayRef(g_ppc_opcode); 521bd03f6dfSMichał Górny 522f8b825f6SPavel Labath case llvm::Triple::ppc64le: 523bd03f6dfSMichał Górny return llvm::makeArrayRef(g_ppcle_opcode); 524f8b825f6SPavel Labath 525f8b825f6SPavel Labath default: 526f8b825f6SPavel Labath return llvm::createStringError(llvm::inconvertibleErrorCode(), 527f8b825f6SPavel Labath "CPU type not supported!"); 528f8b825f6SPavel Labath } 529f8b825f6SPavel Labath } 530f8b825f6SPavel Labath 53199f436b0SPavel Labath size_t NativeProcessProtocol::GetSoftwareBreakpointPCOffset() { 53299f436b0SPavel Labath switch (GetArchitecture().GetMachine()) { 53399f436b0SPavel Labath case llvm::Triple::x86: 53499f436b0SPavel Labath case llvm::Triple::x86_64: 53599f436b0SPavel Labath case llvm::Triple::systemz: 53699f436b0SPavel Labath // These architectures report increment the PC after breakpoint is hit. 53799f436b0SPavel Labath return cantFail(GetSoftwareBreakpointTrapOpcode(0)).size(); 53899f436b0SPavel Labath 53999f436b0SPavel Labath case llvm::Triple::arm: 54099f436b0SPavel Labath case llvm::Triple::aarch64: 5417dd7a360SJason Molenda case llvm::Triple::aarch64_32: 54299f436b0SPavel Labath case llvm::Triple::mips64: 54399f436b0SPavel Labath case llvm::Triple::mips64el: 54499f436b0SPavel Labath case llvm::Triple::mips: 54599f436b0SPavel Labath case llvm::Triple::mipsel: 546bd03f6dfSMichał Górny case llvm::Triple::ppc: 547bd03f6dfSMichał Górny case llvm::Triple::ppc64: 54899f436b0SPavel Labath case llvm::Triple::ppc64le: 54999f436b0SPavel Labath // On these architectures the PC doesn't get updated for breakpoint hits. 55099f436b0SPavel Labath return 0; 55199f436b0SPavel Labath 55299f436b0SPavel Labath default: 55399f436b0SPavel Labath llvm_unreachable("CPU type not supported!"); 55499f436b0SPavel Labath } 55599f436b0SPavel Labath } 55699f436b0SPavel Labath 557aef7908fSPavel Labath void NativeProcessProtocol::FixupBreakpointPCAsNeeded( 558aef7908fSPavel Labath NativeThreadProtocol &thread) { 559a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Breakpoints); 560aef7908fSPavel Labath 561aef7908fSPavel Labath Status error; 562aef7908fSPavel Labath 563aef7908fSPavel Labath // Find out the size of a breakpoint (might depend on where we are in the 564aef7908fSPavel Labath // code). 565aef7908fSPavel Labath NativeRegisterContext &context = thread.GetRegisterContext(); 566aef7908fSPavel Labath 567aef7908fSPavel Labath uint32_t breakpoint_size = GetSoftwareBreakpointPCOffset(); 568aef7908fSPavel Labath LLDB_LOG(log, "breakpoint size: {0}", breakpoint_size); 569aef7908fSPavel Labath if (breakpoint_size == 0) 570aef7908fSPavel Labath return; 571aef7908fSPavel Labath 572aef7908fSPavel Labath // First try probing for a breakpoint at a software breakpoint location: PC - 573aef7908fSPavel Labath // breakpoint size. 574aef7908fSPavel Labath const lldb::addr_t initial_pc_addr = context.GetPCfromBreakpointLocation(); 575aef7908fSPavel Labath lldb::addr_t breakpoint_addr = initial_pc_addr; 576aef7908fSPavel Labath // Do not allow breakpoint probe to wrap around. 577aef7908fSPavel Labath if (breakpoint_addr >= breakpoint_size) 578aef7908fSPavel Labath breakpoint_addr -= breakpoint_size; 579aef7908fSPavel Labath 580be828518SPavel Labath if (m_software_breakpoints.count(breakpoint_addr) == 0) { 581aef7908fSPavel Labath // We didn't find one at a software probe location. Nothing to do. 582aef7908fSPavel Labath LLDB_LOG(log, 583be828518SPavel Labath "pid {0} no lldb software breakpoint found at current pc with " 584aef7908fSPavel Labath "adjustment: {1}", 585aef7908fSPavel Labath GetID(), breakpoint_addr); 586aef7908fSPavel Labath return; 587aef7908fSPavel Labath } 588aef7908fSPavel Labath 589aef7908fSPavel Labath // 590aef7908fSPavel Labath // We have a software breakpoint and need to adjust the PC. 591aef7908fSPavel Labath // 592aef7908fSPavel Labath 593aef7908fSPavel Labath // Change the program counter. 594aef7908fSPavel Labath LLDB_LOG(log, "pid {0} tid {1}: changing PC from {2:x} to {3:x}", GetID(), 595aef7908fSPavel Labath thread.GetID(), initial_pc_addr, breakpoint_addr); 596aef7908fSPavel Labath 597aef7908fSPavel Labath error = context.SetPC(breakpoint_addr); 598aef7908fSPavel Labath if (error.Fail()) { 599aef7908fSPavel Labath // This can happen in case the process was killed between the time we read 600aef7908fSPavel Labath // the PC and when we are updating it. There's nothing better to do than to 601aef7908fSPavel Labath // swallow the error. 602aef7908fSPavel Labath LLDB_LOG(log, "pid {0} tid {1}: failed to set PC: {2}", GetID(), 603aef7908fSPavel Labath thread.GetID(), error); 604aef7908fSPavel Labath } 605aef7908fSPavel Labath } 606aef7908fSPavel Labath 60797206d57SZachary Turner Status NativeProcessProtocol::RemoveBreakpoint(lldb::addr_t addr, 608d5ffbad2SOmair Javaid bool hardware) { 609d5ffbad2SOmair Javaid if (hardware) 610d5ffbad2SOmair Javaid return RemoveHardwareBreakpoint(addr); 611d5ffbad2SOmair Javaid else 612be828518SPavel Labath return RemoveSoftwareBreakpoint(addr); 613af245d11STodd Fiala } 614af245d11STodd Fiala 6152ce26527SPavel Labath Status NativeProcessProtocol::ReadMemoryWithoutTrap(lldb::addr_t addr, 6162ce26527SPavel Labath void *buf, size_t size, 6172ce26527SPavel Labath size_t &bytes_read) { 6182ce26527SPavel Labath Status error = ReadMemory(addr, buf, size, bytes_read); 6192ce26527SPavel Labath if (error.Fail()) 6202ce26527SPavel Labath return error; 621be828518SPavel Labath 622be828518SPavel Labath auto data = 623be828518SPavel Labath llvm::makeMutableArrayRef(static_cast<uint8_t *>(buf), bytes_read); 624be828518SPavel Labath for (const auto &pair : m_software_breakpoints) { 625be828518SPavel Labath lldb::addr_t bp_addr = pair.first; 626be828518SPavel Labath auto saved_opcodes = makeArrayRef(pair.second.saved_opcodes); 627be828518SPavel Labath 628be828518SPavel Labath if (bp_addr + saved_opcodes.size() < addr || addr + bytes_read <= bp_addr) 629e9264b74SKazuaki Ishizaki continue; // Breakpoint not in range, ignore 630be828518SPavel Labath 631be828518SPavel Labath if (bp_addr < addr) { 632be828518SPavel Labath saved_opcodes = saved_opcodes.drop_front(addr - bp_addr); 633be828518SPavel Labath bp_addr = addr; 634be828518SPavel Labath } 635be828518SPavel Labath auto bp_data = data.drop_front(bp_addr - addr); 636be828518SPavel Labath std::copy_n(saved_opcodes.begin(), 637be828518SPavel Labath std::min(saved_opcodes.size(), bp_data.size()), 638be828518SPavel Labath bp_data.begin()); 639be828518SPavel Labath } 640be828518SPavel Labath return Status(); 641be828518SPavel Labath } 642be828518SPavel Labath 64370795c1eSAntonio Afonso llvm::Expected<llvm::StringRef> 64470795c1eSAntonio Afonso NativeProcessProtocol::ReadCStringFromMemory(lldb::addr_t addr, char *buffer, 64570795c1eSAntonio Afonso size_t max_size, 64670795c1eSAntonio Afonso size_t &total_bytes_read) { 64770795c1eSAntonio Afonso static const size_t cache_line_size = 64870795c1eSAntonio Afonso llvm::sys::Process::getPageSizeEstimate(); 64970795c1eSAntonio Afonso size_t bytes_read = 0; 65070795c1eSAntonio Afonso size_t bytes_left = max_size; 65170795c1eSAntonio Afonso addr_t curr_addr = addr; 65270795c1eSAntonio Afonso size_t string_size; 65370795c1eSAntonio Afonso char *curr_buffer = buffer; 65470795c1eSAntonio Afonso total_bytes_read = 0; 65570795c1eSAntonio Afonso Status status; 65670795c1eSAntonio Afonso 65770795c1eSAntonio Afonso while (bytes_left > 0 && status.Success()) { 65870795c1eSAntonio Afonso addr_t cache_line_bytes_left = 65970795c1eSAntonio Afonso cache_line_size - (curr_addr % cache_line_size); 66070795c1eSAntonio Afonso addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left); 66165fdb342SRaphael Isemann status = ReadMemory(curr_addr, static_cast<void *>(curr_buffer), 66270795c1eSAntonio Afonso bytes_to_read, bytes_read); 66370795c1eSAntonio Afonso 66470795c1eSAntonio Afonso if (bytes_read == 0) 66570795c1eSAntonio Afonso break; 66670795c1eSAntonio Afonso 66770795c1eSAntonio Afonso void *str_end = std::memchr(curr_buffer, '\0', bytes_read); 66870795c1eSAntonio Afonso if (str_end != nullptr) { 66970795c1eSAntonio Afonso total_bytes_read = 67065fdb342SRaphael Isemann static_cast<size_t>((static_cast<char *>(str_end) - buffer + 1)); 67170795c1eSAntonio Afonso status.Clear(); 67270795c1eSAntonio Afonso break; 67370795c1eSAntonio Afonso } 67470795c1eSAntonio Afonso 67570795c1eSAntonio Afonso total_bytes_read += bytes_read; 67670795c1eSAntonio Afonso curr_buffer += bytes_read; 67770795c1eSAntonio Afonso curr_addr += bytes_read; 67870795c1eSAntonio Afonso bytes_left -= bytes_read; 67970795c1eSAntonio Afonso } 68070795c1eSAntonio Afonso 68170795c1eSAntonio Afonso string_size = total_bytes_read - 1; 68270795c1eSAntonio Afonso 68370795c1eSAntonio Afonso // Make sure we return a null terminated string. 68470795c1eSAntonio Afonso if (bytes_left == 0 && max_size > 0 && buffer[max_size - 1] != '\0') { 68570795c1eSAntonio Afonso buffer[max_size - 1] = '\0'; 68670795c1eSAntonio Afonso total_bytes_read--; 68770795c1eSAntonio Afonso } 68870795c1eSAntonio Afonso 68970795c1eSAntonio Afonso if (!status.Success()) 69070795c1eSAntonio Afonso return status.ToError(); 69170795c1eSAntonio Afonso 69270795c1eSAntonio Afonso return llvm::StringRef(buffer, string_size); 69370795c1eSAntonio Afonso } 69470795c1eSAntonio Afonso 695be828518SPavel Labath lldb::StateType NativeProcessProtocol::GetState() const { 696be828518SPavel Labath std::lock_guard<std::recursive_mutex> guard(m_state_mutex); 697be828518SPavel Labath return m_state; 6982ce26527SPavel Labath } 6992ce26527SPavel Labath 700b9c1b51eSKate Stone void NativeProcessProtocol::SetState(lldb::StateType state, 701b9c1b51eSKate Stone bool notify_delegates) { 70216ff8604SSaleem Abdulrasool std::lock_guard<std::recursive_mutex> guard(m_state_mutex); 7035830aa75STamas Berghammer 7045830aa75STamas Berghammer if (state == m_state) 7055830aa75STamas Berghammer return; 7065830aa75STamas Berghammer 707af245d11STodd Fiala m_state = state; 708af245d11STodd Fiala 709b9c1b51eSKate Stone if (StateIsStoppedState(state, false)) { 710af245d11STodd Fiala ++m_stop_id; 711af245d11STodd Fiala 712af245d11STodd Fiala // Give process a chance to do any stop id bump processing, such as 713af245d11STodd Fiala // clearing cached data that is invalidated each time the process runs. 71405097246SAdrian Prantl // Note if/when we support some threads running, we'll end up needing to 71505097246SAdrian Prantl // manage this per thread and per process. 716af245d11STodd Fiala DoStopIDBumped(m_stop_id); 717af245d11STodd Fiala } 718af245d11STodd Fiala 719af245d11STodd Fiala // Optionally notify delegates of the state change. 720af245d11STodd Fiala if (notify_delegates) 721af245d11STodd Fiala SynchronouslyNotifyProcessStateChanged(state); 722af245d11STodd Fiala } 723af245d11STodd Fiala 724b9c1b51eSKate Stone uint32_t NativeProcessProtocol::GetStopID() const { 72516ff8604SSaleem Abdulrasool std::lock_guard<std::recursive_mutex> guard(m_state_mutex); 726af245d11STodd Fiala return m_stop_id; 727af245d11STodd Fiala } 728af245d11STodd Fiala 729b9c1b51eSKate Stone void NativeProcessProtocol::DoStopIDBumped(uint32_t /* newBumpId */) { 730af245d11STodd Fiala // Default implementation does nothing. 731af245d11STodd Fiala } 7328bc34f4dSOleksiy Vyalov 73396e600fcSPavel Labath NativeProcessProtocol::Factory::~Factory() = default; 734