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