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 // Erase any blocks from the L1 cache that intersect with the flush range
61 if (!m_L1_cache.empty()) {
62 AddrRange flush_range(addr, size);
63 BlockMap::iterator pos = m_L1_cache.upper_bound(addr);
64 if (pos != m_L1_cache.begin()) {
65 --pos;
66 }
67 while (pos != m_L1_cache.end()) {
68 AddrRange chunk_range(pos->first, pos->second->GetByteSize());
69 if (!chunk_range.DoesIntersect(flush_range))
70 break;
71 pos = m_L1_cache.erase(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 Status &error) {
143 // This function assumes that the address given is aligned correctly.
144 assert((line_base_addr % m_L2_cache_line_byte_size) == 0);
145
146 std::lock_guard<std::recursive_mutex> guard(m_mutex);
147 auto pos = m_L2_cache.find(line_base_addr);
148 if (pos != m_L2_cache.end())
149 return pos->second;
150
151 auto data_buffer_heap_sp =
152 std::make_shared<DataBufferHeap>(m_L2_cache_line_byte_size, 0);
153 size_t process_bytes_read = m_process.ReadMemoryFromInferior(
154 line_base_addr, data_buffer_heap_sp->GetBytes(),
155 data_buffer_heap_sp->GetByteSize(), error);
156
157 // If we failed a read, not much we can do.
158 if (process_bytes_read == 0)
159 return lldb::DataBufferSP();
160
161 // If we didn't get a complete read, we can still cache what we did get.
162 if (process_bytes_read < m_L2_cache_line_byte_size)
163 data_buffer_heap_sp->SetByteSize(process_bytes_read);
164
165 m_L2_cache[line_base_addr] = data_buffer_heap_sp;
166 return data_buffer_heap_sp;
167}
168
169size_t MemoryCache::Read(addr_t addr, void *dst, size_t dst_len,
170 Status &error) {
171 if (!dst || dst_len == 0)
172 return 0;
173
174 std::lock_guard<std::recursive_mutex> guard(m_mutex);
175 // FIXME: We should do a more thorough check to make sure that we're not
176 // overlapping with any invalid ranges (e.g. Read 0x100 - 0x200 but there's an
177 // invalid range 0x180 - 0x280). `FindEntryThatContains` has an implementation
178 // that takes a range, but it only checks to see if the argument is contained
179 // by an existing invalid range. It cannot check if the argument contains
180 // invalid ranges and cannot check for overlaps.
181 if (m_invalid_ranges.FindEntryThatContains(addr)) {
183 "memory read failed for 0x%" PRIx64, addr);
184 return 0;
185 }
186
187 // Check the L1 cache for a range that contains the entire memory read.
188 // L1 cache contains chunks of memory that are not required to be the size of
189 // an L2 cache line. We avoid trying to do partial reads from the L1 cache to
190 // simplify the implementation.
191 if (const uint8_t *l1_data = FindL1CacheEntry(addr, dst_len)) {
192 memcpy(dst, l1_data, dst_len);
193 return dst_len;
194 }
195
196 // If the size of the read is greater than the size of an L2 cache line, we'll
197 // just read from the inferior. If that read is successful, we'll cache what
198 // we read in the L1 cache for future use.
199 if (dst_len > m_L2_cache_line_byte_size) {
200 size_t bytes_read =
201 m_process.ReadMemoryFromInferior(addr, dst, dst_len, error);
202 if (bytes_read > 0)
203 AddL1CacheData(addr, dst, bytes_read);
204 return bytes_read;
205 }
206
207 // If the size of the read fits inside one L2 cache line, we'll try reading
208 // from the L2 cache. Note that if the range of memory we're reading sits
209 // between two contiguous cache lines, we'll touch two cache lines instead of
210 // just one.
211
212 // We're going to have all of our loads and reads be cache line aligned.
213 addr_t cache_line_offset = addr % m_L2_cache_line_byte_size;
214 addr_t cache_line_base_addr = addr - cache_line_offset;
215 DataBufferSP first_cache_line = GetL2CacheLine(cache_line_base_addr, error);
216 // If we get nothing, then the read to the inferior likely failed. Nothing to
217 // do here.
218 if (!first_cache_line)
219 return 0;
220
221 // If the cache line was not filled out completely and the offset is greater
222 // than what we have available, we can't do anything further here.
223 if (cache_line_offset >= first_cache_line->GetByteSize())
224 return 0;
225
226 uint8_t *dst_buf = (uint8_t *)dst;
227 size_t bytes_left = dst_len;
228 size_t read_size = first_cache_line->GetByteSize() - cache_line_offset;
229 if (read_size > bytes_left)
230 read_size = bytes_left;
231
232 memcpy(dst_buf + dst_len - bytes_left,
233 first_cache_line->GetBytes() + cache_line_offset, read_size);
234 bytes_left -= read_size;
235
236 // If the cache line was not filled out completely and we still have data to
237 // read, we can't do anything further.
238 if (first_cache_line->GetByteSize() < m_L2_cache_line_byte_size &&
239 bytes_left > 0)
240 return dst_len - bytes_left;
241
242 // We'll hit this scenario if our read straddles two cache lines.
243 if (bytes_left > 0) {
244 cache_line_base_addr += m_L2_cache_line_byte_size;
245
246 // FIXME: Until we are able to more thoroughly check for invalid ranges, we
247 // will have to check the second line to see if it is in an invalid range as
248 // well. See the check near the beginning of the function for more details.
249 if (m_invalid_ranges.FindEntryThatContains(cache_line_base_addr)) {
251 "memory read failed for 0x%" PRIx64, cache_line_base_addr);
252 return dst_len - bytes_left;
253 }
254
255 DataBufferSP second_cache_line =
256 GetL2CacheLine(cache_line_base_addr, error);
257 if (!second_cache_line)
258 return dst_len - bytes_left;
259
260 read_size = bytes_left;
261 if (read_size > second_cache_line->GetByteSize())
262 read_size = second_cache_line->GetByteSize();
263
264 memcpy(dst_buf + dst_len - bytes_left, second_cache_line->GetBytes(),
265 read_size);
266 bytes_left -= read_size;
267
268 return dst_len - bytes_left;
269 }
270
271 return dst_len;
272}
273
274llvm::SmallVector<llvm::MutableArrayRef<uint8_t>>
276 llvm::MutableArrayRef<uint8_t> buffer) {
277 std::lock_guard<std::recursive_mutex> guard(m_mutex);
278
279 llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> results;
280 results.reserve(ranges.size());
281 llvm::SmallVector<Range<lldb::addr_t, size_t>> missed_ranges;
282
283 // Iterate once serving requests from L1.
284 for (auto range : ranges) {
285 const lldb::addr_t addr = range.GetRangeBase();
286 const size_t len = range.GetByteSize();
287
288 if (m_invalid_ranges.FindEntryThatContains(addr)) {
289 results.push_back(buffer.take_front(0));
290 continue;
291 }
292
293 if (const uint8_t *l1_data = FindL1CacheEntry(addr, len)) {
294 results.push_back(buffer.take_front(len));
295 buffer = buffer.drop_front(len);
296 memcpy(results.back().data(), l1_data, len);
297 continue;
298 }
299
300 // Use a nullptr to denote this needs fetching.
301 results.emplace_back(nullptr, nullptr);
302 missed_ranges.push_back(range);
303 }
304
305 if (missed_ranges.empty())
306 return results;
307
308 llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> fetched_buffers_vec =
309 m_process.DoReadMemoryRanges(missed_ranges, buffer);
310 auto fetched_buffers = llvm::ArrayRef(fetched_buffers_vec);
311
312 for (auto [missed_range, fetched] : llvm::zip(missed_ranges, fetched_buffers))
313 AddL1CacheData(missed_range.GetRangeBase(), fetched);
314
315 // Use the just-fetched memory to fill in the gaps left by the cache.
316 for (auto &result : results)
317 if (result.data() == nullptr)
318 result = fetched_buffers.consume_front();
319
320 return results;
321}
322
324 uint32_t permissions, uint32_t chunk_size)
325 : m_range(addr, byte_size), m_permissions(permissions),
326 m_chunk_size(chunk_size)
327{
328 // The entire address range is free to start with.
329 m_free_blocks.Append(m_range);
330 assert(byte_size > chunk_size);
331}
332
334
336 // We must return something valid for zero bytes.
337 if (size == 0)
338 size = 1;
340
341 const size_t free_count = m_free_blocks.GetSize();
342 for (size_t i=0; i<free_count; ++i)
343 {
344 auto &free_block = m_free_blocks.GetEntryRef(i);
345 const lldb::addr_t range_size = free_block.GetByteSize();
346 if (range_size >= size)
347 {
348 // We found a free block that is big enough for our data. Figure out how
349 // many chunks we will need and calculate the resulting block size we
350 // will reserve.
351 addr_t addr = free_block.GetRangeBase();
352 size_t num_chunks = CalculateChunksNeededForSize(size);
353 lldb::addr_t block_size = num_chunks * m_chunk_size;
354 lldb::addr_t bytes_left = range_size - block_size;
355 if (bytes_left == 0)
356 {
357 // The newly allocated block will take all of the bytes in this
358 // available block, so we can just add it to the allocated ranges and
359 // remove the range from the free ranges.
360 m_reserved_blocks.Insert(free_block, false);
361 m_free_blocks.RemoveEntryAtIndex(i);
362 }
363 else
364 {
365 // Make the new allocated range and add it to the allocated ranges.
366 Range<lldb::addr_t, uint32_t> reserved_block(free_block);
367 reserved_block.SetByteSize(block_size);
368 // Insert the reserved range and don't combine it with other blocks in
369 // the reserved blocks list.
370 m_reserved_blocks.Insert(reserved_block, false);
371 // Adjust the free range in place since we won't change the sorted
372 // ordering of the m_free_blocks list.
373 free_block.SetRangeBase(reserved_block.GetRangeEnd());
374 free_block.SetByteSize(bytes_left);
375 }
376 LLDB_LOG_VERBOSE(log, "({0}) (size = {1} ({1:x})) => {2:x}", this, size,
377 addr);
378 return addr;
379 }
380 }
381
382 LLDB_LOG_VERBOSE(log, "({0}) (size = {1} ({1:x})) => {2:x}", this, size,
385}
386
388 bool success = false;
389 auto entry_idx = m_reserved_blocks.FindEntryIndexThatContains(addr);
390 if (entry_idx != UINT32_MAX)
391 {
392 m_free_blocks.Insert(m_reserved_blocks.GetEntryRef(entry_idx), true);
393 m_reserved_blocks.RemoveEntryAtIndex(entry_idx);
394 success = true;
395 }
397 LLDB_LOG_VERBOSE(log, "({0}) (addr = {1:x}) => {2}", this, addr, success);
398 return success;
399}
400
403
405
406void AllocatedMemoryCache::Clear(bool deallocate_memory) {
407 std::lock_guard<std::recursive_mutex> guard(m_mutex);
408 if (m_process.IsAlive() && deallocate_memory) {
409 PermissionsToBlockMap::iterator pos, end = m_memory_map.end();
410 for (pos = m_memory_map.begin(); pos != end; ++pos)
411 m_process.DoDeallocateMemory(pos->second->GetBaseAddress());
412 }
413 m_memory_map.clear();
414}
415
417AllocatedMemoryCache::AllocatePage(uint32_t byte_size, uint32_t permissions,
418 uint32_t chunk_size, Status &error) {
419 AllocatedBlockSP block_sp;
420 const size_t page_size = 4096;
421 const size_t num_pages = (byte_size + page_size - 1) / page_size;
422 const size_t page_byte_size = num_pages * page_size;
423
424 addr_t addr = m_process.DoAllocateMemory(page_byte_size, permissions, error);
425
427 LLDB_LOGF(log,
428 "Process::DoAllocateMemory (byte_size = 0x%8.8" PRIx32
429 ", permissions = %s) => 0x%16.16" PRIx64,
430 (uint32_t)page_byte_size, GetPermissionsAsCString(permissions),
431 (uint64_t)addr);
432
433 if (addr != LLDB_INVALID_ADDRESS) {
434 block_sp = std::make_shared<AllocatedBlock>(addr, page_byte_size,
435 permissions, chunk_size);
436 m_memory_map.insert(std::make_pair(permissions, block_sp));
437 }
438 return block_sp;
439}
440
442 uint32_t permissions,
443 Status &error) {
444 std::lock_guard<std::recursive_mutex> guard(m_mutex);
445
447 std::pair<PermissionsToBlockMap::iterator, PermissionsToBlockMap::iterator>
448 range = m_memory_map.equal_range(permissions);
449
450 for (PermissionsToBlockMap::iterator pos = range.first; pos != range.second;
451 ++pos) {
452 addr = (*pos).second->ReserveBlock(byte_size);
453 if (addr != LLDB_INVALID_ADDRESS)
454 break;
455 }
456
457 if (addr == LLDB_INVALID_ADDRESS) {
458 AllocatedBlockSP block_sp(AllocatePage(byte_size, permissions, 16, error));
459
460 if (block_sp)
461 addr = block_sp->ReserveBlock(byte_size);
462 }
464 LLDB_LOGF(log,
465 "AllocatedMemoryCache::AllocateMemory (byte_size = 0x%8.8" PRIx32
466 ", permissions = %s) => 0x%16.16" PRIx64,
467 (uint32_t)byte_size, GetPermissionsAsCString(permissions),
468 (uint64_t)addr);
469 return addr;
470}
471
473 std::lock_guard<std::recursive_mutex> guard(m_mutex);
474
475 PermissionsToBlockMap::iterator pos, end = m_memory_map.end();
476 bool success = false;
477 for (pos = m_memory_map.begin(); pos != end; ++pos) {
478 if (pos->second->Contains(addr)) {
479 success = pos->second->FreeBlock(addr);
480 break;
481 }
482 }
484 LLDB_LOGF(log,
485 "AllocatedMemoryCache::DeallocateMemory (addr = 0x%16.16" PRIx64
486 ") => %i",
487 (uint64_t)addr, success);
488 return success;
489}
490
492 std::lock_guard<std::recursive_mutex> guard(m_mutex);
493
494 return llvm::any_of(m_memory_map, [addr](const auto &block) {
495 return block.second->Contains(addr);
496 });
497}
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOGF(log,...)
Definition Log.h:378
#define LLDB_LOG_VERBOSE(log,...)
Definition Log.h:371
uint32_t CalculateChunksNeededForSize(uint32_t size) const
Definition Memory.h:115
bool FreeBlock(lldb::addr_t addr)
Definition Memory.cpp:387
lldb::addr_t ReserveBlock(uint32_t size)
Definition Memory.cpp:335
const uint32_t m_permissions
Definition Memory.h:121
Range< lldb::addr_t, uint32_t > m_range
Definition Memory.h:119
AllocatedBlock(lldb::addr_t addr, uint32_t byte_size, uint32_t permissions, uint32_t chunk_size)
Definition Memory.cpp:323
RangeVector< lldb::addr_t, uint32_t > m_free_blocks
Definition Memory.h:125
RangeVector< lldb::addr_t, uint32_t > m_reserved_blocks
Definition Memory.h:127
const uint32_t m_chunk_size
Definition Memory.h:123
lldb::addr_t AllocateMemory(size_t byte_size, uint32_t permissions, Status &error)
Definition Memory.cpp:441
bool IsInCache(lldb::addr_t addr) const
Definition Memory.cpp:491
AllocatedMemoryCache(Process &process)
Definition Memory.cpp:401
std::recursive_mutex m_mutex
Definition Memory.h:157
void Clear(bool deallocate_memory)
Definition Memory.cpp:406
bool DeallocateMemory(lldb::addr_t ptr)
Definition Memory.cpp:472
std::shared_ptr< AllocatedBlock > AllocatedBlockSP
Definition Memory.h:150
PermissionsToBlockMap m_memory_map
Definition Memory.h:159
AllocatedBlockSP AllocatePage(uint32_t byte_size, uint32_t permissions, uint32_t chunk_size, Status &error)
Definition Memory.cpp:417
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 batching all misses through Process::DoR...
Definition Memory.cpp:275
void AddL1CacheData(lldb::addr_t addr, const void *src, size_t src_len)
Definition Memory.cpp:43
InvalidRanges m_invalid_ranges
Definition Memory.h:71
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:169
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:141
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:357
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:327
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