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