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