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