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 <cinttypes>
18#include <memory>
19
20using namespace lldb;
21using namespace lldb_private;
22
23// MemoryCache constructor
28
29// Destructor
31
32void MemoryCache::Clear(bool clear_invalid_ranges) {
33 std::lock_guard<std::recursive_mutex> guard(m_mutex);
34 m_L1_cache.clear();
35 m_L2_cache.clear();
36 if (clear_invalid_ranges)
37 m_invalid_ranges.Clear();
38 m_L2_cache_line_byte_size = m_process.GetMemoryCacheLineSize();
39}
40
41void MemoryCache::AddL1CacheData(lldb::addr_t addr, const void *src,
42 size_t src_len) {
44 addr, DataBufferSP(new DataBufferHeap(DataBufferHeap(src, src_len))));
45}
46
48 const DataBufferSP &data_buffer_sp) {
49 std::lock_guard<std::recursive_mutex> guard(m_mutex);
50 m_L1_cache[addr] = data_buffer_sp;
51}
52
53void MemoryCache::Flush(addr_t addr, size_t size) {
54 if (size == 0)
55 return;
56
57 std::lock_guard<std::recursive_mutex> guard(m_mutex);
58
59 // Erase any blocks from the L1 cache that intersect with the flush range
60 if (!m_L1_cache.empty()) {
61 AddrRange flush_range(addr, size);
62 BlockMap::iterator pos = m_L1_cache.upper_bound(addr);
63 if (pos != m_L1_cache.begin()) {
64 --pos;
65 }
66 while (pos != m_L1_cache.end()) {
67 AddrRange chunk_range(pos->first, pos->second->GetByteSize());
68 if (!chunk_range.DoesIntersect(flush_range))
69 break;
70 pos = m_L1_cache.erase(pos);
71 }
72 }
73
74 if (!m_L2_cache.empty()) {
75 const uint32_t cache_line_byte_size = m_L2_cache_line_byte_size;
76 const addr_t end_addr = (addr + size - 1);
77 const addr_t first_cache_line_addr = addr - (addr % cache_line_byte_size);
78 const addr_t last_cache_line_addr =
79 end_addr - (end_addr % cache_line_byte_size);
80 // Watch for overflow where size will cause us to go off the end of the
81 // 64 bit address space
82 uint32_t num_cache_lines;
83 if (last_cache_line_addr >= first_cache_line_addr)
84 num_cache_lines = ((last_cache_line_addr - first_cache_line_addr) /
85 cache_line_byte_size) +
86 1;
87 else
88 num_cache_lines =
89 (UINT64_MAX - first_cache_line_addr + 1) / cache_line_byte_size;
90
91 uint32_t cache_idx = 0;
92 for (addr_t curr_addr = first_cache_line_addr; cache_idx < num_cache_lines;
93 curr_addr += cache_line_byte_size, ++cache_idx) {
94 BlockMap::iterator pos = m_L2_cache.find(curr_addr);
95 if (pos != m_L2_cache.end())
96 m_L2_cache.erase(pos);
97 }
98 }
99}
100
102 lldb::addr_t byte_size) {
103 if (byte_size > 0) {
104 std::lock_guard<std::recursive_mutex> guard(m_mutex);
105 InvalidRanges::Entry range(base_addr, byte_size);
106 m_invalid_ranges.Append(range);
107 m_invalid_ranges.Sort();
108 }
109}
110
112 lldb::addr_t byte_size) {
113 if (byte_size > 0) {
114 std::lock_guard<std::recursive_mutex> guard(m_mutex);
115 const uint32_t idx = m_invalid_ranges.FindEntryIndexThatContains(base_addr);
116 if (idx != UINT32_MAX) {
117 const InvalidRanges::Entry *entry = m_invalid_ranges.GetEntryAtIndex(idx);
118 if (entry->GetRangeBase() == base_addr &&
119 entry->GetByteSize() == byte_size)
120 return m_invalid_ranges.RemoveEntryAtIndex(idx);
121 }
122 }
123 return false;
124}
125
127 size_t len) const {
128 if (m_L1_cache.empty())
129 return nullptr;
130 AddrRange read_range(addr, len);
131 BlockMap::const_iterator pos = m_L1_cache.upper_bound(addr);
132 if (pos != m_L1_cache.begin())
133 --pos;
134 AddrRange chunk_range(pos->first, pos->second->GetByteSize());
135 if (!chunk_range.Contains(read_range))
136 return nullptr;
137 return pos->second->GetBytes() + (addr - chunk_range.GetRangeBase());
138}
139
141 Status &error) {
142 // This function assumes that the address given is aligned correctly.
143 assert((line_base_addr % m_L2_cache_line_byte_size) == 0);
144
145 std::lock_guard<std::recursive_mutex> guard(m_mutex);
146 auto pos = m_L2_cache.find(line_base_addr);
147 if (pos != m_L2_cache.end())
148 return pos->second;
149
150 auto data_buffer_heap_sp =
151 std::make_shared<DataBufferHeap>(m_L2_cache_line_byte_size, 0);
152 size_t process_bytes_read = m_process.ReadMemoryFromInferior(
153 line_base_addr, data_buffer_heap_sp->GetBytes(),
154 data_buffer_heap_sp->GetByteSize(), error);
155
156 // If we failed a read, not much we can do.
157 if (process_bytes_read == 0)
158 return lldb::DataBufferSP();
159
160 // If we didn't get a complete read, we can still cache what we did get.
161 if (process_bytes_read < m_L2_cache_line_byte_size)
162 data_buffer_heap_sp->SetByteSize(process_bytes_read);
163
164 m_L2_cache[line_base_addr] = data_buffer_heap_sp;
165 return data_buffer_heap_sp;
166}
167
168size_t MemoryCache::Read(addr_t addr, void *dst, size_t dst_len,
169 Status &error) {
170 if (!dst || dst_len == 0)
171 return 0;
172
173 std::lock_guard<std::recursive_mutex> guard(m_mutex);
174 // FIXME: We should do a more thorough check to make sure that we're not
175 // overlapping with any invalid ranges (e.g. Read 0x100 - 0x200 but there's an
176 // invalid range 0x180 - 0x280). `FindEntryThatContains` has an implementation
177 // that takes a range, but it only checks to see if the argument is contained
178 // by an existing invalid range. It cannot check if the argument contains
179 // invalid ranges and cannot check for overlaps.
180 if (m_invalid_ranges.FindEntryThatContains(addr)) {
182 "memory read failed for 0x%" PRIx64, addr);
183 return 0;
184 }
185
186 // Check the L1 cache for a range that contains the entire memory read.
187 // L1 cache contains chunks of memory that are not required to be the size of
188 // an L2 cache line. We avoid trying to do partial reads from the L1 cache to
189 // simplify the implementation.
190 if (const uint8_t *l1_data = FindL1CacheEntry(addr, dst_len)) {
191 memcpy(dst, l1_data, dst_len);
192 return dst_len;
193 }
194
195 // If the size of the read is greater than the size of an L2 cache line, we'll
196 // just read from the inferior. If that read is successful, we'll cache what
197 // we read in the L1 cache for future use.
198 if (dst_len > m_L2_cache_line_byte_size) {
199 size_t bytes_read =
200 m_process.ReadMemoryFromInferior(addr, dst, dst_len, error);
201 if (bytes_read > 0)
202 AddL1CacheData(addr, dst, bytes_read);
203 return bytes_read;
204 }
205
206 // If the size of the read fits inside one L2 cache line, we'll try reading
207 // from the L2 cache. Note that if the range of memory we're reading sits
208 // between two contiguous cache lines, we'll touch two cache lines instead of
209 // just one.
210
211 // We're going to have all of our loads and reads be cache line aligned.
212 addr_t cache_line_offset = addr % m_L2_cache_line_byte_size;
213 addr_t cache_line_base_addr = addr - cache_line_offset;
214 DataBufferSP first_cache_line = GetL2CacheLine(cache_line_base_addr, error);
215 // If we get nothing, then the read to the inferior likely failed. Nothing to
216 // do here.
217 if (!first_cache_line)
218 return 0;
219
220 // If the cache line was not filled out completely and the offset is greater
221 // than what we have available, we can't do anything further here.
222 if (cache_line_offset >= first_cache_line->GetByteSize())
223 return 0;
224
225 uint8_t *dst_buf = (uint8_t *)dst;
226 size_t bytes_left = dst_len;
227 size_t read_size = first_cache_line->GetByteSize() - cache_line_offset;
228 if (read_size > bytes_left)
229 read_size = bytes_left;
230
231 memcpy(dst_buf + dst_len - bytes_left,
232 first_cache_line->GetBytes() + cache_line_offset, read_size);
233 bytes_left -= read_size;
234
235 // If the cache line was not filled out completely and we still have data to
236 // read, we can't do anything further.
237 if (first_cache_line->GetByteSize() < m_L2_cache_line_byte_size &&
238 bytes_left > 0)
239 return dst_len - bytes_left;
240
241 // We'll hit this scenario if our read straddles two cache lines.
242 if (bytes_left > 0) {
243 cache_line_base_addr += m_L2_cache_line_byte_size;
244
245 // FIXME: Until we are able to more thoroughly check for invalid ranges, we
246 // will have to check the second line to see if it is in an invalid range as
247 // well. See the check near the beginning of the function for more details.
248 if (m_invalid_ranges.FindEntryThatContains(cache_line_base_addr)) {
250 "memory read failed for 0x%" PRIx64, cache_line_base_addr);
251 return dst_len - bytes_left;
252 }
253
254 DataBufferSP second_cache_line =
255 GetL2CacheLine(cache_line_base_addr, error);
256 if (!second_cache_line)
257 return dst_len - bytes_left;
258
259 read_size = bytes_left;
260 if (read_size > second_cache_line->GetByteSize())
261 read_size = second_cache_line->GetByteSize();
262
263 memcpy(dst_buf + dst_len - bytes_left, second_cache_line->GetBytes(),
264 read_size);
265 bytes_left -= read_size;
266
267 return dst_len - bytes_left;
268 }
269
270 return dst_len;
271}
272
274 uint32_t permissions, uint32_t chunk_size)
275 : m_range(addr, byte_size), m_permissions(permissions),
276 m_chunk_size(chunk_size)
277{
278 // The entire address range is free to start with.
279 m_free_blocks.Append(m_range);
280 assert(byte_size > chunk_size);
281}
282
284
286 // We must return something valid for zero bytes.
287 if (size == 0)
288 size = 1;
290
291 const size_t free_count = m_free_blocks.GetSize();
292 for (size_t i=0; i<free_count; ++i)
293 {
294 auto &free_block = m_free_blocks.GetEntryRef(i);
295 const lldb::addr_t range_size = free_block.GetByteSize();
296 if (range_size >= size)
297 {
298 // We found a free block that is big enough for our data. Figure out how
299 // many chunks we will need and calculate the resulting block size we
300 // will reserve.
301 addr_t addr = free_block.GetRangeBase();
302 size_t num_chunks = CalculateChunksNeededForSize(size);
303 lldb::addr_t block_size = num_chunks * m_chunk_size;
304 lldb::addr_t bytes_left = range_size - block_size;
305 if (bytes_left == 0)
306 {
307 // The newly allocated block will take all of the bytes in this
308 // available block, so we can just add it to the allocated ranges and
309 // remove the range from the free ranges.
310 m_reserved_blocks.Insert(free_block, false);
311 m_free_blocks.RemoveEntryAtIndex(i);
312 }
313 else
314 {
315 // Make the new allocated range and add it to the allocated ranges.
316 Range<lldb::addr_t, uint32_t> reserved_block(free_block);
317 reserved_block.SetByteSize(block_size);
318 // Insert the reserved range and don't combine it with other blocks in
319 // the reserved blocks list.
320 m_reserved_blocks.Insert(reserved_block, false);
321 // Adjust the free range in place since we won't change the sorted
322 // ordering of the m_free_blocks list.
323 free_block.SetRangeBase(reserved_block.GetRangeEnd());
324 free_block.SetByteSize(bytes_left);
325 }
326 LLDB_LOG_VERBOSE(log, "({0}) (size = {1} ({1:x})) => {2:x}", this, size,
327 addr);
328 return addr;
329 }
330 }
331
332 LLDB_LOG_VERBOSE(log, "({0}) (size = {1} ({1:x})) => {2:x}", this, size,
335}
336
338 bool success = false;
339 auto entry_idx = m_reserved_blocks.FindEntryIndexThatContains(addr);
340 if (entry_idx != UINT32_MAX)
341 {
342 m_free_blocks.Insert(m_reserved_blocks.GetEntryRef(entry_idx), true);
343 m_reserved_blocks.RemoveEntryAtIndex(entry_idx);
344 success = true;
345 }
347 LLDB_LOG_VERBOSE(log, "({0}) (addr = {1:x}) => {2}", this, addr, success);
348 return success;
349}
350
353
355
356void AllocatedMemoryCache::Clear(bool deallocate_memory) {
357 std::lock_guard<std::recursive_mutex> guard(m_mutex);
358 if (m_process.IsAlive() && deallocate_memory) {
359 PermissionsToBlockMap::iterator pos, end = m_memory_map.end();
360 for (pos = m_memory_map.begin(); pos != end; ++pos)
361 m_process.DoDeallocateMemory(pos->second->GetBaseAddress());
362 }
363 m_memory_map.clear();
364}
365
367AllocatedMemoryCache::AllocatePage(uint32_t byte_size, uint32_t permissions,
368 uint32_t chunk_size, Status &error) {
369 AllocatedBlockSP block_sp;
370 const size_t page_size = 4096;
371 const size_t num_pages = (byte_size + page_size - 1) / page_size;
372 const size_t page_byte_size = num_pages * page_size;
373
374 addr_t addr = m_process.DoAllocateMemory(page_byte_size, permissions, error);
375
377 LLDB_LOGF(log,
378 "Process::DoAllocateMemory (byte_size = 0x%8.8" PRIx32
379 ", permissions = %s) => 0x%16.16" PRIx64,
380 (uint32_t)page_byte_size, GetPermissionsAsCString(permissions),
381 (uint64_t)addr);
382
383 if (addr != LLDB_INVALID_ADDRESS) {
384 block_sp = std::make_shared<AllocatedBlock>(addr, page_byte_size,
385 permissions, chunk_size);
386 m_memory_map.insert(std::make_pair(permissions, block_sp));
387 }
388 return block_sp;
389}
390
392 uint32_t permissions,
393 Status &error) {
394 std::lock_guard<std::recursive_mutex> guard(m_mutex);
395
397 std::pair<PermissionsToBlockMap::iterator, PermissionsToBlockMap::iterator>
398 range = m_memory_map.equal_range(permissions);
399
400 for (PermissionsToBlockMap::iterator pos = range.first; pos != range.second;
401 ++pos) {
402 addr = (*pos).second->ReserveBlock(byte_size);
403 if (addr != LLDB_INVALID_ADDRESS)
404 break;
405 }
406
407 if (addr == LLDB_INVALID_ADDRESS) {
408 AllocatedBlockSP block_sp(AllocatePage(byte_size, permissions, 16, error));
409
410 if (block_sp)
411 addr = block_sp->ReserveBlock(byte_size);
412 }
414 LLDB_LOGF(log,
415 "AllocatedMemoryCache::AllocateMemory (byte_size = 0x%8.8" PRIx32
416 ", permissions = %s) => 0x%16.16" PRIx64,
417 (uint32_t)byte_size, GetPermissionsAsCString(permissions),
418 (uint64_t)addr);
419 return addr;
420}
421
423 std::lock_guard<std::recursive_mutex> guard(m_mutex);
424
425 PermissionsToBlockMap::iterator pos, end = m_memory_map.end();
426 bool success = false;
427 for (pos = m_memory_map.begin(); pos != end; ++pos) {
428 if (pos->second->Contains(addr)) {
429 success = pos->second->FreeBlock(addr);
430 break;
431 }
432 }
434 LLDB_LOGF(log,
435 "AllocatedMemoryCache::DeallocateMemory (addr = 0x%16.16" PRIx64
436 ") => %i",
437 (uint64_t)addr, success);
438 return success;
439}
440
442 std::lock_guard<std::recursive_mutex> guard(m_mutex);
443
444 return llvm::any_of(m_memory_map, [addr](const auto &block) {
445 return block.second->Contains(addr);
446 });
447}
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:101
bool FreeBlock(lldb::addr_t addr)
Definition Memory.cpp:337
lldb::addr_t ReserveBlock(uint32_t size)
Definition Memory.cpp:285
const uint32_t m_permissions
Definition Memory.h:107
Range< lldb::addr_t, uint32_t > m_range
Definition Memory.h:105
AllocatedBlock(lldb::addr_t addr, uint32_t byte_size, uint32_t permissions, uint32_t chunk_size)
Definition Memory.cpp:273
RangeVector< lldb::addr_t, uint32_t > m_free_blocks
Definition Memory.h:111
RangeVector< lldb::addr_t, uint32_t > m_reserved_blocks
Definition Memory.h:113
const uint32_t m_chunk_size
Definition Memory.h:109
lldb::addr_t AllocateMemory(size_t byte_size, uint32_t permissions, Status &error)
Definition Memory.cpp:391
bool IsInCache(lldb::addr_t addr) const
Definition Memory.cpp:441
AllocatedMemoryCache(Process &process)
Definition Memory.cpp:351
std::recursive_mutex m_mutex
Definition Memory.h:143
void Clear(bool deallocate_memory)
Definition Memory.cpp:356
bool DeallocateMemory(lldb::addr_t ptr)
Definition Memory.cpp:422
std::shared_ptr< AllocatedBlock > AllocatedBlockSP
Definition Memory.h:136
PermissionsToBlockMap m_memory_map
Definition Memory.h:145
AllocatedBlockSP AllocatePage(uint32_t byte_size, uint32_t permissions, uint32_t chunk_size, Status &error)
Definition Memory.cpp:367
A subclass of DataBuffer that stores a data buffer on the heap.
uint32_t GetMemoryCacheLineSize() const
Definition Memory.h:34
const uint8_t * FindL1CacheEntry(lldb::addr_t addr, size_t len) const
Definition Memory.cpp:126
MemoryCache(Process &process)
Definition Memory.cpp:24
std::recursive_mutex m_mutex
Definition Memory.h:51
bool RemoveInvalidRange(lldb::addr_t base_addr, lldb::addr_t byte_size)
Definition Memory.cpp:111
void Flush(lldb::addr_t addr, size_t size)
Definition Memory.cpp:53
void AddL1CacheData(lldb::addr_t addr, const void *src, size_t src_len)
Definition Memory.cpp:41
InvalidRanges m_invalid_ranges
Definition Memory.h:57
void Clear(bool clear_invalid_ranges=false)
Definition Memory.cpp:32
size_t Read(lldb::addr_t addr, void *dst, size_t dst_len, Status &error)
Definition Memory.cpp:168
void AddInvalidRange(lldb::addr_t base_addr, lldb::addr_t byte_size)
Definition Memory.cpp:101
lldb::DataBufferSP GetL2CacheLine(lldb::addr_t addr, Status &error)
Definition Memory.cpp:140
Range< lldb::addr_t, lldb::addr_t > AddrRange
Definition Memory.h:49
uint32_t m_L2_cache_line_byte_size
Definition Memory.h:59
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