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/State.h"
18 #include "lldb/Core/Log.h"
19 #include "lldb/Target/Process.h"
20 
21 using namespace lldb;
22 using namespace lldb_private;
23 
24 //----------------------------------------------------------------------
25 // MemoryCache constructor
26 //----------------------------------------------------------------------
27 MemoryCache::MemoryCache(Process &process) :
28     m_process (process),
29     m_cache_line_byte_size (512),
30     m_mutex (Mutex::eMutexTypeRecursive),
31     m_cache (),
32     m_invalid_ranges ()
33 {
34 }
35 
36 //----------------------------------------------------------------------
37 // Destructor
38 //----------------------------------------------------------------------
39 MemoryCache::~MemoryCache()
40 {
41 }
42 
43 void
44 MemoryCache::Clear(bool clear_invalid_ranges)
45 {
46     Mutex::Locker locker (m_mutex);
47     m_cache.clear();
48     if (clear_invalid_ranges)
49         m_invalid_ranges.Clear();
50 }
51 
52 void
53 MemoryCache::Flush (addr_t addr, size_t size)
54 {
55     if (size == 0)
56         return;
57 
58     Mutex::Locker locker (m_mutex);
59     if (m_cache.empty())
60         return;
61 
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;
71     else
72         num_cache_lines = (UINT64_MAX - first_cache_line_addr + 1)/cache_line_byte_size;
73 
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)
78     {
79         BlockMap::iterator pos = m_cache.find (curr_addr);
80         if (pos != m_cache.end())
81             m_cache.erase(pos);
82     }
83 }
84 
85 void
86 MemoryCache::AddInvalidRange (lldb::addr_t base_addr, lldb::addr_t byte_size)
87 {
88     if (byte_size > 0)
89     {
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();
94     }
95 }
96 
97 bool
98 MemoryCache::RemoveInvalidRange (lldb::addr_t base_addr, lldb::addr_t byte_size)
99 {
100     if (byte_size > 0)
101     {
102         Mutex::Locker locker (m_mutex);
103         const uint32_t idx = m_invalid_ranges.FindEntryIndexThatContains(base_addr);
104         if (idx != UINT32_MAX)
105         {
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);
109         }
110     }
111     return false;
112 }
113 
114 
115 
116 size_t
117 MemoryCache::Read (addr_t addr,
118                    void *dst,
119                    size_t dst_len,
120                    Error &error)
121 {
122     size_t bytes_left = dst_len;
123     if (dst && bytes_left > 0)
124     {
125         const uint32_t cache_line_byte_size = m_cache_line_byte_size;
126         uint8_t *dst_buf = (uint8_t *)dst;
127         addr_t curr_addr = addr - (addr % cache_line_byte_size);
128         addr_t cache_offset = addr - curr_addr;
129         Mutex::Locker locker (m_mutex);
130 
131         while (bytes_left > 0)
132         {
133             if (m_invalid_ranges.FindEntryThatContains(curr_addr))
134             {
135                 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, curr_addr);
136                 return dst_len - bytes_left;
137             }
138 
139             BlockMap::const_iterator pos = m_cache.find (curr_addr);
140             BlockMap::const_iterator end = m_cache.end ();
141 
142             if (pos != end)
143             {
144                 size_t curr_read_size = cache_line_byte_size - cache_offset;
145                 if (curr_read_size > bytes_left)
146                     curr_read_size = bytes_left;
147 
148                 memcpy (dst_buf + dst_len - bytes_left, pos->second->GetBytes() + cache_offset, curr_read_size);
149 
150                 bytes_left -= curr_read_size;
151                 curr_addr += curr_read_size + cache_offset;
152                 cache_offset = 0;
153 
154                 if (bytes_left > 0)
155                 {
156                     // Get sequential cache page hits
157                     for (++pos; (pos != end) && (bytes_left > 0); ++pos)
158                     {
159                         assert ((curr_addr % cache_line_byte_size) == 0);
160 
161                         if (pos->first != curr_addr)
162                             break;
163 
164                         curr_read_size = pos->second->GetByteSize();
165                         if (curr_read_size > bytes_left)
166                             curr_read_size = bytes_left;
167 
168                         memcpy (dst_buf + dst_len - bytes_left, pos->second->GetBytes(), curr_read_size);
169 
170                         bytes_left -= curr_read_size;
171                         curr_addr += curr_read_size;
172 
173                         // We have a cache page that succeeded to read some bytes
174                         // but not an entire page. If this happens, we must cap
175                         // off how much data we are able to read...
176                         if (pos->second->GetByteSize() != cache_line_byte_size)
177                             return dst_len - bytes_left;
178                     }
179                 }
180             }
181 
182             // We need to read from the process
183 
184             if (bytes_left > 0)
185             {
186                 assert ((curr_addr % cache_line_byte_size) == 0);
187                 std::unique_ptr<DataBufferHeap> data_buffer_heap_ap(new DataBufferHeap (cache_line_byte_size, 0));
188                 size_t process_bytes_read = m_process.ReadMemoryFromInferior (curr_addr,
189                                                                               data_buffer_heap_ap->GetBytes(),
190                                                                               data_buffer_heap_ap->GetByteSize(),
191                                                                               error);
192                 if (process_bytes_read == 0)
193                     return dst_len - bytes_left;
194 
195                 if (process_bytes_read != cache_line_byte_size)
196                     data_buffer_heap_ap->SetByteSize (process_bytes_read);
197                 m_cache[curr_addr] = DataBufferSP (data_buffer_heap_ap.release());
198                 // We have read data and put it into the cache, continue through the
199                 // loop again to get the data out of the cache...
200             }
201         }
202     }
203 
204     return dst_len - bytes_left;
205 }
206 
207 
208 
209 AllocatedBlock::AllocatedBlock (lldb::addr_t addr,
210                                 uint32_t byte_size,
211                                 uint32_t permissions,
212                                 uint32_t chunk_size) :
213     m_addr (addr),
214     m_byte_size (byte_size),
215     m_permissions (permissions),
216     m_chunk_size (chunk_size),
217     m_offset_to_chunk_size ()
218 //    m_allocated (byte_size / chunk_size)
219 {
220     assert (byte_size > chunk_size);
221 }
222 
223 AllocatedBlock::~AllocatedBlock ()
224 {
225 }
226 
227 lldb::addr_t
228 AllocatedBlock::ReserveBlock (uint32_t size)
229 {
230     addr_t addr = LLDB_INVALID_ADDRESS;
231     if (size <= m_byte_size)
232     {
233         const uint32_t needed_chunks = CalculateChunksNeededForSize (size);
234         Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE));
235 
236         if (m_offset_to_chunk_size.empty())
237         {
238             m_offset_to_chunk_size[0] = needed_chunks;
239             if (log)
240                 log->Printf ("[1] AllocatedBlock::ReserveBlock (size = %u (0x%x)) => offset = 0x%x, %u %u bit chunks", size, size, 0, needed_chunks, m_chunk_size);
241             addr = m_addr;
242         }
243         else
244         {
245             uint32_t last_offset = 0;
246             OffsetToChunkSize::const_iterator pos = m_offset_to_chunk_size.begin();
247             OffsetToChunkSize::const_iterator end = m_offset_to_chunk_size.end();
248             while (pos != end)
249             {
250                 if (pos->first > last_offset)
251                 {
252                     const uint32_t bytes_available = pos->first - last_offset;
253                     const uint32_t num_chunks = CalculateChunksNeededForSize (bytes_available);
254                     if (num_chunks >= needed_chunks)
255                     {
256                         m_offset_to_chunk_size[last_offset] = needed_chunks;
257                         if (log)
258                             log->Printf ("[2] AllocatedBlock::ReserveBlock (size = %u (0x%x)) => offset = 0x%x, %u %u bit chunks", size, size, last_offset, needed_chunks, m_chunk_size);
259                         addr = m_addr + last_offset;
260                         break;
261                     }
262                 }
263 
264                 last_offset = pos->first + pos->second * m_chunk_size;
265 
266                 if (++pos == end)
267                 {
268                     // Last entry...
269                     const uint32_t chunks_left = CalculateChunksNeededForSize (m_byte_size - last_offset);
270                     if (chunks_left >= needed_chunks)
271                     {
272                         m_offset_to_chunk_size[last_offset] = needed_chunks;
273                         if (log)
274                             log->Printf ("[3] AllocatedBlock::ReserveBlock (size = %u (0x%x)) => offset = 0x%x, %u %u bit chunks", size, size, last_offset, needed_chunks, m_chunk_size);
275                         addr = m_addr + last_offset;
276                         break;
277                     }
278                 }
279             }
280         }
281 //        const uint32_t total_chunks = m_allocated.size ();
282 //        uint32_t unallocated_idx = 0;
283 //        uint32_t allocated_idx = m_allocated.find_first();
284 //        uint32_t first_chunk_idx = UINT32_MAX;
285 //        uint32_t num_chunks;
286 //        while (1)
287 //        {
288 //            if (allocated_idx == UINT32_MAX)
289 //            {
290 //                // No more bits are set starting from unallocated_idx, so we
291 //                // either have enough chunks for the request, or we don't.
292 //                // Eiter way we break out of the while loop...
293 //                num_chunks = total_chunks - unallocated_idx;
294 //                if (needed_chunks <= num_chunks)
295 //                    first_chunk_idx = unallocated_idx;
296 //                break;
297 //            }
298 //            else if (allocated_idx > unallocated_idx)
299 //            {
300 //                // We have some allocated chunks, check if there are enough
301 //                // free chunks to satisfy the request?
302 //                num_chunks = allocated_idx - unallocated_idx;
303 //                if (needed_chunks <= num_chunks)
304 //                {
305 //                    // Yep, we have enough!
306 //                    first_chunk_idx = unallocated_idx;
307 //                    break;
308 //                }
309 //            }
310 //
311 //            while (unallocated_idx < total_chunks)
312 //            {
313 //                if (m_allocated[unallocated_idx])
314 //                    ++unallocated_idx;
315 //                else
316 //                    break;
317 //            }
318 //
319 //            if (unallocated_idx >= total_chunks)
320 //                break;
321 //
322 //            allocated_idx = m_allocated.find_next(unallocated_idx);
323 //        }
324 //
325 //        if (first_chunk_idx != UINT32_MAX)
326 //        {
327 //            const uint32_t end_bit_idx = unallocated_idx + needed_chunks;
328 //            for (uint32_t idx = first_chunk_idx; idx < end_bit_idx; ++idx)
329 //                m_allocated.set(idx);
330 //            return m_addr + m_chunk_size * first_chunk_idx;
331 //        }
332     }
333     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE));
334     if (log)
335         log->Printf ("AllocatedBlock::ReserveBlock (size = %u (0x%x)) => 0x%16.16" PRIx64, size, size, (uint64_t)addr);
336     return addr;
337 }
338 
339 bool
340 AllocatedBlock::FreeBlock (addr_t addr)
341 {
342     uint32_t offset = addr - m_addr;
343     OffsetToChunkSize::iterator pos = m_offset_to_chunk_size.find (offset);
344     bool success = false;
345     if (pos != m_offset_to_chunk_size.end())
346     {
347         m_offset_to_chunk_size.erase (pos);
348         success = true;
349     }
350     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE));
351     if (log)
352         log->Printf ("AllocatedBlock::FreeBlock (addr = 0x%16.16" PRIx64 ") => %i", (uint64_t)addr, success);
353     return success;
354 }
355 
356 
357 AllocatedMemoryCache::AllocatedMemoryCache (Process &process) :
358     m_process (process),
359     m_mutex (Mutex::eMutexTypeRecursive),
360     m_memory_map()
361 {
362 }
363 
364 AllocatedMemoryCache::~AllocatedMemoryCache ()
365 {
366 }
367 
368 
369 void
370 AllocatedMemoryCache::Clear()
371 {
372     Mutex::Locker locker (m_mutex);
373     if (m_process.IsAlive())
374     {
375         PermissionsToBlockMap::iterator pos, end = m_memory_map.end();
376         for (pos = m_memory_map.begin(); pos != end; ++pos)
377             m_process.DoDeallocateMemory(pos->second->GetBaseAddress());
378     }
379     m_memory_map.clear();
380 }
381 
382 
383 AllocatedMemoryCache::AllocatedBlockSP
384 AllocatedMemoryCache::AllocatePage (uint32_t byte_size,
385                                     uint32_t permissions,
386                                     uint32_t chunk_size,
387                                     Error &error)
388 {
389     AllocatedBlockSP block_sp;
390     const size_t page_size = 4096;
391     const size_t num_pages = (byte_size + page_size - 1) / page_size;
392     const size_t page_byte_size = num_pages * page_size;
393 
394     addr_t addr = m_process.DoAllocateMemory(page_byte_size, permissions, error);
395 
396     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
397     if (log)
398     {
399         log->Printf ("Process::DoAllocateMemory (byte_size = 0x%8.8" PRIx32 ", permissions = %s) => 0x%16.16" PRIx64,
400                      (uint32_t)page_byte_size,
401                      GetPermissionsAsCString(permissions),
402                      (uint64_t)addr);
403     }
404 
405     if (addr != LLDB_INVALID_ADDRESS)
406     {
407         block_sp.reset (new AllocatedBlock (addr, page_byte_size, permissions, chunk_size));
408         m_memory_map.insert (std::make_pair (permissions, block_sp));
409     }
410     return block_sp;
411 }
412 
413 lldb::addr_t
414 AllocatedMemoryCache::AllocateMemory (size_t byte_size,
415                                       uint32_t permissions,
416                                       Error &error)
417 {
418     Mutex::Locker locker (m_mutex);
419 
420     addr_t addr = LLDB_INVALID_ADDRESS;
421     std::pair<PermissionsToBlockMap::iterator, PermissionsToBlockMap::iterator> range = m_memory_map.equal_range (permissions);
422 
423     for (PermissionsToBlockMap::iterator pos = range.first; pos != range.second; ++pos)
424     {
425         addr = (*pos).second->ReserveBlock (byte_size);
426     }
427 
428     if (addr == LLDB_INVALID_ADDRESS)
429     {
430         AllocatedBlockSP block_sp (AllocatePage (byte_size, permissions, 16, error));
431 
432         if (block_sp)
433             addr = block_sp->ReserveBlock (byte_size);
434     }
435     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
436     if (log)
437         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);
438     return addr;
439 }
440 
441 bool
442 AllocatedMemoryCache::DeallocateMemory (lldb::addr_t addr)
443 {
444     Mutex::Locker locker (m_mutex);
445 
446     PermissionsToBlockMap::iterator pos, end = m_memory_map.end();
447     bool success = false;
448     for (pos = m_memory_map.begin(); pos != end; ++pos)
449     {
450         if (pos->second->Contains (addr))
451         {
452             success = pos->second->FreeBlock (addr);
453             break;
454         }
455     }
456     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
457     if (log)
458         log->Printf("AllocatedMemoryCache::DeallocateMemory (addr = 0x%16.16" PRIx64 ") => %i", (uint64_t)addr, success);
459     return success;
460 }
461 
462 
463