LLDB  mainline
Memory.cpp
Go to the documentation of this file.
1 //===-- Memory.cpp ----------------------------------------------*- C++ -*-===//
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 
9 #include "lldb/Target/Memory.h"
10 #include "lldb/Target/Process.h"
12 #include "lldb/Utility/Log.h"
13 #include "lldb/Utility/RangeMap.h"
14 #include "lldb/Utility/State.h"
15 
16 #include <cinttypes>
17 #include <memory>
18 
19 using namespace lldb;
20 using namespace lldb_private;
21 
22 // MemoryCache constructor
23 MemoryCache::MemoryCache(Process &process)
24  : m_mutex(), m_L1_cache(), m_L2_cache(), m_invalid_ranges(),
25  m_process(process),
26  m_L2_cache_line_byte_size(process.GetMemoryCacheLineSize()) {}
27 
28 // Destructor
30 
31 void MemoryCache::Clear(bool clear_invalid_ranges) {
32  std::lock_guard<std::recursive_mutex> guard(m_mutex);
33  m_L1_cache.clear();
34  m_L2_cache.clear();
35  if (clear_invalid_ranges)
38 }
39 
40 void MemoryCache::AddL1CacheData(lldb::addr_t addr, const void *src,
41  size_t src_len) {
43  addr, DataBufferSP(new DataBufferHeap(DataBufferHeap(src, src_len))));
44 }
45 
47  const DataBufferSP &data_buffer_sp) {
48  std::lock_guard<std::recursive_mutex> guard(m_mutex);
49  m_L1_cache[addr] = data_buffer_sp;
50 }
51 
52 void MemoryCache::Flush(addr_t addr, size_t size) {
53  if (size == 0)
54  return;
55 
56  std::lock_guard<std::recursive_mutex> guard(m_mutex);
57 
58  // Erase any blocks from the L1 cache that intersect with the flush range
59  if (!m_L1_cache.empty()) {
60  AddrRange flush_range(addr, size);
61  BlockMap::iterator pos = m_L1_cache.upper_bound(addr);
62  if (pos != m_L1_cache.begin()) {
63  --pos;
64  }
65  while (pos != m_L1_cache.end()) {
66  AddrRange chunk_range(pos->first, pos->second->GetByteSize());
67  if (!chunk_range.DoesIntersect(flush_range))
68  break;
69  pos = m_L1_cache.erase(pos);
70  }
71  }
72 
73  if (!m_L2_cache.empty()) {
74  const uint32_t cache_line_byte_size = m_L2_cache_line_byte_size;
75  const addr_t end_addr = (addr + size - 1);
76  const addr_t first_cache_line_addr = addr - (addr % cache_line_byte_size);
77  const addr_t last_cache_line_addr =
78  end_addr - (end_addr % cache_line_byte_size);
79  // Watch for overflow where size will cause us to go off the end of the
80  // 64 bit address space
81  uint32_t num_cache_lines;
82  if (last_cache_line_addr >= first_cache_line_addr)
83  num_cache_lines = ((last_cache_line_addr - first_cache_line_addr) /
84  cache_line_byte_size) +
85  1;
86  else
87  num_cache_lines =
88  (UINT64_MAX - first_cache_line_addr + 1) / cache_line_byte_size;
89 
90  uint32_t cache_idx = 0;
91  for (addr_t curr_addr = first_cache_line_addr; cache_idx < num_cache_lines;
92  curr_addr += cache_line_byte_size, ++cache_idx) {
93  BlockMap::iterator pos = m_L2_cache.find(curr_addr);
94  if (pos != m_L2_cache.end())
95  m_L2_cache.erase(pos);
96  }
97  }
98 }
99 
101  lldb::addr_t byte_size) {
102  if (byte_size > 0) {
103  std::lock_guard<std::recursive_mutex> guard(m_mutex);
104  InvalidRanges::Entry range(base_addr, byte_size);
105  m_invalid_ranges.Append(range);
107  }
108 }
109 
111  lldb::addr_t byte_size) {
112  if (byte_size > 0) {
113  std::lock_guard<std::recursive_mutex> guard(m_mutex);
115  if (idx != UINT32_MAX) {
117  if (entry->GetRangeBase() == base_addr &&
118  entry->GetByteSize() == byte_size)
120  }
121  }
122  return false;
123 }
124 
125 size_t MemoryCache::Read(addr_t addr, void *dst, size_t dst_len,
126  Status &error) {
127  size_t bytes_left = dst_len;
128 
129  // Check the L1 cache for a range that contain the entire memory read. If we
130  // find a range in the L1 cache that does, we use it. Else we fall back to
131  // reading memory in m_L2_cache_line_byte_size byte sized chunks. The L1
132  // cache contains chunks of memory that are not required to be
133  // m_L2_cache_line_byte_size bytes in size, so we don't try anything tricky
134  // when reading from them (no partial reads from the L1 cache).
135 
136  std::lock_guard<std::recursive_mutex> guard(m_mutex);
137  if (!m_L1_cache.empty()) {
138  AddrRange read_range(addr, dst_len);
139  BlockMap::iterator pos = m_L1_cache.upper_bound(addr);
140  if (pos != m_L1_cache.begin()) {
141  --pos;
142  }
143  AddrRange chunk_range(pos->first, pos->second->GetByteSize());
144  if (chunk_range.Contains(read_range)) {
145  memcpy(dst, pos->second->GetBytes() + (addr - chunk_range.GetRangeBase()),
146  dst_len);
147  return dst_len;
148  }
149  }
150 
151  // If this memory read request is larger than the cache line size, then we
152  // (1) try to read as much of it at once as possible, and (2) don't add the
153  // data to the memory cache. We don't want to split a big read up into more
154  // separate reads than necessary, and with a large memory read request, it is
155  // unlikely that the caller function will ask for the next
156  // 4 bytes after the large memory read - so there's little benefit to saving
157  // it in the cache.
158  if (dst && dst_len > m_L2_cache_line_byte_size) {
159  size_t bytes_read =
160  m_process.ReadMemoryFromInferior(addr, dst, dst_len, error);
161  // Add this non block sized range to the L1 cache if we actually read
162  // anything
163  if (bytes_read > 0)
164  AddL1CacheData(addr, dst, bytes_read);
165  return bytes_read;
166  }
167 
168  if (dst && bytes_left > 0) {
169  const uint32_t cache_line_byte_size = m_L2_cache_line_byte_size;
170  uint8_t *dst_buf = (uint8_t *)dst;
171  addr_t curr_addr = addr - (addr % cache_line_byte_size);
172  addr_t cache_offset = addr - curr_addr;
173 
174  while (bytes_left > 0) {
175  if (m_invalid_ranges.FindEntryThatContains(curr_addr)) {
176  error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64,
177  curr_addr);
178  return dst_len - bytes_left;
179  }
180 
181  BlockMap::const_iterator pos = m_L2_cache.find(curr_addr);
182  BlockMap::const_iterator end = m_L2_cache.end();
183 
184  if (pos != end) {
185  size_t curr_read_size = cache_line_byte_size - cache_offset;
186  if (curr_read_size > bytes_left)
187  curr_read_size = bytes_left;
188 
189  memcpy(dst_buf + dst_len - bytes_left,
190  pos->second->GetBytes() + cache_offset, curr_read_size);
191 
192  bytes_left -= curr_read_size;
193  curr_addr += curr_read_size + cache_offset;
194  cache_offset = 0;
195 
196  if (bytes_left > 0) {
197  // Get sequential cache page hits
198  for (++pos; (pos != end) && (bytes_left > 0); ++pos) {
199  assert((curr_addr % cache_line_byte_size) == 0);
200 
201  if (pos->first != curr_addr)
202  break;
203 
204  curr_read_size = pos->second->GetByteSize();
205  if (curr_read_size > bytes_left)
206  curr_read_size = bytes_left;
207 
208  memcpy(dst_buf + dst_len - bytes_left, pos->second->GetBytes(),
209  curr_read_size);
210 
211  bytes_left -= curr_read_size;
212  curr_addr += curr_read_size;
213 
214  // We have a cache page that succeeded to read some bytes but not
215  // an entire page. If this happens, we must cap off how much data
216  // we are able to read...
217  if (pos->second->GetByteSize() != cache_line_byte_size)
218  return dst_len - bytes_left;
219  }
220  }
221  }
222 
223  // We need to read from the process
224 
225  if (bytes_left > 0) {
226  assert((curr_addr % cache_line_byte_size) == 0);
227  std::unique_ptr<DataBufferHeap> data_buffer_heap_up(
228  new DataBufferHeap(cache_line_byte_size, 0));
229  size_t process_bytes_read = m_process.ReadMemoryFromInferior(
230  curr_addr, data_buffer_heap_up->GetBytes(),
231  data_buffer_heap_up->GetByteSize(), error);
232  if (process_bytes_read == 0)
233  return dst_len - bytes_left;
234 
235  if (process_bytes_read != cache_line_byte_size)
236  data_buffer_heap_up->SetByteSize(process_bytes_read);
237  m_L2_cache[curr_addr] = DataBufferSP(data_buffer_heap_up.release());
238  // We have read data and put it into the cache, continue through the
239  // loop again to get the data out of the cache...
240  }
241  }
242  }
243 
244  return dst_len - bytes_left;
245 }
246 
248  uint32_t permissions, uint32_t chunk_size)
249  : m_range(addr, byte_size), m_permissions(permissions),
250  m_chunk_size(chunk_size)
251 {
252  // The entire address range is free to start with.
254  assert(byte_size > chunk_size);
255 }
256 
258 
260  // We must return something valid for zero bytes.
261  if (size == 0)
262  size = 1;
264 
265  const size_t free_count = m_free_blocks.GetSize();
266  for (size_t i=0; i<free_count; ++i)
267  {
268  auto &free_block = m_free_blocks.GetEntryRef(i);
269  const lldb::addr_t range_size = free_block.GetByteSize();
270  if (range_size >= size)
271  {
272  // We found a free block that is big enough for our data. Figure out how
273  // many chunks we will need and calculate the resulting block size we
274  // will reserve.
275  addr_t addr = free_block.GetRangeBase();
276  size_t num_chunks = CalculateChunksNeededForSize(size);
277  lldb::addr_t block_size = num_chunks * m_chunk_size;
278  lldb::addr_t bytes_left = range_size - block_size;
279  if (bytes_left == 0)
280  {
281  // The newly allocated block will take all of the bytes in this
282  // available block, so we can just add it to the allocated ranges and
283  // remove the range from the free ranges.
284  m_reserved_blocks.Insert(free_block, false);
286  }
287  else
288  {
289  // Make the new allocated range and add it to the allocated ranges.
290  Range<lldb::addr_t, uint32_t> reserved_block(free_block);
291  reserved_block.SetByteSize(block_size);
292  // Insert the reserved range and don't combine it with other blocks in
293  // the reserved blocks list.
294  m_reserved_blocks.Insert(reserved_block, false);
295  // Adjust the free range in place since we won't change the sorted
296  // ordering of the m_free_blocks list.
297  free_block.SetRangeBase(reserved_block.GetRangeEnd());
298  free_block.SetByteSize(bytes_left);
299  }
300  LLDB_LOGV(log, "({0}) (size = {1} ({1:x})) => {2:x}", this, size, addr);
301  return addr;
302  }
303  }
304 
305  LLDB_LOGV(log, "({0}) (size = {1} ({1:x})) => {2:x}", this, size,
307  return LLDB_INVALID_ADDRESS;
308 }
309 
311  bool success = false;
312  auto entry_idx = m_reserved_blocks.FindEntryIndexThatContains(addr);
313  if (entry_idx != UINT32_MAX)
314  {
317  success = true;
318  }
320  LLDB_LOGV(log, "({0}) (addr = {1:x}) => {2}", this, addr, success);
321  return success;
322 }
323 
325  : m_process(process), m_mutex(), m_memory_map() {}
326 
328 
330  std::lock_guard<std::recursive_mutex> guard(m_mutex);
331  if (m_process.IsAlive()) {
332  PermissionsToBlockMap::iterator pos, end = m_memory_map.end();
333  for (pos = m_memory_map.begin(); pos != end; ++pos)
334  m_process.DoDeallocateMemory(pos->second->GetBaseAddress());
335  }
336  m_memory_map.clear();
337 }
338 
341  uint32_t chunk_size, Status &error) {
342  AllocatedBlockSP block_sp;
343  const size_t page_size = 4096;
344  const size_t num_pages = (byte_size + page_size - 1) / page_size;
345  const size_t page_byte_size = num_pages * page_size;
346 
347  addr_t addr = m_process.DoAllocateMemory(page_byte_size, permissions, error);
348 
350  if (log) {
351  log->Printf("Process::DoAllocateMemory (byte_size = 0x%8.8" PRIx32
352  ", permissions = %s) => 0x%16.16" PRIx64,
353  (uint32_t)page_byte_size, GetPermissionsAsCString(permissions),
354  (uint64_t)addr);
355  }
356 
357  if (addr != LLDB_INVALID_ADDRESS) {
358  block_sp = std::make_shared<AllocatedBlock>(addr, page_byte_size,
359  permissions, chunk_size);
360  m_memory_map.insert(std::make_pair(permissions, block_sp));
361  }
362  return block_sp;
363 }
364 
366  uint32_t permissions,
367  Status &error) {
368  std::lock_guard<std::recursive_mutex> guard(m_mutex);
369 
371  std::pair<PermissionsToBlockMap::iterator, PermissionsToBlockMap::iterator>
372  range = m_memory_map.equal_range(permissions);
373 
374  for (PermissionsToBlockMap::iterator pos = range.first; pos != range.second;
375  ++pos) {
376  addr = (*pos).second->ReserveBlock(byte_size);
377  if (addr != LLDB_INVALID_ADDRESS)
378  break;
379  }
380 
381  if (addr == LLDB_INVALID_ADDRESS) {
382  AllocatedBlockSP block_sp(AllocatePage(byte_size, permissions, 16, error));
383 
384  if (block_sp)
385  addr = block_sp->ReserveBlock(byte_size);
386  }
388  if (log)
389  log->Printf(
390  "AllocatedMemoryCache::AllocateMemory (byte_size = 0x%8.8" PRIx32
391  ", permissions = %s) => 0x%16.16" PRIx64,
392  (uint32_t)byte_size, GetPermissionsAsCString(permissions),
393  (uint64_t)addr);
394  return addr;
395 }
396 
398  std::lock_guard<std::recursive_mutex> guard(m_mutex);
399 
400  PermissionsToBlockMap::iterator pos, end = m_memory_map.end();
401  bool success = false;
402  for (pos = m_memory_map.begin(); pos != end; ++pos) {
403  if (pos->second->Contains(addr)) {
404  success = pos->second->FreeBlock(addr);
405  break;
406  }
407  }
409  if (log)
410  log->Printf("AllocatedMemoryCache::DeallocateMemory (addr = 0x%16.16" PRIx64
411  ") => %i",
412  (uint64_t)addr, success);
413  return success;
414 }
AllocatedBlock(lldb::addr_t addr, uint32_t byte_size, uint32_t permissions, uint32_t chunk_size)
Definition: Memory.cpp:247
RangeVector< lldb::addr_t, uint32_t > m_free_blocks
Definition: Memory.h:103
bool RemoveInvalidRange(lldb::addr_t base_addr, lldb::addr_t byte_size)
Definition: Memory.cpp:110
size_t ReadMemoryFromInferior(lldb::addr_t vm_addr, void *buf, size_t size, Status &error)
Read of memory from a process.
Definition: Process.cpp:2126
#define LIBLLDB_LOG_PROCESS
Definition: Logging.h:15
Enumerations for broadcasting.
Definition: SBLaunchInfo.h:14
void AddInvalidRange(lldb::addr_t base_addr, lldb::addr_t byte_size)
Definition: Memory.cpp:100
uint32_t CalculateChunksNeededForSize(uint32_t size) const
Definition: Memory.h:93
const uint32_t m_chunk_size
Definition: Memory.h:101
void Flush(lldb::addr_t addr, size_t size)
Definition: Memory.cpp:52
AllocatedBlockSP AllocatePage(uint32_t byte_size, uint32_t permissions, uint32_t chunk_size, Status &error)
Definition: Memory.cpp:340
Entry & GetEntryRef(size_t i)
Definition: RangeMap.h:483
const char * GetPermissionsAsCString(uint32_t permissions)
Definition: State.cpp:44
std::recursive_mutex m_mutex
Definition: Memory.h:51
A subclass of DataBuffer that stores a data buffer on the heap.
uint64_t GetMemoryCacheLineSize() const
Definition: Process.cpp:203
bool RemoveEntryAtIndex(uint32_t idx)
Definition: RangeMap.h:373
#define UINT32_MAX
Definition: lldb-defines.h:31
lldb::addr_t AllocateMemory(size_t byte_size, uint32_t permissions, Status &error)
Definition: Memory.cpp:365
void Clear(bool clear_invalid_ranges=false)
Definition: Memory.cpp:31
#define LLDB_INVALID_ADDRESS
Invalid value definitions.
Definition: lldb-defines.h:85
Log * GetLogIfAllCategoriesSet(uint32_t mask)
Definition: Logging.cpp:57
size_t Read(lldb::addr_t addr, void *dst, size_t dst_len, Status &error)
Definition: Memory.cpp:125
bool RemoveEntrtAtIndex(uint32_t idx)
Definition: RangeMap.h:143
const Entry * GetEntryAtIndex(size_t i) const
Definition: RangeMap.h:243
InvalidRanges m_invalid_ranges
Definition: Memory.h:57
void Insert(const Entry &entry, bool combine)
Definition: RangeMap.h:349
A plug-in interface definition class for debugging a process.
Definition: Process.h:353
const Entry * FindEntryThatContains(B addr) const
Definition: RangeMap.h:283
std::shared_ptr< AllocatedBlock > AllocatedBlockSP
Definition: Memory.h:126
RangeVector< lldb::addr_t, uint32_t > m_reserved_blocks
Definition: Memory.h:105
uint32_t FindEntryIndexThatContains(B addr) const
Definition: RangeMap.h:261
void SetByteSize(SizeType s)
Definition: RangeMap.h:73
bool FreeBlock(lldb::addr_t addr)
Definition: Memory.cpp:310
PermissionsToBlockMap m_memory_map
Definition: Memory.h:135
uint64_t addr_t
Definition: lldb-types.h:83
virtual bool IsAlive()
Check if a process is still alive.
Definition: Process.cpp:1182
Definition: SBAddress.h:15
uint32_t FindEntryIndexThatContains(B addr) const
Definition: RangeMap.h:496
size_t GetSize() const
Definition: RangeMap.h:475
lldb::addr_t ReserveBlock(uint32_t size)
Definition: Memory.cpp:259
virtual Status DoDeallocateMemory(lldb::addr_t ptr)
Actually deallocate memory in the process.
Definition: Process.h:1865
bool DeallocateMemory(lldb::addr_t ptr)
Definition: Memory.cpp:397
Range< lldb::addr_t, uint32_t > m_range
Definition: Memory.h:97
BaseType GetRangeEnd() const
Definition: RangeMap.h:62
virtual lldb::addr_t DoAllocateMemory(size_t size, uint32_t permissions, Status &error)
Actually allocate memory in the process.
Definition: Process.h:1662
uint32_t m_L2_cache_line_byte_size
Definition: Memory.h:59
int SetErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Set the current error string to a formatted error string.
Definition: Status.cpp:255
void Append(const Entry &entry)
Definition: RangeMap.h:343
void AddL1CacheData(lldb::addr_t addr, const void *src, size_t src_len)
Definition: Memory.cpp:40
SizeType GetByteSize() const
Definition: RangeMap.h:71
std::recursive_mutex m_mutex
Definition: Memory.h:133
#define UINT64_MAX
Definition: lldb-defines.h:35
AllocatedMemoryCache(Process &process)
Definition: Memory.cpp:324
void Printf(const char *format,...) __attribute__((format(printf
Definition: Log.cpp:113
#define LLDB_LOGV(log,...)
Definition: Log.h:216
void Append(const Entry &entry)
Definition: RangeMap.h:139
An error handling class.
Definition: Status.h:44
BaseType GetRangeBase() const
Definition: RangeMap.h:46