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 <inttypes.h>
11 #include "lldb/Core/RangeMap.h"
12 #include "lldb/Target/Process.h"
13 #include "lldb/Utility/DataBufferHeap.h"
14 #include "lldb/Utility/Log.h"
15 #include "lldb/Utility/State.h"
16 
17 using namespace lldb;
18 using namespace lldb_private;
19 
20 //----------------------------------------------------------------------
21 // MemoryCache constructor
22 //----------------------------------------------------------------------
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 //----------------------------------------------------------------------
29 // Destructor
30 //----------------------------------------------------------------------
31 MemoryCache::~MemoryCache() {}
32 
33 void 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();
40 }
41 
42 void 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 
48 void 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 
54 void 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 
102 void MemoryCache::AddInvalidRange(lldb::addr_t base_addr,
103                                   lldb::addr_t byte_size) {
104   if (byte_size > 0) {
105     std::lock_guard<std::recursive_mutex> guard(m_mutex);
106     InvalidRanges::Entry range(base_addr, byte_size);
107     m_invalid_ranges.Append(range);
108     m_invalid_ranges.Sort();
109   }
110 }
111 
112 bool MemoryCache::RemoveInvalidRange(lldb::addr_t base_addr,
113                                      lldb::addr_t byte_size) {
114   if (byte_size > 0) {
115     std::lock_guard<std::recursive_mutex> guard(m_mutex);
116     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;
125 }
126 
127 size_t MemoryCache::Read(addr_t addr, void *dst, size_t dst_len,
128                          Status &error) {
129   size_t bytes_left = dst_len;
130 
131   // 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).
137 
138   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;
144     }
145     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;
150     }
151   }
152 
153   // 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
158   // 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 
216             // 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...
219             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;
247 }
248 
249 AllocatedBlock::AllocatedBlock(lldb::addr_t addr, uint32_t byte_size,
250                                uint32_t permissions, uint32_t chunk_size)
251     : m_range(addr, byte_size), m_permissions(permissions),
252       m_chunk_size(chunk_size)
253 {
254   // The entire address range is free to start with.
255   m_free_blocks.Append(m_range);
256   assert(byte_size > chunk_size);
257 }
258 
259 AllocatedBlock::~AllocatedBlock() {}
260 
261 lldb::addr_t AllocatedBlock::ReserveBlock(uint32_t size) {
262   // We must return something valid for zero bytes.
263   if (size == 0)
264     size = 1;
265   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
266 
267   const size_t free_count = m_free_blocks.GetSize();
268   for (size_t i=0; i<free_count; ++i)
269   {
270     auto &free_block = m_free_blocks.GetEntryRef(i);
271     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
275       // many chunks we will need and calculate the resulting block size we
276       // will reserve.
277       addr_t addr = free_block.GetRangeBase();
278       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.
292         Range<lldb::addr_t, uint32_t> reserved_block(free_block);
293         reserved_block.SetByteSize(block_size);
294         // Insert the reserved range and don't combine it with other blocks in
295         // the reserved blocks list.
296         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);
301       }
302       LLDB_LOGV(log, "({0}) (size = {1} ({1:x})) => {2:x}", this, size, addr);
303       return addr;
304     }
305   }
306 
307   LLDB_LOGV(log, "({0}) (size = {1} ({1:x})) => {2:x}", this, size,
308             LLDB_INVALID_ADDRESS);
309   return LLDB_INVALID_ADDRESS;
310 }
311 
312 bool AllocatedBlock::FreeBlock(addr_t addr) {
313   bool success = false;
314   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);
319     success = true;
320   }
321   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
322   LLDB_LOGV(log, "({0}) (addr = {1:x}) => {2}", this, addr, success);
323   return success;
324 }
325 
326 AllocatedMemoryCache::AllocatedMemoryCache(Process &process)
327     : m_process(process), m_mutex(), m_memory_map() {}
328 
329 AllocatedMemoryCache::~AllocatedMemoryCache() {}
330 
331 void 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();
339 }
340 
341 AllocatedMemoryCache::AllocatedBlockSP
342 AllocatedMemoryCache::AllocatePage(uint32_t byte_size, uint32_t permissions,
343                                    uint32_t chunk_size, Status &error) {
344   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;
348 
349   addr_t addr = m_process.DoAllocateMemory(page_byte_size, permissions, error);
350 
351   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   }
358 
359   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 
367 lldb::addr_t AllocatedMemoryCache::AllocateMemory(size_t byte_size,
368                                                   uint32_t permissions,
369                                                   Status &error) {
370   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);
379     if (addr != LLDB_INVALID_ADDRESS)
380       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;
397 }
398 
399 bool AllocatedMemoryCache::DeallocateMemory(lldb::addr_t addr) {
400   std::lock_guard<std::recursive_mutex> guard(m_mutex);
401 
402   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;
408     }
409   }
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;
416 }
417