xref: /src/contrib/llvm-project/lldb/source/Target/Memory.cpp (revision 06c3fb2749bda94cb5201f81ffdb8fa6c3161b2e)
1cfca06d7SDimitry Andric //===-- Memory.cpp --------------------------------------------------------===//
2f034231aSEd Maste //
35f29bb8aSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
45f29bb8aSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
55f29bb8aSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6f034231aSEd Maste //
7f034231aSEd Maste //===----------------------------------------------------------------------===//
8f034231aSEd Maste 
9f034231aSEd Maste #include "lldb/Target/Memory.h"
10f034231aSEd Maste #include "lldb/Target/Process.h"
1174a628f7SDimitry Andric #include "lldb/Utility/DataBufferHeap.h"
12145449b1SDimitry Andric #include "lldb/Utility/LLDBLog.h"
1374a628f7SDimitry Andric #include "lldb/Utility/Log.h"
145f29bb8aSDimitry Andric #include "lldb/Utility/RangeMap.h"
1594994d37SDimitry Andric #include "lldb/Utility/State.h"
16f034231aSEd Maste 
175f29bb8aSDimitry Andric #include <cinttypes>
185f29bb8aSDimitry Andric #include <memory>
195f29bb8aSDimitry Andric 
20f034231aSEd Maste using namespace lldb;
21f034231aSEd Maste using namespace lldb_private;
22f034231aSEd Maste 
23f034231aSEd Maste // MemoryCache constructor
MemoryCache(Process & process)24f3fbd1c0SDimitry Andric MemoryCache::MemoryCache(Process &process)
2514f1b3e8SDimitry Andric     : m_mutex(), m_L1_cache(), m_L2_cache(), m_invalid_ranges(),
265e95aa85SEd Maste       m_process(process),
2714f1b3e8SDimitry Andric       m_L2_cache_line_byte_size(process.GetMemoryCacheLineSize()) {}
28f034231aSEd Maste 
29f034231aSEd Maste // Destructor
30344a3780SDimitry Andric MemoryCache::~MemoryCache() = default;
31f034231aSEd Maste 
Clear(bool clear_invalid_ranges)3214f1b3e8SDimitry Andric void MemoryCache::Clear(bool clear_invalid_ranges) {
33f3fbd1c0SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_mutex);
345e95aa85SEd Maste   m_L1_cache.clear();
355e95aa85SEd Maste   m_L2_cache.clear();
36f034231aSEd Maste   if (clear_invalid_ranges)
37f034231aSEd Maste     m_invalid_ranges.Clear();
385e95aa85SEd Maste   m_L2_cache_line_byte_size = m_process.GetMemoryCacheLineSize();
395e95aa85SEd Maste }
405e95aa85SEd Maste 
AddL1CacheData(lldb::addr_t addr,const void * src,size_t src_len)4114f1b3e8SDimitry Andric void MemoryCache::AddL1CacheData(lldb::addr_t addr, const void *src,
4214f1b3e8SDimitry Andric                                  size_t src_len) {
4314f1b3e8SDimitry Andric   AddL1CacheData(
4414f1b3e8SDimitry Andric       addr, DataBufferSP(new DataBufferHeap(DataBufferHeap(src, src_len))));
455e95aa85SEd Maste }
465e95aa85SEd Maste 
AddL1CacheData(lldb::addr_t addr,const DataBufferSP & data_buffer_sp)4714f1b3e8SDimitry Andric void MemoryCache::AddL1CacheData(lldb::addr_t addr,
4814f1b3e8SDimitry Andric                                  const DataBufferSP &data_buffer_sp) {
49f3fbd1c0SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_mutex);
505e95aa85SEd Maste   m_L1_cache[addr] = data_buffer_sp;
51f034231aSEd Maste }
52f034231aSEd Maste 
Flush(addr_t addr,size_t size)5314f1b3e8SDimitry Andric void MemoryCache::Flush(addr_t addr, size_t size) {
54f034231aSEd Maste   if (size == 0)
55f034231aSEd Maste     return;
56f034231aSEd Maste 
57f3fbd1c0SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_mutex);
58f034231aSEd Maste 
595e95aa85SEd Maste   // Erase any blocks from the L1 cache that intersect with the flush range
6014f1b3e8SDimitry Andric   if (!m_L1_cache.empty()) {
615e95aa85SEd Maste     AddrRange flush_range(addr, size);
62f3fbd1c0SDimitry Andric     BlockMap::iterator pos = m_L1_cache.upper_bound(addr);
6314f1b3e8SDimitry Andric     if (pos != m_L1_cache.begin()) {
64f3fbd1c0SDimitry Andric       --pos;
65f3fbd1c0SDimitry Andric     }
6614f1b3e8SDimitry Andric     while (pos != m_L1_cache.end()) {
675e95aa85SEd Maste       AddrRange chunk_range(pos->first, pos->second->GetByteSize());
685e95aa85SEd Maste       if (!chunk_range.DoesIntersect(flush_range))
695e95aa85SEd Maste         break;
705e95aa85SEd Maste       pos = m_L1_cache.erase(pos);
715e95aa85SEd Maste     }
725e95aa85SEd Maste   }
735e95aa85SEd Maste 
7414f1b3e8SDimitry Andric   if (!m_L2_cache.empty()) {
755e95aa85SEd Maste     const uint32_t cache_line_byte_size = m_L2_cache_line_byte_size;
76f034231aSEd Maste     const addr_t end_addr = (addr + size - 1);
77f034231aSEd Maste     const addr_t first_cache_line_addr = addr - (addr % cache_line_byte_size);
7814f1b3e8SDimitry Andric     const addr_t last_cache_line_addr =
7914f1b3e8SDimitry Andric         end_addr - (end_addr % cache_line_byte_size);
80f034231aSEd Maste     // Watch for overflow where size will cause us to go off the end of the
81f034231aSEd Maste     // 64 bit address space
82f034231aSEd Maste     uint32_t num_cache_lines;
83f034231aSEd Maste     if (last_cache_line_addr >= first_cache_line_addr)
8414f1b3e8SDimitry Andric       num_cache_lines = ((last_cache_line_addr - first_cache_line_addr) /
8514f1b3e8SDimitry Andric                          cache_line_byte_size) +
8614f1b3e8SDimitry Andric                         1;
87f034231aSEd Maste     else
8814f1b3e8SDimitry Andric       num_cache_lines =
8914f1b3e8SDimitry Andric           (UINT64_MAX - first_cache_line_addr + 1) / cache_line_byte_size;
90f034231aSEd Maste 
91f034231aSEd Maste     uint32_t cache_idx = 0;
9214f1b3e8SDimitry Andric     for (addr_t curr_addr = first_cache_line_addr; cache_idx < num_cache_lines;
9314f1b3e8SDimitry Andric          curr_addr += cache_line_byte_size, ++cache_idx) {
945e95aa85SEd Maste       BlockMap::iterator pos = m_L2_cache.find(curr_addr);
955e95aa85SEd Maste       if (pos != m_L2_cache.end())
965e95aa85SEd Maste         m_L2_cache.erase(pos);
975e95aa85SEd Maste     }
98f034231aSEd Maste   }
99f034231aSEd Maste }
100f034231aSEd Maste 
AddInvalidRange(lldb::addr_t base_addr,lldb::addr_t byte_size)10114f1b3e8SDimitry Andric void MemoryCache::AddInvalidRange(lldb::addr_t base_addr,
10214f1b3e8SDimitry Andric                                   lldb::addr_t byte_size) {
10314f1b3e8SDimitry Andric   if (byte_size > 0) {
104f3fbd1c0SDimitry Andric     std::lock_guard<std::recursive_mutex> guard(m_mutex);
105f034231aSEd Maste     InvalidRanges::Entry range(base_addr, byte_size);
106f034231aSEd Maste     m_invalid_ranges.Append(range);
107f034231aSEd Maste     m_invalid_ranges.Sort();
108f034231aSEd Maste   }
109f034231aSEd Maste }
110f034231aSEd Maste 
RemoveInvalidRange(lldb::addr_t base_addr,lldb::addr_t byte_size)11114f1b3e8SDimitry Andric bool MemoryCache::RemoveInvalidRange(lldb::addr_t base_addr,
11214f1b3e8SDimitry Andric                                      lldb::addr_t byte_size) {
11314f1b3e8SDimitry Andric   if (byte_size > 0) {
114f3fbd1c0SDimitry Andric     std::lock_guard<std::recursive_mutex> guard(m_mutex);
115f034231aSEd Maste     const uint32_t idx = m_invalid_ranges.FindEntryIndexThatContains(base_addr);
11614f1b3e8SDimitry Andric     if (idx != UINT32_MAX) {
117f034231aSEd Maste       const InvalidRanges::Entry *entry = m_invalid_ranges.GetEntryAtIndex(idx);
11814f1b3e8SDimitry Andric       if (entry->GetRangeBase() == base_addr &&
11914f1b3e8SDimitry Andric           entry->GetByteSize() == byte_size)
120cfca06d7SDimitry Andric         return m_invalid_ranges.RemoveEntryAtIndex(idx);
121f034231aSEd Maste     }
122f034231aSEd Maste   }
123f034231aSEd Maste   return false;
124f034231aSEd Maste }
125f034231aSEd Maste 
GetL2CacheLine(lldb::addr_t line_base_addr,Status & error)1267fa27ce4SDimitry Andric lldb::DataBufferSP MemoryCache::GetL2CacheLine(lldb::addr_t line_base_addr,
127b76161e4SDimitry Andric                                                Status &error) {
1287fa27ce4SDimitry Andric   // This function assumes that the address given is aligned correctly.
1297fa27ce4SDimitry Andric   assert((line_base_addr % m_L2_cache_line_byte_size) == 0);
1305e95aa85SEd Maste 
131f3fbd1c0SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1327fa27ce4SDimitry Andric   auto pos = m_L2_cache.find(line_base_addr);
1337fa27ce4SDimitry Andric   if (pos != m_L2_cache.end())
1347fa27ce4SDimitry Andric     return pos->second;
1357fa27ce4SDimitry Andric 
1367fa27ce4SDimitry Andric   auto data_buffer_heap_sp =
1377fa27ce4SDimitry Andric       std::make_shared<DataBufferHeap>(m_L2_cache_line_byte_size, 0);
1387fa27ce4SDimitry Andric   size_t process_bytes_read = m_process.ReadMemoryFromInferior(
1397fa27ce4SDimitry Andric       line_base_addr, data_buffer_heap_sp->GetBytes(),
1407fa27ce4SDimitry Andric       data_buffer_heap_sp->GetByteSize(), error);
1417fa27ce4SDimitry Andric 
1427fa27ce4SDimitry Andric   // If we failed a read, not much we can do.
1437fa27ce4SDimitry Andric   if (process_bytes_read == 0)
1447fa27ce4SDimitry Andric     return lldb::DataBufferSP();
1457fa27ce4SDimitry Andric 
1467fa27ce4SDimitry Andric   // If we didn't get a complete read, we can still cache what we did get.
1477fa27ce4SDimitry Andric   if (process_bytes_read < m_L2_cache_line_byte_size)
1487fa27ce4SDimitry Andric     data_buffer_heap_sp->SetByteSize(process_bytes_read);
1497fa27ce4SDimitry Andric 
1507fa27ce4SDimitry Andric   m_L2_cache[line_base_addr] = data_buffer_heap_sp;
1517fa27ce4SDimitry Andric   return data_buffer_heap_sp;
1527fa27ce4SDimitry Andric }
1537fa27ce4SDimitry Andric 
Read(addr_t addr,void * dst,size_t dst_len,Status & error)1547fa27ce4SDimitry Andric size_t MemoryCache::Read(addr_t addr, void *dst, size_t dst_len,
1557fa27ce4SDimitry Andric                          Status &error) {
1567fa27ce4SDimitry Andric   if (!dst || dst_len == 0)
1577fa27ce4SDimitry Andric     return 0;
1587fa27ce4SDimitry Andric 
1597fa27ce4SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1607fa27ce4SDimitry Andric   // FIXME: We should do a more thorough check to make sure that we're not
1617fa27ce4SDimitry Andric   // overlapping with any invalid ranges (e.g. Read 0x100 - 0x200 but there's an
1627fa27ce4SDimitry Andric   // invalid range 0x180 - 0x280). `FindEntryThatContains` has an implementation
1637fa27ce4SDimitry Andric   // that takes a range, but it only checks to see if the argument is contained
1647fa27ce4SDimitry Andric   // by an existing invalid range. It cannot check if the argument contains
1657fa27ce4SDimitry Andric   // invalid ranges and cannot check for overlaps.
1667fa27ce4SDimitry Andric   if (m_invalid_ranges.FindEntryThatContains(addr)) {
1677fa27ce4SDimitry Andric     error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
1687fa27ce4SDimitry Andric     return 0;
1697fa27ce4SDimitry Andric   }
1707fa27ce4SDimitry Andric 
1717fa27ce4SDimitry Andric   // Check the L1 cache for a range that contains the entire memory read.
1727fa27ce4SDimitry Andric   // L1 cache contains chunks of memory that are not required to be the size of
1737fa27ce4SDimitry Andric   // an L2 cache line. We avoid trying to do partial reads from the L1 cache to
1747fa27ce4SDimitry Andric   // simplify the implementation.
17514f1b3e8SDimitry Andric   if (!m_L1_cache.empty()) {
1765e95aa85SEd Maste     AddrRange read_range(addr, dst_len);
177e81d9d49SDimitry Andric     BlockMap::iterator pos = m_L1_cache.upper_bound(addr);
17814f1b3e8SDimitry Andric     if (pos != m_L1_cache.begin()) {
1795e95aa85SEd Maste       --pos;
1805e95aa85SEd Maste     }
181e81d9d49SDimitry Andric     AddrRange chunk_range(pos->first, pos->second->GetByteSize());
18214f1b3e8SDimitry Andric     if (chunk_range.Contains(read_range)) {
1835f29bb8aSDimitry Andric       memcpy(dst, pos->second->GetBytes() + (addr - chunk_range.GetRangeBase()),
18414f1b3e8SDimitry Andric              dst_len);
1855e95aa85SEd Maste       return dst_len;
1865e95aa85SEd Maste     }
1875e95aa85SEd Maste   }
1885e95aa85SEd Maste 
1897fa27ce4SDimitry Andric   // If the size of the read is greater than the size of an L2 cache line, we'll
1907fa27ce4SDimitry Andric   // just read from the inferior. If that read is successful, we'll cache what
1917fa27ce4SDimitry Andric   // we read in the L1 cache for future use.
1927fa27ce4SDimitry Andric   if (dst_len > m_L2_cache_line_byte_size) {
19314f1b3e8SDimitry Andric     size_t bytes_read =
19414f1b3e8SDimitry Andric         m_process.ReadMemoryFromInferior(addr, dst, dst_len, error);
1955e95aa85SEd Maste     if (bytes_read > 0)
1965e95aa85SEd Maste       AddL1CacheData(addr, dst, bytes_read);
1975e95aa85SEd Maste     return bytes_read;
1980cac4ca3SEd Maste   }
1990cac4ca3SEd Maste 
2007fa27ce4SDimitry Andric   // If the size of the read fits inside one L2 cache line, we'll try reading
2017fa27ce4SDimitry Andric   // from the L2 cache. Note that if the range of memory we're reading sits
2027fa27ce4SDimitry Andric   // between two contiguous cache lines, we'll touch two cache lines instead of
2037fa27ce4SDimitry Andric   // just one.
2047fa27ce4SDimitry Andric 
2057fa27ce4SDimitry Andric   // We're going to have all of our loads and reads be cache line aligned.
2067fa27ce4SDimitry Andric   addr_t cache_line_offset = addr % m_L2_cache_line_byte_size;
2077fa27ce4SDimitry Andric   addr_t cache_line_base_addr = addr - cache_line_offset;
2087fa27ce4SDimitry Andric   DataBufferSP first_cache_line = GetL2CacheLine(cache_line_base_addr, error);
2097fa27ce4SDimitry Andric   // If we get nothing, then the read to the inferior likely failed. Nothing to
2107fa27ce4SDimitry Andric   // do here.
2117fa27ce4SDimitry Andric   if (!first_cache_line)
2127fa27ce4SDimitry Andric     return 0;
2137fa27ce4SDimitry Andric 
2147fa27ce4SDimitry Andric   // If the cache line was not filled out completely and the offset is greater
2157fa27ce4SDimitry Andric   // than what we have available, we can't do anything further here.
2167fa27ce4SDimitry Andric   if (cache_line_offset >= first_cache_line->GetByteSize())
2177fa27ce4SDimitry Andric     return 0;
2187fa27ce4SDimitry Andric 
219f034231aSEd Maste   uint8_t *dst_buf = (uint8_t *)dst;
2207fa27ce4SDimitry Andric   size_t bytes_left = dst_len;
2217fa27ce4SDimitry Andric   size_t read_size = first_cache_line->GetByteSize() - cache_line_offset;
2227fa27ce4SDimitry Andric   if (read_size > bytes_left)
2237fa27ce4SDimitry Andric     read_size = bytes_left;
224f034231aSEd Maste 
22514f1b3e8SDimitry Andric   memcpy(dst_buf + dst_len - bytes_left,
2267fa27ce4SDimitry Andric          first_cache_line->GetBytes() + cache_line_offset, read_size);
2277fa27ce4SDimitry Andric   bytes_left -= read_size;
228f034231aSEd Maste 
2297fa27ce4SDimitry Andric   // If the cache line was not filled out completely and we still have data to
2307fa27ce4SDimitry Andric   // read, we can't do anything further.
2317fa27ce4SDimitry Andric   if (first_cache_line->GetByteSize() < m_L2_cache_line_byte_size &&
2327fa27ce4SDimitry Andric       bytes_left > 0)
2337fa27ce4SDimitry Andric     return dst_len - bytes_left;
234f034231aSEd Maste 
2357fa27ce4SDimitry Andric   // We'll hit this scenario if our read straddles two cache lines.
23614f1b3e8SDimitry Andric   if (bytes_left > 0) {
2377fa27ce4SDimitry Andric     cache_line_base_addr += m_L2_cache_line_byte_size;
238f034231aSEd Maste 
2397fa27ce4SDimitry Andric     // FIXME: Until we are able to more thoroughly check for invalid ranges, we
2407fa27ce4SDimitry Andric     // will have to check the second line to see if it is in an invalid range as
2417fa27ce4SDimitry Andric     // well. See the check near the beginning of the function for more details.
2427fa27ce4SDimitry Andric     if (m_invalid_ranges.FindEntryThatContains(cache_line_base_addr)) {
2437fa27ce4SDimitry Andric       error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64,
2447fa27ce4SDimitry Andric                                      cache_line_base_addr);
245f034231aSEd Maste       return dst_len - bytes_left;
246f034231aSEd Maste     }
247f034231aSEd Maste 
2487fa27ce4SDimitry Andric     DataBufferSP second_cache_line =
2497fa27ce4SDimitry Andric         GetL2CacheLine(cache_line_base_addr, error);
2507fa27ce4SDimitry Andric     if (!second_cache_line)
251f034231aSEd Maste       return dst_len - bytes_left;
252f034231aSEd Maste 
2537fa27ce4SDimitry Andric     read_size = bytes_left;
2547fa27ce4SDimitry Andric     if (read_size > second_cache_line->GetByteSize())
2557fa27ce4SDimitry Andric       read_size = second_cache_line->GetByteSize();
2567fa27ce4SDimitry Andric 
2577fa27ce4SDimitry Andric     memcpy(dst_buf + dst_len - bytes_left, second_cache_line->GetBytes(),
2587fa27ce4SDimitry Andric            read_size);
2597fa27ce4SDimitry Andric     bytes_left -= read_size;
260f034231aSEd Maste 
261f034231aSEd Maste     return dst_len - bytes_left;
262f034231aSEd Maste   }
263f034231aSEd Maste 
2647fa27ce4SDimitry Andric   return dst_len;
2657fa27ce4SDimitry Andric }
2667fa27ce4SDimitry Andric 
AllocatedBlock(lldb::addr_t addr,uint32_t byte_size,uint32_t permissions,uint32_t chunk_size)26714f1b3e8SDimitry Andric AllocatedBlock::AllocatedBlock(lldb::addr_t addr, uint32_t byte_size,
26814f1b3e8SDimitry Andric                                uint32_t permissions, uint32_t chunk_size)
26974a628f7SDimitry Andric     : m_range(addr, byte_size), m_permissions(permissions),
27074a628f7SDimitry Andric       m_chunk_size(chunk_size)
271f034231aSEd Maste {
27274a628f7SDimitry Andric   // The entire address range is free to start with.
27374a628f7SDimitry Andric   m_free_blocks.Append(m_range);
274f034231aSEd Maste   assert(byte_size > chunk_size);
275f034231aSEd Maste }
276f034231aSEd Maste 
277344a3780SDimitry Andric AllocatedBlock::~AllocatedBlock() = default;
278f034231aSEd Maste 
ReserveBlock(uint32_t size)27914f1b3e8SDimitry Andric lldb::addr_t AllocatedBlock::ReserveBlock(uint32_t size) {
28074a628f7SDimitry Andric   // We must return something valid for zero bytes.
28174a628f7SDimitry Andric   if (size == 0)
28274a628f7SDimitry Andric     size = 1;
283145449b1SDimitry Andric   Log *log = GetLog(LLDBLog::Process);
284f034231aSEd Maste 
28574a628f7SDimitry Andric   const size_t free_count = m_free_blocks.GetSize();
28674a628f7SDimitry Andric   for (size_t i=0; i<free_count; ++i)
28774a628f7SDimitry Andric   {
28874a628f7SDimitry Andric     auto &free_block = m_free_blocks.GetEntryRef(i);
28974a628f7SDimitry Andric     const lldb::addr_t range_size = free_block.GetByteSize();
29074a628f7SDimitry Andric     if (range_size >= size)
29174a628f7SDimitry Andric     {
29274a628f7SDimitry Andric       // We found a free block that is big enough for our data. Figure out how
293f73363f1SDimitry Andric       // many chunks we will need and calculate the resulting block size we
294f73363f1SDimitry Andric       // will reserve.
29574a628f7SDimitry Andric       addr_t addr = free_block.GetRangeBase();
29674a628f7SDimitry Andric       size_t num_chunks = CalculateChunksNeededForSize(size);
29774a628f7SDimitry Andric       lldb::addr_t block_size = num_chunks * m_chunk_size;
29874a628f7SDimitry Andric       lldb::addr_t bytes_left = range_size - block_size;
29974a628f7SDimitry Andric       if (bytes_left == 0)
30074a628f7SDimitry Andric       {
30174a628f7SDimitry Andric         // The newly allocated block will take all of the bytes in this
30274a628f7SDimitry Andric         // available block, so we can just add it to the allocated ranges and
30374a628f7SDimitry Andric         // remove the range from the free ranges.
30474a628f7SDimitry Andric         m_reserved_blocks.Insert(free_block, false);
30574a628f7SDimitry Andric         m_free_blocks.RemoveEntryAtIndex(i);
306f034231aSEd Maste       }
30774a628f7SDimitry Andric       else
30874a628f7SDimitry Andric       {
30974a628f7SDimitry Andric         // Make the new allocated range and add it to the allocated ranges.
31074a628f7SDimitry Andric         Range<lldb::addr_t, uint32_t> reserved_block(free_block);
31174a628f7SDimitry Andric         reserved_block.SetByteSize(block_size);
312f73363f1SDimitry Andric         // Insert the reserved range and don't combine it with other blocks in
313f73363f1SDimitry Andric         // the reserved blocks list.
31474a628f7SDimitry Andric         m_reserved_blocks.Insert(reserved_block, false);
31574a628f7SDimitry Andric         // Adjust the free range in place since we won't change the sorted
31674a628f7SDimitry Andric         // ordering of the m_free_blocks list.
31774a628f7SDimitry Andric         free_block.SetRangeBase(reserved_block.GetRangeEnd());
31874a628f7SDimitry Andric         free_block.SetByteSize(bytes_left);
319f034231aSEd Maste       }
32074a628f7SDimitry Andric       LLDB_LOGV(log, "({0}) (size = {1} ({1:x})) => {2:x}", this, size, addr);
321f034231aSEd Maste       return addr;
322f034231aSEd Maste     }
32374a628f7SDimitry Andric   }
32474a628f7SDimitry Andric 
32574a628f7SDimitry Andric   LLDB_LOGV(log, "({0}) (size = {1} ({1:x})) => {2:x}", this, size,
32674a628f7SDimitry Andric             LLDB_INVALID_ADDRESS);
32774a628f7SDimitry Andric   return LLDB_INVALID_ADDRESS;
32874a628f7SDimitry Andric }
329f034231aSEd Maste 
FreeBlock(addr_t addr)33014f1b3e8SDimitry Andric bool AllocatedBlock::FreeBlock(addr_t addr) {
331f034231aSEd Maste   bool success = false;
33274a628f7SDimitry Andric   auto entry_idx = m_reserved_blocks.FindEntryIndexThatContains(addr);
33374a628f7SDimitry Andric   if (entry_idx != UINT32_MAX)
33474a628f7SDimitry Andric   {
33574a628f7SDimitry Andric     m_free_blocks.Insert(m_reserved_blocks.GetEntryRef(entry_idx), true);
33674a628f7SDimitry Andric     m_reserved_blocks.RemoveEntryAtIndex(entry_idx);
337f034231aSEd Maste     success = true;
338f034231aSEd Maste   }
339145449b1SDimitry Andric   Log *log = GetLog(LLDBLog::Process);
34074a628f7SDimitry Andric   LLDB_LOGV(log, "({0}) (addr = {1:x}) => {2}", this, addr, success);
341f034231aSEd Maste   return success;
342f034231aSEd Maste }
343f034231aSEd Maste 
AllocatedMemoryCache(Process & process)34414f1b3e8SDimitry Andric AllocatedMemoryCache::AllocatedMemoryCache(Process &process)
34514f1b3e8SDimitry Andric     : m_process(process), m_mutex(), m_memory_map() {}
346f034231aSEd Maste 
347344a3780SDimitry Andric AllocatedMemoryCache::~AllocatedMemoryCache() = default;
348f034231aSEd Maste 
Clear(bool deallocate_memory)349e3b55780SDimitry Andric void AllocatedMemoryCache::Clear(bool deallocate_memory) {
350f3fbd1c0SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_mutex);
351e3b55780SDimitry Andric   if (m_process.IsAlive() && deallocate_memory) {
352f034231aSEd Maste     PermissionsToBlockMap::iterator pos, end = m_memory_map.end();
353f034231aSEd Maste     for (pos = m_memory_map.begin(); pos != end; ++pos)
354f034231aSEd Maste       m_process.DoDeallocateMemory(pos->second->GetBaseAddress());
355f034231aSEd Maste   }
356f034231aSEd Maste   m_memory_map.clear();
357f034231aSEd Maste }
358f034231aSEd Maste 
359f034231aSEd Maste AllocatedMemoryCache::AllocatedBlockSP
AllocatePage(uint32_t byte_size,uint32_t permissions,uint32_t chunk_size,Status & error)36014f1b3e8SDimitry Andric AllocatedMemoryCache::AllocatePage(uint32_t byte_size, uint32_t permissions,
361b76161e4SDimitry Andric                                    uint32_t chunk_size, Status &error) {
362f034231aSEd Maste   AllocatedBlockSP block_sp;
363f034231aSEd Maste   const size_t page_size = 4096;
364f034231aSEd Maste   const size_t num_pages = (byte_size + page_size - 1) / page_size;
365f034231aSEd Maste   const size_t page_byte_size = num_pages * page_size;
366f034231aSEd Maste 
367f034231aSEd Maste   addr_t addr = m_process.DoAllocateMemory(page_byte_size, permissions, error);
368f034231aSEd Maste 
369145449b1SDimitry Andric   Log *log = GetLog(LLDBLog::Process);
37014f1b3e8SDimitry Andric   if (log) {
371ead24645SDimitry Andric     LLDB_LOGF(log,
372ead24645SDimitry Andric               "Process::DoAllocateMemory (byte_size = 0x%8.8" PRIx32
37314f1b3e8SDimitry Andric               ", permissions = %s) => 0x%16.16" PRIx64,
37414f1b3e8SDimitry Andric               (uint32_t)page_byte_size, GetPermissionsAsCString(permissions),
375f034231aSEd Maste               (uint64_t)addr);
376f034231aSEd Maste   }
377f034231aSEd Maste 
37814f1b3e8SDimitry Andric   if (addr != LLDB_INVALID_ADDRESS) {
3795f29bb8aSDimitry Andric     block_sp = std::make_shared<AllocatedBlock>(addr, page_byte_size,
3805f29bb8aSDimitry Andric                                                 permissions, chunk_size);
381f034231aSEd Maste     m_memory_map.insert(std::make_pair(permissions, block_sp));
382f034231aSEd Maste   }
383f034231aSEd Maste   return block_sp;
384f034231aSEd Maste }
385f034231aSEd Maste 
AllocateMemory(size_t byte_size,uint32_t permissions,Status & error)38614f1b3e8SDimitry Andric lldb::addr_t AllocatedMemoryCache::AllocateMemory(size_t byte_size,
387f034231aSEd Maste                                                   uint32_t permissions,
388b76161e4SDimitry Andric                                                   Status &error) {
389f3fbd1c0SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_mutex);
390f034231aSEd Maste 
391f034231aSEd Maste   addr_t addr = LLDB_INVALID_ADDRESS;
39214f1b3e8SDimitry Andric   std::pair<PermissionsToBlockMap::iterator, PermissionsToBlockMap::iterator>
39314f1b3e8SDimitry Andric       range = m_memory_map.equal_range(permissions);
394f034231aSEd Maste 
39514f1b3e8SDimitry Andric   for (PermissionsToBlockMap::iterator pos = range.first; pos != range.second;
39614f1b3e8SDimitry Andric        ++pos) {
397f034231aSEd Maste     addr = (*pos).second->ReserveBlock(byte_size);
3980cac4ca3SEd Maste     if (addr != LLDB_INVALID_ADDRESS)
3990cac4ca3SEd Maste       break;
400f034231aSEd Maste   }
401f034231aSEd Maste 
40214f1b3e8SDimitry Andric   if (addr == LLDB_INVALID_ADDRESS) {
403f034231aSEd Maste     AllocatedBlockSP block_sp(AllocatePage(byte_size, permissions, 16, error));
404f034231aSEd Maste 
405f034231aSEd Maste     if (block_sp)
406f034231aSEd Maste       addr = block_sp->ReserveBlock(byte_size);
407f034231aSEd Maste   }
408145449b1SDimitry Andric   Log *log = GetLog(LLDBLog::Process);
409ead24645SDimitry Andric   LLDB_LOGF(log,
41014f1b3e8SDimitry Andric             "AllocatedMemoryCache::AllocateMemory (byte_size = 0x%8.8" PRIx32
41114f1b3e8SDimitry Andric             ", permissions = %s) => 0x%16.16" PRIx64,
41214f1b3e8SDimitry Andric             (uint32_t)byte_size, GetPermissionsAsCString(permissions),
41314f1b3e8SDimitry Andric             (uint64_t)addr);
414f034231aSEd Maste   return addr;
415f034231aSEd Maste }
416f034231aSEd Maste 
DeallocateMemory(lldb::addr_t addr)41714f1b3e8SDimitry Andric bool AllocatedMemoryCache::DeallocateMemory(lldb::addr_t addr) {
418f3fbd1c0SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_mutex);
419f034231aSEd Maste 
420f034231aSEd Maste   PermissionsToBlockMap::iterator pos, end = m_memory_map.end();
421f034231aSEd Maste   bool success = false;
42214f1b3e8SDimitry Andric   for (pos = m_memory_map.begin(); pos != end; ++pos) {
42314f1b3e8SDimitry Andric     if (pos->second->Contains(addr)) {
424f034231aSEd Maste       success = pos->second->FreeBlock(addr);
425f034231aSEd Maste       break;
426f034231aSEd Maste     }
427f034231aSEd Maste   }
428145449b1SDimitry Andric   Log *log = GetLog(LLDBLog::Process);
429ead24645SDimitry Andric   LLDB_LOGF(log,
430ead24645SDimitry Andric             "AllocatedMemoryCache::DeallocateMemory (addr = 0x%16.16" PRIx64
43114f1b3e8SDimitry Andric             ") => %i",
43214f1b3e8SDimitry Andric             (uint64_t)addr, success);
433f034231aSEd Maste   return success;
434f034231aSEd Maste }
435