Skip to content

Commit 4f47055

Browse files
[lldb] Implement Process::ReadMemoryRanges
This commit introduces a base-class implementation for a method that reads memory from multiple ranges at once. This implementation simply calls the underlying `ReadMemoryFromInferior` method on each requested range, intentionally bypassing the memory caching mechanism (though this may be easily changed in the future). `Process` implementations that can be perform this operation more efficiently - e.g. with the MultiMemPacket described in [1] - are expected to override this method. As an example, this commit changes AppleObjCClassDescriptorV2 to use the new API. Note about the API ------------------ In the RFC, we discussed having the API return some kind of class `ReadMemoryRangesResult`. However, while writing such a class, it became clear that it was merely wrapping a vector, without providing anything useful. For example, this class: ``` struct ReadMemoryRangesResult { ReadMemoryRangesResult( llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> ranges) : ranges(std::move(ranges)) {} llvm::ArrayRef<llvm::MutableArrayRef<uint8_t>> getRanges() const { return ranges; } private: llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> ranges; }; ``` As can be seen in the added test and in the added use-case (AppleObjCClassDescriptorV2), users of this API will just iterate over the vector of memory buffers. So they want a return type that can be iterated over, and the vector seems more natural than creating a new class and defining iterators for it. Likewise, in the RFC, we discussed wrapping the result into an `Expected`. Upon experimenting with the code, this feels like it limits what the API is able to do as the base class implementation never needs to fail the entire result, it's the individual reads that may fail and this is expressed through a zero-length result. Any derived classes overriding `ReadMemoryRanges` should also never produce a top level failure: if they did, they can just fall back to the base class implementation, which would produce a better result. [1]: https://discourse.llvm.org/t/rfc-a-new-vectorized-memory-read-packet/
1 parent a1f233a commit 4f47055

File tree

4 files changed

+121
-11
lines changed

4 files changed

+121
-11
lines changed

lldb/include/lldb/Target/Process.h

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1571,6 +1571,25 @@ class Process : public std::enable_shared_from_this<Process>,
15711571
virtual size_t ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
15721572
Status &error);
15731573

1574+
/// Read from multiple memory ranges and write the results into buffer.
1575+
///
1576+
/// \param[in] ranges
1577+
/// A collection of ranges (base address + size) to read from.
1578+
///
1579+
/// \param[out] buffer
1580+
/// A buffer where the read memory will be written to. It must be at least
1581+
/// as long as the sum of the sizes of each range.
1582+
///
1583+
/// \return
1584+
/// A vector of MutableArrayRef, where each MutableArrayRef is a slice of
1585+
/// the input buffer into which the memory contents were copied. The size
1586+
/// of the slice indicates how many bytes were read successfully. Partial
1587+
/// reads are always performed from the start of the requested range,
1588+
/// never from the middle or end.
1589+
virtual llvm::SmallVector<llvm::MutableArrayRef<uint8_t>>
1590+
ReadMemoryRanges(llvm::ArrayRef<Range<lldb::addr_t, size_t>> ranges,
1591+
llvm::MutableArrayRef<uint8_t> buffer);
1592+
15741593
/// Read of memory from a process.
15751594
///
15761595
/// This function has the same semantics of ReadMemory except that it

lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCClassDescriptorV2.cpp

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -279,22 +279,23 @@ ClassDescriptorV2::ReadMethods(llvm::ArrayRef<lldb::addr_t> addresses,
279279
const size_t num_methods = addresses.size();
280280

281281
llvm::SmallVector<uint8_t, 0> buffer(num_methods * size, 0);
282-
llvm::DenseSet<uint32_t> failed_indices;
283282

284-
for (auto [idx, addr] : llvm::enumerate(addresses)) {
285-
Status error;
286-
process->ReadMemory(addr, buffer.data() + idx * size, size, error);
287-
if (error.Fail())
288-
failed_indices.insert(idx);
289-
}
283+
llvm::SmallVector<Range<addr_t, size_t>> mem_ranges =
284+
llvm::to_vector(llvm::map_range(llvm::seq(num_methods), [&](size_t idx) {
285+
return Range<addr_t, size_t>(addresses[idx], size);
286+
}));
287+
288+
llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> read_results =
289+
process->ReadMemoryRanges(mem_ranges, buffer);
290290

291291
llvm::SmallVector<method_t, 0> methods;
292292
methods.reserve(num_methods);
293-
for (auto [idx, addr] : llvm::enumerate(addresses)) {
294-
if (failed_indices.contains(idx))
293+
for (auto [addr, memory] : llvm::zip(addresses, read_results)) {
294+
// Ignore partial reads.
295+
if (memory.size() != size)
295296
continue;
296-
DataExtractor extractor(buffer.data() + idx * size, size,
297-
process->GetByteOrder(),
297+
298+
DataExtractor extractor(memory.data(), size, process->GetByteOrder(),
298299
process->GetAddressByteSize());
299300
methods.push_back(method_t());
300301
methods.back().Read(extractor, process, addr, relative_selector_base_addr,

lldb/source/Target/Process.cpp

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1971,6 +1971,34 @@ size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Status &error) {
19711971
}
19721972
}
19731973

1974+
llvm::SmallVector<llvm::MutableArrayRef<uint8_t>>
1975+
Process::ReadMemoryRanges(llvm::ArrayRef<Range<lldb::addr_t, size_t>> ranges,
1976+
llvm::MutableArrayRef<uint8_t> buffer) {
1977+
llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> results;
1978+
1979+
for (auto [addr, len] : ranges) {
1980+
// This is either a programmer error, or a protocol violation.
1981+
// In production builds, gracefully fail.
1982+
assert(buffer.size() >= len);
1983+
if (buffer.size() < len) {
1984+
results.push_back(buffer.take_front(0));
1985+
continue;
1986+
}
1987+
1988+
Status status;
1989+
size_t num_bytes_read =
1990+
ReadMemoryFromInferior(addr, buffer.data(), len, status);
1991+
// FIXME: ReadMemoryFromInferior promises to return 0 in case of errors, but
1992+
// it doesn't; it never checks for errors.
1993+
if (status.Fail())
1994+
num_bytes_read = 0;
1995+
results.push_back(buffer.take_front(num_bytes_read));
1996+
buffer = buffer.drop_front(num_bytes_read);
1997+
}
1998+
1999+
return results;
2000+
}
2001+
19742002
void Process::DoFindInMemory(lldb::addr_t start_addr, lldb::addr_t end_addr,
19752003
const uint8_t *buf, size_t size,
19762004
AddressRanges &matches, size_t alignment,

lldb/unittests/Target/MemoryTest.cpp

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
#include "lldb/Utility/ArchSpec.h"
1818
#include "lldb/Utility/DataBufferHeap.h"
1919
#include "gtest/gtest.h"
20+
#include <cstdint>
21+
#include <random>
2022

2123
using namespace lldb_private;
2224
using namespace lldb;
@@ -225,3 +227,63 @@ TEST_F(MemoryTest, TesetMemoryCacheRead) {
225227
// instead of using an
226228
// old cache
227229
}
230+
231+
/// A process class that reads `lower_byte(address)` for each `address` it
232+
/// reads.
233+
class DummyReaderProcess : public Process {
234+
public:
235+
size_t DoReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
236+
Status &error) override {
237+
uint8_t *buffer = static_cast<uint8_t*>(buf);
238+
for(size_t addr = vm_addr; addr < vm_addr + size; addr++)
239+
buffer[addr - vm_addr] = addr;
240+
return size;
241+
}
242+
// Boilerplate, nothing interesting below.
243+
DummyReaderProcess(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp)
244+
: Process(target_sp, listener_sp) {}
245+
bool CanDebug(lldb::TargetSP, bool) override { return true; }
246+
Status DoDestroy() override { return {}; }
247+
void RefreshStateAfterStop() override {}
248+
bool DoUpdateThreadList(ThreadList &, ThreadList &) override { return false; }
249+
llvm::StringRef GetPluginName() override { return "Dummy"; }
250+
};
251+
252+
TEST_F(MemoryTest, TestReadMemoryRanges) {
253+
ArchSpec arch("x86_64-apple-macosx-");
254+
255+
Platform::SetHostPlatform(PlatformRemoteMacOSX::CreateInstance(true, &arch));
256+
257+
DebuggerSP debugger_sp = Debugger::CreateInstance();
258+
ASSERT_TRUE(debugger_sp);
259+
260+
TargetSP target_sp = CreateTarget(debugger_sp, arch);
261+
ASSERT_TRUE(target_sp);
262+
263+
ListenerSP listener_sp(Listener::MakeListener("dummy"));
264+
ProcessSP process_sp =
265+
std::make_shared<DummyReaderProcess>(target_sp, listener_sp);
266+
ASSERT_TRUE(process_sp);
267+
268+
DummyProcess *process = static_cast<DummyProcess *>(process_sp.get());
269+
process->SetMaxReadSize(1024);
270+
271+
llvm::SmallVector<uint8_t, 0> buffer(1024, 0);
272+
273+
// Read 8 ranges of 128 bytes, starting at random addresses
274+
std::mt19937 rng(42);
275+
std::uniform_int_distribution<addr_t> distribution(1, 100000);
276+
llvm::SmallVector<Range<addr_t, size_t>> ranges;
277+
for (unsigned i = 0; i < 1024; i += 128)
278+
ranges.emplace_back(distribution(rng), 128);
279+
280+
llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> read_results =
281+
process->ReadMemoryRanges(ranges, buffer);
282+
283+
for (auto [range, memory] : llvm::zip(ranges, read_results)) {
284+
ASSERT_EQ(memory.size(), 128u);
285+
addr_t range_base = range.GetRangeBase();
286+
for (auto [idx, byte] : llvm::enumerate(memory))
287+
ASSERT_EQ(byte, static_cast<uint8_t>(range_base + idx));
288+
}
289+
}

0 commit comments

Comments
 (0)