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