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