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