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