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 (Mutex::eMutexTypeRecursive),
30     m_L1_cache (),
31     m_L2_cache (),
32     m_invalid_ranges (),
33     m_process (process),
34     m_L2_cache_line_byte_size (process.GetMemoryCacheLineSize())
35 {
36 }
37 
38 //----------------------------------------------------------------------
39 // Destructor
40 //----------------------------------------------------------------------
41 MemoryCache::~MemoryCache()
42 {
43 }
44 
45 void
46 MemoryCache::Clear(bool clear_invalid_ranges)
47 {
48     Mutex::Locker locker (m_mutex);
49     m_L1_cache.clear();
50     m_L2_cache.clear();
51     if (clear_invalid_ranges)
52         m_invalid_ranges.Clear();
53     m_L2_cache_line_byte_size = m_process.GetMemoryCacheLineSize();
54 }
55 
56 void
57 MemoryCache::AddL1CacheData(lldb::addr_t addr, const void *src, size_t src_len)
58 {
59     AddL1CacheData(addr,DataBufferSP (new DataBufferHeap(DataBufferHeap(src, src_len))));
60 }
61 
62 void
63 MemoryCache::AddL1CacheData(lldb::addr_t addr, const DataBufferSP &data_buffer_sp)
64 {
65     Mutex::Locker locker (m_mutex);
66     m_L1_cache[addr] = data_buffer_sp;
67 }
68 
69 void
70 MemoryCache::Flush (addr_t addr, size_t size)
71 {
72     if (size == 0)
73         return;
74 
75     Mutex::Locker locker (m_mutex);
76 
77     // Erase any blocks from the L1 cache that intersect with the flush range
78     if (!m_L1_cache.empty())
79     {
80         AddrRange flush_range(addr, size);
81         BlockMap::iterator pos = m_L1_cache.lower_bound(addr);
82         while (pos != m_L1_cache.end())
83         {
84             AddrRange chunk_range(pos->first, pos->second->GetByteSize());
85             if (!chunk_range.DoesIntersect(flush_range))
86                 break;
87             pos = m_L1_cache.erase(pos);
88         }
89     }
90 
91     if (!m_L2_cache.empty())
92     {
93         const uint32_t cache_line_byte_size = m_L2_cache_line_byte_size;
94         const addr_t end_addr = (addr + size - 1);
95         const addr_t first_cache_line_addr = addr - (addr % cache_line_byte_size);
96         const addr_t last_cache_line_addr = end_addr - (end_addr % cache_line_byte_size);
97         // Watch for overflow where size will cause us to go off the end of the
98         // 64 bit address space
99         uint32_t num_cache_lines;
100         if (last_cache_line_addr >= first_cache_line_addr)
101             num_cache_lines = ((last_cache_line_addr - first_cache_line_addr)/cache_line_byte_size) + 1;
102         else
103             num_cache_lines = (UINT64_MAX - first_cache_line_addr + 1)/cache_line_byte_size;
104 
105         uint32_t cache_idx = 0;
106         for (addr_t curr_addr = first_cache_line_addr;
107              cache_idx < num_cache_lines;
108              curr_addr += cache_line_byte_size, ++cache_idx)
109         {
110             BlockMap::iterator pos = m_L2_cache.find (curr_addr);
111             if (pos != m_L2_cache.end())
112                 m_L2_cache.erase(pos);
113         }
114     }
115 }
116 
117 void
118 MemoryCache::AddInvalidRange (lldb::addr_t base_addr, lldb::addr_t byte_size)
119 {
120     if (byte_size > 0)
121     {
122         Mutex::Locker locker (m_mutex);
123         InvalidRanges::Entry range (base_addr, byte_size);
124         m_invalid_ranges.Append(range);
125         m_invalid_ranges.Sort();
126     }
127 }
128 
129 bool
130 MemoryCache::RemoveInvalidRange (lldb::addr_t base_addr, lldb::addr_t byte_size)
131 {
132     if (byte_size > 0)
133     {
134         Mutex::Locker locker (m_mutex);
135         const uint32_t idx = m_invalid_ranges.FindEntryIndexThatContains(base_addr);
136         if (idx != UINT32_MAX)
137         {
138             const InvalidRanges::Entry *entry = m_invalid_ranges.GetEntryAtIndex (idx);
139             if (entry->GetRangeBase() == base_addr && entry->GetByteSize() == byte_size)
140                 return m_invalid_ranges.RemoveEntrtAtIndex (idx);
141         }
142     }
143     return false;
144 }
145 
146 
147 
148 size_t
149 MemoryCache::Read (addr_t addr,
150                    void *dst,
151                    size_t dst_len,
152                    Error &error)
153 {
154     size_t bytes_left = dst_len;
155 
156     // Check the L1 cache for a range that contain the entire memory read.
157     // If we find a range in the L1 cache that does, we use it. Else we fall
158     // back to reading memory in m_L2_cache_line_byte_size byte sized chunks.
159     // The L1 cache contains chunks of memory that are not required to be
160     // m_L2_cache_line_byte_size bytes in size, so we don't try anything
161     // tricky when reading from them (no partial reads from the L1 cache).
162 
163     Mutex::Locker locker(m_mutex);
164     if (!m_L1_cache.empty())
165     {
166         AddrRange read_range(addr, dst_len);
167         BlockMap::iterator pos = m_L1_cache.lower_bound(addr);
168         if (pos != m_L1_cache.end())
169         {
170             AddrRange chunk_range(pos->first, pos->second->GetByteSize());
171             bool match = chunk_range.Contains(read_range);
172             if (!match && pos != m_L1_cache.begin())
173             {
174                 --pos;
175                 chunk_range.SetRangeBase(pos->first);
176                 chunk_range.SetByteSize(pos->second->GetByteSize());
177                 match = chunk_range.Contains(read_range);
178             }
179 
180             if (match)
181             {
182                 memcpy(dst, pos->second->GetBytes() + addr - chunk_range.GetRangeBase(), dst_len);
183                 return dst_len;
184             }
185         }
186     }
187 
188 
189     // If this memory read request is larger than the cache line size, then
190     // we (1) try to read as much of it at once as possible, and (2) don't
191     // add the data to the memory cache.  We don't want to split a big read
192     // up into more separate reads than necessary, and with a large memory read
193     // request, it is unlikely that the caller function will ask for the next
194     // 4 bytes after the large memory read - so there's little benefit to saving
195     // it in the cache.
196     if (dst && dst_len > m_L2_cache_line_byte_size)
197     {
198         size_t bytes_read = m_process.ReadMemoryFromInferior (addr, dst, dst_len, error);
199         // Add this non block sized range to the L1 cache if we actually read anything
200         if (bytes_read > 0)
201             AddL1CacheData(addr, dst, bytes_read);
202         return bytes_read;
203     }
204 
205     if (dst && bytes_left > 0)
206     {
207         const uint32_t cache_line_byte_size = m_L2_cache_line_byte_size;
208         uint8_t *dst_buf = (uint8_t *)dst;
209         addr_t curr_addr = addr - (addr % cache_line_byte_size);
210         addr_t cache_offset = addr - curr_addr;
211 
212         while (bytes_left > 0)
213         {
214             if (m_invalid_ranges.FindEntryThatContains(curr_addr))
215             {
216                 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, curr_addr);
217                 return dst_len - bytes_left;
218             }
219 
220             BlockMap::const_iterator pos = m_L2_cache.find (curr_addr);
221             BlockMap::const_iterator end = m_L2_cache.end ();
222 
223             if (pos != end)
224             {
225                 size_t curr_read_size = cache_line_byte_size - cache_offset;
226                 if (curr_read_size > bytes_left)
227                     curr_read_size = bytes_left;
228 
229                 memcpy (dst_buf + dst_len - bytes_left, pos->second->GetBytes() + cache_offset, curr_read_size);
230 
231                 bytes_left -= curr_read_size;
232                 curr_addr += curr_read_size + cache_offset;
233                 cache_offset = 0;
234 
235                 if (bytes_left > 0)
236                 {
237                     // Get sequential cache page hits
238                     for (++pos; (pos != end) && (bytes_left > 0); ++pos)
239                     {
240                         assert ((curr_addr % cache_line_byte_size) == 0);
241 
242                         if (pos->first != curr_addr)
243                             break;
244 
245                         curr_read_size = pos->second->GetByteSize();
246                         if (curr_read_size > bytes_left)
247                             curr_read_size = bytes_left;
248 
249                         memcpy (dst_buf + dst_len - bytes_left, pos->second->GetBytes(), curr_read_size);
250 
251                         bytes_left -= curr_read_size;
252                         curr_addr += curr_read_size;
253 
254                         // We have a cache page that succeeded to read some bytes
255                         // but not an entire page. If this happens, we must cap
256                         // off how much data we are able to read...
257                         if (pos->second->GetByteSize() != cache_line_byte_size)
258                             return dst_len - bytes_left;
259                     }
260                 }
261             }
262 
263             // We need to read from the process
264 
265             if (bytes_left > 0)
266             {
267                 assert ((curr_addr % cache_line_byte_size) == 0);
268                 std::unique_ptr<DataBufferHeap> data_buffer_heap_ap(new DataBufferHeap (cache_line_byte_size, 0));
269                 size_t process_bytes_read = m_process.ReadMemoryFromInferior (curr_addr,
270                                                                               data_buffer_heap_ap->GetBytes(),
271                                                                               data_buffer_heap_ap->GetByteSize(),
272                                                                               error);
273                 if (process_bytes_read == 0)
274                     return dst_len - bytes_left;
275 
276                 if (process_bytes_read != cache_line_byte_size)
277                     data_buffer_heap_ap->SetByteSize (process_bytes_read);
278                 m_L2_cache[curr_addr] = DataBufferSP (data_buffer_heap_ap.release());
279                 // We have read data and put it into the cache, continue through the
280                 // loop again to get the data out of the cache...
281             }
282         }
283     }
284 
285     return dst_len - bytes_left;
286 }
287 
288 
289 
290 AllocatedBlock::AllocatedBlock (lldb::addr_t addr,
291                                 uint32_t byte_size,
292                                 uint32_t permissions,
293                                 uint32_t chunk_size) :
294     m_addr (addr),
295     m_byte_size (byte_size),
296     m_permissions (permissions),
297     m_chunk_size (chunk_size),
298     m_offset_to_chunk_size ()
299 //    m_allocated (byte_size / chunk_size)
300 {
301     assert (byte_size > chunk_size);
302 }
303 
304 AllocatedBlock::~AllocatedBlock ()
305 {
306 }
307 
308 lldb::addr_t
309 AllocatedBlock::ReserveBlock (uint32_t size)
310 {
311     addr_t addr = LLDB_INVALID_ADDRESS;
312     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE));
313     if (size <= m_byte_size)
314     {
315         const uint32_t needed_chunks = CalculateChunksNeededForSize (size);
316 
317         if (m_offset_to_chunk_size.empty())
318         {
319             m_offset_to_chunk_size[0] = needed_chunks;
320             if (log)
321                 log->Printf("[1] AllocatedBlock::ReserveBlock(%p) (size = %u (0x%x)) => offset = 0x%x, %u %u bit chunks", (void *)this,
322                             size, size, 0, needed_chunks, m_chunk_size);
323             addr = m_addr;
324         }
325         else
326         {
327             uint32_t last_offset = 0;
328             OffsetToChunkSize::const_iterator pos = m_offset_to_chunk_size.begin();
329             OffsetToChunkSize::const_iterator end = m_offset_to_chunk_size.end();
330             while (pos != end)
331             {
332                 if (pos->first > last_offset)
333                 {
334                     const uint32_t bytes_available = pos->first - last_offset;
335                     const uint32_t num_chunks = CalculateChunksNeededForSize (bytes_available);
336                     if (num_chunks >= needed_chunks)
337                     {
338                         m_offset_to_chunk_size[last_offset] = needed_chunks;
339                         if (log)
340                             log->Printf("[2] AllocatedBlock::ReserveBlock(%p) (size = %u (0x%x)) => offset = 0x%x, %u %u bit chunks - "
341                                         "num_chunks %lu",
342                                         (void *)this, size, size, last_offset, needed_chunks, m_chunk_size, m_offset_to_chunk_size.size());
343                         addr = m_addr + last_offset;
344                         break;
345                     }
346                 }
347 
348                 last_offset = pos->first + pos->second * m_chunk_size;
349 
350                 if (++pos == end)
351                 {
352                     // Last entry...
353                     const uint32_t chunks_left = CalculateChunksNeededForSize (m_byte_size - last_offset);
354                     if (chunks_left >= needed_chunks)
355                     {
356                         m_offset_to_chunk_size[last_offset] = needed_chunks;
357                         if (log)
358                             log->Printf("[3] AllocatedBlock::ReserveBlock(%p) (size = %u (0x%x)) => offset = 0x%x, %u %u bit chunks - "
359                                         "num_chunks %lu",
360                                         (void *)this, size, size, last_offset, needed_chunks, m_chunk_size, m_offset_to_chunk_size.size());
361                         addr = m_addr + last_offset;
362                         break;
363                     }
364                 }
365             }
366         }
367 //        const uint32_t total_chunks = m_allocated.size ();
368 //        uint32_t unallocated_idx = 0;
369 //        uint32_t allocated_idx = m_allocated.find_first();
370 //        uint32_t first_chunk_idx = UINT32_MAX;
371 //        uint32_t num_chunks;
372 //        while (1)
373 //        {
374 //            if (allocated_idx == UINT32_MAX)
375 //            {
376 //                // No more bits are set starting from unallocated_idx, so we
377 //                // either have enough chunks for the request, or we don't.
378 //                // Eiter way we break out of the while loop...
379 //                num_chunks = total_chunks - unallocated_idx;
380 //                if (needed_chunks <= num_chunks)
381 //                    first_chunk_idx = unallocated_idx;
382 //                break;
383 //            }
384 //            else if (allocated_idx > unallocated_idx)
385 //            {
386 //                // We have some allocated chunks, check if there are enough
387 //                // free chunks to satisfy the request?
388 //                num_chunks = allocated_idx - unallocated_idx;
389 //                if (needed_chunks <= num_chunks)
390 //                {
391 //                    // Yep, we have enough!
392 //                    first_chunk_idx = unallocated_idx;
393 //                    break;
394 //                }
395 //            }
396 //
397 //            while (unallocated_idx < total_chunks)
398 //            {
399 //                if (m_allocated[unallocated_idx])
400 //                    ++unallocated_idx;
401 //                else
402 //                    break;
403 //            }
404 //
405 //            if (unallocated_idx >= total_chunks)
406 //                break;
407 //
408 //            allocated_idx = m_allocated.find_next(unallocated_idx);
409 //        }
410 //
411 //        if (first_chunk_idx != UINT32_MAX)
412 //        {
413 //            const uint32_t end_bit_idx = unallocated_idx + needed_chunks;
414 //            for (uint32_t idx = first_chunk_idx; idx < end_bit_idx; ++idx)
415 //                m_allocated.set(idx);
416 //            return m_addr + m_chunk_size * first_chunk_idx;
417 //        }
418     }
419 
420     if (log)
421         log->Printf("AllocatedBlock::ReserveBlock(%p) (size = %u (0x%x)) => 0x%16.16" PRIx64, (void *)this, size, size, (uint64_t)addr);
422     return addr;
423 }
424 
425 bool
426 AllocatedBlock::FreeBlock (addr_t addr)
427 {
428     uint32_t offset = addr - m_addr;
429     OffsetToChunkSize::iterator pos = m_offset_to_chunk_size.find (offset);
430     bool success = false;
431     if (pos != m_offset_to_chunk_size.end())
432     {
433         m_offset_to_chunk_size.erase (pos);
434         success = true;
435     }
436     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE));
437     if (log)
438         log->Printf("AllocatedBlock::FreeBlock(%p) (addr = 0x%16.16" PRIx64 ") => %i, num_chunks: %lu", (void *)this, (uint64_t)addr,
439                     success, m_offset_to_chunk_size.size());
440     return success;
441 }
442 
443 
444 AllocatedMemoryCache::AllocatedMemoryCache (Process &process) :
445     m_process (process),
446     m_mutex (Mutex::eMutexTypeRecursive),
447     m_memory_map()
448 {
449 }
450 
451 AllocatedMemoryCache::~AllocatedMemoryCache ()
452 {
453 }
454 
455 
456 void
457 AllocatedMemoryCache::Clear()
458 {
459     Mutex::Locker locker (m_mutex);
460     if (m_process.IsAlive())
461     {
462         PermissionsToBlockMap::iterator pos, end = m_memory_map.end();
463         for (pos = m_memory_map.begin(); pos != end; ++pos)
464             m_process.DoDeallocateMemory(pos->second->GetBaseAddress());
465     }
466     m_memory_map.clear();
467 }
468 
469 
470 AllocatedMemoryCache::AllocatedBlockSP
471 AllocatedMemoryCache::AllocatePage (uint32_t byte_size,
472                                     uint32_t permissions,
473                                     uint32_t chunk_size,
474                                     Error &error)
475 {
476     AllocatedBlockSP block_sp;
477     const size_t page_size = 4096;
478     const size_t num_pages = (byte_size + page_size - 1) / page_size;
479     const size_t page_byte_size = num_pages * page_size;
480 
481     addr_t addr = m_process.DoAllocateMemory(page_byte_size, permissions, error);
482 
483     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
484     if (log)
485     {
486         log->Printf ("Process::DoAllocateMemory (byte_size = 0x%8.8" PRIx32 ", permissions = %s) => 0x%16.16" PRIx64,
487                      (uint32_t)page_byte_size,
488                      GetPermissionsAsCString(permissions),
489                      (uint64_t)addr);
490     }
491 
492     if (addr != LLDB_INVALID_ADDRESS)
493     {
494         block_sp.reset (new AllocatedBlock (addr, page_byte_size, permissions, chunk_size));
495         m_memory_map.insert (std::make_pair (permissions, block_sp));
496     }
497     return block_sp;
498 }
499 
500 lldb::addr_t
501 AllocatedMemoryCache::AllocateMemory (size_t byte_size,
502                                       uint32_t permissions,
503                                       Error &error)
504 {
505     Mutex::Locker locker (m_mutex);
506 
507     addr_t addr = LLDB_INVALID_ADDRESS;
508     std::pair<PermissionsToBlockMap::iterator, PermissionsToBlockMap::iterator> range = m_memory_map.equal_range (permissions);
509 
510     for (PermissionsToBlockMap::iterator pos = range.first; pos != range.second; ++pos)
511     {
512         addr = (*pos).second->ReserveBlock (byte_size);
513         if (addr != LLDB_INVALID_ADDRESS)
514             break;
515     }
516 
517     if (addr == LLDB_INVALID_ADDRESS)
518     {
519         AllocatedBlockSP block_sp (AllocatePage (byte_size, permissions, 16, error));
520 
521         if (block_sp)
522             addr = block_sp->ReserveBlock (byte_size);
523     }
524     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
525     if (log)
526         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);
527     return addr;
528 }
529 
530 bool
531 AllocatedMemoryCache::DeallocateMemory (lldb::addr_t addr)
532 {
533     Mutex::Locker locker (m_mutex);
534 
535     PermissionsToBlockMap::iterator pos, end = m_memory_map.end();
536     bool success = false;
537     for (pos = m_memory_map.begin(); pos != end; ++pos)
538     {
539         if (pos->second->Contains (addr))
540         {
541             success = pos->second->FreeBlock (addr);
542             break;
543         }
544     }
545     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
546     if (log)
547         log->Printf("AllocatedMemoryCache::DeallocateMemory (addr = 0x%16.16" PRIx64 ") => %i", (uint64_t)addr, success);
548     return success;
549 }
550 
551 
552