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