1 //===-- RenderScriptRuntime.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 // C Includes
11 // C++ Includes
12 // Other libraries and framework includes
13 // Project includes
14 #include "RenderScriptRuntime.h"
15 
16 #include "lldb/Breakpoint/StoppointCallbackContext.h"
17 #include "lldb/Core/ConstString.h"
18 #include "lldb/Core/Debugger.h"
19 #include "lldb/Core/Error.h"
20 #include "lldb/Core/Log.h"
21 #include "lldb/Core/PluginManager.h"
22 #include "lldb/Core/RegularExpression.h"
23 #include "lldb/Core/ValueObjectVariable.h"
24 #include "lldb/DataFormatters/DumpValueObjectOptions.h"
25 #include "lldb/Expression/UserExpression.h"
26 #include "lldb/Host/StringConvert.h"
27 #include "lldb/Interpreter/Args.h"
28 #include "lldb/Interpreter/CommandInterpreter.h"
29 #include "lldb/Interpreter/CommandObjectMultiword.h"
30 #include "lldb/Interpreter/CommandReturnObject.h"
31 #include "lldb/Interpreter/Options.h"
32 #include "lldb/Symbol/Symbol.h"
33 #include "lldb/Symbol/Type.h"
34 #include "lldb/Symbol/VariableList.h"
35 #include "lldb/Target/Process.h"
36 #include "lldb/Target/RegisterContext.h"
37 #include "lldb/Target/Target.h"
38 #include "lldb/Target/Thread.h"
39 
40 using namespace lldb;
41 using namespace lldb_private;
42 using namespace lldb_renderscript;
43 
44 namespace
45 {
46 
47 // The empirical_type adds a basic level of validation to arbitrary data
48 // allowing us to track if data has been discovered and stored or not.
49 // An empirical_type will be marked as valid only if it has been explicitly assigned to.
50 template <typename type_t> class empirical_type
51 {
52 public:
53     // Ctor. Contents is invalid when constructed.
54     empirical_type() : valid(false) {}
55 
56     // Return true and copy contents to out if valid, else return false.
57     bool
58     get(type_t &out) const
59     {
60         if (valid)
61             out = data;
62         return valid;
63     }
64 
65     // Return a pointer to the contents or nullptr if it was not valid.
66     const type_t *
67     get() const
68     {
69         return valid ? &data : nullptr;
70     }
71 
72     // Assign data explicitly.
73     void
74     set(const type_t in)
75     {
76         data = in;
77         valid = true;
78     }
79 
80     // Mark contents as invalid.
81     void
82     invalidate()
83     {
84         valid = false;
85     }
86 
87     // Returns true if this type contains valid data.
88     bool
89     isValid() const
90     {
91         return valid;
92     }
93 
94     // Assignment operator.
95     empirical_type<type_t> &
96     operator=(const type_t in)
97     {
98         set(in);
99         return *this;
100     }
101 
102     // Dereference operator returns contents.
103     // Warning: Will assert if not valid so use only when you know data is valid.
104     const type_t &operator*() const
105     {
106         assert(valid);
107         return data;
108     }
109 
110 protected:
111     bool valid;
112     type_t data;
113 };
114 
115 // ArgItem is used by the GetArgs() function when reading function arguments from the target.
116 struct ArgItem
117 {
118     enum
119     {
120         ePointer,
121         eInt32,
122         eInt64,
123         eLong,
124         eBool
125     } type;
126 
127     uint64_t value;
128 
129     explicit operator uint64_t() const { return value; }
130 };
131 
132 // Context structure to be passed into GetArgsXXX(), argument reading functions below.
133 struct GetArgsCtx
134 {
135     RegisterContext *reg_ctx;
136     Process *process;
137 };
138 
139 bool
140 GetArgsX86(const GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args)
141 {
142     Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
143 
144     // get the current stack pointer
145     uint64_t sp = ctx.reg_ctx->GetSP();
146 
147     for (size_t i = 0; i < num_args; ++i)
148     {
149         ArgItem &arg = arg_list[i];
150         // advance up the stack by one argument
151         sp += sizeof(uint32_t);
152         // get the argument type size
153         size_t arg_size = sizeof(uint32_t);
154         // read the argument from memory
155         arg.value = 0;
156         Error error;
157         size_t read = ctx.process->ReadMemory(sp, &arg.value, sizeof(uint32_t), error);
158         if (read != arg_size || !error.Success())
159         {
160             if (log)
161                 log->Printf("%s - error reading argument: %" PRIu64 " '%s'", __FUNCTION__, uint64_t(i),
162                             error.AsCString());
163             return false;
164         }
165     }
166     return true;
167 }
168 
169 bool
170 GetArgsX86_64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args)
171 {
172     Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
173 
174     // number of arguments passed in registers
175     static const uint32_t c_args_in_reg = 6;
176     // register passing order
177     static const std::array<const char *, c_args_in_reg> c_reg_names{{"rdi", "rsi", "rdx", "rcx", "r8", "r9"}};
178     // argument type to size mapping
179     static const std::array<size_t, 5> arg_size{{
180         8, // ePointer,
181         4, // eInt32,
182         8, // eInt64,
183         8, // eLong,
184         4, // eBool,
185     }};
186 
187     // get the current stack pointer
188     uint64_t sp = ctx.reg_ctx->GetSP();
189     // step over the return address
190     sp += sizeof(uint64_t);
191 
192     // check the stack alignment was correct (16 byte aligned)
193     if ((sp & 0xf) != 0x0)
194     {
195         if (log)
196             log->Printf("%s - stack misaligned", __FUNCTION__);
197         return false;
198     }
199 
200     // find the start of arguments on the stack
201     uint64_t sp_offset = 0;
202     for (uint32_t i = c_args_in_reg; i < num_args; ++i)
203     {
204         sp_offset += arg_size[arg_list[i].type];
205     }
206     // round up to multiple of 16
207     sp_offset = (sp_offset + 0xf) & 0xf;
208     sp += sp_offset;
209 
210     for (size_t i = 0; i < num_args; ++i)
211     {
212         bool success = false;
213         ArgItem &arg = arg_list[i];
214         // arguments passed in registers
215         if (i < c_args_in_reg)
216         {
217             const RegisterInfo *rArg = ctx.reg_ctx->GetRegisterInfoByName(c_reg_names[i]);
218             RegisterValue rVal;
219             if (ctx.reg_ctx->ReadRegister(rArg, rVal))
220                 arg.value = rVal.GetAsUInt64(0, &success);
221         }
222         // arguments passed on the stack
223         else
224         {
225             // get the argument type size
226             const size_t size = arg_size[arg_list[i].type];
227             // read the argument from memory
228             arg.value = 0;
229             // note: due to little endian layout reading 4 or 8 bytes will give the correct value.
230             Error error;
231             size_t read = ctx.process->ReadMemory(sp, &arg.value, size, error);
232             success = (error.Success() && read==size);
233             // advance past this argument
234             sp -= size;
235         }
236         // fail if we couldn't read this argument
237         if (!success)
238         {
239             if (log)
240                 log->Printf("%s - error reading argument: %" PRIu64, __FUNCTION__, uint64_t(i));
241             return false;
242         }
243     }
244     return true;
245 }
246 
247 bool
248 GetArgsArm(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args)
249 {
250     // number of arguments passed in registers
251     static const uint32_t c_args_in_reg = 4;
252 
253     Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
254 
255     // get the current stack pointer
256     uint64_t sp = ctx.reg_ctx->GetSP();
257 
258     for (size_t i = 0; i < num_args; ++i)
259     {
260         bool success = false;
261         ArgItem &arg = arg_list[i];
262         // arguments passed in registers
263         if (i < c_args_in_reg)
264         {
265             const RegisterInfo *rArg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
266             RegisterValue rVal;
267             if (ctx.reg_ctx->ReadRegister(rArg, rVal))
268                 arg.value = rVal.GetAsUInt32(0, &success);
269         }
270         // arguments passed on the stack
271         else
272         {
273             // get the argument type size
274             const size_t arg_size = sizeof(uint32_t);
275             // clear all 64bits
276             arg.value = 0;
277             // read this argument from memory
278             Error error;
279             size_t bytes_read = ctx.process->ReadMemory(sp, &arg.value, arg_size, error);
280             success = (error.Success() && bytes_read == arg_size);
281             // advance the stack pointer
282             sp += sizeof(uint32_t);
283         }
284         // fail if we couldn't read this argument
285         if (!success)
286         {
287             if (log)
288                 log->Printf("%s - error reading argument: %" PRIu64, __FUNCTION__, uint64_t(i));
289             return false;
290         }
291     }
292     return true;
293 }
294 
295 bool
296 GetArgsAarch64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args)
297 {
298     // number of arguments passed in registers
299     static const uint32_t c_args_in_reg = 8;
300 
301     Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
302 
303     for (size_t i = 0; i < num_args; ++i)
304     {
305         bool success = false;
306         ArgItem &arg = arg_list[i];
307         // arguments passed in registers
308         if (i < c_args_in_reg)
309         {
310             const RegisterInfo *rArg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
311             RegisterValue rVal;
312             if (ctx.reg_ctx->ReadRegister(rArg, rVal))
313                 arg.value = rVal.GetAsUInt64(0, &success);
314         }
315         // arguments passed on the stack
316         else
317         {
318             if (log)
319                 log->Printf("%s - reading arguments spilled to stack not implemented", __FUNCTION__);
320         }
321         // fail if we couldn't read this argument
322         if (!success)
323         {
324             if (log)
325                 log->Printf("%s - error reading argument: %" PRIu64, __FUNCTION__,
326                             uint64_t(i));
327             return false;
328         }
329     }
330     return true;
331 }
332 
333 bool
334 GetArgsMipsel(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args)
335 {
336     // number of arguments passed in registers
337     static const uint32_t c_args_in_reg = 4;
338     // register file offset to first argument
339     static const uint32_t c_reg_offset = 4;
340 
341     Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
342 
343     for (size_t i = 0; i < num_args; ++i)
344     {
345         bool success = false;
346         ArgItem &arg = arg_list[i];
347         // arguments passed in registers
348         if (i < c_args_in_reg)
349         {
350             const RegisterInfo *rArg = ctx.reg_ctx->GetRegisterInfoAtIndex(i + c_reg_offset);
351             RegisterValue rVal;
352             if (ctx.reg_ctx->ReadRegister(rArg, rVal))
353                 arg.value = rVal.GetAsUInt64(0, &success);
354         }
355         // arguments passed on the stack
356         else
357         {
358             if (log)
359                 log->Printf("%s - reading arguments spilled to stack not implemented.", __FUNCTION__);
360         }
361         // fail if we couldn't read this argument
362         if (!success)
363         {
364             if (log)
365                 log->Printf("%s - error reading argument: %" PRIu64, __FUNCTION__, uint64_t(i));
366             return false;
367         }
368     }
369     return true;
370 }
371 
372 bool
373 GetArgsMips64el(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args)
374 {
375     // number of arguments passed in registers
376     static const uint32_t c_args_in_reg = 8;
377     // register file offset to first argument
378     static const uint32_t c_reg_offset = 4;
379 
380     Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
381 
382     // get the current stack pointer
383     uint64_t sp = ctx.reg_ctx->GetSP();
384 
385     for (size_t i = 0; i < num_args; ++i)
386     {
387         bool success = false;
388         ArgItem &arg = arg_list[i];
389         // arguments passed in registers
390         if (i < c_args_in_reg)
391         {
392             const RegisterInfo *rArg = ctx.reg_ctx->GetRegisterInfoAtIndex(i + c_reg_offset);
393             RegisterValue rVal;
394             if (ctx.reg_ctx->ReadRegister(rArg, rVal))
395                 arg.value = rVal.GetAsUInt64(0, &success);
396         }
397         // arguments passed on the stack
398         else
399         {
400             // get the argument type size
401             const size_t arg_size = sizeof(uint64_t);
402             // clear all 64bits
403             arg.value = 0;
404             // read this argument from memory
405             Error error;
406             size_t bytes_read = ctx.process->ReadMemory(sp, &arg.value, arg_size, error);
407             success = (error.Success() && bytes_read == arg_size);
408             // advance the stack pointer
409             sp += arg_size;
410         }
411         // fail if we couldn't read this argument
412         if (!success)
413         {
414             if (log)
415                 log->Printf("%s - error reading argument: %" PRIu64, __FUNCTION__, uint64_t(i));
416             return false;
417         }
418     }
419     return true;
420 }
421 
422 bool
423 GetArgs(ExecutionContext &context, ArgItem *arg_list, size_t num_args)
424 {
425     Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
426 
427     // verify that we have a target
428     if (!context.GetTargetPtr())
429     {
430         if (log)
431             log->Printf("%s - invalid target", __FUNCTION__);
432         return false;
433     }
434 
435     GetArgsCtx ctx = {context.GetRegisterContext(), context.GetProcessPtr()};
436     assert(ctx.reg_ctx && ctx.process);
437 
438     // dispatch based on architecture
439     switch (context.GetTargetPtr()->GetArchitecture().GetMachine())
440     {
441         case llvm::Triple::ArchType::x86:
442             return GetArgsX86(ctx, arg_list, num_args);
443 
444         case llvm::Triple::ArchType::x86_64:
445             return GetArgsX86_64(ctx, arg_list, num_args);
446 
447         case llvm::Triple::ArchType::arm:
448             return GetArgsArm(ctx, arg_list, num_args);
449 
450         case llvm::Triple::ArchType::aarch64:
451             return GetArgsAarch64(ctx, arg_list, num_args);
452 
453         case llvm::Triple::ArchType::mipsel:
454             return GetArgsMipsel(ctx, arg_list, num_args);
455 
456         case llvm::Triple::ArchType::mips64el:
457             return GetArgsMips64el(ctx, arg_list, num_args);
458 
459         default:
460             // unsupported architecture
461             if (log)
462             {
463                 log->Printf("%s - architecture not supported: '%s'", __FUNCTION__,
464                             context.GetTargetRef().GetArchitecture().GetArchitectureName());
465             }
466             return false;
467     }
468 }
469 } // anonymous namespace
470 
471 // The ScriptDetails class collects data associated with a single script instance.
472 struct RenderScriptRuntime::ScriptDetails
473 {
474     ~ScriptDetails() = default;
475 
476     enum ScriptType
477     {
478         eScript,
479         eScriptC
480     };
481 
482     // The derived type of the script.
483     empirical_type<ScriptType> type;
484     // The name of the original source file.
485     empirical_type<std::string> resName;
486     // Path to script .so file on the device.
487     empirical_type<std::string> scriptDyLib;
488     // Directory where kernel objects are cached on device.
489     empirical_type<std::string> cacheDir;
490     // Pointer to the context which owns this script.
491     empirical_type<lldb::addr_t> context;
492     // Pointer to the script object itself.
493     empirical_type<lldb::addr_t> script;
494 };
495 
496 // This Element class represents the Element object in RS,
497 // defining the type associated with an Allocation.
498 struct RenderScriptRuntime::Element
499 {
500     // Taken from rsDefines.h
501     enum DataKind
502     {
503         RS_KIND_USER,
504         RS_KIND_PIXEL_L = 7,
505         RS_KIND_PIXEL_A,
506         RS_KIND_PIXEL_LA,
507         RS_KIND_PIXEL_RGB,
508         RS_KIND_PIXEL_RGBA,
509         RS_KIND_PIXEL_DEPTH,
510         RS_KIND_PIXEL_YUV,
511         RS_KIND_INVALID = 100
512     };
513 
514     // Taken from rsDefines.h
515     enum DataType
516     {
517         RS_TYPE_NONE = 0,
518         RS_TYPE_FLOAT_16,
519         RS_TYPE_FLOAT_32,
520         RS_TYPE_FLOAT_64,
521         RS_TYPE_SIGNED_8,
522         RS_TYPE_SIGNED_16,
523         RS_TYPE_SIGNED_32,
524         RS_TYPE_SIGNED_64,
525         RS_TYPE_UNSIGNED_8,
526         RS_TYPE_UNSIGNED_16,
527         RS_TYPE_UNSIGNED_32,
528         RS_TYPE_UNSIGNED_64,
529         RS_TYPE_BOOLEAN,
530 
531         RS_TYPE_UNSIGNED_5_6_5,
532         RS_TYPE_UNSIGNED_5_5_5_1,
533         RS_TYPE_UNSIGNED_4_4_4_4,
534 
535         RS_TYPE_MATRIX_4X4,
536         RS_TYPE_MATRIX_3X3,
537         RS_TYPE_MATRIX_2X2,
538 
539         RS_TYPE_ELEMENT = 1000,
540         RS_TYPE_TYPE,
541         RS_TYPE_ALLOCATION,
542         RS_TYPE_SAMPLER,
543         RS_TYPE_SCRIPT,
544         RS_TYPE_MESH,
545         RS_TYPE_PROGRAM_FRAGMENT,
546         RS_TYPE_PROGRAM_VERTEX,
547         RS_TYPE_PROGRAM_RASTER,
548         RS_TYPE_PROGRAM_STORE,
549         RS_TYPE_FONT,
550 
551         RS_TYPE_INVALID = 10000
552     };
553 
554     std::vector<Element> children;            // Child Element fields for structs
555     empirical_type<lldb::addr_t> element_ptr; // Pointer to the RS Element of the Type
556     empirical_type<DataType> type;            // Type of each data pointer stored by the allocation
557     empirical_type<DataKind> type_kind;       // Defines pixel type if Allocation is created from an image
558     empirical_type<uint32_t> type_vec_size;   // Vector size of each data point, e.g '4' for uchar4
559     empirical_type<uint32_t> field_count;     // Number of Subelements
560     empirical_type<uint32_t> datum_size;      // Size of a single Element with padding
561     empirical_type<uint32_t> padding;         // Number of padding bytes
562     empirical_type<uint32_t> array_size;      // Number of items in array, only needed for strucrs
563     ConstString type_name;                    // Name of type, only needed for structs
564 
565     static const ConstString &
566     GetFallbackStructName(); // Print this as the type name of a struct Element
567                              // If we can't resolve the actual struct name
568 
569     bool
570     shouldRefresh() const
571     {
572         const bool valid_ptr = element_ptr.isValid() && *element_ptr.get() != 0x0;
573         const bool valid_type = type.isValid() && type_vec_size.isValid() && type_kind.isValid();
574         return !valid_ptr || !valid_type || !datum_size.isValid();
575     }
576 };
577 
578 // This AllocationDetails class collects data associated with a single
579 // allocation instance.
580 struct RenderScriptRuntime::AllocationDetails
581 {
582     struct Dimension
583     {
584         uint32_t dim_1;
585         uint32_t dim_2;
586         uint32_t dim_3;
587         uint32_t cubeMap;
588 
589         Dimension()
590         {
591             dim_1 = 0;
592             dim_2 = 0;
593             dim_3 = 0;
594             cubeMap = 0;
595         }
596     };
597 
598     // The FileHeader struct specifies the header we use for writing allocations to a binary file.
599     // Our format begins with the ASCII characters "RSAD", identifying the file as an allocation dump.
600     // Member variables dims and hdr_size are then written consecutively, immediately followed by an instance of
601     // the ElementHeader struct. Because Elements can contain subelements, there may be more than one instance
602     // of the ElementHeader struct. With this first instance being the root element, and the other instances being
603     // the root's descendants. To identify which instances are an ElementHeader's children, each struct
604     // is immediately followed by a sequence of consecutive offsets to the start of its child structs.
605     // These offsets are 4 bytes in size, and the 0 offset signifies no more children.
606     struct FileHeader
607     {
608         uint8_t ident[4];  // ASCII 'RSAD' identifying the file
609         uint32_t dims[3];  // Dimensions
610         uint16_t hdr_size; // Header size in bytes, including all element headers
611     };
612 
613     struct ElementHeader
614     {
615         uint16_t type;         // DataType enum
616         uint32_t kind;         // DataKind enum
617         uint32_t element_size; // Size of a single element, including padding
618         uint16_t vector_size;  // Vector width
619         uint32_t array_size;   // Number of elements in array
620     };
621 
622     // Monotonically increasing from 1
623     static uint32_t ID;
624 
625     // Maps Allocation DataType enum and vector size to printable strings
626     // using mapping from RenderScript numerical types summary documentation
627     static const char *RsDataTypeToString[][4];
628 
629     // Maps Allocation DataKind enum to printable strings
630     static const char *RsDataKindToString[];
631 
632     // Maps allocation types to format sizes for printing.
633     static const uint32_t RSTypeToFormat[][3];
634 
635     // Give each allocation an ID as a way
636     // for commands to reference it.
637     const uint32_t id;
638 
639     RenderScriptRuntime::Element element;  // Allocation Element type
640     empirical_type<Dimension> dimension;   // Dimensions of the Allocation
641     empirical_type<lldb::addr_t> address;  // Pointer to address of the RS Allocation
642     empirical_type<lldb::addr_t> data_ptr; // Pointer to the data held by the Allocation
643     empirical_type<lldb::addr_t> type_ptr; // Pointer to the RS Type of the Allocation
644     empirical_type<lldb::addr_t> context;  // Pointer to the RS Context of the Allocation
645     empirical_type<uint32_t> size;         // Size of the allocation
646     empirical_type<uint32_t> stride;       // Stride between rows of the allocation
647 
648     // Give each allocation an id, so we can reference it in user commands.
649     AllocationDetails() : id(ID++) {}
650 
651     bool
652     shouldRefresh() const
653     {
654         bool valid_ptrs = data_ptr.isValid() && *data_ptr.get() != 0x0;
655         valid_ptrs = valid_ptrs && type_ptr.isValid() && *type_ptr.get() != 0x0;
656         return !valid_ptrs || !dimension.isValid() || !size.isValid() || element.shouldRefresh();
657     }
658 };
659 
660 const ConstString &
661 RenderScriptRuntime::Element::GetFallbackStructName()
662 {
663     static const ConstString FallbackStructName("struct");
664     return FallbackStructName;
665 }
666 
667 uint32_t RenderScriptRuntime::AllocationDetails::ID = 1;
668 
669 const char *RenderScriptRuntime::AllocationDetails::RsDataKindToString[] = {
670     "User",
671     "Undefined",  "Undefined",   "Undefined", "Undefined", "Undefined",  "Undefined", // Enum jumps from 0 to 7
672     "L Pixel",    "A Pixel",     "LA Pixel",  "RGB Pixel",
673     "RGBA Pixel", "Pixel Depth", "YUV Pixel"};
674 
675 const char *RenderScriptRuntime::AllocationDetails::RsDataTypeToString[][4] = {
676     {"None", "None", "None", "None"},
677     {"half", "half2", "half3", "half4"},
678     {"float", "float2", "float3", "float4"},
679     {"double", "double2", "double3", "double4"},
680     {"char", "char2", "char3", "char4"},
681     {"short", "short2", "short3", "short4"},
682     {"int", "int2", "int3", "int4"},
683     {"long", "long2", "long3", "long4"},
684     {"uchar", "uchar2", "uchar3", "uchar4"},
685     {"ushort", "ushort2", "ushort3", "ushort4"},
686     {"uint", "uint2", "uint3", "uint4"},
687     {"ulong", "ulong2", "ulong3", "ulong4"},
688     {"bool", "bool2", "bool3", "bool4"},
689     {"packed_565", "packed_565", "packed_565", "packed_565"},
690     {"packed_5551", "packed_5551", "packed_5551", "packed_5551"},
691     {"packed_4444", "packed_4444", "packed_4444", "packed_4444"},
692     {"rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4"},
693     {"rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3"},
694     {"rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2"},
695 
696     // Handlers
697     {"RS Element", "RS Element", "RS Element", "RS Element"},
698     {"RS Type", "RS Type", "RS Type", "RS Type"},
699     {"RS Allocation", "RS Allocation", "RS Allocation", "RS Allocation"},
700     {"RS Sampler", "RS Sampler", "RS Sampler", "RS Sampler"},
701     {"RS Script", "RS Script", "RS Script", "RS Script"},
702 
703     // Deprecated
704     {"RS Mesh", "RS Mesh", "RS Mesh", "RS Mesh"},
705     {"RS Program Fragment", "RS Program Fragment", "RS Program Fragment", "RS Program Fragment"},
706     {"RS Program Vertex", "RS Program Vertex", "RS Program Vertex", "RS Program Vertex"},
707     {"RS Program Raster", "RS Program Raster", "RS Program Raster", "RS Program Raster"},
708     {"RS Program Store", "RS Program Store", "RS Program Store", "RS Program Store"},
709     {"RS Font", "RS Font", "RS Font", "RS Font"}};
710 
711 // Used as an index into the RSTypeToFormat array elements
712 enum TypeToFormatIndex
713 {
714     eFormatSingle = 0,
715     eFormatVector,
716     eElementSize
717 };
718 
719 // { format enum of single element, format enum of element vector, size of element}
720 const uint32_t RenderScriptRuntime::AllocationDetails::RSTypeToFormat[][3] = {
721     {eFormatHex, eFormatHex, 1},                                          // RS_TYPE_NONE
722     {eFormatFloat, eFormatVectorOfFloat16, 2},                            // RS_TYPE_FLOAT_16
723     {eFormatFloat, eFormatVectorOfFloat32, sizeof(float)},                // RS_TYPE_FLOAT_32
724     {eFormatFloat, eFormatVectorOfFloat64, sizeof(double)},               // RS_TYPE_FLOAT_64
725     {eFormatDecimal, eFormatVectorOfSInt8, sizeof(int8_t)},               // RS_TYPE_SIGNED_8
726     {eFormatDecimal, eFormatVectorOfSInt16, sizeof(int16_t)},             // RS_TYPE_SIGNED_16
727     {eFormatDecimal, eFormatVectorOfSInt32, sizeof(int32_t)},             // RS_TYPE_SIGNED_32
728     {eFormatDecimal, eFormatVectorOfSInt64, sizeof(int64_t)},             // RS_TYPE_SIGNED_64
729     {eFormatDecimal, eFormatVectorOfUInt8, sizeof(uint8_t)},              // RS_TYPE_UNSIGNED_8
730     {eFormatDecimal, eFormatVectorOfUInt16, sizeof(uint16_t)},            // RS_TYPE_UNSIGNED_16
731     {eFormatDecimal, eFormatVectorOfUInt32, sizeof(uint32_t)},            // RS_TYPE_UNSIGNED_32
732     {eFormatDecimal, eFormatVectorOfUInt64, sizeof(uint64_t)},            // RS_TYPE_UNSIGNED_64
733     {eFormatBoolean, eFormatBoolean, 1},                                  // RS_TYPE_BOOL
734     {eFormatHex, eFormatHex, sizeof(uint16_t)},                           // RS_TYPE_UNSIGNED_5_6_5
735     {eFormatHex, eFormatHex, sizeof(uint16_t)},                           // RS_TYPE_UNSIGNED_5_5_5_1
736     {eFormatHex, eFormatHex, sizeof(uint16_t)},                           // RS_TYPE_UNSIGNED_4_4_4_4
737     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 16}, // RS_TYPE_MATRIX_4X4
738     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 9},  // RS_TYPE_MATRIX_3X3
739     {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 4}   // RS_TYPE_MATRIX_2X2
740 };
741 
742 const std::string RenderScriptRuntime::s_runtimeExpandSuffix(".expand");
743 const std::array<const char *, 3> RenderScriptRuntime::s_runtimeCoordVars{{"rsIndex", "p->current.y", "p->current.z"}};
744 //------------------------------------------------------------------
745 // Static Functions
746 //------------------------------------------------------------------
747 LanguageRuntime *
748 RenderScriptRuntime::CreateInstance(Process *process, lldb::LanguageType language)
749 {
750 
751     if (language == eLanguageTypeExtRenderScript)
752         return new RenderScriptRuntime(process);
753     else
754         return nullptr;
755 }
756 
757 // Callback with a module to search for matching symbols.
758 // We first check that the module contains RS kernels.
759 // Then look for a symbol which matches our kernel name.
760 // The breakpoint address is finally set using the address of this symbol.
761 Searcher::CallbackReturn
762 RSBreakpointResolver::SearchCallback(SearchFilter &filter, SymbolContext &context, Address *, bool)
763 {
764     ModuleSP module = context.module_sp;
765 
766     if (!module)
767         return Searcher::eCallbackReturnContinue;
768 
769     // Is this a module containing renderscript kernels?
770     if (nullptr == module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData))
771         return Searcher::eCallbackReturnContinue;
772 
773     // Attempt to set a breakpoint on the kernel name symbol within the module library.
774     // If it's not found, it's likely debug info is unavailable - try to set a
775     // breakpoint on <name>.expand.
776 
777     const Symbol *kernel_sym = module->FindFirstSymbolWithNameAndType(m_kernel_name, eSymbolTypeCode);
778     if (!kernel_sym)
779     {
780         std::string kernel_name_expanded(m_kernel_name.AsCString());
781         kernel_name_expanded.append(".expand");
782         kernel_sym = module->FindFirstSymbolWithNameAndType(ConstString(kernel_name_expanded.c_str()), eSymbolTypeCode);
783     }
784 
785     if (kernel_sym)
786     {
787         Address bp_addr = kernel_sym->GetAddress();
788         if (filter.AddressPasses(bp_addr))
789             m_breakpoint->AddLocation(bp_addr);
790     }
791 
792     return Searcher::eCallbackReturnContinue;
793 }
794 
795 void
796 RenderScriptRuntime::Initialize()
797 {
798     PluginManager::RegisterPlugin(GetPluginNameStatic(), "RenderScript language support", CreateInstance,
799                                   GetCommandObject);
800 }
801 
802 void
803 RenderScriptRuntime::Terminate()
804 {
805     PluginManager::UnregisterPlugin(CreateInstance);
806 }
807 
808 lldb_private::ConstString
809 RenderScriptRuntime::GetPluginNameStatic()
810 {
811     static ConstString g_name("renderscript");
812     return g_name;
813 }
814 
815 RenderScriptRuntime::ModuleKind
816 RenderScriptRuntime::GetModuleKind(const lldb::ModuleSP &module_sp)
817 {
818     if (module_sp)
819     {
820         // Is this a module containing renderscript kernels?
821         const Symbol *info_sym = module_sp->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData);
822         if (info_sym)
823         {
824             return eModuleKindKernelObj;
825         }
826 
827         // Is this the main RS runtime library
828         const ConstString rs_lib("libRS.so");
829         if (module_sp->GetFileSpec().GetFilename() == rs_lib)
830         {
831             return eModuleKindLibRS;
832         }
833 
834         const ConstString rs_driverlib("libRSDriver.so");
835         if (module_sp->GetFileSpec().GetFilename() == rs_driverlib)
836         {
837             return eModuleKindDriver;
838         }
839 
840         const ConstString rs_cpureflib("libRSCpuRef.so");
841         if (module_sp->GetFileSpec().GetFilename() == rs_cpureflib)
842         {
843             return eModuleKindImpl;
844         }
845     }
846     return eModuleKindIgnored;
847 }
848 
849 bool
850 RenderScriptRuntime::IsRenderScriptModule(const lldb::ModuleSP &module_sp)
851 {
852     return GetModuleKind(module_sp) != eModuleKindIgnored;
853 }
854 
855 void
856 RenderScriptRuntime::ModulesDidLoad(const ModuleList &module_list)
857 {
858     Mutex::Locker locker(module_list.GetMutex());
859 
860     size_t num_modules = module_list.GetSize();
861     for (size_t i = 0; i < num_modules; i++)
862     {
863         auto mod = module_list.GetModuleAtIndex(i);
864         if (IsRenderScriptModule(mod))
865         {
866             LoadModule(mod);
867         }
868     }
869 }
870 
871 //------------------------------------------------------------------
872 // PluginInterface protocol
873 //------------------------------------------------------------------
874 lldb_private::ConstString
875 RenderScriptRuntime::GetPluginName()
876 {
877     return GetPluginNameStatic();
878 }
879 
880 uint32_t
881 RenderScriptRuntime::GetPluginVersion()
882 {
883     return 1;
884 }
885 
886 bool
887 RenderScriptRuntime::IsVTableName(const char *name)
888 {
889     return false;
890 }
891 
892 bool
893 RenderScriptRuntime::GetDynamicTypeAndAddress(ValueObject &in_value, lldb::DynamicValueType use_dynamic,
894                                               TypeAndOrName &class_type_or_name, Address &address,
895                                               Value::ValueType &value_type)
896 {
897     return false;
898 }
899 
900 TypeAndOrName
901 RenderScriptRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name, ValueObject &static_value)
902 {
903     return type_and_or_name;
904 }
905 
906 bool
907 RenderScriptRuntime::CouldHaveDynamicValue(ValueObject &in_value)
908 {
909     return false;
910 }
911 
912 lldb::BreakpointResolverSP
913 RenderScriptRuntime::CreateExceptionResolver(Breakpoint *bkpt, bool catch_bp, bool throw_bp)
914 {
915     BreakpointResolverSP resolver_sp;
916     return resolver_sp;
917 }
918 
919 const RenderScriptRuntime::HookDefn RenderScriptRuntime::s_runtimeHookDefns[] = {
920     // rsdScript
921     {
922         "rsdScriptInit",
923         "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_7ScriptCEPKcS7_PKhjj",
924         "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_7ScriptCEPKcS7_PKhmj",
925         0,
926         RenderScriptRuntime::eModuleKindDriver,
927         &lldb_private::RenderScriptRuntime::CaptureScriptInit
928     },
929     {
930         "rsdScriptInvokeForEachMulti",
931         "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0_6ScriptEjPPKNS0_10AllocationEjPS6_PKvjPK12RsScriptCall",
932         "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0_6ScriptEjPPKNS0_10AllocationEmPS6_PKvmPK12RsScriptCall",
933         0,
934         RenderScriptRuntime::eModuleKindDriver,
935         &lldb_private::RenderScriptRuntime::CaptureScriptInvokeForEachMulti
936     },
937     {
938         "rsdScriptSetGlobalVar",
939         "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_6ScriptEjPvj",
940         "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_6ScriptEjPvm",
941         0,
942         RenderScriptRuntime::eModuleKindDriver,
943         &lldb_private::RenderScriptRuntime::CaptureSetGlobalVar
944     },
945 
946     // rsdAllocation
947     {
948         "rsdAllocationInit",
949         "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_10AllocationEb",
950         "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_10AllocationEb",
951         0,
952         RenderScriptRuntime::eModuleKindDriver,
953         &lldb_private::RenderScriptRuntime::CaptureAllocationInit
954     },
955     {
956         "rsdAllocationRead2D",
957         "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_10AllocationEjjj23RsAllocationCubemapFacejjPvjj",
958         "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_10AllocationEjjj23RsAllocationCubemapFacejjPvmm",
959         0,
960         RenderScriptRuntime::eModuleKindDriver,
961         nullptr
962     },
963     {
964         "rsdAllocationDestroy",
965         "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_10AllocationE",
966         "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_10AllocationE",
967         0,
968         RenderScriptRuntime::eModuleKindDriver,
969         &lldb_private::RenderScriptRuntime::CaptureAllocationDestroy
970     },
971 };
972 
973 const size_t RenderScriptRuntime::s_runtimeHookCount = sizeof(s_runtimeHookDefns) / sizeof(s_runtimeHookDefns[0]);
974 
975 bool
976 RenderScriptRuntime::HookCallback(void *baton, StoppointCallbackContext *ctx, lldb::user_id_t break_id,
977                                   lldb::user_id_t break_loc_id)
978 {
979     RuntimeHook *hook_info = (RuntimeHook *)baton;
980     ExecutionContext context(ctx->exe_ctx_ref);
981 
982     RenderScriptRuntime *lang_rt =
983         (RenderScriptRuntime *)context.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
984 
985     lang_rt->HookCallback(hook_info, context);
986 
987     return false;
988 }
989 
990 void
991 RenderScriptRuntime::HookCallback(RuntimeHook *hook_info, ExecutionContext &context)
992 {
993     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
994 
995     if (log)
996         log->Printf("%s - '%s'", __FUNCTION__, hook_info->defn->name);
997 
998     if (hook_info->defn->grabber)
999     {
1000         (this->*(hook_info->defn->grabber))(hook_info, context);
1001     }
1002 }
1003 
1004 void
1005 RenderScriptRuntime::CaptureScriptInvokeForEachMulti(RuntimeHook* hook_info,
1006                                                      ExecutionContext& context)
1007 {
1008     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1009 
1010     enum
1011     {
1012         eRsContext = 0,
1013         eRsScript,
1014         eRsSlot,
1015         eRsAIns,
1016         eRsInLen,
1017         eRsAOut,
1018         eRsUsr,
1019         eRsUsrLen,
1020         eRsSc,
1021     };
1022 
1023     std::array<ArgItem, 9> args{{
1024         ArgItem{ArgItem::ePointer, 0}, // const Context       *rsc
1025         ArgItem{ArgItem::ePointer, 0}, // Script              *s
1026         ArgItem{ArgItem::eInt32, 0},   // uint32_t             slot
1027         ArgItem{ArgItem::ePointer, 0}, // const Allocation   **aIns
1028         ArgItem{ArgItem::eInt32, 0},   // size_t               inLen
1029         ArgItem{ArgItem::ePointer, 0}, // Allocation          *aout
1030         ArgItem{ArgItem::ePointer, 0}, // const void          *usr
1031         ArgItem{ArgItem::eInt32, 0},   // size_t               usrLen
1032         ArgItem{ArgItem::ePointer, 0}, // const RsScriptCall  *sc
1033     }};
1034 
1035     bool success = GetArgs(context, &args[0], args.size());
1036     if (!success)
1037     {
1038         if (log)
1039             log->Printf("%s - Error while reading the function parameters", __FUNCTION__);
1040         return;
1041     }
1042 
1043     const uint32_t target_ptr_size = m_process->GetAddressByteSize();
1044     Error error;
1045     std::vector<uint64_t> allocs;
1046 
1047     // traverse allocation list
1048     for (uint64_t i = 0; i < uint64_t(args[eRsInLen]); ++i)
1049     {
1050         // calculate offest to allocation pointer
1051         const addr_t addr = addr_t(args[eRsAIns]) + i * target_ptr_size;
1052 
1053         // Note: due to little endian layout, reading 32bits or 64bits into res64 will
1054         //       give the correct results.
1055 
1056         uint64_t res64 = 0;
1057         size_t read = m_process->ReadMemory(addr, &res64, target_ptr_size, error);
1058         if (read != target_ptr_size || !error.Success())
1059         {
1060             if (log)
1061                 log->Printf("%s - Error while reading allocation list argument %" PRIu64, __FUNCTION__, i);
1062         }
1063         else
1064         {
1065             allocs.push_back(res64);
1066         }
1067     }
1068 
1069     // if there is an output allocation track it
1070     if (uint64_t aOut = uint64_t(args[eRsAOut]))
1071     {
1072         allocs.push_back(aOut);
1073     }
1074 
1075     // for all allocations we have found
1076     for (const uint64_t alloc_addr : allocs)
1077     {
1078         AllocationDetails* alloc = LookUpAllocation(alloc_addr, true);
1079         if (alloc)
1080         {
1081             // save the allocation address
1082             if (alloc->address.isValid())
1083             {
1084                 // check the allocation address we already have matches
1085                 assert(*alloc->address.get() == alloc_addr);
1086             }
1087             else
1088             {
1089                 alloc->address = alloc_addr;
1090             }
1091 
1092             // save the context
1093             if (log)
1094             {
1095                 if (alloc->context.isValid() && *alloc->context.get() != addr_t(args[eRsContext]))
1096                     log->Printf("%s - Allocation used by multiple contexts", __FUNCTION__);
1097             }
1098             alloc->context = addr_t(args[eRsContext]);
1099         }
1100     }
1101 
1102     // make sure we track this script object
1103     if (lldb_private::RenderScriptRuntime::ScriptDetails *script = LookUpScript(addr_t(args[eRsScript]), true))
1104     {
1105         if (log)
1106         {
1107             if (script->context.isValid() && *script->context.get() != addr_t(args[eRsContext]))
1108                 log->Printf("%s - Script used by multiple contexts", __FUNCTION__);
1109         }
1110         script->context = addr_t(args[eRsContext]);
1111     }
1112 }
1113 
1114 void
1115 RenderScriptRuntime::CaptureSetGlobalVar(RuntimeHook *hook_info, ExecutionContext &context)
1116 {
1117     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1118 
1119     enum
1120     {
1121         eRsContext,
1122         eRsScript,
1123         eRsId,
1124         eRsData,
1125         eRsLength,
1126     };
1127 
1128     std::array<ArgItem, 5> args{{
1129         ArgItem{ArgItem::ePointer, 0}, // eRsContext
1130         ArgItem{ArgItem::ePointer, 0}, // eRsScript
1131         ArgItem{ArgItem::eInt32, 0},   // eRsId
1132         ArgItem{ArgItem::ePointer, 0}, // eRsData
1133         ArgItem{ArgItem::eInt32, 0},   // eRsLength
1134     }};
1135 
1136     bool success = GetArgs(context, &args[0], args.size());
1137     if (!success)
1138     {
1139         if (log)
1140             log->Printf("%s - error reading the function parameters.", __FUNCTION__);
1141         return;
1142     }
1143 
1144     if (log)
1145     {
1146         log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " slot %" PRIu64 " = 0x%" PRIx64 ":%" PRIu64 "bytes.", __FUNCTION__,
1147                     uint64_t(args[eRsContext]), uint64_t(args[eRsScript]), uint64_t(args[eRsId]),
1148                     uint64_t(args[eRsData]), uint64_t(args[eRsLength]));
1149 
1150         addr_t script_addr = addr_t(args[eRsScript]);
1151         if (m_scriptMappings.find(script_addr) != m_scriptMappings.end())
1152         {
1153             auto rsm = m_scriptMappings[script_addr];
1154             if (uint64_t(args[eRsId]) < rsm->m_globals.size())
1155             {
1156                 auto rsg = rsm->m_globals[uint64_t(args[eRsId])];
1157                 log->Printf("%s - Setting of '%s' within '%s' inferred", __FUNCTION__, rsg.m_name.AsCString(),
1158                             rsm->m_module->GetFileSpec().GetFilename().AsCString());
1159             }
1160         }
1161     }
1162 }
1163 
1164 void
1165 RenderScriptRuntime::CaptureAllocationInit(RuntimeHook *hook_info, ExecutionContext &context)
1166 {
1167     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1168 
1169     enum
1170     {
1171         eRsContext,
1172         eRsAlloc,
1173         eRsForceZero
1174     };
1175 
1176     std::array<ArgItem, 3> args{{
1177         ArgItem{ArgItem::ePointer, 0}, // eRsContext
1178         ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
1179         ArgItem{ArgItem::eBool, 0},    // eRsForceZero
1180     }};
1181 
1182     bool success = GetArgs(context, &args[0], args.size());
1183     if (!success) // error case
1184     {
1185         if (log)
1186             log->Printf("%s - error while reading the function parameters", __FUNCTION__);
1187         return; // abort
1188     }
1189 
1190     if (log)
1191         log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 ",0x%" PRIx64 " .", __FUNCTION__, uint64_t(args[eRsContext]),
1192                     uint64_t(args[eRsAlloc]), uint64_t(args[eRsForceZero]));
1193 
1194     AllocationDetails *alloc = LookUpAllocation(uint64_t(args[eRsAlloc]), true);
1195     if (alloc)
1196         alloc->context = uint64_t(args[eRsContext]);
1197 }
1198 
1199 void
1200 RenderScriptRuntime::CaptureAllocationDestroy(RuntimeHook *hook_info, ExecutionContext &context)
1201 {
1202     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1203 
1204     enum
1205     {
1206         eRsContext,
1207         eRsAlloc,
1208     };
1209 
1210     std::array<ArgItem, 2> args{{
1211         ArgItem{ArgItem::ePointer, 0}, // eRsContext
1212         ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
1213     }};
1214 
1215     bool success = GetArgs(context, &args[0], args.size());
1216     if (!success)
1217     {
1218         if (log)
1219             log->Printf("%s - error while reading the function parameters.", __FUNCTION__);
1220         return;
1221     }
1222 
1223     if (log)
1224         log->Printf("%s - 0x%" PRIx64 ", 0x%" PRIx64 ".", __FUNCTION__, uint64_t(args[eRsContext]),
1225                     uint64_t(args[eRsAlloc]));
1226 
1227     for (auto iter = m_allocations.begin(); iter != m_allocations.end(); ++iter)
1228     {
1229         auto &allocation_ap = *iter; // get the unique pointer
1230         if (allocation_ap->address.isValid() && *allocation_ap->address.get() == addr_t(args[eRsAlloc]))
1231         {
1232             m_allocations.erase(iter);
1233             if (log)
1234                 log->Printf("%s - deleted allocation entry.", __FUNCTION__);
1235             return;
1236         }
1237     }
1238 
1239     if (log)
1240         log->Printf("%s - couldn't find destroyed allocation.", __FUNCTION__);
1241 }
1242 
1243 void
1244 RenderScriptRuntime::CaptureScriptInit(RuntimeHook *hook_info, ExecutionContext &context)
1245 {
1246     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1247 
1248     Error error;
1249     Process *process = context.GetProcessPtr();
1250 
1251     enum
1252     {
1253         eRsContext,
1254         eRsScript,
1255         eRsResNamePtr,
1256         eRsCachedDirPtr
1257     };
1258 
1259     std::array<ArgItem, 4> args{{ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0},
1260                                  ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0}}};
1261     bool success = GetArgs(context, &args[0], args.size());
1262     if (!success)
1263     {
1264         if (log)
1265             log->Printf("%s - error while reading the function parameters.", __FUNCTION__);
1266         return;
1267     }
1268 
1269     std::string resname;
1270     process->ReadCStringFromMemory(addr_t(args[eRsResNamePtr]), resname, error);
1271     if (error.Fail())
1272     {
1273         if (log)
1274             log->Printf("%s - error reading resname: %s.", __FUNCTION__, error.AsCString());
1275     }
1276 
1277     std::string cachedir;
1278     process->ReadCStringFromMemory(addr_t(args[eRsCachedDirPtr]), cachedir, error);
1279     if (error.Fail())
1280     {
1281         if (log)
1282             log->Printf("%s - error reading cachedir: %s.", __FUNCTION__, error.AsCString());
1283     }
1284 
1285     if (log)
1286         log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " => '%s' at '%s' .", __FUNCTION__, uint64_t(args[eRsContext]),
1287                     uint64_t(args[eRsScript]), resname.c_str(), cachedir.c_str());
1288 
1289     if (resname.size() > 0)
1290     {
1291         StreamString strm;
1292         strm.Printf("librs.%s.so", resname.c_str());
1293 
1294         ScriptDetails *script = LookUpScript(addr_t(args[eRsScript]), true);
1295         if (script)
1296         {
1297             script->type = ScriptDetails::eScriptC;
1298             script->cacheDir = cachedir;
1299             script->resName = resname;
1300             script->scriptDyLib = strm.GetData();
1301             script->context = addr_t(args[eRsContext]);
1302         }
1303 
1304         if (log)
1305             log->Printf("%s - '%s' tagged with context 0x%" PRIx64 " and script 0x%" PRIx64 ".", __FUNCTION__,
1306                         strm.GetData(), uint64_t(args[eRsContext]), uint64_t(args[eRsScript]));
1307     }
1308     else if (log)
1309     {
1310         log->Printf("%s - resource name invalid, Script not tagged.", __FUNCTION__);
1311     }
1312 }
1313 
1314 void
1315 RenderScriptRuntime::LoadRuntimeHooks(lldb::ModuleSP module, ModuleKind kind)
1316 {
1317     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1318 
1319     if (!module)
1320     {
1321         return;
1322     }
1323 
1324     Target &target = GetProcess()->GetTarget();
1325     llvm::Triple::ArchType targetArchType = target.GetArchitecture().GetMachine();
1326 
1327     if (targetArchType != llvm::Triple::ArchType::x86 &&
1328         targetArchType != llvm::Triple::ArchType::arm &&
1329         targetArchType != llvm::Triple::ArchType::aarch64 &&
1330         targetArchType != llvm::Triple::ArchType::mipsel &&
1331         targetArchType != llvm::Triple::ArchType::mips64el &&
1332         targetArchType != llvm::Triple::ArchType::x86_64)
1333     {
1334         if (log)
1335             log->Printf("%s - unable to hook runtime functions.", __FUNCTION__);
1336         return;
1337     }
1338 
1339     uint32_t archByteSize = target.GetArchitecture().GetAddressByteSize();
1340 
1341     for (size_t idx = 0; idx < s_runtimeHookCount; idx++)
1342     {
1343         const HookDefn *hook_defn = &s_runtimeHookDefns[idx];
1344         if (hook_defn->kind != kind)
1345         {
1346             continue;
1347         }
1348 
1349         const char *symbol_name = (archByteSize == 4) ? hook_defn->symbol_name_m32 : hook_defn->symbol_name_m64;
1350 
1351         const Symbol *sym = module->FindFirstSymbolWithNameAndType(ConstString(symbol_name), eSymbolTypeCode);
1352         if (!sym)
1353         {
1354             if (log)
1355             {
1356                 log->Printf("%s - symbol '%s' related to the function %s not found",
1357                             __FUNCTION__, symbol_name, hook_defn->name);
1358             }
1359             continue;
1360         }
1361 
1362         addr_t addr = sym->GetLoadAddress(&target);
1363         if (addr == LLDB_INVALID_ADDRESS)
1364         {
1365             if (log)
1366                 log->Printf("%s - unable to resolve the address of hook function '%s' with symbol '%s'.",
1367                             __FUNCTION__, hook_defn->name, symbol_name);
1368             continue;
1369         }
1370         else
1371         {
1372             if (log)
1373                 log->Printf("%s - function %s, address resolved at 0x%" PRIx64,
1374                             __FUNCTION__, hook_defn->name, addr);
1375         }
1376 
1377         RuntimeHookSP hook(new RuntimeHook());
1378         hook->address = addr;
1379         hook->defn = hook_defn;
1380         hook->bp_sp = target.CreateBreakpoint(addr, true, false);
1381         hook->bp_sp->SetCallback(HookCallback, hook.get(), true);
1382         m_runtimeHooks[addr] = hook;
1383         if (log)
1384         {
1385             log->Printf("%s - successfully hooked '%s' in '%s' version %" PRIu64 " at 0x%" PRIx64 ".",
1386                         __FUNCTION__, hook_defn->name, module->GetFileSpec().GetFilename().AsCString(),
1387                         (uint64_t)hook_defn->version, (uint64_t)addr);
1388         }
1389     }
1390 }
1391 
1392 void
1393 RenderScriptRuntime::FixupScriptDetails(RSModuleDescriptorSP rsmodule_sp)
1394 {
1395     if (!rsmodule_sp)
1396         return;
1397 
1398     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1399 
1400     const ModuleSP module = rsmodule_sp->m_module;
1401     const FileSpec &file = module->GetPlatformFileSpec();
1402 
1403     // Iterate over all of the scripts that we currently know of.
1404     // Note: We cant push or pop to m_scripts here or it may invalidate rs_script.
1405     for (const auto &rs_script : m_scripts)
1406     {
1407         // Extract the expected .so file path for this script.
1408         std::string dylib;
1409         if (!rs_script->scriptDyLib.get(dylib))
1410             continue;
1411 
1412         // Only proceed if the module that has loaded corresponds to this script.
1413         if (file.GetFilename() != ConstString(dylib.c_str()))
1414             continue;
1415 
1416         // Obtain the script address which we use as a key.
1417         lldb::addr_t script;
1418         if (!rs_script->script.get(script))
1419             continue;
1420 
1421         // If we have a script mapping for the current script.
1422         if (m_scriptMappings.find(script) != m_scriptMappings.end())
1423         {
1424             // if the module we have stored is different to the one we just received.
1425             if (m_scriptMappings[script] != rsmodule_sp)
1426             {
1427                 if (log)
1428                     log->Printf("%s - script %" PRIx64 " wants reassigned to new rsmodule '%s'.", __FUNCTION__,
1429                                 (uint64_t)script, rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
1430             }
1431         }
1432         // We don't have a script mapping for the current script.
1433         else
1434         {
1435             // Obtain the script resource name.
1436             std::string resName;
1437             if (rs_script->resName.get(resName))
1438                 // Set the modules resource name.
1439                 rsmodule_sp->m_resname = resName;
1440             // Add Script/Module pair to map.
1441             m_scriptMappings[script] = rsmodule_sp;
1442             if (log)
1443                 log->Printf("%s - script %" PRIx64 " associated with rsmodule '%s'.", __FUNCTION__,
1444                             (uint64_t)script, rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
1445         }
1446     }
1447 }
1448 
1449 // Uses the Target API to evaluate the expression passed as a parameter to the function
1450 // The result of that expression is returned an unsigned 64 bit int, via the result* paramter.
1451 // Function returns true on success, and false on failure
1452 bool
1453 RenderScriptRuntime::EvalRSExpression(const char *expression, StackFrame *frame_ptr, uint64_t *result)
1454 {
1455     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1456     if (log)
1457         log->Printf("%s(%s)", __FUNCTION__, expression);
1458 
1459     ValueObjectSP expr_result;
1460     EvaluateExpressionOptions options;
1461     options.SetLanguage(lldb::eLanguageTypeC_plus_plus);
1462     // Perform the actual expression evaluation
1463     GetProcess()->GetTarget().EvaluateExpression(expression, frame_ptr, expr_result, options);
1464 
1465     if (!expr_result)
1466     {
1467         if (log)
1468             log->Printf("%s: couldn't evaluate expression.", __FUNCTION__);
1469         return false;
1470     }
1471 
1472     // The result of the expression is invalid
1473     if (!expr_result->GetError().Success())
1474     {
1475         Error err = expr_result->GetError();
1476         if (err.GetError() == UserExpression::kNoResult) // Expression returned void, so this is actually a success
1477         {
1478             if (log)
1479                 log->Printf("%s - expression returned void.", __FUNCTION__);
1480 
1481             result = nullptr;
1482             return true;
1483         }
1484 
1485         if (log)
1486             log->Printf("%s - error evaluating expression result: %s", __FUNCTION__,
1487                         err.AsCString());
1488         return false;
1489     }
1490 
1491     bool success = false;
1492     *result = expr_result->GetValueAsUnsigned(0, &success); // We only read the result as an uint32_t.
1493 
1494     if (!success)
1495     {
1496         if (log)
1497             log->Printf("%s - couldn't convert expression result to uint32_t", __FUNCTION__);
1498         return false;
1499     }
1500 
1501     return true;
1502 }
1503 
1504 namespace
1505 {
1506 // Used to index expression format strings
1507 enum ExpressionStrings
1508 {
1509    eExprGetOffsetPtr = 0,
1510    eExprAllocGetType,
1511    eExprTypeDimX,
1512    eExprTypeDimY,
1513    eExprTypeDimZ,
1514    eExprTypeElemPtr,
1515    eExprElementType,
1516    eExprElementKind,
1517    eExprElementVec,
1518    eExprElementFieldCount,
1519    eExprSubelementsId,
1520    eExprSubelementsName,
1521    eExprSubelementsArrSize,
1522 
1523    _eExprLast // keep at the end, implicit size of the array runtimeExpressions
1524 };
1525 
1526 // max length of an expanded expression
1527 const int jit_max_expr_size = 512;
1528 
1529 // Retrieve the string to JIT for the given expression
1530 const char*
1531 JITTemplate(ExpressionStrings e)
1532 {
1533     // Format strings containing the expressions we may need to evaluate.
1534     static std::array<const char*, _eExprLast> runtimeExpressions = {{
1535      // Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap)
1536      "(int*)_Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocationCubemapFace"
1537      "(0x%" PRIx64 ", %" PRIu32 ", %" PRIu32 ", %" PRIu32 ", 0, 0)",
1538 
1539      // Type* rsaAllocationGetType(Context*, Allocation*)
1540      "(void*)rsaAllocationGetType(0x%" PRIx64 ", 0x%" PRIx64 ")",
1541 
1542      // rsaTypeGetNativeData(Context*, Type*, void* typeData, size)
1543      // Pack the data in the following way mHal.state.dimX; mHal.state.dimY; mHal.state.dimZ;
1544      // mHal.state.lodCount; mHal.state.faces; mElement; into typeData
1545      // Need to specify 32 or 64 bit for uint_t since this differs between devices
1546      "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64 ", 0x%" PRIx64 ", data, 6); data[0]", // X dim
1547      "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64 ", 0x%" PRIx64 ", data, 6); data[1]", // Y dim
1548      "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64 ", 0x%" PRIx64 ", data, 6); data[2]", // Z dim
1549      "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64 ", 0x%" PRIx64 ", data, 6); data[5]", // Element ptr
1550 
1551      // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size)
1552      // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into elemData
1553      "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64 ", 0x%" PRIx64 ", data, 5); data[0]", // Type
1554      "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64 ", 0x%" PRIx64 ", data, 5); data[1]", // Kind
1555      "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64 ", 0x%" PRIx64 ", data, 5); data[3]", // Vector Size
1556      "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64 ", 0x%" PRIx64 ", data, 5); data[4]", // Field Count
1557 
1558      // rsaElementGetSubElements(RsContext con, RsElement elem, uintptr_t *ids, const char **names,
1559      // size_t *arraySizes, uint32_t dataSize)
1560      // Needed for Allocations of structs to gather details about fields/Subelements
1561      // Element* of field
1562      "void* ids[%" PRIu32 "]; const char* names[%" PRIu32 "]; size_t arr_size[%" PRIu32 "];"
1563      "(void*)rsaElementGetSubElements(0x%" PRIx64 ", 0x%" PRIx64 ", ids, names, arr_size, %" PRIu32 "); ids[%" PRIu32 "]",
1564 
1565      // Name of field
1566      "void* ids[%" PRIu32 "]; const char* names[%" PRIu32 "]; size_t arr_size[%" PRIu32 "];"
1567      "(void*)rsaElementGetSubElements(0x%" PRIx64 ", 0x%" PRIx64 ", ids, names, arr_size, %" PRIu32 "); names[%" PRIu32 "]",
1568 
1569      // Array size of field
1570      "void* ids[%" PRIu32 "]; const char* names[%" PRIu32 "]; size_t arr_size[%" PRIu32 "];"
1571      "(void*)rsaElementGetSubElements(0x%" PRIx64 ", 0x%" PRIx64 ", ids, names, arr_size, %" PRIu32 "); arr_size[%" PRIu32 "]"
1572     }};
1573 
1574     return runtimeExpressions[e];
1575 }
1576 } // end of the anonymous namespace
1577 
1578 
1579 // JITs the RS runtime for the internal data pointer of an allocation.
1580 // Is passed x,y,z coordinates for the pointer to a specific element.
1581 // Then sets the data_ptr member in Allocation with the result.
1582 // Returns true on success, false otherwise
1583 bool
1584 RenderScriptRuntime::JITDataPointer(AllocationDetails *allocation, StackFrame *frame_ptr, uint32_t x,
1585                                     uint32_t y, uint32_t z)
1586 {
1587     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1588 
1589     if (!allocation->address.isValid())
1590     {
1591         if (log)
1592             log->Printf("%s - failed to find allocation details.", __FUNCTION__);
1593         return false;
1594     }
1595 
1596     const char *expr_cstr = JITTemplate(eExprGetOffsetPtr);
1597     char buffer[jit_max_expr_size];
1598 
1599     int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->address.get(), x, y, z);
1600     if (chars_written < 0)
1601     {
1602         if (log)
1603             log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1604         return false;
1605     }
1606     else if (chars_written >= jit_max_expr_size)
1607     {
1608         if (log)
1609             log->Printf("%s - expression too long.", __FUNCTION__);
1610         return false;
1611     }
1612 
1613     uint64_t result = 0;
1614     if (!EvalRSExpression(buffer, frame_ptr, &result))
1615         return false;
1616 
1617     addr_t mem_ptr = static_cast<lldb::addr_t>(result);
1618     allocation->data_ptr = mem_ptr;
1619 
1620     return true;
1621 }
1622 
1623 // JITs the RS runtime for the internal pointer to the RS Type of an allocation
1624 // Then sets the type_ptr member in Allocation with the result.
1625 // Returns true on success, false otherwise
1626 bool
1627 RenderScriptRuntime::JITTypePointer(AllocationDetails *allocation, StackFrame *frame_ptr)
1628 {
1629     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1630 
1631     if (!allocation->address.isValid() || !allocation->context.isValid())
1632     {
1633         if (log)
1634             log->Printf("%s - failed to find allocation details.", __FUNCTION__);
1635         return false;
1636     }
1637 
1638     const char *expr_cstr = JITTemplate(eExprAllocGetType);
1639     char buffer[jit_max_expr_size];
1640 
1641     int chars_written =
1642         snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->context.get(), *allocation->address.get());
1643     if (chars_written < 0)
1644     {
1645         if (log)
1646             log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1647         return false;
1648     }
1649     else if (chars_written >= jit_max_expr_size)
1650     {
1651         if (log)
1652             log->Printf("%s - expression too long.", __FUNCTION__);
1653         return false;
1654     }
1655 
1656     uint64_t result = 0;
1657     if (!EvalRSExpression(buffer, frame_ptr, &result))
1658         return false;
1659 
1660     addr_t type_ptr = static_cast<lldb::addr_t>(result);
1661     allocation->type_ptr = type_ptr;
1662 
1663     return true;
1664 }
1665 
1666 // JITs the RS runtime for information about the dimensions and type of an allocation
1667 // Then sets dimension and element_ptr members in Allocation with the result.
1668 // Returns true on success, false otherwise
1669 bool
1670 RenderScriptRuntime::JITTypePacked(AllocationDetails *allocation, StackFrame *frame_ptr)
1671 {
1672     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1673 
1674     if (!allocation->type_ptr.isValid() || !allocation->context.isValid())
1675     {
1676         if (log)
1677             log->Printf("%s - Failed to find allocation details.", __FUNCTION__);
1678         return false;
1679     }
1680 
1681     // Expression is different depending on if device is 32 or 64 bit
1682     uint32_t archByteSize = GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
1683     const uint32_t bits = archByteSize == 4 ? 32 : 64;
1684 
1685     // We want 4 elements from packed data
1686     const uint32_t num_exprs = 4;
1687     assert(num_exprs == (eExprTypeElemPtr - eExprTypeDimX + 1) && "Invalid number of expressions");
1688 
1689     char buffer[num_exprs][jit_max_expr_size];
1690     uint64_t results[num_exprs];
1691 
1692     for (uint32_t i = 0; i < num_exprs; ++i)
1693     {
1694         const char *expr_cstr = JITTemplate(ExpressionStrings(eExprTypeDimX + i));
1695         int chars_written = snprintf(buffer[i], jit_max_expr_size, expr_cstr, bits, *allocation->context.get(),
1696                                      *allocation->type_ptr.get());
1697         if (chars_written < 0)
1698         {
1699             if (log)
1700                 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1701             return false;
1702         }
1703         else if (chars_written >= jit_max_expr_size)
1704         {
1705             if (log)
1706                 log->Printf("%s - expression too long.", __FUNCTION__);
1707             return false;
1708         }
1709 
1710         // Perform expression evaluation
1711         if (!EvalRSExpression(buffer[i], frame_ptr, &results[i]))
1712             return false;
1713     }
1714 
1715     // Assign results to allocation members
1716     AllocationDetails::Dimension dims;
1717     dims.dim_1 = static_cast<uint32_t>(results[0]);
1718     dims.dim_2 = static_cast<uint32_t>(results[1]);
1719     dims.dim_3 = static_cast<uint32_t>(results[2]);
1720     allocation->dimension = dims;
1721 
1722     addr_t elem_ptr = static_cast<lldb::addr_t>(results[3]);
1723     allocation->element.element_ptr = elem_ptr;
1724 
1725     if (log)
1726         log->Printf("%s - dims (%" PRIu32 ", %" PRIu32 ", %" PRIu32 ") Element*: 0x%" PRIx64 ".", __FUNCTION__,
1727                     dims.dim_1, dims.dim_2, dims.dim_3, elem_ptr);
1728 
1729     return true;
1730 }
1731 
1732 // JITs the RS runtime for information about the Element of an allocation
1733 // Then sets type, type_vec_size, field_count and type_kind members in Element with the result.
1734 // Returns true on success, false otherwise
1735 bool
1736 RenderScriptRuntime::JITElementPacked(Element &elem, const lldb::addr_t context, StackFrame *frame_ptr)
1737 {
1738     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1739 
1740     if (!elem.element_ptr.isValid())
1741     {
1742         if (log)
1743             log->Printf("%s - failed to find allocation details.", __FUNCTION__);
1744         return false;
1745     }
1746 
1747     // We want 4 elements from packed data
1748     const uint32_t num_exprs = 4;
1749     assert(num_exprs == (eExprElementFieldCount - eExprElementType + 1) && "Invalid number of expressions");
1750 
1751     char buffer[num_exprs][jit_max_expr_size];
1752     uint64_t results[num_exprs];
1753 
1754     for (uint32_t i = 0; i < num_exprs; i++)
1755     {
1756         const char *expr_cstr = JITTemplate(ExpressionStrings(eExprElementType + i));
1757         int chars_written = snprintf(buffer[i], jit_max_expr_size, expr_cstr, context, *elem.element_ptr.get());
1758         if (chars_written < 0)
1759         {
1760             if (log)
1761                 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1762             return false;
1763         }
1764         else if (chars_written >= jit_max_expr_size)
1765         {
1766             if (log)
1767                 log->Printf("%s - expression too long.", __FUNCTION__);
1768             return false;
1769         }
1770 
1771         // Perform expression evaluation
1772         if (!EvalRSExpression(buffer[i], frame_ptr, &results[i]))
1773             return false;
1774     }
1775 
1776     // Assign results to allocation members
1777     elem.type = static_cast<RenderScriptRuntime::Element::DataType>(results[0]);
1778     elem.type_kind = static_cast<RenderScriptRuntime::Element::DataKind>(results[1]);
1779     elem.type_vec_size = static_cast<uint32_t>(results[2]);
1780     elem.field_count = static_cast<uint32_t>(results[3]);
1781 
1782     if (log)
1783         log->Printf("%s - data type %" PRIu32 ", pixel type %" PRIu32 ", vector size %" PRIu32 ", field count %" PRIu32,
1784                     __FUNCTION__, *elem.type.get(), *elem.type_kind.get(), *elem.type_vec_size.get(), *elem.field_count.get());
1785 
1786     // If this Element has subelements then JIT rsaElementGetSubElements() for details about its fields
1787     if (*elem.field_count.get() > 0 && !JITSubelements(elem, context, frame_ptr))
1788         return false;
1789 
1790     return true;
1791 }
1792 
1793 // JITs the RS runtime for information about the subelements/fields of a struct allocation
1794 // This is necessary for infering the struct type so we can pretty print the allocation's contents.
1795 // Returns true on success, false otherwise
1796 bool
1797 RenderScriptRuntime::JITSubelements(Element &elem, const lldb::addr_t context, StackFrame *frame_ptr)
1798 {
1799     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1800 
1801     if (!elem.element_ptr.isValid() || !elem.field_count.isValid())
1802     {
1803         if (log)
1804             log->Printf("%s - failed to find allocation details.", __FUNCTION__);
1805         return false;
1806     }
1807 
1808     const short num_exprs = 3;
1809     assert(num_exprs == (eExprSubelementsArrSize - eExprSubelementsId + 1) && "Invalid number of expressions");
1810 
1811     char expr_buffer[jit_max_expr_size];
1812     uint64_t results;
1813 
1814     // Iterate over struct fields.
1815     const uint32_t field_count = *elem.field_count.get();
1816     for (uint32_t field_index = 0; field_index < field_count; ++field_index)
1817     {
1818         Element child;
1819         for (uint32_t expr_index = 0; expr_index < num_exprs; ++expr_index)
1820         {
1821             const char *expr_cstr = JITTemplate(ExpressionStrings(eExprSubelementsId + expr_index));
1822             int chars_written = snprintf(expr_buffer, jit_max_expr_size, expr_cstr,
1823                                          field_count, field_count, field_count,
1824                                          context, *elem.element_ptr.get(), field_count, field_index);
1825             if (chars_written < 0)
1826             {
1827                 if (log)
1828                     log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1829                 return false;
1830             }
1831             else if (chars_written >= jit_max_expr_size)
1832             {
1833                 if (log)
1834                     log->Printf("%s - expression too long.", __FUNCTION__);
1835                 return false;
1836             }
1837 
1838             // Perform expression evaluation
1839             if (!EvalRSExpression(expr_buffer, frame_ptr, &results))
1840                 return false;
1841 
1842             if (log)
1843                 log->Printf("%s - expr result 0x%" PRIx64 ".", __FUNCTION__, results);
1844 
1845             switch (expr_index)
1846             {
1847                 case 0: // Element* of child
1848                     child.element_ptr = static_cast<addr_t>(results);
1849                     break;
1850                 case 1: // Name of child
1851                 {
1852                     lldb::addr_t address = static_cast<addr_t>(results);
1853                     Error err;
1854                     std::string name;
1855                     GetProcess()->ReadCStringFromMemory(address, name, err);
1856                     if (!err.Fail())
1857                         child.type_name = ConstString(name);
1858                     else
1859                     {
1860                         if (log)
1861                             log->Printf("%s - warning: Couldn't read field name.", __FUNCTION__);
1862                     }
1863                     break;
1864                 }
1865                 case 2: // Array size of child
1866                     child.array_size = static_cast<uint32_t>(results);
1867                     break;
1868             }
1869         }
1870 
1871         // We need to recursively JIT each Element field of the struct since
1872         // structs can be nested inside structs.
1873         if (!JITElementPacked(child, context, frame_ptr))
1874             return false;
1875         elem.children.push_back(child);
1876     }
1877 
1878     // Try to infer the name of the struct type so we can pretty print the allocation contents.
1879     FindStructTypeName(elem, frame_ptr);
1880 
1881     return true;
1882 }
1883 
1884 // JITs the RS runtime for the address of the last element in the allocation.
1885 // The `elem_size` paramter represents the size of a single element, including padding.
1886 // Which is needed as an offset from the last element pointer.
1887 // Using this offset minus the starting address we can calculate the size of the allocation.
1888 // Returns true on success, false otherwise
1889 bool
1890 RenderScriptRuntime::JITAllocationSize(AllocationDetails *allocation, StackFrame *frame_ptr)
1891 {
1892     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1893 
1894     if (!allocation->address.isValid() || !allocation->dimension.isValid() || !allocation->data_ptr.isValid() ||
1895         !allocation->element.datum_size.isValid())
1896     {
1897         if (log)
1898             log->Printf("%s - failed to find allocation details.", __FUNCTION__);
1899         return false;
1900     }
1901 
1902     // Find dimensions
1903     uint32_t dim_x = allocation->dimension.get()->dim_1;
1904     uint32_t dim_y = allocation->dimension.get()->dim_2;
1905     uint32_t dim_z = allocation->dimension.get()->dim_3;
1906 
1907     // Our plan of jitting the last element address doesn't seem to work for struct Allocations
1908     // Instead try to infer the size ourselves without any inter element padding.
1909     if (allocation->element.children.size() > 0)
1910     {
1911         if (dim_x == 0) dim_x = 1;
1912         if (dim_y == 0) dim_y = 1;
1913         if (dim_z == 0) dim_z = 1;
1914 
1915         allocation->size = dim_x * dim_y * dim_z * *allocation->element.datum_size.get();
1916 
1917         if (log)
1918             log->Printf("%s - infered size of struct allocation %" PRIu32 ".", __FUNCTION__,
1919                         *allocation->size.get());
1920         return true;
1921     }
1922 
1923     const char *expr_cstr = JITTemplate(eExprGetOffsetPtr);
1924     char buffer[jit_max_expr_size];
1925 
1926     // Calculate last element
1927     dim_x = dim_x == 0 ? 0 : dim_x - 1;
1928     dim_y = dim_y == 0 ? 0 : dim_y - 1;
1929     dim_z = dim_z == 0 ? 0 : dim_z - 1;
1930 
1931     int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->address.get(), dim_x, dim_y, dim_z);
1932     if (chars_written < 0)
1933     {
1934         if (log)
1935             log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1936         return false;
1937     }
1938     else if (chars_written >= jit_max_expr_size)
1939     {
1940         if (log)
1941             log->Printf("%s - expression too long.", __FUNCTION__);
1942         return false;
1943     }
1944 
1945     uint64_t result = 0;
1946     if (!EvalRSExpression(buffer, frame_ptr, &result))
1947         return false;
1948 
1949     addr_t mem_ptr = static_cast<lldb::addr_t>(result);
1950     // Find pointer to last element and add on size of an element
1951     allocation->size =
1952         static_cast<uint32_t>(mem_ptr - *allocation->data_ptr.get()) + *allocation->element.datum_size.get();
1953 
1954     return true;
1955 }
1956 
1957 // JITs the RS runtime for information about the stride between rows in the allocation.
1958 // This is done to detect padding, since allocated memory is 16-byte aligned.
1959 // Returns true on success, false otherwise
1960 bool
1961 RenderScriptRuntime::JITAllocationStride(AllocationDetails *allocation, StackFrame *frame_ptr)
1962 {
1963     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1964 
1965     if (!allocation->address.isValid() || !allocation->data_ptr.isValid())
1966     {
1967         if (log)
1968             log->Printf("%s - failed to find allocation details.", __FUNCTION__);
1969         return false;
1970     }
1971 
1972     const char *expr_cstr = JITTemplate(eExprGetOffsetPtr);
1973     char buffer[jit_max_expr_size];
1974 
1975     int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->address.get(), 0, 1, 0);
1976     if (chars_written < 0)
1977     {
1978         if (log)
1979             log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1980         return false;
1981     }
1982     else if (chars_written >= jit_max_expr_size)
1983     {
1984         if (log)
1985             log->Printf("%s - expression too long.", __FUNCTION__);
1986         return false;
1987     }
1988 
1989     uint64_t result = 0;
1990     if (!EvalRSExpression(buffer, frame_ptr, &result))
1991         return false;
1992 
1993     addr_t mem_ptr = static_cast<lldb::addr_t>(result);
1994     allocation->stride = static_cast<uint32_t>(mem_ptr - *allocation->data_ptr.get());
1995 
1996     return true;
1997 }
1998 
1999 // JIT all the current runtime info regarding an allocation
2000 bool
2001 RenderScriptRuntime::RefreshAllocation(AllocationDetails *allocation, StackFrame *frame_ptr)
2002 {
2003     // GetOffsetPointer()
2004     if (!JITDataPointer(allocation, frame_ptr))
2005         return false;
2006 
2007     // rsaAllocationGetType()
2008     if (!JITTypePointer(allocation, frame_ptr))
2009         return false;
2010 
2011     // rsaTypeGetNativeData()
2012     if (!JITTypePacked(allocation, frame_ptr))
2013         return false;
2014 
2015     // rsaElementGetNativeData()
2016     if (!JITElementPacked(allocation->element, *allocation->context.get(), frame_ptr))
2017         return false;
2018 
2019     // Sets the datum_size member in Element
2020     SetElementSize(allocation->element);
2021 
2022     // Use GetOffsetPointer() to infer size of the allocation
2023     if (!JITAllocationSize(allocation, frame_ptr))
2024         return false;
2025 
2026     return true;
2027 }
2028 
2029 // Function attempts to set the type_name member of the paramaterised Element object.
2030 // This string should be the name of the struct type the Element represents.
2031 // We need this string for pretty printing the Element to users.
2032 void
2033 RenderScriptRuntime::FindStructTypeName(Element &elem, StackFrame *frame_ptr)
2034 {
2035     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2036 
2037     if (!elem.type_name.IsEmpty()) // Name already set
2038         return;
2039     else
2040         elem.type_name = Element::GetFallbackStructName(); // Default type name if we don't succeed
2041 
2042     // Find all the global variables from the script rs modules
2043     VariableList variable_list;
2044     for (auto module_sp : m_rsmodules)
2045         module_sp->m_module->FindGlobalVariables(RegularExpression("."), true, UINT32_MAX, variable_list);
2046 
2047     // Iterate over all the global variables looking for one with a matching type to the Element.
2048     // We make the assumption a match exists since there needs to be a global variable to reflect the
2049     // struct type back into java host code.
2050     for (uint32_t var_index = 0; var_index < variable_list.GetSize(); ++var_index)
2051     {
2052         const VariableSP var_sp(variable_list.GetVariableAtIndex(var_index));
2053         if (!var_sp)
2054             continue;
2055 
2056         ValueObjectSP valobj_sp = ValueObjectVariable::Create(frame_ptr, var_sp);
2057         if (!valobj_sp)
2058             continue;
2059 
2060         // Find the number of variable fields.
2061         // If it has no fields, or more fields than our Element, then it can't be the struct we're looking for.
2062         // Don't check for equality since RS can add extra struct members for padding.
2063         size_t num_children = valobj_sp->GetNumChildren();
2064         if (num_children > elem.children.size() || num_children == 0)
2065             continue;
2066 
2067         // Iterate over children looking for members with matching field names.
2068         // If all the field names match, this is likely the struct we want.
2069         //
2070         //   TODO: This could be made more robust by also checking children data sizes, or array size
2071         bool found = true;
2072         for (size_t child_index = 0; child_index < num_children; ++child_index)
2073         {
2074             ValueObjectSP child = valobj_sp->GetChildAtIndex(child_index, true);
2075             if (!child || (child->GetName() != elem.children[child_index].type_name))
2076             {
2077                 found = false;
2078                 break;
2079             }
2080         }
2081 
2082         // RS can add extra struct members for padding in the format '#rs_padding_[0-9]+'
2083         if (found && num_children < elem.children.size())
2084         {
2085             const uint32_t size_diff = elem.children.size() - num_children;
2086             if (log)
2087                 log->Printf("%s - %" PRIu32 " padding struct entries", __FUNCTION__, size_diff);
2088 
2089             for (uint32_t padding_index = 0; padding_index < size_diff; ++padding_index)
2090             {
2091                 const ConstString &name = elem.children[num_children + padding_index].type_name;
2092                 if (strcmp(name.AsCString(), "#rs_padding") < 0)
2093                     found = false;
2094             }
2095         }
2096 
2097         // We've found a global var with matching type
2098         if (found)
2099         {
2100             // Dereference since our Element type isn't a pointer.
2101             if (valobj_sp->IsPointerType())
2102             {
2103                 Error err;
2104                 ValueObjectSP deref_valobj = valobj_sp->Dereference(err);
2105                 if (!err.Fail())
2106                     valobj_sp = deref_valobj;
2107             }
2108 
2109             // Save name of variable in Element.
2110             elem.type_name = valobj_sp->GetTypeName();
2111             if (log)
2112                 log->Printf("%s - element name set to %s", __FUNCTION__, elem.type_name.AsCString());
2113 
2114             return;
2115         }
2116     }
2117 }
2118 
2119 // Function sets the datum_size member of Element. Representing the size of a single instance including padding.
2120 // Assumes the relevant allocation information has already been jitted.
2121 void
2122 RenderScriptRuntime::SetElementSize(Element &elem)
2123 {
2124     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2125     const Element::DataType type = *elem.type.get();
2126     assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT && "Invalid allocation type");
2127 
2128     const uint32_t vec_size = *elem.type_vec_size.get();
2129     uint32_t data_size = 0;
2130     uint32_t padding = 0;
2131 
2132     // Element is of a struct type, calculate size recursively.
2133     if ((type == Element::RS_TYPE_NONE) && (elem.children.size() > 0))
2134     {
2135         for (Element &child : elem.children)
2136         {
2137             SetElementSize(child);
2138             const uint32_t array_size = child.array_size.isValid() ? *child.array_size.get() : 1;
2139             data_size += *child.datum_size.get() * array_size;
2140         }
2141     }
2142     // These have been packed already
2143     else if (type == Element::RS_TYPE_UNSIGNED_5_6_5   ||
2144              type == Element::RS_TYPE_UNSIGNED_5_5_5_1 ||
2145              type == Element::RS_TYPE_UNSIGNED_4_4_4_4)
2146     {
2147         data_size = AllocationDetails::RSTypeToFormat[type][eElementSize];
2148     }
2149     else if (type < Element::RS_TYPE_ELEMENT)
2150     {
2151         data_size = vec_size * AllocationDetails::RSTypeToFormat[type][eElementSize];
2152         if (vec_size == 3)
2153             padding = AllocationDetails::RSTypeToFormat[type][eElementSize];
2154     }
2155     else
2156         data_size = GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
2157 
2158     elem.padding = padding;
2159     elem.datum_size = data_size + padding;
2160     if (log)
2161         log->Printf("%s - element size set to %" PRIu32, __FUNCTION__, data_size + padding);
2162 }
2163 
2164 // Given an allocation, this function copies the allocation contents from device into a buffer on the heap.
2165 // Returning a shared pointer to the buffer containing the data.
2166 std::shared_ptr<uint8_t>
2167 RenderScriptRuntime::GetAllocationData(AllocationDetails *allocation, StackFrame *frame_ptr)
2168 {
2169     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2170 
2171     // JIT all the allocation details
2172     if (allocation->shouldRefresh())
2173     {
2174         if (log)
2175             log->Printf("%s - allocation details not calculated yet, jitting info", __FUNCTION__);
2176 
2177         if (!RefreshAllocation(allocation, frame_ptr))
2178         {
2179             if (log)
2180                 log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
2181             return nullptr;
2182         }
2183     }
2184 
2185     assert(allocation->data_ptr.isValid() && allocation->element.type.isValid() &&
2186            allocation->element.type_vec_size.isValid() && allocation->size.isValid() &&
2187            "Allocation information not available");
2188 
2189     // Allocate a buffer to copy data into
2190     const uint32_t size = *allocation->size.get();
2191     std::shared_ptr<uint8_t> buffer(new uint8_t[size]);
2192     if (!buffer)
2193     {
2194         if (log)
2195             log->Printf("%s - couldn't allocate a %" PRIu32 " byte buffer", __FUNCTION__, size);
2196         return nullptr;
2197     }
2198 
2199     // Read the inferior memory
2200     Error error;
2201     lldb::addr_t data_ptr = *allocation->data_ptr.get();
2202     GetProcess()->ReadMemory(data_ptr, buffer.get(), size, error);
2203     if (error.Fail())
2204     {
2205         if (log)
2206             log->Printf("%s - '%s' Couldn't read %" PRIu32 " bytes of allocation data from 0x%" PRIx64,
2207                         __FUNCTION__, error.AsCString(), size, data_ptr);
2208         return nullptr;
2209     }
2210 
2211     return buffer;
2212 }
2213 
2214 // Function copies data from a binary file into an allocation.
2215 // There is a header at the start of the file, FileHeader, before the data content itself.
2216 // Information from this header is used to display warnings to the user about incompatabilities
2217 bool
2218 RenderScriptRuntime::LoadAllocation(Stream &strm, const uint32_t alloc_id, const char *filename, StackFrame *frame_ptr)
2219 {
2220     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2221 
2222     // Find allocation with the given id
2223     AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
2224     if (!alloc)
2225         return false;
2226 
2227     if (log)
2228         log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__, *alloc->address.get());
2229 
2230     // JIT all the allocation details
2231     if (alloc->shouldRefresh())
2232     {
2233         if (log)
2234             log->Printf("%s - allocation details not calculated yet, jitting info.", __FUNCTION__);
2235 
2236         if (!RefreshAllocation(alloc, frame_ptr))
2237         {
2238             if (log)
2239                 log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
2240             return false;
2241         }
2242     }
2243 
2244     assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() && alloc->element.type_vec_size.isValid() &&
2245            alloc->size.isValid() && alloc->element.datum_size.isValid() && "Allocation information not available");
2246 
2247     // Check we can read from file
2248     FileSpec file(filename, true);
2249     if (!file.Exists())
2250     {
2251         strm.Printf("Error: File %s does not exist", filename);
2252         strm.EOL();
2253         return false;
2254     }
2255 
2256     if (!file.Readable())
2257     {
2258         strm.Printf("Error: File %s does not have readable permissions", filename);
2259         strm.EOL();
2260         return false;
2261     }
2262 
2263     // Read file into data buffer
2264     DataBufferSP data_sp(file.ReadFileContents());
2265 
2266     // Cast start of buffer to FileHeader and use pointer to read metadata
2267     void *file_buffer = data_sp->GetBytes();
2268     if (file_buffer == nullptr ||
2269         data_sp->GetByteSize() < (sizeof(AllocationDetails::FileHeader) + sizeof(AllocationDetails::ElementHeader)))
2270     {
2271         strm.Printf("Error: File %s does not contain enough data for header", filename);
2272         strm.EOL();
2273         return false;
2274     }
2275     const AllocationDetails::FileHeader *file_header = static_cast<AllocationDetails::FileHeader *>(file_buffer);
2276 
2277     // Check file starts with ascii characters "RSAD"
2278     if (memcmp(file_header->ident, "RSAD", 4))
2279     {
2280         strm.Printf("Error: File doesn't contain identifier for an RS allocation dump. Are you sure this is the correct file?");
2281         strm.EOL();
2282         return false;
2283     }
2284 
2285     // Look at the type of the root element in the header
2286     AllocationDetails::ElementHeader root_element_header;
2287     memcpy(&root_element_header, static_cast<uint8_t *>(file_buffer) + sizeof(AllocationDetails::FileHeader),
2288            sizeof(AllocationDetails::ElementHeader));
2289 
2290     if (log)
2291         log->Printf("%s - header type %" PRIu32 ", element size %" PRIu32, __FUNCTION__,
2292                     root_element_header.type, root_element_header.element_size);
2293 
2294     // Check if the target allocation and file both have the same number of bytes for an Element
2295     if (*alloc->element.datum_size.get() != root_element_header.element_size)
2296     {
2297         strm.Printf("Warning: Mismatched Element sizes - file %" PRIu32 " bytes, allocation %" PRIu32 " bytes",
2298                     root_element_header.element_size, *alloc->element.datum_size.get());
2299         strm.EOL();
2300     }
2301 
2302     // Check if the target allocation and file both have the same type
2303     const uint32_t alloc_type = static_cast<uint32_t>(*alloc->element.type.get());
2304     const uint32_t file_type = root_element_header.type;
2305 
2306     if (file_type > Element::RS_TYPE_FONT)
2307     {
2308         strm.Printf("Warning: File has unknown allocation type");
2309         strm.EOL();
2310     }
2311     else if (alloc_type != file_type)
2312     {
2313         // Enum value isn't monotonous, so doesn't always index RsDataTypeToString array
2314         uint32_t printable_target_type_index = alloc_type;
2315         uint32_t printable_head_type_index = file_type;
2316         if (alloc_type >= Element::RS_TYPE_ELEMENT && alloc_type <= Element::RS_TYPE_FONT)
2317             printable_target_type_index = static_cast<Element::DataType>((alloc_type - Element::RS_TYPE_ELEMENT) +
2318                                                                          Element::RS_TYPE_MATRIX_2X2 + 1);
2319 
2320         if (file_type >= Element::RS_TYPE_ELEMENT && file_type <= Element::RS_TYPE_FONT)
2321             printable_head_type_index = static_cast<Element::DataType>((file_type - Element::RS_TYPE_ELEMENT) +
2322                                                                        Element::RS_TYPE_MATRIX_2X2 + 1);
2323 
2324         const char *file_type_cstr = AllocationDetails::RsDataTypeToString[printable_head_type_index][0];
2325         const char *target_type_cstr = AllocationDetails::RsDataTypeToString[printable_target_type_index][0];
2326 
2327         strm.Printf("Warning: Mismatched Types - file '%s' type, allocation '%s' type", file_type_cstr,
2328                     target_type_cstr);
2329         strm.EOL();
2330     }
2331 
2332     // Advance buffer past header
2333     file_buffer = static_cast<uint8_t *>(file_buffer) + file_header->hdr_size;
2334 
2335     // Calculate size of allocation data in file
2336     size_t length = data_sp->GetByteSize() - file_header->hdr_size;
2337 
2338     // Check if the target allocation and file both have the same total data size.
2339     const uint32_t alloc_size = *alloc->size.get();
2340     if (alloc_size != length)
2341     {
2342         strm.Printf("Warning: Mismatched allocation sizes - file 0x%" PRIx64 " bytes, allocation 0x%" PRIx32 " bytes",
2343                     (uint64_t)length, alloc_size);
2344         strm.EOL();
2345         length = alloc_size < length ? alloc_size : length; // Set length to copy to minimum
2346     }
2347 
2348     // Copy file data from our buffer into the target allocation.
2349     lldb::addr_t alloc_data = *alloc->data_ptr.get();
2350     Error error;
2351     size_t bytes_written = GetProcess()->WriteMemory(alloc_data, file_buffer, length, error);
2352     if (!error.Success() || bytes_written != length)
2353     {
2354         strm.Printf("Error: Couldn't write data to allocation %s", error.AsCString());
2355         strm.EOL();
2356         return false;
2357     }
2358 
2359     strm.Printf("Contents of file '%s' read into allocation %" PRIu32, filename, alloc->id);
2360     strm.EOL();
2361 
2362     return true;
2363 }
2364 
2365 // Function takes as parameters a byte buffer, which will eventually be written to file as the element header,
2366 // an offset into that buffer, and an Element that will be saved into the buffer at the parametrised offset.
2367 // Return value is the new offset after writing the element into the buffer.
2368 // Elements are saved to the file as the ElementHeader struct followed by offsets to the structs of all the element's
2369 // children.
2370 size_t
2371 RenderScriptRuntime::PopulateElementHeaders(const std::shared_ptr<uint8_t> header_buffer, size_t offset,
2372                                             const Element &elem)
2373 {
2374     // File struct for an element header with all the relevant details copied from elem.
2375     // We assume members are valid already.
2376     AllocationDetails::ElementHeader elem_header;
2377     elem_header.type = *elem.type.get();
2378     elem_header.kind = *elem.type_kind.get();
2379     elem_header.element_size = *elem.datum_size.get();
2380     elem_header.vector_size = *elem.type_vec_size.get();
2381     elem_header.array_size = elem.array_size.isValid() ? *elem.array_size.get() : 0;
2382     const size_t elem_header_size = sizeof(AllocationDetails::ElementHeader);
2383 
2384     // Copy struct into buffer and advance offset
2385     // We assume that header_buffer has been checked for nullptr before this method is called
2386     memcpy(header_buffer.get() + offset, &elem_header, elem_header_size);
2387     offset += elem_header_size;
2388 
2389     // Starting offset of child ElementHeader struct
2390     size_t child_offset = offset + ((elem.children.size() + 1) * sizeof(uint32_t));
2391     for (const RenderScriptRuntime::Element &child : elem.children)
2392     {
2393         // Recursively populate the buffer with the element header structs of children.
2394         // Then save the offsets where they were set after the parent element header.
2395         memcpy(header_buffer.get() + offset, &child_offset, sizeof(uint32_t));
2396         offset += sizeof(uint32_t);
2397 
2398         child_offset = PopulateElementHeaders(header_buffer, child_offset, child);
2399     }
2400 
2401     // Zero indicates no more children
2402     memset(header_buffer.get() + offset, 0, sizeof(uint32_t));
2403 
2404     return child_offset;
2405 }
2406 
2407 // Given an Element object this function returns the total size needed in the file header to store the element's
2408 // details.
2409 // Taking into account the size of the element header struct, plus the offsets to all the element's children.
2410 // Function is recursive so that the size of all ancestors is taken into account.
2411 size_t
2412 RenderScriptRuntime::CalculateElementHeaderSize(const Element &elem)
2413 {
2414     size_t size = (elem.children.size() + 1) * sizeof(uint32_t); // Offsets to children plus zero terminator
2415     size += sizeof(AllocationDetails::ElementHeader);            // Size of header struct with type details
2416 
2417     // Calculate recursively for all descendants
2418     for (const Element &child : elem.children)
2419         size += CalculateElementHeaderSize(child);
2420 
2421     return size;
2422 }
2423 
2424 // Function copies allocation contents into a binary file.
2425 // This file can then be loaded later into a different allocation.
2426 // There is a header, FileHeader, before the allocation data containing meta-data.
2427 bool
2428 RenderScriptRuntime::SaveAllocation(Stream &strm, const uint32_t alloc_id, const char *filename, StackFrame *frame_ptr)
2429 {
2430     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2431 
2432     // Find allocation with the given id
2433     AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
2434     if (!alloc)
2435         return false;
2436 
2437     if (log)
2438         log->Printf("%s - found allocation 0x%" PRIx64 ".", __FUNCTION__, *alloc->address.get());
2439 
2440     // JIT all the allocation details
2441     if (alloc->shouldRefresh())
2442     {
2443         if (log)
2444             log->Printf("%s - allocation details not calculated yet, jitting info.", __FUNCTION__);
2445 
2446         if (!RefreshAllocation(alloc, frame_ptr))
2447         {
2448             if (log)
2449                 log->Printf("%s - couldn't JIT allocation details.", __FUNCTION__);
2450             return false;
2451         }
2452     }
2453 
2454     assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() && alloc->element.type_vec_size.isValid() &&
2455            alloc->element.datum_size.get() && alloc->element.type_kind.isValid() && alloc->dimension.isValid() &&
2456            "Allocation information not available");
2457 
2458     // Check we can create writable file
2459     FileSpec file_spec(filename, true);
2460     File file(file_spec, File::eOpenOptionWrite | File::eOpenOptionCanCreate | File::eOpenOptionTruncate);
2461     if (!file)
2462     {
2463         strm.Printf("Error: Failed to open '%s' for writing", filename);
2464         strm.EOL();
2465         return false;
2466     }
2467 
2468     // Read allocation into buffer of heap memory
2469     const std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
2470     if (!buffer)
2471     {
2472         strm.Printf("Error: Couldn't read allocation data into buffer");
2473         strm.EOL();
2474         return false;
2475     }
2476 
2477     // Create the file header
2478     AllocationDetails::FileHeader head;
2479     memcpy(head.ident, "RSAD", 4);
2480     head.dims[0] = static_cast<uint32_t>(alloc->dimension.get()->dim_1);
2481     head.dims[1] = static_cast<uint32_t>(alloc->dimension.get()->dim_2);
2482     head.dims[2] = static_cast<uint32_t>(alloc->dimension.get()->dim_3);
2483 
2484     const size_t element_header_size = CalculateElementHeaderSize(alloc->element);
2485     assert((sizeof(AllocationDetails::FileHeader) + element_header_size) < UINT16_MAX && "Element header too large");
2486     head.hdr_size = static_cast<uint16_t>(sizeof(AllocationDetails::FileHeader) + element_header_size);
2487 
2488     // Write the file header
2489     size_t num_bytes = sizeof(AllocationDetails::FileHeader);
2490     if (log)
2491         log->Printf("%s - writing File Header, 0x%" PRIx64 " bytes", __FUNCTION__, (uint64_t)num_bytes);
2492 
2493     Error err = file.Write(&head, num_bytes);
2494     if (!err.Success())
2495     {
2496         strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), filename);
2497         strm.EOL();
2498         return false;
2499     }
2500 
2501     // Create the headers describing the element type of the allocation.
2502     std::shared_ptr<uint8_t> element_header_buffer(new uint8_t[element_header_size]);
2503     if (element_header_buffer == nullptr)
2504     {
2505         strm.Printf("Internal Error: Couldn't allocate %" PRIu64 " bytes on the heap", (uint64_t)element_header_size);
2506         strm.EOL();
2507         return false;
2508     }
2509 
2510     PopulateElementHeaders(element_header_buffer, 0, alloc->element);
2511 
2512     // Write headers for allocation element type to file
2513     num_bytes = element_header_size;
2514     if (log)
2515         log->Printf("%s - writing element headers, 0x%" PRIx64 " bytes.", __FUNCTION__, (uint64_t)num_bytes);
2516 
2517     err = file.Write(element_header_buffer.get(), num_bytes);
2518     if (!err.Success())
2519     {
2520         strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), filename);
2521         strm.EOL();
2522         return false;
2523     }
2524 
2525     // Write allocation data to file
2526     num_bytes = static_cast<size_t>(*alloc->size.get());
2527     if (log)
2528         log->Printf("%s - writing 0x%" PRIx64 " bytes", __FUNCTION__, (uint64_t)num_bytes);
2529 
2530     err = file.Write(buffer.get(), num_bytes);
2531     if (!err.Success())
2532     {
2533         strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), filename);
2534         strm.EOL();
2535         return false;
2536     }
2537 
2538     strm.Printf("Allocation written to file '%s'", filename);
2539     strm.EOL();
2540     return true;
2541 }
2542 
2543 bool
2544 RenderScriptRuntime::LoadModule(const lldb::ModuleSP &module_sp)
2545 {
2546     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2547 
2548     if (module_sp)
2549     {
2550         for (const auto &rs_module : m_rsmodules)
2551         {
2552             if (rs_module->m_module == module_sp)
2553             {
2554                 // Check if the user has enabled automatically breaking on
2555                 // all RS kernels.
2556                 if (m_breakAllKernels)
2557                     BreakOnModuleKernels(rs_module);
2558 
2559                 return false;
2560             }
2561         }
2562         bool module_loaded = false;
2563         switch (GetModuleKind(module_sp))
2564         {
2565             case eModuleKindKernelObj:
2566             {
2567                 RSModuleDescriptorSP module_desc;
2568                 module_desc.reset(new RSModuleDescriptor(module_sp));
2569                 if (module_desc->ParseRSInfo())
2570                 {
2571                     m_rsmodules.push_back(module_desc);
2572                     module_loaded = true;
2573                 }
2574                 if (module_loaded)
2575                 {
2576                     FixupScriptDetails(module_desc);
2577                 }
2578                 break;
2579             }
2580             case eModuleKindDriver:
2581             {
2582                 if (!m_libRSDriver)
2583                 {
2584                     m_libRSDriver = module_sp;
2585                     LoadRuntimeHooks(m_libRSDriver, RenderScriptRuntime::eModuleKindDriver);
2586                 }
2587                 break;
2588             }
2589             case eModuleKindImpl:
2590             {
2591                 m_libRSCpuRef = module_sp;
2592                 break;
2593             }
2594             case eModuleKindLibRS:
2595             {
2596                 if (!m_libRS)
2597                 {
2598                     m_libRS = module_sp;
2599                     static ConstString gDbgPresentStr("gDebuggerPresent");
2600                     const Symbol *debug_present =
2601                         m_libRS->FindFirstSymbolWithNameAndType(gDbgPresentStr, eSymbolTypeData);
2602                     if (debug_present)
2603                     {
2604                         Error error;
2605                         uint32_t flag = 0x00000001U;
2606                         Target &target = GetProcess()->GetTarget();
2607                         addr_t addr = debug_present->GetLoadAddress(&target);
2608                         GetProcess()->WriteMemory(addr, &flag, sizeof(flag), error);
2609                         if (error.Success())
2610                         {
2611                             if (log)
2612                                 log->Printf("%s - debugger present flag set on debugee.", __FUNCTION__);
2613 
2614                             m_debuggerPresentFlagged = true;
2615                         }
2616                         else if (log)
2617                         {
2618                             log->Printf("%s - error writing debugger present flags '%s' ", __FUNCTION__,
2619                                         error.AsCString());
2620                         }
2621                     }
2622                     else if (log)
2623                     {
2624                         log->Printf("%s - error writing debugger present flags - symbol not found", __FUNCTION__);
2625                     }
2626                 }
2627                 break;
2628             }
2629             default:
2630                 break;
2631         }
2632         if (module_loaded)
2633             Update();
2634         return module_loaded;
2635     }
2636     return false;
2637 }
2638 
2639 void
2640 RenderScriptRuntime::Update()
2641 {
2642     if (m_rsmodules.size() > 0)
2643     {
2644         if (!m_initiated)
2645         {
2646             Initiate();
2647         }
2648     }
2649 }
2650 
2651 // The maximum line length of an .rs.info packet
2652 #define MAXLINE 500
2653 #define STRINGIFY(x) #x
2654 #define MAXLINESTR_(x) "%" STRINGIFY(x) "s"
2655 #define MAXLINESTR MAXLINESTR_(MAXLINE)
2656 
2657 // The .rs.info symbol in renderscript modules contains a string which needs to be parsed.
2658 // The string is basic and is parsed on a line by line basis.
2659 bool
2660 RSModuleDescriptor::ParseRSInfo()
2661 {
2662     assert(m_module);
2663     const Symbol *info_sym = m_module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData);
2664     if (!info_sym)
2665         return false;
2666 
2667     const addr_t addr = info_sym->GetAddressRef().GetFileAddress();
2668     if (addr == LLDB_INVALID_ADDRESS)
2669         return false;
2670 
2671     const addr_t size = info_sym->GetByteSize();
2672     const FileSpec fs = m_module->GetFileSpec();
2673 
2674     const DataBufferSP buffer = fs.ReadFileContents(addr, size);
2675     if (!buffer)
2676         return false;
2677 
2678     // split rs.info. contents into lines
2679     std::vector<std::string> info_lines;
2680     {
2681         const std::string info((const char *)buffer->GetBytes());
2682         for (size_t tail = 0; tail < info.size();)
2683         {
2684             // find next new line or end of string
2685             size_t head = info.find('\n', tail);
2686             head = (head == std::string::npos) ? info.size() : head;
2687             std::string line = info.substr(tail, head - tail);
2688             // add to line list
2689             info_lines.push_back(line);
2690             tail = head + 1;
2691         }
2692     }
2693 
2694     std::array<char, MAXLINE> name{{'\0'}};
2695     std::array<char, MAXLINE> value{{'\0'}};
2696 
2697     // parse all text lines of .rs.info
2698     for (auto line = info_lines.begin(); line != info_lines.end(); ++line)
2699     {
2700         uint32_t numDefns = 0;
2701         if (sscanf(line->c_str(), "exportVarCount: %" PRIu32 "", &numDefns) == 1)
2702         {
2703             while (numDefns--)
2704                 m_globals.push_back(RSGlobalDescriptor(this, (++line)->c_str()));
2705         }
2706         else if (sscanf(line->c_str(), "exportForEachCount: %" PRIu32 "", &numDefns) == 1)
2707         {
2708             while (numDefns--)
2709             {
2710                 uint32_t slot = 0;
2711                 name[0] = '\0';
2712                 static const char *fmt_s = "%" PRIu32 " - " MAXLINESTR;
2713                 if (sscanf((++line)->c_str(), fmt_s, &slot, name.data()) == 2)
2714                 {
2715                     if (name[0] != '\0')
2716                         m_kernels.push_back(RSKernelDescriptor(this, name.data(), slot));
2717                 }
2718             }
2719         }
2720         else if (sscanf(line->c_str(), "pragmaCount: %" PRIu32 "", &numDefns) == 1)
2721         {
2722             while (numDefns--)
2723             {
2724                 name[0] = value[0] = '\0';
2725                 static const char *fmt_s = MAXLINESTR " - " MAXLINESTR;
2726                 if (sscanf((++line)->c_str(), fmt_s, name.data(), value.data()) != 0)
2727                 {
2728                     if (name[0] != '\0')
2729                         m_pragmas[std::string(name.data())] = value.data();
2730                 }
2731             }
2732         }
2733         else
2734         {
2735             Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2736             if (log)
2737             {
2738                 log->Printf("%s - skipping .rs.info field '%s'", __FUNCTION__, line->c_str());
2739             }
2740         }
2741     }
2742 
2743     // 'root' kernel should always be present
2744     return m_kernels.size() > 0;
2745 }
2746 
2747 void
2748 RenderScriptRuntime::Status(Stream &strm) const
2749 {
2750     if (m_libRS)
2751     {
2752         strm.Printf("Runtime Library discovered.");
2753         strm.EOL();
2754     }
2755     if (m_libRSDriver)
2756     {
2757         strm.Printf("Runtime Driver discovered.");
2758         strm.EOL();
2759     }
2760     if (m_libRSCpuRef)
2761     {
2762         strm.Printf("CPU Reference Implementation discovered.");
2763         strm.EOL();
2764     }
2765 
2766     if (m_runtimeHooks.size())
2767     {
2768         strm.Printf("Runtime functions hooked:");
2769         strm.EOL();
2770         for (auto b : m_runtimeHooks)
2771         {
2772             strm.Indent(b.second->defn->name);
2773             strm.EOL();
2774         }
2775     }
2776     else
2777     {
2778         strm.Printf("Runtime is not hooked.");
2779         strm.EOL();
2780     }
2781 }
2782 
2783 void
2784 RenderScriptRuntime::DumpContexts(Stream &strm) const
2785 {
2786     strm.Printf("Inferred RenderScript Contexts:");
2787     strm.EOL();
2788     strm.IndentMore();
2789 
2790     std::map<addr_t, uint64_t> contextReferences;
2791 
2792     // Iterate over all of the currently discovered scripts.
2793     // Note: We cant push or pop from m_scripts inside this loop or it may invalidate script.
2794     for (const auto &script : m_scripts)
2795     {
2796         if (!script->context.isValid())
2797             continue;
2798         lldb::addr_t context = *script->context;
2799 
2800         if (contextReferences.find(context) != contextReferences.end())
2801         {
2802             contextReferences[context]++;
2803         }
2804         else
2805         {
2806             contextReferences[context] = 1;
2807         }
2808     }
2809 
2810     for (const auto &cRef : contextReferences)
2811     {
2812         strm.Printf("Context 0x%" PRIx64 ": %" PRIu64 " script instances", cRef.first, cRef.second);
2813         strm.EOL();
2814     }
2815     strm.IndentLess();
2816 }
2817 
2818 void
2819 RenderScriptRuntime::DumpKernels(Stream &strm) const
2820 {
2821     strm.Printf("RenderScript Kernels:");
2822     strm.EOL();
2823     strm.IndentMore();
2824     for (const auto &module : m_rsmodules)
2825     {
2826         strm.Printf("Resource '%s':", module->m_resname.c_str());
2827         strm.EOL();
2828         for (const auto &kernel : module->m_kernels)
2829         {
2830             strm.Indent(kernel.m_name.AsCString());
2831             strm.EOL();
2832         }
2833     }
2834     strm.IndentLess();
2835 }
2836 
2837 RenderScriptRuntime::AllocationDetails *
2838 RenderScriptRuntime::FindAllocByID(Stream &strm, const uint32_t alloc_id)
2839 {
2840     AllocationDetails *alloc = nullptr;
2841 
2842     // See if we can find allocation using id as an index;
2843     if (alloc_id <= m_allocations.size() && alloc_id != 0 && m_allocations[alloc_id - 1]->id == alloc_id)
2844     {
2845         alloc = m_allocations[alloc_id - 1].get();
2846         return alloc;
2847     }
2848 
2849     // Fallback to searching
2850     for (const auto &a : m_allocations)
2851     {
2852         if (a->id == alloc_id)
2853         {
2854             alloc = a.get();
2855             break;
2856         }
2857     }
2858 
2859     if (alloc == nullptr)
2860     {
2861         strm.Printf("Error: Couldn't find allocation with id matching %" PRIu32, alloc_id);
2862         strm.EOL();
2863     }
2864 
2865     return alloc;
2866 }
2867 
2868 // Prints the contents of an allocation to the output stream, which may be a file
2869 bool
2870 RenderScriptRuntime::DumpAllocation(Stream &strm, StackFrame *frame_ptr, const uint32_t id)
2871 {
2872     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2873 
2874     // Check we can find the desired allocation
2875     AllocationDetails *alloc = FindAllocByID(strm, id);
2876     if (!alloc)
2877         return false; // FindAllocByID() will print error message for us here
2878 
2879     if (log)
2880         log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__, *alloc->address.get());
2881 
2882     // Check we have information about the allocation, if not calculate it
2883     if (alloc->shouldRefresh())
2884     {
2885         if (log)
2886             log->Printf("%s - allocation details not calculated yet, jitting info.", __FUNCTION__);
2887 
2888         // JIT all the allocation information
2889         if (!RefreshAllocation(alloc, frame_ptr))
2890         {
2891             strm.Printf("Error: Couldn't JIT allocation details");
2892             strm.EOL();
2893             return false;
2894         }
2895     }
2896 
2897     // Establish format and size of each data element
2898     const uint32_t vec_size = *alloc->element.type_vec_size.get();
2899     const Element::DataType type = *alloc->element.type.get();
2900 
2901     assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT && "Invalid allocation type");
2902 
2903     lldb::Format format;
2904     if (type >= Element::RS_TYPE_ELEMENT)
2905         format = eFormatHex;
2906     else
2907         format = vec_size == 1 ? static_cast<lldb::Format>(AllocationDetails::RSTypeToFormat[type][eFormatSingle])
2908                                : static_cast<lldb::Format>(AllocationDetails::RSTypeToFormat[type][eFormatVector]);
2909 
2910     const uint32_t data_size = *alloc->element.datum_size.get();
2911 
2912     if (log)
2913         log->Printf("%s - element size %" PRIu32 " bytes, including padding", __FUNCTION__, data_size);
2914 
2915     // Allocate a buffer to copy data into
2916     std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
2917     if (!buffer)
2918     {
2919         strm.Printf("Error: Couldn't read allocation data");
2920         strm.EOL();
2921         return false;
2922     }
2923 
2924     // Calculate stride between rows as there may be padding at end of rows since
2925     // allocated memory is 16-byte aligned
2926     if (!alloc->stride.isValid())
2927     {
2928         if (alloc->dimension.get()->dim_2 == 0) // We only have one dimension
2929             alloc->stride = 0;
2930         else if (!JITAllocationStride(alloc, frame_ptr))
2931         {
2932             strm.Printf("Error: Couldn't calculate allocation row stride");
2933             strm.EOL();
2934             return false;
2935         }
2936     }
2937     const uint32_t stride = *alloc->stride.get();
2938     const uint32_t size = *alloc->size.get(); // Size of whole allocation
2939     const uint32_t padding = alloc->element.padding.isValid() ? *alloc->element.padding.get() : 0;
2940     if (log)
2941         log->Printf("%s - stride %" PRIu32 " bytes, size %" PRIu32 " bytes, padding %" PRIu32,
2942                     __FUNCTION__, stride, size, padding);
2943 
2944     // Find dimensions used to index loops, so need to be non-zero
2945     uint32_t dim_x = alloc->dimension.get()->dim_1;
2946     dim_x = dim_x == 0 ? 1 : dim_x;
2947 
2948     uint32_t dim_y = alloc->dimension.get()->dim_2;
2949     dim_y = dim_y == 0 ? 1 : dim_y;
2950 
2951     uint32_t dim_z = alloc->dimension.get()->dim_3;
2952     dim_z = dim_z == 0 ? 1 : dim_z;
2953 
2954     // Use data extractor to format output
2955     const uint32_t archByteSize = GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
2956     DataExtractor alloc_data(buffer.get(), size, GetProcess()->GetByteOrder(), archByteSize);
2957 
2958     uint32_t offset = 0;   // Offset in buffer to next element to be printed
2959     uint32_t prev_row = 0; // Offset to the start of the previous row
2960 
2961     // Iterate over allocation dimensions, printing results to user
2962     strm.Printf("Data (X, Y, Z):");
2963     for (uint32_t z = 0; z < dim_z; ++z)
2964     {
2965         for (uint32_t y = 0; y < dim_y; ++y)
2966         {
2967             // Use stride to index start of next row.
2968             if (!(y == 0 && z == 0))
2969                 offset = prev_row + stride;
2970             prev_row = offset;
2971 
2972             // Print each element in the row individually
2973             for (uint32_t x = 0; x < dim_x; ++x)
2974             {
2975                 strm.Printf("\n(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ") = ", x, y, z);
2976                 if ((type == Element::RS_TYPE_NONE) && (alloc->element.children.size() > 0) &&
2977                     (alloc->element.type_name != Element::GetFallbackStructName()))
2978                 {
2979                     // Here we are dumping an Element of struct type.
2980                     // This is done using expression evaluation with the name of the struct type and pointer to element.
2981 
2982                     // Don't print the name of the resulting expression, since this will be '$[0-9]+'
2983                     DumpValueObjectOptions expr_options;
2984                     expr_options.SetHideName(true);
2985 
2986                     // Setup expression as derefrencing a pointer cast to element address.
2987                     char expr_char_buffer[jit_max_expr_size];
2988                     int chars_written = snprintf(expr_char_buffer, jit_max_expr_size, "*(%s*) 0x%" PRIx64,
2989                                                  alloc->element.type_name.AsCString(), *alloc->data_ptr.get() + offset);
2990 
2991                     if (chars_written < 0 || chars_written >= jit_max_expr_size)
2992                     {
2993                         if (log)
2994                             log->Printf("%s - error in snprintf().", __FUNCTION__);
2995                         continue;
2996                     }
2997 
2998                     // Evaluate expression
2999                     ValueObjectSP expr_result;
3000                     GetProcess()->GetTarget().EvaluateExpression(expr_char_buffer, frame_ptr, expr_result);
3001 
3002                     // Print the results to our stream.
3003                     expr_result->Dump(strm, expr_options);
3004                 }
3005                 else
3006                 {
3007                     alloc_data.Dump(&strm, offset, format, data_size - padding, 1, 1, LLDB_INVALID_ADDRESS, 0, 0);
3008                 }
3009                 offset += data_size;
3010             }
3011         }
3012     }
3013     strm.EOL();
3014 
3015     return true;
3016 }
3017 
3018 // Function recalculates all our cached information about allocations by jitting the
3019 // RS runtime regarding each allocation we know about.
3020 // Returns true if all allocations could be recomputed, false otherwise.
3021 bool
3022 RenderScriptRuntime::RecomputeAllAllocations(Stream &strm, StackFrame *frame_ptr)
3023 {
3024     bool success = true;
3025     for (auto &alloc : m_allocations)
3026     {
3027         // JIT current allocation information
3028         if (!RefreshAllocation(alloc.get(), frame_ptr))
3029         {
3030             strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32 "\n", alloc->id);
3031             success = false;
3032         }
3033     }
3034 
3035     if (success)
3036         strm.Printf("All allocations successfully recomputed");
3037     strm.EOL();
3038 
3039     return success;
3040 }
3041 
3042 // Prints information regarding currently loaded allocations.
3043 // These details are gathered by jitting the runtime, which has as latency.
3044 // Index parameter specifies a single allocation ID to print, or a zero value to print them all
3045 void
3046 RenderScriptRuntime::ListAllocations(Stream &strm, StackFrame *frame_ptr, const uint32_t index)
3047 {
3048     strm.Printf("RenderScript Allocations:");
3049     strm.EOL();
3050     strm.IndentMore();
3051 
3052     for (auto &alloc : m_allocations)
3053     {
3054         // index will only be zero if we want to print all allocations
3055         if (index != 0 && index != alloc->id)
3056             continue;
3057 
3058         // JIT current allocation information
3059         if (alloc->shouldRefresh() && !RefreshAllocation(alloc.get(), frame_ptr))
3060         {
3061             strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32, alloc->id);
3062             strm.EOL();
3063             continue;
3064         }
3065 
3066         strm.Printf("%" PRIu32 ":", alloc->id);
3067         strm.EOL();
3068         strm.IndentMore();
3069 
3070         strm.Indent("Context: ");
3071         if (!alloc->context.isValid())
3072             strm.Printf("unknown\n");
3073         else
3074             strm.Printf("0x%" PRIx64 "\n", *alloc->context.get());
3075 
3076         strm.Indent("Address: ");
3077         if (!alloc->address.isValid())
3078             strm.Printf("unknown\n");
3079         else
3080             strm.Printf("0x%" PRIx64 "\n", *alloc->address.get());
3081 
3082         strm.Indent("Data pointer: ");
3083         if (!alloc->data_ptr.isValid())
3084             strm.Printf("unknown\n");
3085         else
3086             strm.Printf("0x%" PRIx64 "\n", *alloc->data_ptr.get());
3087 
3088         strm.Indent("Dimensions: ");
3089         if (!alloc->dimension.isValid())
3090             strm.Printf("unknown\n");
3091         else
3092             strm.Printf("(%" PRId32 ", %" PRId32 ", %" PRId32 ")\n",
3093                         alloc->dimension.get()->dim_1, alloc->dimension.get()->dim_2, alloc->dimension.get()->dim_3);
3094 
3095         strm.Indent("Data Type: ");
3096         if (!alloc->element.type.isValid() || !alloc->element.type_vec_size.isValid())
3097             strm.Printf("unknown\n");
3098         else
3099         {
3100             const int vector_size = *alloc->element.type_vec_size.get();
3101             Element::DataType type = *alloc->element.type.get();
3102 
3103             if (!alloc->element.type_name.IsEmpty())
3104                 strm.Printf("%s\n", alloc->element.type_name.AsCString());
3105             else
3106             {
3107                 // Enum value isn't monotonous, so doesn't always index RsDataTypeToString array
3108                 if (type >= Element::RS_TYPE_ELEMENT && type <= Element::RS_TYPE_FONT)
3109                     type = static_cast<Element::DataType>((type - Element::RS_TYPE_ELEMENT) +
3110                                                           Element::RS_TYPE_MATRIX_2X2 + 1);
3111 
3112                 if (type >= (sizeof(AllocationDetails::RsDataTypeToString) /
3113                              sizeof(AllocationDetails::RsDataTypeToString[0])) ||
3114                     vector_size > 4 || vector_size < 1)
3115                     strm.Printf("invalid type\n");
3116                 else
3117                     strm.Printf("%s\n", AllocationDetails::RsDataTypeToString[static_cast<uint32_t>(type)]
3118                                                                              [vector_size - 1]);
3119             }
3120         }
3121 
3122         strm.Indent("Data Kind: ");
3123         if (!alloc->element.type_kind.isValid())
3124             strm.Printf("unknown\n");
3125         else
3126         {
3127             const Element::DataKind kind = *alloc->element.type_kind.get();
3128             if (kind < Element::RS_KIND_USER || kind > Element::RS_KIND_PIXEL_YUV)
3129                 strm.Printf("invalid kind\n");
3130             else
3131                 strm.Printf("%s\n", AllocationDetails::RsDataKindToString[static_cast<uint32_t>(kind)]);
3132         }
3133 
3134         strm.EOL();
3135         strm.IndentLess();
3136     }
3137     strm.IndentLess();
3138 }
3139 
3140 // Set breakpoints on every kernel found in RS module
3141 void
3142 RenderScriptRuntime::BreakOnModuleKernels(const RSModuleDescriptorSP rsmodule_sp)
3143 {
3144     for (const auto &kernel : rsmodule_sp->m_kernels)
3145     {
3146         // Don't set breakpoint on 'root' kernel
3147         if (strcmp(kernel.m_name.AsCString(), "root") == 0)
3148             continue;
3149 
3150         CreateKernelBreakpoint(kernel.m_name);
3151     }
3152 }
3153 
3154 // Method is internally called by the 'kernel breakpoint all' command to
3155 // enable or disable breaking on all kernels.
3156 //
3157 // When do_break is true we want to enable this functionality.
3158 // When do_break is false we want to disable it.
3159 void
3160 RenderScriptRuntime::SetBreakAllKernels(bool do_break, TargetSP target)
3161 {
3162     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3163 
3164     InitSearchFilter(target);
3165 
3166     // Set breakpoints on all the kernels
3167     if (do_break && !m_breakAllKernels)
3168     {
3169         m_breakAllKernels = true;
3170 
3171         for (const auto &module : m_rsmodules)
3172             BreakOnModuleKernels(module);
3173 
3174         if (log)
3175             log->Printf("%s(True) - breakpoints set on all currently loaded kernels.", __FUNCTION__);
3176     }
3177     else if (!do_break && m_breakAllKernels) // Breakpoints won't be set on any new kernels.
3178     {
3179         m_breakAllKernels = false;
3180 
3181         if (log)
3182             log->Printf("%s(False) - breakpoints no longer automatically set.", __FUNCTION__);
3183     }
3184 }
3185 
3186 // Given the name of a kernel this function creates a breakpoint using our
3187 // own breakpoint resolver, and returns the Breakpoint shared pointer.
3188 BreakpointSP
3189 RenderScriptRuntime::CreateKernelBreakpoint(const ConstString &name)
3190 {
3191     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3192 
3193     if (!m_filtersp)
3194     {
3195         if (log)
3196             log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
3197         return nullptr;
3198     }
3199 
3200     BreakpointResolverSP resolver_sp(new RSBreakpointResolver(nullptr, name));
3201     BreakpointSP bp = GetProcess()->GetTarget().CreateBreakpoint(m_filtersp, resolver_sp, false, false, false);
3202 
3203     // Give RS breakpoints a specific name, so the user can manipulate them as a group.
3204     Error err;
3205     if (!bp->AddName("RenderScriptKernel", err) && log)
3206         log->Printf("%s - error setting break name, '%s'.", __FUNCTION__, err.AsCString());
3207 
3208     return bp;
3209 }
3210 
3211 // Given an expression for a variable this function tries to calculate the variable's value.
3212 // If this is possible it returns true and sets the uint64_t parameter to the variables unsigned value.
3213 // Otherwise function returns false.
3214 bool
3215 RenderScriptRuntime::GetFrameVarAsUnsigned(const StackFrameSP frame_sp, const char *var_name, uint64_t &val)
3216 {
3217     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3218     Error error;
3219     VariableSP var_sp;
3220 
3221     // Find variable in stack frame
3222     ValueObjectSP value_sp(frame_sp->GetValueForVariableExpressionPath(
3223         var_name, eNoDynamicValues,
3224         StackFrame::eExpressionPathOptionCheckPtrVsMember | StackFrame::eExpressionPathOptionsAllowDirectIVarAccess,
3225         var_sp, error));
3226     if (!error.Success())
3227     {
3228         if (log)
3229             log->Printf("%s - error, couldn't find '%s' in frame", __FUNCTION__, var_name);
3230         return false;
3231     }
3232 
3233     // Find the uint32_t value for the variable
3234     bool success = false;
3235     val = value_sp->GetValueAsUnsigned(0, &success);
3236     if (!success)
3237     {
3238         if (log)
3239             log->Printf("%s - error, couldn't parse '%s' as an uint32_t.", __FUNCTION__, var_name);
3240         return false;
3241     }
3242 
3243     return true;
3244 }
3245 
3246 // Function attempts to find the current coordinate of a kernel invocation by investigating the
3247 // values of frame variables in the .expand function. These coordinates are returned via the coord
3248 // array reference parameter. Returns true if the coordinates could be found, and false otherwise.
3249 bool
3250 RenderScriptRuntime::GetKernelCoordinate(RSCoordinate &coord, Thread *thread_ptr)
3251 {
3252     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3253 
3254     if (!thread_ptr)
3255     {
3256         if (log)
3257             log->Printf("%s - Error, No thread pointer", __FUNCTION__);
3258 
3259         return false;
3260     }
3261 
3262     // Walk the call stack looking for a function whose name has the suffix '.expand'
3263     // and contains the variables we're looking for.
3264     for (uint32_t i = 0; i < thread_ptr->GetStackFrameCount(); ++i)
3265     {
3266         if (!thread_ptr->SetSelectedFrameByIndex(i))
3267             continue;
3268 
3269         StackFrameSP frame_sp = thread_ptr->GetSelectedFrame();
3270         if (!frame_sp)
3271             continue;
3272 
3273         // Find the function name
3274         const SymbolContext sym_ctx = frame_sp->GetSymbolContext(false);
3275         const char *func_name_cstr = sym_ctx.GetFunctionName().AsCString();
3276         if (!func_name_cstr)
3277             continue;
3278 
3279         if (log)
3280             log->Printf("%s - Inspecting function '%s'", __FUNCTION__, func_name_cstr);
3281 
3282         // Check if function name has .expand suffix
3283         std::string func_name(func_name_cstr);
3284         const int length_difference = func_name.length() - RenderScriptRuntime::s_runtimeExpandSuffix.length();
3285         if (length_difference <= 0)
3286             continue;
3287 
3288         const int32_t has_expand_suffix = func_name.compare(length_difference,
3289                                                             RenderScriptRuntime::s_runtimeExpandSuffix.length(),
3290                                                             RenderScriptRuntime::s_runtimeExpandSuffix);
3291 
3292         if (has_expand_suffix != 0)
3293             continue;
3294 
3295         if (log)
3296             log->Printf("%s - Found .expand function '%s'", __FUNCTION__, func_name_cstr);
3297 
3298         // Get values for variables in .expand frame that tell us the current kernel invocation
3299         bool found_coord_variables = true;
3300         assert(RenderScriptRuntime::s_runtimeCoordVars.size() == coord.size());
3301 
3302         for (uint32_t i = 0; i < coord.size(); ++i)
3303         {
3304             uint64_t value = 0;
3305             if (!GetFrameVarAsUnsigned(frame_sp, RenderScriptRuntime::s_runtimeCoordVars[i], value))
3306             {
3307                 found_coord_variables = false;
3308                 break;
3309             }
3310             coord[i] = value;
3311         }
3312 
3313         if (found_coord_variables)
3314             return true;
3315     }
3316     return false;
3317 }
3318 
3319 // Callback when a kernel breakpoint hits and we're looking for a specific coordinate.
3320 // Baton parameter contains a pointer to the target coordinate we want to break on.
3321 // Function then checks the .expand frame for the current coordinate and breaks to user if it matches.
3322 // Parameter 'break_id' is the id of the Breakpoint which made the callback.
3323 // Parameter 'break_loc_id' is the id for the BreakpointLocation which was hit,
3324 // a single logical breakpoint can have multiple addresses.
3325 bool
3326 RenderScriptRuntime::KernelBreakpointHit(void *baton, StoppointCallbackContext *ctx, user_id_t break_id,
3327                                          user_id_t break_loc_id)
3328 {
3329     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3330 
3331     assert(baton && "Error: null baton in conditional kernel breakpoint callback");
3332 
3333     // Coordinate we want to stop on
3334     const uint32_t *target_coord = static_cast<const uint32_t *>(baton);
3335 
3336     if (log)
3337         log->Printf("%s - Break ID %" PRIu64 ", (%" PRIu32 ", %" PRIu32 ", %" PRIu32 ")", __FUNCTION__, break_id,
3338                     target_coord[0], target_coord[1], target_coord[2]);
3339 
3340     // Select current thread
3341     ExecutionContext context(ctx->exe_ctx_ref);
3342     Thread *thread_ptr = context.GetThreadPtr();
3343     assert(thread_ptr && "Null thread pointer");
3344 
3345     // Find current kernel invocation from .expand frame variables
3346     RSCoordinate current_coord{}; // Zero initialise array
3347     if (!GetKernelCoordinate(current_coord, thread_ptr))
3348     {
3349         if (log)
3350             log->Printf("%s - Error, couldn't select .expand stack frame", __FUNCTION__);
3351         return false;
3352     }
3353 
3354     if (log)
3355         log->Printf("%s - (%" PRIu32 ",%" PRIu32 ",%" PRIu32 ")", __FUNCTION__, current_coord[0], current_coord[1],
3356                     current_coord[2]);
3357 
3358     // Check if the current kernel invocation coordinate matches our target coordinate
3359     if (current_coord[0] == target_coord[0] &&
3360         current_coord[1] == target_coord[1] &&
3361         current_coord[2] == target_coord[2])
3362     {
3363         if (log)
3364             log->Printf("%s, BREAKING (%" PRIu32 ",%" PRIu32 ",%" PRIu32 ")", __FUNCTION__, current_coord[0],
3365                         current_coord[1], current_coord[2]);
3366 
3367         BreakpointSP breakpoint_sp = context.GetTargetPtr()->GetBreakpointByID(break_id);
3368         assert(breakpoint_sp != nullptr && "Error: Couldn't find breakpoint matching break id for callback");
3369         breakpoint_sp->SetEnabled(false); // Optimise since conditional breakpoint should only be hit once.
3370         return true;
3371     }
3372 
3373     // No match on coordinate
3374     return false;
3375 }
3376 
3377 // Tries to set a breakpoint on the start of a kernel, resolved using the kernel name.
3378 // Argument 'coords', represents a three dimensional coordinate which can be used to specify
3379 // a single kernel instance to break on. If this is set then we add a callback to the breakpoint.
3380 void
3381 RenderScriptRuntime::PlaceBreakpointOnKernel(Stream &strm, const char *name, const std::array<int, 3> coords,
3382                                              Error &error, TargetSP target)
3383 {
3384     if (!name)
3385     {
3386         error.SetErrorString("invalid kernel name");
3387         return;
3388     }
3389 
3390     InitSearchFilter(target);
3391 
3392     ConstString kernel_name(name);
3393     BreakpointSP bp = CreateKernelBreakpoint(kernel_name);
3394 
3395     // We have a conditional breakpoint on a specific coordinate
3396     if (coords[0] != -1)
3397     {
3398         strm.Printf("Conditional kernel breakpoint on coordinate %" PRId32 ", %" PRId32 ", %" PRId32,
3399                     coords[0], coords[1], coords[2]);
3400         strm.EOL();
3401 
3402         // Allocate memory for the baton, and copy over coordinate
3403         uint32_t *baton = new uint32_t[coords.size()];
3404         baton[0] = coords[0]; baton[1] = coords[1]; baton[2] = coords[2];
3405 
3406         // Create a callback that will be invoked everytime the breakpoint is hit.
3407         // The baton object passed to the handler is the target coordinate we want to break on.
3408         bp->SetCallback(KernelBreakpointHit, baton, true);
3409 
3410         // Store a shared pointer to the baton, so the memory will eventually be cleaned up after destruction
3411         m_conditional_breaks[bp->GetID()] = std::shared_ptr<uint32_t>(baton);
3412     }
3413 
3414     if (bp)
3415         bp->GetDescription(&strm, lldb::eDescriptionLevelInitial, false);
3416 }
3417 
3418 void
3419 RenderScriptRuntime::DumpModules(Stream &strm) const
3420 {
3421     strm.Printf("RenderScript Modules:");
3422     strm.EOL();
3423     strm.IndentMore();
3424     for (const auto &module : m_rsmodules)
3425     {
3426         module->Dump(strm);
3427     }
3428     strm.IndentLess();
3429 }
3430 
3431 RenderScriptRuntime::ScriptDetails *
3432 RenderScriptRuntime::LookUpScript(addr_t address, bool create)
3433 {
3434     for (const auto &s : m_scripts)
3435     {
3436         if (s->script.isValid())
3437             if (*s->script == address)
3438                 return s.get();
3439     }
3440     if (create)
3441     {
3442         std::unique_ptr<ScriptDetails> s(new ScriptDetails);
3443         s->script = address;
3444         m_scripts.push_back(std::move(s));
3445         return m_scripts.back().get();
3446     }
3447     return nullptr;
3448 }
3449 
3450 RenderScriptRuntime::AllocationDetails *
3451 RenderScriptRuntime::LookUpAllocation(addr_t address, bool create)
3452 {
3453     for (const auto &a : m_allocations)
3454     {
3455         if (a->address.isValid())
3456             if (*a->address == address)
3457                 return a.get();
3458     }
3459     if (create)
3460     {
3461         std::unique_ptr<AllocationDetails> a(new AllocationDetails);
3462         a->address = address;
3463         m_allocations.push_back(std::move(a));
3464         return m_allocations.back().get();
3465     }
3466     return nullptr;
3467 }
3468 
3469 void
3470 RSModuleDescriptor::Dump(Stream &strm) const
3471 {
3472     strm.Indent();
3473     m_module->GetFileSpec().Dump(&strm);
3474     if (m_module->GetNumCompileUnits())
3475     {
3476         strm.Indent("Debug info loaded.");
3477     }
3478     else
3479     {
3480         strm.Indent("Debug info does not exist.");
3481     }
3482     strm.EOL();
3483     strm.IndentMore();
3484     strm.Indent();
3485     strm.Printf("Globals: %" PRIu64, static_cast<uint64_t>(m_globals.size()));
3486     strm.EOL();
3487     strm.IndentMore();
3488     for (const auto &global : m_globals)
3489     {
3490         global.Dump(strm);
3491     }
3492     strm.IndentLess();
3493     strm.Indent();
3494     strm.Printf("Kernels: %" PRIu64, static_cast<uint64_t>(m_kernels.size()));
3495     strm.EOL();
3496     strm.IndentMore();
3497     for (const auto &kernel : m_kernels)
3498     {
3499         kernel.Dump(strm);
3500     }
3501     strm.Printf("Pragmas: %" PRIu64, static_cast<uint64_t>(m_pragmas.size()));
3502     strm.EOL();
3503     strm.IndentMore();
3504     for (const auto &key_val : m_pragmas)
3505     {
3506         strm.Printf("%s: %s", key_val.first.c_str(), key_val.second.c_str());
3507         strm.EOL();
3508     }
3509     strm.IndentLess(4);
3510 }
3511 
3512 void
3513 RSGlobalDescriptor::Dump(Stream &strm) const
3514 {
3515     strm.Indent(m_name.AsCString());
3516     VariableList var_list;
3517     m_module->m_module->FindGlobalVariables(m_name, nullptr, true, 1U, var_list);
3518     if (var_list.GetSize() == 1)
3519     {
3520         auto var = var_list.GetVariableAtIndex(0);
3521         auto type = var->GetType();
3522         if (type)
3523         {
3524             strm.Printf(" - ");
3525             type->DumpTypeName(&strm);
3526         }
3527         else
3528         {
3529             strm.Printf(" - Unknown Type");
3530         }
3531     }
3532     else
3533     {
3534         strm.Printf(" - variable identified, but not found in binary");
3535         const Symbol *s = m_module->m_module->FindFirstSymbolWithNameAndType(m_name, eSymbolTypeData);
3536         if (s)
3537         {
3538             strm.Printf(" (symbol exists) ");
3539         }
3540     }
3541 
3542     strm.EOL();
3543 }
3544 
3545 void
3546 RSKernelDescriptor::Dump(Stream &strm) const
3547 {
3548     strm.Indent(m_name.AsCString());
3549     strm.EOL();
3550 }
3551 
3552 class CommandObjectRenderScriptRuntimeModuleDump : public CommandObjectParsed
3553 {
3554 public:
3555     CommandObjectRenderScriptRuntimeModuleDump(CommandInterpreter &interpreter)
3556         : CommandObjectParsed(interpreter, "renderscript module dump",
3557                               "Dumps renderscript specific information for all modules.", "renderscript module dump",
3558                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
3559     {
3560     }
3561 
3562     ~CommandObjectRenderScriptRuntimeModuleDump() override = default;
3563 
3564     bool
3565     DoExecute(Args &command, CommandReturnObject &result) override
3566     {
3567         RenderScriptRuntime *runtime =
3568             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
3569         runtime->DumpModules(result.GetOutputStream());
3570         result.SetStatus(eReturnStatusSuccessFinishResult);
3571         return true;
3572     }
3573 };
3574 
3575 class CommandObjectRenderScriptRuntimeModule : public CommandObjectMultiword
3576 {
3577 public:
3578     CommandObjectRenderScriptRuntimeModule(CommandInterpreter &interpreter)
3579         : CommandObjectMultiword(interpreter, "renderscript module", "Commands that deal with renderscript modules.",
3580                                  nullptr)
3581     {
3582         LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleDump(interpreter)));
3583     }
3584 
3585     ~CommandObjectRenderScriptRuntimeModule() override = default;
3586 };
3587 
3588 class CommandObjectRenderScriptRuntimeKernelList : public CommandObjectParsed
3589 {
3590 public:
3591     CommandObjectRenderScriptRuntimeKernelList(CommandInterpreter &interpreter)
3592         : CommandObjectParsed(interpreter, "renderscript kernel list",
3593                               "Lists renderscript kernel names and associated script resources.",
3594                               "renderscript kernel list", eCommandRequiresProcess | eCommandProcessMustBeLaunched)
3595     {
3596     }
3597 
3598     ~CommandObjectRenderScriptRuntimeKernelList() override = default;
3599 
3600     bool
3601     DoExecute(Args &command, CommandReturnObject &result) override
3602     {
3603         RenderScriptRuntime *runtime =
3604             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
3605         runtime->DumpKernels(result.GetOutputStream());
3606         result.SetStatus(eReturnStatusSuccessFinishResult);
3607         return true;
3608     }
3609 };
3610 
3611 class CommandObjectRenderScriptRuntimeKernelBreakpointSet : public CommandObjectParsed
3612 {
3613 public:
3614     CommandObjectRenderScriptRuntimeKernelBreakpointSet(CommandInterpreter &interpreter)
3615         : CommandObjectParsed(interpreter, "renderscript kernel breakpoint set",
3616                               "Sets a breakpoint on a renderscript kernel.",
3617                               "renderscript kernel breakpoint set <kernel_name> [-c x,y,z]",
3618                               eCommandRequiresProcess | eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
3619           m_options(interpreter)
3620     {
3621     }
3622 
3623     ~CommandObjectRenderScriptRuntimeKernelBreakpointSet() override = default;
3624 
3625     Options *
3626     GetOptions() override
3627     {
3628         return &m_options;
3629     }
3630 
3631     class CommandOptions : public Options
3632     {
3633     public:
3634         CommandOptions(CommandInterpreter &interpreter) : Options(interpreter) {}
3635 
3636         ~CommandOptions() override = default;
3637 
3638         Error
3639         SetOptionValue(uint32_t option_idx, const char *option_arg) override
3640         {
3641             Error error;
3642             const int short_option = m_getopt_table[option_idx].val;
3643 
3644             switch (short_option)
3645             {
3646                 case 'c':
3647                     if (!ParseCoordinate(option_arg))
3648                         error.SetErrorStringWithFormat("Couldn't parse coordinate '%s', should be in format 'x,y,z'.",
3649                                                        option_arg);
3650                     break;
3651                 default:
3652                     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
3653                     break;
3654             }
3655             return error;
3656         }
3657 
3658         // -c takes an argument of the form 'num[,num][,num]'.
3659         // Where 'id_cstr' is this argument with the whitespace trimmed.
3660         // Missing coordinates are defaulted to zero.
3661         bool
3662         ParseCoordinate(const char *id_cstr)
3663         {
3664             RegularExpression regex;
3665             RegularExpression::Match regex_match(3);
3666 
3667             bool matched = false;
3668             if (regex.Compile("^([0-9]+),([0-9]+),([0-9]+)$") && regex.Execute(id_cstr, &regex_match))
3669                 matched = true;
3670             else if (regex.Compile("^([0-9]+),([0-9]+)$") && regex.Execute(id_cstr, &regex_match))
3671                 matched = true;
3672             else if (regex.Compile("^([0-9]+)$") && regex.Execute(id_cstr, &regex_match))
3673                 matched = true;
3674             for (uint32_t i = 0; i < 3; i++)
3675             {
3676                 std::string group;
3677                 if (regex_match.GetMatchAtIndex(id_cstr, i + 1, group))
3678                     m_coord[i] = (uint32_t)strtoul(group.c_str(), nullptr, 0);
3679                 else
3680                     m_coord[i] = 0;
3681             }
3682             return matched;
3683         }
3684 
3685         void
3686         OptionParsingStarting() override
3687         {
3688             // -1 means the -c option hasn't been set
3689             m_coord[0] = -1;
3690             m_coord[1] = -1;
3691             m_coord[2] = -1;
3692         }
3693 
3694         const OptionDefinition *
3695         GetDefinitions() override
3696         {
3697             return g_option_table;
3698         }
3699 
3700         static OptionDefinition g_option_table[];
3701         std::array<int, 3> m_coord;
3702     };
3703 
3704     bool
3705     DoExecute(Args &command, CommandReturnObject &result) override
3706     {
3707         const size_t argc = command.GetArgumentCount();
3708         if (argc < 1)
3709         {
3710             result.AppendErrorWithFormat("'%s' takes 1 argument of kernel name, and an optional coordinate.",
3711                                          m_cmd_name.c_str());
3712             result.SetStatus(eReturnStatusFailed);
3713             return false;
3714         }
3715 
3716         RenderScriptRuntime *runtime =
3717             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
3718 
3719         Error error;
3720         runtime->PlaceBreakpointOnKernel(result.GetOutputStream(), command.GetArgumentAtIndex(0), m_options.m_coord,
3721                                          error, m_exe_ctx.GetTargetSP());
3722 
3723         if (error.Success())
3724         {
3725             result.AppendMessage("Breakpoint(s) created");
3726             result.SetStatus(eReturnStatusSuccessFinishResult);
3727             return true;
3728         }
3729         result.SetStatus(eReturnStatusFailed);
3730         result.AppendErrorWithFormat("Error: %s", error.AsCString());
3731         return false;
3732     }
3733 
3734 private:
3735     CommandOptions m_options;
3736 };
3737 
3738 OptionDefinition CommandObjectRenderScriptRuntimeKernelBreakpointSet::CommandOptions::g_option_table[] = {
3739     {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeValue,
3740      "Set a breakpoint on a single invocation of the kernel with specified coordinate.\n"
3741      "Coordinate takes the form 'x[,y][,z] where x,y,z are positive integers representing kernel dimensions. "
3742      "Any unset dimensions will be defaulted to zero."},
3743     {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr}};
3744 
3745 class CommandObjectRenderScriptRuntimeKernelBreakpointAll : public CommandObjectParsed
3746 {
3747 public:
3748     CommandObjectRenderScriptRuntimeKernelBreakpointAll(CommandInterpreter &interpreter)
3749         : CommandObjectParsed(
3750               interpreter, "renderscript kernel breakpoint all",
3751               "Automatically sets a breakpoint on all renderscript kernels that are or will be loaded.\n"
3752               "Disabling option means breakpoints will no longer be set on any kernels loaded in the future, "
3753               "but does not remove currently set breakpoints.",
3754               "renderscript kernel breakpoint all <enable/disable>",
3755               eCommandRequiresProcess | eCommandProcessMustBeLaunched | eCommandProcessMustBePaused)
3756     {
3757     }
3758 
3759     ~CommandObjectRenderScriptRuntimeKernelBreakpointAll() override = default;
3760 
3761     bool
3762     DoExecute(Args &command, CommandReturnObject &result) override
3763     {
3764         const size_t argc = command.GetArgumentCount();
3765         if (argc != 1)
3766         {
3767             result.AppendErrorWithFormat("'%s' takes 1 argument of 'enable' or 'disable'", m_cmd_name.c_str());
3768             result.SetStatus(eReturnStatusFailed);
3769             return false;
3770         }
3771 
3772         RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
3773             m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
3774 
3775         bool do_break = false;
3776         const char *argument = command.GetArgumentAtIndex(0);
3777         if (strcmp(argument, "enable") == 0)
3778         {
3779             do_break = true;
3780             result.AppendMessage("Breakpoints will be set on all kernels.");
3781         }
3782         else if (strcmp(argument, "disable") == 0)
3783         {
3784             do_break = false;
3785             result.AppendMessage("Breakpoints will not be set on any new kernels.");
3786         }
3787         else
3788         {
3789             result.AppendErrorWithFormat("Argument must be either 'enable' or 'disable'");
3790             result.SetStatus(eReturnStatusFailed);
3791             return false;
3792         }
3793 
3794         runtime->SetBreakAllKernels(do_break, m_exe_ctx.GetTargetSP());
3795 
3796         result.SetStatus(eReturnStatusSuccessFinishResult);
3797         return true;
3798     }
3799 };
3800 
3801 class CommandObjectRenderScriptRuntimeKernelCoordinate : public CommandObjectParsed
3802 {
3803 public:
3804     CommandObjectRenderScriptRuntimeKernelCoordinate(CommandInterpreter &interpreter)
3805         : CommandObjectParsed(interpreter, "renderscript kernel coordinate",
3806                               "Shows the (x,y,z) coordinate of the current kernel invocation.",
3807                               "renderscript kernel coordinate",
3808                               eCommandRequiresProcess | eCommandProcessMustBeLaunched | eCommandProcessMustBePaused)
3809     {
3810     }
3811 
3812     ~CommandObjectRenderScriptRuntimeKernelCoordinate() override = default;
3813 
3814     bool
3815     DoExecute(Args &command, CommandReturnObject &result) override
3816     {
3817         RSCoordinate coord{}; // Zero initialize array
3818         bool success = RenderScriptRuntime::GetKernelCoordinate(coord, m_exe_ctx.GetThreadPtr());
3819         Stream &stream = result.GetOutputStream();
3820 
3821         if (success)
3822         {
3823             stream.Printf("Coordinate: (%" PRIu32 ", %" PRIu32 ", %" PRIu32 ")", coord[0], coord[1], coord[2]);
3824             stream.EOL();
3825             result.SetStatus(eReturnStatusSuccessFinishResult);
3826         }
3827         else
3828         {
3829             stream.Printf("Error: Coordinate could not be found.");
3830             stream.EOL();
3831             result.SetStatus(eReturnStatusFailed);
3832         }
3833         return true;
3834     }
3835 };
3836 
3837 class CommandObjectRenderScriptRuntimeKernelBreakpoint : public CommandObjectMultiword
3838 {
3839 public:
3840     CommandObjectRenderScriptRuntimeKernelBreakpoint(CommandInterpreter &interpreter)
3841         : CommandObjectMultiword(interpreter, "renderscript kernel",
3842                                  "Commands that generate breakpoints on renderscript kernels.", nullptr)
3843     {
3844         LoadSubCommand("set", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointSet(interpreter)));
3845         LoadSubCommand("all", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointAll(interpreter)));
3846     }
3847 
3848     ~CommandObjectRenderScriptRuntimeKernelBreakpoint() override = default;
3849 };
3850 
3851 class CommandObjectRenderScriptRuntimeKernel : public CommandObjectMultiword
3852 {
3853 public:
3854     CommandObjectRenderScriptRuntimeKernel(CommandInterpreter &interpreter)
3855         : CommandObjectMultiword(interpreter, "renderscript kernel", "Commands that deal with renderscript kernels.",
3856                                  nullptr)
3857     {
3858         LoadSubCommand("list", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelList(interpreter)));
3859         LoadSubCommand("coordinate",
3860                        CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelCoordinate(interpreter)));
3861         LoadSubCommand("breakpoint",
3862                        CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpoint(interpreter)));
3863     }
3864 
3865     ~CommandObjectRenderScriptRuntimeKernel() override = default;
3866 };
3867 
3868 class CommandObjectRenderScriptRuntimeContextDump : public CommandObjectParsed
3869 {
3870 public:
3871     CommandObjectRenderScriptRuntimeContextDump(CommandInterpreter &interpreter)
3872         : CommandObjectParsed(interpreter, "renderscript context dump", "Dumps renderscript context information.",
3873                               "renderscript context dump", eCommandRequiresProcess | eCommandProcessMustBeLaunched)
3874     {
3875     }
3876 
3877     ~CommandObjectRenderScriptRuntimeContextDump() override = default;
3878 
3879     bool
3880     DoExecute(Args &command, CommandReturnObject &result) override
3881     {
3882         RenderScriptRuntime *runtime =
3883             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
3884         runtime->DumpContexts(result.GetOutputStream());
3885         result.SetStatus(eReturnStatusSuccessFinishResult);
3886         return true;
3887     }
3888 };
3889 
3890 class CommandObjectRenderScriptRuntimeContext : public CommandObjectMultiword
3891 {
3892 public:
3893     CommandObjectRenderScriptRuntimeContext(CommandInterpreter &interpreter)
3894         : CommandObjectMultiword(interpreter, "renderscript context", "Commands that deal with renderscript contexts.",
3895                                  nullptr)
3896     {
3897         LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeContextDump(interpreter)));
3898     }
3899 
3900     ~CommandObjectRenderScriptRuntimeContext() override = default;
3901 };
3902 
3903 class CommandObjectRenderScriptRuntimeAllocationDump : public CommandObjectParsed
3904 {
3905 public:
3906     CommandObjectRenderScriptRuntimeAllocationDump(CommandInterpreter &interpreter)
3907         : CommandObjectParsed(interpreter, "renderscript allocation dump",
3908                               "Displays the contents of a particular allocation", "renderscript allocation dump <ID>",
3909                               eCommandRequiresProcess | eCommandProcessMustBeLaunched),
3910           m_options(interpreter)
3911     {
3912     }
3913 
3914     ~CommandObjectRenderScriptRuntimeAllocationDump() override = default;
3915 
3916     Options *
3917     GetOptions() override
3918     {
3919         return &m_options;
3920     }
3921 
3922     class CommandOptions : public Options
3923     {
3924     public:
3925         CommandOptions(CommandInterpreter &interpreter) : Options(interpreter) {}
3926 
3927         ~CommandOptions() override = default;
3928 
3929         Error
3930         SetOptionValue(uint32_t option_idx, const char *option_arg) override
3931         {
3932             Error error;
3933             const int short_option = m_getopt_table[option_idx].val;
3934 
3935             switch (short_option)
3936             {
3937                 case 'f':
3938                     m_outfile.SetFile(option_arg, true);
3939                     if (m_outfile.Exists())
3940                     {
3941                         m_outfile.Clear();
3942                         error.SetErrorStringWithFormat("file already exists: '%s'", option_arg);
3943                     }
3944                     break;
3945                 default:
3946                     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
3947                     break;
3948             }
3949             return error;
3950         }
3951 
3952         void
3953         OptionParsingStarting() override
3954         {
3955             m_outfile.Clear();
3956         }
3957 
3958         const OptionDefinition *
3959         GetDefinitions() override
3960         {
3961             return g_option_table;
3962         }
3963 
3964         static OptionDefinition g_option_table[];
3965         FileSpec m_outfile;
3966     };
3967 
3968     bool
3969     DoExecute(Args &command, CommandReturnObject &result) override
3970     {
3971         const size_t argc = command.GetArgumentCount();
3972         if (argc < 1)
3973         {
3974             result.AppendErrorWithFormat("'%s' takes 1 argument, an allocation ID. As well as an optional -f argument",
3975                                          m_cmd_name.c_str());
3976             result.SetStatus(eReturnStatusFailed);
3977             return false;
3978         }
3979 
3980         RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
3981             m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
3982 
3983         const char *id_cstr = command.GetArgumentAtIndex(0);
3984         bool convert_complete = false;
3985         const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
3986         if (!convert_complete)
3987         {
3988             result.AppendErrorWithFormat("invalid allocation id argument '%s'", id_cstr);
3989             result.SetStatus(eReturnStatusFailed);
3990             return false;
3991         }
3992 
3993         Stream *output_strm = nullptr;
3994         StreamFile outfile_stream;
3995         const FileSpec &outfile_spec = m_options.m_outfile; // Dump allocation to file instead
3996         if (outfile_spec)
3997         {
3998             // Open output file
3999             char path[256];
4000             outfile_spec.GetPath(path, sizeof(path));
4001             if (outfile_stream.GetFile().Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate).Success())
4002             {
4003                 output_strm = &outfile_stream;
4004                 result.GetOutputStream().Printf("Results written to '%s'", path);
4005                 result.GetOutputStream().EOL();
4006             }
4007             else
4008             {
4009                 result.AppendErrorWithFormat("Couldn't open file '%s'", path);
4010                 result.SetStatus(eReturnStatusFailed);
4011                 return false;
4012             }
4013         }
4014         else
4015             output_strm = &result.GetOutputStream();
4016 
4017         assert(output_strm != nullptr);
4018         bool success = runtime->DumpAllocation(*output_strm, m_exe_ctx.GetFramePtr(), id);
4019 
4020         if (success)
4021             result.SetStatus(eReturnStatusSuccessFinishResult);
4022         else
4023             result.SetStatus(eReturnStatusFailed);
4024 
4025         return true;
4026     }
4027 
4028 private:
4029     CommandOptions m_options;
4030 };
4031 
4032 OptionDefinition CommandObjectRenderScriptRuntimeAllocationDump::CommandOptions::g_option_table[] = {
4033     {LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeFilename,
4034      "Print results to specified file instead of command line."},
4035     {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr}};
4036 
4037 class CommandObjectRenderScriptRuntimeAllocationList : public CommandObjectParsed
4038 {
4039 public:
4040     CommandObjectRenderScriptRuntimeAllocationList(CommandInterpreter &interpreter)
4041         : CommandObjectParsed(interpreter, "renderscript allocation list",
4042                               "List renderscript allocations and their information.", "renderscript allocation list",
4043                               eCommandRequiresProcess | eCommandProcessMustBeLaunched),
4044           m_options(interpreter)
4045     {
4046     }
4047 
4048     ~CommandObjectRenderScriptRuntimeAllocationList() override = default;
4049 
4050     Options *
4051     GetOptions() override
4052     {
4053         return &m_options;
4054     }
4055 
4056     class CommandOptions : public Options
4057     {
4058     public:
4059         CommandOptions(CommandInterpreter &interpreter) : Options(interpreter), m_id(0) {}
4060 
4061         ~CommandOptions() override = default;
4062 
4063         Error
4064         SetOptionValue(uint32_t option_idx, const char *option_arg) override
4065         {
4066             Error error;
4067             const int short_option = m_getopt_table[option_idx].val;
4068 
4069             switch (short_option)
4070             {
4071                 case 'i':
4072                     bool success;
4073                     m_id = StringConvert::ToUInt32(option_arg, 0, 0, &success);
4074                     if (!success)
4075                         error.SetErrorStringWithFormat("invalid integer value for option '%c'", short_option);
4076                     break;
4077                 default:
4078                     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4079                     break;
4080             }
4081             return error;
4082         }
4083 
4084         void
4085         OptionParsingStarting() override
4086         {
4087             m_id = 0;
4088         }
4089 
4090         const OptionDefinition *
4091         GetDefinitions() override
4092         {
4093             return g_option_table;
4094         }
4095 
4096         static OptionDefinition g_option_table[];
4097         uint32_t m_id;
4098     };
4099 
4100     bool
4101     DoExecute(Args &command, CommandReturnObject &result) override
4102     {
4103         RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4104             m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
4105         runtime->ListAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr(), m_options.m_id);
4106         result.SetStatus(eReturnStatusSuccessFinishResult);
4107         return true;
4108     }
4109 
4110 private:
4111     CommandOptions m_options;
4112 };
4113 
4114 OptionDefinition CommandObjectRenderScriptRuntimeAllocationList::CommandOptions::g_option_table[] = {
4115     {LLDB_OPT_SET_1, false, "id", 'i', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeIndex,
4116      "Only show details of a single allocation with specified id."},
4117     {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr}};
4118 
4119 class CommandObjectRenderScriptRuntimeAllocationLoad : public CommandObjectParsed
4120 {
4121 public:
4122     CommandObjectRenderScriptRuntimeAllocationLoad(CommandInterpreter &interpreter)
4123         : CommandObjectParsed(
4124               interpreter, "renderscript allocation load", "Loads renderscript allocation contents from a file.",
4125               "renderscript allocation load <ID> <filename>", eCommandRequiresProcess | eCommandProcessMustBeLaunched)
4126     {
4127     }
4128 
4129     ~CommandObjectRenderScriptRuntimeAllocationLoad() override = default;
4130 
4131     bool
4132     DoExecute(Args &command, CommandReturnObject &result) override
4133     {
4134         const size_t argc = command.GetArgumentCount();
4135         if (argc != 2)
4136         {
4137             result.AppendErrorWithFormat("'%s' takes 2 arguments, an allocation ID and filename to read from.",
4138                                          m_cmd_name.c_str());
4139             result.SetStatus(eReturnStatusFailed);
4140             return false;
4141         }
4142 
4143         RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4144             m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
4145 
4146         const char *id_cstr = command.GetArgumentAtIndex(0);
4147         bool convert_complete = false;
4148         const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
4149         if (!convert_complete)
4150         {
4151             result.AppendErrorWithFormat("invalid allocation id argument '%s'", id_cstr);
4152             result.SetStatus(eReturnStatusFailed);
4153             return false;
4154         }
4155 
4156         const char *filename = command.GetArgumentAtIndex(1);
4157         bool success = runtime->LoadAllocation(result.GetOutputStream(), id, filename, m_exe_ctx.GetFramePtr());
4158 
4159         if (success)
4160             result.SetStatus(eReturnStatusSuccessFinishResult);
4161         else
4162             result.SetStatus(eReturnStatusFailed);
4163 
4164         return true;
4165     }
4166 };
4167 
4168 class CommandObjectRenderScriptRuntimeAllocationSave : public CommandObjectParsed
4169 {
4170 public:
4171     CommandObjectRenderScriptRuntimeAllocationSave(CommandInterpreter &interpreter)
4172         : CommandObjectParsed(
4173               interpreter, "renderscript allocation save", "Write renderscript allocation contents to a file.",
4174               "renderscript allocation save <ID> <filename>", eCommandRequiresProcess | eCommandProcessMustBeLaunched)
4175     {
4176     }
4177 
4178     ~CommandObjectRenderScriptRuntimeAllocationSave() override = default;
4179 
4180     bool
4181     DoExecute(Args &command, CommandReturnObject &result) override
4182     {
4183         const size_t argc = command.GetArgumentCount();
4184         if (argc != 2)
4185         {
4186             result.AppendErrorWithFormat("'%s' takes 2 arguments, an allocation ID and filename to read from.",
4187                                          m_cmd_name.c_str());
4188             result.SetStatus(eReturnStatusFailed);
4189             return false;
4190         }
4191 
4192         RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4193             m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
4194 
4195         const char *id_cstr = command.GetArgumentAtIndex(0);
4196         bool convert_complete = false;
4197         const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
4198         if (!convert_complete)
4199         {
4200             result.AppendErrorWithFormat("invalid allocation id argument '%s'", id_cstr);
4201             result.SetStatus(eReturnStatusFailed);
4202             return false;
4203         }
4204 
4205         const char *filename = command.GetArgumentAtIndex(1);
4206         bool success = runtime->SaveAllocation(result.GetOutputStream(), id, filename, m_exe_ctx.GetFramePtr());
4207 
4208         if (success)
4209             result.SetStatus(eReturnStatusSuccessFinishResult);
4210         else
4211             result.SetStatus(eReturnStatusFailed);
4212 
4213         return true;
4214     }
4215 };
4216 
4217 class CommandObjectRenderScriptRuntimeAllocationRefresh : public CommandObjectParsed
4218 {
4219 public:
4220     CommandObjectRenderScriptRuntimeAllocationRefresh(CommandInterpreter &interpreter)
4221         : CommandObjectParsed(interpreter, "renderscript allocation refresh",
4222                               "Recomputes the details of all allocations.", "renderscript allocation refresh",
4223                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
4224     {
4225     }
4226 
4227     ~CommandObjectRenderScriptRuntimeAllocationRefresh() override = default;
4228 
4229     bool
4230     DoExecute(Args &command, CommandReturnObject &result) override
4231     {
4232         RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4233             m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
4234 
4235         bool success = runtime->RecomputeAllAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr());
4236 
4237         if (success)
4238         {
4239             result.SetStatus(eReturnStatusSuccessFinishResult);
4240             return true;
4241         }
4242         else
4243         {
4244             result.SetStatus(eReturnStatusFailed);
4245             return false;
4246         }
4247     }
4248 };
4249 
4250 class CommandObjectRenderScriptRuntimeAllocation : public CommandObjectMultiword
4251 {
4252 public:
4253     CommandObjectRenderScriptRuntimeAllocation(CommandInterpreter &interpreter)
4254         : CommandObjectMultiword(interpreter, "renderscript allocation",
4255                                  "Commands that deal with renderscript allocations.", nullptr)
4256     {
4257         LoadSubCommand("list", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationList(interpreter)));
4258         LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationDump(interpreter)));
4259         LoadSubCommand("save", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationSave(interpreter)));
4260         LoadSubCommand("load", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationLoad(interpreter)));
4261         LoadSubCommand("refresh", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationRefresh(interpreter)));
4262     }
4263 
4264     ~CommandObjectRenderScriptRuntimeAllocation() override = default;
4265 };
4266 
4267 class CommandObjectRenderScriptRuntimeStatus : public CommandObjectParsed
4268 {
4269 public:
4270     CommandObjectRenderScriptRuntimeStatus(CommandInterpreter &interpreter)
4271         : CommandObjectParsed(interpreter, "renderscript status", "Displays current renderscript runtime status.",
4272                               "renderscript status", eCommandRequiresProcess | eCommandProcessMustBeLaunched)
4273     {
4274     }
4275 
4276     ~CommandObjectRenderScriptRuntimeStatus() override = default;
4277 
4278     bool
4279     DoExecute(Args &command, CommandReturnObject &result) override
4280     {
4281         RenderScriptRuntime *runtime =
4282             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
4283         runtime->Status(result.GetOutputStream());
4284         result.SetStatus(eReturnStatusSuccessFinishResult);
4285         return true;
4286     }
4287 };
4288 
4289 class CommandObjectRenderScriptRuntime : public CommandObjectMultiword
4290 {
4291 public:
4292     CommandObjectRenderScriptRuntime(CommandInterpreter &interpreter)
4293         : CommandObjectMultiword(interpreter, "renderscript", "A set of commands for operating on renderscript.",
4294                                  "renderscript <subcommand> [<subcommand-options>]")
4295     {
4296         LoadSubCommand("module", CommandObjectSP(new CommandObjectRenderScriptRuntimeModule(interpreter)));
4297         LoadSubCommand("status", CommandObjectSP(new CommandObjectRenderScriptRuntimeStatus(interpreter)));
4298         LoadSubCommand("kernel", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernel(interpreter)));
4299         LoadSubCommand("context", CommandObjectSP(new CommandObjectRenderScriptRuntimeContext(interpreter)));
4300         LoadSubCommand("allocation", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocation(interpreter)));
4301     }
4302 
4303     ~CommandObjectRenderScriptRuntime() override = default;
4304 };
4305 
4306 void
4307 RenderScriptRuntime::Initiate()
4308 {
4309     assert(!m_initiated);
4310 }
4311 
4312 RenderScriptRuntime::RenderScriptRuntime(Process *process)
4313     : lldb_private::CPPLanguageRuntime(process),
4314       m_initiated(false),
4315       m_debuggerPresentFlagged(false),
4316       m_breakAllKernels(false)
4317 {
4318     ModulesDidLoad(process->GetTarget().GetImages());
4319 }
4320 
4321 lldb::CommandObjectSP
4322 RenderScriptRuntime::GetCommandObject(lldb_private::CommandInterpreter &interpreter)
4323 {
4324     return CommandObjectSP(new CommandObjectRenderScriptRuntime(interpreter));
4325 }
4326 
4327 RenderScriptRuntime::~RenderScriptRuntime() = default;
4328