1dda28197Spatrick //===-- NativeProcessProtocol.cpp -----------------------------------------===//
2061da546Spatrick //
3061da546Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4061da546Spatrick // See https://llvm.org/LICENSE.txt for license information.
5061da546Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6061da546Spatrick //
7061da546Spatrick //===----------------------------------------------------------------------===//
8061da546Spatrick
9061da546Spatrick #include "lldb/Host/common/NativeProcessProtocol.h"
10061da546Spatrick #include "lldb/Host/Host.h"
11061da546Spatrick #include "lldb/Host/common/NativeBreakpointList.h"
12061da546Spatrick #include "lldb/Host/common/NativeRegisterContext.h"
13061da546Spatrick #include "lldb/Host/common/NativeThreadProtocol.h"
14061da546Spatrick #include "lldb/Utility/LLDBAssert.h"
15*f6aab3d8Srobert #include "lldb/Utility/LLDBLog.h"
16061da546Spatrick #include "lldb/Utility/Log.h"
17061da546Spatrick #include "lldb/Utility/State.h"
18061da546Spatrick #include "lldb/lldb-enumerations.h"
19061da546Spatrick
20061da546Spatrick #include "llvm/Support/Process.h"
21*f6aab3d8Srobert #include <optional>
22061da546Spatrick
23061da546Spatrick using namespace lldb;
24061da546Spatrick using namespace lldb_private;
25061da546Spatrick
26061da546Spatrick // NativeProcessProtocol Members
27061da546Spatrick
NativeProcessProtocol(lldb::pid_t pid,int terminal_fd,NativeDelegate & delegate)28061da546Spatrick NativeProcessProtocol::NativeProcessProtocol(lldb::pid_t pid, int terminal_fd,
29061da546Spatrick NativeDelegate &delegate)
30be691f3bSpatrick : m_pid(pid), m_delegate(delegate), m_terminal_fd(terminal_fd) {
31be691f3bSpatrick delegate.InitializeDelegate(this);
32061da546Spatrick }
33061da546Spatrick
Interrupt()34061da546Spatrick lldb_private::Status NativeProcessProtocol::Interrupt() {
35061da546Spatrick Status error;
36061da546Spatrick #if !defined(SIGSTOP)
37061da546Spatrick error.SetErrorString("local host does not support signaling");
38061da546Spatrick return error;
39061da546Spatrick #else
40061da546Spatrick return Signal(SIGSTOP);
41061da546Spatrick #endif
42061da546Spatrick }
43061da546Spatrick
IgnoreSignals(llvm::ArrayRef<int> signals)44061da546Spatrick Status NativeProcessProtocol::IgnoreSignals(llvm::ArrayRef<int> signals) {
45061da546Spatrick m_signals_to_ignore.clear();
46061da546Spatrick m_signals_to_ignore.insert(signals.begin(), signals.end());
47061da546Spatrick return Status();
48061da546Spatrick }
49061da546Spatrick
50061da546Spatrick lldb_private::Status
GetMemoryRegionInfo(lldb::addr_t load_addr,MemoryRegionInfo & range_info)51061da546Spatrick NativeProcessProtocol::GetMemoryRegionInfo(lldb::addr_t load_addr,
52061da546Spatrick MemoryRegionInfo &range_info) {
53061da546Spatrick // Default: not implemented.
54061da546Spatrick return Status("not implemented");
55061da546Spatrick }
56061da546Spatrick
57be691f3bSpatrick lldb_private::Status
ReadMemoryTags(int32_t type,lldb::addr_t addr,size_t len,std::vector<uint8_t> & tags)58be691f3bSpatrick NativeProcessProtocol::ReadMemoryTags(int32_t type, lldb::addr_t addr,
59be691f3bSpatrick size_t len, std::vector<uint8_t> &tags) {
60be691f3bSpatrick return Status("not implemented");
61be691f3bSpatrick }
62be691f3bSpatrick
63be691f3bSpatrick lldb_private::Status
WriteMemoryTags(int32_t type,lldb::addr_t addr,size_t len,const std::vector<uint8_t> & tags)64be691f3bSpatrick NativeProcessProtocol::WriteMemoryTags(int32_t type, lldb::addr_t addr,
65be691f3bSpatrick size_t len,
66be691f3bSpatrick const std::vector<uint8_t> &tags) {
67be691f3bSpatrick return Status("not implemented");
68be691f3bSpatrick }
69be691f3bSpatrick
GetExitStatus()70*f6aab3d8Srobert std::optional<WaitStatus> NativeProcessProtocol::GetExitStatus() {
71061da546Spatrick if (m_state == lldb::eStateExited)
72061da546Spatrick return m_exit_status;
73061da546Spatrick
74*f6aab3d8Srobert return std::nullopt;
75061da546Spatrick }
76061da546Spatrick
SetExitStatus(WaitStatus status,bool bNotifyStateChange)77061da546Spatrick bool NativeProcessProtocol::SetExitStatus(WaitStatus status,
78061da546Spatrick bool bNotifyStateChange) {
79*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
80061da546Spatrick LLDB_LOG(log, "status = {0}, notify = {1}", status, bNotifyStateChange);
81061da546Spatrick
82061da546Spatrick // Exit status already set
83061da546Spatrick if (m_state == lldb::eStateExited) {
84061da546Spatrick if (m_exit_status)
85061da546Spatrick LLDB_LOG(log, "exit status already set to {0}", *m_exit_status);
86061da546Spatrick else
87061da546Spatrick LLDB_LOG(log, "state is exited, but status not set");
88061da546Spatrick return false;
89061da546Spatrick }
90061da546Spatrick
91061da546Spatrick m_state = lldb::eStateExited;
92061da546Spatrick m_exit_status = status;
93061da546Spatrick
94061da546Spatrick if (bNotifyStateChange)
95061da546Spatrick SynchronouslyNotifyProcessStateChanged(lldb::eStateExited);
96061da546Spatrick
97061da546Spatrick return true;
98061da546Spatrick }
99061da546Spatrick
GetThreadAtIndex(uint32_t idx)100061da546Spatrick NativeThreadProtocol *NativeProcessProtocol::GetThreadAtIndex(uint32_t idx) {
101061da546Spatrick std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
102061da546Spatrick if (idx < m_threads.size())
103061da546Spatrick return m_threads[idx].get();
104061da546Spatrick return nullptr;
105061da546Spatrick }
106061da546Spatrick
107061da546Spatrick NativeThreadProtocol *
GetThreadByIDUnlocked(lldb::tid_t tid)108061da546Spatrick NativeProcessProtocol::GetThreadByIDUnlocked(lldb::tid_t tid) {
109061da546Spatrick for (const auto &thread : m_threads) {
110061da546Spatrick if (thread->GetID() == tid)
111061da546Spatrick return thread.get();
112061da546Spatrick }
113061da546Spatrick return nullptr;
114061da546Spatrick }
115061da546Spatrick
GetThreadByID(lldb::tid_t tid)116061da546Spatrick NativeThreadProtocol *NativeProcessProtocol::GetThreadByID(lldb::tid_t tid) {
117061da546Spatrick std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
118061da546Spatrick return GetThreadByIDUnlocked(tid);
119061da546Spatrick }
120061da546Spatrick
IsAlive() const121061da546Spatrick bool NativeProcessProtocol::IsAlive() const {
122061da546Spatrick return m_state != eStateDetached && m_state != eStateExited &&
123061da546Spatrick m_state != eStateInvalid && m_state != eStateUnloaded;
124061da546Spatrick }
125061da546Spatrick
126061da546Spatrick const NativeWatchpointList::WatchpointMap &
GetWatchpointMap() const127061da546Spatrick NativeProcessProtocol::GetWatchpointMap() const {
128061da546Spatrick return m_watchpoint_list.GetWatchpointMap();
129061da546Spatrick }
130061da546Spatrick
131*f6aab3d8Srobert std::optional<std::pair<uint32_t, uint32_t>>
GetHardwareDebugSupportInfo() const132061da546Spatrick NativeProcessProtocol::GetHardwareDebugSupportInfo() const {
133*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
134061da546Spatrick
135061da546Spatrick // get any thread
136061da546Spatrick NativeThreadProtocol *thread(
137061da546Spatrick const_cast<NativeProcessProtocol *>(this)->GetThreadAtIndex(0));
138061da546Spatrick if (!thread) {
139061da546Spatrick LLDB_LOG(log, "failed to find a thread to grab a NativeRegisterContext!");
140*f6aab3d8Srobert return std::nullopt;
141061da546Spatrick }
142061da546Spatrick
143061da546Spatrick NativeRegisterContext ®_ctx = thread->GetRegisterContext();
144061da546Spatrick return std::make_pair(reg_ctx.NumSupportedHardwareBreakpoints(),
145061da546Spatrick reg_ctx.NumSupportedHardwareWatchpoints());
146061da546Spatrick }
147061da546Spatrick
SetWatchpoint(lldb::addr_t addr,size_t size,uint32_t watch_flags,bool hardware)148061da546Spatrick Status NativeProcessProtocol::SetWatchpoint(lldb::addr_t addr, size_t size,
149061da546Spatrick uint32_t watch_flags,
150061da546Spatrick bool hardware) {
151061da546Spatrick // This default implementation assumes setting the watchpoint for the process
152061da546Spatrick // will require setting the watchpoint for each of the threads. Furthermore,
153061da546Spatrick // it will track watchpoints set for the process and will add them to each
154061da546Spatrick // thread that is attached to via the (FIXME implement) OnThreadAttached ()
155061da546Spatrick // method.
156061da546Spatrick
157*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
158061da546Spatrick
159061da546Spatrick // Update the thread list
160061da546Spatrick UpdateThreads();
161061da546Spatrick
162061da546Spatrick // Keep track of the threads we successfully set the watchpoint for. If one
163061da546Spatrick // of the thread watchpoint setting operations fails, back off and remove the
164061da546Spatrick // watchpoint for all the threads that were successfully set so we get back
165061da546Spatrick // to a consistent state.
166061da546Spatrick std::vector<NativeThreadProtocol *> watchpoint_established_threads;
167061da546Spatrick
168061da546Spatrick // Tell each thread to set a watchpoint. In the event that hardware
169061da546Spatrick // watchpoints are requested but the SetWatchpoint fails, try to set a
170061da546Spatrick // software watchpoint as a fallback. It's conceivable that if there are
171061da546Spatrick // more threads than hardware watchpoints available, some of the threads will
172061da546Spatrick // fail to set hardware watchpoints while software ones may be available.
173061da546Spatrick std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
174061da546Spatrick for (const auto &thread : m_threads) {
175061da546Spatrick assert(thread && "thread list should not have a NULL thread!");
176061da546Spatrick
177061da546Spatrick Status thread_error =
178061da546Spatrick thread->SetWatchpoint(addr, size, watch_flags, hardware);
179061da546Spatrick if (thread_error.Fail() && hardware) {
180061da546Spatrick // Try software watchpoints since we failed on hardware watchpoint
181061da546Spatrick // setting and we may have just run out of hardware watchpoints.
182061da546Spatrick thread_error = thread->SetWatchpoint(addr, size, watch_flags, false);
183061da546Spatrick if (thread_error.Success())
184061da546Spatrick LLDB_LOG(log,
185061da546Spatrick "hardware watchpoint requested but software watchpoint set");
186061da546Spatrick }
187061da546Spatrick
188061da546Spatrick if (thread_error.Success()) {
189061da546Spatrick // Remember that we set this watchpoint successfully in case we need to
190061da546Spatrick // clear it later.
191061da546Spatrick watchpoint_established_threads.push_back(thread.get());
192061da546Spatrick } else {
193061da546Spatrick // Unset the watchpoint for each thread we successfully set so that we
194061da546Spatrick // get back to a consistent state of "not set" for the watchpoint.
195061da546Spatrick for (auto unwatch_thread_sp : watchpoint_established_threads) {
196061da546Spatrick Status remove_error = unwatch_thread_sp->RemoveWatchpoint(addr);
197061da546Spatrick if (remove_error.Fail())
198061da546Spatrick LLDB_LOG(log, "RemoveWatchpoint failed for pid={0}, tid={1}: {2}",
199061da546Spatrick GetID(), unwatch_thread_sp->GetID(), remove_error);
200061da546Spatrick }
201061da546Spatrick
202061da546Spatrick return thread_error;
203061da546Spatrick }
204061da546Spatrick }
205061da546Spatrick return m_watchpoint_list.Add(addr, size, watch_flags, hardware);
206061da546Spatrick }
207061da546Spatrick
RemoveWatchpoint(lldb::addr_t addr)208061da546Spatrick Status NativeProcessProtocol::RemoveWatchpoint(lldb::addr_t addr) {
209061da546Spatrick // Update the thread list
210061da546Spatrick UpdateThreads();
211061da546Spatrick
212061da546Spatrick Status overall_error;
213061da546Spatrick
214061da546Spatrick std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
215061da546Spatrick for (const auto &thread : m_threads) {
216061da546Spatrick assert(thread && "thread list should not have a NULL thread!");
217061da546Spatrick
218061da546Spatrick const Status thread_error = thread->RemoveWatchpoint(addr);
219061da546Spatrick if (thread_error.Fail()) {
220061da546Spatrick // Keep track of the first thread error if any threads fail. We want to
221061da546Spatrick // try to remove the watchpoint from every thread, though, even if one or
222061da546Spatrick // more have errors.
223061da546Spatrick if (!overall_error.Fail())
224061da546Spatrick overall_error = thread_error;
225061da546Spatrick }
226061da546Spatrick }
227061da546Spatrick const Status error = m_watchpoint_list.Remove(addr);
228061da546Spatrick return overall_error.Fail() ? overall_error : error;
229061da546Spatrick }
230061da546Spatrick
231061da546Spatrick const HardwareBreakpointMap &
GetHardwareBreakpointMap() const232061da546Spatrick NativeProcessProtocol::GetHardwareBreakpointMap() const {
233061da546Spatrick return m_hw_breakpoints_map;
234061da546Spatrick }
235061da546Spatrick
SetHardwareBreakpoint(lldb::addr_t addr,size_t size)236061da546Spatrick Status NativeProcessProtocol::SetHardwareBreakpoint(lldb::addr_t addr,
237061da546Spatrick size_t size) {
238061da546Spatrick // This default implementation assumes setting a hardware breakpoint for this
239061da546Spatrick // process will require setting same hardware breakpoint for each of its
240061da546Spatrick // existing threads. New thread will do the same once created.
241*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
242061da546Spatrick
243061da546Spatrick // Update the thread list
244061da546Spatrick UpdateThreads();
245061da546Spatrick
246061da546Spatrick // Exit here if target does not have required hardware breakpoint capability.
247061da546Spatrick auto hw_debug_cap = GetHardwareDebugSupportInfo();
248061da546Spatrick
249*f6aab3d8Srobert if (hw_debug_cap == std::nullopt || hw_debug_cap->first == 0 ||
250061da546Spatrick hw_debug_cap->first <= m_hw_breakpoints_map.size())
251061da546Spatrick return Status("Target does not have required no of hardware breakpoints");
252061da546Spatrick
253061da546Spatrick // Vector below stores all thread pointer for which we have we successfully
254061da546Spatrick // set this hardware breakpoint. If any of the current process threads fails
255061da546Spatrick // to set this hardware breakpoint then roll back and remove this breakpoint
256061da546Spatrick // for all the threads that had already set it successfully.
257061da546Spatrick std::vector<NativeThreadProtocol *> breakpoint_established_threads;
258061da546Spatrick
259061da546Spatrick // Request to set a hardware breakpoint for each of current process threads.
260061da546Spatrick std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
261061da546Spatrick for (const auto &thread : m_threads) {
262061da546Spatrick assert(thread && "thread list should not have a NULL thread!");
263061da546Spatrick
264061da546Spatrick Status thread_error = thread->SetHardwareBreakpoint(addr, size);
265061da546Spatrick if (thread_error.Success()) {
266061da546Spatrick // Remember that we set this breakpoint successfully in case we need to
267061da546Spatrick // clear it later.
268061da546Spatrick breakpoint_established_threads.push_back(thread.get());
269061da546Spatrick } else {
270061da546Spatrick // Unset the breakpoint for each thread we successfully set so that we
271061da546Spatrick // get back to a consistent state of "not set" for this hardware
272061da546Spatrick // breakpoint.
273061da546Spatrick for (auto rollback_thread_sp : breakpoint_established_threads) {
274061da546Spatrick Status remove_error =
275061da546Spatrick rollback_thread_sp->RemoveHardwareBreakpoint(addr);
276061da546Spatrick if (remove_error.Fail())
277061da546Spatrick LLDB_LOG(log,
278061da546Spatrick "RemoveHardwareBreakpoint failed for pid={0}, tid={1}: {2}",
279061da546Spatrick GetID(), rollback_thread_sp->GetID(), remove_error);
280061da546Spatrick }
281061da546Spatrick
282061da546Spatrick return thread_error;
283061da546Spatrick }
284061da546Spatrick }
285061da546Spatrick
286061da546Spatrick // Register new hardware breakpoint into hardware breakpoints map of current
287061da546Spatrick // process.
288061da546Spatrick m_hw_breakpoints_map[addr] = {addr, size};
289061da546Spatrick
290061da546Spatrick return Status();
291061da546Spatrick }
292061da546Spatrick
RemoveHardwareBreakpoint(lldb::addr_t addr)293061da546Spatrick Status NativeProcessProtocol::RemoveHardwareBreakpoint(lldb::addr_t addr) {
294061da546Spatrick // Update the thread list
295061da546Spatrick UpdateThreads();
296061da546Spatrick
297061da546Spatrick Status error;
298061da546Spatrick
299061da546Spatrick std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
300061da546Spatrick for (const auto &thread : m_threads) {
301061da546Spatrick assert(thread && "thread list should not have a NULL thread!");
302061da546Spatrick error = thread->RemoveHardwareBreakpoint(addr);
303061da546Spatrick }
304061da546Spatrick
305061da546Spatrick // Also remove from hardware breakpoint map of current process.
306061da546Spatrick m_hw_breakpoints_map.erase(addr);
307061da546Spatrick
308061da546Spatrick return error;
309061da546Spatrick }
310061da546Spatrick
SynchronouslyNotifyProcessStateChanged(lldb::StateType state)311061da546Spatrick void NativeProcessProtocol::SynchronouslyNotifyProcessStateChanged(
312061da546Spatrick lldb::StateType state) {
313*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
314061da546Spatrick
315be691f3bSpatrick m_delegate.ProcessStateChanged(this, state);
316061da546Spatrick
317*f6aab3d8Srobert switch (state) {
318*f6aab3d8Srobert case eStateStopped:
319*f6aab3d8Srobert case eStateExited:
320*f6aab3d8Srobert case eStateCrashed:
321*f6aab3d8Srobert NotifyTracersProcessDidStop();
322*f6aab3d8Srobert break;
323*f6aab3d8Srobert default:
324*f6aab3d8Srobert break;
325*f6aab3d8Srobert }
326*f6aab3d8Srobert
327be691f3bSpatrick LLDB_LOG(log, "sent state notification [{0}] from process {1}", state,
328be691f3bSpatrick GetID());
329061da546Spatrick }
330061da546Spatrick
NotifyDidExec()331061da546Spatrick void NativeProcessProtocol::NotifyDidExec() {
332*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
333be691f3bSpatrick LLDB_LOG(log, "process {0} exec()ed", GetID());
334061da546Spatrick
335*f6aab3d8Srobert m_software_breakpoints.clear();
336*f6aab3d8Srobert
337be691f3bSpatrick m_delegate.DidExec(this);
338061da546Spatrick }
339061da546Spatrick
SetSoftwareBreakpoint(lldb::addr_t addr,uint32_t size_hint)340061da546Spatrick Status NativeProcessProtocol::SetSoftwareBreakpoint(lldb::addr_t addr,
341061da546Spatrick uint32_t size_hint) {
342*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Breakpoints);
343061da546Spatrick LLDB_LOG(log, "addr = {0:x}, size_hint = {1}", addr, size_hint);
344061da546Spatrick
345061da546Spatrick auto it = m_software_breakpoints.find(addr);
346061da546Spatrick if (it != m_software_breakpoints.end()) {
347061da546Spatrick ++it->second.ref_count;
348061da546Spatrick return Status();
349061da546Spatrick }
350061da546Spatrick auto expected_bkpt = EnableSoftwareBreakpoint(addr, size_hint);
351061da546Spatrick if (!expected_bkpt)
352061da546Spatrick return Status(expected_bkpt.takeError());
353061da546Spatrick
354061da546Spatrick m_software_breakpoints.emplace(addr, std::move(*expected_bkpt));
355061da546Spatrick return Status();
356061da546Spatrick }
357061da546Spatrick
RemoveSoftwareBreakpoint(lldb::addr_t addr)358061da546Spatrick Status NativeProcessProtocol::RemoveSoftwareBreakpoint(lldb::addr_t addr) {
359*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Breakpoints);
360061da546Spatrick LLDB_LOG(log, "addr = {0:x}", addr);
361061da546Spatrick auto it = m_software_breakpoints.find(addr);
362061da546Spatrick if (it == m_software_breakpoints.end())
363061da546Spatrick return Status("Breakpoint not found.");
364061da546Spatrick assert(it->second.ref_count > 0);
365061da546Spatrick if (--it->second.ref_count > 0)
366061da546Spatrick return Status();
367061da546Spatrick
368061da546Spatrick // This is the last reference. Let's remove the breakpoint.
369061da546Spatrick Status error;
370061da546Spatrick
371061da546Spatrick // Clear a software breakpoint instruction
372061da546Spatrick llvm::SmallVector<uint8_t, 4> curr_break_op(
373061da546Spatrick it->second.breakpoint_opcodes.size(), 0);
374061da546Spatrick
375061da546Spatrick // Read the breakpoint opcode
376061da546Spatrick size_t bytes_read = 0;
377061da546Spatrick error =
378061da546Spatrick ReadMemory(addr, curr_break_op.data(), curr_break_op.size(), bytes_read);
379061da546Spatrick if (error.Fail() || bytes_read < curr_break_op.size()) {
380061da546Spatrick return Status("addr=0x%" PRIx64
381061da546Spatrick ": tried to read %zu bytes but only read %zu",
382061da546Spatrick addr, curr_break_op.size(), bytes_read);
383061da546Spatrick }
384061da546Spatrick const auto &saved = it->second.saved_opcodes;
385061da546Spatrick // Make sure the breakpoint opcode exists at this address
386*f6aab3d8Srobert if (llvm::ArrayRef(curr_break_op) != it->second.breakpoint_opcodes) {
387061da546Spatrick if (curr_break_op != it->second.saved_opcodes)
388061da546Spatrick return Status("Original breakpoint trap is no longer in memory.");
389061da546Spatrick LLDB_LOG(log,
390061da546Spatrick "Saved opcodes ({0:@[x]}) have already been restored at {1:x}.",
391061da546Spatrick llvm::make_range(saved.begin(), saved.end()), addr);
392061da546Spatrick } else {
393061da546Spatrick // We found a valid breakpoint opcode at this address, now restore the
394061da546Spatrick // saved opcode.
395061da546Spatrick size_t bytes_written = 0;
396061da546Spatrick error = WriteMemory(addr, saved.data(), saved.size(), bytes_written);
397061da546Spatrick if (error.Fail() || bytes_written < saved.size()) {
398061da546Spatrick return Status("addr=0x%" PRIx64
399061da546Spatrick ": tried to write %zu bytes but only wrote %zu",
400061da546Spatrick addr, saved.size(), bytes_written);
401061da546Spatrick }
402061da546Spatrick
403061da546Spatrick // Verify that our original opcode made it back to the inferior
404061da546Spatrick llvm::SmallVector<uint8_t, 4> verify_opcode(saved.size(), 0);
405061da546Spatrick size_t verify_bytes_read = 0;
406061da546Spatrick error = ReadMemory(addr, verify_opcode.data(), verify_opcode.size(),
407061da546Spatrick verify_bytes_read);
408061da546Spatrick if (error.Fail() || verify_bytes_read < verify_opcode.size()) {
409061da546Spatrick return Status("addr=0x%" PRIx64
410061da546Spatrick ": tried to read %zu verification bytes but only read %zu",
411061da546Spatrick addr, verify_opcode.size(), verify_bytes_read);
412061da546Spatrick }
413061da546Spatrick if (verify_opcode != saved)
414061da546Spatrick LLDB_LOG(log, "Restoring bytes at {0:x}: {1:@[x]}", addr,
415061da546Spatrick llvm::make_range(saved.begin(), saved.end()));
416061da546Spatrick }
417061da546Spatrick
418061da546Spatrick m_software_breakpoints.erase(it);
419061da546Spatrick return Status();
420061da546Spatrick }
421061da546Spatrick
422061da546Spatrick llvm::Expected<NativeProcessProtocol::SoftwareBreakpoint>
EnableSoftwareBreakpoint(lldb::addr_t addr,uint32_t size_hint)423061da546Spatrick NativeProcessProtocol::EnableSoftwareBreakpoint(lldb::addr_t addr,
424061da546Spatrick uint32_t size_hint) {
425*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Breakpoints);
426061da546Spatrick
427061da546Spatrick auto expected_trap = GetSoftwareBreakpointTrapOpcode(size_hint);
428061da546Spatrick if (!expected_trap)
429061da546Spatrick return expected_trap.takeError();
430061da546Spatrick
431061da546Spatrick llvm::SmallVector<uint8_t, 4> saved_opcode_bytes(expected_trap->size(), 0);
432061da546Spatrick // Save the original opcodes by reading them so we can restore later.
433061da546Spatrick size_t bytes_read = 0;
434061da546Spatrick Status error = ReadMemory(addr, saved_opcode_bytes.data(),
435061da546Spatrick saved_opcode_bytes.size(), bytes_read);
436061da546Spatrick if (error.Fail())
437061da546Spatrick return error.ToError();
438061da546Spatrick
439061da546Spatrick // Ensure we read as many bytes as we expected.
440061da546Spatrick if (bytes_read != saved_opcode_bytes.size()) {
441061da546Spatrick return llvm::createStringError(
442061da546Spatrick llvm::inconvertibleErrorCode(),
443061da546Spatrick "Failed to read memory while attempting to set breakpoint: attempted "
444061da546Spatrick "to read {0} bytes but only read {1}.",
445061da546Spatrick saved_opcode_bytes.size(), bytes_read);
446061da546Spatrick }
447061da546Spatrick
448061da546Spatrick LLDB_LOG(
449061da546Spatrick log, "Overwriting bytes at {0:x}: {1:@[x]}", addr,
450061da546Spatrick llvm::make_range(saved_opcode_bytes.begin(), saved_opcode_bytes.end()));
451061da546Spatrick
452061da546Spatrick // Write a software breakpoint in place of the original opcode.
453061da546Spatrick size_t bytes_written = 0;
454061da546Spatrick error = WriteMemory(addr, expected_trap->data(), expected_trap->size(),
455061da546Spatrick bytes_written);
456061da546Spatrick if (error.Fail())
457061da546Spatrick return error.ToError();
458061da546Spatrick
459061da546Spatrick // Ensure we wrote as many bytes as we expected.
460061da546Spatrick if (bytes_written != expected_trap->size()) {
461061da546Spatrick return llvm::createStringError(
462061da546Spatrick llvm::inconvertibleErrorCode(),
463061da546Spatrick "Failed write memory while attempting to set "
464061da546Spatrick "breakpoint: attempted to write {0} bytes but only wrote {1}",
465061da546Spatrick expected_trap->size(), bytes_written);
466061da546Spatrick }
467061da546Spatrick
468061da546Spatrick llvm::SmallVector<uint8_t, 4> verify_bp_opcode_bytes(expected_trap->size(),
469061da546Spatrick 0);
470061da546Spatrick size_t verify_bytes_read = 0;
471061da546Spatrick error = ReadMemory(addr, verify_bp_opcode_bytes.data(),
472061da546Spatrick verify_bp_opcode_bytes.size(), verify_bytes_read);
473061da546Spatrick if (error.Fail())
474061da546Spatrick return error.ToError();
475061da546Spatrick
476061da546Spatrick // Ensure we read as many verification bytes as we expected.
477061da546Spatrick if (verify_bytes_read != verify_bp_opcode_bytes.size()) {
478061da546Spatrick return llvm::createStringError(
479061da546Spatrick llvm::inconvertibleErrorCode(),
480061da546Spatrick "Failed to read memory while "
481061da546Spatrick "attempting to verify breakpoint: attempted to read {0} bytes "
482061da546Spatrick "but only read {1}",
483061da546Spatrick verify_bp_opcode_bytes.size(), verify_bytes_read);
484061da546Spatrick }
485061da546Spatrick
486*f6aab3d8Srobert if (llvm::ArrayRef(verify_bp_opcode_bytes.data(), verify_bytes_read) !=
487061da546Spatrick *expected_trap) {
488061da546Spatrick return llvm::createStringError(
489061da546Spatrick llvm::inconvertibleErrorCode(),
490061da546Spatrick "Verification of software breakpoint "
491061da546Spatrick "writing failed - trap opcodes not successfully read back "
492061da546Spatrick "after writing when setting breakpoint at {0:x}",
493061da546Spatrick addr);
494061da546Spatrick }
495061da546Spatrick
496061da546Spatrick LLDB_LOG(log, "addr = {0:x}: SUCCESS", addr);
497061da546Spatrick return SoftwareBreakpoint{1, saved_opcode_bytes, *expected_trap};
498061da546Spatrick }
499061da546Spatrick
500061da546Spatrick llvm::Expected<llvm::ArrayRef<uint8_t>>
GetSoftwareBreakpointTrapOpcode(size_t size_hint)501061da546Spatrick NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_t size_hint) {
502061da546Spatrick static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
503061da546Spatrick static const uint8_t g_i386_opcode[] = {0xCC};
504061da546Spatrick static const uint8_t g_mips64_opcode[] = {0x00, 0x00, 0x00, 0x0d};
505061da546Spatrick static const uint8_t g_mips64el_opcode[] = {0x0d, 0x00, 0x00, 0x00};
506061da546Spatrick static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
507be691f3bSpatrick static const uint8_t g_ppc_opcode[] = {0x7f, 0xe0, 0x00, 0x08}; // trap
508be691f3bSpatrick static const uint8_t g_ppcle_opcode[] = {0x08, 0x00, 0xe0, 0x7f}; // trap
509*f6aab3d8Srobert static const uint8_t g_riscv_opcode[] = {0x73, 0x00, 0x10, 0x00}; // ebreak
510*f6aab3d8Srobert static const uint8_t g_riscv_opcode_c[] = {0x02, 0x90}; // c.ebreak
511*f6aab3d8Srobert static const uint8_t g_loongarch_opcode[] = {0x05, 0x00, 0x2a,
512*f6aab3d8Srobert 0x00}; // break 0x5
513061da546Spatrick
514061da546Spatrick switch (GetArchitecture().GetMachine()) {
515061da546Spatrick case llvm::Triple::aarch64:
516061da546Spatrick case llvm::Triple::aarch64_32:
517*f6aab3d8Srobert return llvm::ArrayRef(g_aarch64_opcode);
518061da546Spatrick
519061da546Spatrick case llvm::Triple::x86:
520061da546Spatrick case llvm::Triple::x86_64:
521*f6aab3d8Srobert return llvm::ArrayRef(g_i386_opcode);
522061da546Spatrick
523061da546Spatrick case llvm::Triple::mips:
524061da546Spatrick case llvm::Triple::mips64:
525*f6aab3d8Srobert return llvm::ArrayRef(g_mips64_opcode);
526061da546Spatrick
527061da546Spatrick case llvm::Triple::mipsel:
528061da546Spatrick case llvm::Triple::mips64el:
529*f6aab3d8Srobert return llvm::ArrayRef(g_mips64el_opcode);
530061da546Spatrick
531061da546Spatrick case llvm::Triple::systemz:
532*f6aab3d8Srobert return llvm::ArrayRef(g_s390x_opcode);
533061da546Spatrick
534be691f3bSpatrick case llvm::Triple::ppc:
535be691f3bSpatrick case llvm::Triple::ppc64:
536*f6aab3d8Srobert return llvm::ArrayRef(g_ppc_opcode);
537be691f3bSpatrick
538061da546Spatrick case llvm::Triple::ppc64le:
539*f6aab3d8Srobert return llvm::ArrayRef(g_ppcle_opcode);
540*f6aab3d8Srobert
541*f6aab3d8Srobert case llvm::Triple::riscv32:
542*f6aab3d8Srobert case llvm::Triple::riscv64: {
543*f6aab3d8Srobert return size_hint == 2 ? llvm::ArrayRef(g_riscv_opcode_c)
544*f6aab3d8Srobert : llvm::ArrayRef(g_riscv_opcode);
545*f6aab3d8Srobert }
546*f6aab3d8Srobert
547*f6aab3d8Srobert case llvm::Triple::loongarch32:
548*f6aab3d8Srobert case llvm::Triple::loongarch64:
549*f6aab3d8Srobert return llvm::ArrayRef(g_loongarch_opcode);
550061da546Spatrick
551061da546Spatrick default:
552061da546Spatrick return llvm::createStringError(llvm::inconvertibleErrorCode(),
553061da546Spatrick "CPU type not supported!");
554061da546Spatrick }
555061da546Spatrick }
556061da546Spatrick
GetSoftwareBreakpointPCOffset()557061da546Spatrick size_t NativeProcessProtocol::GetSoftwareBreakpointPCOffset() {
558061da546Spatrick switch (GetArchitecture().GetMachine()) {
559061da546Spatrick case llvm::Triple::x86:
560061da546Spatrick case llvm::Triple::x86_64:
561061da546Spatrick case llvm::Triple::systemz:
562061da546Spatrick // These architectures report increment the PC after breakpoint is hit.
563061da546Spatrick return cantFail(GetSoftwareBreakpointTrapOpcode(0)).size();
564061da546Spatrick
565061da546Spatrick case llvm::Triple::arm:
566061da546Spatrick case llvm::Triple::aarch64:
567061da546Spatrick case llvm::Triple::aarch64_32:
568061da546Spatrick case llvm::Triple::mips64:
569061da546Spatrick case llvm::Triple::mips64el:
570061da546Spatrick case llvm::Triple::mips:
571061da546Spatrick case llvm::Triple::mipsel:
572be691f3bSpatrick case llvm::Triple::ppc:
573be691f3bSpatrick case llvm::Triple::ppc64:
574061da546Spatrick case llvm::Triple::ppc64le:
575*f6aab3d8Srobert case llvm::Triple::riscv32:
576*f6aab3d8Srobert case llvm::Triple::riscv64:
577*f6aab3d8Srobert case llvm::Triple::loongarch32:
578*f6aab3d8Srobert case llvm::Triple::loongarch64:
579061da546Spatrick // On these architectures the PC doesn't get updated for breakpoint hits.
580061da546Spatrick return 0;
581061da546Spatrick
582061da546Spatrick default:
583061da546Spatrick llvm_unreachable("CPU type not supported!");
584061da546Spatrick }
585061da546Spatrick }
586061da546Spatrick
FixupBreakpointPCAsNeeded(NativeThreadProtocol & thread)587061da546Spatrick void NativeProcessProtocol::FixupBreakpointPCAsNeeded(
588061da546Spatrick NativeThreadProtocol &thread) {
589*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Breakpoints);
590061da546Spatrick
591061da546Spatrick Status error;
592061da546Spatrick
593061da546Spatrick // Find out the size of a breakpoint (might depend on where we are in the
594061da546Spatrick // code).
595061da546Spatrick NativeRegisterContext &context = thread.GetRegisterContext();
596061da546Spatrick
597061da546Spatrick uint32_t breakpoint_size = GetSoftwareBreakpointPCOffset();
598061da546Spatrick LLDB_LOG(log, "breakpoint size: {0}", breakpoint_size);
599061da546Spatrick if (breakpoint_size == 0)
600061da546Spatrick return;
601061da546Spatrick
602061da546Spatrick // First try probing for a breakpoint at a software breakpoint location: PC -
603061da546Spatrick // breakpoint size.
604061da546Spatrick const lldb::addr_t initial_pc_addr = context.GetPCfromBreakpointLocation();
605061da546Spatrick lldb::addr_t breakpoint_addr = initial_pc_addr;
606061da546Spatrick // Do not allow breakpoint probe to wrap around.
607061da546Spatrick if (breakpoint_addr >= breakpoint_size)
608061da546Spatrick breakpoint_addr -= breakpoint_size;
609061da546Spatrick
610061da546Spatrick if (m_software_breakpoints.count(breakpoint_addr) == 0) {
611061da546Spatrick // We didn't find one at a software probe location. Nothing to do.
612061da546Spatrick LLDB_LOG(log,
613061da546Spatrick "pid {0} no lldb software breakpoint found at current pc with "
614061da546Spatrick "adjustment: {1}",
615061da546Spatrick GetID(), breakpoint_addr);
616061da546Spatrick return;
617061da546Spatrick }
618061da546Spatrick
619061da546Spatrick //
620061da546Spatrick // We have a software breakpoint and need to adjust the PC.
621061da546Spatrick //
622061da546Spatrick
623061da546Spatrick // Change the program counter.
624061da546Spatrick LLDB_LOG(log, "pid {0} tid {1}: changing PC from {2:x} to {3:x}", GetID(),
625061da546Spatrick thread.GetID(), initial_pc_addr, breakpoint_addr);
626061da546Spatrick
627061da546Spatrick error = context.SetPC(breakpoint_addr);
628061da546Spatrick if (error.Fail()) {
629061da546Spatrick // This can happen in case the process was killed between the time we read
630061da546Spatrick // the PC and when we are updating it. There's nothing better to do than to
631061da546Spatrick // swallow the error.
632061da546Spatrick LLDB_LOG(log, "pid {0} tid {1}: failed to set PC: {2}", GetID(),
633061da546Spatrick thread.GetID(), error);
634061da546Spatrick }
635061da546Spatrick }
636061da546Spatrick
RemoveBreakpoint(lldb::addr_t addr,bool hardware)637061da546Spatrick Status NativeProcessProtocol::RemoveBreakpoint(lldb::addr_t addr,
638061da546Spatrick bool hardware) {
639061da546Spatrick if (hardware)
640061da546Spatrick return RemoveHardwareBreakpoint(addr);
641061da546Spatrick else
642061da546Spatrick return RemoveSoftwareBreakpoint(addr);
643061da546Spatrick }
644061da546Spatrick
ReadMemoryWithoutTrap(lldb::addr_t addr,void * buf,size_t size,size_t & bytes_read)645061da546Spatrick Status NativeProcessProtocol::ReadMemoryWithoutTrap(lldb::addr_t addr,
646061da546Spatrick void *buf, size_t size,
647061da546Spatrick size_t &bytes_read) {
648061da546Spatrick Status error = ReadMemory(addr, buf, size, bytes_read);
649061da546Spatrick if (error.Fail())
650061da546Spatrick return error;
651061da546Spatrick
652*f6aab3d8Srobert llvm::MutableArrayRef data(static_cast<uint8_t *>(buf), bytes_read);
653061da546Spatrick for (const auto &pair : m_software_breakpoints) {
654061da546Spatrick lldb::addr_t bp_addr = pair.first;
655*f6aab3d8Srobert auto saved_opcodes = llvm::ArrayRef(pair.second.saved_opcodes);
656061da546Spatrick
657061da546Spatrick if (bp_addr + saved_opcodes.size() < addr || addr + bytes_read <= bp_addr)
658dda28197Spatrick continue; // Breakpoint not in range, ignore
659061da546Spatrick
660061da546Spatrick if (bp_addr < addr) {
661061da546Spatrick saved_opcodes = saved_opcodes.drop_front(addr - bp_addr);
662061da546Spatrick bp_addr = addr;
663061da546Spatrick }
664061da546Spatrick auto bp_data = data.drop_front(bp_addr - addr);
665061da546Spatrick std::copy_n(saved_opcodes.begin(),
666061da546Spatrick std::min(saved_opcodes.size(), bp_data.size()),
667061da546Spatrick bp_data.begin());
668061da546Spatrick }
669061da546Spatrick return Status();
670061da546Spatrick }
671061da546Spatrick
672061da546Spatrick llvm::Expected<llvm::StringRef>
ReadCStringFromMemory(lldb::addr_t addr,char * buffer,size_t max_size,size_t & total_bytes_read)673061da546Spatrick NativeProcessProtocol::ReadCStringFromMemory(lldb::addr_t addr, char *buffer,
674061da546Spatrick size_t max_size,
675061da546Spatrick size_t &total_bytes_read) {
676061da546Spatrick static const size_t cache_line_size =
677061da546Spatrick llvm::sys::Process::getPageSizeEstimate();
678061da546Spatrick size_t bytes_read = 0;
679061da546Spatrick size_t bytes_left = max_size;
680061da546Spatrick addr_t curr_addr = addr;
681061da546Spatrick size_t string_size;
682061da546Spatrick char *curr_buffer = buffer;
683061da546Spatrick total_bytes_read = 0;
684061da546Spatrick Status status;
685061da546Spatrick
686061da546Spatrick while (bytes_left > 0 && status.Success()) {
687061da546Spatrick addr_t cache_line_bytes_left =
688061da546Spatrick cache_line_size - (curr_addr % cache_line_size);
689061da546Spatrick addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
690061da546Spatrick status = ReadMemory(curr_addr, static_cast<void *>(curr_buffer),
691061da546Spatrick bytes_to_read, bytes_read);
692061da546Spatrick
693061da546Spatrick if (bytes_read == 0)
694061da546Spatrick break;
695061da546Spatrick
696061da546Spatrick void *str_end = std::memchr(curr_buffer, '\0', bytes_read);
697061da546Spatrick if (str_end != nullptr) {
698061da546Spatrick total_bytes_read =
699061da546Spatrick static_cast<size_t>((static_cast<char *>(str_end) - buffer + 1));
700061da546Spatrick status.Clear();
701061da546Spatrick break;
702061da546Spatrick }
703061da546Spatrick
704061da546Spatrick total_bytes_read += bytes_read;
705061da546Spatrick curr_buffer += bytes_read;
706061da546Spatrick curr_addr += bytes_read;
707061da546Spatrick bytes_left -= bytes_read;
708061da546Spatrick }
709061da546Spatrick
710061da546Spatrick string_size = total_bytes_read - 1;
711061da546Spatrick
712061da546Spatrick // Make sure we return a null terminated string.
713061da546Spatrick if (bytes_left == 0 && max_size > 0 && buffer[max_size - 1] != '\0') {
714061da546Spatrick buffer[max_size - 1] = '\0';
715061da546Spatrick total_bytes_read--;
716061da546Spatrick }
717061da546Spatrick
718061da546Spatrick if (!status.Success())
719061da546Spatrick return status.ToError();
720061da546Spatrick
721061da546Spatrick return llvm::StringRef(buffer, string_size);
722061da546Spatrick }
723061da546Spatrick
GetState() const724061da546Spatrick lldb::StateType NativeProcessProtocol::GetState() const {
725061da546Spatrick std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
726061da546Spatrick return m_state;
727061da546Spatrick }
728061da546Spatrick
SetState(lldb::StateType state,bool notify_delegates)729061da546Spatrick void NativeProcessProtocol::SetState(lldb::StateType state,
730061da546Spatrick bool notify_delegates) {
731061da546Spatrick std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
732061da546Spatrick
733061da546Spatrick if (state == m_state)
734061da546Spatrick return;
735061da546Spatrick
736061da546Spatrick m_state = state;
737061da546Spatrick
738061da546Spatrick if (StateIsStoppedState(state, false)) {
739061da546Spatrick ++m_stop_id;
740061da546Spatrick
741061da546Spatrick // Give process a chance to do any stop id bump processing, such as
742061da546Spatrick // clearing cached data that is invalidated each time the process runs.
743061da546Spatrick // Note if/when we support some threads running, we'll end up needing to
744061da546Spatrick // manage this per thread and per process.
745061da546Spatrick DoStopIDBumped(m_stop_id);
746061da546Spatrick }
747061da546Spatrick
748061da546Spatrick // Optionally notify delegates of the state change.
749061da546Spatrick if (notify_delegates)
750061da546Spatrick SynchronouslyNotifyProcessStateChanged(state);
751061da546Spatrick }
752061da546Spatrick
GetStopID() const753061da546Spatrick uint32_t NativeProcessProtocol::GetStopID() const {
754061da546Spatrick std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
755061da546Spatrick return m_stop_id;
756061da546Spatrick }
757061da546Spatrick
DoStopIDBumped(uint32_t)758061da546Spatrick void NativeProcessProtocol::DoStopIDBumped(uint32_t /* newBumpId */) {
759061da546Spatrick // Default implementation does nothing.
760061da546Spatrick }
761061da546Spatrick
762061da546Spatrick NativeProcessProtocol::Factory::~Factory() = default;
763