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