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