LLDB mainline
Memory.cpp
Go to the documentation of this file.
1//===-- Memory.cpp --------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10#include "lldb/Target/Process.h"
13#include "lldb/Utility/Log.h"
15#include "lldb/Utility/State.h"
16
17#include "llvm/ADT/STLExtras.h"
18
19#include <cinttypes>
20#include <memory>
21
22using namespace lldb;
23using namespace lldb_private;
24
25// MemoryCache constructor
30
31// Destructor
33
34void MemoryCache::Clear(bool clear_invalid_ranges) {
35 std::lock_guard<std::recursive_mutex> guard(m_mutex);
36 m_L1_cache.clear();
37 m_L2_cache.clear();
38 if (clear_invalid_ranges)
39 m_invalid_ranges.Clear();
40 m_L2_cache_line_byte_size = m_process.GetMemoryCacheLineSize();
41}
42
43void MemoryCache::AddL1CacheData(lldb::addr_t addr, const void *src,
44 size_t src_len) {
45 AddL1CacheData(addr, std::make_shared<DataBufferHeap>(src, src_len));
46}
47
49 const DataBufferSP &data_buffer_sp) {
50 std::lock_guard<std::recursive_mutex> guard(m_mutex);
51 m_L1_cache[addr] = data_buffer_sp;
52}
53
54void MemoryCache::Flush(addr_t addr, size_t size) {
55 if (size == 0)
56 return;
57
58 std::lock_guard<std::recursive_mutex> guard(m_mutex);
59
60 // L1 chunks can overlap, and a chunk starting below addr can still reach
61 // into the flushed range, so scan the whole L1 cache and erase every chunk
62 // that intersects it.
63 if (!m_L1_cache.empty()) {
64 AddrRange flush_range(addr, size);
65 BlockMap::iterator pos = m_L1_cache.begin();
66 while (pos != m_L1_cache.end()) {
67 AddrRange chunk_range(pos->first, pos->second->GetByteSize());
68 if (chunk_range.DoesIntersect(flush_range))
69 pos = m_L1_cache.erase(pos);
70 else
71 ++pos;
72 }
73 }
74
75 if (!m_L2_cache.empty()) {
76 const uint32_t cache_line_byte_size = m_L2_cache_line_byte_size;
77 const addr_t end_addr = (addr + size - 1);
78 const addr_t first_cache_line_addr = addr - (addr % cache_line_byte_size);
79 const addr_t last_cache_line_addr =
80 end_addr - (end_addr % cache_line_byte_size);
81 // Watch for overflow where size will cause us to go off the end of the
82 // 64 bit address space
83 uint32_t num_cache_lines;
84 if (last_cache_line_addr >= first_cache_line_addr)
85 num_cache_lines = ((last_cache_line_addr - first_cache_line_addr) /
86 cache_line_byte_size) +
87 1;
88 else
89 num_cache_lines =
90 (UINT64_MAX - first_cache_line_addr + 1) / cache_line_byte_size;
91
92 uint32_t cache_idx = 0;
93 for (addr_t curr_addr = first_cache_line_addr; cache_idx < num_cache_lines;
94 curr_addr += cache_line_byte_size, ++cache_idx) {
95 BlockMap::iterator pos = m_L2_cache.find(curr_addr);
96 if (pos != m_L2_cache.end())
97 m_L2_cache.erase(pos);
98 }
99 }
100}
101
103 lldb::addr_t byte_size) {
104 if (byte_size > 0) {
105 std::lock_guard<std::recursive_mutex> guard(m_mutex);
106 InvalidRanges::Entry range(base_addr, byte_size);
107 m_invalid_ranges.Append(range);
108 m_invalid_ranges.Sort();
109 }
110}
111
113 lldb::addr_t byte_size) {
114 if (byte_size > 0) {
115 std::lock_guard<std::recursive_mutex> guard(m_mutex);
116 const uint32_t idx = m_invalid_ranges.FindEntryIndexThatContains(base_addr);
117 if (idx != UINT32_MAX) {
118 const InvalidRanges::Entry *entry = m_invalid_ranges.GetEntryAtIndex(idx);
119 if (entry->GetRangeBase() == base_addr &&
120 entry->GetByteSize() == byte_size)
121 return m_invalid_ranges.RemoveEntryAtIndex(idx);
122 }
123 }
124 return false;
125}
126
128 size_t len) const {
129 if (m_L1_cache.empty())
130 return nullptr;
131 AddrRange read_range(addr, len);
132 BlockMap::const_iterator pos = m_L1_cache.upper_bound(addr);
133 if (pos != m_L1_cache.begin())
134 --pos;
135 AddrRange chunk_range(pos->first, pos->second->GetByteSize());
136 if (!chunk_range.Contains(read_range))
137 return nullptr;
138 return pos->second->GetBytes() + (addr - chunk_range.GetRangeBase());
139}
140
142 size_t len) const {
143 if (m_L2_cache.empty())
144 return nullptr;
145 const lldb::addr_t line_offset = addr % m_L2_cache_line_byte_size;
146 BlockMap::const_iterator pos = m_L2_cache.find(addr - line_offset);
147 if (pos == m_L2_cache.end())
148 return nullptr;
149 if (line_offset + len > pos->second->GetByteSize())
150 return nullptr;
151 return pos->second->GetBytes() + line_offset;
152}
153
155 size_t len) const {
156 const uint8_t *cached = FindL1CacheEntry(addr, len);
157 if (!cached)
158 cached = FindL2CacheEntry(addr, len);
159 return cached;
160}
161
163 Status &error) {
164 // This function assumes that the address given is aligned correctly.
165 assert((line_base_addr % m_L2_cache_line_byte_size) == 0);
166
167 std::lock_guard<std::recursive_mutex> guard(m_mutex);
168 auto pos = m_L2_cache.find(line_base_addr);
169 if (pos != m_L2_cache.end())
170 return pos->second;
171
172 auto data_buffer_heap_sp =
173 std::make_shared<DataBufferHeap>(m_L2_cache_line_byte_size, 0);
174 size_t process_bytes_read = m_process.ReadMemoryFromInferior(
175 line_base_addr, data_buffer_heap_sp->GetBytes(),
176 data_buffer_heap_sp->GetByteSize(), error);
177
178 // If we failed a read, not much we can do.
179 if (process_bytes_read == 0)
180 return lldb::DataBufferSP();
181
182 // If we didn't get a complete read, we can still cache what we did get.
183 if (process_bytes_read < m_L2_cache_line_byte_size)
184 data_buffer_heap_sp->SetByteSize(process_bytes_read);
185
186 m_L2_cache[line_base_addr] = data_buffer_heap_sp;
187 return data_buffer_heap_sp;
188}
189
190size_t MemoryCache::Read(addr_t addr, void *dst, size_t dst_len,
191 Status &error) {
192 if (!dst || dst_len == 0)
193 return 0;
194
195 std::lock_guard<std::recursive_mutex> guard(m_mutex);
196
197 if (const InvalidRanges::Entry *invalid =
198 m_invalid_ranges.FindEntryThatIntersects(
199 InvalidRanges::Entry(addr, dst_len))) {
200 const addr_t invalid_addr = invalid->GetRangeBase();
202 "memory read failed for 0x%" PRIx64, invalid_addr);
203 if (invalid_addr <= addr)
204 return 0;
205 dst_len = invalid_addr - addr;
206 }
207
208 // Check the L1 cache for a range that contains the entire memory read.
209 // L1 cache contains chunks of memory that are not required to be the size of
210 // an L2 cache line. We avoid trying to do partial reads from the L1 cache to
211 // simplify the implementation.
212 if (const uint8_t *l1_data = FindL1CacheEntry(addr, dst_len)) {
213 memcpy(dst, l1_data, dst_len);
214 return dst_len;
215 }
216
217 // If the size of the read is greater than the size of an L2 cache line, we'll
218 // just read from the inferior. If that read is successful, we'll cache what
219 // we read in the L1 cache for future use.
220 if (dst_len > m_L2_cache_line_byte_size) {
221 size_t bytes_read =
222 m_process.ReadMemoryFromInferior(addr, dst, dst_len, error);
223 if (bytes_read > 0)
224 AddL1CacheData(addr, dst, bytes_read);
225 return bytes_read;
226 }
227
228 // If the size of the read fits inside one L2 cache line, we'll try reading
229 // from the L2 cache. Note that if the range of memory we're reading sits
230 // between two contiguous cache lines, we'll touch two cache lines instead of
231 // just one.
232
233 // We're going to have all of our loads and reads be cache line aligned.
234 addr_t cache_line_offset = addr % m_L2_cache_line_byte_size;
235 addr_t cache_line_base_addr = addr - cache_line_offset;
236 DataBufferSP first_cache_line = GetL2CacheLine(cache_line_base_addr, error);
237 // If we get nothing, then the read to the inferior likely failed. Nothing to
238 // do here.
239 if (!first_cache_line)
240 return 0;
241
242 // If the cache line was not filled out completely and the offset is greater
243 // than what we have available, we can't do anything further here.
244 if (cache_line_offset >= first_cache_line->GetByteSize())
245 return 0;
246
247 uint8_t *dst_buf = (uint8_t *)dst;
248 size_t bytes_left = dst_len;
249 size_t read_size = first_cache_line->GetByteSize() - cache_line_offset;
250 if (read_size > bytes_left)
251 read_size = bytes_left;
252
253 memcpy(dst_buf + dst_len - bytes_left,
254 first_cache_line->GetBytes() + cache_line_offset, read_size);
255 bytes_left -= read_size;
256
257 // If the cache line was not filled out completely and we still have data to
258 // read, we can't do anything further.
259 if (first_cache_line->GetByteSize() < m_L2_cache_line_byte_size &&
260 bytes_left > 0)
261 return dst_len - bytes_left;
262
263 // We'll hit this scenario if our read straddles two cache lines.
264 if (bytes_left > 0) {
265 cache_line_base_addr += m_L2_cache_line_byte_size;
266
267 // FIXME: Until we are able to more thoroughly check for invalid ranges, we
268 // will have to check the second line to see if it is in an invalid range as
269 // well. See the check near the beginning of the function for more details.
270 if (m_invalid_ranges.FindEntryThatContains(cache_line_base_addr)) {
272 "memory read failed for 0x%" PRIx64, cache_line_base_addr);
273 return dst_len - bytes_left;
274 }
275
276 DataBufferSP second_cache_line =
277 GetL2CacheLine(cache_line_base_addr, error);
278 if (!second_cache_line)
279 return dst_len - bytes_left;
280
281 read_size = bytes_left;
282 if (read_size > second_cache_line->GetByteSize())
283 read_size = second_cache_line->GetByteSize();
284
285 memcpy(dst_buf + dst_len - bytes_left, second_cache_line->GetBytes(),
286 read_size);
287 bytes_left -= read_size;
288
289 return dst_len - bytes_left;
290 }
291
292 return dst_len;
293}
294
295llvm::SmallVector<llvm::MutableArrayRef<uint8_t>>
297 llvm::MutableArrayRef<uint8_t> buffer) {
298 // A cache hit writes into `buffer` below, so check its size before that
299 // write. Fail the same way Process::DoReadMemoryRanges does.
300 auto total_ranges_len = llvm::sum_of(
301 llvm::map_range(ranges, [](auto range) { return range.size; }));
302 assert(buffer.size() >= total_ranges_len &&
303 "MemoryCache::ReadRanges: provided buffer is too short");
304 if (buffer.size() < total_ranges_len) {
305 llvm::MutableArrayRef<uint8_t> empty;
306 return {ranges.size(), empty};
307 }
308
309 std::lock_guard<std::recursive_mutex> guard(m_mutex);
310
311 llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> results;
312 results.reserve(ranges.size());
313 llvm::SmallVector<Range<lldb::addr_t, size_t>> missed_ranges;
314
315 // Iterate once serving requests from the caches.
316 for (auto range : ranges) {
317 const lldb::addr_t addr = range.GetRangeBase();
318 const size_t len = range.GetByteSize();
319
320 if (m_invalid_ranges.FindEntryThatContains(addr)) {
321 results.push_back(buffer.take_front(0));
322 continue;
323 }
324
325 const uint8_t *cached = FindCacheEntry(addr, len);
326 if (cached) {
327 results.push_back(buffer.take_front(len));
328 buffer = buffer.drop_front(len);
329 memcpy(results.back().data(), cached, len);
330 continue;
331 }
332
333 // Use a nullptr to denote this needs fetching.
334 results.emplace_back(nullptr, nullptr);
335 missed_ranges.push_back(range);
336 }
337
338 if (missed_ranges.empty())
339 return results;
340
341 llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> fetched_buffers_vec =
342 m_process.DoReadMemoryRanges(missed_ranges, buffer);
343 auto fetched_buffers = llvm::ArrayRef(fetched_buffers_vec);
344
345 for (auto [missed_range, fetched] : llvm::zip(missed_ranges, fetched_buffers))
346 AddL1CacheData(missed_range.GetRangeBase(), fetched);
347
348 // Use the just-fetched memory to fill in the gaps left by the cache.
349 for (auto &result : results)
350 if (result.data() == nullptr)
351 result = fetched_buffers.consume_front();
352
353 return results;
354}
355
357 uint32_t permissions, uint32_t chunk_size)
358 : m_range(addr, byte_size), m_permissions(permissions),
359 m_chunk_size(chunk_size)
360{
361 // The entire address range is free to start with.
362 m_free_blocks.Append(m_range);
363 assert(byte_size > chunk_size);
364}
365
367
369 // We must return something valid for zero bytes.
370 if (size == 0)
371 size = 1;
373
374 const size_t free_count = m_free_blocks.GetSize();
375 for (size_t i=0; i<free_count; ++i)
376 {
377 auto &free_block = m_free_blocks.GetEntryRef(i);
378 const lldb::addr_t range_size = free_block.GetByteSize();
379 if (range_size >= size)
380 {
381 // We found a free block that is big enough for our data. Figure out how
382 // many chunks we will need and calculate the resulting block size we
383 // will reserve.
384 addr_t addr = free_block.GetRangeBase();
385 size_t num_chunks = CalculateChunksNeededForSize(size);
386 lldb::addr_t block_size = num_chunks * m_chunk_size;
387 lldb::addr_t bytes_left = range_size - block_size;
388 if (bytes_left == 0)
389 {
390 // The newly allocated block will take all of the bytes in this
391 // available block, so we can just add it to the allocated ranges and
392 // remove the range from the free ranges.
393 m_reserved_blocks.Insert(free_block, false);
394 m_free_blocks.RemoveEntryAtIndex(i);
395 }
396 else
397 {
398 // Make the new allocated range and add it to the allocated ranges.
399 Range<lldb::addr_t, uint32_t> reserved_block(free_block);
400 reserved_block.SetByteSize(block_size);
401 // Insert the reserved range and don't combine it with other blocks in
402 // the reserved blocks list.
403 m_reserved_blocks.Insert(reserved_block, false);
404 // Adjust the free range in place since we won't change the sorted
405 // ordering of the m_free_blocks list.
406 free_block.SetRangeBase(reserved_block.GetRangeEnd());
407 free_block.SetByteSize(bytes_left);
408 }
409 LLDB_LOG_VERBOSE(log, "({0}) (size = {1} ({1:x})) => {2:x}", this, size,
410 addr);
411 return addr;
412 }
413 }
414
415 LLDB_LOG_VERBOSE(log, "({0}) (size = {1} ({1:x})) => {2:x}", this, size,
418}
419
421 bool success = false;
422 auto entry_idx = m_reserved_blocks.FindEntryIndexThatContains(addr);
423 if (entry_idx != UINT32_MAX)
424 {
425 m_free_blocks.Insert(m_reserved_blocks.GetEntryRef(entry_idx), true);
426 m_reserved_blocks.RemoveEntryAtIndex(entry_idx);
427 success = true;
428 }
430 LLDB_LOG_VERBOSE(log, "({0}) (addr = {1:x}) => {2}", this, addr, success);
431 return success;
432}
433
436
438
439void AllocatedMemoryCache::Clear(bool deallocate_memory) {
440 std::lock_guard<std::recursive_mutex> guard(m_mutex);
441 if (m_process.IsAlive() && deallocate_memory) {
442 PermissionsToBlockMap::iterator pos, end = m_memory_map.end();
443 for (pos = m_memory_map.begin(); pos != end; ++pos)
444 m_process.DoDeallocateMemory(pos->second->GetBaseAddress());
445 }
446 m_memory_map.clear();
447}
448
450AllocatedMemoryCache::AllocatePage(uint32_t byte_size, uint32_t permissions,
451 uint32_t chunk_size, Status &error) {
452 AllocatedBlockSP block_sp;
453 const size_t page_size = 4096;
454 const size_t num_pages = (byte_size + page_size - 1) / page_size;
455 const size_t page_byte_size = num_pages * page_size;
456
457 addr_t addr = m_process.DoAllocateMemory(page_byte_size, permissions, error);
458
460 LLDB_LOGF(log,
461 "Process::DoAllocateMemory (byte_size = 0x%8.8" PRIx32
462 ", permissions = %s) => 0x%16.16" PRIx64,
463 (uint32_t)page_byte_size, GetPermissionsAsCString(permissions),
464 (uint64_t)addr);
465
466 if (addr != LLDB_INVALID_ADDRESS) {
467 block_sp = std::make_shared<AllocatedBlock>(addr, page_byte_size,
468 permissions, chunk_size);
469 m_memory_map.insert(std::make_pair(permissions, block_sp));
470 }
471 return block_sp;
472}
473
475 uint32_t permissions,
476 Status &error) {
477 std::lock_guard<std::recursive_mutex> guard(m_mutex);
478
480 std::pair<PermissionsToBlockMap::iterator, PermissionsToBlockMap::iterator>
481 range = m_memory_map.equal_range(permissions);
482
483 for (PermissionsToBlockMap::iterator pos = range.first; pos != range.second;
484 ++pos) {
485 addr = (*pos).second->ReserveBlock(byte_size);
486 if (addr != LLDB_INVALID_ADDRESS)
487 break;
488 }
489
490 if (addr == LLDB_INVALID_ADDRESS) {
491 AllocatedBlockSP block_sp(AllocatePage(byte_size, permissions, 16, error));
492
493 if (block_sp)
494 addr = block_sp->ReserveBlock(byte_size);
495 }
497 LLDB_LOGF(log,
498 "AllocatedMemoryCache::AllocateMemory (byte_size = 0x%8.8" PRIx32
499 ", permissions = %s) => 0x%16.16" PRIx64,
500 (uint32_t)byte_size, GetPermissionsAsCString(permissions),
501 (uint64_t)addr);
502 return addr;
503}
504
506 std::lock_guard<std::recursive_mutex> guard(m_mutex);
507
508 PermissionsToBlockMap::iterator pos, end = m_memory_map.end();
509 bool success = false;
510 for (pos = m_memory_map.begin(); pos != end; ++pos) {
511 if (pos->second->Contains(addr)) {
512 success = pos->second->FreeBlock(addr);
513 break;
514 }
515 }
517 LLDB_LOGF(log,
518 "AllocatedMemoryCache::DeallocateMemory (addr = 0x%16.16" PRIx64
519 ") => %i",
520 (uint64_t)addr, success);
521 return success;
522}
523
525 std::lock_guard<std::recursive_mutex> guard(m_mutex);
526
527 return llvm::any_of(m_memory_map, [addr](const auto &block) {
528 return block.second->Contains(addr);
529 });
530}
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOGF(log,...)
Definition Log.h:389
#define LLDB_LOG_VERBOSE(log,...)
Definition Log.h:382
uint32_t CalculateChunksNeededForSize(uint32_t size) const
Definition Memory.h:126
bool FreeBlock(lldb::addr_t addr)
Definition Memory.cpp:420
lldb::addr_t ReserveBlock(uint32_t size)
Definition Memory.cpp:368
const uint32_t m_permissions
Definition Memory.h:132
Range< lldb::addr_t, uint32_t > m_range
Definition Memory.h:130
AllocatedBlock(lldb::addr_t addr, uint32_t byte_size, uint32_t permissions, uint32_t chunk_size)
Definition Memory.cpp:356
RangeVector< lldb::addr_t, uint32_t > m_free_blocks
Definition Memory.h:136
RangeVector< lldb::addr_t, uint32_t > m_reserved_blocks
Definition Memory.h:138
const uint32_t m_chunk_size
Definition Memory.h:134
lldb::addr_t AllocateMemory(size_t byte_size, uint32_t permissions, Status &error)
Definition Memory.cpp:474
bool IsInCache(lldb::addr_t addr) const
Definition Memory.cpp:524
AllocatedMemoryCache(Process &process)
Definition Memory.cpp:434
std::recursive_mutex m_mutex
Definition Memory.h:168
void Clear(bool deallocate_memory)
Definition Memory.cpp:439
bool DeallocateMemory(lldb::addr_t ptr)
Definition Memory.cpp:505
std::shared_ptr< AllocatedBlock > AllocatedBlockSP
Definition Memory.h:161
PermissionsToBlockMap m_memory_map
Definition Memory.h:170
AllocatedBlockSP AllocatePage(uint32_t byte_size, uint32_t permissions, uint32_t chunk_size, Status &error)
Definition Memory.cpp:450
uint32_t GetMemoryCacheLineSize() const
Definition Memory.h:43
const uint8_t * FindL1CacheEntry(lldb::addr_t addr, size_t len) const
Definition Memory.cpp:127
MemoryCache(Process &process)
Definition Memory.cpp:26
std::recursive_mutex m_mutex
Definition Memory.h:65
bool RemoveInvalidRange(lldb::addr_t base_addr, lldb::addr_t byte_size)
Definition Memory.cpp:112
void Flush(lldb::addr_t addr, size_t size)
Definition Memory.cpp:54
llvm::SmallVector< llvm::MutableArrayRef< uint8_t > > ReadRanges(llvm::ArrayRef< Range< lldb::addr_t, size_t > > ranges, llvm::MutableArrayRef< uint8_t > buffer)
Reads multiple memory ranges, serving cache hits from L1 and L2 and batching all misses through Proce...
Definition Memory.cpp:296
void AddL1CacheData(lldb::addr_t addr, const void *src, size_t src_len)
Definition Memory.cpp:43
const uint8_t * FindL2CacheEntry(lldb::addr_t addr, size_t len) const
Definition Memory.cpp:141
InvalidRanges m_invalid_ranges
Definition Memory.h:71
const uint8_t * FindCacheEntry(lldb::addr_t addr, size_t len) const
Definition Memory.cpp:154
void Clear(bool clear_invalid_ranges=false)
Definition Memory.cpp:34
size_t Read(lldb::addr_t addr, void *dst, size_t dst_len, Status &error)
Definition Memory.cpp:190
void AddInvalidRange(lldb::addr_t base_addr, lldb::addr_t byte_size)
Definition Memory.cpp:102
lldb::DataBufferSP GetL2CacheLine(lldb::addr_t addr, Status &error)
Definition Memory.cpp:162
Range< lldb::addr_t, lldb::addr_t > AddrRange
Definition Memory.h:63
uint32_t m_L2_cache_line_byte_size
Definition Memory.h:73
A plug-in interface definition class for debugging a process.
Definition Process.h:367
An error handling class.
Definition Status.h:118
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
#define UINT64_MAX
#define LLDB_INVALID_ADDRESS
#define UINT32_MAX
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:338
const char * GetPermissionsAsCString(uint32_t permissions)
Definition State.cpp:44
std::shared_ptr< lldb_private::DataBuffer > DataBufferSP
uint64_t addr_t
Definition lldb-types.h:80
bool Contains(BaseType r) const
Definition RangeMap.h:93
BaseType GetRangeBase() const
Definition RangeMap.h:45
SizeType GetByteSize() const
Definition RangeMap.h:87
BaseType GetRangeEnd() const
Definition RangeMap.h:78
bool DoesIntersect(const Range &rhs) const
Definition RangeMap.h:117
void SetByteSize(SizeType s)
Definition RangeMap.h:89