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 // FIXME: We should do a more thorough check to make sure that we're not
197 // overlapping with any invalid ranges (e.g. Read 0x100 - 0x200 but there's an
198 // invalid range 0x180 - 0x280). `FindEntryThatContains` has an implementation
199 // that takes a range, but it only checks to see if the argument is contained
200 // by an existing invalid range. It cannot check if the argument contains
201 // invalid ranges and cannot check for overlaps.
202 if (m_invalid_ranges.FindEntryThatContains(addr)) {
204 "memory read failed for 0x%" PRIx64, addr);
205 return 0;
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 std::lock_guard<std::recursive_mutex> guard(m_mutex);
299
300 llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> results;
301 results.reserve(ranges.size());
302 llvm::SmallVector<Range<lldb::addr_t, size_t>> missed_ranges;
303
304 // Iterate once serving requests from the caches.
305 for (auto range : ranges) {
306 const lldb::addr_t addr = range.GetRangeBase();
307 const size_t len = range.GetByteSize();
308
309 if (m_invalid_ranges.FindEntryThatContains(addr)) {
310 results.push_back(buffer.take_front(0));
311 continue;
312 }
313
314 const uint8_t *cached = FindCacheEntry(addr, len);
315 if (cached) {
316 results.push_back(buffer.take_front(len));
317 buffer = buffer.drop_front(len);
318 memcpy(results.back().data(), cached, len);
319 continue;
320 }
321
322 // Use a nullptr to denote this needs fetching.
323 results.emplace_back(nullptr, nullptr);
324 missed_ranges.push_back(range);
325 }
326
327 if (missed_ranges.empty())
328 return results;
329
330 llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> fetched_buffers_vec =
331 m_process.DoReadMemoryRanges(missed_ranges, buffer);
332 auto fetched_buffers = llvm::ArrayRef(fetched_buffers_vec);
333
334 for (auto [missed_range, fetched] : llvm::zip(missed_ranges, fetched_buffers))
335 AddL1CacheData(missed_range.GetRangeBase(), fetched);
336
337 // Use the just-fetched memory to fill in the gaps left by the cache.
338 for (auto &result : results)
339 if (result.data() == nullptr)
340 result = fetched_buffers.consume_front();
341
342 return results;
343}
344
346 uint32_t permissions, uint32_t chunk_size)
347 : m_range(addr, byte_size), m_permissions(permissions),
348 m_chunk_size(chunk_size)
349{
350 // The entire address range is free to start with.
351 m_free_blocks.Append(m_range);
352 assert(byte_size > chunk_size);
353}
354
356
358 // We must return something valid for zero bytes.
359 if (size == 0)
360 size = 1;
362
363 const size_t free_count = m_free_blocks.GetSize();
364 for (size_t i=0; i<free_count; ++i)
365 {
366 auto &free_block = m_free_blocks.GetEntryRef(i);
367 const lldb::addr_t range_size = free_block.GetByteSize();
368 if (range_size >= size)
369 {
370 // We found a free block that is big enough for our data. Figure out how
371 // many chunks we will need and calculate the resulting block size we
372 // will reserve.
373 addr_t addr = free_block.GetRangeBase();
374 size_t num_chunks = CalculateChunksNeededForSize(size);
375 lldb::addr_t block_size = num_chunks * m_chunk_size;
376 lldb::addr_t bytes_left = range_size - block_size;
377 if (bytes_left == 0)
378 {
379 // The newly allocated block will take all of the bytes in this
380 // available block, so we can just add it to the allocated ranges and
381 // remove the range from the free ranges.
382 m_reserved_blocks.Insert(free_block, false);
383 m_free_blocks.RemoveEntryAtIndex(i);
384 }
385 else
386 {
387 // Make the new allocated range and add it to the allocated ranges.
388 Range<lldb::addr_t, uint32_t> reserved_block(free_block);
389 reserved_block.SetByteSize(block_size);
390 // Insert the reserved range and don't combine it with other blocks in
391 // the reserved blocks list.
392 m_reserved_blocks.Insert(reserved_block, false);
393 // Adjust the free range in place since we won't change the sorted
394 // ordering of the m_free_blocks list.
395 free_block.SetRangeBase(reserved_block.GetRangeEnd());
396 free_block.SetByteSize(bytes_left);
397 }
398 LLDB_LOG_VERBOSE(log, "({0}) (size = {1} ({1:x})) => {2:x}", this, size,
399 addr);
400 return addr;
401 }
402 }
403
404 LLDB_LOG_VERBOSE(log, "({0}) (size = {1} ({1:x})) => {2:x}", this, size,
407}
408
410 bool success = false;
411 auto entry_idx = m_reserved_blocks.FindEntryIndexThatContains(addr);
412 if (entry_idx != UINT32_MAX)
413 {
414 m_free_blocks.Insert(m_reserved_blocks.GetEntryRef(entry_idx), true);
415 m_reserved_blocks.RemoveEntryAtIndex(entry_idx);
416 success = true;
417 }
419 LLDB_LOG_VERBOSE(log, "({0}) (addr = {1:x}) => {2}", this, addr, success);
420 return success;
421}
422
425
427
428void AllocatedMemoryCache::Clear(bool deallocate_memory) {
429 std::lock_guard<std::recursive_mutex> guard(m_mutex);
430 if (m_process.IsAlive() && deallocate_memory) {
431 PermissionsToBlockMap::iterator pos, end = m_memory_map.end();
432 for (pos = m_memory_map.begin(); pos != end; ++pos)
433 m_process.DoDeallocateMemory(pos->second->GetBaseAddress());
434 }
435 m_memory_map.clear();
436}
437
439AllocatedMemoryCache::AllocatePage(uint32_t byte_size, uint32_t permissions,
440 uint32_t chunk_size, Status &error) {
441 AllocatedBlockSP block_sp;
442 const size_t page_size = 4096;
443 const size_t num_pages = (byte_size + page_size - 1) / page_size;
444 const size_t page_byte_size = num_pages * page_size;
445
446 addr_t addr = m_process.DoAllocateMemory(page_byte_size, permissions, error);
447
449 LLDB_LOGF(log,
450 "Process::DoAllocateMemory (byte_size = 0x%8.8" PRIx32
451 ", permissions = %s) => 0x%16.16" PRIx64,
452 (uint32_t)page_byte_size, GetPermissionsAsCString(permissions),
453 (uint64_t)addr);
454
455 if (addr != LLDB_INVALID_ADDRESS) {
456 block_sp = std::make_shared<AllocatedBlock>(addr, page_byte_size,
457 permissions, chunk_size);
458 m_memory_map.insert(std::make_pair(permissions, block_sp));
459 }
460 return block_sp;
461}
462
464 uint32_t permissions,
465 Status &error) {
466 std::lock_guard<std::recursive_mutex> guard(m_mutex);
467
469 std::pair<PermissionsToBlockMap::iterator, PermissionsToBlockMap::iterator>
470 range = m_memory_map.equal_range(permissions);
471
472 for (PermissionsToBlockMap::iterator pos = range.first; pos != range.second;
473 ++pos) {
474 addr = (*pos).second->ReserveBlock(byte_size);
475 if (addr != LLDB_INVALID_ADDRESS)
476 break;
477 }
478
479 if (addr == LLDB_INVALID_ADDRESS) {
480 AllocatedBlockSP block_sp(AllocatePage(byte_size, permissions, 16, error));
481
482 if (block_sp)
483 addr = block_sp->ReserveBlock(byte_size);
484 }
486 LLDB_LOGF(log,
487 "AllocatedMemoryCache::AllocateMemory (byte_size = 0x%8.8" PRIx32
488 ", permissions = %s) => 0x%16.16" PRIx64,
489 (uint32_t)byte_size, GetPermissionsAsCString(permissions),
490 (uint64_t)addr);
491 return addr;
492}
493
495 std::lock_guard<std::recursive_mutex> guard(m_mutex);
496
497 PermissionsToBlockMap::iterator pos, end = m_memory_map.end();
498 bool success = false;
499 for (pos = m_memory_map.begin(); pos != end; ++pos) {
500 if (pos->second->Contains(addr)) {
501 success = pos->second->FreeBlock(addr);
502 break;
503 }
504 }
506 LLDB_LOGF(log,
507 "AllocatedMemoryCache::DeallocateMemory (addr = 0x%16.16" PRIx64
508 ") => %i",
509 (uint64_t)addr, success);
510 return success;
511}
512
514 std::lock_guard<std::recursive_mutex> guard(m_mutex);
515
516 return llvm::any_of(m_memory_map, [addr](const auto &block) {
517 return block.second->Contains(addr);
518 });
519}
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:409
lldb::addr_t ReserveBlock(uint32_t size)
Definition Memory.cpp:357
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:345
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:463
bool IsInCache(lldb::addr_t addr) const
Definition Memory.cpp:513
AllocatedMemoryCache(Process &process)
Definition Memory.cpp:423
std::recursive_mutex m_mutex
Definition Memory.h:168
void Clear(bool deallocate_memory)
Definition Memory.cpp:428
bool DeallocateMemory(lldb::addr_t ptr)
Definition Memory.cpp:494
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:439
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:360
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