1 //===-- RenderScriptRuntime.cpp ---------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
12 // Other libraries and framework includes
13 #include "llvm/ADT/StringSwitch.h"
16 #include "RenderScriptRuntime.h"
17 #include "RenderScriptScriptGroup.h"
19 #include "lldb/Breakpoint/StoppointCallbackContext.h"
20 #include "lldb/Core/Debugger.h"
21 #include "lldb/Core/DumpDataExtractor.h"
22 #include "lldb/Core/PluginManager.h"
23 #include "lldb/Core/RegisterValue.h"
24 #include "lldb/Core/ValueObjectVariable.h"
25 #include "lldb/DataFormatters/DumpValueObjectOptions.h"
26 #include "lldb/Expression/UserExpression.h"
27 #include "lldb/Host/OptionParser.h"
28 #include "lldb/Host/StringConvert.h"
29 #include "lldb/Interpreter/Args.h"
30 #include "lldb/Interpreter/CommandInterpreter.h"
31 #include "lldb/Interpreter/CommandObjectMultiword.h"
32 #include "lldb/Interpreter/CommandReturnObject.h"
33 #include "lldb/Interpreter/Options.h"
34 #include "lldb/Symbol/Function.h"
35 #include "lldb/Symbol/Symbol.h"
36 #include "lldb/Symbol/Type.h"
37 #include "lldb/Symbol/VariableList.h"
38 #include "lldb/Target/Process.h"
39 #include "lldb/Target/RegisterContext.h"
40 #include "lldb/Target/SectionLoadList.h"
41 #include "lldb/Target/Target.h"
42 #include "lldb/Target/Thread.h"
43 #include "lldb/Utility/ConstString.h"
44 #include "lldb/Utility/DataBufferLLVM.h"
45 #include "lldb/Utility/Error.h"
46 #include "lldb/Utility/Log.h"
47 #include "lldb/Utility/RegularExpression.h"
50 using namespace lldb_private;
51 using namespace lldb_renderscript;
53 #define FMT_COORD "(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ")"
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
61 template <typename type_t> class empirical_type {
63 // Ctor. Contents is invalid when constructed.
64 empirical_type() : valid(false) {}
66 // Return true and copy contents to out if valid, else return false.
67 bool get(type_t &out) const {
73 // Return a pointer to the contents or nullptr if it was not valid.
74 const type_t *get() const { return valid ? &data : nullptr; }
76 // Assign data explicitly.
77 void set(const type_t in) {
82 // Mark contents as invalid.
83 void invalidate() { valid = false; }
85 // Returns true if this type contains valid data.
86 bool isValid() const { return valid; }
88 // Assignment operator.
89 empirical_type<type_t> &operator=(const type_t in) {
94 // Dereference operator returns contents.
95 // Warning: Will assert if not valid so use only when you know data is valid.
96 const type_t &operator*() const {
106 // ArgItem is used by the GetArgs() function when reading function arguments
109 enum { ePointer, eInt32, eInt64, eLong, eBool } type;
113 explicit operator uint64_t() const { return value; }
116 // Context structure to be passed into GetArgsXXX(), argument reading functions
119 RegisterContext *reg_ctx;
123 bool GetArgsX86(const GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
124 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
128 // get the current stack pointer
129 uint64_t sp = ctx.reg_ctx->GetSP();
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
141 ctx.process->ReadMemory(sp, &arg.value, sizeof(uint32_t), err);
142 if (read != arg_size || !err.Success()) {
144 log->Printf("%s - error reading argument: %" PRIu64 " '%s'",
145 __FUNCTION__, uint64_t(i), err.AsCString());
152 bool GetArgsX86_64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
153 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
155 // number of arguments passed in registers
156 static const uint32_t args_in_reg = 6;
157 // register passing order
158 static const std::array<const char *, args_in_reg> reg_names{
159 {"rdi", "rsi", "rdx", "rcx", "r8", "r9"}};
160 // argument type to size mapping
161 static const std::array<size_t, 5> arg_size{{
171 // get the current stack pointer
172 uint64_t sp = ctx.reg_ctx->GetSP();
173 // step over the return address
174 sp += sizeof(uint64_t);
176 // check the stack alignment was correct (16 byte aligned)
177 if ((sp & 0xf) != 0x0) {
179 log->Printf("%s - stack misaligned", __FUNCTION__);
183 // find the start of arguments on the stack
184 uint64_t sp_offset = 0;
185 for (uint32_t i = args_in_reg; i < num_args; ++i) {
186 sp_offset += arg_size[arg_list[i].type];
188 // round up to multiple of 16
189 sp_offset = (sp_offset + 0xf) & 0xf;
192 for (size_t i = 0; i < num_args; ++i) {
193 bool success = false;
194 ArgItem &arg = arg_list[i];
195 // arguments passed in registers
196 if (i < args_in_reg) {
197 const RegisterInfo *reg =
198 ctx.reg_ctx->GetRegisterInfoByName(reg_names[i]);
199 RegisterValue reg_val;
200 if (ctx.reg_ctx->ReadRegister(reg, reg_val))
201 arg.value = reg_val.GetAsUInt64(0, &success);
203 // arguments passed on the stack
205 // get the argument type size
206 const size_t size = arg_size[arg_list[i].type];
207 // read the argument from memory
209 // note: due to little endian layout reading 4 or 8 bytes will give the
211 size_t read = ctx.process->ReadMemory(sp, &arg.value, size, err);
212 success = (err.Success() && read == size);
213 // advance past this argument
216 // fail if we couldn't read this argument
219 log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
220 __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
227 bool GetArgsArm(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
228 // number of arguments passed in registers
229 static const uint32_t args_in_reg = 4;
231 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
235 // get the current stack pointer
236 uint64_t sp = ctx.reg_ctx->GetSP();
238 for (size_t i = 0; i < num_args; ++i) {
239 bool success = false;
240 ArgItem &arg = arg_list[i];
241 // arguments passed in registers
242 if (i < args_in_reg) {
243 const RegisterInfo *reg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
244 RegisterValue reg_val;
245 if (ctx.reg_ctx->ReadRegister(reg, reg_val))
246 arg.value = reg_val.GetAsUInt32(0, &success);
248 // arguments passed on the stack
250 // get the argument type size
251 const size_t arg_size = sizeof(uint32_t);
254 // read this argument from memory
256 ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
257 success = (err.Success() && bytes_read == arg_size);
258 // advance the stack pointer
259 sp += sizeof(uint32_t);
261 // fail if we couldn't read this argument
264 log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
265 __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
272 bool GetArgsAarch64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
273 // number of arguments passed in registers
274 static const uint32_t args_in_reg = 8;
276 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
278 for (size_t i = 0; i < num_args; ++i) {
279 bool success = false;
280 ArgItem &arg = arg_list[i];
281 // arguments passed in registers
282 if (i < args_in_reg) {
283 const RegisterInfo *reg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
284 RegisterValue reg_val;
285 if (ctx.reg_ctx->ReadRegister(reg, reg_val))
286 arg.value = reg_val.GetAsUInt64(0, &success);
288 // arguments passed on the stack
291 log->Printf("%s - reading arguments spilled to stack not implemented",
294 // fail if we couldn't read this argument
297 log->Printf("%s - error reading argument: %" PRIu64, __FUNCTION__,
305 bool GetArgsMipsel(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
306 // number of arguments passed in registers
307 static const uint32_t args_in_reg = 4;
308 // register file offset to first argument
309 static const uint32_t reg_offset = 4;
311 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
315 // find offset to arguments on the stack (+16 to skip over a0-a3 shadow space)
316 uint64_t sp = ctx.reg_ctx->GetSP() + 16;
318 for (size_t i = 0; i < num_args; ++i) {
319 bool success = false;
320 ArgItem &arg = arg_list[i];
321 // arguments passed in registers
322 if (i < args_in_reg) {
323 const RegisterInfo *reg =
324 ctx.reg_ctx->GetRegisterInfoAtIndex(i + reg_offset);
325 RegisterValue reg_val;
326 if (ctx.reg_ctx->ReadRegister(reg, reg_val))
327 arg.value = reg_val.GetAsUInt64(0, &success);
329 // arguments passed on the stack
331 const size_t arg_size = sizeof(uint32_t);
334 ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
335 success = (err.Success() && bytes_read == arg_size);
336 // advance the stack pointer
339 // fail if we couldn't read this argument
342 log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
343 __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
350 bool GetArgsMips64el(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
351 // number of arguments passed in registers
352 static const uint32_t args_in_reg = 8;
353 // register file offset to first argument
354 static const uint32_t reg_offset = 4;
356 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
360 // get the current stack pointer
361 uint64_t sp = ctx.reg_ctx->GetSP();
363 for (size_t i = 0; i < num_args; ++i) {
364 bool success = false;
365 ArgItem &arg = arg_list[i];
366 // arguments passed in registers
367 if (i < args_in_reg) {
368 const RegisterInfo *reg =
369 ctx.reg_ctx->GetRegisterInfoAtIndex(i + reg_offset);
370 RegisterValue reg_val;
371 if (ctx.reg_ctx->ReadRegister(reg, reg_val))
372 arg.value = reg_val.GetAsUInt64(0, &success);
374 // arguments passed on the stack
376 // get the argument type size
377 const size_t arg_size = sizeof(uint64_t);
380 // read this argument from memory
382 ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
383 success = (err.Success() && bytes_read == arg_size);
384 // advance the stack pointer
387 // fail if we couldn't read this argument
390 log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
391 __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
398 bool GetArgs(ExecutionContext &exe_ctx, ArgItem *arg_list, size_t num_args) {
399 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
401 // verify that we have a target
402 if (!exe_ctx.GetTargetPtr()) {
404 log->Printf("%s - invalid target", __FUNCTION__);
408 GetArgsCtx ctx = {exe_ctx.GetRegisterContext(), exe_ctx.GetProcessPtr()};
409 assert(ctx.reg_ctx && ctx.process);
411 // dispatch based on architecture
412 switch (exe_ctx.GetTargetPtr()->GetArchitecture().GetMachine()) {
413 case llvm::Triple::ArchType::x86:
414 return GetArgsX86(ctx, arg_list, num_args);
416 case llvm::Triple::ArchType::x86_64:
417 return GetArgsX86_64(ctx, arg_list, num_args);
419 case llvm::Triple::ArchType::arm:
420 return GetArgsArm(ctx, arg_list, num_args);
422 case llvm::Triple::ArchType::aarch64:
423 return GetArgsAarch64(ctx, arg_list, num_args);
425 case llvm::Triple::ArchType::mipsel:
426 return GetArgsMipsel(ctx, arg_list, num_args);
428 case llvm::Triple::ArchType::mips64el:
429 return GetArgsMips64el(ctx, arg_list, num_args);
432 // unsupported architecture
435 "%s - architecture not supported: '%s'", __FUNCTION__,
436 exe_ctx.GetTargetRef().GetArchitecture().GetArchitectureName());
442 bool IsRenderScriptScriptModule(ModuleSP module) {
445 return module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"),
446 eSymbolTypeData) != nullptr;
449 bool ParseCoordinate(llvm::StringRef coord_s, RSCoordinate &coord) {
450 // takes an argument of the form 'num[,num][,num]'.
451 // Where 'coord_s' is a comma separated 1,2 or 3-dimensional coordinate
452 // with the whitespace trimmed.
453 // Missing coordinates are defaulted to zero.
454 // If parsing of any elements fails the contents of &coord are undefined
455 // and `false` is returned, `true` otherwise
457 RegularExpression regex;
458 RegularExpression::Match regex_match(3);
460 bool matched = false;
461 if (regex.Compile(llvm::StringRef("^([0-9]+),([0-9]+),([0-9]+)$")) &&
462 regex.Execute(coord_s, ®ex_match))
464 else if (regex.Compile(llvm::StringRef("^([0-9]+),([0-9]+)$")) &&
465 regex.Execute(coord_s, ®ex_match))
467 else if (regex.Compile(llvm::StringRef("^([0-9]+)$")) &&
468 regex.Execute(coord_s, ®ex_match))
474 auto get_index = [&](int idx, uint32_t &i) -> bool {
477 if (regex_match.GetMatchAtIndex(coord_s.str().c_str(), idx + 1, group))
478 return !llvm::StringRef(group).getAsInteger<uint32_t>(10, i);
482 return get_index(0, coord.x) && get_index(1, coord.y) &&
483 get_index(2, coord.z);
486 bool SkipPrologue(lldb::ModuleSP &module, Address &addr) {
487 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
489 uint32_t resolved_flags =
490 module->ResolveSymbolContextForAddress(addr, eSymbolContextFunction, sc);
491 if (resolved_flags & eSymbolContextFunction) {
493 const uint32_t offset = sc.function->GetPrologueByteSize();
494 ConstString name = sc.GetFunctionName();
498 log->Printf("%s: Prologue offset for %s is %" PRIu32, __FUNCTION__,
499 name.AsCString(), offset);
505 } // anonymous namespace
507 // The ScriptDetails class collects data associated with a single script
509 struct RenderScriptRuntime::ScriptDetails {
510 ~ScriptDetails() = default;
512 enum ScriptType { eScript, eScriptC };
514 // The derived type of the script.
515 empirical_type<ScriptType> type;
516 // The name of the original source file.
517 empirical_type<std::string> res_name;
518 // Path to script .so file on the device.
519 empirical_type<std::string> shared_lib;
520 // Directory where kernel objects are cached on device.
521 empirical_type<std::string> cache_dir;
522 // Pointer to the context which owns this script.
523 empirical_type<lldb::addr_t> context;
524 // Pointer to the script object itself.
525 empirical_type<lldb::addr_t> script;
528 // This Element class represents the Element object in RS, defining the type
529 // associated with an Allocation.
530 struct RenderScriptRuntime::Element {
531 // Taken from rsDefines.h
541 RS_KIND_INVALID = 100
544 // Taken from rsDefines.h
560 RS_TYPE_UNSIGNED_5_6_5,
561 RS_TYPE_UNSIGNED_5_5_5_1,
562 RS_TYPE_UNSIGNED_4_4_4_4,
568 RS_TYPE_ELEMENT = 1000,
574 RS_TYPE_PROGRAM_FRAGMENT,
575 RS_TYPE_PROGRAM_VERTEX,
576 RS_TYPE_PROGRAM_RASTER,
577 RS_TYPE_PROGRAM_STORE,
580 RS_TYPE_INVALID = 10000
583 std::vector<Element> children; // Child Element fields for structs
584 empirical_type<lldb::addr_t>
585 element_ptr; // Pointer to the RS Element of the Type
586 empirical_type<DataType>
587 type; // Type of each data pointer stored by the allocation
588 empirical_type<DataKind>
589 type_kind; // Defines pixel type if Allocation is created from an image
590 empirical_type<uint32_t>
591 type_vec_size; // Vector size of each data point, e.g '4' for uchar4
592 empirical_type<uint32_t> field_count; // Number of Subelements
593 empirical_type<uint32_t> datum_size; // Size of a single Element with padding
594 empirical_type<uint32_t> padding; // Number of padding bytes
595 empirical_type<uint32_t>
596 array_size; // Number of items in array, only needed for strucrs
597 ConstString type_name; // Name of type, only needed for structs
599 static const ConstString &
600 GetFallbackStructName(); // Print this as the type name of a struct Element
601 // If we can't resolve the actual struct name
603 bool ShouldRefresh() const {
604 const bool valid_ptr = element_ptr.isValid() && *element_ptr.get() != 0x0;
605 const bool valid_type =
606 type.isValid() && type_vec_size.isValid() && type_kind.isValid();
607 return !valid_ptr || !valid_type || !datum_size.isValid();
611 // This AllocationDetails class collects data associated with a single
612 // allocation instance.
613 struct RenderScriptRuntime::AllocationDetails {
628 // The FileHeader struct specifies the header we use for writing allocations
629 // to a binary file. Our format begins with the ASCII characters "RSAD",
630 // identifying the file as an allocation dump. Member variables dims and
631 // hdr_size are then written consecutively, immediately followed by an
632 // instance of the ElementHeader struct. Because Elements can contain
633 // subelements, there may be more than one instance of the ElementHeader
634 // struct. With this first instance being the root element, and the other
635 // instances being the root's descendants. To identify which instances are an
636 // ElementHeader's children, each struct is immediately followed by a sequence
637 // of consecutive offsets to the start of its child structs. These offsets are
638 // 4 bytes in size, and the 0 offset signifies no more children.
640 uint8_t ident[4]; // ASCII 'RSAD' identifying the file
641 uint32_t dims[3]; // Dimensions
642 uint16_t hdr_size; // Header size in bytes, including all element headers
645 struct ElementHeader {
646 uint16_t type; // DataType enum
647 uint32_t kind; // DataKind enum
648 uint32_t element_size; // Size of a single element, including padding
649 uint16_t vector_size; // Vector width
650 uint32_t array_size; // Number of elements in array
653 // Monotonically increasing from 1
656 // Maps Allocation DataType enum and vector size to printable strings
657 // using mapping from RenderScript numerical types summary documentation
658 static const char *RsDataTypeToString[][4];
660 // Maps Allocation DataKind enum to printable strings
661 static const char *RsDataKindToString[];
663 // Maps allocation types to format sizes for printing.
664 static const uint32_t RSTypeToFormat[][3];
666 // Give each allocation an ID as a way
667 // for commands to reference it.
670 // Allocation Element type
671 RenderScriptRuntime::Element element;
672 // Dimensions of the Allocation
673 empirical_type<Dimension> dimension;
674 // Pointer to address of the RS Allocation
675 empirical_type<lldb::addr_t> address;
676 // Pointer to the data held by the Allocation
677 empirical_type<lldb::addr_t> data_ptr;
678 // Pointer to the RS Type of the Allocation
679 empirical_type<lldb::addr_t> type_ptr;
680 // Pointer to the RS Context of the Allocation
681 empirical_type<lldb::addr_t> context;
682 // Size of the allocation
683 empirical_type<uint32_t> size;
684 // Stride between rows of the allocation
685 empirical_type<uint32_t> stride;
687 // Give each allocation an id, so we can reference it in user commands.
688 AllocationDetails() : id(ID++) {}
690 bool ShouldRefresh() const {
691 bool valid_ptrs = data_ptr.isValid() && *data_ptr.get() != 0x0;
692 valid_ptrs = valid_ptrs && type_ptr.isValid() && *type_ptr.get() != 0x0;
693 return !valid_ptrs || !dimension.isValid() || !size.isValid() ||
694 element.ShouldRefresh();
698 const ConstString &RenderScriptRuntime::Element::GetFallbackStructName() {
699 static const ConstString FallbackStructName("struct");
700 return FallbackStructName;
703 uint32_t RenderScriptRuntime::AllocationDetails::ID = 1;
705 const char *RenderScriptRuntime::AllocationDetails::RsDataKindToString[] = {
706 "User", "Undefined", "Undefined", "Undefined",
707 "Undefined", "Undefined", "Undefined", // Enum jumps from 0 to 7
708 "L Pixel", "A Pixel", "LA Pixel", "RGB Pixel",
709 "RGBA Pixel", "Pixel Depth", "YUV Pixel"};
711 const char *RenderScriptRuntime::AllocationDetails::RsDataTypeToString[][4] = {
712 {"None", "None", "None", "None"},
713 {"half", "half2", "half3", "half4"},
714 {"float", "float2", "float3", "float4"},
715 {"double", "double2", "double3", "double4"},
716 {"char", "char2", "char3", "char4"},
717 {"short", "short2", "short3", "short4"},
718 {"int", "int2", "int3", "int4"},
719 {"long", "long2", "long3", "long4"},
720 {"uchar", "uchar2", "uchar3", "uchar4"},
721 {"ushort", "ushort2", "ushort3", "ushort4"},
722 {"uint", "uint2", "uint3", "uint4"},
723 {"ulong", "ulong2", "ulong3", "ulong4"},
724 {"bool", "bool2", "bool3", "bool4"},
725 {"packed_565", "packed_565", "packed_565", "packed_565"},
726 {"packed_5551", "packed_5551", "packed_5551", "packed_5551"},
727 {"packed_4444", "packed_4444", "packed_4444", "packed_4444"},
728 {"rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4"},
729 {"rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3"},
730 {"rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2"},
733 {"RS Element", "RS Element", "RS Element", "RS Element"},
734 {"RS Type", "RS Type", "RS Type", "RS Type"},
735 {"RS Allocation", "RS Allocation", "RS Allocation", "RS Allocation"},
736 {"RS Sampler", "RS Sampler", "RS Sampler", "RS Sampler"},
737 {"RS Script", "RS Script", "RS Script", "RS Script"},
740 {"RS Mesh", "RS Mesh", "RS Mesh", "RS Mesh"},
741 {"RS Program Fragment", "RS Program Fragment", "RS Program Fragment",
742 "RS Program Fragment"},
743 {"RS Program Vertex", "RS Program Vertex", "RS Program Vertex",
744 "RS Program Vertex"},
745 {"RS Program Raster", "RS Program Raster", "RS Program Raster",
746 "RS Program Raster"},
747 {"RS Program Store", "RS Program Store", "RS Program Store",
749 {"RS Font", "RS Font", "RS Font", "RS Font"}};
751 // Used as an index into the RSTypeToFormat array elements
752 enum TypeToFormatIndex { eFormatSingle = 0, eFormatVector, eElementSize };
754 // { format enum of single element, format enum of element vector, size of
756 const uint32_t RenderScriptRuntime::AllocationDetails::RSTypeToFormat[][3] = {
758 {eFormatHex, eFormatHex, 1},
760 {eFormatFloat, eFormatVectorOfFloat16, 2},
762 {eFormatFloat, eFormatVectorOfFloat32, sizeof(float)},
764 {eFormatFloat, eFormatVectorOfFloat64, sizeof(double)},
766 {eFormatDecimal, eFormatVectorOfSInt8, sizeof(int8_t)},
768 {eFormatDecimal, eFormatVectorOfSInt16, sizeof(int16_t)},
770 {eFormatDecimal, eFormatVectorOfSInt32, sizeof(int32_t)},
772 {eFormatDecimal, eFormatVectorOfSInt64, sizeof(int64_t)},
773 // RS_TYPE_UNSIGNED_8
774 {eFormatDecimal, eFormatVectorOfUInt8, sizeof(uint8_t)},
775 // RS_TYPE_UNSIGNED_16
776 {eFormatDecimal, eFormatVectorOfUInt16, sizeof(uint16_t)},
777 // RS_TYPE_UNSIGNED_32
778 {eFormatDecimal, eFormatVectorOfUInt32, sizeof(uint32_t)},
779 // RS_TYPE_UNSIGNED_64
780 {eFormatDecimal, eFormatVectorOfUInt64, sizeof(uint64_t)},
782 {eFormatBoolean, eFormatBoolean, 1},
783 // RS_TYPE_UNSIGNED_5_6_5
784 {eFormatHex, eFormatHex, sizeof(uint16_t)},
785 // RS_TYPE_UNSIGNED_5_5_5_1
786 {eFormatHex, eFormatHex, sizeof(uint16_t)},
787 // RS_TYPE_UNSIGNED_4_4_4_4
788 {eFormatHex, eFormatHex, sizeof(uint16_t)},
789 // RS_TYPE_MATRIX_4X4
790 {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 16},
791 // RS_TYPE_MATRIX_3X3
792 {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 9},
793 // RS_TYPE_MATRIX_2X2
794 {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 4}};
796 //------------------------------------------------------------------
798 //------------------------------------------------------------------
800 RenderScriptRuntime::CreateInstance(Process *process,
801 lldb::LanguageType language) {
803 if (language == eLanguageTypeExtRenderScript)
804 return new RenderScriptRuntime(process);
809 // Callback with a module to search for matching symbols. We first check that
810 // the module contains RS kernels. Then look for a symbol which matches our
811 // kernel name. The breakpoint address is finally set using the address of this
813 Searcher::CallbackReturn
814 RSBreakpointResolver::SearchCallback(SearchFilter &filter,
815 SymbolContext &context, Address *, bool) {
816 ModuleSP module = context.module_sp;
818 if (!module || !IsRenderScriptScriptModule(module))
819 return Searcher::eCallbackReturnContinue;
821 // Attempt to set a breakpoint on the kernel name symbol within the module
822 // library. If it's not found, it's likely debug info is unavailable - try to
823 // set a breakpoint on <name>.expand.
824 const Symbol *kernel_sym =
825 module->FindFirstSymbolWithNameAndType(m_kernel_name, eSymbolTypeCode);
827 std::string kernel_name_expanded(m_kernel_name.AsCString());
828 kernel_name_expanded.append(".expand");
829 kernel_sym = module->FindFirstSymbolWithNameAndType(
830 ConstString(kernel_name_expanded.c_str()), eSymbolTypeCode);
834 Address bp_addr = kernel_sym->GetAddress();
835 if (filter.AddressPasses(bp_addr))
836 m_breakpoint->AddLocation(bp_addr);
839 return Searcher::eCallbackReturnContinue;
842 Searcher::CallbackReturn
843 RSReduceBreakpointResolver::SearchCallback(lldb_private::SearchFilter &filter,
844 lldb_private::SymbolContext &context,
846 // We need to have access to the list of reductions currently parsed, as
847 // reduce names don't actually exist as
848 // symbols in a module. They are only identifiable by parsing the .rs.info
849 // packet, or finding the expand symbol. We
850 // therefore need access to the list of parsed rs modules to properly resolve
852 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
853 ModuleSP module = context.module_sp;
855 if (!module || !IsRenderScriptScriptModule(module))
856 return Searcher::eCallbackReturnContinue;
859 return Searcher::eCallbackReturnContinue;
861 for (const auto &module_desc : *m_rsmodules) {
862 if (module_desc->m_module != module)
865 for (const auto &reduction : module_desc->m_reductions) {
866 if (reduction.m_reduce_name != m_reduce_name)
869 std::array<std::pair<ConstString, int>, 5> funcs{
870 {{reduction.m_init_name, eKernelTypeInit},
871 {reduction.m_accum_name, eKernelTypeAccum},
872 {reduction.m_comb_name, eKernelTypeComb},
873 {reduction.m_outc_name, eKernelTypeOutC},
874 {reduction.m_halter_name, eKernelTypeHalter}}};
876 for (const auto &kernel : funcs) {
877 // Skip constituent functions that don't match our spec
878 if (!(m_kernel_types & kernel.second))
881 const auto kernel_name = kernel.first;
882 const auto symbol = module->FindFirstSymbolWithNameAndType(
883 kernel_name, eSymbolTypeCode);
887 auto address = symbol->GetAddress();
888 if (filter.AddressPasses(address)) {
890 if (!SkipPrologue(module, address)) {
892 log->Printf("%s: Error trying to skip prologue", __FUNCTION__);
894 m_breakpoint->AddLocation(address, &new_bp);
896 log->Printf("%s: %s reduction breakpoint on %s in %s", __FUNCTION__,
897 new_bp ? "new" : "existing", kernel_name.GetCString(),
898 address.GetModule()->GetFileSpec().GetCString());
903 return eCallbackReturnContinue;
906 Searcher::CallbackReturn RSScriptGroupBreakpointResolver::SearchCallback(
907 SearchFilter &filter, SymbolContext &context, Address *addr,
911 return eCallbackReturnContinue;
913 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
914 ModuleSP &module = context.module_sp;
916 if (!module || !IsRenderScriptScriptModule(module))
917 return Searcher::eCallbackReturnContinue;
919 std::vector<std::string> names;
920 m_breakpoint->GetNames(names);
922 return eCallbackReturnContinue;
924 for (auto &name : names) {
925 const RSScriptGroupDescriptorSP sg = FindScriptGroup(ConstString(name));
928 log->Printf("%s: could not find script group for %s", __FUNCTION__,
934 log->Printf("%s: Found ScriptGroup for %s", __FUNCTION__, name.c_str());
936 for (const RSScriptGroupDescriptor::Kernel &k : sg->m_kernels) {
938 log->Printf("%s: Adding breakpoint for %s", __FUNCTION__,
939 k.m_name.AsCString());
940 log->Printf("%s: Kernel address 0x%" PRIx64, __FUNCTION__, k.m_addr);
943 const lldb_private::Symbol *sym =
944 module->FindFirstSymbolWithNameAndType(k.m_name, eSymbolTypeCode);
947 log->Printf("%s: Unable to find symbol for %s", __FUNCTION__,
948 k.m_name.AsCString());
953 log->Printf("%s: Found symbol name is %s", __FUNCTION__,
954 sym->GetName().AsCString());
957 auto address = sym->GetAddress();
958 if (!SkipPrologue(module, address)) {
960 log->Printf("%s: Error trying to skip prologue", __FUNCTION__);
964 m_breakpoint->AddLocation(address, &new_bp);
967 log->Printf("%s: Placed %sbreakpoint on %s", __FUNCTION__,
968 new_bp ? "new " : "", k.m_name.AsCString());
970 // exit after placing the first breakpoint if we do not intend to stop
971 // on all kernels making up this script group
977 return eCallbackReturnContinue;
980 void RenderScriptRuntime::Initialize() {
981 PluginManager::RegisterPlugin(GetPluginNameStatic(),
982 "RenderScript language support", CreateInstance,
986 void RenderScriptRuntime::Terminate() {
987 PluginManager::UnregisterPlugin(CreateInstance);
990 lldb_private::ConstString RenderScriptRuntime::GetPluginNameStatic() {
991 static ConstString plugin_name("renderscript");
995 RenderScriptRuntime::ModuleKind
996 RenderScriptRuntime::GetModuleKind(const lldb::ModuleSP &module_sp) {
998 if (IsRenderScriptScriptModule(module_sp))
999 return eModuleKindKernelObj;
1001 // Is this the main RS runtime library
1002 const ConstString rs_lib("libRS.so");
1003 if (module_sp->GetFileSpec().GetFilename() == rs_lib) {
1004 return eModuleKindLibRS;
1007 const ConstString rs_driverlib("libRSDriver.so");
1008 if (module_sp->GetFileSpec().GetFilename() == rs_driverlib) {
1009 return eModuleKindDriver;
1012 const ConstString rs_cpureflib("libRSCpuRef.so");
1013 if (module_sp->GetFileSpec().GetFilename() == rs_cpureflib) {
1014 return eModuleKindImpl;
1017 return eModuleKindIgnored;
1020 bool RenderScriptRuntime::IsRenderScriptModule(
1021 const lldb::ModuleSP &module_sp) {
1022 return GetModuleKind(module_sp) != eModuleKindIgnored;
1025 void RenderScriptRuntime::ModulesDidLoad(const ModuleList &module_list) {
1026 std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
1028 size_t num_modules = module_list.GetSize();
1029 for (size_t i = 0; i < num_modules; i++) {
1030 auto mod = module_list.GetModuleAtIndex(i);
1031 if (IsRenderScriptModule(mod)) {
1037 //------------------------------------------------------------------
1038 // PluginInterface protocol
1039 //------------------------------------------------------------------
1040 lldb_private::ConstString RenderScriptRuntime::GetPluginName() {
1041 return GetPluginNameStatic();
1044 uint32_t RenderScriptRuntime::GetPluginVersion() { return 1; }
1046 bool RenderScriptRuntime::IsVTableName(const char *name) { return false; }
1048 bool RenderScriptRuntime::GetDynamicTypeAndAddress(
1049 ValueObject &in_value, lldb::DynamicValueType use_dynamic,
1050 TypeAndOrName &class_type_or_name, Address &address,
1051 Value::ValueType &value_type) {
1056 RenderScriptRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name,
1057 ValueObject &static_value) {
1058 return type_and_or_name;
1061 bool RenderScriptRuntime::CouldHaveDynamicValue(ValueObject &in_value) {
1065 lldb::BreakpointResolverSP
1066 RenderScriptRuntime::CreateExceptionResolver(Breakpoint *bp, bool catch_bp,
1068 BreakpointResolverSP resolver_sp;
1072 const RenderScriptRuntime::HookDefn RenderScriptRuntime::s_runtimeHookDefns[] =
1075 {"rsdScriptInit", "_Z13rsdScriptInitPKN7android12renderscript7ContextEP"
1076 "NS0_7ScriptCEPKcS7_PKhjj",
1077 "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_"
1078 "7ScriptCEPKcS7_PKhmj",
1079 0, RenderScriptRuntime::eModuleKindDriver,
1080 &lldb_private::RenderScriptRuntime::CaptureScriptInit},
1081 {"rsdScriptInvokeForEachMulti",
1082 "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
1083 "_6ScriptEjPPKNS0_10AllocationEjPS6_PKvjPK12RsScriptCall",
1084 "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
1085 "_6ScriptEjPPKNS0_10AllocationEmPS6_PKvmPK12RsScriptCall",
1086 0, RenderScriptRuntime::eModuleKindDriver,
1087 &lldb_private::RenderScriptRuntime::CaptureScriptInvokeForEachMulti},
1088 {"rsdScriptSetGlobalVar", "_Z21rsdScriptSetGlobalVarPKN7android12render"
1089 "script7ContextEPKNS0_6ScriptEjPvj",
1090 "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_"
1092 0, RenderScriptRuntime::eModuleKindDriver,
1093 &lldb_private::RenderScriptRuntime::CaptureSetGlobalVar},
1096 {"rsdAllocationInit", "_Z17rsdAllocationInitPKN7android12renderscript7C"
1097 "ontextEPNS0_10AllocationEb",
1098 "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_"
1100 0, RenderScriptRuntime::eModuleKindDriver,
1101 &lldb_private::RenderScriptRuntime::CaptureAllocationInit},
1102 {"rsdAllocationRead2D",
1103 "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
1104 "10AllocationEjjj23RsAllocationCubemapFacejjPvjj",
1105 "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
1106 "10AllocationEjjj23RsAllocationCubemapFacejjPvmm",
1107 0, RenderScriptRuntime::eModuleKindDriver, nullptr},
1108 {"rsdAllocationDestroy", "_Z20rsdAllocationDestroyPKN7android12rendersc"
1109 "ript7ContextEPNS0_10AllocationE",
1110 "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_"
1112 0, RenderScriptRuntime::eModuleKindDriver,
1113 &lldb_private::RenderScriptRuntime::CaptureAllocationDestroy},
1115 // renderscript script groups
1116 {"rsdDebugHintScriptGroup2", "_ZN7android12renderscript21debugHintScrip"
1117 "tGroup2EPKcjPKPFvPK24RsExpandKernelDriver"
1119 "_ZN7android12renderscript21debugHintScriptGroup2EPKcjPKPFvPK24RsExpan"
1120 "dKernelDriverInfojjjEj",
1121 0, RenderScriptRuntime::eModuleKindImpl,
1122 &lldb_private::RenderScriptRuntime::CaptureDebugHintScriptGroup2}};
1124 const size_t RenderScriptRuntime::s_runtimeHookCount =
1125 sizeof(s_runtimeHookDefns) / sizeof(s_runtimeHookDefns[0]);
1127 bool RenderScriptRuntime::HookCallback(void *baton,
1128 StoppointCallbackContext *ctx,
1129 lldb::user_id_t break_id,
1130 lldb::user_id_t break_loc_id) {
1131 RuntimeHook *hook = (RuntimeHook *)baton;
1132 ExecutionContext exe_ctx(ctx->exe_ctx_ref);
1134 RenderScriptRuntime *lang_rt =
1135 (RenderScriptRuntime *)exe_ctx.GetProcessPtr()->GetLanguageRuntime(
1136 eLanguageTypeExtRenderScript);
1138 lang_rt->HookCallback(hook, exe_ctx);
1143 void RenderScriptRuntime::HookCallback(RuntimeHook *hook,
1144 ExecutionContext &exe_ctx) {
1145 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1148 log->Printf("%s - '%s'", __FUNCTION__, hook->defn->name);
1150 if (hook->defn->grabber) {
1151 (this->*(hook->defn->grabber))(hook, exe_ctx);
1155 void RenderScriptRuntime::CaptureDebugHintScriptGroup2(
1156 RuntimeHook *hook_info, ExecutionContext &context) {
1157 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1166 std::array<ArgItem, 4> args{{
1167 {ArgItem::ePointer, 0}, // const char *groupName
1168 {ArgItem::eInt32, 0}, // const uint32_t groupNameSize
1169 {ArgItem::ePointer, 0}, // const ExpandFuncTy *kernel
1170 {ArgItem::eInt32, 0}, // const uint32_t kernelCount
1173 if (!GetArgs(context, args.data(), args.size())) {
1175 log->Printf("%s - Error while reading the function parameters",
1179 log->Printf("%s - groupName : 0x%" PRIx64, __FUNCTION__,
1180 addr_t(args[eGroupName]));
1181 log->Printf("%s - groupNameSize: %" PRIu64, __FUNCTION__,
1182 uint64_t(args[eGroupNameSize]));
1183 log->Printf("%s - kernel : 0x%" PRIx64, __FUNCTION__,
1184 addr_t(args[eKernel]));
1185 log->Printf("%s - kernelCount : %" PRIu64, __FUNCTION__,
1186 uint64_t(args[eKernelCount]));
1189 // parse script group name
1190 ConstString group_name;
1193 const uint64_t len = uint64_t(args[eGroupNameSize]);
1194 std::unique_ptr<char[]> buffer(new char[uint32_t(len + 1)]);
1195 m_process->ReadMemory(addr_t(args[eGroupName]), buffer.get(), len, err);
1196 buffer.get()[len] = '\0';
1197 if (!err.Success()) {
1199 log->Printf("Error reading scriptgroup name from target");
1203 log->Printf("Extracted scriptgroup name %s", buffer.get());
1205 // write back the script group name
1206 group_name.SetCString(buffer.get());
1209 // create or access existing script group
1210 RSScriptGroupDescriptorSP group;
1212 // search for existing script group
1213 for (auto sg : m_scriptGroups) {
1214 if (sg->m_name == group_name) {
1220 group.reset(new RSScriptGroupDescriptor);
1221 group->m_name = group_name;
1222 m_scriptGroups.push_back(group);
1224 // already have this script group
1226 log->Printf("Attempt to add duplicate script group %s",
1227 group_name.AsCString());
1233 const uint32_t target_ptr_size = m_process->GetAddressByteSize();
1234 std::vector<addr_t> kernels;
1235 // parse kernel addresses in script group
1236 for (uint64_t i = 0; i < uint64_t(args[eKernelCount]); ++i) {
1237 RSScriptGroupDescriptor::Kernel kernel;
1238 // extract script group kernel addresses from the target
1239 const addr_t ptr_addr = addr_t(args[eKernel]) + i * target_ptr_size;
1240 uint64_t kernel_addr = 0;
1243 m_process->ReadMemory(ptr_addr, &kernel_addr, target_ptr_size, err);
1244 if (!err.Success() || read != target_ptr_size) {
1246 log->Printf("Error parsing kernel address %" PRIu64 " in script group",
1251 log->Printf("Extracted scriptgroup kernel address - 0x%" PRIx64,
1253 kernel.m_addr = kernel_addr;
1255 // try to resolve the associated kernel name
1256 if (!ResolveKernelName(kernel.m_addr, kernel.m_name)) {
1258 log->Printf("Parsed scriptgroup kernel %" PRIu64 " - 0x%" PRIx64, i,
1263 // try to find the non '.expand' function
1265 const llvm::StringRef expand(".expand");
1266 const llvm::StringRef name_ref = kernel.m_name.GetStringRef();
1267 if (name_ref.endswith(expand)) {
1268 const ConstString base_kernel(name_ref.drop_back(expand.size()));
1269 // verify this function is a valid kernel
1270 if (IsKnownKernel(base_kernel)) {
1271 kernel.m_name = base_kernel;
1273 log->Printf("%s - found non expand version '%s'", __FUNCTION__,
1274 base_kernel.GetCString());
1278 // add to a list of script group kernels we know about
1279 group->m_kernels.push_back(kernel);
1282 // Resolve any pending scriptgroup breakpoints
1284 Target &target = m_process->GetTarget();
1285 const BreakpointList &list = target.GetBreakpointList();
1286 const size_t num_breakpoints = list.GetSize();
1288 log->Printf("Resolving %zu breakpoints", num_breakpoints);
1289 for (size_t i = 0; i < num_breakpoints; ++i) {
1290 const BreakpointSP bp = list.GetBreakpointAtIndex(i);
1292 if (bp->MatchesName(group_name.AsCString())) {
1294 log->Printf("Found breakpoint with name %s",
1295 group_name.AsCString());
1296 bp->ResolveBreakpoint();
1303 void RenderScriptRuntime::CaptureScriptInvokeForEachMulti(
1304 RuntimeHook *hook, ExecutionContext &exe_ctx) {
1305 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1319 std::array<ArgItem, 9> args{{
1320 ArgItem{ArgItem::ePointer, 0}, // const Context *rsc
1321 ArgItem{ArgItem::ePointer, 0}, // Script *s
1322 ArgItem{ArgItem::eInt32, 0}, // uint32_t slot
1323 ArgItem{ArgItem::ePointer, 0}, // const Allocation **aIns
1324 ArgItem{ArgItem::eInt32, 0}, // size_t inLen
1325 ArgItem{ArgItem::ePointer, 0}, // Allocation *aout
1326 ArgItem{ArgItem::ePointer, 0}, // const void *usr
1327 ArgItem{ArgItem::eInt32, 0}, // size_t usrLen
1328 ArgItem{ArgItem::ePointer, 0}, // const RsScriptCall *sc
1331 bool success = GetArgs(exe_ctx, &args[0], args.size());
1334 log->Printf("%s - Error while reading the function parameters",
1339 const uint32_t target_ptr_size = m_process->GetAddressByteSize();
1341 std::vector<uint64_t> allocs;
1343 // traverse allocation list
1344 for (uint64_t i = 0; i < uint64_t(args[eRsInLen]); ++i) {
1345 // calculate offest to allocation pointer
1346 const addr_t addr = addr_t(args[eRsAIns]) + i * target_ptr_size;
1348 // Note: due to little endian layout, reading 32bits or 64bits into res
1349 // will give the correct results.
1350 uint64_t result = 0;
1351 size_t read = m_process->ReadMemory(addr, &result, target_ptr_size, err);
1352 if (read != target_ptr_size || !err.Success()) {
1355 "%s - Error while reading allocation list argument %" PRIu64,
1358 allocs.push_back(result);
1362 // if there is an output allocation track it
1363 if (uint64_t alloc_out = uint64_t(args[eRsAOut])) {
1364 allocs.push_back(alloc_out);
1367 // for all allocations we have found
1368 for (const uint64_t alloc_addr : allocs) {
1369 AllocationDetails *alloc = LookUpAllocation(alloc_addr);
1371 alloc = CreateAllocation(alloc_addr);
1374 // save the allocation address
1375 if (alloc->address.isValid()) {
1376 // check the allocation address we already have matches
1377 assert(*alloc->address.get() == alloc_addr);
1379 alloc->address = alloc_addr;
1384 if (alloc->context.isValid() &&
1385 *alloc->context.get() != addr_t(args[eRsContext]))
1386 log->Printf("%s - Allocation used by multiple contexts",
1389 alloc->context = addr_t(args[eRsContext]);
1393 // make sure we track this script object
1394 if (lldb_private::RenderScriptRuntime::ScriptDetails *script =
1395 LookUpScript(addr_t(args[eRsScript]), true)) {
1397 if (script->context.isValid() &&
1398 *script->context.get() != addr_t(args[eRsContext]))
1399 log->Printf("%s - Script used by multiple contexts", __FUNCTION__);
1401 script->context = addr_t(args[eRsContext]);
1405 void RenderScriptRuntime::CaptureSetGlobalVar(RuntimeHook *hook,
1406 ExecutionContext &context) {
1407 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1417 std::array<ArgItem, 5> args{{
1418 ArgItem{ArgItem::ePointer, 0}, // eRsContext
1419 ArgItem{ArgItem::ePointer, 0}, // eRsScript
1420 ArgItem{ArgItem::eInt32, 0}, // eRsId
1421 ArgItem{ArgItem::ePointer, 0}, // eRsData
1422 ArgItem{ArgItem::eInt32, 0}, // eRsLength
1425 bool success = GetArgs(context, &args[0], args.size());
1428 log->Printf("%s - error reading the function parameters.", __FUNCTION__);
1433 log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " slot %" PRIu64 " = 0x%" PRIx64
1434 ":%" PRIu64 "bytes.",
1435 __FUNCTION__, uint64_t(args[eRsContext]),
1436 uint64_t(args[eRsScript]), uint64_t(args[eRsId]),
1437 uint64_t(args[eRsData]), uint64_t(args[eRsLength]));
1439 addr_t script_addr = addr_t(args[eRsScript]);
1440 if (m_scriptMappings.find(script_addr) != m_scriptMappings.end()) {
1441 auto rsm = m_scriptMappings[script_addr];
1442 if (uint64_t(args[eRsId]) < rsm->m_globals.size()) {
1443 auto rsg = rsm->m_globals[uint64_t(args[eRsId])];
1444 log->Printf("%s - Setting of '%s' within '%s' inferred", __FUNCTION__,
1445 rsg.m_name.AsCString(),
1446 rsm->m_module->GetFileSpec().GetFilename().AsCString());
1452 void RenderScriptRuntime::CaptureAllocationInit(RuntimeHook *hook,
1453 ExecutionContext &exe_ctx) {
1454 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1456 enum { eRsContext, eRsAlloc, eRsForceZero };
1458 std::array<ArgItem, 3> args{{
1459 ArgItem{ArgItem::ePointer, 0}, // eRsContext
1460 ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
1461 ArgItem{ArgItem::eBool, 0}, // eRsForceZero
1464 bool success = GetArgs(exe_ctx, &args[0], args.size());
1467 log->Printf("%s - error while reading the function parameters",
1473 log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 ",0x%" PRIx64 " .",
1474 __FUNCTION__, uint64_t(args[eRsContext]),
1475 uint64_t(args[eRsAlloc]), uint64_t(args[eRsForceZero]));
1477 AllocationDetails *alloc = CreateAllocation(uint64_t(args[eRsAlloc]));
1479 alloc->context = uint64_t(args[eRsContext]);
1482 void RenderScriptRuntime::CaptureAllocationDestroy(RuntimeHook *hook,
1483 ExecutionContext &exe_ctx) {
1484 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1491 std::array<ArgItem, 2> args{{
1492 ArgItem{ArgItem::ePointer, 0}, // eRsContext
1493 ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
1496 bool success = GetArgs(exe_ctx, &args[0], args.size());
1499 log->Printf("%s - error while reading the function parameters.",
1505 log->Printf("%s - 0x%" PRIx64 ", 0x%" PRIx64 ".", __FUNCTION__,
1506 uint64_t(args[eRsContext]), uint64_t(args[eRsAlloc]));
1508 for (auto iter = m_allocations.begin(); iter != m_allocations.end(); ++iter) {
1509 auto &allocation_ap = *iter; // get the unique pointer
1510 if (allocation_ap->address.isValid() &&
1511 *allocation_ap->address.get() == addr_t(args[eRsAlloc])) {
1512 m_allocations.erase(iter);
1514 log->Printf("%s - deleted allocation entry.", __FUNCTION__);
1520 log->Printf("%s - couldn't find destroyed allocation.", __FUNCTION__);
1523 void RenderScriptRuntime::CaptureScriptInit(RuntimeHook *hook,
1524 ExecutionContext &exe_ctx) {
1525 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1528 Process *process = exe_ctx.GetProcessPtr();
1530 enum { eRsContext, eRsScript, eRsResNamePtr, eRsCachedDirPtr };
1532 std::array<ArgItem, 4> args{
1533 {ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0},
1534 ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0}}};
1535 bool success = GetArgs(exe_ctx, &args[0], args.size());
1538 log->Printf("%s - error while reading the function parameters.",
1543 std::string res_name;
1544 process->ReadCStringFromMemory(addr_t(args[eRsResNamePtr]), res_name, err);
1547 log->Printf("%s - error reading res_name: %s.", __FUNCTION__,
1551 std::string cache_dir;
1552 process->ReadCStringFromMemory(addr_t(args[eRsCachedDirPtr]), cache_dir, err);
1555 log->Printf("%s - error reading cache_dir: %s.", __FUNCTION__,
1560 log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " => '%s' at '%s' .",
1561 __FUNCTION__, uint64_t(args[eRsContext]),
1562 uint64_t(args[eRsScript]), res_name.c_str(), cache_dir.c_str());
1564 if (res_name.size() > 0) {
1566 strm.Printf("librs.%s.so", res_name.c_str());
1568 ScriptDetails *script = LookUpScript(addr_t(args[eRsScript]), true);
1570 script->type = ScriptDetails::eScriptC;
1571 script->cache_dir = cache_dir;
1572 script->res_name = res_name;
1573 script->shared_lib = strm.GetString();
1574 script->context = addr_t(args[eRsContext]);
1578 log->Printf("%s - '%s' tagged with context 0x%" PRIx64
1579 " and script 0x%" PRIx64 ".",
1580 __FUNCTION__, strm.GetData(), uint64_t(args[eRsContext]),
1581 uint64_t(args[eRsScript]));
1583 log->Printf("%s - resource name invalid, Script not tagged.", __FUNCTION__);
1587 void RenderScriptRuntime::LoadRuntimeHooks(lldb::ModuleSP module,
1589 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1595 Target &target = GetProcess()->GetTarget();
1596 const llvm::Triple::ArchType machine = target.GetArchitecture().GetMachine();
1598 if (machine != llvm::Triple::ArchType::x86 &&
1599 machine != llvm::Triple::ArchType::arm &&
1600 machine != llvm::Triple::ArchType::aarch64 &&
1601 machine != llvm::Triple::ArchType::mipsel &&
1602 machine != llvm::Triple::ArchType::mips64el &&
1603 machine != llvm::Triple::ArchType::x86_64) {
1605 log->Printf("%s - unable to hook runtime functions.", __FUNCTION__);
1609 const uint32_t target_ptr_size =
1610 target.GetArchitecture().GetAddressByteSize();
1612 std::array<bool, s_runtimeHookCount> hook_placed;
1613 hook_placed.fill(false);
1615 for (size_t idx = 0; idx < s_runtimeHookCount; idx++) {
1616 const HookDefn *hook_defn = &s_runtimeHookDefns[idx];
1617 if (hook_defn->kind != kind) {
1621 const char *symbol_name = (target_ptr_size == 4)
1622 ? hook_defn->symbol_name_m32
1623 : hook_defn->symbol_name_m64;
1625 const Symbol *sym = module->FindFirstSymbolWithNameAndType(
1626 ConstString(symbol_name), eSymbolTypeCode);
1629 log->Printf("%s - symbol '%s' related to the function %s not found",
1630 __FUNCTION__, symbol_name, hook_defn->name);
1635 addr_t addr = sym->GetLoadAddress(&target);
1636 if (addr == LLDB_INVALID_ADDRESS) {
1638 log->Printf("%s - unable to resolve the address of hook function '%s' "
1639 "with symbol '%s'.",
1640 __FUNCTION__, hook_defn->name, symbol_name);
1644 log->Printf("%s - function %s, address resolved at 0x%" PRIx64,
1645 __FUNCTION__, hook_defn->name, addr);
1648 RuntimeHookSP hook(new RuntimeHook());
1649 hook->address = addr;
1650 hook->defn = hook_defn;
1651 hook->bp_sp = target.CreateBreakpoint(addr, true, false);
1652 hook->bp_sp->SetCallback(HookCallback, hook.get(), true);
1653 m_runtimeHooks[addr] = hook;
1655 log->Printf("%s - successfully hooked '%s' in '%s' version %" PRIu64
1656 " at 0x%" PRIx64 ".",
1657 __FUNCTION__, hook_defn->name,
1658 module->GetFileSpec().GetFilename().AsCString(),
1659 (uint64_t)hook_defn->version, (uint64_t)addr);
1661 hook_placed[idx] = true;
1664 // log any unhooked function
1666 for (size_t i = 0; i < hook_placed.size(); ++i) {
1669 const HookDefn &hook_defn = s_runtimeHookDefns[i];
1670 if (hook_defn.kind != kind)
1672 log->Printf("%s - function %s was not hooked", __FUNCTION__,
1678 void RenderScriptRuntime::FixupScriptDetails(RSModuleDescriptorSP rsmodule_sp) {
1682 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1684 const ModuleSP module = rsmodule_sp->m_module;
1685 const FileSpec &file = module->GetPlatformFileSpec();
1687 // Iterate over all of the scripts that we currently know of.
1688 // Note: We cant push or pop to m_scripts here or it may invalidate rs_script.
1689 for (const auto &rs_script : m_scripts) {
1690 // Extract the expected .so file path for this script.
1691 std::string shared_lib;
1692 if (!rs_script->shared_lib.get(shared_lib))
1695 // Only proceed if the module that has loaded corresponds to this script.
1696 if (file.GetFilename() != ConstString(shared_lib.c_str()))
1699 // Obtain the script address which we use as a key.
1700 lldb::addr_t script;
1701 if (!rs_script->script.get(script))
1704 // If we have a script mapping for the current script.
1705 if (m_scriptMappings.find(script) != m_scriptMappings.end()) {
1706 // if the module we have stored is different to the one we just received.
1707 if (m_scriptMappings[script] != rsmodule_sp) {
1710 "%s - script %" PRIx64 " wants reassigned to new rsmodule '%s'.",
1711 __FUNCTION__, (uint64_t)script,
1712 rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
1715 // We don't have a script mapping for the current script.
1717 // Obtain the script resource name.
1718 std::string res_name;
1719 if (rs_script->res_name.get(res_name))
1720 // Set the modules resource name.
1721 rsmodule_sp->m_resname = res_name;
1722 // Add Script/Module pair to map.
1723 m_scriptMappings[script] = rsmodule_sp;
1726 "%s - script %" PRIx64 " associated with rsmodule '%s'.",
1727 __FUNCTION__, (uint64_t)script,
1728 rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
1733 // Uses the Target API to evaluate the expression passed as a parameter to the
1734 // function The result of that expression is returned an unsigned 64 bit int,
1735 // via the result* parameter. Function returns true on success, and false on
1737 bool RenderScriptRuntime::EvalRSExpression(const char *expr,
1738 StackFrame *frame_ptr,
1740 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1742 log->Printf("%s(%s)", __FUNCTION__, expr);
1744 ValueObjectSP expr_result;
1745 EvaluateExpressionOptions options;
1746 options.SetLanguage(lldb::eLanguageTypeC_plus_plus);
1747 // Perform the actual expression evaluation
1748 auto &target = GetProcess()->GetTarget();
1749 target.EvaluateExpression(expr, frame_ptr, expr_result, options);
1753 log->Printf("%s: couldn't evaluate expression.", __FUNCTION__);
1757 // The result of the expression is invalid
1758 if (!expr_result->GetError().Success()) {
1759 Error err = expr_result->GetError();
1760 // Expression returned is void, so this is actually a success
1761 if (err.GetError() == UserExpression::kNoResult) {
1763 log->Printf("%s - expression returned void.", __FUNCTION__);
1770 log->Printf("%s - error evaluating expression result: %s", __FUNCTION__,
1775 bool success = false;
1776 // We only read the result as an uint32_t.
1777 *result = expr_result->GetValueAsUnsigned(0, &success);
1781 log->Printf("%s - couldn't convert expression result to uint32_t",
1790 // Used to index expression format strings
1791 enum ExpressionStrings {
1792 eExprGetOffsetPtr = 0,
1801 eExprElementFieldCount,
1803 eExprSubelementsName,
1804 eExprSubelementsArrSize,
1806 _eExprLast // keep at the end, implicit size of the array runtime_expressions
1809 // max length of an expanded expression
1810 const int jit_max_expr_size = 512;
1812 // Retrieve the string to JIT for the given expression
1813 #define JIT_TEMPLATE_CONTEXT "void* ctxt = (void*)rsDebugGetContextWrapper(0x%" PRIx64 "); "
1814 const char *JITTemplate(ExpressionStrings e) {
1815 // Format strings containing the expressions we may need to evaluate.
1816 static std::array<const char *, _eExprLast> runtime_expressions = {
1817 {// Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap)
1819 "Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocation"
1821 "(0x%" PRIx64 ", %" PRIu32 ", %" PRIu32 ", %" PRIu32 ", 0, 0)", // eExprGetOffsetPtr
1823 // Type* rsaAllocationGetType(Context*, Allocation*)
1824 JIT_TEMPLATE_CONTEXT "(void*)rsaAllocationGetType(ctxt, 0x%" PRIx64 ")", // eExprAllocGetType
1826 // rsaTypeGetNativeData(Context*, Type*, void* typeData, size) Pack the
1827 // data in the following way mHal.state.dimX; mHal.state.dimY;
1828 // mHal.state.dimZ; mHal.state.lodCount; mHal.state.faces; mElement; into
1829 // typeData Need to specify 32 or 64 bit for uint_t since this differs
1831 JIT_TEMPLATE_CONTEXT
1832 "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
1833 ", 0x%" PRIx64 ", data, 6); data[0]", // eExprTypeDimX
1834 JIT_TEMPLATE_CONTEXT
1835 "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
1836 ", 0x%" PRIx64 ", data, 6); data[1]", // eExprTypeDimY
1837 JIT_TEMPLATE_CONTEXT
1838 "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
1839 ", 0x%" PRIx64 ", data, 6); data[2]", // eExprTypeDimZ
1840 JIT_TEMPLATE_CONTEXT
1841 "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
1842 ", 0x%" PRIx64 ", data, 6); data[5]", // eExprTypeElemPtr
1844 // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size)
1845 // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into
1847 JIT_TEMPLATE_CONTEXT
1848 "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
1849 ", 0x%" PRIx64 ", data, 5); data[0]", // eExprElementType
1850 JIT_TEMPLATE_CONTEXT
1851 "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
1852 ", 0x%" PRIx64 ", data, 5); data[1]", // eExprElementKind
1853 JIT_TEMPLATE_CONTEXT
1854 "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
1855 ", 0x%" PRIx64 ", data, 5); data[3]", // eExprElementVec
1856 JIT_TEMPLATE_CONTEXT
1857 "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
1858 ", 0x%" PRIx64 ", data, 5); data[4]", // eExprElementFieldCount
1860 // rsaElementGetSubElements(RsContext con, RsElement elem, uintptr_t
1861 // *ids, const char **names, size_t *arraySizes, uint32_t dataSize)
1862 // Needed for Allocations of structs to gather details about
1863 // fields/Subelements Element* of field
1864 JIT_TEMPLATE_CONTEXT "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1865 "]; size_t arr_size[%" PRIu32 "];"
1866 "(void*)rsaElementGetSubElements(ctxt, 0x%" PRIx64
1867 ", ids, names, arr_size, %" PRIu32 "); ids[%" PRIu32 "]", // eExprSubelementsId
1870 JIT_TEMPLATE_CONTEXT "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1871 "]; size_t arr_size[%" PRIu32 "];"
1872 "(void*)rsaElementGetSubElements(ctxt, 0x%" PRIx64
1873 ", ids, names, arr_size, %" PRIu32 "); names[%" PRIu32 "]", // eExprSubelementsName
1875 // Array size of field
1876 JIT_TEMPLATE_CONTEXT "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1877 "]; size_t arr_size[%" PRIu32 "];"
1878 "(void*)rsaElementGetSubElements(ctxt, 0x%" PRIx64
1879 ", ids, names, arr_size, %" PRIu32 "); arr_size[%" PRIu32 "]"}}; // eExprSubelementsArrSize
1881 return runtime_expressions[e];
1883 } // end of the anonymous namespace
1885 // JITs the RS runtime for the internal data pointer of an allocation. Is passed
1886 // x,y,z coordinates for the pointer to a specific element. Then sets the
1887 // data_ptr member in Allocation with the result. Returns true on success, false
1889 bool RenderScriptRuntime::JITDataPointer(AllocationDetails *alloc,
1890 StackFrame *frame_ptr, uint32_t x,
1891 uint32_t y, uint32_t z) {
1892 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1894 if (!alloc->address.isValid()) {
1896 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
1900 const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
1901 char expr_buf[jit_max_expr_size];
1903 int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
1904 *alloc->address.get(), x, y, z);
1907 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1909 } else if (written >= jit_max_expr_size) {
1911 log->Printf("%s - expression too long.", __FUNCTION__);
1915 uint64_t result = 0;
1916 if (!EvalRSExpression(expr_buf, frame_ptr, &result))
1919 addr_t data_ptr = static_cast<lldb::addr_t>(result);
1920 alloc->data_ptr = data_ptr;
1925 // JITs the RS runtime for the internal pointer to the RS Type of an allocation
1926 // Then sets the type_ptr member in Allocation with the result. Returns true on
1927 // success, false otherwise
1928 bool RenderScriptRuntime::JITTypePointer(AllocationDetails *alloc,
1929 StackFrame *frame_ptr) {
1930 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1932 if (!alloc->address.isValid() || !alloc->context.isValid()) {
1934 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
1938 const char *fmt_str = JITTemplate(eExprAllocGetType);
1939 char expr_buf[jit_max_expr_size];
1941 int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
1942 *alloc->context.get(), *alloc->address.get());
1945 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1947 } else if (written >= jit_max_expr_size) {
1949 log->Printf("%s - expression too long.", __FUNCTION__);
1953 uint64_t result = 0;
1954 if (!EvalRSExpression(expr_buf, frame_ptr, &result))
1957 addr_t type_ptr = static_cast<lldb::addr_t>(result);
1958 alloc->type_ptr = type_ptr;
1963 // JITs the RS runtime for information about the dimensions and type of an
1964 // allocation Then sets dimension and element_ptr members in Allocation with the
1965 // result. Returns true on success, false otherwise
1966 bool RenderScriptRuntime::JITTypePacked(AllocationDetails *alloc,
1967 StackFrame *frame_ptr) {
1968 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1970 if (!alloc->type_ptr.isValid() || !alloc->context.isValid()) {
1972 log->Printf("%s - Failed to find allocation details.", __FUNCTION__);
1976 // Expression is different depending on if device is 32 or 64 bit
1977 uint32_t target_ptr_size =
1978 GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
1979 const uint32_t bits = target_ptr_size == 4 ? 32 : 64;
1981 // We want 4 elements from packed data
1982 const uint32_t num_exprs = 4;
1983 assert(num_exprs == (eExprTypeElemPtr - eExprTypeDimX + 1) &&
1984 "Invalid number of expressions");
1986 char expr_bufs[num_exprs][jit_max_expr_size];
1987 uint64_t results[num_exprs];
1989 for (uint32_t i = 0; i < num_exprs; ++i) {
1990 const char *fmt_str = JITTemplate(ExpressionStrings(eExprTypeDimX + i));
1991 int written = snprintf(expr_bufs[i], jit_max_expr_size, fmt_str,
1992 *alloc->context.get(), bits, *alloc->type_ptr.get());
1995 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1997 } else if (written >= jit_max_expr_size) {
1999 log->Printf("%s - expression too long.", __FUNCTION__);
2003 // Perform expression evaluation
2004 if (!EvalRSExpression(expr_bufs[i], frame_ptr, &results[i]))
2008 // Assign results to allocation members
2009 AllocationDetails::Dimension dims;
2010 dims.dim_1 = static_cast<uint32_t>(results[0]);
2011 dims.dim_2 = static_cast<uint32_t>(results[1]);
2012 dims.dim_3 = static_cast<uint32_t>(results[2]);
2013 alloc->dimension = dims;
2015 addr_t element_ptr = static_cast<lldb::addr_t>(results[3]);
2016 alloc->element.element_ptr = element_ptr;
2019 log->Printf("%s - dims (%" PRIu32 ", %" PRIu32 ", %" PRIu32
2020 ") Element*: 0x%" PRIx64 ".",
2021 __FUNCTION__, dims.dim_1, dims.dim_2, dims.dim_3, element_ptr);
2026 // JITs the RS runtime for information about the Element of an allocation Then
2027 // sets type, type_vec_size, field_count and type_kind members in Element with
2028 // the result. Returns true on success, false otherwise
2029 bool RenderScriptRuntime::JITElementPacked(Element &elem,
2030 const lldb::addr_t context,
2031 StackFrame *frame_ptr) {
2032 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2034 if (!elem.element_ptr.isValid()) {
2036 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
2040 // We want 4 elements from packed data
2041 const uint32_t num_exprs = 4;
2042 assert(num_exprs == (eExprElementFieldCount - eExprElementType + 1) &&
2043 "Invalid number of expressions");
2045 char expr_bufs[num_exprs][jit_max_expr_size];
2046 uint64_t results[num_exprs];
2048 for (uint32_t i = 0; i < num_exprs; i++) {
2049 const char *fmt_str = JITTemplate(ExpressionStrings(eExprElementType + i));
2050 int written = snprintf(expr_bufs[i], jit_max_expr_size, fmt_str, context,
2051 *elem.element_ptr.get());
2054 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
2056 } else if (written >= jit_max_expr_size) {
2058 log->Printf("%s - expression too long.", __FUNCTION__);
2062 // Perform expression evaluation
2063 if (!EvalRSExpression(expr_bufs[i], frame_ptr, &results[i]))
2067 // Assign results to allocation members
2068 elem.type = static_cast<RenderScriptRuntime::Element::DataType>(results[0]);
2070 static_cast<RenderScriptRuntime::Element::DataKind>(results[1]);
2071 elem.type_vec_size = static_cast<uint32_t>(results[2]);
2072 elem.field_count = static_cast<uint32_t>(results[3]);
2075 log->Printf("%s - data type %" PRIu32 ", pixel type %" PRIu32
2076 ", vector size %" PRIu32 ", field count %" PRIu32,
2077 __FUNCTION__, *elem.type.get(), *elem.type_kind.get(),
2078 *elem.type_vec_size.get(), *elem.field_count.get());
2080 // If this Element has subelements then JIT rsaElementGetSubElements() for
2081 // details about its fields
2082 if (*elem.field_count.get() > 0 && !JITSubelements(elem, context, frame_ptr))
2088 // JITs the RS runtime for information about the subelements/fields of a struct
2089 // allocation This is necessary for infering the struct type so we can pretty
2090 // print the allocation's contents. Returns true on success, false otherwise
2091 bool RenderScriptRuntime::JITSubelements(Element &elem,
2092 const lldb::addr_t context,
2093 StackFrame *frame_ptr) {
2094 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2096 if (!elem.element_ptr.isValid() || !elem.field_count.isValid()) {
2098 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
2102 const short num_exprs = 3;
2103 assert(num_exprs == (eExprSubelementsArrSize - eExprSubelementsId + 1) &&
2104 "Invalid number of expressions");
2106 char expr_buffer[jit_max_expr_size];
2109 // Iterate over struct fields.
2110 const uint32_t field_count = *elem.field_count.get();
2111 for (uint32_t field_index = 0; field_index < field_count; ++field_index) {
2113 for (uint32_t expr_index = 0; expr_index < num_exprs; ++expr_index) {
2114 const char *fmt_str =
2115 JITTemplate(ExpressionStrings(eExprSubelementsId + expr_index));
2116 int written = snprintf(expr_buffer, jit_max_expr_size, fmt_str,
2117 context, field_count, field_count, field_count,
2118 *elem.element_ptr.get(), field_count, field_index);
2121 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
2123 } else if (written >= jit_max_expr_size) {
2125 log->Printf("%s - expression too long.", __FUNCTION__);
2129 // Perform expression evaluation
2130 if (!EvalRSExpression(expr_buffer, frame_ptr, &results))
2134 log->Printf("%s - expr result 0x%" PRIx64 ".", __FUNCTION__, results);
2136 switch (expr_index) {
2137 case 0: // Element* of child
2138 child.element_ptr = static_cast<addr_t>(results);
2140 case 1: // Name of child
2142 lldb::addr_t address = static_cast<addr_t>(results);
2145 GetProcess()->ReadCStringFromMemory(address, name, err);
2147 child.type_name = ConstString(name);
2150 log->Printf("%s - warning: Couldn't read field name.",
2155 case 2: // Array size of child
2156 child.array_size = static_cast<uint32_t>(results);
2161 // We need to recursively JIT each Element field of the struct since
2162 // structs can be nested inside structs.
2163 if (!JITElementPacked(child, context, frame_ptr))
2165 elem.children.push_back(child);
2168 // Try to infer the name of the struct type so we can pretty print the
2169 // allocation contents.
2170 FindStructTypeName(elem, frame_ptr);
2175 // JITs the RS runtime for the address of the last element in the allocation.
2176 // The `elem_size` parameter represents the size of a single element, including
2177 // padding. Which is needed as an offset from the last element pointer. Using
2178 // this offset minus the starting address we can calculate the size of the
2179 // allocation. Returns true on success, false otherwise
2180 bool RenderScriptRuntime::JITAllocationSize(AllocationDetails *alloc,
2181 StackFrame *frame_ptr) {
2182 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2184 if (!alloc->address.isValid() || !alloc->dimension.isValid() ||
2185 !alloc->data_ptr.isValid() || !alloc->element.datum_size.isValid()) {
2187 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
2192 uint32_t dim_x = alloc->dimension.get()->dim_1;
2193 uint32_t dim_y = alloc->dimension.get()->dim_2;
2194 uint32_t dim_z = alloc->dimension.get()->dim_3;
2196 // Our plan of jitting the last element address doesn't seem to work for
2197 // struct Allocations` Instead try to infer the size ourselves without any
2198 // inter element padding.
2199 if (alloc->element.children.size() > 0) {
2207 alloc->size = dim_x * dim_y * dim_z * *alloc->element.datum_size.get();
2210 log->Printf("%s - inferred size of struct allocation %" PRIu32 ".",
2211 __FUNCTION__, *alloc->size.get());
2215 const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
2216 char expr_buf[jit_max_expr_size];
2218 // Calculate last element
2219 dim_x = dim_x == 0 ? 0 : dim_x - 1;
2220 dim_y = dim_y == 0 ? 0 : dim_y - 1;
2221 dim_z = dim_z == 0 ? 0 : dim_z - 1;
2223 int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
2224 *alloc->address.get(), dim_x, dim_y, dim_z);
2227 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
2229 } else if (written >= jit_max_expr_size) {
2231 log->Printf("%s - expression too long.", __FUNCTION__);
2235 uint64_t result = 0;
2236 if (!EvalRSExpression(expr_buf, frame_ptr, &result))
2239 addr_t mem_ptr = static_cast<lldb::addr_t>(result);
2240 // Find pointer to last element and add on size of an element
2241 alloc->size = static_cast<uint32_t>(mem_ptr - *alloc->data_ptr.get()) +
2242 *alloc->element.datum_size.get();
2247 // JITs the RS runtime for information about the stride between rows in the
2248 // allocation. This is done to detect padding, since allocated memory is 16-byte
2250 // Returns true on success, false otherwise
2251 bool RenderScriptRuntime::JITAllocationStride(AllocationDetails *alloc,
2252 StackFrame *frame_ptr) {
2253 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2255 if (!alloc->address.isValid() || !alloc->data_ptr.isValid()) {
2257 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
2261 const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
2262 char expr_buf[jit_max_expr_size];
2264 int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
2265 *alloc->address.get(), 0, 1, 0);
2268 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
2270 } else if (written >= jit_max_expr_size) {
2272 log->Printf("%s - expression too long.", __FUNCTION__);
2276 uint64_t result = 0;
2277 if (!EvalRSExpression(expr_buf, frame_ptr, &result))
2280 addr_t mem_ptr = static_cast<lldb::addr_t>(result);
2281 alloc->stride = static_cast<uint32_t>(mem_ptr - *alloc->data_ptr.get());
2286 // JIT all the current runtime info regarding an allocation
2287 bool RenderScriptRuntime::RefreshAllocation(AllocationDetails *alloc,
2288 StackFrame *frame_ptr) {
2289 // GetOffsetPointer()
2290 if (!JITDataPointer(alloc, frame_ptr))
2293 // rsaAllocationGetType()
2294 if (!JITTypePointer(alloc, frame_ptr))
2297 // rsaTypeGetNativeData()
2298 if (!JITTypePacked(alloc, frame_ptr))
2301 // rsaElementGetNativeData()
2302 if (!JITElementPacked(alloc->element, *alloc->context.get(), frame_ptr))
2305 // Sets the datum_size member in Element
2306 SetElementSize(alloc->element);
2308 // Use GetOffsetPointer() to infer size of the allocation
2309 if (!JITAllocationSize(alloc, frame_ptr))
2315 // Function attempts to set the type_name member of the paramaterised Element
2317 // This string should be the name of the struct type the Element represents.
2318 // We need this string for pretty printing the Element to users.
2319 void RenderScriptRuntime::FindStructTypeName(Element &elem,
2320 StackFrame *frame_ptr) {
2321 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2323 if (!elem.type_name.IsEmpty()) // Name already set
2326 elem.type_name = Element::GetFallbackStructName(); // Default type name if
2329 // Find all the global variables from the script rs modules
2330 VariableList var_list;
2331 for (auto module_sp : m_rsmodules)
2332 module_sp->m_module->FindGlobalVariables(
2333 RegularExpression(llvm::StringRef(".")), true, UINT32_MAX, var_list);
2335 // Iterate over all the global variables looking for one with a matching type
2337 // We make the assumption a match exists since there needs to be a global
2338 // variable to reflect the struct type back into java host code.
2339 for (uint32_t i = 0; i < var_list.GetSize(); ++i) {
2340 const VariableSP var_sp(var_list.GetVariableAtIndex(i));
2344 ValueObjectSP valobj_sp = ValueObjectVariable::Create(frame_ptr, var_sp);
2348 // Find the number of variable fields.
2349 // If it has no fields, or more fields than our Element, then it can't be
2350 // the struct we're looking for.
2351 // Don't check for equality since RS can add extra struct members for
2353 size_t num_children = valobj_sp->GetNumChildren();
2354 if (num_children > elem.children.size() || num_children == 0)
2357 // Iterate over children looking for members with matching field names.
2358 // If all the field names match, this is likely the struct we want.
2359 // TODO: This could be made more robust by also checking children data
2360 // sizes, or array size
2362 for (size_t i = 0; i < num_children; ++i) {
2363 ValueObjectSP child = valobj_sp->GetChildAtIndex(i, true);
2364 if (!child || (child->GetName() != elem.children[i].type_name)) {
2370 // RS can add extra struct members for padding in the format
2371 // '#rs_padding_[0-9]+'
2372 if (found && num_children < elem.children.size()) {
2373 const uint32_t size_diff = elem.children.size() - num_children;
2375 log->Printf("%s - %" PRIu32 " padding struct entries", __FUNCTION__,
2378 for (uint32_t i = 0; i < size_diff; ++i) {
2379 const ConstString &name = elem.children[num_children + i].type_name;
2380 if (strcmp(name.AsCString(), "#rs_padding") < 0)
2385 // We've found a global variable with matching type
2387 // Dereference since our Element type isn't a pointer.
2388 if (valobj_sp->IsPointerType()) {
2390 ValueObjectSP deref_valobj = valobj_sp->Dereference(err);
2392 valobj_sp = deref_valobj;
2395 // Save name of variable in Element.
2396 elem.type_name = valobj_sp->GetTypeName();
2398 log->Printf("%s - element name set to %s", __FUNCTION__,
2399 elem.type_name.AsCString());
2406 // Function sets the datum_size member of Element. Representing the size of a
2407 // single instance including padding.
2408 // Assumes the relevant allocation information has already been jitted.
2409 void RenderScriptRuntime::SetElementSize(Element &elem) {
2410 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2411 const Element::DataType type = *elem.type.get();
2412 assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
2413 "Invalid allocation type");
2415 const uint32_t vec_size = *elem.type_vec_size.get();
2416 uint32_t data_size = 0;
2417 uint32_t padding = 0;
2419 // Element is of a struct type, calculate size recursively.
2420 if ((type == Element::RS_TYPE_NONE) && (elem.children.size() > 0)) {
2421 for (Element &child : elem.children) {
2422 SetElementSize(child);
2423 const uint32_t array_size =
2424 child.array_size.isValid() ? *child.array_size.get() : 1;
2425 data_size += *child.datum_size.get() * array_size;
2428 // These have been packed already
2429 else if (type == Element::RS_TYPE_UNSIGNED_5_6_5 ||
2430 type == Element::RS_TYPE_UNSIGNED_5_5_5_1 ||
2431 type == Element::RS_TYPE_UNSIGNED_4_4_4_4) {
2432 data_size = AllocationDetails::RSTypeToFormat[type][eElementSize];
2433 } else if (type < Element::RS_TYPE_ELEMENT) {
2435 vec_size * AllocationDetails::RSTypeToFormat[type][eElementSize];
2437 padding = AllocationDetails::RSTypeToFormat[type][eElementSize];
2440 GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
2442 elem.padding = padding;
2443 elem.datum_size = data_size + padding;
2445 log->Printf("%s - element size set to %" PRIu32, __FUNCTION__,
2446 data_size + padding);
2449 // Given an allocation, this function copies the allocation contents from device
2450 // into a buffer on the heap.
2451 // Returning a shared pointer to the buffer containing the data.
2452 std::shared_ptr<uint8_t>
2453 RenderScriptRuntime::GetAllocationData(AllocationDetails *alloc,
2454 StackFrame *frame_ptr) {
2455 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2457 // JIT all the allocation details
2458 if (alloc->ShouldRefresh()) {
2460 log->Printf("%s - allocation details not calculated yet, jitting info",
2463 if (!RefreshAllocation(alloc, frame_ptr)) {
2465 log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
2470 assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2471 alloc->element.type_vec_size.isValid() && alloc->size.isValid() &&
2472 "Allocation information not available");
2474 // Allocate a buffer to copy data into
2475 const uint32_t size = *alloc->size.get();
2476 std::shared_ptr<uint8_t> buffer(new uint8_t[size]);
2479 log->Printf("%s - couldn't allocate a %" PRIu32 " byte buffer",
2480 __FUNCTION__, size);
2484 // Read the inferior memory
2486 lldb::addr_t data_ptr = *alloc->data_ptr.get();
2487 GetProcess()->ReadMemory(data_ptr, buffer.get(), size, err);
2490 log->Printf("%s - '%s' Couldn't read %" PRIu32
2491 " bytes of allocation data from 0x%" PRIx64,
2492 __FUNCTION__, err.AsCString(), size, data_ptr);
2499 // Function copies data from a binary file into an allocation.
2500 // There is a header at the start of the file, FileHeader, before the data
2502 // Information from this header is used to display warnings to the user about
2503 // incompatibilities
2504 bool RenderScriptRuntime::LoadAllocation(Stream &strm, const uint32_t alloc_id,
2506 StackFrame *frame_ptr) {
2507 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2509 // Find allocation with the given id
2510 AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
2515 log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__,
2516 *alloc->address.get());
2518 // JIT all the allocation details
2519 if (alloc->ShouldRefresh()) {
2521 log->Printf("%s - allocation details not calculated yet, jitting info.",
2524 if (!RefreshAllocation(alloc, frame_ptr)) {
2526 log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
2531 assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2532 alloc->element.type_vec_size.isValid() && alloc->size.isValid() &&
2533 alloc->element.datum_size.isValid() &&
2534 "Allocation information not available");
2536 // Check we can read from file
2537 FileSpec file(path, true);
2538 if (!file.Exists()) {
2539 strm.Printf("Error: File %s does not exist", path);
2544 if (!file.Readable()) {
2545 strm.Printf("Error: File %s does not have readable permissions", path);
2550 // Read file into data buffer
2551 auto data_sp = DataBufferLLVM::CreateFromPath(file.GetPath());
2553 // Cast start of buffer to FileHeader and use pointer to read metadata
2554 void *file_buf = data_sp->GetBytes();
2555 if (file_buf == nullptr ||
2556 data_sp->GetByteSize() < (sizeof(AllocationDetails::FileHeader) +
2557 sizeof(AllocationDetails::ElementHeader))) {
2558 strm.Printf("Error: File %s does not contain enough data for header", path);
2562 const AllocationDetails::FileHeader *file_header =
2563 static_cast<AllocationDetails::FileHeader *>(file_buf);
2565 // Check file starts with ascii characters "RSAD"
2566 if (memcmp(file_header->ident, "RSAD", 4)) {
2567 strm.Printf("Error: File doesn't contain identifier for an RS allocation "
2568 "dump. Are you sure this is the correct file?");
2573 // Look at the type of the root element in the header
2574 AllocationDetails::ElementHeader root_el_hdr;
2575 memcpy(&root_el_hdr, static_cast<uint8_t *>(file_buf) +
2576 sizeof(AllocationDetails::FileHeader),
2577 sizeof(AllocationDetails::ElementHeader));
2580 log->Printf("%s - header type %" PRIu32 ", element size %" PRIu32,
2581 __FUNCTION__, root_el_hdr.type, root_el_hdr.element_size);
2583 // Check if the target allocation and file both have the same number of bytes
2585 if (*alloc->element.datum_size.get() != root_el_hdr.element_size) {
2586 strm.Printf("Warning: Mismatched Element sizes - file %" PRIu32
2587 " bytes, allocation %" PRIu32 " bytes",
2588 root_el_hdr.element_size, *alloc->element.datum_size.get());
2592 // Check if the target allocation and file both have the same type
2593 const uint32_t alloc_type = static_cast<uint32_t>(*alloc->element.type.get());
2594 const uint32_t file_type = root_el_hdr.type;
2596 if (file_type > Element::RS_TYPE_FONT) {
2597 strm.Printf("Warning: File has unknown allocation type");
2599 } else if (alloc_type != file_type) {
2600 // Enum value isn't monotonous, so doesn't always index RsDataTypeToString
2602 uint32_t target_type_name_idx = alloc_type;
2603 uint32_t head_type_name_idx = file_type;
2604 if (alloc_type >= Element::RS_TYPE_ELEMENT &&
2605 alloc_type <= Element::RS_TYPE_FONT)
2606 target_type_name_idx = static_cast<Element::DataType>(
2607 (alloc_type - Element::RS_TYPE_ELEMENT) +
2608 Element::RS_TYPE_MATRIX_2X2 + 1);
2610 if (file_type >= Element::RS_TYPE_ELEMENT &&
2611 file_type <= Element::RS_TYPE_FONT)
2612 head_type_name_idx = static_cast<Element::DataType>(
2613 (file_type - Element::RS_TYPE_ELEMENT) + Element::RS_TYPE_MATRIX_2X2 +
2616 const char *head_type_name =
2617 AllocationDetails::RsDataTypeToString[head_type_name_idx][0];
2618 const char *target_type_name =
2619 AllocationDetails::RsDataTypeToString[target_type_name_idx][0];
2622 "Warning: Mismatched Types - file '%s' type, allocation '%s' type",
2623 head_type_name, target_type_name);
2627 // Advance buffer past header
2628 file_buf = static_cast<uint8_t *>(file_buf) + file_header->hdr_size;
2630 // Calculate size of allocation data in file
2631 size_t size = data_sp->GetByteSize() - file_header->hdr_size;
2633 // Check if the target allocation and file both have the same total data size.
2634 const uint32_t alloc_size = *alloc->size.get();
2635 if (alloc_size != size) {
2636 strm.Printf("Warning: Mismatched allocation sizes - file 0x%" PRIx64
2637 " bytes, allocation 0x%" PRIx32 " bytes",
2638 (uint64_t)size, alloc_size);
2640 // Set length to copy to minimum
2641 size = alloc_size < size ? alloc_size : size;
2644 // Copy file data from our buffer into the target allocation.
2645 lldb::addr_t alloc_data = *alloc->data_ptr.get();
2647 size_t written = GetProcess()->WriteMemory(alloc_data, file_buf, size, err);
2648 if (!err.Success() || written != size) {
2649 strm.Printf("Error: Couldn't write data to allocation %s", err.AsCString());
2654 strm.Printf("Contents of file '%s' read into allocation %" PRIu32, path,
2661 // Function takes as parameters a byte buffer, which will eventually be written
2662 // to file as the element header, an offset into that buffer, and an Element
2663 // that will be saved into the buffer at the parametrised offset.
2664 // Return value is the new offset after writing the element into the buffer.
2665 // Elements are saved to the file as the ElementHeader struct followed by
2666 // offsets to the structs of all the element's children.
2667 size_t RenderScriptRuntime::PopulateElementHeaders(
2668 const std::shared_ptr<uint8_t> header_buffer, size_t offset,
2669 const Element &elem) {
2670 // File struct for an element header with all the relevant details copied from
2671 // elem. We assume members are valid already.
2672 AllocationDetails::ElementHeader elem_header;
2673 elem_header.type = *elem.type.get();
2674 elem_header.kind = *elem.type_kind.get();
2675 elem_header.element_size = *elem.datum_size.get();
2676 elem_header.vector_size = *elem.type_vec_size.get();
2677 elem_header.array_size =
2678 elem.array_size.isValid() ? *elem.array_size.get() : 0;
2679 const size_t elem_header_size = sizeof(AllocationDetails::ElementHeader);
2681 // Copy struct into buffer and advance offset
2682 // We assume that header_buffer has been checked for nullptr before this
2684 memcpy(header_buffer.get() + offset, &elem_header, elem_header_size);
2685 offset += elem_header_size;
2687 // Starting offset of child ElementHeader struct
2688 size_t child_offset =
2689 offset + ((elem.children.size() + 1) * sizeof(uint32_t));
2690 for (const RenderScriptRuntime::Element &child : elem.children) {
2691 // Recursively populate the buffer with the element header structs of
2692 // children. Then save the offsets where they were set after the parent
2694 memcpy(header_buffer.get() + offset, &child_offset, sizeof(uint32_t));
2695 offset += sizeof(uint32_t);
2697 child_offset = PopulateElementHeaders(header_buffer, child_offset, child);
2700 // Zero indicates no more children
2701 memset(header_buffer.get() + offset, 0, sizeof(uint32_t));
2703 return child_offset;
2706 // Given an Element object this function returns the total size needed in the
2707 // file header to store the element's details. Taking into account the size of
2708 // the element header struct, plus the offsets to all the element's children.
2709 // Function is recursive so that the size of all ancestors is taken into
2711 size_t RenderScriptRuntime::CalculateElementHeaderSize(const Element &elem) {
2712 // Offsets to children plus zero terminator
2713 size_t size = (elem.children.size() + 1) * sizeof(uint32_t);
2714 // Size of header struct with type details
2715 size += sizeof(AllocationDetails::ElementHeader);
2717 // Calculate recursively for all descendants
2718 for (const Element &child : elem.children)
2719 size += CalculateElementHeaderSize(child);
2724 // Function copies allocation contents into a binary file. This file can then be
2725 // loaded later into a different allocation. There is a header, FileHeader,
2726 // before the allocation data containing meta-data.
2727 bool RenderScriptRuntime::SaveAllocation(Stream &strm, const uint32_t alloc_id,
2729 StackFrame *frame_ptr) {
2730 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2732 // Find allocation with the given id
2733 AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
2738 log->Printf("%s - found allocation 0x%" PRIx64 ".", __FUNCTION__,
2739 *alloc->address.get());
2741 // JIT all the allocation details
2742 if (alloc->ShouldRefresh()) {
2744 log->Printf("%s - allocation details not calculated yet, jitting info.",
2747 if (!RefreshAllocation(alloc, frame_ptr)) {
2749 log->Printf("%s - couldn't JIT allocation details.", __FUNCTION__);
2754 assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2755 alloc->element.type_vec_size.isValid() &&
2756 alloc->element.datum_size.get() &&
2757 alloc->element.type_kind.isValid() && alloc->dimension.isValid() &&
2758 "Allocation information not available");
2760 // Check we can create writable file
2761 FileSpec file_spec(path, true);
2762 File file(file_spec, File::eOpenOptionWrite | File::eOpenOptionCanCreate |
2763 File::eOpenOptionTruncate);
2765 strm.Printf("Error: Failed to open '%s' for writing", path);
2770 // Read allocation into buffer of heap memory
2771 const std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
2773 strm.Printf("Error: Couldn't read allocation data into buffer");
2778 // Create the file header
2779 AllocationDetails::FileHeader head;
2780 memcpy(head.ident, "RSAD", 4);
2781 head.dims[0] = static_cast<uint32_t>(alloc->dimension.get()->dim_1);
2782 head.dims[1] = static_cast<uint32_t>(alloc->dimension.get()->dim_2);
2783 head.dims[2] = static_cast<uint32_t>(alloc->dimension.get()->dim_3);
2785 const size_t element_header_size = CalculateElementHeaderSize(alloc->element);
2786 assert((sizeof(AllocationDetails::FileHeader) + element_header_size) <
2788 "Element header too large");
2789 head.hdr_size = static_cast<uint16_t>(sizeof(AllocationDetails::FileHeader) +
2790 element_header_size);
2792 // Write the file header
2793 size_t num_bytes = sizeof(AllocationDetails::FileHeader);
2795 log->Printf("%s - writing File Header, 0x%" PRIx64 " bytes", __FUNCTION__,
2796 (uint64_t)num_bytes);
2798 Error err = file.Write(&head, num_bytes);
2799 if (!err.Success()) {
2800 strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
2805 // Create the headers describing the element type of the allocation.
2806 std::shared_ptr<uint8_t> element_header_buffer(
2807 new uint8_t[element_header_size]);
2808 if (element_header_buffer == nullptr) {
2809 strm.Printf("Internal Error: Couldn't allocate %" PRIu64
2810 " bytes on the heap",
2811 (uint64_t)element_header_size);
2816 PopulateElementHeaders(element_header_buffer, 0, alloc->element);
2818 // Write headers for allocation element type to file
2819 num_bytes = element_header_size;
2821 log->Printf("%s - writing element headers, 0x%" PRIx64 " bytes.",
2822 __FUNCTION__, (uint64_t)num_bytes);
2824 err = file.Write(element_header_buffer.get(), num_bytes);
2825 if (!err.Success()) {
2826 strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
2831 // Write allocation data to file
2832 num_bytes = static_cast<size_t>(*alloc->size.get());
2834 log->Printf("%s - writing 0x%" PRIx64 " bytes", __FUNCTION__,
2835 (uint64_t)num_bytes);
2837 err = file.Write(buffer.get(), num_bytes);
2838 if (!err.Success()) {
2839 strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
2844 strm.Printf("Allocation written to file '%s'", path);
2849 bool RenderScriptRuntime::LoadModule(const lldb::ModuleSP &module_sp) {
2850 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2853 for (const auto &rs_module : m_rsmodules) {
2854 if (rs_module->m_module == module_sp) {
2855 // Check if the user has enabled automatically breaking on
2857 if (m_breakAllKernels)
2858 BreakOnModuleKernels(rs_module);
2863 bool module_loaded = false;
2864 switch (GetModuleKind(module_sp)) {
2865 case eModuleKindKernelObj: {
2866 RSModuleDescriptorSP module_desc;
2867 module_desc.reset(new RSModuleDescriptor(module_sp));
2868 if (module_desc->ParseRSInfo()) {
2869 m_rsmodules.push_back(module_desc);
2870 module_desc->WarnIfVersionMismatch(GetProcess()
2873 .GetAsyncOutputStream()
2875 module_loaded = true;
2877 if (module_loaded) {
2878 FixupScriptDetails(module_desc);
2882 case eModuleKindDriver: {
2883 if (!m_libRSDriver) {
2884 m_libRSDriver = module_sp;
2885 LoadRuntimeHooks(m_libRSDriver, RenderScriptRuntime::eModuleKindDriver);
2889 case eModuleKindImpl: {
2890 if (!m_libRSCpuRef) {
2891 m_libRSCpuRef = module_sp;
2892 LoadRuntimeHooks(m_libRSCpuRef, RenderScriptRuntime::eModuleKindImpl);
2896 case eModuleKindLibRS: {
2898 m_libRS = module_sp;
2899 static ConstString gDbgPresentStr("gDebuggerPresent");
2900 const Symbol *debug_present = m_libRS->FindFirstSymbolWithNameAndType(
2901 gDbgPresentStr, eSymbolTypeData);
2902 if (debug_present) {
2904 uint32_t flag = 0x00000001U;
2905 Target &target = GetProcess()->GetTarget();
2906 addr_t addr = debug_present->GetLoadAddress(&target);
2907 GetProcess()->WriteMemory(addr, &flag, sizeof(flag), err);
2908 if (err.Success()) {
2910 log->Printf("%s - debugger present flag set on debugee.",
2913 m_debuggerPresentFlagged = true;
2915 log->Printf("%s - error writing debugger present flags '%s' ",
2916 __FUNCTION__, err.AsCString());
2920 "%s - error writing debugger present flags - symbol not found",
2931 return module_loaded;
2936 void RenderScriptRuntime::Update() {
2937 if (m_rsmodules.size() > 0) {
2944 void RSModuleDescriptor::WarnIfVersionMismatch(lldb_private::Stream *s) const {
2948 if (m_slang_version.empty() || m_bcc_version.empty()) {
2949 s->PutCString("WARNING: Unknown bcc or slang (llvm-rs-cc) version; debug "
2950 "experience may be unreliable");
2952 } else if (m_slang_version != m_bcc_version) {
2953 s->Printf("WARNING: The debug info emitted by the slang frontend "
2954 "(llvm-rs-cc) used to build this module (%s) does not match the "
2955 "version of bcc used to generate the debug information (%s). "
2956 "This is an unsupported configuration and may result in a poor "
2957 "debugging experience; proceed with caution",
2958 m_slang_version.c_str(), m_bcc_version.c_str());
2963 bool RSModuleDescriptor::ParsePragmaCount(llvm::StringRef *lines,
2965 // Skip the pragma prototype line
2967 for (; n_lines--; ++lines) {
2968 const auto kv_pair = lines->split(" - ");
2969 m_pragmas[kv_pair.first.trim().str()] = kv_pair.second.trim().str();
2974 bool RSModuleDescriptor::ParseExportReduceCount(llvm::StringRef *lines,
2976 // The list of reduction kernels in the `.rs.info` symbol is of the form
2977 // "signature - accumulatordatasize - reduction_name - initializer_name -
2978 // accumulator_name - combiner_name -
2979 // outconverter_name - halter_name"
2980 // Where a function is not explicitly named by the user, or is not generated
2981 // by the compiler, it is named "." so the
2982 // dash separated list should always be 8 items long
2983 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
2984 // Skip the exportReduceCount line
2986 for (; n_lines--; ++lines) {
2987 llvm::SmallVector<llvm::StringRef, 8> spec;
2988 lines->split(spec, " - ");
2989 if (spec.size() != 8) {
2990 if (spec.size() < 8) {
2992 log->Error("Error parsing RenderScript reduction spec. wrong number "
2996 log->Warning("Extraneous members in reduction spec: '%s'",
2997 lines->str().c_str());
3000 const auto sig_s = spec[0];
3002 if (sig_s.getAsInteger(10, sig)) {
3004 log->Error("Error parsing Renderscript reduction spec: invalid kernel "
3006 sig_s.str().c_str());
3010 const auto accum_data_size_s = spec[1];
3011 uint32_t accum_data_size;
3012 if (accum_data_size_s.getAsInteger(10, accum_data_size)) {
3014 log->Error("Error parsing Renderscript reduction spec: invalid "
3015 "accumulator data size %s",
3016 accum_data_size_s.str().c_str());
3021 log->Printf("Found RenderScript reduction '%s'", spec[2].str().c_str());
3023 m_reductions.push_back(RSReductionDescriptor(this, sig, accum_data_size,
3024 spec[2], spec[3], spec[4],
3025 spec[5], spec[6], spec[7]));
3030 bool RSModuleDescriptor::ParseVersionInfo(llvm::StringRef *lines,
3032 // Skip the versionInfo line
3034 for (; n_lines--; ++lines) {
3035 // We're only interested in bcc and slang versions, and ignore all other
3036 // versionInfo lines
3037 const auto kv_pair = lines->split(" - ");
3038 if (kv_pair.first == "slang")
3039 m_slang_version = kv_pair.second.str();
3040 else if (kv_pair.first == "bcc")
3041 m_bcc_version = kv_pair.second.str();
3046 bool RSModuleDescriptor::ParseExportForeachCount(llvm::StringRef *lines,
3048 // Skip the exportForeachCount line
3050 for (; n_lines--; ++lines) {
3052 // `forEach` kernels are listed in the `.rs.info` packet as a "slot - name"
3054 const auto kv_pair = lines->split(" - ");
3055 if (kv_pair.first.getAsInteger(10, slot))
3057 m_kernels.push_back(RSKernelDescriptor(this, kv_pair.second, slot));
3062 bool RSModuleDescriptor::ParseExportVarCount(llvm::StringRef *lines,
3064 // Skip the ExportVarCount line
3066 for (; n_lines--; ++lines)
3067 m_globals.push_back(RSGlobalDescriptor(this, *lines));
3071 // The .rs.info symbol in renderscript modules contains a string which needs to
3073 // The string is basic and is parsed on a line by line basis.
3074 bool RSModuleDescriptor::ParseRSInfo() {
3076 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3077 const Symbol *info_sym = m_module->FindFirstSymbolWithNameAndType(
3078 ConstString(".rs.info"), eSymbolTypeData);
3082 const addr_t addr = info_sym->GetAddressRef().GetFileAddress();
3083 if (addr == LLDB_INVALID_ADDRESS)
3086 const addr_t size = info_sym->GetByteSize();
3087 const FileSpec fs = m_module->GetFileSpec();
3089 auto buffer = DataBufferLLVM::CreateSliceFromPath(fs.GetPath(), size, addr);
3093 // split rs.info. contents into lines
3094 llvm::SmallVector<llvm::StringRef, 128> info_lines;
3096 const llvm::StringRef raw_rs_info((const char *)buffer->GetBytes());
3097 raw_rs_info.split(info_lines, '\n');
3099 log->Printf("'.rs.info symbol for '%s':\n%s",
3100 m_module->GetFileSpec().GetCString(),
3101 raw_rs_info.str().c_str());
3114 const auto rs_info_handler = [](llvm::StringRef name) -> int {
3115 return llvm::StringSwitch<int>(name)
3116 // The number of visible global variables in the script
3117 .Case("exportVarCount", eExportVar)
3118 // The number of RenderScrip `forEach` kernels __attribute__((kernel))
3119 .Case("exportForEachCount", eExportForEach)
3120 // The number of generalreductions: This marked in the script by
3121 // `#pragma reduce()`
3122 .Case("exportReduceCount", eExportReduce)
3123 // Total count of all RenderScript specific `#pragmas` used in the
3125 .Case("pragmaCount", ePragma)
3126 .Case("objectSlotCount", eObjectSlot)
3127 .Case("versionInfo", eVersionInfo)
3131 // parse all text lines of .rs.info
3132 for (auto line = info_lines.begin(); line != info_lines.end(); ++line) {
3133 const auto kv_pair = line->split(": ");
3134 const auto key = kv_pair.first;
3135 const auto val = kv_pair.second.trim();
3137 const auto handler = rs_info_handler(key);
3140 // getAsInteger returns `true` on an error condition - we're only interested
3141 // in numeric fields at the moment
3143 if (val.getAsInteger(10, n_lines)) {
3144 LLDB_LOGV(log, "Failed to parse non-numeric '.rs.info' section {0}",
3148 if (info_lines.end() - (line + 1) < (ptrdiff_t)n_lines)
3151 bool success = false;
3154 success = ParseExportVarCount(line, n_lines);
3156 case eExportForEach:
3157 success = ParseExportForeachCount(line, n_lines);
3160 success = ParseExportReduceCount(line, n_lines);
3163 success = ParsePragmaCount(line, n_lines);
3166 success = ParseVersionInfo(line, n_lines);
3170 log->Printf("%s - skipping .rs.info field '%s'", __FUNCTION__,
3171 line->str().c_str());
3179 return info_lines.size() > 0;
3182 void RenderScriptRuntime::Status(Stream &strm) const {
3184 strm.Printf("Runtime Library discovered.");
3187 if (m_libRSDriver) {
3188 strm.Printf("Runtime Driver discovered.");
3191 if (m_libRSCpuRef) {
3192 strm.Printf("CPU Reference Implementation discovered.");
3196 if (m_runtimeHooks.size()) {
3197 strm.Printf("Runtime functions hooked:");
3199 for (auto b : m_runtimeHooks) {
3200 strm.Indent(b.second->defn->name);
3204 strm.Printf("Runtime is not hooked.");
3209 void RenderScriptRuntime::DumpContexts(Stream &strm) const {
3210 strm.Printf("Inferred RenderScript Contexts:");
3214 std::map<addr_t, uint64_t> contextReferences;
3216 // Iterate over all of the currently discovered scripts.
3217 // Note: We cant push or pop from m_scripts inside this loop or it may
3218 // invalidate script.
3219 for (const auto &script : m_scripts) {
3220 if (!script->context.isValid())
3222 lldb::addr_t context = *script->context;
3224 if (contextReferences.find(context) != contextReferences.end()) {
3225 contextReferences[context]++;
3227 contextReferences[context] = 1;
3231 for (const auto &cRef : contextReferences) {
3232 strm.Printf("Context 0x%" PRIx64 ": %" PRIu64 " script instances",
3233 cRef.first, cRef.second);
3239 void RenderScriptRuntime::DumpKernels(Stream &strm) const {
3240 strm.Printf("RenderScript Kernels:");
3243 for (const auto &module : m_rsmodules) {
3244 strm.Printf("Resource '%s':", module->m_resname.c_str());
3246 for (const auto &kernel : module->m_kernels) {
3247 strm.Indent(kernel.m_name.AsCString());
3254 RenderScriptRuntime::AllocationDetails *
3255 RenderScriptRuntime::FindAllocByID(Stream &strm, const uint32_t alloc_id) {
3256 AllocationDetails *alloc = nullptr;
3258 // See if we can find allocation using id as an index;
3259 if (alloc_id <= m_allocations.size() && alloc_id != 0 &&
3260 m_allocations[alloc_id - 1]->id == alloc_id) {
3261 alloc = m_allocations[alloc_id - 1].get();
3265 // Fallback to searching
3266 for (const auto &a : m_allocations) {
3267 if (a->id == alloc_id) {
3273 if (alloc == nullptr) {
3274 strm.Printf("Error: Couldn't find allocation with id matching %" PRIu32,
3282 // Prints the contents of an allocation to the output stream, which may be a
3284 bool RenderScriptRuntime::DumpAllocation(Stream &strm, StackFrame *frame_ptr,
3285 const uint32_t id) {
3286 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3288 // Check we can find the desired allocation
3289 AllocationDetails *alloc = FindAllocByID(strm, id);
3291 return false; // FindAllocByID() will print error message for us here
3294 log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__,
3295 *alloc->address.get());
3297 // Check we have information about the allocation, if not calculate it
3298 if (alloc->ShouldRefresh()) {
3300 log->Printf("%s - allocation details not calculated yet, jitting info.",
3303 // JIT all the allocation information
3304 if (!RefreshAllocation(alloc, frame_ptr)) {
3305 strm.Printf("Error: Couldn't JIT allocation details");
3311 // Establish format and size of each data element
3312 const uint32_t vec_size = *alloc->element.type_vec_size.get();
3313 const Element::DataType type = *alloc->element.type.get();
3315 assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
3316 "Invalid allocation type");
3318 lldb::Format format;
3319 if (type >= Element::RS_TYPE_ELEMENT)
3320 format = eFormatHex;
3322 format = vec_size == 1
3323 ? static_cast<lldb::Format>(
3324 AllocationDetails::RSTypeToFormat[type][eFormatSingle])
3325 : static_cast<lldb::Format>(
3326 AllocationDetails::RSTypeToFormat[type][eFormatVector]);
3328 const uint32_t data_size = *alloc->element.datum_size.get();
3331 log->Printf("%s - element size %" PRIu32 " bytes, including padding",
3332 __FUNCTION__, data_size);
3334 // Allocate a buffer to copy data into
3335 std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
3337 strm.Printf("Error: Couldn't read allocation data");
3342 // Calculate stride between rows as there may be padding at end of rows since
3343 // allocated memory is 16-byte aligned
3344 if (!alloc->stride.isValid()) {
3345 if (alloc->dimension.get()->dim_2 == 0) // We only have one dimension
3347 else if (!JITAllocationStride(alloc, frame_ptr)) {
3348 strm.Printf("Error: Couldn't calculate allocation row stride");
3353 const uint32_t stride = *alloc->stride.get();
3354 const uint32_t size = *alloc->size.get(); // Size of whole allocation
3355 const uint32_t padding =
3356 alloc->element.padding.isValid() ? *alloc->element.padding.get() : 0;
3358 log->Printf("%s - stride %" PRIu32 " bytes, size %" PRIu32
3359 " bytes, padding %" PRIu32,
3360 __FUNCTION__, stride, size, padding);
3362 // Find dimensions used to index loops, so need to be non-zero
3363 uint32_t dim_x = alloc->dimension.get()->dim_1;
3364 dim_x = dim_x == 0 ? 1 : dim_x;
3366 uint32_t dim_y = alloc->dimension.get()->dim_2;
3367 dim_y = dim_y == 0 ? 1 : dim_y;
3369 uint32_t dim_z = alloc->dimension.get()->dim_3;
3370 dim_z = dim_z == 0 ? 1 : dim_z;
3372 // Use data extractor to format output
3373 const uint32_t target_ptr_size =
3374 GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
3375 DataExtractor alloc_data(buffer.get(), size, GetProcess()->GetByteOrder(),
3378 uint32_t offset = 0; // Offset in buffer to next element to be printed
3379 uint32_t prev_row = 0; // Offset to the start of the previous row
3381 // Iterate over allocation dimensions, printing results to user
3382 strm.Printf("Data (X, Y, Z):");
3383 for (uint32_t z = 0; z < dim_z; ++z) {
3384 for (uint32_t y = 0; y < dim_y; ++y) {
3385 // Use stride to index start of next row.
3386 if (!(y == 0 && z == 0))
3387 offset = prev_row + stride;
3390 // Print each element in the row individually
3391 for (uint32_t x = 0; x < dim_x; ++x) {
3392 strm.Printf("\n(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ") = ", x, y, z);
3393 if ((type == Element::RS_TYPE_NONE) &&
3394 (alloc->element.children.size() > 0) &&
3395 (alloc->element.type_name != Element::GetFallbackStructName())) {
3396 // Here we are dumping an Element of struct type.
3397 // This is done using expression evaluation with the name of the
3398 // struct type and pointer to element.
3399 // Don't print the name of the resulting expression, since this will
3401 DumpValueObjectOptions expr_options;
3402 expr_options.SetHideName(true);
3404 // Setup expression as derefrencing a pointer cast to element address.
3405 char expr_char_buffer[jit_max_expr_size];
3407 snprintf(expr_char_buffer, jit_max_expr_size, "*(%s*) 0x%" PRIx64,
3408 alloc->element.type_name.AsCString(),
3409 *alloc->data_ptr.get() + offset);
3411 if (written < 0 || written >= jit_max_expr_size) {
3413 log->Printf("%s - error in snprintf().", __FUNCTION__);
3417 // Evaluate expression
3418 ValueObjectSP expr_result;
3419 GetProcess()->GetTarget().EvaluateExpression(expr_char_buffer,
3420 frame_ptr, expr_result);
3422 // Print the results to our stream.
3423 expr_result->Dump(strm, expr_options);
3425 DumpDataExtractor(alloc_data, &strm, offset, format,
3426 data_size - padding, 1, 1, LLDB_INVALID_ADDRESS, 0,
3429 offset += data_size;
3438 // Function recalculates all our cached information about allocations by jitting
3439 // the RS runtime regarding each allocation we know about. Returns true if all
3440 // allocations could be recomputed, false otherwise.
3441 bool RenderScriptRuntime::RecomputeAllAllocations(Stream &strm,
3442 StackFrame *frame_ptr) {
3443 bool success = true;
3444 for (auto &alloc : m_allocations) {
3445 // JIT current allocation information
3446 if (!RefreshAllocation(alloc.get(), frame_ptr)) {
3447 strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32
3455 strm.Printf("All allocations successfully recomputed");
3461 // Prints information regarding currently loaded allocations. These details are
3462 // gathered by jitting the runtime, which has as latency. Index parameter
3463 // specifies a single allocation ID to print, or a zero value to print them all
3464 void RenderScriptRuntime::ListAllocations(Stream &strm, StackFrame *frame_ptr,
3465 const uint32_t index) {
3466 strm.Printf("RenderScript Allocations:");
3470 for (auto &alloc : m_allocations) {
3471 // index will only be zero if we want to print all allocations
3472 if (index != 0 && index != alloc->id)
3475 // JIT current allocation information
3476 if (alloc->ShouldRefresh() && !RefreshAllocation(alloc.get(), frame_ptr)) {
3477 strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32,
3483 strm.Printf("%" PRIu32 ":", alloc->id);
3487 strm.Indent("Context: ");
3488 if (!alloc->context.isValid())
3489 strm.Printf("unknown\n");
3491 strm.Printf("0x%" PRIx64 "\n", *alloc->context.get());
3493 strm.Indent("Address: ");
3494 if (!alloc->address.isValid())
3495 strm.Printf("unknown\n");
3497 strm.Printf("0x%" PRIx64 "\n", *alloc->address.get());
3499 strm.Indent("Data pointer: ");
3500 if (!alloc->data_ptr.isValid())
3501 strm.Printf("unknown\n");
3503 strm.Printf("0x%" PRIx64 "\n", *alloc->data_ptr.get());
3505 strm.Indent("Dimensions: ");
3506 if (!alloc->dimension.isValid())
3507 strm.Printf("unknown\n");
3509 strm.Printf("(%" PRId32 ", %" PRId32 ", %" PRId32 ")\n",
3510 alloc->dimension.get()->dim_1, alloc->dimension.get()->dim_2,
3511 alloc->dimension.get()->dim_3);
3513 strm.Indent("Data Type: ");
3514 if (!alloc->element.type.isValid() ||
3515 !alloc->element.type_vec_size.isValid())
3516 strm.Printf("unknown\n");
3518 const int vector_size = *alloc->element.type_vec_size.get();
3519 Element::DataType type = *alloc->element.type.get();
3521 if (!alloc->element.type_name.IsEmpty())
3522 strm.Printf("%s\n", alloc->element.type_name.AsCString());
3524 // Enum value isn't monotonous, so doesn't always index
3525 // RsDataTypeToString array
3526 if (type >= Element::RS_TYPE_ELEMENT && type <= Element::RS_TYPE_FONT)
3528 static_cast<Element::DataType>((type - Element::RS_TYPE_ELEMENT) +
3529 Element::RS_TYPE_MATRIX_2X2 + 1);
3531 if (type >= (sizeof(AllocationDetails::RsDataTypeToString) /
3532 sizeof(AllocationDetails::RsDataTypeToString[0])) ||
3533 vector_size > 4 || vector_size < 1)
3534 strm.Printf("invalid type\n");
3538 AllocationDetails::RsDataTypeToString[static_cast<uint32_t>(type)]
3543 strm.Indent("Data Kind: ");
3544 if (!alloc->element.type_kind.isValid())
3545 strm.Printf("unknown\n");
3547 const Element::DataKind kind = *alloc->element.type_kind.get();
3548 if (kind < Element::RS_KIND_USER || kind > Element::RS_KIND_PIXEL_YUV)
3549 strm.Printf("invalid kind\n");
3553 AllocationDetails::RsDataKindToString[static_cast<uint32_t>(kind)]);
3562 // Set breakpoints on every kernel found in RS module
3563 void RenderScriptRuntime::BreakOnModuleKernels(
3564 const RSModuleDescriptorSP rsmodule_sp) {
3565 for (const auto &kernel : rsmodule_sp->m_kernels) {
3566 // Don't set breakpoint on 'root' kernel
3567 if (strcmp(kernel.m_name.AsCString(), "root") == 0)
3570 CreateKernelBreakpoint(kernel.m_name);
3574 // Method is internally called by the 'kernel breakpoint all' command to enable
3575 // or disable breaking on all kernels. When do_break is true we want to enable
3576 // this functionality. When do_break is false we want to disable it.
3577 void RenderScriptRuntime::SetBreakAllKernels(bool do_break, TargetSP target) {
3579 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3581 InitSearchFilter(target);
3583 // Set breakpoints on all the kernels
3584 if (do_break && !m_breakAllKernels) {
3585 m_breakAllKernels = true;
3587 for (const auto &module : m_rsmodules)
3588 BreakOnModuleKernels(module);
3591 log->Printf("%s(True) - breakpoints set on all currently loaded kernels.",
3593 } else if (!do_break &&
3594 m_breakAllKernels) // Breakpoints won't be set on any new kernels.
3596 m_breakAllKernels = false;
3599 log->Printf("%s(False) - breakpoints no longer automatically set.",
3604 // Given the name of a kernel this function creates a breakpoint using our
3605 // own breakpoint resolver, and returns the Breakpoint shared pointer.
3607 RenderScriptRuntime::CreateKernelBreakpoint(const ConstString &name) {
3609 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3613 log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
3617 BreakpointResolverSP resolver_sp(new RSBreakpointResolver(nullptr, name));
3618 BreakpointSP bp = GetProcess()->GetTarget().CreateBreakpoint(
3619 m_filtersp, resolver_sp, false, false, false);
3621 // Give RS breakpoints a specific name, so the user can manipulate them as a
3624 if (!bp->AddName("RenderScriptKernel", err))
3626 log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
3633 RenderScriptRuntime::CreateReductionBreakpoint(const ConstString &name,
3636 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3640 log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
3644 BreakpointResolverSP resolver_sp(new RSReduceBreakpointResolver(
3645 nullptr, name, &m_rsmodules, kernel_types));
3646 BreakpointSP bp = GetProcess()->GetTarget().CreateBreakpoint(
3647 m_filtersp, resolver_sp, false, false, false);
3649 // Give RS breakpoints a specific name, so the user can manipulate them as a
3652 if (!bp->AddName("RenderScriptReduction", err))
3654 log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
3660 // Given an expression for a variable this function tries to calculate the
3661 // variable's value. If this is possible it returns true and sets the uint64_t
3662 // parameter to the variables unsigned value. Otherwise function returns false.
3663 bool RenderScriptRuntime::GetFrameVarAsUnsigned(const StackFrameSP frame_sp,
3664 const char *var_name,
3666 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3670 // Find variable in stack frame
3671 ValueObjectSP value_sp(frame_sp->GetValueForVariableExpressionPath(
3672 var_name, eNoDynamicValues,
3673 StackFrame::eExpressionPathOptionCheckPtrVsMember |
3674 StackFrame::eExpressionPathOptionsAllowDirectIVarAccess,
3676 if (!err.Success()) {
3678 log->Printf("%s - error, couldn't find '%s' in frame", __FUNCTION__,
3683 // Find the uint32_t value for the variable
3684 bool success = false;
3685 val = value_sp->GetValueAsUnsigned(0, &success);
3688 log->Printf("%s - error, couldn't parse '%s' as an uint32_t.",
3689 __FUNCTION__, var_name);
3696 // Function attempts to find the current coordinate of a kernel invocation by
3697 // investigating the values of frame variables in the .expand function. These
3698 // coordinates are returned via the coord array reference parameter. Returns
3699 // true if the coordinates could be found, and false otherwise.
3700 bool RenderScriptRuntime::GetKernelCoordinate(RSCoordinate &coord,
3701 Thread *thread_ptr) {
3702 static const char *const x_expr = "rsIndex";
3703 static const char *const y_expr = "p->current.y";
3704 static const char *const z_expr = "p->current.z";
3706 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3710 log->Printf("%s - Error, No thread pointer", __FUNCTION__);
3715 // Walk the call stack looking for a function whose name has the suffix
3716 // '.expand' and contains the variables we're looking for.
3717 for (uint32_t i = 0; i < thread_ptr->GetStackFrameCount(); ++i) {
3718 if (!thread_ptr->SetSelectedFrameByIndex(i))
3721 StackFrameSP frame_sp = thread_ptr->GetSelectedFrame();
3725 // Find the function name
3726 const SymbolContext sym_ctx = frame_sp->GetSymbolContext(false);
3727 const ConstString func_name = sym_ctx.GetFunctionName();
3732 log->Printf("%s - Inspecting function '%s'", __FUNCTION__,
3733 func_name.GetCString());
3735 // Check if function name has .expand suffix
3736 if (!func_name.GetStringRef().endswith(".expand"))
3740 log->Printf("%s - Found .expand function '%s'", __FUNCTION__,
3741 func_name.GetCString());
3743 // Get values for variables in .expand frame that tell us the current kernel
3746 bool found = GetFrameVarAsUnsigned(frame_sp, x_expr, x) &&
3747 GetFrameVarAsUnsigned(frame_sp, y_expr, y) &&
3748 GetFrameVarAsUnsigned(frame_sp, z_expr, z);
3751 // The RenderScript runtime uses uint32_t for these vars. If they're not
3752 // within bounds, our frame parsing is garbage
3753 assert(x <= UINT32_MAX && y <= UINT32_MAX && z <= UINT32_MAX);
3754 coord.x = (uint32_t)x;
3755 coord.y = (uint32_t)y;
3756 coord.z = (uint32_t)z;
3763 // Callback when a kernel breakpoint hits and we're looking for a specific
3764 // coordinate. Baton parameter contains a pointer to the target coordinate we
3765 // want to break on.
3766 // Function then checks the .expand frame for the current coordinate and breaks
3767 // to user if it matches.
3768 // Parameter 'break_id' is the id of the Breakpoint which made the callback.
3769 // Parameter 'break_loc_id' is the id for the BreakpointLocation which was hit,
3770 // a single logical breakpoint can have multiple addresses.
3771 bool RenderScriptRuntime::KernelBreakpointHit(void *baton,
3772 StoppointCallbackContext *ctx,
3774 user_id_t break_loc_id) {
3776 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3779 "Error: null baton in conditional kernel breakpoint callback");
3781 // Coordinate we want to stop on
3782 RSCoordinate target_coord = *static_cast<RSCoordinate *>(baton);
3785 log->Printf("%s - Break ID %" PRIu64 ", " FMT_COORD, __FUNCTION__, break_id,
3786 target_coord.x, target_coord.y, target_coord.z);
3788 // Select current thread
3789 ExecutionContext context(ctx->exe_ctx_ref);
3790 Thread *thread_ptr = context.GetThreadPtr();
3791 assert(thread_ptr && "Null thread pointer");
3793 // Find current kernel invocation from .expand frame variables
3794 RSCoordinate current_coord{};
3795 if (!GetKernelCoordinate(current_coord, thread_ptr)) {
3797 log->Printf("%s - Error, couldn't select .expand stack frame",
3803 log->Printf("%s - " FMT_COORD, __FUNCTION__, current_coord.x,
3804 current_coord.y, current_coord.z);
3806 // Check if the current kernel invocation coordinate matches our target
3808 if (target_coord == current_coord) {
3810 log->Printf("%s, BREAKING " FMT_COORD, __FUNCTION__, current_coord.x,
3811 current_coord.y, current_coord.z);
3813 BreakpointSP breakpoint_sp =
3814 context.GetTargetPtr()->GetBreakpointByID(break_id);
3815 assert(breakpoint_sp != nullptr &&
3816 "Error: Couldn't find breakpoint matching break id for callback");
3817 breakpoint_sp->SetEnabled(false); // Optimise since conditional breakpoint
3818 // should only be hit once.
3822 // No match on coordinate
3826 void RenderScriptRuntime::SetConditional(BreakpointSP bp, Stream &messages,
3827 const RSCoordinate &coord) {
3828 messages.Printf("Conditional kernel breakpoint on coordinate " FMT_COORD,
3829 coord.x, coord.y, coord.z);
3832 // Allocate memory for the baton, and copy over coordinate
3833 RSCoordinate *baton = new RSCoordinate(coord);
3835 // Create a callback that will be invoked every time the breakpoint is hit.
3836 // The baton object passed to the handler is the target coordinate we want to
3838 bp->SetCallback(KernelBreakpointHit, baton, true);
3840 // Store a shared pointer to the baton, so the memory will eventually be
3841 // cleaned up after destruction
3842 m_conditional_breaks[bp->GetID()] = std::unique_ptr<RSCoordinate>(baton);
3845 // Tries to set a breakpoint on the start of a kernel, resolved using the kernel
3846 // name. Argument 'coords', represents a three dimensional coordinate which can
3848 // used to specify a single kernel instance to break on. If this is set then we
3850 // to the breakpoint.
3851 bool RenderScriptRuntime::PlaceBreakpointOnKernel(TargetSP target,
3854 const RSCoordinate *coord) {
3858 InitSearchFilter(target);
3860 ConstString kernel_name(name);
3861 BreakpointSP bp = CreateKernelBreakpoint(kernel_name);
3865 // We have a conditional breakpoint on a specific coordinate
3867 SetConditional(bp, messages, *coord);
3869 bp->GetDescription(&messages, lldb::eDescriptionLevelInitial, false);
3875 RenderScriptRuntime::CreateScriptGroupBreakpoint(const ConstString &name,
3878 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3882 log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
3886 BreakpointResolverSP resolver_sp(new RSScriptGroupBreakpointResolver(
3887 nullptr, name, m_scriptGroups, stop_on_all));
3888 BreakpointSP bp = GetProcess()->GetTarget().CreateBreakpoint(
3889 m_filtersp, resolver_sp, false, false, false);
3890 // Give RS breakpoints a specific name, so the user can manipulate them as a
3893 if (!bp->AddName(name.AsCString(), err))
3895 log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
3897 // ask the breakpoint to resolve itself
3898 bp->ResolveBreakpoint();
3902 bool RenderScriptRuntime::PlaceBreakpointOnScriptGroup(TargetSP target,
3904 const ConstString &name,
3906 InitSearchFilter(target);
3907 BreakpointSP bp = CreateScriptGroupBreakpoint(name, multi);
3909 bp->GetDescription(&strm, lldb::eDescriptionLevelInitial, false);
3913 bool RenderScriptRuntime::PlaceBreakpointOnReduction(TargetSP target,
3915 const char *reduce_name,
3916 const RSCoordinate *coord,
3921 InitSearchFilter(target);
3923 CreateReductionBreakpoint(ConstString(reduce_name), kernel_types);
3928 SetConditional(bp, messages, *coord);
3930 bp->GetDescription(&messages, lldb::eDescriptionLevelInitial, false);
3935 void RenderScriptRuntime::DumpModules(Stream &strm) const {
3936 strm.Printf("RenderScript Modules:");
3939 for (const auto &module : m_rsmodules) {
3945 RenderScriptRuntime::ScriptDetails *
3946 RenderScriptRuntime::LookUpScript(addr_t address, bool create) {
3947 for (const auto &s : m_scripts) {
3948 if (s->script.isValid())
3949 if (*s->script == address)
3953 std::unique_ptr<ScriptDetails> s(new ScriptDetails);
3954 s->script = address;
3955 m_scripts.push_back(std::move(s));
3956 return m_scripts.back().get();
3961 RenderScriptRuntime::AllocationDetails *
3962 RenderScriptRuntime::LookUpAllocation(addr_t address) {
3963 for (const auto &a : m_allocations) {
3964 if (a->address.isValid())
3965 if (*a->address == address)
3971 RenderScriptRuntime::AllocationDetails *
3972 RenderScriptRuntime::CreateAllocation(addr_t address) {
3973 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
3975 // Remove any previous allocation which contains the same address
3976 auto it = m_allocations.begin();
3977 while (it != m_allocations.end()) {
3978 if (*((*it)->address) == address) {
3980 log->Printf("%s - Removing allocation id: %d, address: 0x%" PRIx64,
3981 __FUNCTION__, (*it)->id, address);
3983 it = m_allocations.erase(it);
3989 std::unique_ptr<AllocationDetails> a(new AllocationDetails);
3990 a->address = address;
3991 m_allocations.push_back(std::move(a));
3992 return m_allocations.back().get();
3995 bool RenderScriptRuntime::ResolveKernelName(lldb::addr_t kernel_addr,
3996 ConstString &name) {
3997 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS);
3999 Target &target = GetProcess()->GetTarget();
4001 // RenderScript module
4002 if (!target.GetSectionLoadList().ResolveLoadAddress(kernel_addr, resolved)) {
4004 log->Printf("%s: unable to resolve 0x%" PRIx64 " to a loaded symbol",
4005 __FUNCTION__, kernel_addr);
4009 Symbol *sym = resolved.CalculateSymbolContextSymbol();
4013 name = sym->GetName();
4014 assert(IsRenderScriptModule(resolved.CalculateSymbolContextModule()));
4016 log->Printf("%s: 0x%" PRIx64 " resolved to the symbol '%s'", __FUNCTION__,
4017 kernel_addr, name.GetCString());
4021 void RSModuleDescriptor::Dump(Stream &strm) const {
4022 int indent = strm.GetIndentLevel();
4025 m_module->GetFileSpec().Dump(&strm);
4026 strm.Indent(m_module->GetNumCompileUnits() ? "Debug info loaded."
4027 : "Debug info does not exist.");
4032 strm.Printf("Globals: %" PRIu64, static_cast<uint64_t>(m_globals.size()));
4035 for (const auto &global : m_globals) {
4041 strm.Printf("Kernels: %" PRIu64, static_cast<uint64_t>(m_kernels.size()));
4044 for (const auto &kernel : m_kernels) {
4050 strm.Printf("Pragmas: %" PRIu64, static_cast<uint64_t>(m_pragmas.size()));
4053 for (const auto &key_val : m_pragmas) {
4055 strm.Printf("%s: %s", key_val.first.c_str(), key_val.second.c_str());
4061 strm.Printf("Reductions: %" PRIu64,
4062 static_cast<uint64_t>(m_reductions.size()));
4065 for (const auto &reduction : m_reductions) {
4066 reduction.Dump(strm);
4069 strm.SetIndentLevel(indent);
4072 void RSGlobalDescriptor::Dump(Stream &strm) const {
4073 strm.Indent(m_name.AsCString());
4074 VariableList var_list;
4075 m_module->m_module->FindGlobalVariables(m_name, nullptr, true, 1U, var_list);
4076 if (var_list.GetSize() == 1) {
4077 auto var = var_list.GetVariableAtIndex(0);
4078 auto type = var->GetType();
4081 type->DumpTypeName(&strm);
4083 strm.Printf(" - Unknown Type");
4086 strm.Printf(" - variable identified, but not found in binary");
4087 const Symbol *s = m_module->m_module->FindFirstSymbolWithNameAndType(
4088 m_name, eSymbolTypeData);
4090 strm.Printf(" (symbol exists) ");
4097 void RSKernelDescriptor::Dump(Stream &strm) const {
4098 strm.Indent(m_name.AsCString());
4102 void RSReductionDescriptor::Dump(lldb_private::Stream &stream) const {
4103 stream.Indent(m_reduce_name.AsCString());
4104 stream.IndentMore();
4107 stream.Printf("accumulator: %s", m_accum_name.AsCString());
4110 stream.Printf("initializer: %s", m_init_name.AsCString());
4113 stream.Printf("combiner: %s", m_comb_name.AsCString());
4116 stream.Printf("outconverter: %s", m_outc_name.AsCString());
4118 // XXX This is currently unspecified by RenderScript, and unused
4120 // stream.Printf("halter: '%s'", m_init_name.AsCString());
4122 stream.IndentLess();
4125 class CommandObjectRenderScriptRuntimeModuleDump : public CommandObjectParsed {
4127 CommandObjectRenderScriptRuntimeModuleDump(CommandInterpreter &interpreter)
4128 : CommandObjectParsed(
4129 interpreter, "renderscript module dump",
4130 "Dumps renderscript specific information for all modules.",
4131 "renderscript module dump",
4132 eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
4134 ~CommandObjectRenderScriptRuntimeModuleDump() override = default;
4136 bool DoExecute(Args &command, CommandReturnObject &result) override {
4137 RenderScriptRuntime *runtime =
4138 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4139 eLanguageTypeExtRenderScript);
4140 runtime->DumpModules(result.GetOutputStream());
4141 result.SetStatus(eReturnStatusSuccessFinishResult);
4146 class CommandObjectRenderScriptRuntimeModule : public CommandObjectMultiword {
4148 CommandObjectRenderScriptRuntimeModule(CommandInterpreter &interpreter)
4149 : CommandObjectMultiword(interpreter, "renderscript module",
4150 "Commands that deal with RenderScript modules.",
4153 "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleDump(
4157 ~CommandObjectRenderScriptRuntimeModule() override = default;
4160 class CommandObjectRenderScriptRuntimeKernelList : public CommandObjectParsed {
4162 CommandObjectRenderScriptRuntimeKernelList(CommandInterpreter &interpreter)
4163 : CommandObjectParsed(
4164 interpreter, "renderscript kernel list",
4165 "Lists renderscript kernel names and associated script resources.",
4166 "renderscript kernel list",
4167 eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
4169 ~CommandObjectRenderScriptRuntimeKernelList() override = default;
4171 bool DoExecute(Args &command, CommandReturnObject &result) override {
4172 RenderScriptRuntime *runtime =
4173 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4174 eLanguageTypeExtRenderScript);
4175 runtime->DumpKernels(result.GetOutputStream());
4176 result.SetStatus(eReturnStatusSuccessFinishResult);
4181 static OptionDefinition g_renderscript_reduction_bp_set_options[] = {
4182 {LLDB_OPT_SET_1, false, "function-role", 't',
4183 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeOneLiner,
4184 "Break on a comma separated set of reduction kernel types "
4185 "(accumulator,outcoverter,combiner,initializer"},
4186 {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument,
4187 nullptr, nullptr, 0, eArgTypeValue,
4188 "Set a breakpoint on a single invocation of the kernel with specified "
4190 "Coordinate takes the form 'x[,y][,z] where x,y,z are positive "
4191 "integers representing kernel dimensions. "
4192 "Any unset dimensions will be defaulted to zero."}};
4194 class CommandObjectRenderScriptRuntimeReductionBreakpointSet
4195 : public CommandObjectParsed {
4197 CommandObjectRenderScriptRuntimeReductionBreakpointSet(
4198 CommandInterpreter &interpreter)
4199 : CommandObjectParsed(
4200 interpreter, "renderscript reduction breakpoint set",
4201 "Set a breakpoint on named RenderScript general reductions",
4202 "renderscript reduction breakpoint set <kernel_name> [-t "
4203 "<reduction_kernel_type,...>]",
4204 eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4205 eCommandProcessMustBePaused),
4208 class CommandOptions : public Options {
4212 m_kernel_types(RSReduceBreakpointResolver::eKernelTypeAll) {}
4214 ~CommandOptions() override = default;
4216 Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4217 ExecutionContext *exe_ctx) override {
4219 StreamString err_str;
4220 const int short_option = m_getopt_table[option_idx].val;
4221 switch (short_option) {
4223 if (!ParseReductionTypes(option_arg, err_str))
4224 err.SetErrorStringWithFormat(
4225 "Unable to deduce reduction types for %s: %s",
4226 option_arg.str().c_str(), err_str.GetData());
4229 auto coord = RSCoordinate{};
4230 if (!ParseCoordinate(option_arg, coord))
4231 err.SetErrorStringWithFormat("unable to parse coordinate for %s",
4232 option_arg.str().c_str());
4234 m_have_coord = true;
4240 err.SetErrorStringWithFormat("Invalid option '-%c'", short_option);
4245 void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4246 m_have_coord = false;
4249 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4250 return llvm::makeArrayRef(g_renderscript_reduction_bp_set_options);
4253 bool ParseReductionTypes(llvm::StringRef option_val,
4254 StreamString &err_str) {
4255 m_kernel_types = RSReduceBreakpointResolver::eKernelTypeNone;
4256 const auto reduce_name_to_type = [](llvm::StringRef name) -> int {
4257 return llvm::StringSwitch<int>(name)
4258 .Case("accumulator", RSReduceBreakpointResolver::eKernelTypeAccum)
4259 .Case("initializer", RSReduceBreakpointResolver::eKernelTypeInit)
4260 .Case("outconverter", RSReduceBreakpointResolver::eKernelTypeOutC)
4261 .Case("combiner", RSReduceBreakpointResolver::eKernelTypeComb)
4262 .Case("all", RSReduceBreakpointResolver::eKernelTypeAll)
4263 // Currently not exposed by the runtime
4264 // .Case("halter", RSReduceBreakpointResolver::eKernelTypeHalter)
4268 // Matching a comma separated list of known words is fairly
4269 // straightforward with PCRE, but we're
4270 // using ERE, so we end up with a little ugliness...
4271 RegularExpression::Match match(/* max_matches */ 5);
4272 RegularExpression match_type_list(
4273 llvm::StringRef("^([[:alpha:]]+)(,[[:alpha:]]+){0,4}$"));
4275 assert(match_type_list.IsValid());
4277 if (!match_type_list.Execute(option_val, &match)) {
4279 "a comma-separated list of kernel types is required");
4283 // splitting on commas is much easier with llvm::StringRef than regex
4284 llvm::SmallVector<llvm::StringRef, 5> type_names;
4285 llvm::StringRef(option_val).split(type_names, ',');
4287 for (const auto &name : type_names) {
4288 const int type = reduce_name_to_type(name);
4290 err_str.Printf("unknown kernel type name %s", name.str().c_str());
4293 m_kernel_types |= type;
4300 llvm::StringRef m_reduce_name;
4301 RSCoordinate m_coord;
4305 Options *GetOptions() override { return &m_options; }
4307 bool DoExecute(Args &command, CommandReturnObject &result) override {
4308 const size_t argc = command.GetArgumentCount();
4310 result.AppendErrorWithFormat("'%s' takes 1 argument of reduction name, "
4311 "and an optional kernel type list",
4312 m_cmd_name.c_str());
4313 result.SetStatus(eReturnStatusFailed);
4317 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4318 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4319 eLanguageTypeExtRenderScript));
4321 auto &outstream = result.GetOutputStream();
4322 auto name = command.GetArgumentAtIndex(0);
4323 auto &target = m_exe_ctx.GetTargetSP();
4324 auto coord = m_options.m_have_coord ? &m_options.m_coord : nullptr;
4325 if (!runtime->PlaceBreakpointOnReduction(target, outstream, name, coord,
4326 m_options.m_kernel_types)) {
4327 result.SetStatus(eReturnStatusFailed);
4328 result.AppendError("Error: unable to place breakpoint on reduction");
4331 result.AppendMessage("Breakpoint(s) created");
4332 result.SetStatus(eReturnStatusSuccessFinishResult);
4337 CommandOptions m_options;
4340 static OptionDefinition g_renderscript_kernel_bp_set_options[] = {
4341 {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument,
4342 nullptr, nullptr, 0, eArgTypeValue,
4343 "Set a breakpoint on a single invocation of the kernel with specified "
4345 "Coordinate takes the form 'x[,y][,z] where x,y,z are positive "
4346 "integers representing kernel dimensions. "
4347 "Any unset dimensions will be defaulted to zero."}};
4349 class CommandObjectRenderScriptRuntimeKernelBreakpointSet
4350 : public CommandObjectParsed {
4352 CommandObjectRenderScriptRuntimeKernelBreakpointSet(
4353 CommandInterpreter &interpreter)
4354 : CommandObjectParsed(
4355 interpreter, "renderscript kernel breakpoint set",
4356 "Sets a breakpoint on a renderscript kernel.",
4357 "renderscript kernel breakpoint set <kernel_name> [-c x,y,z]",
4358 eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4359 eCommandProcessMustBePaused),
4362 ~CommandObjectRenderScriptRuntimeKernelBreakpointSet() override = default;
4364 Options *GetOptions() override { return &m_options; }
4366 class CommandOptions : public Options {
4368 CommandOptions() : Options() {}
4370 ~CommandOptions() override = default;
4372 Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4373 ExecutionContext *exe_ctx) override {
4375 const int short_option = m_getopt_table[option_idx].val;
4377 switch (short_option) {
4379 auto coord = RSCoordinate{};
4380 if (!ParseCoordinate(option_arg, coord))
4381 err.SetErrorStringWithFormat(
4382 "Couldn't parse coordinate '%s', should be in format 'x,y,z'.",
4383 option_arg.str().c_str());
4385 m_have_coord = true;
4391 err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4397 void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4398 m_have_coord = false;
4401 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4402 return llvm::makeArrayRef(g_renderscript_kernel_bp_set_options);
4405 RSCoordinate m_coord;
4409 bool DoExecute(Args &command, CommandReturnObject &result) override {
4410 const size_t argc = command.GetArgumentCount();
4412 result.AppendErrorWithFormat(
4413 "'%s' takes 1 argument of kernel name, and an optional coordinate.",
4414 m_cmd_name.c_str());
4415 result.SetStatus(eReturnStatusFailed);
4419 RenderScriptRuntime *runtime =
4420 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4421 eLanguageTypeExtRenderScript);
4423 auto &outstream = result.GetOutputStream();
4424 auto &target = m_exe_ctx.GetTargetSP();
4425 auto name = command.GetArgumentAtIndex(0);
4426 auto coord = m_options.m_have_coord ? &m_options.m_coord : nullptr;
4427 if (!runtime->PlaceBreakpointOnKernel(target, outstream, name, coord)) {
4428 result.SetStatus(eReturnStatusFailed);
4429 result.AppendErrorWithFormat(
4430 "Error: unable to set breakpoint on kernel '%s'", name);
4434 result.AppendMessage("Breakpoint(s) created");
4435 result.SetStatus(eReturnStatusSuccessFinishResult);
4440 CommandOptions m_options;
4443 class CommandObjectRenderScriptRuntimeKernelBreakpointAll
4444 : public CommandObjectParsed {
4446 CommandObjectRenderScriptRuntimeKernelBreakpointAll(
4447 CommandInterpreter &interpreter)
4448 : CommandObjectParsed(
4449 interpreter, "renderscript kernel breakpoint all",
4450 "Automatically sets a breakpoint on all renderscript kernels that "
4451 "are or will be loaded.\n"
4452 "Disabling option means breakpoints will no longer be set on any "
4453 "kernels loaded in the future, "
4454 "but does not remove currently set breakpoints.",
4455 "renderscript kernel breakpoint all <enable/disable>",
4456 eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4457 eCommandProcessMustBePaused) {}
4459 ~CommandObjectRenderScriptRuntimeKernelBreakpointAll() override = default;
4461 bool DoExecute(Args &command, CommandReturnObject &result) override {
4462 const size_t argc = command.GetArgumentCount();
4464 result.AppendErrorWithFormat(
4465 "'%s' takes 1 argument of 'enable' or 'disable'", m_cmd_name.c_str());
4466 result.SetStatus(eReturnStatusFailed);
4470 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4471 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4472 eLanguageTypeExtRenderScript));
4474 bool do_break = false;
4475 const char *argument = command.GetArgumentAtIndex(0);
4476 if (strcmp(argument, "enable") == 0) {
4478 result.AppendMessage("Breakpoints will be set on all kernels.");
4479 } else if (strcmp(argument, "disable") == 0) {
4481 result.AppendMessage("Breakpoints will not be set on any new kernels.");
4483 result.AppendErrorWithFormat(
4484 "Argument must be either 'enable' or 'disable'");
4485 result.SetStatus(eReturnStatusFailed);
4489 runtime->SetBreakAllKernels(do_break, m_exe_ctx.GetTargetSP());
4491 result.SetStatus(eReturnStatusSuccessFinishResult);
4496 class CommandObjectRenderScriptRuntimeReductionBreakpoint
4497 : public CommandObjectMultiword {
4499 CommandObjectRenderScriptRuntimeReductionBreakpoint(
4500 CommandInterpreter &interpreter)
4501 : CommandObjectMultiword(interpreter, "renderscript reduction breakpoint",
4502 "Commands that manipulate breakpoints on "
4503 "renderscript general reductions.",
4506 "set", CommandObjectSP(
4507 new CommandObjectRenderScriptRuntimeReductionBreakpointSet(
4511 ~CommandObjectRenderScriptRuntimeReductionBreakpoint() override = default;
4514 class CommandObjectRenderScriptRuntimeKernelCoordinate
4515 : public CommandObjectParsed {
4517 CommandObjectRenderScriptRuntimeKernelCoordinate(
4518 CommandInterpreter &interpreter)
4519 : CommandObjectParsed(
4520 interpreter, "renderscript kernel coordinate",
4521 "Shows the (x,y,z) coordinate of the current kernel invocation.",
4522 "renderscript kernel coordinate",
4523 eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4524 eCommandProcessMustBePaused) {}
4526 ~CommandObjectRenderScriptRuntimeKernelCoordinate() override = default;
4528 bool DoExecute(Args &command, CommandReturnObject &result) override {
4529 RSCoordinate coord{};
4530 bool success = RenderScriptRuntime::GetKernelCoordinate(
4531 coord, m_exe_ctx.GetThreadPtr());
4532 Stream &stream = result.GetOutputStream();
4535 stream.Printf("Coordinate: " FMT_COORD, coord.x, coord.y, coord.z);
4537 result.SetStatus(eReturnStatusSuccessFinishResult);
4539 stream.Printf("Error: Coordinate could not be found.");
4541 result.SetStatus(eReturnStatusFailed);
4547 class CommandObjectRenderScriptRuntimeKernelBreakpoint
4548 : public CommandObjectMultiword {
4550 CommandObjectRenderScriptRuntimeKernelBreakpoint(
4551 CommandInterpreter &interpreter)
4552 : CommandObjectMultiword(
4553 interpreter, "renderscript kernel",
4554 "Commands that generate breakpoints on renderscript kernels.",
4558 CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointSet(
4562 CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointAll(
4566 ~CommandObjectRenderScriptRuntimeKernelBreakpoint() override = default;
4569 class CommandObjectRenderScriptRuntimeKernel : public CommandObjectMultiword {
4571 CommandObjectRenderScriptRuntimeKernel(CommandInterpreter &interpreter)
4572 : CommandObjectMultiword(interpreter, "renderscript kernel",
4573 "Commands that deal with RenderScript kernels.",
4576 "list", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelList(
4581 new CommandObjectRenderScriptRuntimeKernelCoordinate(interpreter)));
4585 new CommandObjectRenderScriptRuntimeKernelBreakpoint(interpreter)));
4588 ~CommandObjectRenderScriptRuntimeKernel() override = default;
4591 class CommandObjectRenderScriptRuntimeContextDump : public CommandObjectParsed {
4593 CommandObjectRenderScriptRuntimeContextDump(CommandInterpreter &interpreter)
4594 : CommandObjectParsed(interpreter, "renderscript context dump",
4595 "Dumps renderscript context information.",
4596 "renderscript context dump",
4597 eCommandRequiresProcess |
4598 eCommandProcessMustBeLaunched) {}
4600 ~CommandObjectRenderScriptRuntimeContextDump() override = default;
4602 bool DoExecute(Args &command, CommandReturnObject &result) override {
4603 RenderScriptRuntime *runtime =
4604 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4605 eLanguageTypeExtRenderScript);
4606 runtime->DumpContexts(result.GetOutputStream());
4607 result.SetStatus(eReturnStatusSuccessFinishResult);
4612 static OptionDefinition g_renderscript_runtime_alloc_dump_options[] = {
4613 {LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument,
4614 nullptr, nullptr, 0, eArgTypeFilename,
4615 "Print results to specified file instead of command line."}};
4617 class CommandObjectRenderScriptRuntimeContext : public CommandObjectMultiword {
4619 CommandObjectRenderScriptRuntimeContext(CommandInterpreter &interpreter)
4620 : CommandObjectMultiword(interpreter, "renderscript context",
4621 "Commands that deal with RenderScript contexts.",
4624 "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeContextDump(
4628 ~CommandObjectRenderScriptRuntimeContext() override = default;
4631 class CommandObjectRenderScriptRuntimeAllocationDump
4632 : public CommandObjectParsed {
4634 CommandObjectRenderScriptRuntimeAllocationDump(
4635 CommandInterpreter &interpreter)
4636 : CommandObjectParsed(interpreter, "renderscript allocation dump",
4637 "Displays the contents of a particular allocation",
4638 "renderscript allocation dump <ID>",
4639 eCommandRequiresProcess |
4640 eCommandProcessMustBeLaunched),
4643 ~CommandObjectRenderScriptRuntimeAllocationDump() override = default;
4645 Options *GetOptions() override { return &m_options; }
4647 class CommandOptions : public Options {
4649 CommandOptions() : Options() {}
4651 ~CommandOptions() override = default;
4653 Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4654 ExecutionContext *exe_ctx) override {
4656 const int short_option = m_getopt_table[option_idx].val;
4658 switch (short_option) {
4660 m_outfile.SetFile(option_arg, true);
4661 if (m_outfile.Exists()) {
4663 err.SetErrorStringWithFormat("file already exists: '%s'",
4664 option_arg.str().c_str());
4668 err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4674 void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4678 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4679 return llvm::makeArrayRef(g_renderscript_runtime_alloc_dump_options);
4685 bool DoExecute(Args &command, CommandReturnObject &result) override {
4686 const size_t argc = command.GetArgumentCount();
4688 result.AppendErrorWithFormat("'%s' takes 1 argument, an allocation ID. "
4689 "As well as an optional -f argument",
4690 m_cmd_name.c_str());
4691 result.SetStatus(eReturnStatusFailed);
4695 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4696 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4697 eLanguageTypeExtRenderScript));
4699 const char *id_cstr = command.GetArgumentAtIndex(0);
4700 bool success = false;
4702 StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
4704 result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4706 result.SetStatus(eReturnStatusFailed);
4710 Stream *output_strm = nullptr;
4711 StreamFile outfile_stream;
4712 const FileSpec &outfile_spec =
4713 m_options.m_outfile; // Dump allocation to file instead
4717 outfile_spec.GetPath(path, sizeof(path));
4718 if (outfile_stream.GetFile()
4719 .Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate)
4721 output_strm = &outfile_stream;
4722 result.GetOutputStream().Printf("Results written to '%s'", path);
4723 result.GetOutputStream().EOL();
4725 result.AppendErrorWithFormat("Couldn't open file '%s'", path);
4726 result.SetStatus(eReturnStatusFailed);
4730 output_strm = &result.GetOutputStream();
4732 assert(output_strm != nullptr);
4734 runtime->DumpAllocation(*output_strm, m_exe_ctx.GetFramePtr(), id);
4737 result.SetStatus(eReturnStatusSuccessFinishResult);
4739 result.SetStatus(eReturnStatusFailed);
4745 CommandOptions m_options;
4748 static OptionDefinition g_renderscript_runtime_alloc_list_options[] = {
4749 {LLDB_OPT_SET_1, false, "id", 'i', OptionParser::eRequiredArgument, nullptr,
4750 nullptr, 0, eArgTypeIndex,
4751 "Only show details of a single allocation with specified id."}};
4753 class CommandObjectRenderScriptRuntimeAllocationList
4754 : public CommandObjectParsed {
4756 CommandObjectRenderScriptRuntimeAllocationList(
4757 CommandInterpreter &interpreter)
4758 : CommandObjectParsed(
4759 interpreter, "renderscript allocation list",
4760 "List renderscript allocations and their information.",
4761 "renderscript allocation list",
4762 eCommandRequiresProcess | eCommandProcessMustBeLaunched),
4765 ~CommandObjectRenderScriptRuntimeAllocationList() override = default;
4767 Options *GetOptions() override { return &m_options; }
4769 class CommandOptions : public Options {
4771 CommandOptions() : Options(), m_id(0) {}
4773 ~CommandOptions() override = default;
4775 Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4776 ExecutionContext *exe_ctx) override {
4778 const int short_option = m_getopt_table[option_idx].val;
4780 switch (short_option) {
4782 if (option_arg.getAsInteger(0, m_id))
4783 err.SetErrorStringWithFormat("invalid integer value for option '%c'",
4787 err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4793 void OptionParsingStarting(ExecutionContext *exe_ctx) override { m_id = 0; }
4795 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4796 return llvm::makeArrayRef(g_renderscript_runtime_alloc_list_options);
4802 bool DoExecute(Args &command, CommandReturnObject &result) override {
4803 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4804 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4805 eLanguageTypeExtRenderScript));
4806 runtime->ListAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr(),
4808 result.SetStatus(eReturnStatusSuccessFinishResult);
4813 CommandOptions m_options;
4816 class CommandObjectRenderScriptRuntimeAllocationLoad
4817 : public CommandObjectParsed {
4819 CommandObjectRenderScriptRuntimeAllocationLoad(
4820 CommandInterpreter &interpreter)
4821 : CommandObjectParsed(
4822 interpreter, "renderscript allocation load",
4823 "Loads renderscript allocation contents from a file.",
4824 "renderscript allocation load <ID> <filename>",
4825 eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
4827 ~CommandObjectRenderScriptRuntimeAllocationLoad() override = default;
4829 bool DoExecute(Args &command, CommandReturnObject &result) override {
4830 const size_t argc = command.GetArgumentCount();
4832 result.AppendErrorWithFormat(
4833 "'%s' takes 2 arguments, an allocation ID and filename to read from.",
4834 m_cmd_name.c_str());
4835 result.SetStatus(eReturnStatusFailed);
4839 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4840 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4841 eLanguageTypeExtRenderScript));
4843 const char *id_cstr = command.GetArgumentAtIndex(0);
4844 bool success = false;
4846 StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
4848 result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4850 result.SetStatus(eReturnStatusFailed);
4854 const char *path = command.GetArgumentAtIndex(1);
4855 bool loaded = runtime->LoadAllocation(result.GetOutputStream(), id, path,
4856 m_exe_ctx.GetFramePtr());
4859 result.SetStatus(eReturnStatusSuccessFinishResult);
4861 result.SetStatus(eReturnStatusFailed);
4867 class CommandObjectRenderScriptRuntimeAllocationSave
4868 : public CommandObjectParsed {
4870 CommandObjectRenderScriptRuntimeAllocationSave(
4871 CommandInterpreter &interpreter)
4872 : CommandObjectParsed(interpreter, "renderscript allocation save",
4873 "Write renderscript allocation contents to a file.",
4874 "renderscript allocation save <ID> <filename>",
4875 eCommandRequiresProcess |
4876 eCommandProcessMustBeLaunched) {}
4878 ~CommandObjectRenderScriptRuntimeAllocationSave() override = default;
4880 bool DoExecute(Args &command, CommandReturnObject &result) override {
4881 const size_t argc = command.GetArgumentCount();
4883 result.AppendErrorWithFormat(
4884 "'%s' takes 2 arguments, an allocation ID and filename to read from.",
4885 m_cmd_name.c_str());
4886 result.SetStatus(eReturnStatusFailed);
4890 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4891 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4892 eLanguageTypeExtRenderScript));
4894 const char *id_cstr = command.GetArgumentAtIndex(0);
4895 bool success = false;
4897 StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
4899 result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4901 result.SetStatus(eReturnStatusFailed);
4905 const char *path = command.GetArgumentAtIndex(1);
4906 bool saved = runtime->SaveAllocation(result.GetOutputStream(), id, path,
4907 m_exe_ctx.GetFramePtr());
4910 result.SetStatus(eReturnStatusSuccessFinishResult);
4912 result.SetStatus(eReturnStatusFailed);
4918 class CommandObjectRenderScriptRuntimeAllocationRefresh
4919 : public CommandObjectParsed {
4921 CommandObjectRenderScriptRuntimeAllocationRefresh(
4922 CommandInterpreter &interpreter)
4923 : CommandObjectParsed(interpreter, "renderscript allocation refresh",
4924 "Recomputes the details of all allocations.",
4925 "renderscript allocation refresh",
4926 eCommandRequiresProcess |
4927 eCommandProcessMustBeLaunched) {}
4929 ~CommandObjectRenderScriptRuntimeAllocationRefresh() override = default;
4931 bool DoExecute(Args &command, CommandReturnObject &result) override {
4932 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4933 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4934 eLanguageTypeExtRenderScript));
4936 bool success = runtime->RecomputeAllAllocations(result.GetOutputStream(),
4937 m_exe_ctx.GetFramePtr());
4940 result.SetStatus(eReturnStatusSuccessFinishResult);
4943 result.SetStatus(eReturnStatusFailed);
4949 class CommandObjectRenderScriptRuntimeAllocation
4950 : public CommandObjectMultiword {
4952 CommandObjectRenderScriptRuntimeAllocation(CommandInterpreter &interpreter)
4953 : CommandObjectMultiword(
4954 interpreter, "renderscript allocation",
4955 "Commands that deal with RenderScript allocations.", nullptr) {
4959 new CommandObjectRenderScriptRuntimeAllocationList(interpreter)));
4963 new CommandObjectRenderScriptRuntimeAllocationDump(interpreter)));
4967 new CommandObjectRenderScriptRuntimeAllocationSave(interpreter)));
4971 new CommandObjectRenderScriptRuntimeAllocationLoad(interpreter)));
4974 CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationRefresh(
4978 ~CommandObjectRenderScriptRuntimeAllocation() override = default;
4981 class CommandObjectRenderScriptRuntimeStatus : public CommandObjectParsed {
4983 CommandObjectRenderScriptRuntimeStatus(CommandInterpreter &interpreter)
4984 : CommandObjectParsed(interpreter, "renderscript status",
4985 "Displays current RenderScript runtime status.",
4986 "renderscript status",
4987 eCommandRequiresProcess |
4988 eCommandProcessMustBeLaunched) {}
4990 ~CommandObjectRenderScriptRuntimeStatus() override = default;
4992 bool DoExecute(Args &command, CommandReturnObject &result) override {
4993 RenderScriptRuntime *runtime =
4994 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4995 eLanguageTypeExtRenderScript);
4996 runtime->Status(result.GetOutputStream());
4997 result.SetStatus(eReturnStatusSuccessFinishResult);
5002 class CommandObjectRenderScriptRuntimeReduction
5003 : public CommandObjectMultiword {
5005 CommandObjectRenderScriptRuntimeReduction(CommandInterpreter &interpreter)
5006 : CommandObjectMultiword(interpreter, "renderscript reduction",
5007 "Commands that handle general reduction kernels",
5011 CommandObjectSP(new CommandObjectRenderScriptRuntimeReductionBreakpoint(
5014 ~CommandObjectRenderScriptRuntimeReduction() override = default;
5017 class CommandObjectRenderScriptRuntime : public CommandObjectMultiword {
5019 CommandObjectRenderScriptRuntime(CommandInterpreter &interpreter)
5020 : CommandObjectMultiword(
5021 interpreter, "renderscript",
5022 "Commands for operating on the RenderScript runtime.",
5023 "renderscript <subcommand> [<subcommand-options>]") {
5025 "module", CommandObjectSP(
5026 new CommandObjectRenderScriptRuntimeModule(interpreter)));
5028 "status", CommandObjectSP(
5029 new CommandObjectRenderScriptRuntimeStatus(interpreter)));
5031 "kernel", CommandObjectSP(
5032 new CommandObjectRenderScriptRuntimeKernel(interpreter)));
5033 LoadSubCommand("context",
5034 CommandObjectSP(new CommandObjectRenderScriptRuntimeContext(
5039 new CommandObjectRenderScriptRuntimeAllocation(interpreter)));
5040 LoadSubCommand("scriptgroup",
5041 NewCommandObjectRenderScriptScriptGroup(interpreter));
5045 new CommandObjectRenderScriptRuntimeReduction(interpreter)));
5048 ~CommandObjectRenderScriptRuntime() override = default;
5051 void RenderScriptRuntime::Initiate() { assert(!m_initiated); }
5053 RenderScriptRuntime::RenderScriptRuntime(Process *process)
5054 : lldb_private::CPPLanguageRuntime(process), m_initiated(false),
5055 m_debuggerPresentFlagged(false), m_breakAllKernels(false),
5056 m_ir_passes(nullptr) {
5057 ModulesDidLoad(process->GetTarget().GetImages());
5060 lldb::CommandObjectSP RenderScriptRuntime::GetCommandObject(
5061 lldb_private::CommandInterpreter &interpreter) {
5062 return CommandObjectSP(new CommandObjectRenderScriptRuntime(interpreter));
5065 RenderScriptRuntime::~RenderScriptRuntime() = default;