1 //===-- IRMemoryMap.cpp ---------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "lldb/Expression/IRMemoryMap.h"
10 #include "lldb/Target/MemoryRegionInfo.h"
11 #include "lldb/Target/Process.h"
12 #include "lldb/Target/Target.h"
13 #include "lldb/Utility/DataBufferHeap.h"
14 #include "lldb/Utility/DataExtractor.h"
15 #include "lldb/Utility/LLDBAssert.h"
16 #include "lldb/Utility/Log.h"
17 #include "lldb/Utility/Scalar.h"
18 #include "lldb/Utility/Status.h"
19 
20 using namespace lldb_private;
21 
22 IRMemoryMap::IRMemoryMap(lldb::TargetSP target_sp) : m_target_wp(target_sp) {
23   if (target_sp)
24     m_process_wp = target_sp->GetProcessSP();
25 }
26 
27 IRMemoryMap::~IRMemoryMap() {
28   lldb::ProcessSP process_sp = m_process_wp.lock();
29 
30   if (process_sp) {
31     AllocationMap::iterator iter;
32 
33     Status err;
34 
35     while ((iter = m_allocations.begin()) != m_allocations.end()) {
36       err.Clear();
37       if (iter->second.m_leak)
38         m_allocations.erase(iter);
39       else
40         Free(iter->first, err);
41     }
42   }
43 }
44 
45 lldb::addr_t IRMemoryMap::FindSpace(size_t size) {
46   // The FindSpace algorithm's job is to find a region of memory that the
47   // underlying process is unlikely to be using.
48   //
49   // The memory returned by this function will never be written to.  The only
50   // point is that it should not shadow process memory if possible, so that
51   // expressions processing real values from the process do not use the wrong
52   // data.
53   //
54   // If the process can in fact allocate memory (CanJIT() lets us know this)
55   // then this can be accomplished just be allocating memory in the inferior.
56   // Then no guessing is required.
57 
58   lldb::TargetSP target_sp = m_target_wp.lock();
59   lldb::ProcessSP process_sp = m_process_wp.lock();
60 
61   const bool process_is_alive = process_sp && process_sp->IsAlive();
62 
63   lldb::addr_t ret = LLDB_INVALID_ADDRESS;
64   if (size == 0)
65     return ret;
66 
67   if (process_is_alive && process_sp->CanJIT()) {
68     Status alloc_error;
69 
70     ret = process_sp->AllocateMemory(size, lldb::ePermissionsReadable |
71                                                lldb::ePermissionsWritable,
72                                      alloc_error);
73 
74     if (!alloc_error.Success())
75       return LLDB_INVALID_ADDRESS;
76     else
77       return ret;
78   }
79 
80   // At this point we know that we need to hunt.
81   //
82   // First, go to the end of the existing allocations we've made if there are
83   // any allocations.  Otherwise start at the beginning of memory.
84 
85   if (m_allocations.empty()) {
86     ret = 0x0;
87   } else {
88     auto back = m_allocations.rbegin();
89     lldb::addr_t addr = back->first;
90     size_t alloc_size = back->second.m_size;
91     ret = llvm::alignTo(addr + alloc_size, 4096);
92   }
93 
94   // Now, if it's possible to use the GetMemoryRegionInfo API to detect mapped
95   // regions, walk forward through memory until a region is found that has
96   // adequate space for our allocation.
97   if (process_is_alive) {
98     const uint64_t end_of_memory = process_sp->GetAddressByteSize() == 8
99                                        ? 0xffffffffffffffffull
100                                        : 0xffffffffull;
101 
102     lldbassert(process_sp->GetAddressByteSize() == 4 ||
103                end_of_memory != 0xffffffffull);
104 
105     MemoryRegionInfo region_info;
106     Status err = process_sp->GetMemoryRegionInfo(ret, region_info);
107     if (err.Success()) {
108       while (true) {
109         if (region_info.GetReadable() != MemoryRegionInfo::OptionalBool::eNo ||
110             region_info.GetWritable() != MemoryRegionInfo::OptionalBool::eNo ||
111             region_info.GetExecutable() !=
112                 MemoryRegionInfo::OptionalBool::eNo) {
113           if (region_info.GetRange().GetRangeEnd() - 1 >= end_of_memory) {
114             ret = LLDB_INVALID_ADDRESS;
115             break;
116           } else {
117             ret = region_info.GetRange().GetRangeEnd();
118           }
119         } else if (ret + size < region_info.GetRange().GetRangeEnd()) {
120           return ret;
121         } else {
122           // ret stays the same.  We just need to walk a bit further.
123         }
124 
125         err = process_sp->GetMemoryRegionInfo(
126             region_info.GetRange().GetRangeEnd(), region_info);
127         if (err.Fail()) {
128           lldbassert(0 && "GetMemoryRegionInfo() succeeded, then failed");
129           ret = LLDB_INVALID_ADDRESS;
130           break;
131         }
132       }
133     }
134   }
135 
136   // We've tried our algorithm, and it didn't work.  Now we have to reset back
137   // to the end of the allocations we've already reported, or use a 'sensible'
138   // default if this is our first allocation.
139 
140   if (m_allocations.empty()) {
141     uint32_t address_byte_size = GetAddressByteSize();
142     if (address_byte_size != UINT32_MAX) {
143       switch (address_byte_size) {
144       case 8:
145         ret = 0xffffffff00000000ull;
146         break;
147       case 4:
148         ret = 0xee000000ull;
149         break;
150       default:
151         break;
152       }
153     }
154   } else {
155     auto back = m_allocations.rbegin();
156     lldb::addr_t addr = back->first;
157     size_t alloc_size = back->second.m_size;
158     ret = llvm::alignTo(addr + alloc_size, 4096);
159   }
160 
161   return ret;
162 }
163 
164 IRMemoryMap::AllocationMap::iterator
165 IRMemoryMap::FindAllocation(lldb::addr_t addr, size_t size) {
166   if (addr == LLDB_INVALID_ADDRESS)
167     return m_allocations.end();
168 
169   AllocationMap::iterator iter = m_allocations.lower_bound(addr);
170 
171   if (iter == m_allocations.end() || iter->first > addr) {
172     if (iter == m_allocations.begin())
173       return m_allocations.end();
174     iter--;
175   }
176 
177   if (iter->first <= addr && iter->first + iter->second.m_size >= addr + size)
178     return iter;
179 
180   return m_allocations.end();
181 }
182 
183 bool IRMemoryMap::IntersectsAllocation(lldb::addr_t addr, size_t size) const {
184   if (addr == LLDB_INVALID_ADDRESS)
185     return false;
186 
187   AllocationMap::const_iterator iter = m_allocations.lower_bound(addr);
188 
189   // Since we only know that the returned interval begins at a location greater
190   // than or equal to where the given interval begins, it's possible that the
191   // given interval intersects either the returned interval or the previous
192   // interval.  Thus, we need to check both. Note that we only need to check
193   // these two intervals.  Since all intervals are disjoint it is not possible
194   // that an adjacent interval does not intersect, but a non-adjacent interval
195   // does intersect.
196   if (iter != m_allocations.end()) {
197     if (AllocationsIntersect(addr, size, iter->second.m_process_start,
198                              iter->second.m_size))
199       return true;
200   }
201 
202   if (iter != m_allocations.begin()) {
203     --iter;
204     if (AllocationsIntersect(addr, size, iter->second.m_process_start,
205                              iter->second.m_size))
206       return true;
207   }
208 
209   return false;
210 }
211 
212 bool IRMemoryMap::AllocationsIntersect(lldb::addr_t addr1, size_t size1,
213                                        lldb::addr_t addr2, size_t size2) {
214   // Given two half open intervals [A, B) and [X, Y), the only 6 permutations
215   // that satisfy A<B and X<Y are the following:
216   // A B X Y
217   // A X B Y  (intersects)
218   // A X Y B  (intersects)
219   // X A B Y  (intersects)
220   // X A Y B  (intersects)
221   // X Y A B
222   // The first is B <= X, and the last is Y <= A. So the condition is !(B <= X
223   // || Y <= A)), or (X < B && A < Y)
224   return (addr2 < (addr1 + size1)) && (addr1 < (addr2 + size2));
225 }
226 
227 lldb::ByteOrder IRMemoryMap::GetByteOrder() {
228   lldb::ProcessSP process_sp = m_process_wp.lock();
229 
230   if (process_sp)
231     return process_sp->GetByteOrder();
232 
233   lldb::TargetSP target_sp = m_target_wp.lock();
234 
235   if (target_sp)
236     return target_sp->GetArchitecture().GetByteOrder();
237 
238   return lldb::eByteOrderInvalid;
239 }
240 
241 uint32_t IRMemoryMap::GetAddressByteSize() {
242   lldb::ProcessSP process_sp = m_process_wp.lock();
243 
244   if (process_sp)
245     return process_sp->GetAddressByteSize();
246 
247   lldb::TargetSP target_sp = m_target_wp.lock();
248 
249   if (target_sp)
250     return target_sp->GetArchitecture().GetAddressByteSize();
251 
252   return UINT32_MAX;
253 }
254 
255 ExecutionContextScope *IRMemoryMap::GetBestExecutionContextScope() const {
256   lldb::ProcessSP process_sp = m_process_wp.lock();
257 
258   if (process_sp)
259     return process_sp.get();
260 
261   lldb::TargetSP target_sp = m_target_wp.lock();
262 
263   if (target_sp)
264     return target_sp.get();
265 
266   return nullptr;
267 }
268 
269 IRMemoryMap::Allocation::Allocation(lldb::addr_t process_alloc,
270                                     lldb::addr_t process_start, size_t size,
271                                     uint32_t permissions, uint8_t alignment,
272                                     AllocationPolicy policy)
273     : m_process_alloc(process_alloc), m_process_start(process_start),
274       m_size(size), m_policy(policy), m_leak(false), m_permissions(permissions),
275       m_alignment(alignment) {
276   switch (policy) {
277   default:
278     llvm_unreachable("Invalid AllocationPolicy");
279   case eAllocationPolicyHostOnly:
280   case eAllocationPolicyMirror:
281     m_data.SetByteSize(size);
282     break;
283   case eAllocationPolicyProcessOnly:
284     break;
285   }
286 }
287 
288 lldb::addr_t IRMemoryMap::Malloc(size_t size, uint8_t alignment,
289                                  uint32_t permissions, AllocationPolicy policy,
290                                  bool zero_memory, Status &error) {
291   lldb_private::Log *log(
292       lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
293   error.Clear();
294 
295   lldb::ProcessSP process_sp;
296   lldb::addr_t allocation_address = LLDB_INVALID_ADDRESS;
297   lldb::addr_t aligned_address = LLDB_INVALID_ADDRESS;
298 
299   size_t allocation_size;
300 
301   if (size == 0) {
302     // FIXME: Malloc(0) should either return an invalid address or assert, in
303     // order to cut down on unnecessary allocations.
304     allocation_size = alignment;
305   } else {
306     // Round up the requested size to an aligned value.
307     allocation_size = llvm::alignTo(size, alignment);
308 
309     // The process page cache does not see the requested alignment. We can't
310     // assume its result will be any more than 1-byte aligned. To work around
311     // this, request `alignment - 1` additional bytes.
312     allocation_size += alignment - 1;
313   }
314 
315   switch (policy) {
316   default:
317     error.SetErrorToGenericError();
318     error.SetErrorString("Couldn't malloc: invalid allocation policy");
319     return LLDB_INVALID_ADDRESS;
320   case eAllocationPolicyHostOnly:
321     allocation_address = FindSpace(allocation_size);
322     if (allocation_address == LLDB_INVALID_ADDRESS) {
323       error.SetErrorToGenericError();
324       error.SetErrorString("Couldn't malloc: address space is full");
325       return LLDB_INVALID_ADDRESS;
326     }
327     break;
328   case eAllocationPolicyMirror:
329     process_sp = m_process_wp.lock();
330     LLDB_LOGF(log,
331               "IRMemoryMap::%s process_sp=0x%" PRIxPTR
332               ", process_sp->CanJIT()=%s, process_sp->IsAlive()=%s",
333               __FUNCTION__, reinterpret_cast<uintptr_t>(process_sp.get()),
334               process_sp && process_sp->CanJIT() ? "true" : "false",
335               process_sp && process_sp->IsAlive() ? "true" : "false");
336     if (process_sp && process_sp->CanJIT() && process_sp->IsAlive()) {
337       if (!zero_memory)
338         allocation_address =
339             process_sp->AllocateMemory(allocation_size, permissions, error);
340       else
341         allocation_address =
342             process_sp->CallocateMemory(allocation_size, permissions, error);
343 
344       if (!error.Success())
345         return LLDB_INVALID_ADDRESS;
346     } else {
347       LLDB_LOGF(log,
348                 "IRMemoryMap::%s switching to eAllocationPolicyHostOnly "
349                 "due to failed condition (see previous expr log message)",
350                 __FUNCTION__);
351       policy = eAllocationPolicyHostOnly;
352       allocation_address = FindSpace(allocation_size);
353       if (allocation_address == LLDB_INVALID_ADDRESS) {
354         error.SetErrorToGenericError();
355         error.SetErrorString("Couldn't malloc: address space is full");
356         return LLDB_INVALID_ADDRESS;
357       }
358     }
359     break;
360   case eAllocationPolicyProcessOnly:
361     process_sp = m_process_wp.lock();
362     if (process_sp) {
363       if (process_sp->CanJIT() && process_sp->IsAlive()) {
364         if (!zero_memory)
365           allocation_address =
366               process_sp->AllocateMemory(allocation_size, permissions, error);
367         else
368           allocation_address =
369               process_sp->CallocateMemory(allocation_size, permissions, error);
370 
371         if (!error.Success())
372           return LLDB_INVALID_ADDRESS;
373       } else {
374         error.SetErrorToGenericError();
375         error.SetErrorString(
376             "Couldn't malloc: process doesn't support allocating memory");
377         return LLDB_INVALID_ADDRESS;
378       }
379     } else {
380       error.SetErrorToGenericError();
381       error.SetErrorString("Couldn't malloc: process doesn't exist, and this "
382                            "memory must be in the process");
383       return LLDB_INVALID_ADDRESS;
384     }
385     break;
386   }
387 
388   lldb::addr_t mask = alignment - 1;
389   aligned_address = (allocation_address + mask) & (~mask);
390 
391   m_allocations.emplace(
392       std::piecewise_construct, std::forward_as_tuple(aligned_address),
393       std::forward_as_tuple(allocation_address, aligned_address,
394                             allocation_size, permissions, alignment, policy));
395 
396   if (zero_memory) {
397     Status write_error;
398     std::vector<uint8_t> zero_buf(size, 0);
399     WriteMemory(aligned_address, zero_buf.data(), size, write_error);
400   }
401 
402   if (log) {
403     const char *policy_string;
404 
405     switch (policy) {
406     default:
407       policy_string = "<invalid policy>";
408       break;
409     case eAllocationPolicyHostOnly:
410       policy_string = "eAllocationPolicyHostOnly";
411       break;
412     case eAllocationPolicyProcessOnly:
413       policy_string = "eAllocationPolicyProcessOnly";
414       break;
415     case eAllocationPolicyMirror:
416       policy_string = "eAllocationPolicyMirror";
417       break;
418     }
419 
420     LLDB_LOGF(log,
421               "IRMemoryMap::Malloc (%" PRIu64 ", 0x%" PRIx64 ", 0x%" PRIx64
422               ", %s) -> 0x%" PRIx64,
423               (uint64_t)allocation_size, (uint64_t)alignment,
424               (uint64_t)permissions, policy_string, aligned_address);
425   }
426 
427   return aligned_address;
428 }
429 
430 void IRMemoryMap::Leak(lldb::addr_t process_address, Status &error) {
431   error.Clear();
432 
433   AllocationMap::iterator iter = m_allocations.find(process_address);
434 
435   if (iter == m_allocations.end()) {
436     error.SetErrorToGenericError();
437     error.SetErrorString("Couldn't leak: allocation doesn't exist");
438     return;
439   }
440 
441   Allocation &allocation = iter->second;
442 
443   allocation.m_leak = true;
444 }
445 
446 void IRMemoryMap::Free(lldb::addr_t process_address, Status &error) {
447   error.Clear();
448 
449   AllocationMap::iterator iter = m_allocations.find(process_address);
450 
451   if (iter == m_allocations.end()) {
452     error.SetErrorToGenericError();
453     error.SetErrorString("Couldn't free: allocation doesn't exist");
454     return;
455   }
456 
457   Allocation &allocation = iter->second;
458 
459   switch (allocation.m_policy) {
460   default:
461   case eAllocationPolicyHostOnly: {
462     lldb::ProcessSP process_sp = m_process_wp.lock();
463     if (process_sp) {
464       if (process_sp->CanJIT() && process_sp->IsAlive())
465         process_sp->DeallocateMemory(
466             allocation.m_process_alloc); // FindSpace allocated this for real
467     }
468 
469     break;
470   }
471   case eAllocationPolicyMirror:
472   case eAllocationPolicyProcessOnly: {
473     lldb::ProcessSP process_sp = m_process_wp.lock();
474     if (process_sp)
475       process_sp->DeallocateMemory(allocation.m_process_alloc);
476   }
477   }
478 
479   if (lldb_private::Log *log =
480           lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)) {
481     LLDB_LOGF(log,
482               "IRMemoryMap::Free (0x%" PRIx64 ") freed [0x%" PRIx64
483               "..0x%" PRIx64 ")",
484               (uint64_t)process_address, iter->second.m_process_start,
485               iter->second.m_process_start + iter->second.m_size);
486   }
487 
488   m_allocations.erase(iter);
489 }
490 
491 bool IRMemoryMap::GetAllocSize(lldb::addr_t address, size_t &size) {
492   AllocationMap::iterator iter = FindAllocation(address, size);
493   if (iter == m_allocations.end())
494     return false;
495 
496   Allocation &al = iter->second;
497 
498   if (address > (al.m_process_start + al.m_size)) {
499     size = 0;
500     return false;
501   }
502 
503   if (address > al.m_process_start) {
504     int dif = address - al.m_process_start;
505     size = al.m_size - dif;
506     return true;
507   }
508 
509   size = al.m_size;
510   return true;
511 }
512 
513 void IRMemoryMap::WriteMemory(lldb::addr_t process_address,
514                               const uint8_t *bytes, size_t size,
515                               Status &error) {
516   error.Clear();
517 
518   AllocationMap::iterator iter = FindAllocation(process_address, size);
519 
520   if (iter == m_allocations.end()) {
521     lldb::ProcessSP process_sp = m_process_wp.lock();
522 
523     if (process_sp) {
524       process_sp->WriteMemory(process_address, bytes, size, error);
525       return;
526     }
527 
528     error.SetErrorToGenericError();
529     error.SetErrorString("Couldn't write: no allocation contains the target "
530                          "range and the process doesn't exist");
531     return;
532   }
533 
534   Allocation &allocation = iter->second;
535 
536   uint64_t offset = process_address - allocation.m_process_start;
537 
538   lldb::ProcessSP process_sp;
539 
540   switch (allocation.m_policy) {
541   default:
542     error.SetErrorToGenericError();
543     error.SetErrorString("Couldn't write: invalid allocation policy");
544     return;
545   case eAllocationPolicyHostOnly:
546     if (!allocation.m_data.GetByteSize()) {
547       error.SetErrorToGenericError();
548       error.SetErrorString("Couldn't write: data buffer is empty");
549       return;
550     }
551     ::memcpy(allocation.m_data.GetBytes() + offset, bytes, size);
552     break;
553   case eAllocationPolicyMirror:
554     if (!allocation.m_data.GetByteSize()) {
555       error.SetErrorToGenericError();
556       error.SetErrorString("Couldn't write: data buffer is empty");
557       return;
558     }
559     ::memcpy(allocation.m_data.GetBytes() + offset, bytes, size);
560     process_sp = m_process_wp.lock();
561     if (process_sp) {
562       process_sp->WriteMemory(process_address, bytes, size, error);
563       if (!error.Success())
564         return;
565     }
566     break;
567   case eAllocationPolicyProcessOnly:
568     process_sp = m_process_wp.lock();
569     if (process_sp) {
570       process_sp->WriteMemory(process_address, bytes, size, error);
571       if (!error.Success())
572         return;
573     }
574     break;
575   }
576 
577   if (lldb_private::Log *log =
578           lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)) {
579     LLDB_LOGF(log,
580               "IRMemoryMap::WriteMemory (0x%" PRIx64 ", 0x%" PRIxPTR
581               ", 0x%" PRId64 ") went to [0x%" PRIx64 "..0x%" PRIx64 ")",
582               (uint64_t)process_address, reinterpret_cast<uintptr_t>(bytes), (uint64_t)size,
583               (uint64_t)allocation.m_process_start,
584               (uint64_t)allocation.m_process_start +
585                   (uint64_t)allocation.m_size);
586   }
587 }
588 
589 void IRMemoryMap::WriteScalarToMemory(lldb::addr_t process_address,
590                                       Scalar &scalar, size_t size,
591                                       Status &error) {
592   error.Clear();
593 
594   if (size == UINT32_MAX)
595     size = scalar.GetByteSize();
596 
597   if (size > 0) {
598     uint8_t buf[32];
599     const size_t mem_size =
600         scalar.GetAsMemoryData(buf, size, GetByteOrder(), error);
601     if (mem_size > 0) {
602       return WriteMemory(process_address, buf, mem_size, error);
603     } else {
604       error.SetErrorToGenericError();
605       error.SetErrorString(
606           "Couldn't write scalar: failed to get scalar as memory data");
607     }
608   } else {
609     error.SetErrorToGenericError();
610     error.SetErrorString("Couldn't write scalar: its size was zero");
611   }
612 }
613 
614 void IRMemoryMap::WritePointerToMemory(lldb::addr_t process_address,
615                                        lldb::addr_t address, Status &error) {
616   error.Clear();
617 
618   Scalar scalar(address);
619 
620   WriteScalarToMemory(process_address, scalar, GetAddressByteSize(), error);
621 }
622 
623 void IRMemoryMap::ReadMemory(uint8_t *bytes, lldb::addr_t process_address,
624                              size_t size, Status &error) {
625   error.Clear();
626 
627   AllocationMap::iterator iter = FindAllocation(process_address, size);
628 
629   if (iter == m_allocations.end()) {
630     lldb::ProcessSP process_sp = m_process_wp.lock();
631 
632     if (process_sp) {
633       process_sp->ReadMemory(process_address, bytes, size, error);
634       return;
635     }
636 
637     lldb::TargetSP target_sp = m_target_wp.lock();
638 
639     if (target_sp) {
640       Address absolute_address(process_address);
641       target_sp->ReadMemory(absolute_address, bytes, size, error, true);
642       return;
643     }
644 
645     error.SetErrorToGenericError();
646     error.SetErrorString("Couldn't read: no allocation contains the target "
647                          "range, and neither the process nor the target exist");
648     return;
649   }
650 
651   Allocation &allocation = iter->second;
652 
653   uint64_t offset = process_address - allocation.m_process_start;
654 
655   if (offset > allocation.m_size) {
656     error.SetErrorToGenericError();
657     error.SetErrorString("Couldn't read: data is not in the allocation");
658     return;
659   }
660 
661   lldb::ProcessSP process_sp;
662 
663   switch (allocation.m_policy) {
664   default:
665     error.SetErrorToGenericError();
666     error.SetErrorString("Couldn't read: invalid allocation policy");
667     return;
668   case eAllocationPolicyHostOnly:
669     if (!allocation.m_data.GetByteSize()) {
670       error.SetErrorToGenericError();
671       error.SetErrorString("Couldn't read: data buffer is empty");
672       return;
673     }
674     if (allocation.m_data.GetByteSize() < offset + size) {
675       error.SetErrorToGenericError();
676       error.SetErrorString("Couldn't read: not enough underlying data");
677       return;
678     }
679 
680     ::memcpy(bytes, allocation.m_data.GetBytes() + offset, size);
681     break;
682   case eAllocationPolicyMirror:
683     process_sp = m_process_wp.lock();
684     if (process_sp) {
685       process_sp->ReadMemory(process_address, bytes, size, error);
686       if (!error.Success())
687         return;
688     } else {
689       if (!allocation.m_data.GetByteSize()) {
690         error.SetErrorToGenericError();
691         error.SetErrorString("Couldn't read: data buffer is empty");
692         return;
693       }
694       ::memcpy(bytes, allocation.m_data.GetBytes() + offset, size);
695     }
696     break;
697   case eAllocationPolicyProcessOnly:
698     process_sp = m_process_wp.lock();
699     if (process_sp) {
700       process_sp->ReadMemory(process_address, bytes, size, error);
701       if (!error.Success())
702         return;
703     }
704     break;
705   }
706 
707   if (lldb_private::Log *log =
708           lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)) {
709     LLDB_LOGF(log,
710               "IRMemoryMap::ReadMemory (0x%" PRIx64 ", 0x%" PRIxPTR
711               ", 0x%" PRId64 ") came from [0x%" PRIx64 "..0x%" PRIx64 ")",
712               (uint64_t)process_address, reinterpret_cast<uintptr_t>(bytes), (uint64_t)size,
713               (uint64_t)allocation.m_process_start,
714               (uint64_t)allocation.m_process_start +
715                   (uint64_t)allocation.m_size);
716   }
717 }
718 
719 void IRMemoryMap::ReadScalarFromMemory(Scalar &scalar,
720                                        lldb::addr_t process_address,
721                                        size_t size, Status &error) {
722   error.Clear();
723 
724   if (size > 0) {
725     DataBufferHeap buf(size, 0);
726     ReadMemory(buf.GetBytes(), process_address, size, error);
727 
728     if (!error.Success())
729       return;
730 
731     DataExtractor extractor(buf.GetBytes(), buf.GetByteSize(), GetByteOrder(),
732                             GetAddressByteSize());
733 
734     lldb::offset_t offset = 0;
735 
736     switch (size) {
737     default:
738       error.SetErrorToGenericError();
739       error.SetErrorStringWithFormat(
740           "Couldn't read scalar: unsupported size %" PRIu64, (uint64_t)size);
741       return;
742     case 1:
743       scalar = extractor.GetU8(&offset);
744       break;
745     case 2:
746       scalar = extractor.GetU16(&offset);
747       break;
748     case 4:
749       scalar = extractor.GetU32(&offset);
750       break;
751     case 8:
752       scalar = extractor.GetU64(&offset);
753       break;
754     }
755   } else {
756     error.SetErrorToGenericError();
757     error.SetErrorString("Couldn't read scalar: its size was zero");
758   }
759 }
760 
761 void IRMemoryMap::ReadPointerFromMemory(lldb::addr_t *address,
762                                         lldb::addr_t process_address,
763                                         Status &error) {
764   error.Clear();
765 
766   Scalar pointer_scalar;
767   ReadScalarFromMemory(pointer_scalar, process_address, GetAddressByteSize(),
768                        error);
769 
770   if (!error.Success())
771     return;
772 
773   *address = pointer_scalar.ULongLong();
774 }
775 
776 void IRMemoryMap::GetMemoryData(DataExtractor &extractor,
777                                 lldb::addr_t process_address, size_t size,
778                                 Status &error) {
779   error.Clear();
780 
781   if (size > 0) {
782     AllocationMap::iterator iter = FindAllocation(process_address, size);
783 
784     if (iter == m_allocations.end()) {
785       error.SetErrorToGenericError();
786       error.SetErrorStringWithFormat(
787           "Couldn't find an allocation containing [0x%" PRIx64 "..0x%" PRIx64
788           ")",
789           process_address, process_address + size);
790       return;
791     }
792 
793     Allocation &allocation = iter->second;
794 
795     switch (allocation.m_policy) {
796     default:
797       error.SetErrorToGenericError();
798       error.SetErrorString(
799           "Couldn't get memory data: invalid allocation policy");
800       return;
801     case eAllocationPolicyProcessOnly:
802       error.SetErrorToGenericError();
803       error.SetErrorString(
804           "Couldn't get memory data: memory is only in the target");
805       return;
806     case eAllocationPolicyMirror: {
807       lldb::ProcessSP process_sp = m_process_wp.lock();
808 
809       if (!allocation.m_data.GetByteSize()) {
810         error.SetErrorToGenericError();
811         error.SetErrorString("Couldn't get memory data: data buffer is empty");
812         return;
813       }
814       if (process_sp) {
815         process_sp->ReadMemory(allocation.m_process_start,
816                                allocation.m_data.GetBytes(),
817                                allocation.m_data.GetByteSize(), error);
818         if (!error.Success())
819           return;
820         uint64_t offset = process_address - allocation.m_process_start;
821         extractor = DataExtractor(allocation.m_data.GetBytes() + offset, size,
822                                   GetByteOrder(), GetAddressByteSize());
823         return;
824       }
825     } break;
826     case eAllocationPolicyHostOnly:
827       if (!allocation.m_data.GetByteSize()) {
828         error.SetErrorToGenericError();
829         error.SetErrorString("Couldn't get memory data: data buffer is empty");
830         return;
831       }
832       uint64_t offset = process_address - allocation.m_process_start;
833       extractor = DataExtractor(allocation.m_data.GetBytes() + offset, size,
834                                 GetByteOrder(), GetAddressByteSize());
835       return;
836     }
837   } else {
838     error.SetErrorToGenericError();
839     error.SetErrorString("Couldn't get memory data: its size was zero");
840     return;
841   }
842 }
843