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