Path: blob/main/contrib/llvm-project/lldb/source/Target/Memory.cpp
39587 views
//===-- Memory.cpp --------------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "lldb/Target/Memory.h"9#include "lldb/Target/Process.h"10#include "lldb/Utility/DataBufferHeap.h"11#include "lldb/Utility/LLDBLog.h"12#include "lldb/Utility/Log.h"13#include "lldb/Utility/RangeMap.h"14#include "lldb/Utility/State.h"1516#include <cinttypes>17#include <memory>1819using namespace lldb;20using namespace lldb_private;2122// MemoryCache constructor23MemoryCache::MemoryCache(Process &process)24: m_mutex(), m_L1_cache(), m_L2_cache(), m_invalid_ranges(),25m_process(process),26m_L2_cache_line_byte_size(process.GetMemoryCacheLineSize()) {}2728// Destructor29MemoryCache::~MemoryCache() = default;3031void MemoryCache::Clear(bool clear_invalid_ranges) {32std::lock_guard<std::recursive_mutex> guard(m_mutex);33m_L1_cache.clear();34m_L2_cache.clear();35if (clear_invalid_ranges)36m_invalid_ranges.Clear();37m_L2_cache_line_byte_size = m_process.GetMemoryCacheLineSize();38}3940void MemoryCache::AddL1CacheData(lldb::addr_t addr, const void *src,41size_t src_len) {42AddL1CacheData(43addr, DataBufferSP(new DataBufferHeap(DataBufferHeap(src, src_len))));44}4546void MemoryCache::AddL1CacheData(lldb::addr_t addr,47const DataBufferSP &data_buffer_sp) {48std::lock_guard<std::recursive_mutex> guard(m_mutex);49m_L1_cache[addr] = data_buffer_sp;50}5152void MemoryCache::Flush(addr_t addr, size_t size) {53if (size == 0)54return;5556std::lock_guard<std::recursive_mutex> guard(m_mutex);5758// Erase any blocks from the L1 cache that intersect with the flush range59if (!m_L1_cache.empty()) {60AddrRange flush_range(addr, size);61BlockMap::iterator pos = m_L1_cache.upper_bound(addr);62if (pos != m_L1_cache.begin()) {63--pos;64}65while (pos != m_L1_cache.end()) {66AddrRange chunk_range(pos->first, pos->second->GetByteSize());67if (!chunk_range.DoesIntersect(flush_range))68break;69pos = m_L1_cache.erase(pos);70}71}7273if (!m_L2_cache.empty()) {74const uint32_t cache_line_byte_size = m_L2_cache_line_byte_size;75const addr_t end_addr = (addr + size - 1);76const addr_t first_cache_line_addr = addr - (addr % cache_line_byte_size);77const addr_t last_cache_line_addr =78end_addr - (end_addr % cache_line_byte_size);79// Watch for overflow where size will cause us to go off the end of the80// 64 bit address space81uint32_t num_cache_lines;82if (last_cache_line_addr >= first_cache_line_addr)83num_cache_lines = ((last_cache_line_addr - first_cache_line_addr) /84cache_line_byte_size) +851;86else87num_cache_lines =88(UINT64_MAX - first_cache_line_addr + 1) / cache_line_byte_size;8990uint32_t cache_idx = 0;91for (addr_t curr_addr = first_cache_line_addr; cache_idx < num_cache_lines;92curr_addr += cache_line_byte_size, ++cache_idx) {93BlockMap::iterator pos = m_L2_cache.find(curr_addr);94if (pos != m_L2_cache.end())95m_L2_cache.erase(pos);96}97}98}99100void MemoryCache::AddInvalidRange(lldb::addr_t base_addr,101lldb::addr_t byte_size) {102if (byte_size > 0) {103std::lock_guard<std::recursive_mutex> guard(m_mutex);104InvalidRanges::Entry range(base_addr, byte_size);105m_invalid_ranges.Append(range);106m_invalid_ranges.Sort();107}108}109110bool MemoryCache::RemoveInvalidRange(lldb::addr_t base_addr,111lldb::addr_t byte_size) {112if (byte_size > 0) {113std::lock_guard<std::recursive_mutex> guard(m_mutex);114const uint32_t idx = m_invalid_ranges.FindEntryIndexThatContains(base_addr);115if (idx != UINT32_MAX) {116const InvalidRanges::Entry *entry = m_invalid_ranges.GetEntryAtIndex(idx);117if (entry->GetRangeBase() == base_addr &&118entry->GetByteSize() == byte_size)119return m_invalid_ranges.RemoveEntryAtIndex(idx);120}121}122return false;123}124125lldb::DataBufferSP MemoryCache::GetL2CacheLine(lldb::addr_t line_base_addr,126Status &error) {127// This function assumes that the address given is aligned correctly.128assert((line_base_addr % m_L2_cache_line_byte_size) == 0);129130std::lock_guard<std::recursive_mutex> guard(m_mutex);131auto pos = m_L2_cache.find(line_base_addr);132if (pos != m_L2_cache.end())133return pos->second;134135auto data_buffer_heap_sp =136std::make_shared<DataBufferHeap>(m_L2_cache_line_byte_size, 0);137size_t process_bytes_read = m_process.ReadMemoryFromInferior(138line_base_addr, data_buffer_heap_sp->GetBytes(),139data_buffer_heap_sp->GetByteSize(), error);140141// If we failed a read, not much we can do.142if (process_bytes_read == 0)143return lldb::DataBufferSP();144145// If we didn't get a complete read, we can still cache what we did get.146if (process_bytes_read < m_L2_cache_line_byte_size)147data_buffer_heap_sp->SetByteSize(process_bytes_read);148149m_L2_cache[line_base_addr] = data_buffer_heap_sp;150return data_buffer_heap_sp;151}152153size_t MemoryCache::Read(addr_t addr, void *dst, size_t dst_len,154Status &error) {155if (!dst || dst_len == 0)156return 0;157158std::lock_guard<std::recursive_mutex> guard(m_mutex);159// FIXME: We should do a more thorough check to make sure that we're not160// overlapping with any invalid ranges (e.g. Read 0x100 - 0x200 but there's an161// invalid range 0x180 - 0x280). `FindEntryThatContains` has an implementation162// that takes a range, but it only checks to see if the argument is contained163// by an existing invalid range. It cannot check if the argument contains164// invalid ranges and cannot check for overlaps.165if (m_invalid_ranges.FindEntryThatContains(addr)) {166error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);167return 0;168}169170// Check the L1 cache for a range that contains the entire memory read.171// L1 cache contains chunks of memory that are not required to be the size of172// an L2 cache line. We avoid trying to do partial reads from the L1 cache to173// simplify the implementation.174if (!m_L1_cache.empty()) {175AddrRange read_range(addr, dst_len);176BlockMap::iterator pos = m_L1_cache.upper_bound(addr);177if (pos != m_L1_cache.begin()) {178--pos;179}180AddrRange chunk_range(pos->first, pos->second->GetByteSize());181if (chunk_range.Contains(read_range)) {182memcpy(dst, pos->second->GetBytes() + (addr - chunk_range.GetRangeBase()),183dst_len);184return dst_len;185}186}187188// If the size of the read is greater than the size of an L2 cache line, we'll189// just read from the inferior. If that read is successful, we'll cache what190// we read in the L1 cache for future use.191if (dst_len > m_L2_cache_line_byte_size) {192size_t bytes_read =193m_process.ReadMemoryFromInferior(addr, dst, dst_len, error);194if (bytes_read > 0)195AddL1CacheData(addr, dst, bytes_read);196return bytes_read;197}198199// If the size of the read fits inside one L2 cache line, we'll try reading200// from the L2 cache. Note that if the range of memory we're reading sits201// between two contiguous cache lines, we'll touch two cache lines instead of202// just one.203204// We're going to have all of our loads and reads be cache line aligned.205addr_t cache_line_offset = addr % m_L2_cache_line_byte_size;206addr_t cache_line_base_addr = addr - cache_line_offset;207DataBufferSP first_cache_line = GetL2CacheLine(cache_line_base_addr, error);208// If we get nothing, then the read to the inferior likely failed. Nothing to209// do here.210if (!first_cache_line)211return 0;212213// If the cache line was not filled out completely and the offset is greater214// than what we have available, we can't do anything further here.215if (cache_line_offset >= first_cache_line->GetByteSize())216return 0;217218uint8_t *dst_buf = (uint8_t *)dst;219size_t bytes_left = dst_len;220size_t read_size = first_cache_line->GetByteSize() - cache_line_offset;221if (read_size > bytes_left)222read_size = bytes_left;223224memcpy(dst_buf + dst_len - bytes_left,225first_cache_line->GetBytes() + cache_line_offset, read_size);226bytes_left -= read_size;227228// If the cache line was not filled out completely and we still have data to229// read, we can't do anything further.230if (first_cache_line->GetByteSize() < m_L2_cache_line_byte_size &&231bytes_left > 0)232return dst_len - bytes_left;233234// We'll hit this scenario if our read straddles two cache lines.235if (bytes_left > 0) {236cache_line_base_addr += m_L2_cache_line_byte_size;237238// FIXME: Until we are able to more thoroughly check for invalid ranges, we239// will have to check the second line to see if it is in an invalid range as240// well. See the check near the beginning of the function for more details.241if (m_invalid_ranges.FindEntryThatContains(cache_line_base_addr)) {242error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64,243cache_line_base_addr);244return dst_len - bytes_left;245}246247DataBufferSP second_cache_line =248GetL2CacheLine(cache_line_base_addr, error);249if (!second_cache_line)250return dst_len - bytes_left;251252read_size = bytes_left;253if (read_size > second_cache_line->GetByteSize())254read_size = second_cache_line->GetByteSize();255256memcpy(dst_buf + dst_len - bytes_left, second_cache_line->GetBytes(),257read_size);258bytes_left -= read_size;259260return dst_len - bytes_left;261}262263return dst_len;264}265266AllocatedBlock::AllocatedBlock(lldb::addr_t addr, uint32_t byte_size,267uint32_t permissions, uint32_t chunk_size)268: m_range(addr, byte_size), m_permissions(permissions),269m_chunk_size(chunk_size)270{271// The entire address range is free to start with.272m_free_blocks.Append(m_range);273assert(byte_size > chunk_size);274}275276AllocatedBlock::~AllocatedBlock() = default;277278lldb::addr_t AllocatedBlock::ReserveBlock(uint32_t size) {279// We must return something valid for zero bytes.280if (size == 0)281size = 1;282Log *log = GetLog(LLDBLog::Process);283284const size_t free_count = m_free_blocks.GetSize();285for (size_t i=0; i<free_count; ++i)286{287auto &free_block = m_free_blocks.GetEntryRef(i);288const lldb::addr_t range_size = free_block.GetByteSize();289if (range_size >= size)290{291// We found a free block that is big enough for our data. Figure out how292// many chunks we will need and calculate the resulting block size we293// will reserve.294addr_t addr = free_block.GetRangeBase();295size_t num_chunks = CalculateChunksNeededForSize(size);296lldb::addr_t block_size = num_chunks * m_chunk_size;297lldb::addr_t bytes_left = range_size - block_size;298if (bytes_left == 0)299{300// The newly allocated block will take all of the bytes in this301// available block, so we can just add it to the allocated ranges and302// remove the range from the free ranges.303m_reserved_blocks.Insert(free_block, false);304m_free_blocks.RemoveEntryAtIndex(i);305}306else307{308// Make the new allocated range and add it to the allocated ranges.309Range<lldb::addr_t, uint32_t> reserved_block(free_block);310reserved_block.SetByteSize(block_size);311// Insert the reserved range and don't combine it with other blocks in312// the reserved blocks list.313m_reserved_blocks.Insert(reserved_block, false);314// Adjust the free range in place since we won't change the sorted315// ordering of the m_free_blocks list.316free_block.SetRangeBase(reserved_block.GetRangeEnd());317free_block.SetByteSize(bytes_left);318}319LLDB_LOGV(log, "({0}) (size = {1} ({1:x})) => {2:x}", this, size, addr);320return addr;321}322}323324LLDB_LOGV(log, "({0}) (size = {1} ({1:x})) => {2:x}", this, size,325LLDB_INVALID_ADDRESS);326return LLDB_INVALID_ADDRESS;327}328329bool AllocatedBlock::FreeBlock(addr_t addr) {330bool success = false;331auto entry_idx = m_reserved_blocks.FindEntryIndexThatContains(addr);332if (entry_idx != UINT32_MAX)333{334m_free_blocks.Insert(m_reserved_blocks.GetEntryRef(entry_idx), true);335m_reserved_blocks.RemoveEntryAtIndex(entry_idx);336success = true;337}338Log *log = GetLog(LLDBLog::Process);339LLDB_LOGV(log, "({0}) (addr = {1:x}) => {2}", this, addr, success);340return success;341}342343AllocatedMemoryCache::AllocatedMemoryCache(Process &process)344: m_process(process), m_mutex(), m_memory_map() {}345346AllocatedMemoryCache::~AllocatedMemoryCache() = default;347348void AllocatedMemoryCache::Clear(bool deallocate_memory) {349std::lock_guard<std::recursive_mutex> guard(m_mutex);350if (m_process.IsAlive() && deallocate_memory) {351PermissionsToBlockMap::iterator pos, end = m_memory_map.end();352for (pos = m_memory_map.begin(); pos != end; ++pos)353m_process.DoDeallocateMemory(pos->second->GetBaseAddress());354}355m_memory_map.clear();356}357358AllocatedMemoryCache::AllocatedBlockSP359AllocatedMemoryCache::AllocatePage(uint32_t byte_size, uint32_t permissions,360uint32_t chunk_size, Status &error) {361AllocatedBlockSP block_sp;362const size_t page_size = 4096;363const size_t num_pages = (byte_size + page_size - 1) / page_size;364const size_t page_byte_size = num_pages * page_size;365366addr_t addr = m_process.DoAllocateMemory(page_byte_size, permissions, error);367368Log *log = GetLog(LLDBLog::Process);369if (log) {370LLDB_LOGF(log,371"Process::DoAllocateMemory (byte_size = 0x%8.8" PRIx32372", permissions = %s) => 0x%16.16" PRIx64,373(uint32_t)page_byte_size, GetPermissionsAsCString(permissions),374(uint64_t)addr);375}376377if (addr != LLDB_INVALID_ADDRESS) {378block_sp = std::make_shared<AllocatedBlock>(addr, page_byte_size,379permissions, chunk_size);380m_memory_map.insert(std::make_pair(permissions, block_sp));381}382return block_sp;383}384385lldb::addr_t AllocatedMemoryCache::AllocateMemory(size_t byte_size,386uint32_t permissions,387Status &error) {388std::lock_guard<std::recursive_mutex> guard(m_mutex);389390addr_t addr = LLDB_INVALID_ADDRESS;391std::pair<PermissionsToBlockMap::iterator, PermissionsToBlockMap::iterator>392range = m_memory_map.equal_range(permissions);393394for (PermissionsToBlockMap::iterator pos = range.first; pos != range.second;395++pos) {396addr = (*pos).second->ReserveBlock(byte_size);397if (addr != LLDB_INVALID_ADDRESS)398break;399}400401if (addr == LLDB_INVALID_ADDRESS) {402AllocatedBlockSP block_sp(AllocatePage(byte_size, permissions, 16, error));403404if (block_sp)405addr = block_sp->ReserveBlock(byte_size);406}407Log *log = GetLog(LLDBLog::Process);408LLDB_LOGF(log,409"AllocatedMemoryCache::AllocateMemory (byte_size = 0x%8.8" PRIx32410", permissions = %s) => 0x%16.16" PRIx64,411(uint32_t)byte_size, GetPermissionsAsCString(permissions),412(uint64_t)addr);413return addr;414}415416bool AllocatedMemoryCache::DeallocateMemory(lldb::addr_t addr) {417std::lock_guard<std::recursive_mutex> guard(m_mutex);418419PermissionsToBlockMap::iterator pos, end = m_memory_map.end();420bool success = false;421for (pos = m_memory_map.begin(); pos != end; ++pos) {422if (pos->second->Contains(addr)) {423success = pos->second->FreeBlock(addr);424break;425}426}427Log *log = GetLog(LLDBLog::Process);428LLDB_LOGF(log,429"AllocatedMemoryCache::DeallocateMemory (addr = 0x%16.16" PRIx64430") => %i",431(uint64_t)addr, success);432return success;433}434435436