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