Memory.cpp revision 360784
140090Smsmith//===-- Memory.cpp ----------------------------------------------*- C++ -*-===// 240090Smsmith// 340090Smsmith// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 440090Smsmith// See https://llvm.org/LICENSE.txt for license information. 540090Smsmith// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 640090Smsmith// 740090Smsmith//===----------------------------------------------------------------------===// 840090Smsmith 940090Smsmith#include "lldb/Target/Memory.h" 1040090Smsmith#include "lldb/Target/Process.h" 1140090Smsmith#include "lldb/Utility/DataBufferHeap.h" 1240090Smsmith#include "lldb/Utility/Log.h" 1340090Smsmith#include "lldb/Utility/RangeMap.h" 1440090Smsmith#include "lldb/Utility/State.h" 1540090Smsmith 1640090Smsmith#include <cinttypes> 1740090Smsmith#include <memory> 1840090Smsmith 1940090Smsmithusing namespace lldb; 2040090Smsmithusing namespace lldb_private; 2140090Smsmith 2240090Smsmith// MemoryCache constructor 2340090SmsmithMemoryCache::MemoryCache(Process &process) 2440090Smsmith : m_mutex(), m_L1_cache(), m_L2_cache(), m_invalid_ranges(), 2540116Sjkh m_process(process), 2640090Smsmith m_L2_cache_line_byte_size(process.GetMemoryCacheLineSize()) {} 2740090Smsmith 2840090Smsmith// Destructor 2994936SmuxMemoryCache::~MemoryCache() {} 3094936Smux 3140090Smsmithvoid MemoryCache::Clear(bool clear_invalid_ranges) { 3294936Smux std::lock_guard<std::recursive_mutex> guard(m_mutex); 3394936Smux m_L1_cache.clear(); 3494936Smux m_L2_cache.clear(); 3540090Smsmith if (clear_invalid_ranges) 3640090Smsmith m_invalid_ranges.Clear(); 37116182Sobrien m_L2_cache_line_byte_size = m_process.GetMemoryCacheLineSize(); 38116182Sobrien} 39116182Sobrien 40106308Srwatsonvoid MemoryCache::AddL1CacheData(lldb::addr_t addr, const void *src, 41106308Srwatson size_t src_len) { 4294936Smux AddL1CacheData( 4340090Smsmith addr, DataBufferSP(new DataBufferHeap(DataBufferHeap(src, src_len)))); 4494936Smux} 4594936Smux 4694936Smuxvoid MemoryCache::AddL1CacheData(lldb::addr_t addr, 47106308Srwatson const DataBufferSP &data_buffer_sp) { 4894936Smux std::lock_guard<std::recursive_mutex> guard(m_mutex); 4994936Smux m_L1_cache[addr] = data_buffer_sp; 5040090Smsmith} 5194936Smux 5240090Smsmithvoid MemoryCache::Flush(addr_t addr, size_t size) { 5394936Smux if (size == 0) 5494936Smux return; 5540090Smsmith 5694936Smux std::lock_guard<std::recursive_mutex> guard(m_mutex); 5740090Smsmith 5894936Smux // Erase any blocks from the L1 cache that intersect with the flush range 5940090Smsmith if (!m_L1_cache.empty()) { 6094936Smux AddrRange flush_range(addr, size); 6140090Smsmith BlockMap::iterator pos = m_L1_cache.upper_bound(addr); 6294936Smux if (pos != m_L1_cache.begin()) { 6394936Smux --pos; 6494936Smux } 6594936Smux while (pos != m_L1_cache.end()) { 6694936Smux AddrRange chunk_range(pos->first, pos->second->GetByteSize()); 6794936Smux if (!chunk_range.DoesIntersect(flush_range)) 6894936Smux break; 6994936Smux pos = m_L1_cache.erase(pos); 7085385Sjhb } 7194936Smux } 7294936Smux 7394936Smux if (!m_L2_cache.empty()) { 7494936Smux const uint32_t cache_line_byte_size = m_L2_cache_line_byte_size; 7594936Smux const addr_t end_addr = (addr + size - 1); 7694936Smux const addr_t first_cache_line_addr = addr - (addr % cache_line_byte_size); 7794936Smux const addr_t last_cache_line_addr = 7894936Smux end_addr - (end_addr % cache_line_byte_size); 7994936Smux // Watch for overflow where size will cause us to go off the end of the 8094936Smux // 64 bit address space 8194936Smux uint32_t num_cache_lines; 8294936Smux if (last_cache_line_addr >= first_cache_line_addr) 83107850Salfred num_cache_lines = ((last_cache_line_addr - first_cache_line_addr) / 84107850Salfred cache_line_byte_size) + 85107850Salfred 1; 86107850Salfred else 8794936Smux num_cache_lines = 8894936Smux (UINT64_MAX - first_cache_line_addr + 1) / cache_line_byte_size; 8994936Smux 90128697Sdas uint32_t cache_idx = 0; 9194936Smux for (addr_t curr_addr = first_cache_line_addr; cache_idx < num_cache_lines; 9295839Speter curr_addr += cache_line_byte_size, ++cache_idx) { 9394936Smux BlockMap::iterator pos = m_L2_cache.find(curr_addr); 9494936Smux if (pos != m_L2_cache.end()) 9594936Smux m_L2_cache.erase(pos); 96107849Salfred } 97106308Srwatson } 98106308Srwatson} 99106308Srwatson 100106308Srwatsonvoid MemoryCache::AddInvalidRange(lldb::addr_t base_addr, 101106308Srwatson lldb::addr_t byte_size) { 102128697Sdas if (byte_size > 0) { 10394936Smux std::lock_guard<std::recursive_mutex> guard(m_mutex); 104128697Sdas InvalidRanges::Entry range(base_addr, byte_size); 105128697Sdas m_invalid_ranges.Append(range); 106128697Sdas m_invalid_ranges.Sort(); 107128697Sdas } 108128697Sdas} 109128697Sdas 110128697Sdasbool MemoryCache::RemoveInvalidRange(lldb::addr_t base_addr, 111128697Sdas lldb::addr_t byte_size) { 112128697Sdas if (byte_size > 0) { 113128697Sdas std::lock_guard<std::recursive_mutex> guard(m_mutex); 114128697Sdas const uint32_t idx = m_invalid_ranges.FindEntryIndexThatContains(base_addr); 115128697Sdas if (idx != UINT32_MAX) { 116128697Sdas const InvalidRanges::Entry *entry = m_invalid_ranges.GetEntryAtIndex(idx); 117128697Sdas if (entry->GetRangeBase() == base_addr && 11894936Smux entry->GetByteSize() == byte_size) 11994936Smux return m_invalid_ranges.RemoveEntrtAtIndex(idx); 12094936Smux } 121128697Sdas } 122128697Sdas return false; 12394936Smux} 12494936Smux 125107849Salfredsize_t MemoryCache::Read(addr_t addr, void *dst, size_t dst_len, 126107849Salfred Status &error) { 12794936Smux size_t bytes_left = dst_len; 12894936Smux 12994936Smux // Check the L1 cache for a range that contain the entire memory read. If we 13094936Smux // find a range in the L1 cache that does, we use it. Else we fall back to 13194936Smux // reading memory in m_L2_cache_line_byte_size byte sized chunks. The L1 132111119Simp // cache contains chunks of memory that are not required to be 13394936Smux // m_L2_cache_line_byte_size bytes in size, so we don't try anything tricky 134107849Salfred // when reading from them (no partial reads from the L1 cache). 13594936Smux 13694936Smux std::lock_guard<std::recursive_mutex> guard(m_mutex); 13794936Smux if (!m_L1_cache.empty()) { 138107849Salfred AddrRange read_range(addr, dst_len); 13994936Smux BlockMap::iterator pos = m_L1_cache.upper_bound(addr); 140106308Srwatson if (pos != m_L1_cache.begin()) { 141106308Srwatson --pos; 142106308Srwatson } 143106308Srwatson AddrRange chunk_range(pos->first, pos->second->GetByteSize()); 144106308Srwatson if (chunk_range.Contains(read_range)) { 14594936Smux memcpy(dst, pos->second->GetBytes() + (addr - chunk_range.GetRangeBase()), 14694936Smux dst_len); 14794936Smux return dst_len; 14894936Smux } 14994936Smux } 15094936Smux 151107849Salfred // If this memory read request is larger than the cache line size, then we 152107849Salfred // (1) try to read as much of it at once as possible, and (2) don't add the 153107849Salfred // data to the memory cache. We don't want to split a big read up into more 15494936Smux // separate reads than necessary, and with a large memory read request, it is 15594936Smux // unlikely that the caller function will ask for the next 15694936Smux // 4 bytes after the large memory read - so there's little benefit to saving 15794936Smux // it in the cache. 15894936Smux if (dst && dst_len > m_L2_cache_line_byte_size) { 15994936Smux size_t bytes_read = 160107849Salfred m_process.ReadMemoryFromInferior(addr, dst, dst_len, error); 16194936Smux // Add this non block sized range to the L1 cache if we actually read 16294936Smux // anything 16394936Smux if (bytes_read > 0) 16494936Smux AddL1CacheData(addr, dst, bytes_read); 16594936Smux return bytes_read; 16694936Smux } 167111119Simp 168107849Salfred if (dst && bytes_left > 0) { 16994936Smux const uint32_t cache_line_byte_size = m_L2_cache_line_byte_size; 17094936Smux uint8_t *dst_buf = (uint8_t *)dst; 17194936Smux addr_t curr_addr = addr - (addr % cache_line_byte_size); 17294936Smux addr_t cache_offset = addr - curr_addr; 173106308Srwatson 174106308Srwatson while (bytes_left > 0) { 175106308Srwatson if (m_invalid_ranges.FindEntryThatContains(curr_addr)) { 176106308Srwatson error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, 177106308Srwatson curr_addr); 17894936Smux return dst_len - bytes_left; 17994936Smux } 18094936Smux 181106308Srwatson BlockMap::const_iterator pos = m_L2_cache.find(curr_addr); 182106308Srwatson BlockMap::const_iterator end = m_L2_cache.end(); 183106308Srwatson 184106308Srwatson if (pos != end) { 185106308Srwatson size_t curr_read_size = cache_line_byte_size - cache_offset; 18694936Smux if (curr_read_size > bytes_left) 18794936Smux curr_read_size = bytes_left; 18894936Smux 18994936Smux memcpy(dst_buf + dst_len - bytes_left, 19094936Smux pos->second->GetBytes() + cache_offset, curr_read_size); 19194936Smux 19294936Smux bytes_left -= curr_read_size; 19394936Smux curr_addr += curr_read_size + cache_offset; 19494936Smux cache_offset = 0; 19594936Smux 19694936Smux if (bytes_left > 0) { 19794936Smux // Get sequential cache page hits 19894936Smux for (++pos; (pos != end) && (bytes_left > 0); ++pos) { 19994936Smux assert((curr_addr % cache_line_byte_size) == 0); 20094936Smux 20194936Smux if (pos->first != curr_addr) 20294936Smux break; 20394936Smux 20494936Smux curr_read_size = pos->second->GetByteSize(); 20594936Smux if (curr_read_size > bytes_left) 20694936Smux curr_read_size = bytes_left; 20794936Smux 208111119Simp memcpy(dst_buf + dst_len - bytes_left, pos->second->GetBytes(), 20994936Smux curr_read_size); 21094936Smux 21194936Smux bytes_left -= curr_read_size; 212111119Simp curr_addr += curr_read_size; 21394936Smux 21494936Smux // We have a cache page that succeeded to read some bytes but not 21594936Smux // an entire page. If this happens, we must cap off how much data 21694936Smux // we are able to read... 21794936Smux if (pos->second->GetByteSize() != cache_line_byte_size) 21894936Smux return dst_len - bytes_left; 21994936Smux } 22094936Smux } 22194936Smux } 22294936Smux 22394936Smux // We need to read from the process 22494936Smux 22594936Smux if (bytes_left > 0) { 22694936Smux assert((curr_addr % cache_line_byte_size) == 0); 22794936Smux std::unique_ptr<DataBufferHeap> data_buffer_heap_up( 22894936Smux new DataBufferHeap(cache_line_byte_size, 0)); 22994936Smux size_t process_bytes_read = m_process.ReadMemoryFromInferior( 23094936Smux curr_addr, data_buffer_heap_up->GetBytes(), 23194936Smux data_buffer_heap_up->GetByteSize(), error); 23294936Smux if (process_bytes_read == 0) 23394936Smux return dst_len - bytes_left; 23494936Smux 23594936Smux if (process_bytes_read != cache_line_byte_size) 23694936Smux data_buffer_heap_up->SetByteSize(process_bytes_read); 23794936Smux m_L2_cache[curr_addr] = DataBufferSP(data_buffer_heap_up.release()); 23894936Smux // We have read data and put it into the cache, continue through the 23994936Smux // loop again to get the data out of the cache... 24094936Smux } 24194936Smux } 24294936Smux } 24394936Smux 24494936Smux return dst_len - bytes_left; 24594936Smux} 24694936Smux 24794936SmuxAllocatedBlock::AllocatedBlock(lldb::addr_t addr, uint32_t byte_size, 24894936Smux uint32_t permissions, uint32_t chunk_size) 24994936Smux : m_range(addr, byte_size), m_permissions(permissions), 25094936Smux m_chunk_size(chunk_size) 25194936Smux{ 25294936Smux // The entire address range is free to start with. 25394936Smux m_free_blocks.Append(m_range); 25494936Smux assert(byte_size > chunk_size); 25594936Smux} 25694936Smux 25794936SmuxAllocatedBlock::~AllocatedBlock() {} 25894936Smux 25994936Smuxlldb::addr_t AllocatedBlock::ReserveBlock(uint32_t size) { 26094936Smux // We must return something valid for zero bytes. 26195467Sbde if (size == 0) 26295467Sbde size = 1; 26394936Smux Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 26495467Sbde 26595467Sbde const size_t free_count = m_free_blocks.GetSize(); 26694936Smux for (size_t i=0; i<free_count; ++i) 26794936Smux { 26894936Smux auto &free_block = m_free_blocks.GetEntryRef(i); 26994936Smux const lldb::addr_t range_size = free_block.GetByteSize(); 27094936Smux if (range_size >= size) 27194936Smux { 27285385Sjhb // We found a free block that is big enough for our data. Figure out how 27394936Smux // many chunks we will need and calculate the resulting block size we 27494936Smux // will reserve. 27594936Smux addr_t addr = free_block.GetRangeBase(); 27685385Sjhb size_t num_chunks = CalculateChunksNeededForSize(size); 27740090Smsmith lldb::addr_t block_size = num_chunks * m_chunk_size; 27878247Speter lldb::addr_t bytes_left = range_size - block_size; 27940090Smsmith if (bytes_left == 0) 28094959Smux { 28194936Smux // The newly allocated block will take all of the bytes in this 28294936Smux // available block, so we can just add it to the allocated ranges and 28394936Smux // remove the range from the free ranges. 28494936Smux m_reserved_blocks.Insert(free_block, false); 28594936Smux m_free_blocks.RemoveEntryAtIndex(i); 28694936Smux } 28794936Smux else 28894959Smux { 28994959Smux // Make the new allocated range and add it to the allocated ranges. 29094959Smux Range<lldb::addr_t, uint32_t> reserved_block(free_block); 291111119Simp reserved_block.SetByteSize(block_size); 29294959Smux // Insert the reserved range and don't combine it with other blocks in 29394959Smux // the reserved blocks list. 29494959Smux m_reserved_blocks.Insert(reserved_block, false); 29594936Smux // Adjust the free range in place since we won't change the sorted 29694959Smux // ordering of the m_free_blocks list. 29794936Smux free_block.SetRangeBase(reserved_block.GetRangeEnd()); 29894936Smux free_block.SetByteSize(bytes_left); 29994936Smux } 30040090Smsmith LLDB_LOGV(log, "({0}) (size = {1} ({1:x})) => {2:x}", this, size, addr); 30140090Smsmith return addr; 30242706Smsmith } 30394936Smux } 30494936Smux 30594936Smux LLDB_LOGV(log, "({0}) (size = {1} ({1:x})) => {2:x}", this, size, 30694936Smux LLDB_INVALID_ADDRESS); 30794936Smux return LLDB_INVALID_ADDRESS; 30894936Smux} 30994936Smux 31094936Smuxbool AllocatedBlock::FreeBlock(addr_t addr) { 31194936Smux bool success = false; 31294936Smux auto entry_idx = m_reserved_blocks.FindEntryIndexThatContains(addr); 31394936Smux if (entry_idx != UINT32_MAX) 31494936Smux { 31594936Smux m_free_blocks.Insert(m_reserved_blocks.GetEntryRef(entry_idx), true); 31694936Smux m_reserved_blocks.RemoveEntryAtIndex(entry_idx); 31794936Smux success = true; 31894936Smux } 31994936Smux Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 32094936Smux LLDB_LOGV(log, "({0}) (addr = {1:x}) => {2}", this, addr, success); 32194936Smux return success; 32294936Smux} 32394936Smux 32494959SmuxAllocatedMemoryCache::AllocatedMemoryCache(Process &process) 32594936Smux : m_process(process), m_mutex(), m_memory_map() {} 32694936Smux 32794959SmuxAllocatedMemoryCache::~AllocatedMemoryCache() {} 32894959Smux 32994936Smuxvoid AllocatedMemoryCache::Clear() { 33094936Smux std::lock_guard<std::recursive_mutex> guard(m_mutex); 33194936Smux if (m_process.IsAlive()) { 33294959Smux PermissionsToBlockMap::iterator pos, end = m_memory_map.end(); 33394959Smux for (pos = m_memory_map.begin(); pos != end; ++pos) 33494959Smux m_process.DoDeallocateMemory(pos->second->GetBaseAddress()); 33594959Smux } 33694959Smux m_memory_map.clear(); 33794959Smux} 338111119Simp 33994936SmuxAllocatedMemoryCache::AllocatedBlockSP 34094936SmuxAllocatedMemoryCache::AllocatePage(uint32_t byte_size, uint32_t permissions, 34194936Smux uint32_t chunk_size, Status &error) { 34294936Smux AllocatedBlockSP block_sp; 34394936Smux const size_t page_size = 4096; 34494959Smux const size_t num_pages = (byte_size + page_size - 1) / page_size; 34594936Smux const size_t page_byte_size = num_pages * page_size; 34694959Smux 34794959Smux addr_t addr = m_process.DoAllocateMemory(page_byte_size, permissions, error); 34894936Smux 34994936Smux Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 35094936Smux if (log) { 35194936Smux LLDB_LOGF(log, 35294936Smux "Process::DoAllocateMemory (byte_size = 0x%8.8" PRIx32 35394936Smux ", permissions = %s) => 0x%16.16" PRIx64, 35494959Smux (uint32_t)page_byte_size, GetPermissionsAsCString(permissions), 35594936Smux (uint64_t)addr); 35694959Smux } 35794936Smux 35894936Smux if (addr != LLDB_INVALID_ADDRESS) { 35994936Smux block_sp = std::make_shared<AllocatedBlock>(addr, page_byte_size, 36094936Smux permissions, chunk_size); 36194936Smux m_memory_map.insert(std::make_pair(permissions, block_sp)); 36294936Smux } 36394936Smux return block_sp; 36494936Smux} 36594959Smux 36694936Smuxlldb::addr_t AllocatedMemoryCache::AllocateMemory(size_t byte_size, 36794936Smux uint32_t permissions, 36894936Smux Status &error) { 36994936Smux std::lock_guard<std::recursive_mutex> guard(m_mutex); 37094936Smux 37194936Smux addr_t addr = LLDB_INVALID_ADDRESS; 37294936Smux std::pair<PermissionsToBlockMap::iterator, PermissionsToBlockMap::iterator> 37394959Smux range = m_memory_map.equal_range(permissions); 37494936Smux 37594936Smux for (PermissionsToBlockMap::iterator pos = range.first; pos != range.second; 37694936Smux ++pos) { 37794936Smux addr = (*pos).second->ReserveBlock(byte_size); 37894959Smux if (addr != LLDB_INVALID_ADDRESS) 37994936Smux break; 38094936Smux } 38194936Smux 38294936Smux if (addr == LLDB_INVALID_ADDRESS) { 38394936Smux AllocatedBlockSP block_sp(AllocatePage(byte_size, permissions, 16, error)); 38494936Smux 38594936Smux if (block_sp) 38685385Sjhb addr = block_sp->ReserveBlock(byte_size); 38785385Sjhb } 38885385Sjhb Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 38985385Sjhb LLDB_LOGF(log, 39085385Sjhb "AllocatedMemoryCache::AllocateMemory (byte_size = 0x%8.8" PRIx32 39195839Speter ", permissions = %s) => 0x%16.16" PRIx64, 39285385Sjhb (uint32_t)byte_size, GetPermissionsAsCString(permissions), 39395839Speter (uint64_t)addr); 39495839Speter return addr; 395105354Srobert} 39695839Speter 39795839Speterbool AllocatedMemoryCache::DeallocateMemory(lldb::addr_t addr) { 39895839Speter std::lock_guard<std::recursive_mutex> guard(m_mutex); 39995839Speter 40085385Sjhb PermissionsToBlockMap::iterator pos, end = m_memory_map.end(); 40185385Sjhb bool success = false; 40285385Sjhb for (pos = m_memory_map.begin(); pos != end; ++pos) { 40342706Smsmith if (pos->second->Contains(addr)) { 40442706Smsmith success = pos->second->FreeBlock(addr); 40542706Smsmith break; 40678247Speter } 40742706Smsmith } 40895839Speter Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 40995839Speter LLDB_LOGF(log, 41052947Smjacob "AllocatedMemoryCache::DeallocateMemory (addr = 0x%16.16" PRIx64 41195839Speter ") => %i", 41295839Speter (uint64_t)addr, success); 41395839Speter return success; 41495839Speter} 41552947Smjacob