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