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