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