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