]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/source/Target/Memory.cpp
Merge ^/head r274961 through r276472.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lldb / source / Target / Memory.cpp
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
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
130     // it in the cache.
131     if (dst && dst_len > m_cache_line_byte_size)
132     {
133         return m_process.ReadMemoryFromInferior (addr, dst, dst_len, error);
134     }
135
136     if (dst && bytes_left > 0)
137     {
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);
143         
144         while (bytes_left > 0)
145         {
146             if (m_invalid_ranges.FindEntryThatContains(curr_addr))
147             {
148                 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, curr_addr);
149                 return dst_len - bytes_left;
150             }
151
152             BlockMap::const_iterator pos = m_cache.find (curr_addr);
153             BlockMap::const_iterator end = m_cache.end ();
154             
155             if (pos != end)
156             {
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;
160                 
161                 memcpy (dst_buf + dst_len - bytes_left, pos->second->GetBytes() + cache_offset, curr_read_size);
162                 
163                 bytes_left -= curr_read_size;
164                 curr_addr += curr_read_size + cache_offset;
165                 cache_offset = 0;
166                 
167                 if (bytes_left > 0)
168                 {
169                     // Get sequential cache page hits
170                     for (++pos; (pos != end) && (bytes_left > 0); ++pos)
171                     {
172                         assert ((curr_addr % cache_line_byte_size) == 0);
173                         
174                         if (pos->first != curr_addr)
175                             break;
176                         
177                         curr_read_size = pos->second->GetByteSize();
178                         if (curr_read_size > bytes_left)
179                             curr_read_size = bytes_left;
180                         
181                         memcpy (dst_buf + dst_len - bytes_left, pos->second->GetBytes(), curr_read_size);
182                         
183                         bytes_left -= curr_read_size;
184                         curr_addr += curr_read_size;
185                         
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;
191                     }
192                 }
193             }
194             
195             // We need to read from the process
196             
197             if (bytes_left > 0)
198             {
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(), 
204                                                                               error);
205                 if (process_bytes_read == 0)
206                     return dst_len - bytes_left;
207                 
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...
213             }
214         }
215     }
216     
217     return dst_len - bytes_left;
218 }
219
220
221
222 AllocatedBlock::AllocatedBlock (lldb::addr_t addr, 
223                                 uint32_t byte_size, 
224                                 uint32_t permissions,
225                                 uint32_t chunk_size) :
226     m_addr (addr),
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)
232 {
233     assert (byte_size > chunk_size);
234 }
235
236 AllocatedBlock::~AllocatedBlock ()
237 {
238 }
239
240 lldb::addr_t
241 AllocatedBlock::ReserveBlock (uint32_t size)
242 {
243     addr_t addr = LLDB_INVALID_ADDRESS;
244     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE));
245     if (size <= m_byte_size)
246     {
247         const uint32_t needed_chunks = CalculateChunksNeededForSize (size);
248
249         if (m_offset_to_chunk_size.empty())
250         {
251             m_offset_to_chunk_size[0] = needed_chunks;
252             if (log)
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);
254             addr = m_addr;
255         }
256         else
257         {
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();
261             while (pos != end)
262             {
263                 if (pos->first > last_offset)
264                 {
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)
268                     {
269                         m_offset_to_chunk_size[last_offset] = needed_chunks;
270                         if (log)
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;
273                         break;
274                     }
275                 }
276                 
277                 last_offset = pos->first + pos->second * m_chunk_size;
278
279                 if (++pos == end)
280                 {
281                     // Last entry...
282                     const uint32_t chunks_left = CalculateChunksNeededForSize (m_byte_size - last_offset);
283                     if (chunks_left >= needed_chunks)
284                     {
285                         m_offset_to_chunk_size[last_offset] = needed_chunks;
286                         if (log)
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;
289                         break;
290                     }
291                 }
292             }
293         }
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;
299 //        while (1)
300 //        {
301 //            if (allocated_idx == UINT32_MAX)
302 //            {
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;
309 //                break;                
310 //            }
311 //            else if (allocated_idx > unallocated_idx)
312 //            {
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)
317 //                {
318 //                    // Yep, we have enough!
319 //                    first_chunk_idx = unallocated_idx;
320 //                    break;
321 //                }
322 //            }
323 //            
324 //            while (unallocated_idx < total_chunks)
325 //            {
326 //                if (m_allocated[unallocated_idx])
327 //                    ++unallocated_idx;
328 //                else
329 //                    break;
330 //            }
331 //            
332 //            if (unallocated_idx >= total_chunks)
333 //                break;
334 //            
335 //            allocated_idx = m_allocated.find_next(unallocated_idx);
336 //        }
337 //        
338 //        if (first_chunk_idx != UINT32_MAX)
339 //        {
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;
344 //        }
345     }
346
347     if (log)
348         log->Printf ("AllocatedBlock::ReserveBlock(%p) (size = %u (0x%x)) => 0x%16.16" PRIx64, this, size, size, (uint64_t)addr);
349     return addr;
350 }
351
352 bool
353 AllocatedBlock::FreeBlock (addr_t addr)
354 {
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())
359     {
360         m_offset_to_chunk_size.erase (pos);
361         success = true;
362     }
363     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE));
364     if (log)
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());
366     return success;
367 }
368
369
370 AllocatedMemoryCache::AllocatedMemoryCache (Process &process) :
371     m_process (process),
372     m_mutex (Mutex::eMutexTypeRecursive),
373     m_memory_map()
374 {
375 }
376
377 AllocatedMemoryCache::~AllocatedMemoryCache ()
378 {
379 }
380
381
382 void
383 AllocatedMemoryCache::Clear()
384 {
385     Mutex::Locker locker (m_mutex);
386     if (m_process.IsAlive())
387     {
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());
391     }
392     m_memory_map.clear();
393 }
394
395
396 AllocatedMemoryCache::AllocatedBlockSP
397 AllocatedMemoryCache::AllocatePage (uint32_t byte_size, 
398                                     uint32_t permissions, 
399                                     uint32_t chunk_size, 
400                                     Error &error)
401 {
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;
406
407     addr_t addr = m_process.DoAllocateMemory(page_byte_size, permissions, error);
408
409     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
410     if (log)
411     {
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), 
415                      (uint64_t)addr);
416     }
417
418     if (addr != LLDB_INVALID_ADDRESS)
419     {
420         block_sp.reset (new AllocatedBlock (addr, page_byte_size, permissions, chunk_size));
421         m_memory_map.insert (std::make_pair (permissions, block_sp));
422     }
423     return block_sp;
424 }
425
426 lldb::addr_t
427 AllocatedMemoryCache::AllocateMemory (size_t byte_size, 
428                                       uint32_t permissions, 
429                                       Error &error)
430 {
431     Mutex::Locker locker (m_mutex);
432     
433     addr_t addr = LLDB_INVALID_ADDRESS;
434     std::pair<PermissionsToBlockMap::iterator, PermissionsToBlockMap::iterator> range = m_memory_map.equal_range (permissions);
435
436     for (PermissionsToBlockMap::iterator pos = range.first; pos != range.second; ++pos)
437     {
438         addr = (*pos).second->ReserveBlock (byte_size);
439         if (addr != LLDB_INVALID_ADDRESS)
440             break;
441     }
442     
443     if (addr == LLDB_INVALID_ADDRESS)
444     {
445         AllocatedBlockSP block_sp (AllocatePage (byte_size, permissions, 16, error));
446
447         if (block_sp)
448             addr = block_sp->ReserveBlock (byte_size);
449     }
450     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
451     if (log)
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);
453     return addr;
454 }
455
456 bool
457 AllocatedMemoryCache::DeallocateMemory (lldb::addr_t addr)
458 {
459     Mutex::Locker locker (m_mutex);
460
461     PermissionsToBlockMap::iterator pos, end = m_memory_map.end();
462     bool success = false;
463     for (pos = m_memory_map.begin(); pos != end; ++pos)
464     {
465         if (pos->second->Contains (addr))
466         {
467             success = pos->second->FreeBlock (addr);
468             break;
469         }
470     }
471     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
472     if (log)
473         log->Printf("AllocatedMemoryCache::DeallocateMemory (addr = 0x%16.16" PRIx64 ") => %i", (uint64_t)addr, success);
474     return success;
475 }
476
477