1 //===-- Materializer.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/Materializer.h"
10 #include "lldb/Core/DumpDataExtractor.h"
11 #include "lldb/Core/ValueObjectConstResult.h"
12 #include "lldb/Core/ValueObjectVariable.h"
13 #include "lldb/Expression/ExpressionVariable.h"
14 #include "lldb/Symbol/Symbol.h"
15 #include "lldb/Symbol/Type.h"
16 #include "lldb/Symbol/Variable.h"
17 #include "lldb/Target/ExecutionContext.h"
18 #include "lldb/Target/RegisterContext.h"
19 #include "lldb/Target/StackFrame.h"
20 #include "lldb/Target/Target.h"
21 #include "lldb/Target/Thread.h"
22 #include "lldb/Utility/Log.h"
23 #include "lldb/Utility/RegisterValue.h"
24 
25 #include <memory>
26 
27 using namespace lldb_private;
28 
29 uint32_t Materializer::AddStructMember(Entity &entity) {
30   uint32_t size = entity.GetSize();
31   uint32_t alignment = entity.GetAlignment();
32 
33   uint32_t ret;
34 
35   if (m_current_offset == 0)
36     m_struct_alignment = alignment;
37 
38   if (m_current_offset % alignment)
39     m_current_offset += (alignment - (m_current_offset % alignment));
40 
41   ret = m_current_offset;
42 
43   m_current_offset += size;
44 
45   return ret;
46 }
47 
48 class EntityPersistentVariable : public Materializer::Entity {
49 public:
50   EntityPersistentVariable(lldb::ExpressionVariableSP &persistent_variable_sp,
51                            Materializer::PersistentVariableDelegate *delegate)
52       : Entity(), m_persistent_variable_sp(persistent_variable_sp),
53         m_delegate(delegate) {
54     // Hard-coding to maximum size of a pointer since persistent variables are
55     // materialized by reference
56     m_size = 8;
57     m_alignment = 8;
58   }
59 
60   void MakeAllocation(IRMemoryMap &map, Status &err) {
61     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
62 
63     // Allocate a spare memory area to store the persistent variable's
64     // contents.
65 
66     Status allocate_error;
67     const bool zero_memory = false;
68 
69     lldb::addr_t mem = map.Malloc(
70         m_persistent_variable_sp->GetByteSize(), 8,
71         lldb::ePermissionsReadable | lldb::ePermissionsWritable,
72         IRMemoryMap::eAllocationPolicyMirror, zero_memory, allocate_error);
73 
74     if (!allocate_error.Success()) {
75       err.SetErrorStringWithFormat(
76           "couldn't allocate a memory area to store %s: %s",
77           m_persistent_variable_sp->GetName().GetCString(),
78           allocate_error.AsCString());
79       return;
80     }
81 
82     LLDB_LOGF(log, "Allocated %s (0x%" PRIx64 ") successfully",
83               m_persistent_variable_sp->GetName().GetCString(), mem);
84 
85     // Put the location of the spare memory into the live data of the
86     // ValueObject.
87 
88     m_persistent_variable_sp->m_live_sp = ValueObjectConstResult::Create(
89         map.GetBestExecutionContextScope(),
90         m_persistent_variable_sp->GetCompilerType(),
91         m_persistent_variable_sp->GetName(), mem, eAddressTypeLoad,
92         map.GetAddressByteSize());
93 
94     // Clear the flag if the variable will never be deallocated.
95 
96     if (m_persistent_variable_sp->m_flags &
97         ExpressionVariable::EVKeepInTarget) {
98       Status leak_error;
99       map.Leak(mem, leak_error);
100       m_persistent_variable_sp->m_flags &=
101           ~ExpressionVariable::EVNeedsAllocation;
102     }
103 
104     // Write the contents of the variable to the area.
105 
106     Status write_error;
107 
108     map.WriteMemory(mem, m_persistent_variable_sp->GetValueBytes(),
109                     m_persistent_variable_sp->GetByteSize(), write_error);
110 
111     if (!write_error.Success()) {
112       err.SetErrorStringWithFormat(
113           "couldn't write %s to the target: %s",
114           m_persistent_variable_sp->GetName().AsCString(),
115           write_error.AsCString());
116       return;
117     }
118   }
119 
120   void DestroyAllocation(IRMemoryMap &map, Status &err) {
121     Status deallocate_error;
122 
123     map.Free((lldb::addr_t)m_persistent_variable_sp->m_live_sp->GetValue()
124                  .GetScalar()
125                  .ULongLong(),
126              deallocate_error);
127 
128     m_persistent_variable_sp->m_live_sp.reset();
129 
130     if (!deallocate_error.Success()) {
131       err.SetErrorStringWithFormat(
132           "couldn't deallocate memory for %s: %s",
133           m_persistent_variable_sp->GetName().GetCString(),
134           deallocate_error.AsCString());
135     }
136   }
137 
138   void Materialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map,
139                    lldb::addr_t process_address, Status &err) override {
140     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
141 
142     const lldb::addr_t load_addr = process_address + m_offset;
143 
144     if (log) {
145       LLDB_LOGF(log,
146                 "EntityPersistentVariable::Materialize [address = 0x%" PRIx64
147                 ", m_name = %s, m_flags = 0x%hx]",
148                 (uint64_t)load_addr,
149                 m_persistent_variable_sp->GetName().AsCString(),
150                 m_persistent_variable_sp->m_flags);
151     }
152 
153     if (m_persistent_variable_sp->m_flags &
154         ExpressionVariable::EVNeedsAllocation) {
155       MakeAllocation(map, err);
156       m_persistent_variable_sp->m_flags |=
157           ExpressionVariable::EVIsLLDBAllocated;
158 
159       if (!err.Success())
160         return;
161     }
162 
163     if ((m_persistent_variable_sp->m_flags &
164              ExpressionVariable::EVIsProgramReference &&
165          m_persistent_variable_sp->m_live_sp) ||
166         m_persistent_variable_sp->m_flags &
167             ExpressionVariable::EVIsLLDBAllocated) {
168       Status write_error;
169 
170       map.WriteScalarToMemory(
171           load_addr,
172           m_persistent_variable_sp->m_live_sp->GetValue().GetScalar(),
173           map.GetAddressByteSize(), write_error);
174 
175       if (!write_error.Success()) {
176         err.SetErrorStringWithFormat(
177             "couldn't write the location of %s to memory: %s",
178             m_persistent_variable_sp->GetName().AsCString(),
179             write_error.AsCString());
180       }
181     } else {
182       err.SetErrorStringWithFormat(
183           "no materialization happened for persistent variable %s",
184           m_persistent_variable_sp->GetName().AsCString());
185       return;
186     }
187   }
188 
189   void Dematerialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map,
190                      lldb::addr_t process_address, lldb::addr_t frame_top,
191                      lldb::addr_t frame_bottom, Status &err) override {
192     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
193 
194     const lldb::addr_t load_addr = process_address + m_offset;
195 
196     if (log) {
197       LLDB_LOGF(log,
198                 "EntityPersistentVariable::Dematerialize [address = 0x%" PRIx64
199                 ", m_name = %s, m_flags = 0x%hx]",
200                 (uint64_t)process_address + m_offset,
201                 m_persistent_variable_sp->GetName().AsCString(),
202                 m_persistent_variable_sp->m_flags);
203     }
204 
205     if (m_delegate) {
206       m_delegate->DidDematerialize(m_persistent_variable_sp);
207     }
208 
209     if ((m_persistent_variable_sp->m_flags &
210          ExpressionVariable::EVIsLLDBAllocated) ||
211         (m_persistent_variable_sp->m_flags &
212          ExpressionVariable::EVIsProgramReference)) {
213       if (m_persistent_variable_sp->m_flags &
214               ExpressionVariable::EVIsProgramReference &&
215           !m_persistent_variable_sp->m_live_sp) {
216         // If the reference comes from the program, then the
217         // ClangExpressionVariable's live variable data hasn't been set up yet.
218         // Do this now.
219 
220         lldb::addr_t location;
221         Status read_error;
222 
223         map.ReadPointerFromMemory(&location, load_addr, read_error);
224 
225         if (!read_error.Success()) {
226           err.SetErrorStringWithFormat(
227               "couldn't read the address of program-allocated variable %s: %s",
228               m_persistent_variable_sp->GetName().GetCString(),
229               read_error.AsCString());
230           return;
231         }
232 
233         m_persistent_variable_sp->m_live_sp = ValueObjectConstResult::Create(
234             map.GetBestExecutionContextScope(),
235             m_persistent_variable_sp.get()->GetCompilerType(),
236             m_persistent_variable_sp->GetName(), location, eAddressTypeLoad,
237             m_persistent_variable_sp->GetByteSize());
238 
239         if (frame_top != LLDB_INVALID_ADDRESS &&
240             frame_bottom != LLDB_INVALID_ADDRESS && location >= frame_bottom &&
241             location <= frame_top) {
242           // If the variable is resident in the stack frame created by the
243           // expression, then it cannot be relied upon to stay around.  We
244           // treat it as needing reallocation.
245           m_persistent_variable_sp->m_flags |=
246               ExpressionVariable::EVIsLLDBAllocated;
247           m_persistent_variable_sp->m_flags |=
248               ExpressionVariable::EVNeedsAllocation;
249           m_persistent_variable_sp->m_flags |=
250               ExpressionVariable::EVNeedsFreezeDry;
251           m_persistent_variable_sp->m_flags &=
252               ~ExpressionVariable::EVIsProgramReference;
253         }
254       }
255 
256       lldb::addr_t mem = m_persistent_variable_sp->m_live_sp->GetValue()
257                              .GetScalar()
258                              .ULongLong();
259 
260       if (!m_persistent_variable_sp->m_live_sp) {
261         err.SetErrorStringWithFormat(
262             "couldn't find the memory area used to store %s",
263             m_persistent_variable_sp->GetName().GetCString());
264         return;
265       }
266 
267       if (m_persistent_variable_sp->m_live_sp->GetValue()
268               .GetValueAddressType() != eAddressTypeLoad) {
269         err.SetErrorStringWithFormat(
270             "the address of the memory area for %s is in an incorrect format",
271             m_persistent_variable_sp->GetName().GetCString());
272         return;
273       }
274 
275       if (m_persistent_variable_sp->m_flags &
276               ExpressionVariable::EVNeedsFreezeDry ||
277           m_persistent_variable_sp->m_flags &
278               ExpressionVariable::EVKeepInTarget) {
279         LLDB_LOGF(log, "Dematerializing %s from 0x%" PRIx64 " (size = %llu)",
280                   m_persistent_variable_sp->GetName().GetCString(),
281                   (uint64_t)mem,
282                   (unsigned long long)m_persistent_variable_sp->GetByteSize());
283 
284         // Read the contents of the spare memory area
285 
286         m_persistent_variable_sp->ValueUpdated();
287 
288         Status read_error;
289 
290         map.ReadMemory(m_persistent_variable_sp->GetValueBytes(), mem,
291                        m_persistent_variable_sp->GetByteSize(), read_error);
292 
293         if (!read_error.Success()) {
294           err.SetErrorStringWithFormat(
295               "couldn't read the contents of %s from memory: %s",
296               m_persistent_variable_sp->GetName().GetCString(),
297               read_error.AsCString());
298           return;
299         }
300 
301         m_persistent_variable_sp->m_flags &=
302             ~ExpressionVariable::EVNeedsFreezeDry;
303       }
304     } else {
305       err.SetErrorStringWithFormat(
306           "no dematerialization happened for persistent variable %s",
307           m_persistent_variable_sp->GetName().AsCString());
308       return;
309     }
310 
311     lldb::ProcessSP process_sp =
312         map.GetBestExecutionContextScope()->CalculateProcess();
313     if (!process_sp || !process_sp->CanJIT()) {
314       // Allocations are not persistent so persistent variables cannot stay
315       // materialized.
316 
317       m_persistent_variable_sp->m_flags |=
318           ExpressionVariable::EVNeedsAllocation;
319 
320       DestroyAllocation(map, err);
321       if (!err.Success())
322         return;
323     } else if (m_persistent_variable_sp->m_flags &
324                    ExpressionVariable::EVNeedsAllocation &&
325                !(m_persistent_variable_sp->m_flags &
326                  ExpressionVariable::EVKeepInTarget)) {
327       DestroyAllocation(map, err);
328       if (!err.Success())
329         return;
330     }
331   }
332 
333   void DumpToLog(IRMemoryMap &map, lldb::addr_t process_address,
334                  Log *log) override {
335     StreamString dump_stream;
336 
337     Status err;
338 
339     const lldb::addr_t load_addr = process_address + m_offset;
340 
341     dump_stream.Printf("0x%" PRIx64 ": EntityPersistentVariable (%s)\n",
342                        load_addr,
343                        m_persistent_variable_sp->GetName().AsCString());
344 
345     {
346       dump_stream.Printf("Pointer:\n");
347 
348       DataBufferHeap data(m_size, 0);
349 
350       map.ReadMemory(data.GetBytes(), load_addr, m_size, err);
351 
352       if (!err.Success()) {
353         dump_stream.Printf("  <could not be read>\n");
354       } else {
355         DumpHexBytes(&dump_stream, data.GetBytes(), data.GetByteSize(), 16,
356                      load_addr);
357 
358         dump_stream.PutChar('\n');
359       }
360     }
361 
362     {
363       dump_stream.Printf("Target:\n");
364 
365       lldb::addr_t target_address;
366 
367       map.ReadPointerFromMemory(&target_address, load_addr, err);
368 
369       if (!err.Success()) {
370         dump_stream.Printf("  <could not be read>\n");
371       } else {
372         DataBufferHeap data(m_persistent_variable_sp->GetByteSize(), 0);
373 
374         map.ReadMemory(data.GetBytes(), target_address,
375                        m_persistent_variable_sp->GetByteSize(), err);
376 
377         if (!err.Success()) {
378           dump_stream.Printf("  <could not be read>\n");
379         } else {
380           DumpHexBytes(&dump_stream, data.GetBytes(), data.GetByteSize(), 16,
381                        target_address);
382 
383           dump_stream.PutChar('\n');
384         }
385       }
386     }
387 
388     log->PutString(dump_stream.GetString());
389   }
390 
391   void Wipe(IRMemoryMap &map, lldb::addr_t process_address) override {}
392 
393 private:
394   lldb::ExpressionVariableSP m_persistent_variable_sp;
395   Materializer::PersistentVariableDelegate *m_delegate;
396 };
397 
398 uint32_t Materializer::AddPersistentVariable(
399     lldb::ExpressionVariableSP &persistent_variable_sp,
400     PersistentVariableDelegate *delegate, Status &err) {
401   EntityVector::iterator iter = m_entities.insert(m_entities.end(), EntityUP());
402   *iter = std::make_unique<EntityPersistentVariable>(persistent_variable_sp,
403                                                      delegate);
404   uint32_t ret = AddStructMember(**iter);
405   (*iter)->SetOffset(ret);
406   return ret;
407 }
408 
409 class EntityVariable : public Materializer::Entity {
410 public:
411   EntityVariable(lldb::VariableSP &variable_sp)
412       : Entity(), m_variable_sp(variable_sp), m_is_reference(false),
413         m_temporary_allocation(LLDB_INVALID_ADDRESS),
414         m_temporary_allocation_size(0) {
415     // Hard-coding to maximum size of a pointer since all variables are
416     // materialized by reference
417     m_size = 8;
418     m_alignment = 8;
419     m_is_reference =
420         m_variable_sp->GetType()->GetForwardCompilerType().IsReferenceType();
421   }
422 
423   void Materialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map,
424                    lldb::addr_t process_address, Status &err) override {
425     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
426 
427     const lldb::addr_t load_addr = process_address + m_offset;
428     if (log) {
429       LLDB_LOGF(log,
430                 "EntityVariable::Materialize [address = 0x%" PRIx64
431                 ", m_variable_sp = %s]",
432                 (uint64_t)load_addr, m_variable_sp->GetName().AsCString());
433     }
434 
435     ExecutionContextScope *scope = frame_sp.get();
436 
437     if (!scope)
438       scope = map.GetBestExecutionContextScope();
439 
440     lldb::ValueObjectSP valobj_sp =
441         ValueObjectVariable::Create(scope, m_variable_sp);
442 
443     if (!valobj_sp) {
444       err.SetErrorStringWithFormat(
445           "couldn't get a value object for variable %s",
446           m_variable_sp->GetName().AsCString());
447       return;
448     }
449 
450     Status valobj_error = valobj_sp->GetError();
451 
452     if (valobj_error.Fail()) {
453       err.SetErrorStringWithFormat("couldn't get the value of variable %s: %s",
454                                    m_variable_sp->GetName().AsCString(),
455                                    valobj_error.AsCString());
456       return;
457     }
458 
459     if (m_is_reference) {
460       DataExtractor valobj_extractor;
461       Status extract_error;
462       valobj_sp->GetData(valobj_extractor, extract_error);
463 
464       if (!extract_error.Success()) {
465         err.SetErrorStringWithFormat(
466             "couldn't read contents of reference variable %s: %s",
467             m_variable_sp->GetName().AsCString(), extract_error.AsCString());
468         return;
469       }
470 
471       lldb::offset_t offset = 0;
472       lldb::addr_t reference_addr = valobj_extractor.GetAddress(&offset);
473 
474       Status write_error;
475       map.WritePointerToMemory(load_addr, reference_addr, write_error);
476 
477       if (!write_error.Success()) {
478         err.SetErrorStringWithFormat("couldn't write the contents of reference "
479                                      "variable %s to memory: %s",
480                                      m_variable_sp->GetName().AsCString(),
481                                      write_error.AsCString());
482         return;
483       }
484     } else {
485       AddressType address_type = eAddressTypeInvalid;
486       const bool scalar_is_load_address = false;
487       lldb::addr_t addr_of_valobj =
488           valobj_sp->GetAddressOf(scalar_is_load_address, &address_type);
489       if (addr_of_valobj != LLDB_INVALID_ADDRESS) {
490         Status write_error;
491         map.WritePointerToMemory(load_addr, addr_of_valobj, write_error);
492 
493         if (!write_error.Success()) {
494           err.SetErrorStringWithFormat(
495               "couldn't write the address of variable %s to memory: %s",
496               m_variable_sp->GetName().AsCString(), write_error.AsCString());
497           return;
498         }
499       } else {
500         DataExtractor data;
501         Status extract_error;
502         valobj_sp->GetData(data, extract_error);
503         if (!extract_error.Success()) {
504           err.SetErrorStringWithFormat("couldn't get the value of %s: %s",
505                                        m_variable_sp->GetName().AsCString(),
506                                        extract_error.AsCString());
507           return;
508         }
509 
510         if (m_temporary_allocation != LLDB_INVALID_ADDRESS) {
511           err.SetErrorStringWithFormat(
512               "trying to create a temporary region for %s but one exists",
513               m_variable_sp->GetName().AsCString());
514           return;
515         }
516 
517         if (data.GetByteSize() < m_variable_sp->GetType()->GetByteSize()) {
518           if (data.GetByteSize() == 0 &&
519               !m_variable_sp->LocationExpression().IsValid()) {
520             err.SetErrorStringWithFormat("the variable '%s' has no location, "
521                                          "it may have been optimized out",
522                                          m_variable_sp->GetName().AsCString());
523           } else {
524             err.SetErrorStringWithFormat(
525                 "size of variable %s (%" PRIu64
526                 ") is larger than the ValueObject's size (%" PRIu64 ")",
527                 m_variable_sp->GetName().AsCString(),
528                 m_variable_sp->GetType()->GetByteSize().getValueOr(0),
529                 data.GetByteSize());
530           }
531           return;
532         }
533 
534         llvm::Optional<size_t> opt_bit_align =
535             m_variable_sp->GetType()->GetLayoutCompilerType().GetTypeBitAlign(scope);
536         if (!opt_bit_align) {
537           err.SetErrorStringWithFormat("can't get the type alignment for %s",
538                                        m_variable_sp->GetName().AsCString());
539           return;
540         }
541 
542         size_t byte_align = (*opt_bit_align + 7) / 8;
543 
544         Status alloc_error;
545         const bool zero_memory = false;
546 
547         m_temporary_allocation = map.Malloc(
548             data.GetByteSize(), byte_align,
549             lldb::ePermissionsReadable | lldb::ePermissionsWritable,
550             IRMemoryMap::eAllocationPolicyMirror, zero_memory, alloc_error);
551 
552         m_temporary_allocation_size = data.GetByteSize();
553 
554         m_original_data = std::make_shared<DataBufferHeap>(data.GetDataStart(),
555                                                            data.GetByteSize());
556 
557         if (!alloc_error.Success()) {
558           err.SetErrorStringWithFormat(
559               "couldn't allocate a temporary region for %s: %s",
560               m_variable_sp->GetName().AsCString(), alloc_error.AsCString());
561           return;
562         }
563 
564         Status write_error;
565 
566         map.WriteMemory(m_temporary_allocation, data.GetDataStart(),
567                         data.GetByteSize(), write_error);
568 
569         if (!write_error.Success()) {
570           err.SetErrorStringWithFormat(
571               "couldn't write to the temporary region for %s: %s",
572               m_variable_sp->GetName().AsCString(), write_error.AsCString());
573           return;
574         }
575 
576         Status pointer_write_error;
577 
578         map.WritePointerToMemory(load_addr, m_temporary_allocation,
579                                  pointer_write_error);
580 
581         if (!pointer_write_error.Success()) {
582           err.SetErrorStringWithFormat(
583               "couldn't write the address of the temporary region for %s: %s",
584               m_variable_sp->GetName().AsCString(),
585               pointer_write_error.AsCString());
586         }
587       }
588     }
589   }
590 
591   void Dematerialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map,
592                      lldb::addr_t process_address, lldb::addr_t frame_top,
593                      lldb::addr_t frame_bottom, Status &err) override {
594     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
595 
596     const lldb::addr_t load_addr = process_address + m_offset;
597     if (log) {
598       LLDB_LOGF(log,
599                 "EntityVariable::Dematerialize [address = 0x%" PRIx64
600                 ", m_variable_sp = %s]",
601                 (uint64_t)load_addr, m_variable_sp->GetName().AsCString());
602     }
603 
604     if (m_temporary_allocation != LLDB_INVALID_ADDRESS) {
605       ExecutionContextScope *scope = frame_sp.get();
606 
607       if (!scope)
608         scope = map.GetBestExecutionContextScope();
609 
610       lldb::ValueObjectSP valobj_sp =
611           ValueObjectVariable::Create(scope, m_variable_sp);
612 
613       if (!valobj_sp) {
614         err.SetErrorStringWithFormat(
615             "couldn't get a value object for variable %s",
616             m_variable_sp->GetName().AsCString());
617         return;
618       }
619 
620       lldb_private::DataExtractor data;
621 
622       Status extract_error;
623 
624       map.GetMemoryData(data, m_temporary_allocation, valobj_sp->GetByteSize(),
625                         extract_error);
626 
627       if (!extract_error.Success()) {
628         err.SetErrorStringWithFormat("couldn't get the data for variable %s",
629                                      m_variable_sp->GetName().AsCString());
630         return;
631       }
632 
633       bool actually_write = true;
634 
635       if (m_original_data) {
636         if ((data.GetByteSize() == m_original_data->GetByteSize()) &&
637             !memcmp(m_original_data->GetBytes(), data.GetDataStart(),
638                     data.GetByteSize())) {
639           actually_write = false;
640         }
641       }
642 
643       Status set_error;
644 
645       if (actually_write) {
646         valobj_sp->SetData(data, set_error);
647 
648         if (!set_error.Success()) {
649           err.SetErrorStringWithFormat(
650               "couldn't write the new contents of %s back into the variable",
651               m_variable_sp->GetName().AsCString());
652           return;
653         }
654       }
655 
656       Status free_error;
657 
658       map.Free(m_temporary_allocation, free_error);
659 
660       if (!free_error.Success()) {
661         err.SetErrorStringWithFormat(
662             "couldn't free the temporary region for %s: %s",
663             m_variable_sp->GetName().AsCString(), free_error.AsCString());
664         return;
665       }
666 
667       m_original_data.reset();
668       m_temporary_allocation = LLDB_INVALID_ADDRESS;
669       m_temporary_allocation_size = 0;
670     }
671   }
672 
673   void DumpToLog(IRMemoryMap &map, lldb::addr_t process_address,
674                  Log *log) override {
675     StreamString dump_stream;
676 
677     const lldb::addr_t load_addr = process_address + m_offset;
678     dump_stream.Printf("0x%" PRIx64 ": EntityVariable\n", load_addr);
679 
680     Status err;
681 
682     lldb::addr_t ptr = LLDB_INVALID_ADDRESS;
683 
684     {
685       dump_stream.Printf("Pointer:\n");
686 
687       DataBufferHeap data(m_size, 0);
688 
689       map.ReadMemory(data.GetBytes(), load_addr, m_size, err);
690 
691       if (!err.Success()) {
692         dump_stream.Printf("  <could not be read>\n");
693       } else {
694         DataExtractor extractor(data.GetBytes(), data.GetByteSize(),
695                                 map.GetByteOrder(), map.GetAddressByteSize());
696 
697         DumpHexBytes(&dump_stream, data.GetBytes(), data.GetByteSize(), 16,
698                      load_addr);
699 
700         lldb::offset_t offset;
701 
702         ptr = extractor.GetAddress(&offset);
703 
704         dump_stream.PutChar('\n');
705       }
706     }
707 
708     if (m_temporary_allocation == LLDB_INVALID_ADDRESS) {
709       dump_stream.Printf("Points to process memory:\n");
710     } else {
711       dump_stream.Printf("Temporary allocation:\n");
712     }
713 
714     if (ptr == LLDB_INVALID_ADDRESS) {
715       dump_stream.Printf("  <could not be be found>\n");
716     } else {
717       DataBufferHeap data(m_temporary_allocation_size, 0);
718 
719       map.ReadMemory(data.GetBytes(), m_temporary_allocation,
720                      m_temporary_allocation_size, err);
721 
722       if (!err.Success()) {
723         dump_stream.Printf("  <could not be read>\n");
724       } else {
725         DumpHexBytes(&dump_stream, data.GetBytes(), data.GetByteSize(), 16,
726                      load_addr);
727 
728         dump_stream.PutChar('\n');
729       }
730     }
731 
732     log->PutString(dump_stream.GetString());
733   }
734 
735   void Wipe(IRMemoryMap &map, lldb::addr_t process_address) override {
736     if (m_temporary_allocation != LLDB_INVALID_ADDRESS) {
737       Status free_error;
738 
739       map.Free(m_temporary_allocation, free_error);
740 
741       m_temporary_allocation = LLDB_INVALID_ADDRESS;
742       m_temporary_allocation_size = 0;
743     }
744   }
745 
746 private:
747   lldb::VariableSP m_variable_sp;
748   bool m_is_reference;
749   lldb::addr_t m_temporary_allocation;
750   size_t m_temporary_allocation_size;
751   lldb::DataBufferSP m_original_data;
752 };
753 
754 uint32_t Materializer::AddVariable(lldb::VariableSP &variable_sp, Status &err) {
755   EntityVector::iterator iter = m_entities.insert(m_entities.end(), EntityUP());
756   *iter = std::make_unique<EntityVariable>(variable_sp);
757   uint32_t ret = AddStructMember(**iter);
758   (*iter)->SetOffset(ret);
759   return ret;
760 }
761 
762 class EntityResultVariable : public Materializer::Entity {
763 public:
764   EntityResultVariable(const CompilerType &type, bool is_program_reference,
765                        bool keep_in_memory,
766                        Materializer::PersistentVariableDelegate *delegate)
767       : Entity(), m_type(type), m_is_program_reference(is_program_reference),
768         m_keep_in_memory(keep_in_memory),
769         m_temporary_allocation(LLDB_INVALID_ADDRESS),
770         m_temporary_allocation_size(0), m_delegate(delegate) {
771     // Hard-coding to maximum size of a pointer since all results are
772     // materialized by reference
773     m_size = 8;
774     m_alignment = 8;
775   }
776 
777   void Materialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map,
778                    lldb::addr_t process_address, Status &err) override {
779     if (!m_is_program_reference) {
780       if (m_temporary_allocation != LLDB_INVALID_ADDRESS) {
781         err.SetErrorString("Trying to create a temporary region for the result "
782                            "but one exists");
783         return;
784       }
785 
786       const lldb::addr_t load_addr = process_address + m_offset;
787 
788       ExecutionContextScope *exe_scope = map.GetBestExecutionContextScope();
789 
790       llvm::Optional<uint64_t> byte_size = m_type.GetByteSize(exe_scope);
791       if (!byte_size) {
792         err.SetErrorString("can't get size of type");
793         return;
794       }
795 
796       llvm::Optional<size_t> opt_bit_align = m_type.GetTypeBitAlign(exe_scope);
797       if (!opt_bit_align) {
798         err.SetErrorStringWithFormat("can't get the type alignment");
799         return;
800       }
801 
802       size_t byte_align = (*opt_bit_align + 7) / 8;
803 
804       Status alloc_error;
805       const bool zero_memory = true;
806 
807       m_temporary_allocation = map.Malloc(
808           *byte_size, byte_align,
809           lldb::ePermissionsReadable | lldb::ePermissionsWritable,
810           IRMemoryMap::eAllocationPolicyMirror, zero_memory, alloc_error);
811       m_temporary_allocation_size = *byte_size;
812 
813       if (!alloc_error.Success()) {
814         err.SetErrorStringWithFormat(
815             "couldn't allocate a temporary region for the result: %s",
816             alloc_error.AsCString());
817         return;
818       }
819 
820       Status pointer_write_error;
821 
822       map.WritePointerToMemory(load_addr, m_temporary_allocation,
823                                pointer_write_error);
824 
825       if (!pointer_write_error.Success()) {
826         err.SetErrorStringWithFormat("couldn't write the address of the "
827                                      "temporary region for the result: %s",
828                                      pointer_write_error.AsCString());
829       }
830     }
831   }
832 
833   void Dematerialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map,
834                      lldb::addr_t process_address, lldb::addr_t frame_top,
835                      lldb::addr_t frame_bottom, Status &err) override {
836     err.Clear();
837 
838     ExecutionContextScope *exe_scope = map.GetBestExecutionContextScope();
839 
840     if (!exe_scope) {
841       err.SetErrorString("Couldn't dematerialize a result variable: invalid "
842                          "execution context scope");
843       return;
844     }
845 
846     lldb::addr_t address;
847     Status read_error;
848     const lldb::addr_t load_addr = process_address + m_offset;
849 
850     map.ReadPointerFromMemory(&address, load_addr, read_error);
851 
852     if (!read_error.Success()) {
853       err.SetErrorString("Couldn't dematerialize a result variable: couldn't "
854                          "read its address");
855       return;
856     }
857 
858     lldb::TargetSP target_sp = exe_scope->CalculateTarget();
859 
860     if (!target_sp) {
861       err.SetErrorString("Couldn't dematerialize a result variable: no target");
862       return;
863     }
864 
865     auto type_system_or_err =
866         target_sp->GetScratchTypeSystemForLanguage(m_type.GetMinimumLanguage());
867 
868     if (auto error = type_system_or_err.takeError()) {
869       err.SetErrorStringWithFormat("Couldn't dematerialize a result variable: "
870                                    "couldn't get the corresponding type "
871                                    "system: %s",
872                                    llvm::toString(std::move(error)).c_str());
873       return;
874     }
875     PersistentExpressionState *persistent_state =
876         type_system_or_err->GetPersistentExpressionState();
877 
878     if (!persistent_state) {
879       err.SetErrorString("Couldn't dematerialize a result variable: "
880                          "corresponding type system doesn't handle persistent "
881                          "variables");
882       return;
883     }
884 
885     ConstString name = m_delegate
886                            ? m_delegate->GetName()
887                            : persistent_state->GetNextPersistentVariableName();
888 
889     lldb::ExpressionVariableSP ret = persistent_state->CreatePersistentVariable(
890         exe_scope, name, m_type, map.GetByteOrder(), map.GetAddressByteSize());
891 
892     if (!ret) {
893       err.SetErrorStringWithFormat("couldn't dematerialize a result variable: "
894                                    "failed to make persistent variable %s",
895                                    name.AsCString());
896       return;
897     }
898 
899     lldb::ProcessSP process_sp =
900         map.GetBestExecutionContextScope()->CalculateProcess();
901 
902     if (m_delegate) {
903       m_delegate->DidDematerialize(ret);
904     }
905 
906     bool can_persist =
907         (m_is_program_reference && process_sp && process_sp->CanJIT() &&
908          !(address >= frame_bottom && address < frame_top));
909 
910     if (can_persist && m_keep_in_memory) {
911       ret->m_live_sp = ValueObjectConstResult::Create(exe_scope, m_type, name,
912                                                       address, eAddressTypeLoad,
913                                                       map.GetAddressByteSize());
914     }
915 
916     ret->ValueUpdated();
917 
918     const size_t pvar_byte_size = ret->GetByteSize();
919     uint8_t *pvar_data = ret->GetValueBytes();
920 
921     map.ReadMemory(pvar_data, address, pvar_byte_size, read_error);
922 
923     if (!read_error.Success()) {
924       err.SetErrorString(
925           "Couldn't dematerialize a result variable: couldn't read its memory");
926       return;
927     }
928 
929     if (!can_persist || !m_keep_in_memory) {
930       ret->m_flags |= ExpressionVariable::EVNeedsAllocation;
931 
932       if (m_temporary_allocation != LLDB_INVALID_ADDRESS) {
933         Status free_error;
934         map.Free(m_temporary_allocation, free_error);
935       }
936     } else {
937       ret->m_flags |= ExpressionVariable::EVIsLLDBAllocated;
938     }
939 
940     m_temporary_allocation = LLDB_INVALID_ADDRESS;
941     m_temporary_allocation_size = 0;
942   }
943 
944   void DumpToLog(IRMemoryMap &map, lldb::addr_t process_address,
945                  Log *log) override {
946     StreamString dump_stream;
947 
948     const lldb::addr_t load_addr = process_address + m_offset;
949 
950     dump_stream.Printf("0x%" PRIx64 ": EntityResultVariable\n", load_addr);
951 
952     Status err;
953 
954     lldb::addr_t ptr = LLDB_INVALID_ADDRESS;
955 
956     {
957       dump_stream.Printf("Pointer:\n");
958 
959       DataBufferHeap data(m_size, 0);
960 
961       map.ReadMemory(data.GetBytes(), load_addr, m_size, err);
962 
963       if (!err.Success()) {
964         dump_stream.Printf("  <could not be read>\n");
965       } else {
966         DataExtractor extractor(data.GetBytes(), data.GetByteSize(),
967                                 map.GetByteOrder(), map.GetAddressByteSize());
968 
969         DumpHexBytes(&dump_stream, data.GetBytes(), data.GetByteSize(), 16,
970                      load_addr);
971 
972         lldb::offset_t offset;
973 
974         ptr = extractor.GetAddress(&offset);
975 
976         dump_stream.PutChar('\n');
977       }
978     }
979 
980     if (m_temporary_allocation == LLDB_INVALID_ADDRESS) {
981       dump_stream.Printf("Points to process memory:\n");
982     } else {
983       dump_stream.Printf("Temporary allocation:\n");
984     }
985 
986     if (ptr == LLDB_INVALID_ADDRESS) {
987       dump_stream.Printf("  <could not be be found>\n");
988     } else {
989       DataBufferHeap data(m_temporary_allocation_size, 0);
990 
991       map.ReadMemory(data.GetBytes(), m_temporary_allocation,
992                      m_temporary_allocation_size, err);
993 
994       if (!err.Success()) {
995         dump_stream.Printf("  <could not be read>\n");
996       } else {
997         DumpHexBytes(&dump_stream, data.GetBytes(), data.GetByteSize(), 16,
998                      load_addr);
999 
1000         dump_stream.PutChar('\n');
1001       }
1002     }
1003 
1004     log->PutString(dump_stream.GetString());
1005   }
1006 
1007   void Wipe(IRMemoryMap &map, lldb::addr_t process_address) override {
1008     if (!m_keep_in_memory && m_temporary_allocation != LLDB_INVALID_ADDRESS) {
1009       Status free_error;
1010 
1011       map.Free(m_temporary_allocation, free_error);
1012     }
1013 
1014     m_temporary_allocation = LLDB_INVALID_ADDRESS;
1015     m_temporary_allocation_size = 0;
1016   }
1017 
1018 private:
1019   CompilerType m_type;
1020   bool m_is_program_reference;
1021   bool m_keep_in_memory;
1022 
1023   lldb::addr_t m_temporary_allocation;
1024   size_t m_temporary_allocation_size;
1025   Materializer::PersistentVariableDelegate *m_delegate;
1026 };
1027 
1028 uint32_t Materializer::AddResultVariable(const CompilerType &type,
1029                                          bool is_program_reference,
1030                                          bool keep_in_memory,
1031                                          PersistentVariableDelegate *delegate,
1032                                          Status &err) {
1033   EntityVector::iterator iter = m_entities.insert(m_entities.end(), EntityUP());
1034   *iter = std::make_unique<EntityResultVariable>(type, is_program_reference,
1035                                                  keep_in_memory, delegate);
1036   uint32_t ret = AddStructMember(**iter);
1037   (*iter)->SetOffset(ret);
1038   return ret;
1039 }
1040 
1041 class EntitySymbol : public Materializer::Entity {
1042 public:
1043   EntitySymbol(const Symbol &symbol) : Entity(), m_symbol(symbol) {
1044     // Hard-coding to maximum size of a symbol
1045     m_size = 8;
1046     m_alignment = 8;
1047   }
1048 
1049   void Materialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map,
1050                    lldb::addr_t process_address, Status &err) override {
1051     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1052 
1053     const lldb::addr_t load_addr = process_address + m_offset;
1054 
1055     if (log) {
1056       LLDB_LOGF(log,
1057                 "EntitySymbol::Materialize [address = 0x%" PRIx64
1058                 ", m_symbol = %s]",
1059                 (uint64_t)load_addr, m_symbol.GetName().AsCString());
1060     }
1061 
1062     const Address sym_address = m_symbol.GetAddress();
1063 
1064     ExecutionContextScope *exe_scope = map.GetBestExecutionContextScope();
1065 
1066     lldb::TargetSP target_sp;
1067 
1068     if (exe_scope)
1069       target_sp = map.GetBestExecutionContextScope()->CalculateTarget();
1070 
1071     if (!target_sp) {
1072       err.SetErrorStringWithFormat(
1073           "couldn't resolve symbol %s because there is no target",
1074           m_symbol.GetName().AsCString());
1075       return;
1076     }
1077 
1078     lldb::addr_t resolved_address = sym_address.GetLoadAddress(target_sp.get());
1079 
1080     if (resolved_address == LLDB_INVALID_ADDRESS)
1081       resolved_address = sym_address.GetFileAddress();
1082 
1083     Status pointer_write_error;
1084 
1085     map.WritePointerToMemory(load_addr, resolved_address, pointer_write_error);
1086 
1087     if (!pointer_write_error.Success()) {
1088       err.SetErrorStringWithFormat(
1089           "couldn't write the address of symbol %s: %s",
1090           m_symbol.GetName().AsCString(), pointer_write_error.AsCString());
1091       return;
1092     }
1093   }
1094 
1095   void Dematerialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map,
1096                      lldb::addr_t process_address, lldb::addr_t frame_top,
1097                      lldb::addr_t frame_bottom, Status &err) override {
1098     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1099 
1100     const lldb::addr_t load_addr = process_address + m_offset;
1101 
1102     if (log) {
1103       LLDB_LOGF(log,
1104                 "EntitySymbol::Dematerialize [address = 0x%" PRIx64
1105                 ", m_symbol = %s]",
1106                 (uint64_t)load_addr, m_symbol.GetName().AsCString());
1107     }
1108 
1109     // no work needs to be done
1110   }
1111 
1112   void DumpToLog(IRMemoryMap &map, lldb::addr_t process_address,
1113                  Log *log) override {
1114     StreamString dump_stream;
1115 
1116     Status err;
1117 
1118     const lldb::addr_t load_addr = process_address + m_offset;
1119 
1120     dump_stream.Printf("0x%" PRIx64 ": EntitySymbol (%s)\n", load_addr,
1121                        m_symbol.GetName().AsCString());
1122 
1123     {
1124       dump_stream.Printf("Pointer:\n");
1125 
1126       DataBufferHeap data(m_size, 0);
1127 
1128       map.ReadMemory(data.GetBytes(), load_addr, m_size, err);
1129 
1130       if (!err.Success()) {
1131         dump_stream.Printf("  <could not be read>\n");
1132       } else {
1133         DumpHexBytes(&dump_stream, data.GetBytes(), data.GetByteSize(), 16,
1134                      load_addr);
1135 
1136         dump_stream.PutChar('\n');
1137       }
1138     }
1139 
1140     log->PutString(dump_stream.GetString());
1141   }
1142 
1143   void Wipe(IRMemoryMap &map, lldb::addr_t process_address) override {}
1144 
1145 private:
1146   Symbol m_symbol;
1147 };
1148 
1149 uint32_t Materializer::AddSymbol(const Symbol &symbol_sp, Status &err) {
1150   EntityVector::iterator iter = m_entities.insert(m_entities.end(), EntityUP());
1151   *iter = std::make_unique<EntitySymbol>(symbol_sp);
1152   uint32_t ret = AddStructMember(**iter);
1153   (*iter)->SetOffset(ret);
1154   return ret;
1155 }
1156 
1157 class EntityRegister : public Materializer::Entity {
1158 public:
1159   EntityRegister(const RegisterInfo &register_info)
1160       : Entity(), m_register_info(register_info) {
1161     // Hard-coding alignment conservatively
1162     m_size = m_register_info.byte_size;
1163     m_alignment = m_register_info.byte_size;
1164   }
1165 
1166   void Materialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map,
1167                    lldb::addr_t process_address, Status &err) override {
1168     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1169 
1170     const lldb::addr_t load_addr = process_address + m_offset;
1171 
1172     if (log) {
1173       LLDB_LOGF(log,
1174                 "EntityRegister::Materialize [address = 0x%" PRIx64
1175                 ", m_register_info = %s]",
1176                 (uint64_t)load_addr, m_register_info.name);
1177     }
1178 
1179     RegisterValue reg_value;
1180 
1181     if (!frame_sp.get()) {
1182       err.SetErrorStringWithFormat(
1183           "couldn't materialize register %s without a stack frame",
1184           m_register_info.name);
1185       return;
1186     }
1187 
1188     lldb::RegisterContextSP reg_context_sp = frame_sp->GetRegisterContext();
1189 
1190     if (!reg_context_sp->ReadRegister(&m_register_info, reg_value)) {
1191       err.SetErrorStringWithFormat("couldn't read the value of register %s",
1192                                    m_register_info.name);
1193       return;
1194     }
1195 
1196     DataExtractor register_data;
1197 
1198     if (!reg_value.GetData(register_data)) {
1199       err.SetErrorStringWithFormat("couldn't get the data for register %s",
1200                                    m_register_info.name);
1201       return;
1202     }
1203 
1204     if (register_data.GetByteSize() != m_register_info.byte_size) {
1205       err.SetErrorStringWithFormat(
1206           "data for register %s had size %llu but we expected %llu",
1207           m_register_info.name, (unsigned long long)register_data.GetByteSize(),
1208           (unsigned long long)m_register_info.byte_size);
1209       return;
1210     }
1211 
1212     m_register_contents = std::make_shared<DataBufferHeap>(
1213         register_data.GetDataStart(), register_data.GetByteSize());
1214 
1215     Status write_error;
1216 
1217     map.WriteMemory(load_addr, register_data.GetDataStart(),
1218                     register_data.GetByteSize(), write_error);
1219 
1220     if (!write_error.Success()) {
1221       err.SetErrorStringWithFormat(
1222           "couldn't write the contents of register %s: %s",
1223           m_register_info.name, write_error.AsCString());
1224       return;
1225     }
1226   }
1227 
1228   void Dematerialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map,
1229                      lldb::addr_t process_address, lldb::addr_t frame_top,
1230                      lldb::addr_t frame_bottom, Status &err) override {
1231     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1232 
1233     const lldb::addr_t load_addr = process_address + m_offset;
1234 
1235     if (log) {
1236       LLDB_LOGF(log,
1237                 "EntityRegister::Dematerialize [address = 0x%" PRIx64
1238                 ", m_register_info = %s]",
1239                 (uint64_t)load_addr, m_register_info.name);
1240     }
1241 
1242     Status extract_error;
1243 
1244     DataExtractor register_data;
1245 
1246     if (!frame_sp.get()) {
1247       err.SetErrorStringWithFormat(
1248           "couldn't dematerialize register %s without a stack frame",
1249           m_register_info.name);
1250       return;
1251     }
1252 
1253     lldb::RegisterContextSP reg_context_sp = frame_sp->GetRegisterContext();
1254 
1255     map.GetMemoryData(register_data, load_addr, m_register_info.byte_size,
1256                       extract_error);
1257 
1258     if (!extract_error.Success()) {
1259       err.SetErrorStringWithFormat("couldn't get the data for register %s: %s",
1260                                    m_register_info.name,
1261                                    extract_error.AsCString());
1262       return;
1263     }
1264 
1265     if (!memcmp(register_data.GetDataStart(), m_register_contents->GetBytes(),
1266                 register_data.GetByteSize())) {
1267       // No write required, and in particular we avoid errors if the register
1268       // wasn't writable
1269 
1270       m_register_contents.reset();
1271       return;
1272     }
1273 
1274     m_register_contents.reset();
1275 
1276     RegisterValue register_value(
1277         const_cast<uint8_t *>(register_data.GetDataStart()),
1278         register_data.GetByteSize(), register_data.GetByteOrder());
1279 
1280     if (!reg_context_sp->WriteRegister(&m_register_info, register_value)) {
1281       err.SetErrorStringWithFormat("couldn't write the value of register %s",
1282                                    m_register_info.name);
1283       return;
1284     }
1285   }
1286 
1287   void DumpToLog(IRMemoryMap &map, lldb::addr_t process_address,
1288                  Log *log) override {
1289     StreamString dump_stream;
1290 
1291     Status err;
1292 
1293     const lldb::addr_t load_addr = process_address + m_offset;
1294 
1295     dump_stream.Printf("0x%" PRIx64 ": EntityRegister (%s)\n", load_addr,
1296                        m_register_info.name);
1297 
1298     {
1299       dump_stream.Printf("Value:\n");
1300 
1301       DataBufferHeap data(m_size, 0);
1302 
1303       map.ReadMemory(data.GetBytes(), load_addr, m_size, err);
1304 
1305       if (!err.Success()) {
1306         dump_stream.Printf("  <could not be read>\n");
1307       } else {
1308         DumpHexBytes(&dump_stream, data.GetBytes(), data.GetByteSize(), 16,
1309                      load_addr);
1310 
1311         dump_stream.PutChar('\n');
1312       }
1313     }
1314 
1315     log->PutString(dump_stream.GetString());
1316   }
1317 
1318   void Wipe(IRMemoryMap &map, lldb::addr_t process_address) override {}
1319 
1320 private:
1321   RegisterInfo m_register_info;
1322   lldb::DataBufferSP m_register_contents;
1323 };
1324 
1325 uint32_t Materializer::AddRegister(const RegisterInfo &register_info,
1326                                    Status &err) {
1327   EntityVector::iterator iter = m_entities.insert(m_entities.end(), EntityUP());
1328   *iter = std::make_unique<EntityRegister>(register_info);
1329   uint32_t ret = AddStructMember(**iter);
1330   (*iter)->SetOffset(ret);
1331   return ret;
1332 }
1333 
1334 Materializer::~Materializer() {
1335   DematerializerSP dematerializer_sp = m_dematerializer_wp.lock();
1336 
1337   if (dematerializer_sp)
1338     dematerializer_sp->Wipe();
1339 }
1340 
1341 Materializer::DematerializerSP
1342 Materializer::Materialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map,
1343                           lldb::addr_t process_address, Status &error) {
1344   ExecutionContextScope *exe_scope = frame_sp.get();
1345 
1346   if (!exe_scope)
1347     exe_scope = map.GetBestExecutionContextScope();
1348 
1349   DematerializerSP dematerializer_sp = m_dematerializer_wp.lock();
1350 
1351   if (dematerializer_sp) {
1352     error.SetErrorToGenericError();
1353     error.SetErrorString("Couldn't materialize: already materialized");
1354   }
1355 
1356   DematerializerSP ret(
1357       new Dematerializer(*this, frame_sp, map, process_address));
1358 
1359   if (!exe_scope) {
1360     error.SetErrorToGenericError();
1361     error.SetErrorString("Couldn't materialize: target doesn't exist");
1362   }
1363 
1364   for (EntityUP &entity_up : m_entities) {
1365     entity_up->Materialize(frame_sp, map, process_address, error);
1366 
1367     if (!error.Success())
1368       return DematerializerSP();
1369   }
1370 
1371   if (Log *log =
1372           lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)) {
1373     LLDB_LOGF(
1374         log,
1375         "Materializer::Materialize (frame_sp = %p, process_address = 0x%" PRIx64
1376         ") materialized:",
1377         static_cast<void *>(frame_sp.get()), process_address);
1378     for (EntityUP &entity_up : m_entities)
1379       entity_up->DumpToLog(map, process_address, log);
1380   }
1381 
1382   m_dematerializer_wp = ret;
1383 
1384   return ret;
1385 }
1386 
1387 void Materializer::Dematerializer::Dematerialize(Status &error,
1388                                                  lldb::addr_t frame_bottom,
1389                                                  lldb::addr_t frame_top) {
1390   lldb::StackFrameSP frame_sp;
1391 
1392   lldb::ThreadSP thread_sp = m_thread_wp.lock();
1393   if (thread_sp)
1394     frame_sp = thread_sp->GetFrameWithStackID(m_stack_id);
1395 
1396   ExecutionContextScope *exe_scope = m_map->GetBestExecutionContextScope();
1397 
1398   if (!IsValid()) {
1399     error.SetErrorToGenericError();
1400     error.SetErrorString("Couldn't dematerialize: invalid dematerializer");
1401   }
1402 
1403   if (!exe_scope) {
1404     error.SetErrorToGenericError();
1405     error.SetErrorString("Couldn't dematerialize: target is gone");
1406   } else {
1407     if (Log *log =
1408             lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)) {
1409       LLDB_LOGF(log,
1410                 "Materializer::Dematerialize (frame_sp = %p, process_address "
1411                 "= 0x%" PRIx64 ") about to dematerialize:",
1412                 static_cast<void *>(frame_sp.get()), m_process_address);
1413       for (EntityUP &entity_up : m_materializer->m_entities)
1414         entity_up->DumpToLog(*m_map, m_process_address, log);
1415     }
1416 
1417     for (EntityUP &entity_up : m_materializer->m_entities) {
1418       entity_up->Dematerialize(frame_sp, *m_map, m_process_address, frame_top,
1419                                frame_bottom, error);
1420 
1421       if (!error.Success())
1422         break;
1423     }
1424   }
1425 
1426   Wipe();
1427 }
1428 
1429 void Materializer::Dematerializer::Wipe() {
1430   if (!IsValid())
1431     return;
1432 
1433   for (EntityUP &entity_up : m_materializer->m_entities) {
1434     entity_up->Wipe(*m_map, m_process_address);
1435   }
1436 
1437   m_materializer = nullptr;
1438   m_map = nullptr;
1439   m_process_address = LLDB_INVALID_ADDRESS;
1440 }
1441 
1442 Materializer::PersistentVariableDelegate::~PersistentVariableDelegate() =
1443     default;
1444