blob: b3540a4fc71bdf1f93ac322d9aadc1d927296c98 [file] [log] [blame]
Greg Claytond495c532011-05-17 03:37:42 +00001//===-- Memory.cpp ----------------------------------------------*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Greg Claytond495c532011-05-17 03:37:42 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "lldb/Target/Memory.h"
Virgile Belloffeba252014-03-08 17:15:35 +000010#include <inttypes.h>
Greg Clayton358cf1e2015-06-25 21:46:34 +000011#include "lldb/Core/RangeMap.h"
Greg Claytond495c532011-05-17 03:37:42 +000012#include "lldb/Target/Process.h"
Zachary Turner666cc0b2017-03-04 01:30:05 +000013#include "lldb/Utility/DataBufferHeap.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000014#include "lldb/Utility/Log.h"
Pavel Labathd821c992018-08-07 11:07:21 +000015#include "lldb/Utility/State.h"
Greg Claytond495c532011-05-17 03:37:42 +000016
17using namespace lldb;
18using namespace lldb_private;
19
20//----------------------------------------------------------------------
21// MemoryCache constructor
22//----------------------------------------------------------------------
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +000023MemoryCache::MemoryCache(Process &process)
Kate Stoneb9c1b512016-09-06 20:57:50 +000024 : m_mutex(), m_L1_cache(), m_L2_cache(), m_invalid_ranges(),
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +000025 m_process(process),
Kate Stoneb9c1b512016-09-06 20:57:50 +000026 m_L2_cache_line_byte_size(process.GetMemoryCacheLineSize()) {}
Greg Claytond495c532011-05-17 03:37:42 +000027
28//----------------------------------------------------------------------
29// Destructor
30//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +000031MemoryCache::~MemoryCache() {}
32
33void MemoryCache::Clear(bool clear_invalid_ranges) {
34 std::lock_guard<std::recursive_mutex> guard(m_mutex);
35 m_L1_cache.clear();
36 m_L2_cache.clear();
37 if (clear_invalid_ranges)
38 m_invalid_ranges.Clear();
39 m_L2_cache_line_byte_size = m_process.GetMemoryCacheLineSize();
Greg Claytond495c532011-05-17 03:37:42 +000040}
41
Kate Stoneb9c1b512016-09-06 20:57:50 +000042void MemoryCache::AddL1CacheData(lldb::addr_t addr, const void *src,
43 size_t src_len) {
44 AddL1CacheData(
45 addr, DataBufferSP(new DataBufferHeap(DataBufferHeap(src, src_len))));
46}
47
48void MemoryCache::AddL1CacheData(lldb::addr_t addr,
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
102void MemoryCache::AddInvalidRange(lldb::addr_t base_addr,
103 lldb::addr_t byte_size) {
104 if (byte_size > 0) {
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +0000105 std::lock_guard<std::recursive_mutex> guard(m_mutex);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000106 InvalidRanges::Entry range(base_addr, byte_size);
107 m_invalid_ranges.Append(range);
108 m_invalid_ranges.Sort();
109 }
Greg Clayton358cf1e2015-06-25 21:46:34 +0000110}
111
Kate Stoneb9c1b512016-09-06 20:57:50 +0000112bool MemoryCache::RemoveInvalidRange(lldb::addr_t base_addr,
113 lldb::addr_t byte_size) {
114 if (byte_size > 0) {
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +0000115 std::lock_guard<std::recursive_mutex> guard(m_mutex);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000116 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.RemoveEntrtAtIndex(idx);
122 }
123 }
124 return false;
Greg Claytond495c532011-05-17 03:37:42 +0000125}
126
Zachary Turner97206d52017-05-12 04:51:55 +0000127size_t MemoryCache::Read(addr_t addr, void *dst, size_t dst_len,
128 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000129 size_t bytes_left = dst_len;
Greg Claytonde0e9d02012-04-13 20:37:20 +0000130
Adrian Prantl05097242018-04-30 16:49:04 +0000131 // Check the L1 cache for a range that contain the entire memory read. If we
132 // find a range in the L1 cache that does, we use it. Else we fall back to
133 // reading memory in m_L2_cache_line_byte_size byte sized chunks. The L1
134 // cache contains chunks of memory that are not required to be
135 // m_L2_cache_line_byte_size bytes in size, so we don't try anything tricky
136 // when reading from them (no partial reads from the L1 cache).
Greg Claytonde0e9d02012-04-13 20:37:20 +0000137
Kate Stoneb9c1b512016-09-06 20:57:50 +0000138 std::lock_guard<std::recursive_mutex> guard(m_mutex);
139 if (!m_L1_cache.empty()) {
140 AddrRange read_range(addr, dst_len);
141 BlockMap::iterator pos = m_L1_cache.upper_bound(addr);
142 if (pos != m_L1_cache.begin()) {
143 --pos;
Greg Clayton358cf1e2015-06-25 21:46:34 +0000144 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000145 AddrRange chunk_range(pos->first, pos->second->GetByteSize());
146 if (chunk_range.Contains(read_range)) {
147 memcpy(dst, pos->second->GetBytes() + addr - chunk_range.GetRangeBase(),
148 dst_len);
149 return dst_len;
Greg Claytond495c532011-05-17 03:37:42 +0000150 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000151 }
152
Adrian Prantl05097242018-04-30 16:49:04 +0000153 // If this memory read request is larger than the cache line size, then we
154 // (1) try to read as much of it at once as possible, and (2) don't add the
155 // data to the memory cache. We don't want to split a big read up into more
156 // separate reads than necessary, and with a large memory read request, it is
157 // unlikely that the caller function will ask for the next
Kate Stoneb9c1b512016-09-06 20:57:50 +0000158 // 4 bytes after the large memory read - so there's little benefit to saving
159 // it in the cache.
160 if (dst && dst_len > m_L2_cache_line_byte_size) {
161 size_t bytes_read =
162 m_process.ReadMemoryFromInferior(addr, dst, dst_len, error);
163 // Add this non block sized range to the L1 cache if we actually read
164 // anything
165 if (bytes_read > 0)
166 AddL1CacheData(addr, dst, bytes_read);
167 return bytes_read;
168 }
169
170 if (dst && bytes_left > 0) {
171 const uint32_t cache_line_byte_size = m_L2_cache_line_byte_size;
172 uint8_t *dst_buf = (uint8_t *)dst;
173 addr_t curr_addr = addr - (addr % cache_line_byte_size);
174 addr_t cache_offset = addr - curr_addr;
175
176 while (bytes_left > 0) {
177 if (m_invalid_ranges.FindEntryThatContains(curr_addr)) {
178 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64,
179 curr_addr);
180 return dst_len - bytes_left;
181 }
182
183 BlockMap::const_iterator pos = m_L2_cache.find(curr_addr);
184 BlockMap::const_iterator end = m_L2_cache.end();
185
186 if (pos != end) {
187 size_t curr_read_size = cache_line_byte_size - cache_offset;
188 if (curr_read_size > bytes_left)
189 curr_read_size = bytes_left;
190
191 memcpy(dst_buf + dst_len - bytes_left,
192 pos->second->GetBytes() + cache_offset, curr_read_size);
193
194 bytes_left -= curr_read_size;
195 curr_addr += curr_read_size + cache_offset;
196 cache_offset = 0;
197
198 if (bytes_left > 0) {
199 // Get sequential cache page hits
200 for (++pos; (pos != end) && (bytes_left > 0); ++pos) {
201 assert((curr_addr % cache_line_byte_size) == 0);
202
203 if (pos->first != curr_addr)
204 break;
205
206 curr_read_size = pos->second->GetByteSize();
207 if (curr_read_size > bytes_left)
208 curr_read_size = bytes_left;
209
210 memcpy(dst_buf + dst_len - bytes_left, pos->second->GetBytes(),
211 curr_read_size);
212
213 bytes_left -= curr_read_size;
214 curr_addr += curr_read_size;
215
Adrian Prantl05097242018-04-30 16:49:04 +0000216 // We have a cache page that succeeded to read some bytes but not
217 // an entire page. If this happens, we must cap off how much data
218 // we are able to read...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000219 if (pos->second->GetByteSize() != cache_line_byte_size)
220 return dst_len - bytes_left;
221 }
222 }
223 }
224
225 // We need to read from the process
226
227 if (bytes_left > 0) {
228 assert((curr_addr % cache_line_byte_size) == 0);
229 std::unique_ptr<DataBufferHeap> data_buffer_heap_ap(
230 new DataBufferHeap(cache_line_byte_size, 0));
231 size_t process_bytes_read = m_process.ReadMemoryFromInferior(
232 curr_addr, data_buffer_heap_ap->GetBytes(),
233 data_buffer_heap_ap->GetByteSize(), error);
234 if (process_bytes_read == 0)
235 return dst_len - bytes_left;
236
237 if (process_bytes_read != cache_line_byte_size)
238 data_buffer_heap_ap->SetByteSize(process_bytes_read);
239 m_L2_cache[curr_addr] = DataBufferSP(data_buffer_heap_ap.release());
240 // We have read data and put it into the cache, continue through the
241 // loop again to get the data out of the cache...
242 }
243 }
244 }
245
246 return dst_len - bytes_left;
Greg Claytond495c532011-05-17 03:37:42 +0000247}
248
Kate Stoneb9c1b512016-09-06 20:57:50 +0000249AllocatedBlock::AllocatedBlock(lldb::addr_t addr, uint32_t byte_size,
250 uint32_t permissions, uint32_t chunk_size)
Greg Claytonac7c2ef2017-02-09 17:56:55 +0000251 : m_range(addr, byte_size), m_permissions(permissions),
252 m_chunk_size(chunk_size)
Greg Claytond495c532011-05-17 03:37:42 +0000253{
Greg Claytonac7c2ef2017-02-09 17:56:55 +0000254 // The entire address range is free to start with.
255 m_free_blocks.Append(m_range);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000256 assert(byte_size > chunk_size);
Greg Claytond495c532011-05-17 03:37:42 +0000257}
258
Kate Stoneb9c1b512016-09-06 20:57:50 +0000259AllocatedBlock::~AllocatedBlock() {}
Greg Claytond495c532011-05-17 03:37:42 +0000260
Kate Stoneb9c1b512016-09-06 20:57:50 +0000261lldb::addr_t AllocatedBlock::ReserveBlock(uint32_t size) {
Greg Clayton98f9bcc2017-02-22 23:42:55 +0000262 // We must return something valid for zero bytes.
263 if (size == 0)
264 size = 1;
Pavel Labath3b7e1982017-02-05 00:44:54 +0000265 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Greg Claytonac7c2ef2017-02-09 17:56:55 +0000266
267 const size_t free_count = m_free_blocks.GetSize();
268 for (size_t i=0; i<free_count; ++i)
269 {
Greg Clayton21b4b2e2017-02-09 18:21:04 +0000270 auto &free_block = m_free_blocks.GetEntryRef(i);
Greg Claytonac7c2ef2017-02-09 17:56:55 +0000271 const lldb::addr_t range_size = free_block.GetByteSize();
272 if (range_size >= size)
273 {
274 // We found a free block that is big enough for our data. Figure out how
Adrian Prantl05097242018-04-30 16:49:04 +0000275 // many chunks we will need and calculate the resulting block size we
276 // will reserve.
Greg Clayton98f9bcc2017-02-22 23:42:55 +0000277 addr_t addr = free_block.GetRangeBase();
Greg Claytonac7c2ef2017-02-09 17:56:55 +0000278 size_t num_chunks = CalculateChunksNeededForSize(size);
279 lldb::addr_t block_size = num_chunks * m_chunk_size;
280 lldb::addr_t bytes_left = range_size - block_size;
281 if (bytes_left == 0)
282 {
283 // The newly allocated block will take all of the bytes in this
284 // available block, so we can just add it to the allocated ranges and
285 // remove the range from the free ranges.
286 m_reserved_blocks.Insert(free_block, false);
287 m_free_blocks.RemoveEntryAtIndex(i);
288 }
289 else
290 {
291 // Make the new allocated range and add it to the allocated ranges.
Greg Clayton21b4b2e2017-02-09 18:21:04 +0000292 Range<lldb::addr_t, uint32_t> reserved_block(free_block);
Greg Claytonac7c2ef2017-02-09 17:56:55 +0000293 reserved_block.SetByteSize(block_size);
Adrian Prantl05097242018-04-30 16:49:04 +0000294 // Insert the reserved range and don't combine it with other blocks in
295 // the reserved blocks list.
Greg Claytonac7c2ef2017-02-09 17:56:55 +0000296 m_reserved_blocks.Insert(reserved_block, false);
297 // Adjust the free range in place since we won't change the sorted
298 // ordering of the m_free_blocks list.
299 free_block.SetRangeBase(reserved_block.GetRangeEnd());
300 free_block.SetByteSize(bytes_left);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000301 }
Greg Clayton98f9bcc2017-02-22 23:42:55 +0000302 LLDB_LOGV(log, "({0}) (size = {1} ({1:x})) => {2:x}", this, size, addr);
303 return addr;
Greg Claytond495c532011-05-17 03:37:42 +0000304 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000305 }
Jim Inghame7701fe2014-08-08 20:01:41 +0000306
Greg Clayton98f9bcc2017-02-22 23:42:55 +0000307 LLDB_LOGV(log, "({0}) (size = {1} ({1:x})) => {2:x}", this, size,
308 LLDB_INVALID_ADDRESS);
309 return LLDB_INVALID_ADDRESS;
Greg Claytond495c532011-05-17 03:37:42 +0000310}
311
Kate Stoneb9c1b512016-09-06 20:57:50 +0000312bool AllocatedBlock::FreeBlock(addr_t addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000313 bool success = false;
Greg Claytonac7c2ef2017-02-09 17:56:55 +0000314 auto entry_idx = m_reserved_blocks.FindEntryIndexThatContains(addr);
315 if (entry_idx != UINT32_MAX)
316 {
317 m_free_blocks.Insert(m_reserved_blocks.GetEntryRef(entry_idx), true);
318 m_reserved_blocks.RemoveEntryAtIndex(entry_idx);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000319 success = true;
320 }
Pavel Labath3b7e1982017-02-05 00:44:54 +0000321 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Greg Claytonac7c2ef2017-02-09 17:56:55 +0000322 LLDB_LOGV(log, "({0}) (addr = {1:x}) => {2}", this, addr, success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000323 return success;
Greg Claytond495c532011-05-17 03:37:42 +0000324}
325
Kate Stoneb9c1b512016-09-06 20:57:50 +0000326AllocatedMemoryCache::AllocatedMemoryCache(Process &process)
327 : m_process(process), m_mutex(), m_memory_map() {}
328
329AllocatedMemoryCache::~AllocatedMemoryCache() {}
330
331void AllocatedMemoryCache::Clear() {
332 std::lock_guard<std::recursive_mutex> guard(m_mutex);
333 if (m_process.IsAlive()) {
334 PermissionsToBlockMap::iterator pos, end = m_memory_map.end();
335 for (pos = m_memory_map.begin(); pos != end; ++pos)
336 m_process.DoDeallocateMemory(pos->second->GetBaseAddress());
337 }
338 m_memory_map.clear();
Greg Claytond495c532011-05-17 03:37:42 +0000339}
340
Greg Claytond495c532011-05-17 03:37:42 +0000341AllocatedMemoryCache::AllocatedBlockSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000342AllocatedMemoryCache::AllocatePage(uint32_t byte_size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +0000343 uint32_t chunk_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000344 AllocatedBlockSP block_sp;
345 const size_t page_size = 4096;
346 const size_t num_pages = (byte_size + page_size - 1) / page_size;
347 const size_t page_byte_size = num_pages * page_size;
Greg Claytond495c532011-05-17 03:37:42 +0000348
Kate Stoneb9c1b512016-09-06 20:57:50 +0000349 addr_t addr = m_process.DoAllocateMemory(page_byte_size, permissions, error);
Greg Claytond495c532011-05-17 03:37:42 +0000350
Kate Stoneb9c1b512016-09-06 20:57:50 +0000351 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
352 if (log) {
353 log->Printf("Process::DoAllocateMemory (byte_size = 0x%8.8" PRIx32
354 ", permissions = %s) => 0x%16.16" PRIx64,
355 (uint32_t)page_byte_size, GetPermissionsAsCString(permissions),
356 (uint64_t)addr);
357 }
Greg Claytond495c532011-05-17 03:37:42 +0000358
Kate Stoneb9c1b512016-09-06 20:57:50 +0000359 if (addr != LLDB_INVALID_ADDRESS) {
360 block_sp.reset(
361 new AllocatedBlock(addr, page_byte_size, permissions, chunk_size));
362 m_memory_map.insert(std::make_pair(permissions, block_sp));
363 }
364 return block_sp;
365}
366
367lldb::addr_t AllocatedMemoryCache::AllocateMemory(size_t byte_size,
368 uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +0000369 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000370 std::lock_guard<std::recursive_mutex> guard(m_mutex);
371
372 addr_t addr = LLDB_INVALID_ADDRESS;
373 std::pair<PermissionsToBlockMap::iterator, PermissionsToBlockMap::iterator>
374 range = m_memory_map.equal_range(permissions);
375
376 for (PermissionsToBlockMap::iterator pos = range.first; pos != range.second;
377 ++pos) {
378 addr = (*pos).second->ReserveBlock(byte_size);
Greg Claytond495c532011-05-17 03:37:42 +0000379 if (addr != LLDB_INVALID_ADDRESS)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000380 break;
381 }
382
383 if (addr == LLDB_INVALID_ADDRESS) {
384 AllocatedBlockSP block_sp(AllocatePage(byte_size, permissions, 16, error));
385
386 if (block_sp)
387 addr = block_sp->ReserveBlock(byte_size);
388 }
389 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
390 if (log)
391 log->Printf(
392 "AllocatedMemoryCache::AllocateMemory (byte_size = 0x%8.8" PRIx32
393 ", permissions = %s) => 0x%16.16" PRIx64,
394 (uint32_t)byte_size, GetPermissionsAsCString(permissions),
395 (uint64_t)addr);
396 return addr;
Greg Claytond495c532011-05-17 03:37:42 +0000397}
398
Kate Stoneb9c1b512016-09-06 20:57:50 +0000399bool AllocatedMemoryCache::DeallocateMemory(lldb::addr_t addr) {
400 std::lock_guard<std::recursive_mutex> guard(m_mutex);
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +0000401
Kate Stoneb9c1b512016-09-06 20:57:50 +0000402 PermissionsToBlockMap::iterator pos, end = m_memory_map.end();
403 bool success = false;
404 for (pos = m_memory_map.begin(); pos != end; ++pos) {
405 if (pos->second->Contains(addr)) {
406 success = pos->second->FreeBlock(addr);
407 break;
Greg Claytond495c532011-05-17 03:37:42 +0000408 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000409 }
410 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
411 if (log)
412 log->Printf("AllocatedMemoryCache::DeallocateMemory (addr = 0x%16.16" PRIx64
413 ") => %i",
414 (uint64_t)addr, success);
415 return success;
Greg Claytond495c532011-05-17 03:37:42 +0000416}