Skip to content

Commit c5e7d53

Browse files
felipepiovezanLukacma
authored andcommitted
[lldb] Implement Process::ReadMemoryRanges (llvm#163651)
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. The choice of having the caller allocate a buffer and pass it to `Process::ReadMemoryRanges` is done mostly to follow conventions already done in the Process class. [1]: https://discourse.llvm.org/t/rfc-a-new-vectorized-memory-read-packet/
1 parent 26c90e2 commit c5e7d53

File tree

4 files changed

+219
-11
lines changed

4 files changed

+219
-11
lines changed

lldb/include/lldb/Target/Process.h

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1571,6 +1571,28 @@ 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+
/// This calls ReadMemoryFromInferior multiple times, once per range,
1576+
/// bypassing the read cache. Process implementations that can perform this
1577+
/// operation more efficiently should override this.
1578+
///
1579+
/// \param[in] ranges
1580+
/// A collection of ranges (base address + size) to read from.
1581+
///
1582+
/// \param[out] buffer
1583+
/// A buffer where the read memory will be written to. It must be at least
1584+
/// as long as the sum of the sizes of each range.
1585+
///
1586+
/// \return
1587+
/// A vector of MutableArrayRef, where each MutableArrayRef is a slice of
1588+
/// the input buffer into which the memory contents were copied. The size
1589+
/// of the slice indicates how many bytes were read successfully. Partial
1590+
/// reads are always performed from the start of the requested range,
1591+
/// never from the middle or end.
1592+
virtual llvm::SmallVector<llvm::MutableArrayRef<uint8_t>>
1593+
ReadMemoryRanges(llvm::ArrayRef<Range<lldb::addr_t, size_t>> ranges,
1594+
llvm::MutableArrayRef<uint8_t> buffer);
1595+
15741596
/// Read of memory from a process.
15751597
///
15761598
/// 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
@@ -281,22 +281,23 @@ ClassDescriptorV2::ReadMethods(llvm::ArrayRef<lldb::addr_t> addresses,
281281
const size_t num_methods = addresses.size();
282282

283283
llvm::SmallVector<uint8_t, 0> buffer(num_methods * size, 0);
284-
llvm::DenseSet<uint32_t> failed_indices;
285284

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

293293
llvm::SmallVector<method_t, 0> methods;
294294
methods.reserve(num_methods);
295-
for (auto [idx, addr] : llvm::enumerate(addresses)) {
296-
if (failed_indices.contains(idx))
295+
for (auto [addr, memory] : llvm::zip(addresses, read_results)) {
296+
// Ignore partial reads.
297+
if (memory.size() != size)
297298
continue;
298-
DataExtractor extractor(buffer.data() + idx * size, size,
299-
process->GetByteOrder(),
299+
300+
DataExtractor extractor(memory.data(), size, process->GetByteOrder(),
300301
process->GetAddressByteSize());
301302
methods.push_back(method_t());
302303
methods.back().Read(extractor, process, addr, relative_string_base_addr,

lldb/source/Target/Process.cpp

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1971,6 +1971,49 @@ 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+
auto total_ranges_len = llvm::sum_of(
1978+
llvm::map_range(ranges, [](auto range) { return range.size; }));
1979+
// If the buffer is not large enough, this is a programmer error.
1980+
// In production builds, gracefully fail by returning a length of 0 for all
1981+
// ranges.
1982+
assert(buffer.size() >= total_ranges_len && "provided buffer is too short");
1983+
if (buffer.size() < total_ranges_len) {
1984+
llvm::MutableArrayRef<uint8_t> empty;
1985+
return {ranges.size(), empty};
1986+
}
1987+
1988+
llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> results;
1989+
1990+
// While `buffer` has space, take the next requested range and read
1991+
// memory into a `buffer` piece, then slice it to remove the used memory.
1992+
for (auto [addr, range_len] : ranges) {
1993+
Status status;
1994+
size_t num_bytes_read =
1995+
ReadMemoryFromInferior(addr, buffer.data(), range_len, status);
1996+
// FIXME: ReadMemoryFromInferior promises to return 0 in case of errors, but
1997+
// it doesn't; it never checks for errors.
1998+
if (status.Fail())
1999+
num_bytes_read = 0;
2000+
2001+
assert(num_bytes_read <= range_len && "read more than requested bytes");
2002+
if (num_bytes_read > range_len) {
2003+
// In production builds, gracefully fail by returning length zero for this
2004+
// range.
2005+
results.emplace_back();
2006+
continue;
2007+
}
2008+
2009+
results.push_back(buffer.take_front(num_bytes_read));
2010+
// Slice buffer to remove the used memory.
2011+
buffer = buffer.drop_front(num_bytes_read);
2012+
}
2013+
2014+
return results;
2015+
}
2016+
19742017
void Process::DoFindInMemory(lldb::addr_t start_addr, lldb::addr_t end_addr,
19752018
const uint8_t *buf, size_t size,
19762019
AddressRanges &matches, size_t alignment,

lldb/unittests/Target/MemoryTest.cpp

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

2122
using namespace lldb_private;
2223
using namespace lldb;
@@ -225,3 +226,144 @@ TEST_F(MemoryTest, TesetMemoryCacheRead) {
225226
// instead of using an
226227
// old cache
227228
}
229+
230+
/// A process class that, when asked to read memory from some address X, returns
231+
/// the least significant byte of X.
232+
class DummyReaderProcess : public Process {
233+
public:
234+
// If true, `DoReadMemory` will not return all requested bytes.
235+
// It's not possible to control exactly how many bytes will be read, because
236+
// Process::ReadMemoryFromInferior tries to fulfill the entire request by
237+
// reading smaller chunks until it gets nothing back.
238+
bool read_less_than_requested = false;
239+
bool read_more_than_requested = false;
240+
241+
size_t DoReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
242+
Status &error) override {
243+
if (read_less_than_requested && size > 0)
244+
size--;
245+
if (read_more_than_requested)
246+
size *= 2;
247+
uint8_t *buffer = static_cast<uint8_t *>(buf);
248+
for (size_t addr = vm_addr; addr < vm_addr + size; addr++)
249+
buffer[addr - vm_addr] = static_cast<uint8_t>(addr); // LSB of addr.
250+
return size;
251+
}
252+
// Boilerplate, nothing interesting below.
253+
DummyReaderProcess(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp)
254+
: Process(target_sp, listener_sp) {}
255+
bool CanDebug(lldb::TargetSP, bool) override { return true; }
256+
Status DoDestroy() override { return {}; }
257+
void RefreshStateAfterStop() override {}
258+
bool DoUpdateThreadList(ThreadList &, ThreadList &) override { return false; }
259+
llvm::StringRef GetPluginName() override { return "Dummy"; }
260+
};
261+
262+
TEST_F(MemoryTest, TestReadMemoryRanges) {
263+
ArchSpec arch("x86_64-apple-macosx-");
264+
265+
Platform::SetHostPlatform(PlatformRemoteMacOSX::CreateInstance(true, &arch));
266+
267+
DebuggerSP debugger_sp = Debugger::CreateInstance();
268+
ASSERT_TRUE(debugger_sp);
269+
270+
TargetSP target_sp = CreateTarget(debugger_sp, arch);
271+
ASSERT_TRUE(target_sp);
272+
273+
ListenerSP listener_sp(Listener::MakeListener("dummy"));
274+
ProcessSP process_sp =
275+
std::make_shared<DummyReaderProcess>(target_sp, listener_sp);
276+
ASSERT_TRUE(process_sp);
277+
278+
{
279+
llvm::SmallVector<uint8_t, 0> buffer(1024, 0);
280+
// Read 8 ranges of 128 bytes with arbitrary base addresses.
281+
llvm::SmallVector<Range<addr_t, size_t>> ranges = {
282+
{0x12345, 128}, {0x11112222, 128}, {0x77777777, 128},
283+
{0xffaabbccdd, 128}, {0x0, 128}, {0x4242424242, 128},
284+
{0x17171717, 128}, {0x99999, 128}};
285+
286+
llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> read_results =
287+
process_sp->ReadMemoryRanges(ranges, buffer);
288+
289+
for (auto [range, memory] : llvm::zip(ranges, read_results)) {
290+
ASSERT_EQ(memory.size(), 128u);
291+
addr_t range_base = range.GetRangeBase();
292+
for (auto [idx, byte] : llvm::enumerate(memory))
293+
ASSERT_EQ(byte, static_cast<uint8_t>(range_base + idx));
294+
}
295+
}
296+
297+
auto &dummy_process = static_cast<DummyReaderProcess &>(*process_sp);
298+
dummy_process.read_less_than_requested = true;
299+
{
300+
llvm::SmallVector<uint8_t, 0> buffer(1024, 0);
301+
llvm::SmallVector<Range<addr_t, size_t>> ranges = {
302+
{0x12345, 128}, {0x11112222, 128}, {0x77777777, 128}};
303+
llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> read_results =
304+
dummy_process.ReadMemoryRanges(ranges, buffer);
305+
for (auto [range, memory] : llvm::zip(ranges, read_results)) {
306+
ASSERT_LT(memory.size(), 128u);
307+
addr_t range_base = range.GetRangeBase();
308+
for (auto [idx, byte] : llvm::enumerate(memory))
309+
ASSERT_EQ(byte, static_cast<uint8_t>(range_base + idx));
310+
}
311+
}
312+
}
313+
314+
using MemoryDeathTest = MemoryTest;
315+
316+
TEST_F(MemoryDeathTest, TestReadMemoryRangesReturnsTooMuch) {
317+
ArchSpec arch("x86_64-apple-macosx-");
318+
Platform::SetHostPlatform(PlatformRemoteMacOSX::CreateInstance(true, &arch));
319+
DebuggerSP debugger_sp = Debugger::CreateInstance();
320+
ASSERT_TRUE(debugger_sp);
321+
TargetSP target_sp = CreateTarget(debugger_sp, arch);
322+
ASSERT_TRUE(target_sp);
323+
ListenerSP listener_sp(Listener::MakeListener("dummy"));
324+
ProcessSP process_sp =
325+
std::make_shared<DummyReaderProcess>(target_sp, listener_sp);
326+
ASSERT_TRUE(process_sp);
327+
328+
auto &dummy_process = static_cast<DummyReaderProcess &>(*process_sp);
329+
dummy_process.read_more_than_requested = true;
330+
llvm::SmallVector<uint8_t, 0> buffer(1024, 0);
331+
llvm::SmallVector<Range<addr_t, size_t>> ranges = {{0x12345, 128}};
332+
333+
llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> read_results;
334+
ASSERT_DEBUG_DEATH(
335+
{ read_results = process_sp->ReadMemoryRanges(ranges, buffer); },
336+
"read more than requested bytes");
337+
#ifdef NDEBUG
338+
// With asserts off, the read should return empty ranges.
339+
ASSERT_EQ(read_results.size(), 1u);
340+
ASSERT_TRUE(read_results[0].empty());
341+
#endif
342+
}
343+
344+
TEST_F(MemoryDeathTest, TestReadMemoryRangesWithShortBuffer) {
345+
ArchSpec arch("x86_64-apple-macosx-");
346+
Platform::SetHostPlatform(PlatformRemoteMacOSX::CreateInstance(true, &arch));
347+
DebuggerSP debugger_sp = Debugger::CreateInstance();
348+
ASSERT_TRUE(debugger_sp);
349+
TargetSP target_sp = CreateTarget(debugger_sp, arch);
350+
ASSERT_TRUE(target_sp);
351+
ListenerSP listener_sp(Listener::MakeListener("dummy"));
352+
ProcessSP process_sp =
353+
std::make_shared<DummyReaderProcess>(target_sp, listener_sp);
354+
ASSERT_TRUE(process_sp);
355+
356+
llvm::SmallVector<uint8_t, 0> short_buffer(10, 0);
357+
llvm::SmallVector<Range<addr_t, size_t>> ranges = {{0x12345, 128},
358+
{0x11, 128}};
359+
llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> read_results;
360+
ASSERT_DEBUG_DEATH(
361+
{ read_results = process_sp->ReadMemoryRanges(ranges, short_buffer); },
362+
"provided buffer is too short");
363+
#ifdef NDEBUG
364+
// With asserts off, the read should return empty ranges.
365+
ASSERT_EQ(read_results.size(), ranges.size());
366+
for (llvm::MutableArrayRef<uint8_t> result : read_results)
367+
ASSERT_TRUE(result.empty());
368+
#endif
369+
}

0 commit comments

Comments
 (0)