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