blob: c0597b687b9ea2d720f1e0a4d7ee00b5c234cc6f [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"
Jonas Devlieghere796ac802019-02-11 23:13:08 +000010
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
Jonas Devlieghere796ac802019-02-11 23:13:08 +000017#include <cinttypes>
18#include <memory>
19
Greg Claytond495c532011-05-17 03:37:42 +000020using namespace lldb;
21using namespace lldb_private;
22
23//----------------------------------------------------------------------
24// MemoryCache constructor
25//----------------------------------------------------------------------
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +000026MemoryCache::MemoryCache(Process &process)
Kate Stoneb9c1b512016-09-06 20:57:50 +000027 : m_mutex(), m_L1_cache(), m_L2_cache(), m_invalid_ranges(),
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +000028 m_process(process),
Kate Stoneb9c1b512016-09-06 20:57:50 +000029 m_L2_cache_line_byte_size(process.GetMemoryCacheLineSize()) {}
Greg Claytond495c532011-05-17 03:37:42 +000030
31//----------------------------------------------------------------------
32// Destructor
33//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +000034MemoryCache::~MemoryCache() {}
35
36void MemoryCache::Clear(bool clear_invalid_ranges) {
37 std::lock_guard<std::recursive_mutex> guard(m_mutex);
38 m_L1_cache.clear();
39 m_L2_cache.clear();
40 if (clear_invalid_ranges)
41 m_invalid_ranges.Clear();
42 m_L2_cache_line_byte_size = m_process.GetMemoryCacheLineSize();
Greg Claytond495c532011-05-17 03:37:42 +000043}
44
Kate Stoneb9c1b512016-09-06 20:57:50 +000045void MemoryCache::AddL1CacheData(lldb::addr_t addr, const void *src,
46 size_t src_len) {
47 AddL1CacheData(
48 addr, DataBufferSP(new DataBufferHeap(DataBufferHeap(src, src_len))));
49}
50
51void MemoryCache::AddL1CacheData(lldb::addr_t addr,
52 const DataBufferSP &data_buffer_sp) {
53 std::lock_guard<std::recursive_mutex> guard(m_mutex);
54 m_L1_cache[addr] = data_buffer_sp;
55}
56
57void MemoryCache::Flush(addr_t addr, size_t size) {
58 if (size == 0)
59 return;
60
61 std::lock_guard<std::recursive_mutex> guard(m_mutex);
62
63 // Erase any blocks from the L1 cache that intersect with the flush range
64 if (!m_L1_cache.empty()) {
65 AddrRange flush_range(addr, size);
66 BlockMap::iterator pos = m_L1_cache.upper_bound(addr);
67 if (pos != m_L1_cache.begin()) {
68 --pos;
69 }
70 while (pos != m_L1_cache.end()) {
71 AddrRange chunk_range(pos->first, pos->second->GetByteSize());
72 if (!chunk_range.DoesIntersect(flush_range))
73 break;
74 pos = m_L1_cache.erase(pos);
75 }
76 }
77
78 if (!m_L2_cache.empty()) {
79 const uint32_t cache_line_byte_size = m_L2_cache_line_byte_size;
80 const addr_t end_addr = (addr + size - 1);
81 const addr_t first_cache_line_addr = addr - (addr % cache_line_byte_size);
82 const addr_t last_cache_line_addr =
83 end_addr - (end_addr % cache_line_byte_size);
84 // Watch for overflow where size will cause us to go off the end of the
85 // 64 bit address space
86 uint32_t num_cache_lines;
87 if (last_cache_line_addr >= first_cache_line_addr)
88 num_cache_lines = ((last_cache_line_addr - first_cache_line_addr) /
89 cache_line_byte_size) +
90 1;
91 else
92 num_cache_lines =
93 (UINT64_MAX - first_cache_line_addr + 1) / cache_line_byte_size;
94
95 uint32_t cache_idx = 0;
96 for (addr_t curr_addr = first_cache_line_addr; cache_idx < num_cache_lines;
97 curr_addr += cache_line_byte_size, ++cache_idx) {
98 BlockMap::iterator pos = m_L2_cache.find(curr_addr);
99 if (pos != m_L2_cache.end())
100 m_L2_cache.erase(pos);
101 }
102 }
103}
104
105void MemoryCache::AddInvalidRange(lldb::addr_t base_addr,
106 lldb::addr_t byte_size) {
107 if (byte_size > 0) {
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +0000108 std::lock_guard<std::recursive_mutex> guard(m_mutex);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000109 InvalidRanges::Entry range(base_addr, byte_size);
110 m_invalid_ranges.Append(range);
111 m_invalid_ranges.Sort();
112 }
Greg Clayton358cf1e2015-06-25 21:46:34 +0000113}
114
Kate Stoneb9c1b512016-09-06 20:57:50 +0000115bool MemoryCache::RemoveInvalidRange(lldb::addr_t base_addr,
116 lldb::addr_t byte_size) {
117 if (byte_size > 0) {
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +0000118 std::lock_guard<std::recursive_mutex> guard(m_mutex);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000119 const uint32_t idx = m_invalid_ranges.FindEntryIndexThatContains(base_addr);
120 if (idx != UINT32_MAX) {
121 const InvalidRanges::Entry *entry = m_invalid_ranges.GetEntryAtIndex(idx);
122 if (entry->GetRangeBase() == base_addr &&
123 entry->GetByteSize() == byte_size)
124 return m_invalid_ranges.RemoveEntrtAtIndex(idx);
125 }
126 }
127 return false;
Greg Claytond495c532011-05-17 03:37:42 +0000128}
129
Zachary Turner97206d52017-05-12 04:51:55 +0000130size_t MemoryCache::Read(addr_t addr, void *dst, size_t dst_len,
131 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000132 size_t bytes_left = dst_len;
Greg Claytonde0e9d02012-04-13 20:37:20 +0000133
Adrian Prantl05097242018-04-30 16:49:04 +0000134 // Check the L1 cache for a range that contain the entire memory read. If we
135 // find a range in the L1 cache that does, we use it. Else we fall back to
136 // reading memory in m_L2_cache_line_byte_size byte sized chunks. The L1
137 // cache contains chunks of memory that are not required to be
138 // m_L2_cache_line_byte_size bytes in size, so we don't try anything tricky
139 // when reading from them (no partial reads from the L1 cache).
Greg Claytonde0e9d02012-04-13 20:37:20 +0000140
Kate Stoneb9c1b512016-09-06 20:57:50 +0000141 std::lock_guard<std::recursive_mutex> guard(m_mutex);
142 if (!m_L1_cache.empty()) {
143 AddrRange read_range(addr, dst_len);
144 BlockMap::iterator pos = m_L1_cache.upper_bound(addr);
145 if (pos != m_L1_cache.begin()) {
146 --pos;
Greg Clayton358cf1e2015-06-25 21:46:34 +0000147 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000148 AddrRange chunk_range(pos->first, pos->second->GetByteSize());
149 if (chunk_range.Contains(read_range)) {
150 memcpy(dst, pos->second->GetBytes() + addr - chunk_range.GetRangeBase(),
151 dst_len);
152 return dst_len;
Greg Claytond495c532011-05-17 03:37:42 +0000153 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000154 }
155
Adrian Prantl05097242018-04-30 16:49:04 +0000156 // If this memory read request is larger than the cache line size, then we
157 // (1) try to read as much of it at once as possible, and (2) don't add the
158 // data to the memory cache. We don't want to split a big read up into more
159 // separate reads than necessary, and with a large memory read request, it is
160 // unlikely that the caller function will ask for the next
Kate Stoneb9c1b512016-09-06 20:57:50 +0000161 // 4 bytes after the large memory read - so there's little benefit to saving
162 // it in the cache.
163 if (dst && dst_len > m_L2_cache_line_byte_size) {
164 size_t bytes_read =
165 m_process.ReadMemoryFromInferior(addr, dst, dst_len, error);
166 // Add this non block sized range to the L1 cache if we actually read
167 // anything
168 if (bytes_read > 0)
169 AddL1CacheData(addr, dst, bytes_read);
170 return bytes_read;
171 }
172
173 if (dst && bytes_left > 0) {
174 const uint32_t cache_line_byte_size = m_L2_cache_line_byte_size;
175 uint8_t *dst_buf = (uint8_t *)dst;
176 addr_t curr_addr = addr - (addr % cache_line_byte_size);
177 addr_t cache_offset = addr - curr_addr;
178
179 while (bytes_left > 0) {
180 if (m_invalid_ranges.FindEntryThatContains(curr_addr)) {
181 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64,
182 curr_addr);
183 return dst_len - bytes_left;
184 }
185
186 BlockMap::const_iterator pos = m_L2_cache.find(curr_addr);
187 BlockMap::const_iterator end = m_L2_cache.end();
188
189 if (pos != end) {
190 size_t curr_read_size = cache_line_byte_size - cache_offset;
191 if (curr_read_size > bytes_left)
192 curr_read_size = bytes_left;
193
194 memcpy(dst_buf + dst_len - bytes_left,
195 pos->second->GetBytes() + cache_offset, curr_read_size);
196
197 bytes_left -= curr_read_size;
198 curr_addr += curr_read_size + cache_offset;
199 cache_offset = 0;
200
201 if (bytes_left > 0) {
202 // Get sequential cache page hits
203 for (++pos; (pos != end) && (bytes_left > 0); ++pos) {
204 assert((curr_addr % cache_line_byte_size) == 0);
205
206 if (pos->first != curr_addr)
207 break;
208
209 curr_read_size = pos->second->GetByteSize();
210 if (curr_read_size > bytes_left)
211 curr_read_size = bytes_left;
212
213 memcpy(dst_buf + dst_len - bytes_left, pos->second->GetBytes(),
214 curr_read_size);
215
216 bytes_left -= curr_read_size;
217 curr_addr += curr_read_size;
218
Adrian Prantl05097242018-04-30 16:49:04 +0000219 // We have a cache page that succeeded to read some bytes but not
220 // an entire page. If this happens, we must cap off how much data
221 // we are able to read...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000222 if (pos->second->GetByteSize() != cache_line_byte_size)
223 return dst_len - bytes_left;
224 }
225 }
226 }
227
228 // We need to read from the process
229
230 if (bytes_left > 0) {
231 assert((curr_addr % cache_line_byte_size) == 0);
232 std::unique_ptr<DataBufferHeap> data_buffer_heap_ap(
233 new DataBufferHeap(cache_line_byte_size, 0));
234 size_t process_bytes_read = m_process.ReadMemoryFromInferior(
235 curr_addr, data_buffer_heap_ap->GetBytes(),
236 data_buffer_heap_ap->GetByteSize(), error);
237 if (process_bytes_read == 0)
238 return dst_len - bytes_left;
239
240 if (process_bytes_read != cache_line_byte_size)
241 data_buffer_heap_ap->SetByteSize(process_bytes_read);
242 m_L2_cache[curr_addr] = DataBufferSP(data_buffer_heap_ap.release());
243 // We have read data and put it into the cache, continue through the
244 // loop again to get the data out of the cache...
245 }
246 }
247 }
248
249 return dst_len - bytes_left;
Greg Claytond495c532011-05-17 03:37:42 +0000250}
251
Kate Stoneb9c1b512016-09-06 20:57:50 +0000252AllocatedBlock::AllocatedBlock(lldb::addr_t addr, uint32_t byte_size,
253 uint32_t permissions, uint32_t chunk_size)
Greg Claytonac7c2ef2017-02-09 17:56:55 +0000254 : m_range(addr, byte_size), m_permissions(permissions),
255 m_chunk_size(chunk_size)
Greg Claytond495c532011-05-17 03:37:42 +0000256{
Greg Claytonac7c2ef2017-02-09 17:56:55 +0000257 // The entire address range is free to start with.
258 m_free_blocks.Append(m_range);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000259 assert(byte_size > chunk_size);
Greg Claytond495c532011-05-17 03:37:42 +0000260}
261
Kate Stoneb9c1b512016-09-06 20:57:50 +0000262AllocatedBlock::~AllocatedBlock() {}
Greg Claytond495c532011-05-17 03:37:42 +0000263
Kate Stoneb9c1b512016-09-06 20:57:50 +0000264lldb::addr_t AllocatedBlock::ReserveBlock(uint32_t size) {
Greg Clayton98f9bcc2017-02-22 23:42:55 +0000265 // We must return something valid for zero bytes.
266 if (size == 0)
267 size = 1;
Pavel Labath3b7e1982017-02-05 00:44:54 +0000268 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Greg Claytonac7c2ef2017-02-09 17:56:55 +0000269
270 const size_t free_count = m_free_blocks.GetSize();
271 for (size_t i=0; i<free_count; ++i)
272 {
Greg Clayton21b4b2e2017-02-09 18:21:04 +0000273 auto &free_block = m_free_blocks.GetEntryRef(i);
Greg Claytonac7c2ef2017-02-09 17:56:55 +0000274 const lldb::addr_t range_size = free_block.GetByteSize();
275 if (range_size >= size)
276 {
277 // We found a free block that is big enough for our data. Figure out how
Adrian Prantl05097242018-04-30 16:49:04 +0000278 // many chunks we will need and calculate the resulting block size we
279 // will reserve.
Greg Clayton98f9bcc2017-02-22 23:42:55 +0000280 addr_t addr = free_block.GetRangeBase();
Greg Claytonac7c2ef2017-02-09 17:56:55 +0000281 size_t num_chunks = CalculateChunksNeededForSize(size);
282 lldb::addr_t block_size = num_chunks * m_chunk_size;
283 lldb::addr_t bytes_left = range_size - block_size;
284 if (bytes_left == 0)
285 {
286 // The newly allocated block will take all of the bytes in this
287 // available block, so we can just add it to the allocated ranges and
288 // remove the range from the free ranges.
289 m_reserved_blocks.Insert(free_block, false);
290 m_free_blocks.RemoveEntryAtIndex(i);
291 }
292 else
293 {
294 // Make the new allocated range and add it to the allocated ranges.
Greg Clayton21b4b2e2017-02-09 18:21:04 +0000295 Range<lldb::addr_t, uint32_t> reserved_block(free_block);
Greg Claytonac7c2ef2017-02-09 17:56:55 +0000296 reserved_block.SetByteSize(block_size);
Adrian Prantl05097242018-04-30 16:49:04 +0000297 // Insert the reserved range and don't combine it with other blocks in
298 // the reserved blocks list.
Greg Claytonac7c2ef2017-02-09 17:56:55 +0000299 m_reserved_blocks.Insert(reserved_block, false);
300 // Adjust the free range in place since we won't change the sorted
301 // ordering of the m_free_blocks list.
302 free_block.SetRangeBase(reserved_block.GetRangeEnd());
303 free_block.SetByteSize(bytes_left);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000304 }
Greg Clayton98f9bcc2017-02-22 23:42:55 +0000305 LLDB_LOGV(log, "({0}) (size = {1} ({1:x})) => {2:x}", this, size, addr);
306 return addr;
Greg Claytond495c532011-05-17 03:37:42 +0000307 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000308 }
Jim Inghame7701fe2014-08-08 20:01:41 +0000309
Greg Clayton98f9bcc2017-02-22 23:42:55 +0000310 LLDB_LOGV(log, "({0}) (size = {1} ({1:x})) => {2:x}", this, size,
311 LLDB_INVALID_ADDRESS);
312 return LLDB_INVALID_ADDRESS;
Greg Claytond495c532011-05-17 03:37:42 +0000313}
314
Kate Stoneb9c1b512016-09-06 20:57:50 +0000315bool AllocatedBlock::FreeBlock(addr_t addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000316 bool success = false;
Greg Claytonac7c2ef2017-02-09 17:56:55 +0000317 auto entry_idx = m_reserved_blocks.FindEntryIndexThatContains(addr);
318 if (entry_idx != UINT32_MAX)
319 {
320 m_free_blocks.Insert(m_reserved_blocks.GetEntryRef(entry_idx), true);
321 m_reserved_blocks.RemoveEntryAtIndex(entry_idx);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000322 success = true;
323 }
Pavel Labath3b7e1982017-02-05 00:44:54 +0000324 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Greg Claytonac7c2ef2017-02-09 17:56:55 +0000325 LLDB_LOGV(log, "({0}) (addr = {1:x}) => {2}", this, addr, success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000326 return success;
Greg Claytond495c532011-05-17 03:37:42 +0000327}
328
Kate Stoneb9c1b512016-09-06 20:57:50 +0000329AllocatedMemoryCache::AllocatedMemoryCache(Process &process)
330 : m_process(process), m_mutex(), m_memory_map() {}
331
332AllocatedMemoryCache::~AllocatedMemoryCache() {}
333
334void AllocatedMemoryCache::Clear() {
335 std::lock_guard<std::recursive_mutex> guard(m_mutex);
336 if (m_process.IsAlive()) {
337 PermissionsToBlockMap::iterator pos, end = m_memory_map.end();
338 for (pos = m_memory_map.begin(); pos != end; ++pos)
339 m_process.DoDeallocateMemory(pos->second->GetBaseAddress());
340 }
341 m_memory_map.clear();
Greg Claytond495c532011-05-17 03:37:42 +0000342}
343
Greg Claytond495c532011-05-17 03:37:42 +0000344AllocatedMemoryCache::AllocatedBlockSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000345AllocatedMemoryCache::AllocatePage(uint32_t byte_size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +0000346 uint32_t chunk_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000347 AllocatedBlockSP block_sp;
348 const size_t page_size = 4096;
349 const size_t num_pages = (byte_size + page_size - 1) / page_size;
350 const size_t page_byte_size = num_pages * page_size;
Greg Claytond495c532011-05-17 03:37:42 +0000351
Kate Stoneb9c1b512016-09-06 20:57:50 +0000352 addr_t addr = m_process.DoAllocateMemory(page_byte_size, permissions, error);
Greg Claytond495c532011-05-17 03:37:42 +0000353
Kate Stoneb9c1b512016-09-06 20:57:50 +0000354 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
355 if (log) {
356 log->Printf("Process::DoAllocateMemory (byte_size = 0x%8.8" PRIx32
357 ", permissions = %s) => 0x%16.16" PRIx64,
358 (uint32_t)page_byte_size, GetPermissionsAsCString(permissions),
359 (uint64_t)addr);
360 }
Greg Claytond495c532011-05-17 03:37:42 +0000361
Kate Stoneb9c1b512016-09-06 20:57:50 +0000362 if (addr != LLDB_INVALID_ADDRESS) {
Jonas Devlieghere796ac802019-02-11 23:13:08 +0000363 block_sp = std::make_shared<AllocatedBlock>(addr, page_byte_size,
364 permissions, chunk_size);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000365 m_memory_map.insert(std::make_pair(permissions, block_sp));
366 }
367 return block_sp;
368}
369
370lldb::addr_t AllocatedMemoryCache::AllocateMemory(size_t byte_size,
371 uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +0000372 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000373 std::lock_guard<std::recursive_mutex> guard(m_mutex);
374
375 addr_t addr = LLDB_INVALID_ADDRESS;
376 std::pair<PermissionsToBlockMap::iterator, PermissionsToBlockMap::iterator>
377 range = m_memory_map.equal_range(permissions);
378
379 for (PermissionsToBlockMap::iterator pos = range.first; pos != range.second;
380 ++pos) {
381 addr = (*pos).second->ReserveBlock(byte_size);
Greg Claytond495c532011-05-17 03:37:42 +0000382 if (addr != LLDB_INVALID_ADDRESS)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000383 break;
384 }
385
386 if (addr == LLDB_INVALID_ADDRESS) {
387 AllocatedBlockSP block_sp(AllocatePage(byte_size, permissions, 16, error));
388
389 if (block_sp)
390 addr = block_sp->ReserveBlock(byte_size);
391 }
392 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
393 if (log)
394 log->Printf(
395 "AllocatedMemoryCache::AllocateMemory (byte_size = 0x%8.8" PRIx32
396 ", permissions = %s) => 0x%16.16" PRIx64,
397 (uint32_t)byte_size, GetPermissionsAsCString(permissions),
398 (uint64_t)addr);
399 return addr;
Greg Claytond495c532011-05-17 03:37:42 +0000400}
401
Kate Stoneb9c1b512016-09-06 20:57:50 +0000402bool AllocatedMemoryCache::DeallocateMemory(lldb::addr_t addr) {
403 std::lock_guard<std::recursive_mutex> guard(m_mutex);
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +0000404
Kate Stoneb9c1b512016-09-06 20:57:50 +0000405 PermissionsToBlockMap::iterator pos, end = m_memory_map.end();
406 bool success = false;
407 for (pos = m_memory_map.begin(); pos != end; ++pos) {
408 if (pos->second->Contains(addr)) {
409 success = pos->second->FreeBlock(addr);
410 break;
Greg Claytond495c532011-05-17 03:37:42 +0000411 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000412 }
413 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
414 if (log)
415 log->Printf("AllocatedMemoryCache::DeallocateMemory (addr = 0x%16.16" PRIx64
416 ") => %i",
417 (uint64_t)addr, success);
418 return success;
Greg Claytond495c532011-05-17 03:37:42 +0000419}