1 //===-- Memory.cpp ----------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/Target/Memory.h"
14 // Other libraries and framework includes
16 #include "lldb/Core/DataBufferHeap.h"
17 #include "lldb/Core/State.h"
18 #include "lldb/Core/Log.h"
19 #include "lldb/Target/Process.h"
22 using namespace lldb_private;
24 //----------------------------------------------------------------------
25 // MemoryCache constructor
26 //----------------------------------------------------------------------
27 MemoryCache::MemoryCache(Process &process) :
29 m_cache_line_byte_size (512),
30 m_mutex (Mutex::eMutexTypeRecursive),
36 //----------------------------------------------------------------------
38 //----------------------------------------------------------------------
39 MemoryCache::~MemoryCache()
44 MemoryCache::Clear(bool clear_invalid_ranges)
46 Mutex::Locker locker (m_mutex);
48 if (clear_invalid_ranges)
49 m_invalid_ranges.Clear();
53 MemoryCache::Flush (addr_t addr, size_t size)
58 Mutex::Locker locker (m_mutex);
62 const uint32_t cache_line_byte_size = m_cache_line_byte_size;
63 const addr_t end_addr = (addr + size - 1);
64 const addr_t first_cache_line_addr = addr - (addr % cache_line_byte_size);
65 const addr_t last_cache_line_addr = end_addr - (end_addr % cache_line_byte_size);
66 // Watch for overflow where size will cause us to go off the end of the
67 // 64 bit address space
68 uint32_t num_cache_lines;
69 if (last_cache_line_addr >= first_cache_line_addr)
70 num_cache_lines = ((last_cache_line_addr - first_cache_line_addr)/cache_line_byte_size) + 1;
72 num_cache_lines = (UINT64_MAX - first_cache_line_addr + 1)/cache_line_byte_size;
74 uint32_t cache_idx = 0;
75 for (addr_t curr_addr = first_cache_line_addr;
76 cache_idx < num_cache_lines;
77 curr_addr += cache_line_byte_size, ++cache_idx)
79 BlockMap::iterator pos = m_cache.find (curr_addr);
80 if (pos != m_cache.end())
86 MemoryCache::AddInvalidRange (lldb::addr_t base_addr, lldb::addr_t byte_size)
90 Mutex::Locker locker (m_mutex);
91 InvalidRanges::Entry range (base_addr, byte_size);
92 m_invalid_ranges.Append(range);
93 m_invalid_ranges.Sort();
98 MemoryCache::RemoveInvalidRange (lldb::addr_t base_addr, lldb::addr_t byte_size)
102 Mutex::Locker locker (m_mutex);
103 const uint32_t idx = m_invalid_ranges.FindEntryIndexThatContains(base_addr);
104 if (idx != UINT32_MAX)
106 const InvalidRanges::Entry *entry = m_invalid_ranges.GetEntryAtIndex (idx);
107 if (entry->GetRangeBase() == base_addr && entry->GetByteSize() == byte_size)
108 return m_invalid_ranges.RemoveEntrtAtIndex (idx);
117 MemoryCache::Read (addr_t addr,
122 size_t bytes_left = dst_len;
124 // If this memory read request is larger than the cache line size, then
125 // we (1) try to read as much of it at once as possible, and (2) don't
126 // add the data to the memory cache. We don't want to split a big read
127 // up into more separate reads than necessary, and with a large memory read
128 // request, it is unlikely that the caller function will ask for the next
129 // 4 bytes after the large memory read - so there's little benefit to saving
131 if (dst && dst_len > m_cache_line_byte_size)
133 return m_process.ReadMemoryFromInferior (addr, dst, dst_len, error);
136 if (dst && bytes_left > 0)
138 const uint32_t cache_line_byte_size = m_cache_line_byte_size;
139 uint8_t *dst_buf = (uint8_t *)dst;
140 addr_t curr_addr = addr - (addr % cache_line_byte_size);
141 addr_t cache_offset = addr - curr_addr;
142 Mutex::Locker locker (m_mutex);
144 while (bytes_left > 0)
146 if (m_invalid_ranges.FindEntryThatContains(curr_addr))
148 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, curr_addr);
149 return dst_len - bytes_left;
152 BlockMap::const_iterator pos = m_cache.find (curr_addr);
153 BlockMap::const_iterator end = m_cache.end ();
157 size_t curr_read_size = cache_line_byte_size - cache_offset;
158 if (curr_read_size > bytes_left)
159 curr_read_size = bytes_left;
161 memcpy (dst_buf + dst_len - bytes_left, pos->second->GetBytes() + cache_offset, curr_read_size);
163 bytes_left -= curr_read_size;
164 curr_addr += curr_read_size + cache_offset;
169 // Get sequential cache page hits
170 for (++pos; (pos != end) && (bytes_left > 0); ++pos)
172 assert ((curr_addr % cache_line_byte_size) == 0);
174 if (pos->first != curr_addr)
177 curr_read_size = pos->second->GetByteSize();
178 if (curr_read_size > bytes_left)
179 curr_read_size = bytes_left;
181 memcpy (dst_buf + dst_len - bytes_left, pos->second->GetBytes(), curr_read_size);
183 bytes_left -= curr_read_size;
184 curr_addr += curr_read_size;
186 // We have a cache page that succeeded to read some bytes
187 // but not an entire page. If this happens, we must cap
188 // off how much data we are able to read...
189 if (pos->second->GetByteSize() != cache_line_byte_size)
190 return dst_len - bytes_left;
195 // We need to read from the process
199 assert ((curr_addr % cache_line_byte_size) == 0);
200 std::unique_ptr<DataBufferHeap> data_buffer_heap_ap(new DataBufferHeap (cache_line_byte_size, 0));
201 size_t process_bytes_read = m_process.ReadMemoryFromInferior (curr_addr,
202 data_buffer_heap_ap->GetBytes(),
203 data_buffer_heap_ap->GetByteSize(),
205 if (process_bytes_read == 0)
206 return dst_len - bytes_left;
208 if (process_bytes_read != cache_line_byte_size)
209 data_buffer_heap_ap->SetByteSize (process_bytes_read);
210 m_cache[curr_addr] = DataBufferSP (data_buffer_heap_ap.release());
211 // We have read data and put it into the cache, continue through the
212 // loop again to get the data out of the cache...
217 return dst_len - bytes_left;
222 AllocatedBlock::AllocatedBlock (lldb::addr_t addr,
224 uint32_t permissions,
225 uint32_t chunk_size) :
227 m_byte_size (byte_size),
228 m_permissions (permissions),
229 m_chunk_size (chunk_size),
230 m_offset_to_chunk_size ()
231 // m_allocated (byte_size / chunk_size)
233 assert (byte_size > chunk_size);
236 AllocatedBlock::~AllocatedBlock ()
241 AllocatedBlock::ReserveBlock (uint32_t size)
243 addr_t addr = LLDB_INVALID_ADDRESS;
244 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE));
245 if (size <= m_byte_size)
247 const uint32_t needed_chunks = CalculateChunksNeededForSize (size);
249 if (m_offset_to_chunk_size.empty())
251 m_offset_to_chunk_size[0] = needed_chunks;
253 log->Printf ("[1] AllocatedBlock::ReserveBlock(%p) (size = %u (0x%x)) => offset = 0x%x, %u %u bit chunks", this, size, size, 0, needed_chunks, m_chunk_size);
258 uint32_t last_offset = 0;
259 OffsetToChunkSize::const_iterator pos = m_offset_to_chunk_size.begin();
260 OffsetToChunkSize::const_iterator end = m_offset_to_chunk_size.end();
263 if (pos->first > last_offset)
265 const uint32_t bytes_available = pos->first - last_offset;
266 const uint32_t num_chunks = CalculateChunksNeededForSize (bytes_available);
267 if (num_chunks >= needed_chunks)
269 m_offset_to_chunk_size[last_offset] = needed_chunks;
271 log->Printf ("[2] AllocatedBlock::ReserveBlock(%p) (size = %u (0x%x)) => offset = 0x%x, %u %u bit chunks - num_chunks %lu", this, size, size, last_offset, needed_chunks, m_chunk_size, m_offset_to_chunk_size.size());
272 addr = m_addr + last_offset;
277 last_offset = pos->first + pos->second * m_chunk_size;
282 const uint32_t chunks_left = CalculateChunksNeededForSize (m_byte_size - last_offset);
283 if (chunks_left >= needed_chunks)
285 m_offset_to_chunk_size[last_offset] = needed_chunks;
287 log->Printf ("[3] AllocatedBlock::ReserveBlock(%p) (size = %u (0x%x)) => offset = 0x%x, %u %u bit chunks - num_chunks %lu", this, size, size, last_offset, needed_chunks, m_chunk_size, m_offset_to_chunk_size.size());
288 addr = m_addr + last_offset;
294 // const uint32_t total_chunks = m_allocated.size ();
295 // uint32_t unallocated_idx = 0;
296 // uint32_t allocated_idx = m_allocated.find_first();
297 // uint32_t first_chunk_idx = UINT32_MAX;
298 // uint32_t num_chunks;
301 // if (allocated_idx == UINT32_MAX)
303 // // No more bits are set starting from unallocated_idx, so we
304 // // either have enough chunks for the request, or we don't.
305 // // Eiter way we break out of the while loop...
306 // num_chunks = total_chunks - unallocated_idx;
307 // if (needed_chunks <= num_chunks)
308 // first_chunk_idx = unallocated_idx;
311 // else if (allocated_idx > unallocated_idx)
313 // // We have some allocated chunks, check if there are enough
314 // // free chunks to satisfy the request?
315 // num_chunks = allocated_idx - unallocated_idx;
316 // if (needed_chunks <= num_chunks)
318 // // Yep, we have enough!
319 // first_chunk_idx = unallocated_idx;
324 // while (unallocated_idx < total_chunks)
326 // if (m_allocated[unallocated_idx])
327 // ++unallocated_idx;
332 // if (unallocated_idx >= total_chunks)
335 // allocated_idx = m_allocated.find_next(unallocated_idx);
338 // if (first_chunk_idx != UINT32_MAX)
340 // const uint32_t end_bit_idx = unallocated_idx + needed_chunks;
341 // for (uint32_t idx = first_chunk_idx; idx < end_bit_idx; ++idx)
342 // m_allocated.set(idx);
343 // return m_addr + m_chunk_size * first_chunk_idx;
348 log->Printf ("AllocatedBlock::ReserveBlock(%p) (size = %u (0x%x)) => 0x%16.16" PRIx64, this, size, size, (uint64_t)addr);
353 AllocatedBlock::FreeBlock (addr_t addr)
355 uint32_t offset = addr - m_addr;
356 OffsetToChunkSize::iterator pos = m_offset_to_chunk_size.find (offset);
357 bool success = false;
358 if (pos != m_offset_to_chunk_size.end())
360 m_offset_to_chunk_size.erase (pos);
363 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE));
365 log->Printf ("AllocatedBlock::FreeBlock(%p) (addr = 0x%16.16" PRIx64 ") => %i, num_chunks: %lu", this, (uint64_t)addr, success, m_offset_to_chunk_size.size());
370 AllocatedMemoryCache::AllocatedMemoryCache (Process &process) :
372 m_mutex (Mutex::eMutexTypeRecursive),
377 AllocatedMemoryCache::~AllocatedMemoryCache ()
383 AllocatedMemoryCache::Clear()
385 Mutex::Locker locker (m_mutex);
386 if (m_process.IsAlive())
388 PermissionsToBlockMap::iterator pos, end = m_memory_map.end();
389 for (pos = m_memory_map.begin(); pos != end; ++pos)
390 m_process.DoDeallocateMemory(pos->second->GetBaseAddress());
392 m_memory_map.clear();
396 AllocatedMemoryCache::AllocatedBlockSP
397 AllocatedMemoryCache::AllocatePage (uint32_t byte_size,
398 uint32_t permissions,
402 AllocatedBlockSP block_sp;
403 const size_t page_size = 4096;
404 const size_t num_pages = (byte_size + page_size - 1) / page_size;
405 const size_t page_byte_size = num_pages * page_size;
407 addr_t addr = m_process.DoAllocateMemory(page_byte_size, permissions, error);
409 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
412 log->Printf ("Process::DoAllocateMemory (byte_size = 0x%8.8" PRIx32 ", permissions = %s) => 0x%16.16" PRIx64,
413 (uint32_t)page_byte_size,
414 GetPermissionsAsCString(permissions),
418 if (addr != LLDB_INVALID_ADDRESS)
420 block_sp.reset (new AllocatedBlock (addr, page_byte_size, permissions, chunk_size));
421 m_memory_map.insert (std::make_pair (permissions, block_sp));
427 AllocatedMemoryCache::AllocateMemory (size_t byte_size,
428 uint32_t permissions,
431 Mutex::Locker locker (m_mutex);
433 addr_t addr = LLDB_INVALID_ADDRESS;
434 std::pair<PermissionsToBlockMap::iterator, PermissionsToBlockMap::iterator> range = m_memory_map.equal_range (permissions);
436 for (PermissionsToBlockMap::iterator pos = range.first; pos != range.second; ++pos)
438 addr = (*pos).second->ReserveBlock (byte_size);
439 if (addr != LLDB_INVALID_ADDRESS)
443 if (addr == LLDB_INVALID_ADDRESS)
445 AllocatedBlockSP block_sp (AllocatePage (byte_size, permissions, 16, error));
448 addr = block_sp->ReserveBlock (byte_size);
450 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
452 log->Printf ("AllocatedMemoryCache::AllocateMemory (byte_size = 0x%8.8" PRIx32 ", permissions = %s) => 0x%16.16" PRIx64, (uint32_t)byte_size, GetPermissionsAsCString(permissions), (uint64_t)addr);
457 AllocatedMemoryCache::DeallocateMemory (lldb::addr_t addr)
459 Mutex::Locker locker (m_mutex);
461 PermissionsToBlockMap::iterator pos, end = m_memory_map.end();
462 bool success = false;
463 for (pos = m_memory_map.begin(); pos != end; ++pos)
465 if (pos->second->Contains (addr))
467 success = pos->second->FreeBlock (addr);
471 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
473 log->Printf("AllocatedMemoryCache::DeallocateMemory (addr = 0x%16.16" PRIx64 ") => %i", (uint64_t)addr, success);