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 //===----------------------------------------------------------------------===//
10 #include "llvm/ADT/StringSwitch.h"
12 #include "RenderScriptRuntime.h"
13 #include "RenderScriptScriptGroup.h"
15 #include "lldb/Breakpoint/StoppointCallbackContext.h"
16 #include "lldb/Core/Debugger.h"
17 #include "lldb/Core/DumpDataExtractor.h"
18 #include "lldb/Core/PluginManager.h"
19 #include "lldb/Core/ValueObjectVariable.h"
20 #include "lldb/DataFormatters/DumpValueObjectOptions.h"
21 #include "lldb/Expression/UserExpression.h"
22 #include "lldb/Host/OptionParser.h"
23 #include "lldb/Host/StringConvert.h"
24 #include "lldb/Interpreter/CommandInterpreter.h"
25 #include "lldb/Interpreter/CommandObjectMultiword.h"
26 #include "lldb/Interpreter/CommandReturnObject.h"
27 #include "lldb/Interpreter/Options.h"
28 #include "lldb/Symbol/Function.h"
29 #include "lldb/Symbol/Symbol.h"
30 #include "lldb/Symbol/Type.h"
31 #include "lldb/Symbol/VariableList.h"
32 #include "lldb/Target/Process.h"
33 #include "lldb/Target/RegisterContext.h"
34 #include "lldb/Target/SectionLoadList.h"
35 #include "lldb/Target/Target.h"
36 #include "lldb/Target/Thread.h"
37 #include "lldb/Utility/Args.h"
38 #include "lldb/Utility/ConstString.h"
39 #include "lldb/Utility/Log.h"
40 #include "lldb/Utility/RegisterValue.h"
41 #include "lldb/Utility/RegularExpression.h"
42 #include "lldb/Utility/Status.h"
45 using namespace lldb_private;
46 using namespace lldb_renderscript;
48 #define FMT_COORD "(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ")"
52 // The empirical_type adds a basic level of validation to arbitrary data
53 // allowing us to track if data has been discovered and stored or not. An
54 // empirical_type will be marked as valid only if it has been explicitly
56 template <typename type_t> class empirical_type {
58 // Ctor. Contents is invalid when constructed.
59 empirical_type() : valid(false) {}
61 // Return true and copy contents to out if valid, else return false.
62 bool get(type_t &out) const {
68 // Return a pointer to the contents or nullptr if it was not valid.
69 const type_t *get() const { return valid ? &data : nullptr; }
71 // Assign data explicitly.
72 void set(const type_t in) {
77 // Mark contents as invalid.
78 void invalidate() { valid = false; }
80 // Returns true if this type contains valid data.
81 bool isValid() const { return valid; }
83 // Assignment operator.
84 empirical_type<type_t> &operator=(const type_t in) {
89 // Dereference operator returns contents.
90 // Warning: Will assert if not valid so use only when you know data is valid.
91 const type_t &operator*() const {
101 // ArgItem is used by the GetArgs() function when reading function arguments
104 enum { ePointer, eInt32, eInt64, eLong, eBool } type;
108 explicit operator uint64_t() const { return value; }
111 // Context structure to be passed into GetArgsXXX(), argument reading functions
114 RegisterContext *reg_ctx;
118 bool GetArgsX86(const GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
119 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
123 // get the current stack pointer
124 uint64_t sp = ctx.reg_ctx->GetSP();
126 for (size_t i = 0; i < num_args; ++i) {
127 ArgItem &arg = arg_list[i];
128 // advance up the stack by one argument
129 sp += sizeof(uint32_t);
130 // get the argument type size
131 size_t arg_size = sizeof(uint32_t);
132 // read the argument from memory
136 ctx.process->ReadMemory(sp, &arg.value, sizeof(uint32_t), err);
137 if (read != arg_size || !err.Success()) {
139 log->Printf("%s - error reading argument: %" PRIu64 " '%s'",
140 __FUNCTION__, uint64_t(i), err.AsCString());
147 bool GetArgsX86_64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
148 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
150 // number of arguments passed in registers
151 static const uint32_t args_in_reg = 6;
152 // register passing order
153 static const std::array<const char *, args_in_reg> reg_names{
154 {"rdi", "rsi", "rdx", "rcx", "r8", "r9"}};
155 // argument type to size mapping
156 static const std::array<size_t, 5> arg_size{{
166 // get the current stack pointer
167 uint64_t sp = ctx.reg_ctx->GetSP();
168 // step over the return address
169 sp += sizeof(uint64_t);
171 // check the stack alignment was correct (16 byte aligned)
172 if ((sp & 0xf) != 0x0) {
174 log->Printf("%s - stack misaligned", __FUNCTION__);
178 // find the start of arguments on the stack
179 uint64_t sp_offset = 0;
180 for (uint32_t i = args_in_reg; i < num_args; ++i) {
181 sp_offset += arg_size[arg_list[i].type];
183 // round up to multiple of 16
184 sp_offset = (sp_offset + 0xf) & 0xf;
187 for (size_t i = 0; i < num_args; ++i) {
188 bool success = false;
189 ArgItem &arg = arg_list[i];
190 // arguments passed in registers
191 if (i < args_in_reg) {
192 const RegisterInfo *reg =
193 ctx.reg_ctx->GetRegisterInfoByName(reg_names[i]);
194 RegisterValue reg_val;
195 if (ctx.reg_ctx->ReadRegister(reg, reg_val))
196 arg.value = reg_val.GetAsUInt64(0, &success);
198 // arguments passed on the stack
200 // get the argument type size
201 const size_t size = arg_size[arg_list[i].type];
202 // read the argument from memory
204 // note: due to little endian layout reading 4 or 8 bytes will give the
206 size_t read = ctx.process->ReadMemory(sp, &arg.value, size, err);
207 success = (err.Success() && read == size);
208 // advance past this argument
211 // fail if we couldn't read this argument
214 log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
215 __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
222 bool GetArgsArm(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
223 // number of arguments passed in registers
224 static const uint32_t args_in_reg = 4;
226 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
230 // get the current stack pointer
231 uint64_t sp = ctx.reg_ctx->GetSP();
233 for (size_t i = 0; i < num_args; ++i) {
234 bool success = false;
235 ArgItem &arg = arg_list[i];
236 // arguments passed in registers
237 if (i < args_in_reg) {
238 const RegisterInfo *reg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
239 RegisterValue reg_val;
240 if (ctx.reg_ctx->ReadRegister(reg, reg_val))
241 arg.value = reg_val.GetAsUInt32(0, &success);
243 // arguments passed on the stack
245 // get the argument type size
246 const size_t arg_size = sizeof(uint32_t);
249 // read this argument from memory
251 ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
252 success = (err.Success() && bytes_read == arg_size);
253 // advance the stack pointer
254 sp += sizeof(uint32_t);
256 // fail if we couldn't read this argument
259 log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
260 __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
267 bool GetArgsAarch64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
268 // number of arguments passed in registers
269 static const uint32_t args_in_reg = 8;
271 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
273 for (size_t i = 0; i < num_args; ++i) {
274 bool success = false;
275 ArgItem &arg = arg_list[i];
276 // arguments passed in registers
277 if (i < args_in_reg) {
278 const RegisterInfo *reg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
279 RegisterValue reg_val;
280 if (ctx.reg_ctx->ReadRegister(reg, reg_val))
281 arg.value = reg_val.GetAsUInt64(0, &success);
283 // arguments passed on the stack
286 log->Printf("%s - reading arguments spilled to stack not implemented",
289 // fail if we couldn't read this argument
292 log->Printf("%s - error reading argument: %" PRIu64, __FUNCTION__,
300 bool GetArgsMipsel(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
301 // number of arguments passed in registers
302 static const uint32_t args_in_reg = 4;
303 // register file offset to first argument
304 static const uint32_t reg_offset = 4;
306 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
310 // find offset to arguments on the stack (+16 to skip over a0-a3 shadow
312 uint64_t sp = ctx.reg_ctx->GetSP() + 16;
314 for (size_t i = 0; i < num_args; ++i) {
315 bool success = false;
316 ArgItem &arg = arg_list[i];
317 // arguments passed in registers
318 if (i < args_in_reg) {
319 const RegisterInfo *reg =
320 ctx.reg_ctx->GetRegisterInfoAtIndex(i + reg_offset);
321 RegisterValue reg_val;
322 if (ctx.reg_ctx->ReadRegister(reg, reg_val))
323 arg.value = reg_val.GetAsUInt64(0, &success);
325 // arguments passed on the stack
327 const size_t arg_size = sizeof(uint32_t);
330 ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
331 success = (err.Success() && bytes_read == arg_size);
332 // advance the stack pointer
335 // fail if we couldn't read this argument
338 log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
339 __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
346 bool GetArgsMips64el(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
347 // number of arguments passed in registers
348 static const uint32_t args_in_reg = 8;
349 // register file offset to first argument
350 static const uint32_t reg_offset = 4;
352 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
356 // get the current stack pointer
357 uint64_t sp = ctx.reg_ctx->GetSP();
359 for (size_t i = 0; i < num_args; ++i) {
360 bool success = false;
361 ArgItem &arg = arg_list[i];
362 // arguments passed in registers
363 if (i < args_in_reg) {
364 const RegisterInfo *reg =
365 ctx.reg_ctx->GetRegisterInfoAtIndex(i + reg_offset);
366 RegisterValue reg_val;
367 if (ctx.reg_ctx->ReadRegister(reg, reg_val))
368 arg.value = reg_val.GetAsUInt64(0, &success);
370 // arguments passed on the stack
372 // get the argument type size
373 const size_t arg_size = sizeof(uint64_t);
376 // read this argument from memory
378 ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
379 success = (err.Success() && bytes_read == arg_size);
380 // advance the stack pointer
383 // fail if we couldn't read this argument
386 log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
387 __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
394 bool GetArgs(ExecutionContext &exe_ctx, ArgItem *arg_list, size_t num_args) {
395 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
397 // verify that we have a target
398 if (!exe_ctx.GetTargetPtr()) {
400 log->Printf("%s - invalid target", __FUNCTION__);
404 GetArgsCtx ctx = {exe_ctx.GetRegisterContext(), exe_ctx.GetProcessPtr()};
405 assert(ctx.reg_ctx && ctx.process);
407 // dispatch based on architecture
408 switch (exe_ctx.GetTargetPtr()->GetArchitecture().GetMachine()) {
409 case llvm::Triple::ArchType::x86:
410 return GetArgsX86(ctx, arg_list, num_args);
412 case llvm::Triple::ArchType::x86_64:
413 return GetArgsX86_64(ctx, arg_list, num_args);
415 case llvm::Triple::ArchType::arm:
416 return GetArgsArm(ctx, arg_list, num_args);
418 case llvm::Triple::ArchType::aarch64:
419 return GetArgsAarch64(ctx, arg_list, num_args);
421 case llvm::Triple::ArchType::mipsel:
422 return GetArgsMipsel(ctx, arg_list, num_args);
424 case llvm::Triple::ArchType::mips64el:
425 return GetArgsMips64el(ctx, arg_list, num_args);
428 // unsupported architecture
431 "%s - architecture not supported: '%s'", __FUNCTION__,
432 exe_ctx.GetTargetRef().GetArchitecture().GetArchitectureName());
438 bool IsRenderScriptScriptModule(ModuleSP module) {
441 return module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"),
442 eSymbolTypeData) != nullptr;
445 bool ParseCoordinate(llvm::StringRef coord_s, RSCoordinate &coord) {
446 // takes an argument of the form 'num[,num][,num]'. Where 'coord_s' is a
447 // comma separated 1,2 or 3-dimensional coordinate with the whitespace
448 // trimmed. Missing coordinates are defaulted to zero. If parsing of any
449 // elements fails the contents of &coord are undefined and `false` is
450 // returned, `true` otherwise
452 RegularExpression regex;
453 RegularExpression::Match regex_match(3);
455 bool matched = false;
456 if (regex.Compile(llvm::StringRef("^([0-9]+),([0-9]+),([0-9]+)$")) &&
457 regex.Execute(coord_s, ®ex_match))
459 else if (regex.Compile(llvm::StringRef("^([0-9]+),([0-9]+)$")) &&
460 regex.Execute(coord_s, ®ex_match))
462 else if (regex.Compile(llvm::StringRef("^([0-9]+)$")) &&
463 regex.Execute(coord_s, ®ex_match))
469 auto get_index = [&](int idx, uint32_t &i) -> bool {
472 if (regex_match.GetMatchAtIndex(coord_s.str().c_str(), idx + 1, group))
473 return !llvm::StringRef(group).getAsInteger<uint32_t>(10, i);
477 return get_index(0, coord.x) && get_index(1, coord.y) &&
478 get_index(2, coord.z);
481 bool SkipPrologue(lldb::ModuleSP &module, Address &addr) {
482 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
484 uint32_t resolved_flags =
485 module->ResolveSymbolContextForAddress(addr, eSymbolContextFunction, sc);
486 if (resolved_flags & eSymbolContextFunction) {
488 const uint32_t offset = sc.function->GetPrologueByteSize();
489 ConstString name = sc.GetFunctionName();
493 log->Printf("%s: Prologue offset for %s is %" PRIu32, __FUNCTION__,
494 name.AsCString(), offset);
500 } // anonymous namespace
502 // The ScriptDetails class collects data associated with a single script
504 struct RenderScriptRuntime::ScriptDetails {
505 ~ScriptDetails() = default;
507 enum ScriptType { eScript, eScriptC };
509 // The derived type of the script.
510 empirical_type<ScriptType> type;
511 // The name of the original source file.
512 empirical_type<std::string> res_name;
513 // Path to script .so file on the device.
514 empirical_type<std::string> shared_lib;
515 // Directory where kernel objects are cached on device.
516 empirical_type<std::string> cache_dir;
517 // Pointer to the context which owns this script.
518 empirical_type<lldb::addr_t> context;
519 // Pointer to the script object itself.
520 empirical_type<lldb::addr_t> script;
523 // This Element class represents the Element object in RS, defining the type
524 // associated with an Allocation.
525 struct RenderScriptRuntime::Element {
526 // Taken from rsDefines.h
536 RS_KIND_INVALID = 100
539 // Taken from rsDefines.h
555 RS_TYPE_UNSIGNED_5_6_5,
556 RS_TYPE_UNSIGNED_5_5_5_1,
557 RS_TYPE_UNSIGNED_4_4_4_4,
563 RS_TYPE_ELEMENT = 1000,
569 RS_TYPE_PROGRAM_FRAGMENT,
570 RS_TYPE_PROGRAM_VERTEX,
571 RS_TYPE_PROGRAM_RASTER,
572 RS_TYPE_PROGRAM_STORE,
575 RS_TYPE_INVALID = 10000
578 std::vector<Element> children; // Child Element fields for structs
579 empirical_type<lldb::addr_t>
580 element_ptr; // Pointer to the RS Element of the Type
581 empirical_type<DataType>
582 type; // Type of each data pointer stored by the allocation
583 empirical_type<DataKind>
584 type_kind; // Defines pixel type if Allocation is created from an image
585 empirical_type<uint32_t>
586 type_vec_size; // Vector size of each data point, e.g '4' for uchar4
587 empirical_type<uint32_t> field_count; // Number of Subelements
588 empirical_type<uint32_t> datum_size; // Size of a single Element with padding
589 empirical_type<uint32_t> padding; // Number of padding bytes
590 empirical_type<uint32_t>
591 array_size; // Number of items in array, only needed for structs
592 ConstString type_name; // Name of type, only needed for structs
594 static const ConstString &
595 GetFallbackStructName(); // Print this as the type name of a struct Element
596 // If we can't resolve the actual struct name
598 bool ShouldRefresh() const {
599 const bool valid_ptr = element_ptr.isValid() && *element_ptr.get() != 0x0;
600 const bool valid_type =
601 type.isValid() && type_vec_size.isValid() && type_kind.isValid();
602 return !valid_ptr || !valid_type || !datum_size.isValid();
606 // This AllocationDetails class collects data associated with a single
607 // allocation instance.
608 struct RenderScriptRuntime::AllocationDetails {
623 // The FileHeader struct specifies the header we use for writing allocations
624 // to a binary file. Our format begins with the ASCII characters "RSAD",
625 // identifying the file as an allocation dump. Member variables dims and
626 // hdr_size are then written consecutively, immediately followed by an
627 // instance of the ElementHeader struct. Because Elements can contain
628 // subelements, there may be more than one instance of the ElementHeader
629 // struct. With this first instance being the root element, and the other
630 // instances being the root's descendants. To identify which instances are an
631 // ElementHeader's children, each struct is immediately followed by a
632 // sequence of consecutive offsets to the start of its child structs. These
634 // 4 bytes in size, and the 0 offset signifies no more children.
636 uint8_t ident[4]; // ASCII 'RSAD' identifying the file
637 uint32_t dims[3]; // Dimensions
638 uint16_t hdr_size; // Header size in bytes, including all element headers
641 struct ElementHeader {
642 uint16_t type; // DataType enum
643 uint32_t kind; // DataKind enum
644 uint32_t element_size; // Size of a single element, including padding
645 uint16_t vector_size; // Vector width
646 uint32_t array_size; // Number of elements in array
649 // Monotonically increasing from 1
652 // Maps Allocation DataType enum and vector size to printable strings using
653 // mapping from RenderScript numerical types summary documentation
654 static const char *RsDataTypeToString[][4];
656 // Maps Allocation DataKind enum to printable strings
657 static const char *RsDataKindToString[];
659 // Maps allocation types to format sizes for printing.
660 static const uint32_t RSTypeToFormat[][3];
662 // Give each allocation an ID as a way
663 // for commands to reference it.
666 // Allocation Element type
667 RenderScriptRuntime::Element element;
668 // Dimensions of the Allocation
669 empirical_type<Dimension> dimension;
670 // Pointer to address of the RS Allocation
671 empirical_type<lldb::addr_t> address;
672 // Pointer to the data held by the Allocation
673 empirical_type<lldb::addr_t> data_ptr;
674 // Pointer to the RS Type of the Allocation
675 empirical_type<lldb::addr_t> type_ptr;
676 // Pointer to the RS Context of the Allocation
677 empirical_type<lldb::addr_t> context;
678 // Size of the allocation
679 empirical_type<uint32_t> size;
680 // Stride between rows of the allocation
681 empirical_type<uint32_t> stride;
683 // Give each allocation an id, so we can reference it in user commands.
684 AllocationDetails() : id(ID++) {}
686 bool ShouldRefresh() const {
687 bool valid_ptrs = data_ptr.isValid() && *data_ptr.get() != 0x0;
688 valid_ptrs = valid_ptrs && type_ptr.isValid() && *type_ptr.get() != 0x0;
689 return !valid_ptrs || !dimension.isValid() || !size.isValid() ||
690 element.ShouldRefresh();
694 const ConstString &RenderScriptRuntime::Element::GetFallbackStructName() {
695 static const ConstString FallbackStructName("struct");
696 return FallbackStructName;
699 uint32_t RenderScriptRuntime::AllocationDetails::ID = 1;
701 const char *RenderScriptRuntime::AllocationDetails::RsDataKindToString[] = {
702 "User", "Undefined", "Undefined", "Undefined",
703 "Undefined", "Undefined", "Undefined", // Enum jumps from 0 to 7
704 "L Pixel", "A Pixel", "LA Pixel", "RGB Pixel",
705 "RGBA Pixel", "Pixel Depth", "YUV Pixel"};
707 const char *RenderScriptRuntime::AllocationDetails::RsDataTypeToString[][4] = {
708 {"None", "None", "None", "None"},
709 {"half", "half2", "half3", "half4"},
710 {"float", "float2", "float3", "float4"},
711 {"double", "double2", "double3", "double4"},
712 {"char", "char2", "char3", "char4"},
713 {"short", "short2", "short3", "short4"},
714 {"int", "int2", "int3", "int4"},
715 {"long", "long2", "long3", "long4"},
716 {"uchar", "uchar2", "uchar3", "uchar4"},
717 {"ushort", "ushort2", "ushort3", "ushort4"},
718 {"uint", "uint2", "uint3", "uint4"},
719 {"ulong", "ulong2", "ulong3", "ulong4"},
720 {"bool", "bool2", "bool3", "bool4"},
721 {"packed_565", "packed_565", "packed_565", "packed_565"},
722 {"packed_5551", "packed_5551", "packed_5551", "packed_5551"},
723 {"packed_4444", "packed_4444", "packed_4444", "packed_4444"},
724 {"rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4"},
725 {"rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3"},
726 {"rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2"},
729 {"RS Element", "RS Element", "RS Element", "RS Element"},
730 {"RS Type", "RS Type", "RS Type", "RS Type"},
731 {"RS Allocation", "RS Allocation", "RS Allocation", "RS Allocation"},
732 {"RS Sampler", "RS Sampler", "RS Sampler", "RS Sampler"},
733 {"RS Script", "RS Script", "RS Script", "RS Script"},
736 {"RS Mesh", "RS Mesh", "RS Mesh", "RS Mesh"},
737 {"RS Program Fragment", "RS Program Fragment", "RS Program Fragment",
738 "RS Program Fragment"},
739 {"RS Program Vertex", "RS Program Vertex", "RS Program Vertex",
740 "RS Program Vertex"},
741 {"RS Program Raster", "RS Program Raster", "RS Program Raster",
742 "RS Program Raster"},
743 {"RS Program Store", "RS Program Store", "RS Program Store",
745 {"RS Font", "RS Font", "RS Font", "RS Font"}};
747 // Used as an index into the RSTypeToFormat array elements
748 enum TypeToFormatIndex { eFormatSingle = 0, eFormatVector, eElementSize };
750 // { format enum of single element, format enum of element vector, size of
752 const uint32_t RenderScriptRuntime::AllocationDetails::RSTypeToFormat[][3] = {
754 {eFormatHex, eFormatHex, 1},
756 {eFormatFloat, eFormatVectorOfFloat16, 2},
758 {eFormatFloat, eFormatVectorOfFloat32, sizeof(float)},
760 {eFormatFloat, eFormatVectorOfFloat64, sizeof(double)},
762 {eFormatDecimal, eFormatVectorOfSInt8, sizeof(int8_t)},
764 {eFormatDecimal, eFormatVectorOfSInt16, sizeof(int16_t)},
766 {eFormatDecimal, eFormatVectorOfSInt32, sizeof(int32_t)},
768 {eFormatDecimal, eFormatVectorOfSInt64, sizeof(int64_t)},
769 // RS_TYPE_UNSIGNED_8
770 {eFormatDecimal, eFormatVectorOfUInt8, sizeof(uint8_t)},
771 // RS_TYPE_UNSIGNED_16
772 {eFormatDecimal, eFormatVectorOfUInt16, sizeof(uint16_t)},
773 // RS_TYPE_UNSIGNED_32
774 {eFormatDecimal, eFormatVectorOfUInt32, sizeof(uint32_t)},
775 // RS_TYPE_UNSIGNED_64
776 {eFormatDecimal, eFormatVectorOfUInt64, sizeof(uint64_t)},
778 {eFormatBoolean, eFormatBoolean, 1},
779 // RS_TYPE_UNSIGNED_5_6_5
780 {eFormatHex, eFormatHex, sizeof(uint16_t)},
781 // RS_TYPE_UNSIGNED_5_5_5_1
782 {eFormatHex, eFormatHex, sizeof(uint16_t)},
783 // RS_TYPE_UNSIGNED_4_4_4_4
784 {eFormatHex, eFormatHex, sizeof(uint16_t)},
785 // RS_TYPE_MATRIX_4X4
786 {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 16},
787 // RS_TYPE_MATRIX_3X3
788 {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 9},
789 // RS_TYPE_MATRIX_2X2
790 {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 4}};
792 //------------------------------------------------------------------
794 //------------------------------------------------------------------
796 RenderScriptRuntime::CreateInstance(Process *process,
797 lldb::LanguageType language) {
799 if (language == eLanguageTypeExtRenderScript)
800 return new RenderScriptRuntime(process);
805 // Callback with a module to search for matching symbols. We first check that
806 // the module contains RS kernels. Then look for a symbol which matches our
807 // kernel name. The breakpoint address is finally set using the address of this
809 Searcher::CallbackReturn
810 RSBreakpointResolver::SearchCallback(SearchFilter &filter,
811 SymbolContext &context, Address *, bool) {
812 ModuleSP module = context.module_sp;
814 if (!module || !IsRenderScriptScriptModule(module))
815 return Searcher::eCallbackReturnContinue;
817 // Attempt to set a breakpoint on the kernel name symbol within the module
818 // library. If it's not found, it's likely debug info is unavailable - try to
819 // set a breakpoint on <name>.expand.
820 const Symbol *kernel_sym =
821 module->FindFirstSymbolWithNameAndType(m_kernel_name, eSymbolTypeCode);
823 std::string kernel_name_expanded(m_kernel_name.AsCString());
824 kernel_name_expanded.append(".expand");
825 kernel_sym = module->FindFirstSymbolWithNameAndType(
826 ConstString(kernel_name_expanded.c_str()), eSymbolTypeCode);
830 Address bp_addr = kernel_sym->GetAddress();
831 if (filter.AddressPasses(bp_addr))
832 m_breakpoint->AddLocation(bp_addr);
835 return Searcher::eCallbackReturnContinue;
838 Searcher::CallbackReturn
839 RSReduceBreakpointResolver::SearchCallback(lldb_private::SearchFilter &filter,
840 lldb_private::SymbolContext &context,
842 // We need to have access to the list of reductions currently parsed, as
843 // reduce names don't actually exist as symbols in a module. They are only
844 // identifiable by parsing the .rs.info packet, or finding the expand symbol.
845 // We therefore need access to the list of parsed rs modules to properly
846 // resolve reduction names.
847 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
848 ModuleSP module = context.module_sp;
850 if (!module || !IsRenderScriptScriptModule(module))
851 return Searcher::eCallbackReturnContinue;
854 return Searcher::eCallbackReturnContinue;
856 for (const auto &module_desc : *m_rsmodules) {
857 if (module_desc->m_module != module)
860 for (const auto &reduction : module_desc->m_reductions) {
861 if (reduction.m_reduce_name != m_reduce_name)
864 std::array<std::pair<ConstString, int>, 5> funcs{
865 {{reduction.m_init_name, eKernelTypeInit},
866 {reduction.m_accum_name, eKernelTypeAccum},
867 {reduction.m_comb_name, eKernelTypeComb},
868 {reduction.m_outc_name, eKernelTypeOutC},
869 {reduction.m_halter_name, eKernelTypeHalter}}};
871 for (const auto &kernel : funcs) {
872 // Skip constituent functions that don't match our spec
873 if (!(m_kernel_types & kernel.second))
876 const auto kernel_name = kernel.first;
877 const auto symbol = module->FindFirstSymbolWithNameAndType(
878 kernel_name, eSymbolTypeCode);
882 auto address = symbol->GetAddress();
883 if (filter.AddressPasses(address)) {
885 if (!SkipPrologue(module, address)) {
887 log->Printf("%s: Error trying to skip prologue", __FUNCTION__);
889 m_breakpoint->AddLocation(address, &new_bp);
891 log->Printf("%s: %s reduction breakpoint on %s in %s", __FUNCTION__,
892 new_bp ? "new" : "existing", kernel_name.GetCString(),
893 address.GetModule()->GetFileSpec().GetCString());
898 return eCallbackReturnContinue;
901 Searcher::CallbackReturn RSScriptGroupBreakpointResolver::SearchCallback(
902 SearchFilter &filter, SymbolContext &context, Address *addr,
906 return eCallbackReturnContinue;
908 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
909 ModuleSP &module = context.module_sp;
911 if (!module || !IsRenderScriptScriptModule(module))
912 return Searcher::eCallbackReturnContinue;
914 std::vector<std::string> names;
915 m_breakpoint->GetNames(names);
917 return eCallbackReturnContinue;
919 for (auto &name : names) {
920 const RSScriptGroupDescriptorSP sg = FindScriptGroup(ConstString(name));
923 log->Printf("%s: could not find script group for %s", __FUNCTION__,
929 log->Printf("%s: Found ScriptGroup for %s", __FUNCTION__, name.c_str());
931 for (const RSScriptGroupDescriptor::Kernel &k : sg->m_kernels) {
933 log->Printf("%s: Adding breakpoint for %s", __FUNCTION__,
934 k.m_name.AsCString());
935 log->Printf("%s: Kernel address 0x%" PRIx64, __FUNCTION__, k.m_addr);
938 const lldb_private::Symbol *sym =
939 module->FindFirstSymbolWithNameAndType(k.m_name, eSymbolTypeCode);
942 log->Printf("%s: Unable to find symbol for %s", __FUNCTION__,
943 k.m_name.AsCString());
948 log->Printf("%s: Found symbol name is %s", __FUNCTION__,
949 sym->GetName().AsCString());
952 auto address = sym->GetAddress();
953 if (!SkipPrologue(module, address)) {
955 log->Printf("%s: Error trying to skip prologue", __FUNCTION__);
959 m_breakpoint->AddLocation(address, &new_bp);
962 log->Printf("%s: Placed %sbreakpoint on %s", __FUNCTION__,
963 new_bp ? "new " : "", k.m_name.AsCString());
965 // exit after placing the first breakpoint if we do not intend to stop on
966 // all kernels making up this script group
972 return eCallbackReturnContinue;
975 void RenderScriptRuntime::Initialize() {
976 PluginManager::RegisterPlugin(GetPluginNameStatic(),
977 "RenderScript language support", CreateInstance,
981 void RenderScriptRuntime::Terminate() {
982 PluginManager::UnregisterPlugin(CreateInstance);
985 lldb_private::ConstString RenderScriptRuntime::GetPluginNameStatic() {
986 static ConstString plugin_name("renderscript");
990 RenderScriptRuntime::ModuleKind
991 RenderScriptRuntime::GetModuleKind(const lldb::ModuleSP &module_sp) {
993 if (IsRenderScriptScriptModule(module_sp))
994 return eModuleKindKernelObj;
996 // Is this the main RS runtime library
997 const ConstString rs_lib("libRS.so");
998 if (module_sp->GetFileSpec().GetFilename() == rs_lib) {
999 return eModuleKindLibRS;
1002 const ConstString rs_driverlib("libRSDriver.so");
1003 if (module_sp->GetFileSpec().GetFilename() == rs_driverlib) {
1004 return eModuleKindDriver;
1007 const ConstString rs_cpureflib("libRSCpuRef.so");
1008 if (module_sp->GetFileSpec().GetFilename() == rs_cpureflib) {
1009 return eModuleKindImpl;
1012 return eModuleKindIgnored;
1015 bool RenderScriptRuntime::IsRenderScriptModule(
1016 const lldb::ModuleSP &module_sp) {
1017 return GetModuleKind(module_sp) != eModuleKindIgnored;
1020 void RenderScriptRuntime::ModulesDidLoad(const ModuleList &module_list) {
1021 std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
1023 size_t num_modules = module_list.GetSize();
1024 for (size_t i = 0; i < num_modules; i++) {
1025 auto mod = module_list.GetModuleAtIndex(i);
1026 if (IsRenderScriptModule(mod)) {
1032 //------------------------------------------------------------------
1033 // PluginInterface protocol
1034 //------------------------------------------------------------------
1035 lldb_private::ConstString RenderScriptRuntime::GetPluginName() {
1036 return GetPluginNameStatic();
1039 uint32_t RenderScriptRuntime::GetPluginVersion() { return 1; }
1041 bool RenderScriptRuntime::IsVTableName(const char *name) { return false; }
1043 bool RenderScriptRuntime::GetDynamicTypeAndAddress(
1044 ValueObject &in_value, lldb::DynamicValueType use_dynamic,
1045 TypeAndOrName &class_type_or_name, Address &address,
1046 Value::ValueType &value_type) {
1051 RenderScriptRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name,
1052 ValueObject &static_value) {
1053 return type_and_or_name;
1056 bool RenderScriptRuntime::CouldHaveDynamicValue(ValueObject &in_value) {
1060 lldb::BreakpointResolverSP
1061 RenderScriptRuntime::CreateExceptionResolver(Breakpoint *bp, bool catch_bp,
1063 BreakpointResolverSP resolver_sp;
1067 const RenderScriptRuntime::HookDefn RenderScriptRuntime::s_runtimeHookDefns[] =
1070 {"rsdScriptInit", "_Z13rsdScriptInitPKN7android12renderscript7ContextEP"
1071 "NS0_7ScriptCEPKcS7_PKhjj",
1072 "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_"
1073 "7ScriptCEPKcS7_PKhmj",
1074 0, RenderScriptRuntime::eModuleKindDriver,
1075 &lldb_private::RenderScriptRuntime::CaptureScriptInit},
1076 {"rsdScriptInvokeForEachMulti",
1077 "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
1078 "_6ScriptEjPPKNS0_10AllocationEjPS6_PKvjPK12RsScriptCall",
1079 "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
1080 "_6ScriptEjPPKNS0_10AllocationEmPS6_PKvmPK12RsScriptCall",
1081 0, RenderScriptRuntime::eModuleKindDriver,
1082 &lldb_private::RenderScriptRuntime::CaptureScriptInvokeForEachMulti},
1083 {"rsdScriptSetGlobalVar", "_Z21rsdScriptSetGlobalVarPKN7android12render"
1084 "script7ContextEPKNS0_6ScriptEjPvj",
1085 "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_"
1087 0, RenderScriptRuntime::eModuleKindDriver,
1088 &lldb_private::RenderScriptRuntime::CaptureSetGlobalVar},
1091 {"rsdAllocationInit", "_Z17rsdAllocationInitPKN7android12renderscript7C"
1092 "ontextEPNS0_10AllocationEb",
1093 "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_"
1095 0, RenderScriptRuntime::eModuleKindDriver,
1096 &lldb_private::RenderScriptRuntime::CaptureAllocationInit},
1097 {"rsdAllocationRead2D",
1098 "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
1099 "10AllocationEjjj23RsAllocationCubemapFacejjPvjj",
1100 "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
1101 "10AllocationEjjj23RsAllocationCubemapFacejjPvmm",
1102 0, RenderScriptRuntime::eModuleKindDriver, nullptr},
1103 {"rsdAllocationDestroy", "_Z20rsdAllocationDestroyPKN7android12rendersc"
1104 "ript7ContextEPNS0_10AllocationE",
1105 "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_"
1107 0, RenderScriptRuntime::eModuleKindDriver,
1108 &lldb_private::RenderScriptRuntime::CaptureAllocationDestroy},
1110 // renderscript script groups
1111 {"rsdDebugHintScriptGroup2", "_ZN7android12renderscript21debugHintScrip"
1112 "tGroup2EPKcjPKPFvPK24RsExpandKernelDriver"
1114 "_ZN7android12renderscript21debugHintScriptGroup2EPKcjPKPFvPK24RsExpan"
1115 "dKernelDriverInfojjjEj",
1116 0, RenderScriptRuntime::eModuleKindImpl,
1117 &lldb_private::RenderScriptRuntime::CaptureDebugHintScriptGroup2}};
1119 const size_t RenderScriptRuntime::s_runtimeHookCount =
1120 sizeof(s_runtimeHookDefns) / sizeof(s_runtimeHookDefns[0]);
1122 bool RenderScriptRuntime::HookCallback(void *baton,
1123 StoppointCallbackContext *ctx,
1124 lldb::user_id_t break_id,
1125 lldb::user_id_t break_loc_id) {
1126 RuntimeHook *hook = (RuntimeHook *)baton;
1127 ExecutionContext exe_ctx(ctx->exe_ctx_ref);
1129 RenderScriptRuntime *lang_rt =
1130 (RenderScriptRuntime *)exe_ctx.GetProcessPtr()->GetLanguageRuntime(
1131 eLanguageTypeExtRenderScript);
1133 lang_rt->HookCallback(hook, exe_ctx);
1138 void RenderScriptRuntime::HookCallback(RuntimeHook *hook,
1139 ExecutionContext &exe_ctx) {
1140 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1143 log->Printf("%s - '%s'", __FUNCTION__, hook->defn->name);
1145 if (hook->defn->grabber) {
1146 (this->*(hook->defn->grabber))(hook, exe_ctx);
1150 void RenderScriptRuntime::CaptureDebugHintScriptGroup2(
1151 RuntimeHook *hook_info, ExecutionContext &context) {
1152 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1161 std::array<ArgItem, 4> args{{
1162 {ArgItem::ePointer, 0}, // const char *groupName
1163 {ArgItem::eInt32, 0}, // const uint32_t groupNameSize
1164 {ArgItem::ePointer, 0}, // const ExpandFuncTy *kernel
1165 {ArgItem::eInt32, 0}, // const uint32_t kernelCount
1168 if (!GetArgs(context, args.data(), args.size())) {
1170 log->Printf("%s - Error while reading the function parameters",
1174 log->Printf("%s - groupName : 0x%" PRIx64, __FUNCTION__,
1175 addr_t(args[eGroupName]));
1176 log->Printf("%s - groupNameSize: %" PRIu64, __FUNCTION__,
1177 uint64_t(args[eGroupNameSize]));
1178 log->Printf("%s - kernel : 0x%" PRIx64, __FUNCTION__,
1179 addr_t(args[eKernel]));
1180 log->Printf("%s - kernelCount : %" PRIu64, __FUNCTION__,
1181 uint64_t(args[eKernelCount]));
1184 // parse script group name
1185 ConstString group_name;
1188 const uint64_t len = uint64_t(args[eGroupNameSize]);
1189 std::unique_ptr<char[]> buffer(new char[uint32_t(len + 1)]);
1190 m_process->ReadMemory(addr_t(args[eGroupName]), buffer.get(), len, err);
1191 buffer.get()[len] = '\0';
1192 if (!err.Success()) {
1194 log->Printf("Error reading scriptgroup name from target");
1198 log->Printf("Extracted scriptgroup name %s", buffer.get());
1200 // write back the script group name
1201 group_name.SetCString(buffer.get());
1204 // create or access existing script group
1205 RSScriptGroupDescriptorSP group;
1207 // search for existing script group
1208 for (auto sg : m_scriptGroups) {
1209 if (sg->m_name == group_name) {
1215 group.reset(new RSScriptGroupDescriptor);
1216 group->m_name = group_name;
1217 m_scriptGroups.push_back(group);
1219 // already have this script group
1221 log->Printf("Attempt to add duplicate script group %s",
1222 group_name.AsCString());
1228 const uint32_t target_ptr_size = m_process->GetAddressByteSize();
1229 std::vector<addr_t> kernels;
1230 // parse kernel addresses in script group
1231 for (uint64_t i = 0; i < uint64_t(args[eKernelCount]); ++i) {
1232 RSScriptGroupDescriptor::Kernel kernel;
1233 // extract script group kernel addresses from the target
1234 const addr_t ptr_addr = addr_t(args[eKernel]) + i * target_ptr_size;
1235 uint64_t kernel_addr = 0;
1238 m_process->ReadMemory(ptr_addr, &kernel_addr, target_ptr_size, err);
1239 if (!err.Success() || read != target_ptr_size) {
1241 log->Printf("Error parsing kernel address %" PRIu64 " in script group",
1246 log->Printf("Extracted scriptgroup kernel address - 0x%" PRIx64,
1248 kernel.m_addr = kernel_addr;
1250 // try to resolve the associated kernel name
1251 if (!ResolveKernelName(kernel.m_addr, kernel.m_name)) {
1253 log->Printf("Parsed scriptgroup kernel %" PRIu64 " - 0x%" PRIx64, i,
1258 // try to find the non '.expand' function
1260 const llvm::StringRef expand(".expand");
1261 const llvm::StringRef name_ref = kernel.m_name.GetStringRef();
1262 if (name_ref.endswith(expand)) {
1263 const ConstString base_kernel(name_ref.drop_back(expand.size()));
1264 // verify this function is a valid kernel
1265 if (IsKnownKernel(base_kernel)) {
1266 kernel.m_name = base_kernel;
1268 log->Printf("%s - found non expand version '%s'", __FUNCTION__,
1269 base_kernel.GetCString());
1273 // add to a list of script group kernels we know about
1274 group->m_kernels.push_back(kernel);
1277 // Resolve any pending scriptgroup breakpoints
1279 Target &target = m_process->GetTarget();
1280 const BreakpointList &list = target.GetBreakpointList();
1281 const size_t num_breakpoints = list.GetSize();
1283 log->Printf("Resolving %zu breakpoints", num_breakpoints);
1284 for (size_t i = 0; i < num_breakpoints; ++i) {
1285 const BreakpointSP bp = list.GetBreakpointAtIndex(i);
1287 if (bp->MatchesName(group_name.AsCString())) {
1289 log->Printf("Found breakpoint with name %s",
1290 group_name.AsCString());
1291 bp->ResolveBreakpoint();
1298 void RenderScriptRuntime::CaptureScriptInvokeForEachMulti(
1299 RuntimeHook *hook, ExecutionContext &exe_ctx) {
1300 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1314 std::array<ArgItem, 9> args{{
1315 ArgItem{ArgItem::ePointer, 0}, // const Context *rsc
1316 ArgItem{ArgItem::ePointer, 0}, // Script *s
1317 ArgItem{ArgItem::eInt32, 0}, // uint32_t slot
1318 ArgItem{ArgItem::ePointer, 0}, // const Allocation **aIns
1319 ArgItem{ArgItem::eInt32, 0}, // size_t inLen
1320 ArgItem{ArgItem::ePointer, 0}, // Allocation *aout
1321 ArgItem{ArgItem::ePointer, 0}, // const void *usr
1322 ArgItem{ArgItem::eInt32, 0}, // size_t usrLen
1323 ArgItem{ArgItem::ePointer, 0}, // const RsScriptCall *sc
1326 bool success = GetArgs(exe_ctx, &args[0], args.size());
1329 log->Printf("%s - Error while reading the function parameters",
1334 const uint32_t target_ptr_size = m_process->GetAddressByteSize();
1336 std::vector<uint64_t> allocs;
1338 // traverse allocation list
1339 for (uint64_t i = 0; i < uint64_t(args[eRsInLen]); ++i) {
1340 // calculate offest to allocation pointer
1341 const addr_t addr = addr_t(args[eRsAIns]) + i * target_ptr_size;
1343 // Note: due to little endian layout, reading 32bits or 64bits into res
1344 // will give the correct results.
1345 uint64_t result = 0;
1346 size_t read = m_process->ReadMemory(addr, &result, target_ptr_size, err);
1347 if (read != target_ptr_size || !err.Success()) {
1350 "%s - Error while reading allocation list argument %" PRIu64,
1353 allocs.push_back(result);
1357 // if there is an output allocation track it
1358 if (uint64_t alloc_out = uint64_t(args[eRsAOut])) {
1359 allocs.push_back(alloc_out);
1362 // for all allocations we have found
1363 for (const uint64_t alloc_addr : allocs) {
1364 AllocationDetails *alloc = LookUpAllocation(alloc_addr);
1366 alloc = CreateAllocation(alloc_addr);
1369 // save the allocation address
1370 if (alloc->address.isValid()) {
1371 // check the allocation address we already have matches
1372 assert(*alloc->address.get() == alloc_addr);
1374 alloc->address = alloc_addr;
1379 if (alloc->context.isValid() &&
1380 *alloc->context.get() != addr_t(args[eRsContext]))
1381 log->Printf("%s - Allocation used by multiple contexts",
1384 alloc->context = addr_t(args[eRsContext]);
1388 // make sure we track this script object
1389 if (lldb_private::RenderScriptRuntime::ScriptDetails *script =
1390 LookUpScript(addr_t(args[eRsScript]), true)) {
1392 if (script->context.isValid() &&
1393 *script->context.get() != addr_t(args[eRsContext]))
1394 log->Printf("%s - Script used by multiple contexts", __FUNCTION__);
1396 script->context = addr_t(args[eRsContext]);
1400 void RenderScriptRuntime::CaptureSetGlobalVar(RuntimeHook *hook,
1401 ExecutionContext &context) {
1402 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1412 std::array<ArgItem, 5> args{{
1413 ArgItem{ArgItem::ePointer, 0}, // eRsContext
1414 ArgItem{ArgItem::ePointer, 0}, // eRsScript
1415 ArgItem{ArgItem::eInt32, 0}, // eRsId
1416 ArgItem{ArgItem::ePointer, 0}, // eRsData
1417 ArgItem{ArgItem::eInt32, 0}, // eRsLength
1420 bool success = GetArgs(context, &args[0], args.size());
1423 log->Printf("%s - error reading the function parameters.", __FUNCTION__);
1428 log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " slot %" PRIu64 " = 0x%" PRIx64
1429 ":%" PRIu64 "bytes.",
1430 __FUNCTION__, uint64_t(args[eRsContext]),
1431 uint64_t(args[eRsScript]), uint64_t(args[eRsId]),
1432 uint64_t(args[eRsData]), uint64_t(args[eRsLength]));
1434 addr_t script_addr = addr_t(args[eRsScript]);
1435 if (m_scriptMappings.find(script_addr) != m_scriptMappings.end()) {
1436 auto rsm = m_scriptMappings[script_addr];
1437 if (uint64_t(args[eRsId]) < rsm->m_globals.size()) {
1438 auto rsg = rsm->m_globals[uint64_t(args[eRsId])];
1439 log->Printf("%s - Setting of '%s' within '%s' inferred", __FUNCTION__,
1440 rsg.m_name.AsCString(),
1441 rsm->m_module->GetFileSpec().GetFilename().AsCString());
1447 void RenderScriptRuntime::CaptureAllocationInit(RuntimeHook *hook,
1448 ExecutionContext &exe_ctx) {
1449 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1451 enum { eRsContext, eRsAlloc, eRsForceZero };
1453 std::array<ArgItem, 3> args{{
1454 ArgItem{ArgItem::ePointer, 0}, // eRsContext
1455 ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
1456 ArgItem{ArgItem::eBool, 0}, // eRsForceZero
1459 bool success = GetArgs(exe_ctx, &args[0], args.size());
1462 log->Printf("%s - error while reading the function parameters",
1468 log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 ",0x%" PRIx64 " .",
1469 __FUNCTION__, uint64_t(args[eRsContext]),
1470 uint64_t(args[eRsAlloc]), uint64_t(args[eRsForceZero]));
1472 AllocationDetails *alloc = CreateAllocation(uint64_t(args[eRsAlloc]));
1474 alloc->context = uint64_t(args[eRsContext]);
1477 void RenderScriptRuntime::CaptureAllocationDestroy(RuntimeHook *hook,
1478 ExecutionContext &exe_ctx) {
1479 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1486 std::array<ArgItem, 2> args{{
1487 ArgItem{ArgItem::ePointer, 0}, // eRsContext
1488 ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
1491 bool success = GetArgs(exe_ctx, &args[0], args.size());
1494 log->Printf("%s - error while reading the function parameters.",
1500 log->Printf("%s - 0x%" PRIx64 ", 0x%" PRIx64 ".", __FUNCTION__,
1501 uint64_t(args[eRsContext]), uint64_t(args[eRsAlloc]));
1503 for (auto iter = m_allocations.begin(); iter != m_allocations.end(); ++iter) {
1504 auto &allocation_ap = *iter; // get the unique pointer
1505 if (allocation_ap->address.isValid() &&
1506 *allocation_ap->address.get() == addr_t(args[eRsAlloc])) {
1507 m_allocations.erase(iter);
1509 log->Printf("%s - deleted allocation entry.", __FUNCTION__);
1515 log->Printf("%s - couldn't find destroyed allocation.", __FUNCTION__);
1518 void RenderScriptRuntime::CaptureScriptInit(RuntimeHook *hook,
1519 ExecutionContext &exe_ctx) {
1520 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1523 Process *process = exe_ctx.GetProcessPtr();
1525 enum { eRsContext, eRsScript, eRsResNamePtr, eRsCachedDirPtr };
1527 std::array<ArgItem, 4> args{
1528 {ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0},
1529 ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0}}};
1530 bool success = GetArgs(exe_ctx, &args[0], args.size());
1533 log->Printf("%s - error while reading the function parameters.",
1538 std::string res_name;
1539 process->ReadCStringFromMemory(addr_t(args[eRsResNamePtr]), res_name, err);
1542 log->Printf("%s - error reading res_name: %s.", __FUNCTION__,
1546 std::string cache_dir;
1547 process->ReadCStringFromMemory(addr_t(args[eRsCachedDirPtr]), cache_dir, err);
1550 log->Printf("%s - error reading cache_dir: %s.", __FUNCTION__,
1555 log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " => '%s' at '%s' .",
1556 __FUNCTION__, uint64_t(args[eRsContext]),
1557 uint64_t(args[eRsScript]), res_name.c_str(), cache_dir.c_str());
1559 if (res_name.size() > 0) {
1561 strm.Printf("librs.%s.so", res_name.c_str());
1563 ScriptDetails *script = LookUpScript(addr_t(args[eRsScript]), true);
1565 script->type = ScriptDetails::eScriptC;
1566 script->cache_dir = cache_dir;
1567 script->res_name = res_name;
1568 script->shared_lib = strm.GetString();
1569 script->context = addr_t(args[eRsContext]);
1573 log->Printf("%s - '%s' tagged with context 0x%" PRIx64
1574 " and script 0x%" PRIx64 ".",
1575 __FUNCTION__, strm.GetData(), uint64_t(args[eRsContext]),
1576 uint64_t(args[eRsScript]));
1578 log->Printf("%s - resource name invalid, Script not tagged.", __FUNCTION__);
1582 void RenderScriptRuntime::LoadRuntimeHooks(lldb::ModuleSP module,
1584 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1590 Target &target = GetProcess()->GetTarget();
1591 const llvm::Triple::ArchType machine = target.GetArchitecture().GetMachine();
1593 if (machine != llvm::Triple::ArchType::x86 &&
1594 machine != llvm::Triple::ArchType::arm &&
1595 machine != llvm::Triple::ArchType::aarch64 &&
1596 machine != llvm::Triple::ArchType::mipsel &&
1597 machine != llvm::Triple::ArchType::mips64el &&
1598 machine != llvm::Triple::ArchType::x86_64) {
1600 log->Printf("%s - unable to hook runtime functions.", __FUNCTION__);
1604 const uint32_t target_ptr_size =
1605 target.GetArchitecture().GetAddressByteSize();
1607 std::array<bool, s_runtimeHookCount> hook_placed;
1608 hook_placed.fill(false);
1610 for (size_t idx = 0; idx < s_runtimeHookCount; idx++) {
1611 const HookDefn *hook_defn = &s_runtimeHookDefns[idx];
1612 if (hook_defn->kind != kind) {
1616 const char *symbol_name = (target_ptr_size == 4)
1617 ? hook_defn->symbol_name_m32
1618 : hook_defn->symbol_name_m64;
1620 const Symbol *sym = module->FindFirstSymbolWithNameAndType(
1621 ConstString(symbol_name), eSymbolTypeCode);
1624 log->Printf("%s - symbol '%s' related to the function %s not found",
1625 __FUNCTION__, symbol_name, hook_defn->name);
1630 addr_t addr = sym->GetLoadAddress(&target);
1631 if (addr == LLDB_INVALID_ADDRESS) {
1633 log->Printf("%s - unable to resolve the address of hook function '%s' "
1634 "with symbol '%s'.",
1635 __FUNCTION__, hook_defn->name, symbol_name);
1639 log->Printf("%s - function %s, address resolved at 0x%" PRIx64,
1640 __FUNCTION__, hook_defn->name, addr);
1643 RuntimeHookSP hook(new RuntimeHook());
1644 hook->address = addr;
1645 hook->defn = hook_defn;
1646 hook->bp_sp = target.CreateBreakpoint(addr, true, false);
1647 hook->bp_sp->SetCallback(HookCallback, hook.get(), true);
1648 m_runtimeHooks[addr] = hook;
1650 log->Printf("%s - successfully hooked '%s' in '%s' version %" PRIu64
1651 " at 0x%" PRIx64 ".",
1652 __FUNCTION__, hook_defn->name,
1653 module->GetFileSpec().GetFilename().AsCString(),
1654 (uint64_t)hook_defn->version, (uint64_t)addr);
1656 hook_placed[idx] = true;
1659 // log any unhooked function
1661 for (size_t i = 0; i < hook_placed.size(); ++i) {
1664 const HookDefn &hook_defn = s_runtimeHookDefns[i];
1665 if (hook_defn.kind != kind)
1667 log->Printf("%s - function %s was not hooked", __FUNCTION__,
1673 void RenderScriptRuntime::FixupScriptDetails(RSModuleDescriptorSP rsmodule_sp) {
1677 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1679 const ModuleSP module = rsmodule_sp->m_module;
1680 const FileSpec &file = module->GetPlatformFileSpec();
1682 // Iterate over all of the scripts that we currently know of. Note: We cant
1683 // push or pop to m_scripts here or it may invalidate rs_script.
1684 for (const auto &rs_script : m_scripts) {
1685 // Extract the expected .so file path for this script.
1686 std::string shared_lib;
1687 if (!rs_script->shared_lib.get(shared_lib))
1690 // Only proceed if the module that has loaded corresponds to this script.
1691 if (file.GetFilename() != ConstString(shared_lib.c_str()))
1694 // Obtain the script address which we use as a key.
1695 lldb::addr_t script;
1696 if (!rs_script->script.get(script))
1699 // If we have a script mapping for the current script.
1700 if (m_scriptMappings.find(script) != m_scriptMappings.end()) {
1701 // if the module we have stored is different to the one we just received.
1702 if (m_scriptMappings[script] != rsmodule_sp) {
1705 "%s - script %" PRIx64 " wants reassigned to new rsmodule '%s'.",
1706 __FUNCTION__, (uint64_t)script,
1707 rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
1710 // We don't have a script mapping for the current script.
1712 // Obtain the script resource name.
1713 std::string res_name;
1714 if (rs_script->res_name.get(res_name))
1715 // Set the modules resource name.
1716 rsmodule_sp->m_resname = res_name;
1717 // Add Script/Module pair to map.
1718 m_scriptMappings[script] = rsmodule_sp;
1721 "%s - script %" PRIx64 " associated with rsmodule '%s'.",
1722 __FUNCTION__, (uint64_t)script,
1723 rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
1728 // Uses the Target API to evaluate the expression passed as a parameter to the
1729 // function The result of that expression is returned an unsigned 64 bit int,
1730 // via the result* parameter. Function returns true on success, and false on
1732 bool RenderScriptRuntime::EvalRSExpression(const char *expr,
1733 StackFrame *frame_ptr,
1735 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1737 log->Printf("%s(%s)", __FUNCTION__, expr);
1739 ValueObjectSP expr_result;
1740 EvaluateExpressionOptions options;
1741 options.SetLanguage(lldb::eLanguageTypeC_plus_plus);
1742 // Perform the actual expression evaluation
1743 auto &target = GetProcess()->GetTarget();
1744 target.EvaluateExpression(expr, frame_ptr, expr_result, options);
1748 log->Printf("%s: couldn't evaluate expression.", __FUNCTION__);
1752 // The result of the expression is invalid
1753 if (!expr_result->GetError().Success()) {
1754 Status err = expr_result->GetError();
1755 // Expression returned is void, so this is actually a success
1756 if (err.GetError() == UserExpression::kNoResult) {
1758 log->Printf("%s - expression returned void.", __FUNCTION__);
1765 log->Printf("%s - error evaluating expression result: %s", __FUNCTION__,
1770 bool success = false;
1771 // We only read the result as an uint32_t.
1772 *result = expr_result->GetValueAsUnsigned(0, &success);
1776 log->Printf("%s - couldn't convert expression result to uint32_t",
1785 // Used to index expression format strings
1786 enum ExpressionStrings {
1787 eExprGetOffsetPtr = 0,
1796 eExprElementFieldCount,
1798 eExprSubelementsName,
1799 eExprSubelementsArrSize,
1801 _eExprLast // keep at the end, implicit size of the array runtime_expressions
1804 // max length of an expanded expression
1805 const int jit_max_expr_size = 512;
1807 // Retrieve the string to JIT for the given expression
1808 #define JIT_TEMPLATE_CONTEXT "void* ctxt = (void*)rsDebugGetContextWrapper(0x%" PRIx64 "); "
1809 const char *JITTemplate(ExpressionStrings e) {
1810 // Format strings containing the expressions we may need to evaluate.
1811 static std::array<const char *, _eExprLast> runtime_expressions = {
1812 {// Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap)
1814 "Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocation"
1816 "(0x%" PRIx64 ", %" PRIu32 ", %" PRIu32 ", %" PRIu32 ", 0, 0)", // eExprGetOffsetPtr
1818 // Type* rsaAllocationGetType(Context*, Allocation*)
1819 JIT_TEMPLATE_CONTEXT "(void*)rsaAllocationGetType(ctxt, 0x%" PRIx64 ")", // eExprAllocGetType
1821 // rsaTypeGetNativeData(Context*, Type*, void* typeData, size) Pack the
1822 // data in the following way mHal.state.dimX; mHal.state.dimY;
1823 // mHal.state.dimZ; mHal.state.lodCount; mHal.state.faces; mElement;
1824 // into typeData Need to specify 32 or 64 bit for uint_t since this
1825 // differs between devices
1826 JIT_TEMPLATE_CONTEXT
1827 "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
1828 ", 0x%" PRIx64 ", data, 6); data[0]", // eExprTypeDimX
1829 JIT_TEMPLATE_CONTEXT
1830 "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
1831 ", 0x%" PRIx64 ", data, 6); data[1]", // eExprTypeDimY
1832 JIT_TEMPLATE_CONTEXT
1833 "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
1834 ", 0x%" PRIx64 ", data, 6); data[2]", // eExprTypeDimZ
1835 JIT_TEMPLATE_CONTEXT
1836 "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
1837 ", 0x%" PRIx64 ", data, 6); data[5]", // eExprTypeElemPtr
1839 // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size)
1840 // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into
1842 JIT_TEMPLATE_CONTEXT
1843 "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
1844 ", 0x%" PRIx64 ", data, 5); data[0]", // eExprElementType
1845 JIT_TEMPLATE_CONTEXT
1846 "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
1847 ", 0x%" PRIx64 ", data, 5); data[1]", // eExprElementKind
1848 JIT_TEMPLATE_CONTEXT
1849 "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
1850 ", 0x%" PRIx64 ", data, 5); data[3]", // eExprElementVec
1851 JIT_TEMPLATE_CONTEXT
1852 "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
1853 ", 0x%" PRIx64 ", data, 5); data[4]", // eExprElementFieldCount
1855 // rsaElementGetSubElements(RsContext con, RsElement elem, uintptr_t
1856 // *ids, const char **names, size_t *arraySizes, uint32_t dataSize)
1857 // Needed for Allocations of structs to gather details about
1858 // fields/Subelements Element* of field
1859 JIT_TEMPLATE_CONTEXT "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1860 "]; size_t arr_size[%" PRIu32 "];"
1861 "(void*)rsaElementGetSubElements(ctxt, 0x%" PRIx64
1862 ", ids, names, arr_size, %" PRIu32 "); ids[%" PRIu32 "]", // eExprSubelementsId
1865 JIT_TEMPLATE_CONTEXT "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1866 "]; size_t arr_size[%" PRIu32 "];"
1867 "(void*)rsaElementGetSubElements(ctxt, 0x%" PRIx64
1868 ", ids, names, arr_size, %" PRIu32 "); names[%" PRIu32 "]", // eExprSubelementsName
1870 // Array size of field
1871 JIT_TEMPLATE_CONTEXT "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1872 "]; size_t arr_size[%" PRIu32 "];"
1873 "(void*)rsaElementGetSubElements(ctxt, 0x%" PRIx64
1874 ", ids, names, arr_size, %" PRIu32 "); arr_size[%" PRIu32 "]"}}; // eExprSubelementsArrSize
1876 return runtime_expressions[e];
1878 } // end of the anonymous namespace
1880 // JITs the RS runtime for the internal data pointer of an allocation. Is
1881 // passed x,y,z coordinates for the pointer to a specific element. Then sets
1882 // the data_ptr member in Allocation with the result. Returns true on success,
1884 bool RenderScriptRuntime::JITDataPointer(AllocationDetails *alloc,
1885 StackFrame *frame_ptr, uint32_t x,
1886 uint32_t y, uint32_t z) {
1887 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1889 if (!alloc->address.isValid()) {
1891 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
1895 const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
1896 char expr_buf[jit_max_expr_size];
1898 int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
1899 *alloc->address.get(), x, y, z);
1902 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1904 } else if (written >= jit_max_expr_size) {
1906 log->Printf("%s - expression too long.", __FUNCTION__);
1910 uint64_t result = 0;
1911 if (!EvalRSExpression(expr_buf, frame_ptr, &result))
1914 addr_t data_ptr = static_cast<lldb::addr_t>(result);
1915 alloc->data_ptr = data_ptr;
1920 // JITs the RS runtime for the internal pointer to the RS Type of an allocation
1921 // Then sets the type_ptr member in Allocation with the result. Returns true on
1922 // success, false otherwise
1923 bool RenderScriptRuntime::JITTypePointer(AllocationDetails *alloc,
1924 StackFrame *frame_ptr) {
1925 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1927 if (!alloc->address.isValid() || !alloc->context.isValid()) {
1929 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
1933 const char *fmt_str = JITTemplate(eExprAllocGetType);
1934 char expr_buf[jit_max_expr_size];
1936 int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
1937 *alloc->context.get(), *alloc->address.get());
1940 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1942 } else if (written >= jit_max_expr_size) {
1944 log->Printf("%s - expression too long.", __FUNCTION__);
1948 uint64_t result = 0;
1949 if (!EvalRSExpression(expr_buf, frame_ptr, &result))
1952 addr_t type_ptr = static_cast<lldb::addr_t>(result);
1953 alloc->type_ptr = type_ptr;
1958 // JITs the RS runtime for information about the dimensions and type of an
1959 // allocation Then sets dimension and element_ptr members in Allocation with
1960 // the result. Returns true on success, false otherwise
1961 bool RenderScriptRuntime::JITTypePacked(AllocationDetails *alloc,
1962 StackFrame *frame_ptr) {
1963 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1965 if (!alloc->type_ptr.isValid() || !alloc->context.isValid()) {
1967 log->Printf("%s - Failed to find allocation details.", __FUNCTION__);
1971 // Expression is different depending on if device is 32 or 64 bit
1972 uint32_t target_ptr_size =
1973 GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
1974 const uint32_t bits = target_ptr_size == 4 ? 32 : 64;
1976 // We want 4 elements from packed data
1977 const uint32_t num_exprs = 4;
1978 assert(num_exprs == (eExprTypeElemPtr - eExprTypeDimX + 1) &&
1979 "Invalid number of expressions");
1981 char expr_bufs[num_exprs][jit_max_expr_size];
1982 uint64_t results[num_exprs];
1984 for (uint32_t i = 0; i < num_exprs; ++i) {
1985 const char *fmt_str = JITTemplate(ExpressionStrings(eExprTypeDimX + i));
1986 int written = snprintf(expr_bufs[i], jit_max_expr_size, fmt_str,
1987 *alloc->context.get(), bits, *alloc->type_ptr.get());
1990 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1992 } else if (written >= jit_max_expr_size) {
1994 log->Printf("%s - expression too long.", __FUNCTION__);
1998 // Perform expression evaluation
1999 if (!EvalRSExpression(expr_bufs[i], frame_ptr, &results[i]))
2003 // Assign results to allocation members
2004 AllocationDetails::Dimension dims;
2005 dims.dim_1 = static_cast<uint32_t>(results[0]);
2006 dims.dim_2 = static_cast<uint32_t>(results[1]);
2007 dims.dim_3 = static_cast<uint32_t>(results[2]);
2008 alloc->dimension = dims;
2010 addr_t element_ptr = static_cast<lldb::addr_t>(results[3]);
2011 alloc->element.element_ptr = element_ptr;
2014 log->Printf("%s - dims (%" PRIu32 ", %" PRIu32 ", %" PRIu32
2015 ") Element*: 0x%" PRIx64 ".",
2016 __FUNCTION__, dims.dim_1, dims.dim_2, dims.dim_3, element_ptr);
2021 // JITs the RS runtime for information about the Element of an allocation Then
2022 // sets type, type_vec_size, field_count and type_kind members in Element with
2023 // the result. Returns true on success, false otherwise
2024 bool RenderScriptRuntime::JITElementPacked(Element &elem,
2025 const lldb::addr_t context,
2026 StackFrame *frame_ptr) {
2027 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2029 if (!elem.element_ptr.isValid()) {
2031 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
2035 // We want 4 elements from packed data
2036 const uint32_t num_exprs = 4;
2037 assert(num_exprs == (eExprElementFieldCount - eExprElementType + 1) &&
2038 "Invalid number of expressions");
2040 char expr_bufs[num_exprs][jit_max_expr_size];
2041 uint64_t results[num_exprs];
2043 for (uint32_t i = 0; i < num_exprs; i++) {
2044 const char *fmt_str = JITTemplate(ExpressionStrings(eExprElementType + i));
2045 int written = snprintf(expr_bufs[i], jit_max_expr_size, fmt_str, context,
2046 *elem.element_ptr.get());
2049 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
2051 } else if (written >= jit_max_expr_size) {
2053 log->Printf("%s - expression too long.", __FUNCTION__);
2057 // Perform expression evaluation
2058 if (!EvalRSExpression(expr_bufs[i], frame_ptr, &results[i]))
2062 // Assign results to allocation members
2063 elem.type = static_cast<RenderScriptRuntime::Element::DataType>(results[0]);
2065 static_cast<RenderScriptRuntime::Element::DataKind>(results[1]);
2066 elem.type_vec_size = static_cast<uint32_t>(results[2]);
2067 elem.field_count = static_cast<uint32_t>(results[3]);
2070 log->Printf("%s - data type %" PRIu32 ", pixel type %" PRIu32
2071 ", vector size %" PRIu32 ", field count %" PRIu32,
2072 __FUNCTION__, *elem.type.get(), *elem.type_kind.get(),
2073 *elem.type_vec_size.get(), *elem.field_count.get());
2075 // If this Element has subelements then JIT rsaElementGetSubElements() for
2076 // details about its fields
2077 return !(*elem.field_count.get() > 0 &&
2078 !JITSubelements(elem, context, frame_ptr));
2081 // JITs the RS runtime for information about the subelements/fields of a struct
2082 // allocation This is necessary for infering the struct type so we can pretty
2083 // print the allocation's contents. Returns true on success, false otherwise
2084 bool RenderScriptRuntime::JITSubelements(Element &elem,
2085 const lldb::addr_t context,
2086 StackFrame *frame_ptr) {
2087 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2089 if (!elem.element_ptr.isValid() || !elem.field_count.isValid()) {
2091 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
2095 const short num_exprs = 3;
2096 assert(num_exprs == (eExprSubelementsArrSize - eExprSubelementsId + 1) &&
2097 "Invalid number of expressions");
2099 char expr_buffer[jit_max_expr_size];
2102 // Iterate over struct fields.
2103 const uint32_t field_count = *elem.field_count.get();
2104 for (uint32_t field_index = 0; field_index < field_count; ++field_index) {
2106 for (uint32_t expr_index = 0; expr_index < num_exprs; ++expr_index) {
2107 const char *fmt_str =
2108 JITTemplate(ExpressionStrings(eExprSubelementsId + expr_index));
2109 int written = snprintf(expr_buffer, jit_max_expr_size, fmt_str,
2110 context, field_count, field_count, field_count,
2111 *elem.element_ptr.get(), field_count, field_index);
2114 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
2116 } else if (written >= jit_max_expr_size) {
2118 log->Printf("%s - expression too long.", __FUNCTION__);
2122 // Perform expression evaluation
2123 if (!EvalRSExpression(expr_buffer, frame_ptr, &results))
2127 log->Printf("%s - expr result 0x%" PRIx64 ".", __FUNCTION__, results);
2129 switch (expr_index) {
2130 case 0: // Element* of child
2131 child.element_ptr = static_cast<addr_t>(results);
2133 case 1: // Name of child
2135 lldb::addr_t address = static_cast<addr_t>(results);
2138 GetProcess()->ReadCStringFromMemory(address, name, err);
2140 child.type_name = ConstString(name);
2143 log->Printf("%s - warning: Couldn't read field name.",
2148 case 2: // Array size of child
2149 child.array_size = static_cast<uint32_t>(results);
2154 // We need to recursively JIT each Element field of the struct since
2155 // structs can be nested inside structs.
2156 if (!JITElementPacked(child, context, frame_ptr))
2158 elem.children.push_back(child);
2161 // Try to infer the name of the struct type so we can pretty print the
2162 // allocation contents.
2163 FindStructTypeName(elem, frame_ptr);
2168 // JITs the RS runtime for the address of the last element in the allocation.
2169 // The `elem_size` parameter represents the size of a single element, including
2170 // padding. Which is needed as an offset from the last element pointer. Using
2171 // this offset minus the starting address we can calculate the size of the
2172 // allocation. Returns true on success, false otherwise
2173 bool RenderScriptRuntime::JITAllocationSize(AllocationDetails *alloc,
2174 StackFrame *frame_ptr) {
2175 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2177 if (!alloc->address.isValid() || !alloc->dimension.isValid() ||
2178 !alloc->data_ptr.isValid() || !alloc->element.datum_size.isValid()) {
2180 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
2185 uint32_t dim_x = alloc->dimension.get()->dim_1;
2186 uint32_t dim_y = alloc->dimension.get()->dim_2;
2187 uint32_t dim_z = alloc->dimension.get()->dim_3;
2189 // Our plan of jitting the last element address doesn't seem to work for
2190 // struct Allocations` Instead try to infer the size ourselves without any
2191 // inter element padding.
2192 if (alloc->element.children.size() > 0) {
2200 alloc->size = dim_x * dim_y * dim_z * *alloc->element.datum_size.get();
2203 log->Printf("%s - inferred size of struct allocation %" PRIu32 ".",
2204 __FUNCTION__, *alloc->size.get());
2208 const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
2209 char expr_buf[jit_max_expr_size];
2211 // Calculate last element
2212 dim_x = dim_x == 0 ? 0 : dim_x - 1;
2213 dim_y = dim_y == 0 ? 0 : dim_y - 1;
2214 dim_z = dim_z == 0 ? 0 : dim_z - 1;
2216 int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
2217 *alloc->address.get(), dim_x, dim_y, dim_z);
2220 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
2222 } else if (written >= jit_max_expr_size) {
2224 log->Printf("%s - expression too long.", __FUNCTION__);
2228 uint64_t result = 0;
2229 if (!EvalRSExpression(expr_buf, frame_ptr, &result))
2232 addr_t mem_ptr = static_cast<lldb::addr_t>(result);
2233 // Find pointer to last element and add on size of an element
2234 alloc->size = static_cast<uint32_t>(mem_ptr - *alloc->data_ptr.get()) +
2235 *alloc->element.datum_size.get();
2240 // JITs the RS runtime for information about the stride between rows in the
2241 // allocation. This is done to detect padding, since allocated memory is
2242 // 16-byte aligned. Returns true on success, false otherwise
2243 bool RenderScriptRuntime::JITAllocationStride(AllocationDetails *alloc,
2244 StackFrame *frame_ptr) {
2245 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2247 if (!alloc->address.isValid() || !alloc->data_ptr.isValid()) {
2249 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
2253 const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
2254 char expr_buf[jit_max_expr_size];
2256 int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
2257 *alloc->address.get(), 0, 1, 0);
2260 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
2262 } else if (written >= jit_max_expr_size) {
2264 log->Printf("%s - expression too long.", __FUNCTION__);
2268 uint64_t result = 0;
2269 if (!EvalRSExpression(expr_buf, frame_ptr, &result))
2272 addr_t mem_ptr = static_cast<lldb::addr_t>(result);
2273 alloc->stride = static_cast<uint32_t>(mem_ptr - *alloc->data_ptr.get());
2278 // JIT all the current runtime info regarding an allocation
2279 bool RenderScriptRuntime::RefreshAllocation(AllocationDetails *alloc,
2280 StackFrame *frame_ptr) {
2281 // GetOffsetPointer()
2282 if (!JITDataPointer(alloc, frame_ptr))
2285 // rsaAllocationGetType()
2286 if (!JITTypePointer(alloc, frame_ptr))
2289 // rsaTypeGetNativeData()
2290 if (!JITTypePacked(alloc, frame_ptr))
2293 // rsaElementGetNativeData()
2294 if (!JITElementPacked(alloc->element, *alloc->context.get(), frame_ptr))
2297 // Sets the datum_size member in Element
2298 SetElementSize(alloc->element);
2300 // Use GetOffsetPointer() to infer size of the allocation
2301 return JITAllocationSize(alloc, frame_ptr);
2304 // Function attempts to set the type_name member of the paramaterised Element
2305 // object. This string should be the name of the struct type the Element
2306 // represents. We need this string for pretty printing the Element to users.
2307 void RenderScriptRuntime::FindStructTypeName(Element &elem,
2308 StackFrame *frame_ptr) {
2309 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2311 if (!elem.type_name.IsEmpty()) // Name already set
2314 elem.type_name = Element::GetFallbackStructName(); // Default type name if
2317 // Find all the global variables from the script rs modules
2318 VariableList var_list;
2319 for (auto module_sp : m_rsmodules)
2320 module_sp->m_module->FindGlobalVariables(
2321 RegularExpression(llvm::StringRef(".")), UINT32_MAX, var_list);
2323 // Iterate over all the global variables looking for one with a matching type
2324 // to the Element. We make the assumption a match exists since there needs to
2325 // be a global variable to reflect the struct type back into java host code.
2326 for (uint32_t i = 0; i < var_list.GetSize(); ++i) {
2327 const VariableSP var_sp(var_list.GetVariableAtIndex(i));
2331 ValueObjectSP valobj_sp = ValueObjectVariable::Create(frame_ptr, var_sp);
2335 // Find the number of variable fields.
2336 // If it has no fields, or more fields than our Element, then it can't be
2337 // the struct we're looking for. Don't check for equality since RS can add
2338 // extra struct members for padding.
2339 size_t num_children = valobj_sp->GetNumChildren();
2340 if (num_children > elem.children.size() || num_children == 0)
2343 // Iterate over children looking for members with matching field names. If
2344 // all the field names match, this is likely the struct we want.
2345 // TODO: This could be made more robust by also checking children data
2346 // sizes, or array size
2348 for (size_t i = 0; i < num_children; ++i) {
2349 ValueObjectSP child = valobj_sp->GetChildAtIndex(i, true);
2350 if (!child || (child->GetName() != elem.children[i].type_name)) {
2356 // RS can add extra struct members for padding in the format
2357 // '#rs_padding_[0-9]+'
2358 if (found && num_children < elem.children.size()) {
2359 const uint32_t size_diff = elem.children.size() - num_children;
2361 log->Printf("%s - %" PRIu32 " padding struct entries", __FUNCTION__,
2364 for (uint32_t i = 0; i < size_diff; ++i) {
2365 const ConstString &name = elem.children[num_children + i].type_name;
2366 if (strcmp(name.AsCString(), "#rs_padding") < 0)
2371 // We've found a global variable with matching type
2373 // Dereference since our Element type isn't a pointer.
2374 if (valobj_sp->IsPointerType()) {
2376 ValueObjectSP deref_valobj = valobj_sp->Dereference(err);
2378 valobj_sp = deref_valobj;
2381 // Save name of variable in Element.
2382 elem.type_name = valobj_sp->GetTypeName();
2384 log->Printf("%s - element name set to %s", __FUNCTION__,
2385 elem.type_name.AsCString());
2392 // Function sets the datum_size member of Element. Representing the size of a
2393 // single instance including padding. Assumes the relevant allocation
2394 // information has already been jitted.
2395 void RenderScriptRuntime::SetElementSize(Element &elem) {
2396 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2397 const Element::DataType type = *elem.type.get();
2398 assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
2399 "Invalid allocation type");
2401 const uint32_t vec_size = *elem.type_vec_size.get();
2402 uint32_t data_size = 0;
2403 uint32_t padding = 0;
2405 // Element is of a struct type, calculate size recursively.
2406 if ((type == Element::RS_TYPE_NONE) && (elem.children.size() > 0)) {
2407 for (Element &child : elem.children) {
2408 SetElementSize(child);
2409 const uint32_t array_size =
2410 child.array_size.isValid() ? *child.array_size.get() : 1;
2411 data_size += *child.datum_size.get() * array_size;
2414 // These have been packed already
2415 else if (type == Element::RS_TYPE_UNSIGNED_5_6_5 ||
2416 type == Element::RS_TYPE_UNSIGNED_5_5_5_1 ||
2417 type == Element::RS_TYPE_UNSIGNED_4_4_4_4) {
2418 data_size = AllocationDetails::RSTypeToFormat[type][eElementSize];
2419 } else if (type < Element::RS_TYPE_ELEMENT) {
2421 vec_size * AllocationDetails::RSTypeToFormat[type][eElementSize];
2423 padding = AllocationDetails::RSTypeToFormat[type][eElementSize];
2426 GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
2428 elem.padding = padding;
2429 elem.datum_size = data_size + padding;
2431 log->Printf("%s - element size set to %" PRIu32, __FUNCTION__,
2432 data_size + padding);
2435 // Given an allocation, this function copies the allocation contents from
2436 // device into a buffer on the heap. Returning a shared pointer to the buffer
2437 // containing the data.
2438 std::shared_ptr<uint8_t>
2439 RenderScriptRuntime::GetAllocationData(AllocationDetails *alloc,
2440 StackFrame *frame_ptr) {
2441 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2443 // JIT all the allocation details
2444 if (alloc->ShouldRefresh()) {
2446 log->Printf("%s - allocation details not calculated yet, jitting info",
2449 if (!RefreshAllocation(alloc, frame_ptr)) {
2451 log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
2456 assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2457 alloc->element.type_vec_size.isValid() && alloc->size.isValid() &&
2458 "Allocation information not available");
2460 // Allocate a buffer to copy data into
2461 const uint32_t size = *alloc->size.get();
2462 std::shared_ptr<uint8_t> buffer(new uint8_t[size]);
2465 log->Printf("%s - couldn't allocate a %" PRIu32 " byte buffer",
2466 __FUNCTION__, size);
2470 // Read the inferior memory
2472 lldb::addr_t data_ptr = *alloc->data_ptr.get();
2473 GetProcess()->ReadMemory(data_ptr, buffer.get(), size, err);
2476 log->Printf("%s - '%s' Couldn't read %" PRIu32
2477 " bytes of allocation data from 0x%" PRIx64,
2478 __FUNCTION__, err.AsCString(), size, data_ptr);
2485 // Function copies data from a binary file into an allocation. There is a
2486 // header at the start of the file, FileHeader, before the data content itself.
2487 // Information from this header is used to display warnings to the user about
2488 // incompatibilities
2489 bool RenderScriptRuntime::LoadAllocation(Stream &strm, const uint32_t alloc_id,
2491 StackFrame *frame_ptr) {
2492 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2494 // Find allocation with the given id
2495 AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
2500 log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__,
2501 *alloc->address.get());
2503 // JIT all the allocation details
2504 if (alloc->ShouldRefresh()) {
2506 log->Printf("%s - allocation details not calculated yet, jitting info.",
2509 if (!RefreshAllocation(alloc, frame_ptr)) {
2511 log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
2516 assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2517 alloc->element.type_vec_size.isValid() && alloc->size.isValid() &&
2518 alloc->element.datum_size.isValid() &&
2519 "Allocation information not available");
2521 // Check we can read from file
2522 FileSpec file(path);
2523 FileSystem::Instance().Resolve(file);
2524 if (!FileSystem::Instance().Exists(file)) {
2525 strm.Printf("Error: File %s does not exist", path);
2530 if (!FileSystem::Instance().Readable(file)) {
2531 strm.Printf("Error: File %s does not have readable permissions", path);
2536 // Read file into data buffer
2537 auto data_sp = FileSystem::Instance().CreateDataBuffer(file.GetPath());
2539 // Cast start of buffer to FileHeader and use pointer to read metadata
2540 void *file_buf = data_sp->GetBytes();
2541 if (file_buf == nullptr ||
2542 data_sp->GetByteSize() < (sizeof(AllocationDetails::FileHeader) +
2543 sizeof(AllocationDetails::ElementHeader))) {
2544 strm.Printf("Error: File %s does not contain enough data for header", path);
2548 const AllocationDetails::FileHeader *file_header =
2549 static_cast<AllocationDetails::FileHeader *>(file_buf);
2551 // Check file starts with ascii characters "RSAD"
2552 if (memcmp(file_header->ident, "RSAD", 4)) {
2553 strm.Printf("Error: File doesn't contain identifier for an RS allocation "
2554 "dump. Are you sure this is the correct file?");
2559 // Look at the type of the root element in the header
2560 AllocationDetails::ElementHeader root_el_hdr;
2561 memcpy(&root_el_hdr, static_cast<uint8_t *>(file_buf) +
2562 sizeof(AllocationDetails::FileHeader),
2563 sizeof(AllocationDetails::ElementHeader));
2566 log->Printf("%s - header type %" PRIu32 ", element size %" PRIu32,
2567 __FUNCTION__, root_el_hdr.type, root_el_hdr.element_size);
2569 // Check if the target allocation and file both have the same number of bytes
2571 if (*alloc->element.datum_size.get() != root_el_hdr.element_size) {
2572 strm.Printf("Warning: Mismatched Element sizes - file %" PRIu32
2573 " bytes, allocation %" PRIu32 " bytes",
2574 root_el_hdr.element_size, *alloc->element.datum_size.get());
2578 // Check if the target allocation and file both have the same type
2579 const uint32_t alloc_type = static_cast<uint32_t>(*alloc->element.type.get());
2580 const uint32_t file_type = root_el_hdr.type;
2582 if (file_type > Element::RS_TYPE_FONT) {
2583 strm.Printf("Warning: File has unknown allocation type");
2585 } else if (alloc_type != file_type) {
2586 // Enum value isn't monotonous, so doesn't always index RsDataTypeToString
2588 uint32_t target_type_name_idx = alloc_type;
2589 uint32_t head_type_name_idx = file_type;
2590 if (alloc_type >= Element::RS_TYPE_ELEMENT &&
2591 alloc_type <= Element::RS_TYPE_FONT)
2592 target_type_name_idx = static_cast<Element::DataType>(
2593 (alloc_type - Element::RS_TYPE_ELEMENT) +
2594 Element::RS_TYPE_MATRIX_2X2 + 1);
2596 if (file_type >= Element::RS_TYPE_ELEMENT &&
2597 file_type <= Element::RS_TYPE_FONT)
2598 head_type_name_idx = static_cast<Element::DataType>(
2599 (file_type - Element::RS_TYPE_ELEMENT) + Element::RS_TYPE_MATRIX_2X2 +
2602 const char *head_type_name =
2603 AllocationDetails::RsDataTypeToString[head_type_name_idx][0];
2604 const char *target_type_name =
2605 AllocationDetails::RsDataTypeToString[target_type_name_idx][0];
2608 "Warning: Mismatched Types - file '%s' type, allocation '%s' type",
2609 head_type_name, target_type_name);
2613 // Advance buffer past header
2614 file_buf = static_cast<uint8_t *>(file_buf) + file_header->hdr_size;
2616 // Calculate size of allocation data in file
2617 size_t size = data_sp->GetByteSize() - file_header->hdr_size;
2619 // Check if the target allocation and file both have the same total data
2621 const uint32_t alloc_size = *alloc->size.get();
2622 if (alloc_size != size) {
2623 strm.Printf("Warning: Mismatched allocation sizes - file 0x%" PRIx64
2624 " bytes, allocation 0x%" PRIx32 " bytes",
2625 (uint64_t)size, alloc_size);
2627 // Set length to copy to minimum
2628 size = alloc_size < size ? alloc_size : size;
2631 // Copy file data from our buffer into the target allocation.
2632 lldb::addr_t alloc_data = *alloc->data_ptr.get();
2634 size_t written = GetProcess()->WriteMemory(alloc_data, file_buf, size, err);
2635 if (!err.Success() || written != size) {
2636 strm.Printf("Error: Couldn't write data to allocation %s", err.AsCString());
2641 strm.Printf("Contents of file '%s' read into allocation %" PRIu32, path,
2648 // Function takes as parameters a byte buffer, which will eventually be written
2649 // to file as the element header, an offset into that buffer, and an Element
2650 // that will be saved into the buffer at the parametrised offset. Return value
2651 // is the new offset after writing the element into the buffer. Elements are
2652 // saved to the file as the ElementHeader struct followed by offsets to the
2653 // structs of all the element's children.
2654 size_t RenderScriptRuntime::PopulateElementHeaders(
2655 const std::shared_ptr<uint8_t> header_buffer, size_t offset,
2656 const Element &elem) {
2657 // File struct for an element header with all the relevant details copied
2658 // from elem. We assume members are valid already.
2659 AllocationDetails::ElementHeader elem_header;
2660 elem_header.type = *elem.type.get();
2661 elem_header.kind = *elem.type_kind.get();
2662 elem_header.element_size = *elem.datum_size.get();
2663 elem_header.vector_size = *elem.type_vec_size.get();
2664 elem_header.array_size =
2665 elem.array_size.isValid() ? *elem.array_size.get() : 0;
2666 const size_t elem_header_size = sizeof(AllocationDetails::ElementHeader);
2668 // Copy struct into buffer and advance offset We assume that header_buffer
2669 // has been checked for nullptr before this method is called
2670 memcpy(header_buffer.get() + offset, &elem_header, elem_header_size);
2671 offset += elem_header_size;
2673 // Starting offset of child ElementHeader struct
2674 size_t child_offset =
2675 offset + ((elem.children.size() + 1) * sizeof(uint32_t));
2676 for (const RenderScriptRuntime::Element &child : elem.children) {
2677 // Recursively populate the buffer with the element header structs of
2678 // children. Then save the offsets where they were set after the parent
2680 memcpy(header_buffer.get() + offset, &child_offset, sizeof(uint32_t));
2681 offset += sizeof(uint32_t);
2683 child_offset = PopulateElementHeaders(header_buffer, child_offset, child);
2686 // Zero indicates no more children
2687 memset(header_buffer.get() + offset, 0, sizeof(uint32_t));
2689 return child_offset;
2692 // Given an Element object this function returns the total size needed in the
2693 // file header to store the element's details. Taking into account the size of
2694 // the element header struct, plus the offsets to all the element's children.
2695 // Function is recursive so that the size of all ancestors is taken into
2697 size_t RenderScriptRuntime::CalculateElementHeaderSize(const Element &elem) {
2698 // Offsets to children plus zero terminator
2699 size_t size = (elem.children.size() + 1) * sizeof(uint32_t);
2700 // Size of header struct with type details
2701 size += sizeof(AllocationDetails::ElementHeader);
2703 // Calculate recursively for all descendants
2704 for (const Element &child : elem.children)
2705 size += CalculateElementHeaderSize(child);
2710 // Function copies allocation contents into a binary file. This file can then
2711 // be loaded later into a different allocation. There is a header, FileHeader,
2712 // before the allocation data containing meta-data.
2713 bool RenderScriptRuntime::SaveAllocation(Stream &strm, const uint32_t alloc_id,
2715 StackFrame *frame_ptr) {
2716 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2718 // Find allocation with the given id
2719 AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
2724 log->Printf("%s - found allocation 0x%" PRIx64 ".", __FUNCTION__,
2725 *alloc->address.get());
2727 // JIT all the allocation details
2728 if (alloc->ShouldRefresh()) {
2730 log->Printf("%s - allocation details not calculated yet, jitting info.",
2733 if (!RefreshAllocation(alloc, frame_ptr)) {
2735 log->Printf("%s - couldn't JIT allocation details.", __FUNCTION__);
2740 assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2741 alloc->element.type_vec_size.isValid() &&
2742 alloc->element.datum_size.get() &&
2743 alloc->element.type_kind.isValid() && alloc->dimension.isValid() &&
2744 "Allocation information not available");
2746 // Check we can create writable file
2747 FileSpec file_spec(path);
2748 FileSystem::Instance().Resolve(file_spec);
2750 FileSystem::Instance().Open(file, file_spec,
2751 File::eOpenOptionWrite |
2752 File::eOpenOptionCanCreate |
2753 File::eOpenOptionTruncate);
2756 strm.Printf("Error: Failed to open '%s' for writing", path);
2761 // Read allocation into buffer of heap memory
2762 const std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
2764 strm.Printf("Error: Couldn't read allocation data into buffer");
2769 // Create the file header
2770 AllocationDetails::FileHeader head;
2771 memcpy(head.ident, "RSAD", 4);
2772 head.dims[0] = static_cast<uint32_t>(alloc->dimension.get()->dim_1);
2773 head.dims[1] = static_cast<uint32_t>(alloc->dimension.get()->dim_2);
2774 head.dims[2] = static_cast<uint32_t>(alloc->dimension.get()->dim_3);
2776 const size_t element_header_size = CalculateElementHeaderSize(alloc->element);
2777 assert((sizeof(AllocationDetails::FileHeader) + element_header_size) <
2779 "Element header too large");
2780 head.hdr_size = static_cast<uint16_t>(sizeof(AllocationDetails::FileHeader) +
2781 element_header_size);
2783 // Write the file header
2784 size_t num_bytes = sizeof(AllocationDetails::FileHeader);
2786 log->Printf("%s - writing File Header, 0x%" PRIx64 " bytes", __FUNCTION__,
2787 (uint64_t)num_bytes);
2789 Status err = file.Write(&head, num_bytes);
2790 if (!err.Success()) {
2791 strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
2796 // Create the headers describing the element type of the allocation.
2797 std::shared_ptr<uint8_t> element_header_buffer(
2798 new uint8_t[element_header_size]);
2799 if (element_header_buffer == nullptr) {
2800 strm.Printf("Internal Error: Couldn't allocate %" PRIu64
2801 " bytes on the heap",
2802 (uint64_t)element_header_size);
2807 PopulateElementHeaders(element_header_buffer, 0, alloc->element);
2809 // Write headers for allocation element type to file
2810 num_bytes = element_header_size;
2812 log->Printf("%s - writing element headers, 0x%" PRIx64 " bytes.",
2813 __FUNCTION__, (uint64_t)num_bytes);
2815 err = file.Write(element_header_buffer.get(), num_bytes);
2816 if (!err.Success()) {
2817 strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
2822 // Write allocation data to file
2823 num_bytes = static_cast<size_t>(*alloc->size.get());
2825 log->Printf("%s - writing 0x%" PRIx64 " bytes", __FUNCTION__,
2826 (uint64_t)num_bytes);
2828 err = file.Write(buffer.get(), num_bytes);
2829 if (!err.Success()) {
2830 strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
2835 strm.Printf("Allocation written to file '%s'", path);
2840 bool RenderScriptRuntime::LoadModule(const lldb::ModuleSP &module_sp) {
2841 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2844 for (const auto &rs_module : m_rsmodules) {
2845 if (rs_module->m_module == module_sp) {
2846 // Check if the user has enabled automatically breaking on all RS
2848 if (m_breakAllKernels)
2849 BreakOnModuleKernels(rs_module);
2854 bool module_loaded = false;
2855 switch (GetModuleKind(module_sp)) {
2856 case eModuleKindKernelObj: {
2857 RSModuleDescriptorSP module_desc;
2858 module_desc.reset(new RSModuleDescriptor(module_sp));
2859 if (module_desc->ParseRSInfo()) {
2860 m_rsmodules.push_back(module_desc);
2861 module_desc->WarnIfVersionMismatch(GetProcess()
2864 .GetAsyncOutputStream()
2866 module_loaded = true;
2868 if (module_loaded) {
2869 FixupScriptDetails(module_desc);
2873 case eModuleKindDriver: {
2874 if (!m_libRSDriver) {
2875 m_libRSDriver = module_sp;
2876 LoadRuntimeHooks(m_libRSDriver, RenderScriptRuntime::eModuleKindDriver);
2880 case eModuleKindImpl: {
2881 if (!m_libRSCpuRef) {
2882 m_libRSCpuRef = module_sp;
2883 LoadRuntimeHooks(m_libRSCpuRef, RenderScriptRuntime::eModuleKindImpl);
2887 case eModuleKindLibRS: {
2889 m_libRS = module_sp;
2890 static ConstString gDbgPresentStr("gDebuggerPresent");
2891 const Symbol *debug_present = m_libRS->FindFirstSymbolWithNameAndType(
2892 gDbgPresentStr, eSymbolTypeData);
2893 if (debug_present) {
2895 uint32_t flag = 0x00000001U;
2896 Target &target = GetProcess()->GetTarget();
2897 addr_t addr = debug_present->GetLoadAddress(&target);
2898 GetProcess()->WriteMemory(addr, &flag, sizeof(flag), err);
2899 if (err.Success()) {
2901 log->Printf("%s - debugger present flag set on debugee.",
2904 m_debuggerPresentFlagged = true;
2906 log->Printf("%s - error writing debugger present flags '%s' ",
2907 __FUNCTION__, err.AsCString());
2911 "%s - error writing debugger present flags - symbol not found",
2922 return module_loaded;
2927 void RenderScriptRuntime::Update() {
2928 if (m_rsmodules.size() > 0) {
2935 void RSModuleDescriptor::WarnIfVersionMismatch(lldb_private::Stream *s) const {
2939 if (m_slang_version.empty() || m_bcc_version.empty()) {
2940 s->PutCString("WARNING: Unknown bcc or slang (llvm-rs-cc) version; debug "
2941 "experience may be unreliable");
2943 } else if (m_slang_version != m_bcc_version) {
2944 s->Printf("WARNING: The debug info emitted by the slang frontend "
2945 "(llvm-rs-cc) used to build this module (%s) does not match the "
2946 "version of bcc used to generate the debug information (%s). "
2947 "This is an unsupported configuration and may result in a poor "
2948 "debugging experience; proceed with caution",
2949 m_slang_version.c_str(), m_bcc_version.c_str());
2954 bool RSModuleDescriptor::ParsePragmaCount(llvm::StringRef *lines,
2956 // Skip the pragma prototype line
2958 for (; n_lines--; ++lines) {
2959 const auto kv_pair = lines->split(" - ");
2960 m_pragmas[kv_pair.first.trim().str()] = kv_pair.second.trim().str();
2965 bool RSModuleDescriptor::ParseExportReduceCount(llvm::StringRef *lines,
2967 // The list of reduction kernels in the `.rs.info` symbol is of the form
2968 // "signature - accumulatordatasize - reduction_name - initializer_name -
2969 // accumulator_name - combiner_name - outconverter_name - halter_name" Where
2970 // a function is not explicitly named by the user, or is not generated by the
2971 // compiler, it is named "." so the dash separated list should always be 8
2973 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
2974 // Skip the exportReduceCount line
2976 for (; n_lines--; ++lines) {
2977 llvm::SmallVector<llvm::StringRef, 8> spec;
2978 lines->split(spec, " - ");
2979 if (spec.size() != 8) {
2980 if (spec.size() < 8) {
2982 log->Error("Error parsing RenderScript reduction spec. wrong number "
2986 log->Warning("Extraneous members in reduction spec: '%s'",
2987 lines->str().c_str());
2990 const auto sig_s = spec[0];
2992 if (sig_s.getAsInteger(10, sig)) {
2994 log->Error("Error parsing Renderscript reduction spec: invalid kernel "
2996 sig_s.str().c_str());
3000 const auto accum_data_size_s = spec[1];
3001 uint32_t accum_data_size;
3002 if (accum_data_size_s.getAsInteger(10, accum_data_size)) {
3004 log->Error("Error parsing Renderscript reduction spec: invalid "
3005 "accumulator data size %s",
3006 accum_data_size_s.str().c_str());
3011 log->Printf("Found RenderScript reduction '%s'", spec[2].str().c_str());
3013 m_reductions.push_back(RSReductionDescriptor(this, sig, accum_data_size,
3014 spec[2], spec[3], spec[4],
3015 spec[5], spec[6], spec[7]));
3020 bool RSModuleDescriptor::ParseVersionInfo(llvm::StringRef *lines,
3022 // Skip the versionInfo line
3024 for (; n_lines--; ++lines) {
3025 // We're only interested in bcc and slang versions, and ignore all other
3026 // versionInfo lines
3027 const auto kv_pair = lines->split(" - ");
3028 if (kv_pair.first == "slang")
3029 m_slang_version = kv_pair.second.str();
3030 else if (kv_pair.first == "bcc")
3031 m_bcc_version = kv_pair.second.str();
3036 bool RSModuleDescriptor::ParseExportForeachCount(llvm::StringRef *lines,
3038 // Skip the exportForeachCount line
3040 for (; n_lines--; ++lines) {
3042 // `forEach` kernels are listed in the `.rs.info` packet as a "slot - name"
3044 const auto kv_pair = lines->split(" - ");
3045 if (kv_pair.first.getAsInteger(10, slot))
3047 m_kernels.push_back(RSKernelDescriptor(this, kv_pair.second, slot));
3052 bool RSModuleDescriptor::ParseExportVarCount(llvm::StringRef *lines,
3054 // Skip the ExportVarCount line
3056 for (; n_lines--; ++lines)
3057 m_globals.push_back(RSGlobalDescriptor(this, *lines));
3061 // The .rs.info symbol in renderscript modules contains a string which needs to
3062 // be parsed. The string is basic and is parsed on a line by line basis.
3063 bool RSModuleDescriptor::ParseRSInfo() {
3065 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3066 const Symbol *info_sym = m_module->FindFirstSymbolWithNameAndType(
3067 ConstString(".rs.info"), eSymbolTypeData);
3071 const addr_t addr = info_sym->GetAddressRef().GetFileAddress();
3072 if (addr == LLDB_INVALID_ADDRESS)
3075 const addr_t size = info_sym->GetByteSize();
3076 const FileSpec fs = m_module->GetFileSpec();
3079 FileSystem::Instance().CreateDataBuffer(fs.GetPath(), size, addr);
3083 // split rs.info. contents into lines
3084 llvm::SmallVector<llvm::StringRef, 128> info_lines;
3086 const llvm::StringRef raw_rs_info((const char *)buffer->GetBytes());
3087 raw_rs_info.split(info_lines, '\n');
3089 log->Printf("'.rs.info symbol for '%s':\n%s",
3090 m_module->GetFileSpec().GetCString(),
3091 raw_rs_info.str().c_str());
3104 const auto rs_info_handler = [](llvm::StringRef name) -> int {
3105 return llvm::StringSwitch<int>(name)
3106 // The number of visible global variables in the script
3107 .Case("exportVarCount", eExportVar)
3108 // The number of RenderScrip `forEach` kernels __attribute__((kernel))
3109 .Case("exportForEachCount", eExportForEach)
3110 // The number of generalreductions: This marked in the script by
3111 // `#pragma reduce()`
3112 .Case("exportReduceCount", eExportReduce)
3113 // Total count of all RenderScript specific `#pragmas` used in the
3115 .Case("pragmaCount", ePragma)
3116 .Case("objectSlotCount", eObjectSlot)
3117 .Case("versionInfo", eVersionInfo)
3121 // parse all text lines of .rs.info
3122 for (auto line = info_lines.begin(); line != info_lines.end(); ++line) {
3123 const auto kv_pair = line->split(": ");
3124 const auto key = kv_pair.first;
3125 const auto val = kv_pair.second.trim();
3127 const auto handler = rs_info_handler(key);
3130 // getAsInteger returns `true` on an error condition - we're only
3131 // interested in numeric fields at the moment
3133 if (val.getAsInteger(10, n_lines)) {
3134 LLDB_LOGV(log, "Failed to parse non-numeric '.rs.info' section {0}",
3138 if (info_lines.end() - (line + 1) < (ptrdiff_t)n_lines)
3141 bool success = false;
3144 success = ParseExportVarCount(line, n_lines);
3146 case eExportForEach:
3147 success = ParseExportForeachCount(line, n_lines);
3150 success = ParseExportReduceCount(line, n_lines);
3153 success = ParsePragmaCount(line, n_lines);
3156 success = ParseVersionInfo(line, n_lines);
3160 log->Printf("%s - skipping .rs.info field '%s'", __FUNCTION__,
3161 line->str().c_str());
3169 return info_lines.size() > 0;
3172 void RenderScriptRuntime::DumpStatus(Stream &strm) const {
3174 strm.Printf("Runtime Library discovered.");
3177 if (m_libRSDriver) {
3178 strm.Printf("Runtime Driver discovered.");
3181 if (m_libRSCpuRef) {
3182 strm.Printf("CPU Reference Implementation discovered.");
3186 if (m_runtimeHooks.size()) {
3187 strm.Printf("Runtime functions hooked:");
3189 for (auto b : m_runtimeHooks) {
3190 strm.Indent(b.second->defn->name);
3194 strm.Printf("Runtime is not hooked.");
3199 void RenderScriptRuntime::DumpContexts(Stream &strm) const {
3200 strm.Printf("Inferred RenderScript Contexts:");
3204 std::map<addr_t, uint64_t> contextReferences;
3206 // Iterate over all of the currently discovered scripts. Note: We cant push
3207 // or pop from m_scripts inside this loop or it may invalidate script.
3208 for (const auto &script : m_scripts) {
3209 if (!script->context.isValid())
3211 lldb::addr_t context = *script->context;
3213 if (contextReferences.find(context) != contextReferences.end()) {
3214 contextReferences[context]++;
3216 contextReferences[context] = 1;
3220 for (const auto &cRef : contextReferences) {
3221 strm.Printf("Context 0x%" PRIx64 ": %" PRIu64 " script instances",
3222 cRef.first, cRef.second);
3228 void RenderScriptRuntime::DumpKernels(Stream &strm) const {
3229 strm.Printf("RenderScript Kernels:");
3232 for (const auto &module : m_rsmodules) {
3233 strm.Printf("Resource '%s':", module->m_resname.c_str());
3235 for (const auto &kernel : module->m_kernels) {
3236 strm.Indent(kernel.m_name.AsCString());
3243 RenderScriptRuntime::AllocationDetails *
3244 RenderScriptRuntime::FindAllocByID(Stream &strm, const uint32_t alloc_id) {
3245 AllocationDetails *alloc = nullptr;
3247 // See if we can find allocation using id as an index;
3248 if (alloc_id <= m_allocations.size() && alloc_id != 0 &&
3249 m_allocations[alloc_id - 1]->id == alloc_id) {
3250 alloc = m_allocations[alloc_id - 1].get();
3254 // Fallback to searching
3255 for (const auto &a : m_allocations) {
3256 if (a->id == alloc_id) {
3262 if (alloc == nullptr) {
3263 strm.Printf("Error: Couldn't find allocation with id matching %" PRIu32,
3271 // Prints the contents of an allocation to the output stream, which may be a
3273 bool RenderScriptRuntime::DumpAllocation(Stream &strm, StackFrame *frame_ptr,
3274 const uint32_t id) {
3275 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3277 // Check we can find the desired allocation
3278 AllocationDetails *alloc = FindAllocByID(strm, id);
3280 return false; // FindAllocByID() will print error message for us here
3283 log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__,
3284 *alloc->address.get());
3286 // Check we have information about the allocation, if not calculate it
3287 if (alloc->ShouldRefresh()) {
3289 log->Printf("%s - allocation details not calculated yet, jitting info.",
3292 // JIT all the allocation information
3293 if (!RefreshAllocation(alloc, frame_ptr)) {
3294 strm.Printf("Error: Couldn't JIT allocation details");
3300 // Establish format and size of each data element
3301 const uint32_t vec_size = *alloc->element.type_vec_size.get();
3302 const Element::DataType type = *alloc->element.type.get();
3304 assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
3305 "Invalid allocation type");
3307 lldb::Format format;
3308 if (type >= Element::RS_TYPE_ELEMENT)
3309 format = eFormatHex;
3311 format = vec_size == 1
3312 ? static_cast<lldb::Format>(
3313 AllocationDetails::RSTypeToFormat[type][eFormatSingle])
3314 : static_cast<lldb::Format>(
3315 AllocationDetails::RSTypeToFormat[type][eFormatVector]);
3317 const uint32_t data_size = *alloc->element.datum_size.get();
3320 log->Printf("%s - element size %" PRIu32 " bytes, including padding",
3321 __FUNCTION__, data_size);
3323 // Allocate a buffer to copy data into
3324 std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
3326 strm.Printf("Error: Couldn't read allocation data");
3331 // Calculate stride between rows as there may be padding at end of rows since
3332 // allocated memory is 16-byte aligned
3333 if (!alloc->stride.isValid()) {
3334 if (alloc->dimension.get()->dim_2 == 0) // We only have one dimension
3336 else if (!JITAllocationStride(alloc, frame_ptr)) {
3337 strm.Printf("Error: Couldn't calculate allocation row stride");
3342 const uint32_t stride = *alloc->stride.get();
3343 const uint32_t size = *alloc->size.get(); // Size of whole allocation
3344 const uint32_t padding =
3345 alloc->element.padding.isValid() ? *alloc->element.padding.get() : 0;
3347 log->Printf("%s - stride %" PRIu32 " bytes, size %" PRIu32
3348 " bytes, padding %" PRIu32,
3349 __FUNCTION__, stride, size, padding);
3351 // Find dimensions used to index loops, so need to be non-zero
3352 uint32_t dim_x = alloc->dimension.get()->dim_1;
3353 dim_x = dim_x == 0 ? 1 : dim_x;
3355 uint32_t dim_y = alloc->dimension.get()->dim_2;
3356 dim_y = dim_y == 0 ? 1 : dim_y;
3358 uint32_t dim_z = alloc->dimension.get()->dim_3;
3359 dim_z = dim_z == 0 ? 1 : dim_z;
3361 // Use data extractor to format output
3362 const uint32_t target_ptr_size =
3363 GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
3364 DataExtractor alloc_data(buffer.get(), size, GetProcess()->GetByteOrder(),
3367 uint32_t offset = 0; // Offset in buffer to next element to be printed
3368 uint32_t prev_row = 0; // Offset to the start of the previous row
3370 // Iterate over allocation dimensions, printing results to user
3371 strm.Printf("Data (X, Y, Z):");
3372 for (uint32_t z = 0; z < dim_z; ++z) {
3373 for (uint32_t y = 0; y < dim_y; ++y) {
3374 // Use stride to index start of next row.
3375 if (!(y == 0 && z == 0))
3376 offset = prev_row + stride;
3379 // Print each element in the row individually
3380 for (uint32_t x = 0; x < dim_x; ++x) {
3381 strm.Printf("\n(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ") = ", x, y, z);
3382 if ((type == Element::RS_TYPE_NONE) &&
3383 (alloc->element.children.size() > 0) &&
3384 (alloc->element.type_name != Element::GetFallbackStructName())) {
3385 // Here we are dumping an Element of struct type. This is done using
3386 // expression evaluation with the name of the struct type and pointer
3387 // to element. Don't print the name of the resulting expression,
3388 // since this will be '$[0-9]+'
3389 DumpValueObjectOptions expr_options;
3390 expr_options.SetHideName(true);
3392 // Setup expression as dereferencing a pointer cast to element
3394 char expr_char_buffer[jit_max_expr_size];
3396 snprintf(expr_char_buffer, jit_max_expr_size, "*(%s*) 0x%" PRIx64,
3397 alloc->element.type_name.AsCString(),
3398 *alloc->data_ptr.get() + offset);
3400 if (written < 0 || written >= jit_max_expr_size) {
3402 log->Printf("%s - error in snprintf().", __FUNCTION__);
3406 // Evaluate expression
3407 ValueObjectSP expr_result;
3408 GetProcess()->GetTarget().EvaluateExpression(expr_char_buffer,
3409 frame_ptr, expr_result);
3411 // Print the results to our stream.
3412 expr_result->Dump(strm, expr_options);
3414 DumpDataExtractor(alloc_data, &strm, offset, format,
3415 data_size - padding, 1, 1, LLDB_INVALID_ADDRESS, 0,
3418 offset += data_size;
3427 // Function recalculates all our cached information about allocations by
3428 // jitting the RS runtime regarding each allocation we know about. Returns true
3429 // if all allocations could be recomputed, false otherwise.
3430 bool RenderScriptRuntime::RecomputeAllAllocations(Stream &strm,
3431 StackFrame *frame_ptr) {
3432 bool success = true;
3433 for (auto &alloc : m_allocations) {
3434 // JIT current allocation information
3435 if (!RefreshAllocation(alloc.get(), frame_ptr)) {
3436 strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32
3444 strm.Printf("All allocations successfully recomputed");
3450 // Prints information regarding currently loaded allocations. These details are
3451 // gathered by jitting the runtime, which has as latency. Index parameter
3452 // specifies a single allocation ID to print, or a zero value to print them all
3453 void RenderScriptRuntime::ListAllocations(Stream &strm, StackFrame *frame_ptr,
3454 const uint32_t index) {
3455 strm.Printf("RenderScript Allocations:");
3459 for (auto &alloc : m_allocations) {
3460 // index will only be zero if we want to print all allocations
3461 if (index != 0 && index != alloc->id)
3464 // JIT current allocation information
3465 if (alloc->ShouldRefresh() && !RefreshAllocation(alloc.get(), frame_ptr)) {
3466 strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32,
3472 strm.Printf("%" PRIu32 ":", alloc->id);
3476 strm.Indent("Context: ");
3477 if (!alloc->context.isValid())
3478 strm.Printf("unknown\n");
3480 strm.Printf("0x%" PRIx64 "\n", *alloc->context.get());
3482 strm.Indent("Address: ");
3483 if (!alloc->address.isValid())
3484 strm.Printf("unknown\n");
3486 strm.Printf("0x%" PRIx64 "\n", *alloc->address.get());
3488 strm.Indent("Data pointer: ");
3489 if (!alloc->data_ptr.isValid())
3490 strm.Printf("unknown\n");
3492 strm.Printf("0x%" PRIx64 "\n", *alloc->data_ptr.get());
3494 strm.Indent("Dimensions: ");
3495 if (!alloc->dimension.isValid())
3496 strm.Printf("unknown\n");
3498 strm.Printf("(%" PRId32 ", %" PRId32 ", %" PRId32 ")\n",
3499 alloc->dimension.get()->dim_1, alloc->dimension.get()->dim_2,
3500 alloc->dimension.get()->dim_3);
3502 strm.Indent("Data Type: ");
3503 if (!alloc->element.type.isValid() ||
3504 !alloc->element.type_vec_size.isValid())
3505 strm.Printf("unknown\n");
3507 const int vector_size = *alloc->element.type_vec_size.get();
3508 Element::DataType type = *alloc->element.type.get();
3510 if (!alloc->element.type_name.IsEmpty())
3511 strm.Printf("%s\n", alloc->element.type_name.AsCString());
3513 // Enum value isn't monotonous, so doesn't always index
3514 // RsDataTypeToString array
3515 if (type >= Element::RS_TYPE_ELEMENT && type <= Element::RS_TYPE_FONT)
3517 static_cast<Element::DataType>((type - Element::RS_TYPE_ELEMENT) +
3518 Element::RS_TYPE_MATRIX_2X2 + 1);
3520 if (type >= (sizeof(AllocationDetails::RsDataTypeToString) /
3521 sizeof(AllocationDetails::RsDataTypeToString[0])) ||
3522 vector_size > 4 || vector_size < 1)
3523 strm.Printf("invalid type\n");
3527 AllocationDetails::RsDataTypeToString[static_cast<uint32_t>(type)]
3532 strm.Indent("Data Kind: ");
3533 if (!alloc->element.type_kind.isValid())
3534 strm.Printf("unknown\n");
3536 const Element::DataKind kind = *alloc->element.type_kind.get();
3537 if (kind < Element::RS_KIND_USER || kind > Element::RS_KIND_PIXEL_YUV)
3538 strm.Printf("invalid kind\n");
3542 AllocationDetails::RsDataKindToString[static_cast<uint32_t>(kind)]);
3551 // Set breakpoints on every kernel found in RS module
3552 void RenderScriptRuntime::BreakOnModuleKernels(
3553 const RSModuleDescriptorSP rsmodule_sp) {
3554 for (const auto &kernel : rsmodule_sp->m_kernels) {
3555 // Don't set breakpoint on 'root' kernel
3556 if (strcmp(kernel.m_name.AsCString(), "root") == 0)
3559 CreateKernelBreakpoint(kernel.m_name);
3563 // Method is internally called by the 'kernel breakpoint all' command to enable
3564 // or disable breaking on all kernels. When do_break is true we want to enable
3565 // this functionality. When do_break is false we want to disable it.
3566 void RenderScriptRuntime::SetBreakAllKernels(bool do_break, TargetSP target) {
3568 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3570 InitSearchFilter(target);
3572 // Set breakpoints on all the kernels
3573 if (do_break && !m_breakAllKernels) {
3574 m_breakAllKernels = true;
3576 for (const auto &module : m_rsmodules)
3577 BreakOnModuleKernels(module);
3580 log->Printf("%s(True) - breakpoints set on all currently loaded kernels.",
3582 } else if (!do_break &&
3583 m_breakAllKernels) // Breakpoints won't be set on any new kernels.
3585 m_breakAllKernels = false;
3588 log->Printf("%s(False) - breakpoints no longer automatically set.",
3593 // Given the name of a kernel this function creates a breakpoint using our own
3594 // breakpoint resolver, and returns the Breakpoint shared pointer.
3596 RenderScriptRuntime::CreateKernelBreakpoint(const ConstString &name) {
3598 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3602 log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
3606 BreakpointResolverSP resolver_sp(new RSBreakpointResolver(nullptr, name));
3607 Target &target = GetProcess()->GetTarget();
3608 BreakpointSP bp = target.CreateBreakpoint(
3609 m_filtersp, resolver_sp, false, false, false);
3611 // Give RS breakpoints a specific name, so the user can manipulate them as a
3614 target.AddNameToBreakpoint(bp, "RenderScriptKernel", err);
3615 if (err.Fail() && log)
3617 log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
3624 RenderScriptRuntime::CreateReductionBreakpoint(const ConstString &name,
3627 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3631 log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
3635 BreakpointResolverSP resolver_sp(new RSReduceBreakpointResolver(
3636 nullptr, name, &m_rsmodules, kernel_types));
3637 Target &target = GetProcess()->GetTarget();
3638 BreakpointSP bp = target.CreateBreakpoint(
3639 m_filtersp, resolver_sp, false, false, false);
3641 // Give RS breakpoints a specific name, so the user can manipulate them as a
3644 target.AddNameToBreakpoint(bp, "RenderScriptReduction", err);
3645 if (err.Fail() && log)
3646 log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
3652 // Given an expression for a variable this function tries to calculate the
3653 // variable's value. If this is possible it returns true and sets the uint64_t
3654 // parameter to the variables unsigned value. Otherwise function returns false.
3655 bool RenderScriptRuntime::GetFrameVarAsUnsigned(const StackFrameSP frame_sp,
3656 const char *var_name,
3658 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3662 // Find variable in stack frame
3663 ValueObjectSP value_sp(frame_sp->GetValueForVariableExpressionPath(
3664 var_name, eNoDynamicValues,
3665 StackFrame::eExpressionPathOptionCheckPtrVsMember |
3666 StackFrame::eExpressionPathOptionsAllowDirectIVarAccess,
3668 if (!err.Success()) {
3670 log->Printf("%s - error, couldn't find '%s' in frame", __FUNCTION__,
3675 // Find the uint32_t value for the variable
3676 bool success = false;
3677 val = value_sp->GetValueAsUnsigned(0, &success);
3680 log->Printf("%s - error, couldn't parse '%s' as an uint32_t.",
3681 __FUNCTION__, var_name);
3688 // Function attempts to find the current coordinate of a kernel invocation by
3689 // investigating the values of frame variables in the .expand function. These
3690 // coordinates are returned via the coord array reference parameter. Returns
3691 // true if the coordinates could be found, and false otherwise.
3692 bool RenderScriptRuntime::GetKernelCoordinate(RSCoordinate &coord,
3693 Thread *thread_ptr) {
3694 static const char *const x_expr = "rsIndex";
3695 static const char *const y_expr = "p->current.y";
3696 static const char *const z_expr = "p->current.z";
3698 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3702 log->Printf("%s - Error, No thread pointer", __FUNCTION__);
3707 // Walk the call stack looking for a function whose name has the suffix
3708 // '.expand' and contains the variables we're looking for.
3709 for (uint32_t i = 0; i < thread_ptr->GetStackFrameCount(); ++i) {
3710 if (!thread_ptr->SetSelectedFrameByIndex(i))
3713 StackFrameSP frame_sp = thread_ptr->GetSelectedFrame();
3717 // Find the function name
3718 const SymbolContext sym_ctx =
3719 frame_sp->GetSymbolContext(eSymbolContextFunction);
3720 const ConstString func_name = sym_ctx.GetFunctionName();
3725 log->Printf("%s - Inspecting function '%s'", __FUNCTION__,
3726 func_name.GetCString());
3728 // Check if function name has .expand suffix
3729 if (!func_name.GetStringRef().endswith(".expand"))
3733 log->Printf("%s - Found .expand function '%s'", __FUNCTION__,
3734 func_name.GetCString());
3736 // Get values for variables in .expand frame that tell us the current
3737 // kernel invocation
3739 bool found = GetFrameVarAsUnsigned(frame_sp, x_expr, x) &&
3740 GetFrameVarAsUnsigned(frame_sp, y_expr, y) &&
3741 GetFrameVarAsUnsigned(frame_sp, z_expr, z);
3744 // The RenderScript runtime uses uint32_t for these vars. If they're not
3745 // within bounds, our frame parsing is garbage
3746 assert(x <= UINT32_MAX && y <= UINT32_MAX && z <= UINT32_MAX);
3747 coord.x = (uint32_t)x;
3748 coord.y = (uint32_t)y;
3749 coord.z = (uint32_t)z;
3756 // Callback when a kernel breakpoint hits and we're looking for a specific
3757 // coordinate. Baton parameter contains a pointer to the target coordinate we
3758 // want to break on. Function then checks the .expand frame for the current
3759 // coordinate and breaks to user if it matches. Parameter 'break_id' is the id
3760 // of the Breakpoint which made the callback. Parameter 'break_loc_id' is the
3761 // id for the BreakpointLocation which was hit, a single logical breakpoint can
3762 // have multiple addresses.
3763 bool RenderScriptRuntime::KernelBreakpointHit(void *baton,
3764 StoppointCallbackContext *ctx,
3766 user_id_t break_loc_id) {
3768 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3771 "Error: null baton in conditional kernel breakpoint callback");
3773 // Coordinate we want to stop on
3774 RSCoordinate target_coord = *static_cast<RSCoordinate *>(baton);
3777 log->Printf("%s - Break ID %" PRIu64 ", " FMT_COORD, __FUNCTION__, break_id,
3778 target_coord.x, target_coord.y, target_coord.z);
3780 // Select current thread
3781 ExecutionContext context(ctx->exe_ctx_ref);
3782 Thread *thread_ptr = context.GetThreadPtr();
3783 assert(thread_ptr && "Null thread pointer");
3785 // Find current kernel invocation from .expand frame variables
3786 RSCoordinate current_coord{};
3787 if (!GetKernelCoordinate(current_coord, thread_ptr)) {
3789 log->Printf("%s - Error, couldn't select .expand stack frame",
3795 log->Printf("%s - " FMT_COORD, __FUNCTION__, current_coord.x,
3796 current_coord.y, current_coord.z);
3798 // Check if the current kernel invocation coordinate matches our target
3800 if (target_coord == current_coord) {
3802 log->Printf("%s, BREAKING " FMT_COORD, __FUNCTION__, current_coord.x,
3803 current_coord.y, current_coord.z);
3805 BreakpointSP breakpoint_sp =
3806 context.GetTargetPtr()->GetBreakpointByID(break_id);
3807 assert(breakpoint_sp != nullptr &&
3808 "Error: Couldn't find breakpoint matching break id for callback");
3809 breakpoint_sp->SetEnabled(false); // Optimise since conditional breakpoint
3810 // should only be hit once.
3814 // No match on coordinate
3818 void RenderScriptRuntime::SetConditional(BreakpointSP bp, Stream &messages,
3819 const RSCoordinate &coord) {
3820 messages.Printf("Conditional kernel breakpoint on coordinate " FMT_COORD,
3821 coord.x, coord.y, coord.z);
3824 // Allocate memory for the baton, and copy over coordinate
3825 RSCoordinate *baton = new RSCoordinate(coord);
3827 // Create a callback that will be invoked every time the breakpoint is hit.
3828 // The baton object passed to the handler is the target coordinate we want to
3830 bp->SetCallback(KernelBreakpointHit, baton, true);
3832 // Store a shared pointer to the baton, so the memory will eventually be
3833 // cleaned up after destruction
3834 m_conditional_breaks[bp->GetID()] = std::unique_ptr<RSCoordinate>(baton);
3837 // Tries to set a breakpoint on the start of a kernel, resolved using the
3838 // kernel name. Argument 'coords', represents a three dimensional coordinate
3839 // which can be used to specify a single kernel instance to break on. If this
3840 // is set then we add a callback to the breakpoint.
3841 bool RenderScriptRuntime::PlaceBreakpointOnKernel(TargetSP target,
3844 const RSCoordinate *coord) {
3848 InitSearchFilter(target);
3850 ConstString kernel_name(name);
3851 BreakpointSP bp = CreateKernelBreakpoint(kernel_name);
3855 // We have a conditional breakpoint on a specific coordinate
3857 SetConditional(bp, messages, *coord);
3859 bp->GetDescription(&messages, lldb::eDescriptionLevelInitial, false);
3865 RenderScriptRuntime::CreateScriptGroupBreakpoint(const ConstString &name,
3868 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3872 log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
3876 BreakpointResolverSP resolver_sp(new RSScriptGroupBreakpointResolver(
3877 nullptr, name, m_scriptGroups, stop_on_all));
3878 Target &target = GetProcess()->GetTarget();
3879 BreakpointSP bp = target.CreateBreakpoint(
3880 m_filtersp, resolver_sp, false, false, false);
3881 // Give RS breakpoints a specific name, so the user can manipulate them as a
3884 target.AddNameToBreakpoint(bp, name.GetCString(), err);
3885 if (err.Fail() && log)
3886 log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
3888 // ask the breakpoint to resolve itself
3889 bp->ResolveBreakpoint();
3893 bool RenderScriptRuntime::PlaceBreakpointOnScriptGroup(TargetSP target,
3895 const ConstString &name,
3897 InitSearchFilter(target);
3898 BreakpointSP bp = CreateScriptGroupBreakpoint(name, multi);
3900 bp->GetDescription(&strm, lldb::eDescriptionLevelInitial, false);
3904 bool RenderScriptRuntime::PlaceBreakpointOnReduction(TargetSP target,
3906 const char *reduce_name,
3907 const RSCoordinate *coord,
3912 InitSearchFilter(target);
3914 CreateReductionBreakpoint(ConstString(reduce_name), kernel_types);
3919 SetConditional(bp, messages, *coord);
3921 bp->GetDescription(&messages, lldb::eDescriptionLevelInitial, false);
3926 void RenderScriptRuntime::DumpModules(Stream &strm) const {
3927 strm.Printf("RenderScript Modules:");
3930 for (const auto &module : m_rsmodules) {
3936 RenderScriptRuntime::ScriptDetails *
3937 RenderScriptRuntime::LookUpScript(addr_t address, bool create) {
3938 for (const auto &s : m_scripts) {
3939 if (s->script.isValid())
3940 if (*s->script == address)
3944 std::unique_ptr<ScriptDetails> s(new ScriptDetails);
3945 s->script = address;
3946 m_scripts.push_back(std::move(s));
3947 return m_scripts.back().get();
3952 RenderScriptRuntime::AllocationDetails *
3953 RenderScriptRuntime::LookUpAllocation(addr_t address) {
3954 for (const auto &a : m_allocations) {
3955 if (a->address.isValid())
3956 if (*a->address == address)
3962 RenderScriptRuntime::AllocationDetails *
3963 RenderScriptRuntime::CreateAllocation(addr_t address) {
3964 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
3966 // Remove any previous allocation which contains the same address
3967 auto it = m_allocations.begin();
3968 while (it != m_allocations.end()) {
3969 if (*((*it)->address) == address) {
3971 log->Printf("%s - Removing allocation id: %d, address: 0x%" PRIx64,
3972 __FUNCTION__, (*it)->id, address);
3974 it = m_allocations.erase(it);
3980 std::unique_ptr<AllocationDetails> a(new AllocationDetails);
3981 a->address = address;
3982 m_allocations.push_back(std::move(a));
3983 return m_allocations.back().get();
3986 bool RenderScriptRuntime::ResolveKernelName(lldb::addr_t kernel_addr,
3987 ConstString &name) {
3988 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS);
3990 Target &target = GetProcess()->GetTarget();
3992 // RenderScript module
3993 if (!target.GetSectionLoadList().ResolveLoadAddress(kernel_addr, resolved)) {
3995 log->Printf("%s: unable to resolve 0x%" PRIx64 " to a loaded symbol",
3996 __FUNCTION__, kernel_addr);
4000 Symbol *sym = resolved.CalculateSymbolContextSymbol();
4004 name = sym->GetName();
4005 assert(IsRenderScriptModule(resolved.CalculateSymbolContextModule()));
4007 log->Printf("%s: 0x%" PRIx64 " resolved to the symbol '%s'", __FUNCTION__,
4008 kernel_addr, name.GetCString());
4012 void RSModuleDescriptor::Dump(Stream &strm) const {
4013 int indent = strm.GetIndentLevel();
4016 m_module->GetFileSpec().Dump(&strm);
4017 strm.Indent(m_module->GetNumCompileUnits() ? "Debug info loaded."
4018 : "Debug info does not exist.");
4023 strm.Printf("Globals: %" PRIu64, static_cast<uint64_t>(m_globals.size()));
4026 for (const auto &global : m_globals) {
4032 strm.Printf("Kernels: %" PRIu64, static_cast<uint64_t>(m_kernels.size()));
4035 for (const auto &kernel : m_kernels) {
4041 strm.Printf("Pragmas: %" PRIu64, static_cast<uint64_t>(m_pragmas.size()));
4044 for (const auto &key_val : m_pragmas) {
4046 strm.Printf("%s: %s", key_val.first.c_str(), key_val.second.c_str());
4052 strm.Printf("Reductions: %" PRIu64,
4053 static_cast<uint64_t>(m_reductions.size()));
4056 for (const auto &reduction : m_reductions) {
4057 reduction.Dump(strm);
4060 strm.SetIndentLevel(indent);
4063 void RSGlobalDescriptor::Dump(Stream &strm) const {
4064 strm.Indent(m_name.AsCString());
4065 VariableList var_list;
4066 m_module->m_module->FindGlobalVariables(m_name, nullptr, 1U, var_list);
4067 if (var_list.GetSize() == 1) {
4068 auto var = var_list.GetVariableAtIndex(0);
4069 auto type = var->GetType();
4072 type->DumpTypeName(&strm);
4074 strm.Printf(" - Unknown Type");
4077 strm.Printf(" - variable identified, but not found in binary");
4078 const Symbol *s = m_module->m_module->FindFirstSymbolWithNameAndType(
4079 m_name, eSymbolTypeData);
4081 strm.Printf(" (symbol exists) ");
4088 void RSKernelDescriptor::Dump(Stream &strm) const {
4089 strm.Indent(m_name.AsCString());
4093 void RSReductionDescriptor::Dump(lldb_private::Stream &stream) const {
4094 stream.Indent(m_reduce_name.AsCString());
4095 stream.IndentMore();
4098 stream.Printf("accumulator: %s", m_accum_name.AsCString());
4101 stream.Printf("initializer: %s", m_init_name.AsCString());
4104 stream.Printf("combiner: %s", m_comb_name.AsCString());
4107 stream.Printf("outconverter: %s", m_outc_name.AsCString());
4109 // XXX This is currently unspecified by RenderScript, and unused
4111 // stream.Printf("halter: '%s'", m_init_name.AsCString());
4113 stream.IndentLess();
4116 class CommandObjectRenderScriptRuntimeModuleDump : public CommandObjectParsed {
4118 CommandObjectRenderScriptRuntimeModuleDump(CommandInterpreter &interpreter)
4119 : CommandObjectParsed(
4120 interpreter, "renderscript module dump",
4121 "Dumps renderscript specific information for all modules.",
4122 "renderscript module dump",
4123 eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
4125 ~CommandObjectRenderScriptRuntimeModuleDump() override = default;
4127 bool DoExecute(Args &command, CommandReturnObject &result) override {
4128 RenderScriptRuntime *runtime =
4129 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4130 eLanguageTypeExtRenderScript);
4131 runtime->DumpModules(result.GetOutputStream());
4132 result.SetStatus(eReturnStatusSuccessFinishResult);
4137 class CommandObjectRenderScriptRuntimeModule : public CommandObjectMultiword {
4139 CommandObjectRenderScriptRuntimeModule(CommandInterpreter &interpreter)
4140 : CommandObjectMultiword(interpreter, "renderscript module",
4141 "Commands that deal with RenderScript modules.",
4144 "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleDump(
4148 ~CommandObjectRenderScriptRuntimeModule() override = default;
4151 class CommandObjectRenderScriptRuntimeKernelList : public CommandObjectParsed {
4153 CommandObjectRenderScriptRuntimeKernelList(CommandInterpreter &interpreter)
4154 : CommandObjectParsed(
4155 interpreter, "renderscript kernel list",
4156 "Lists renderscript kernel names and associated script resources.",
4157 "renderscript kernel list",
4158 eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
4160 ~CommandObjectRenderScriptRuntimeKernelList() override = default;
4162 bool DoExecute(Args &command, CommandReturnObject &result) override {
4163 RenderScriptRuntime *runtime =
4164 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4165 eLanguageTypeExtRenderScript);
4166 runtime->DumpKernels(result.GetOutputStream());
4167 result.SetStatus(eReturnStatusSuccessFinishResult);
4172 static constexpr OptionDefinition g_renderscript_reduction_bp_set_options[] = {
4173 {LLDB_OPT_SET_1, false, "function-role", 't',
4174 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeOneLiner,
4175 "Break on a comma separated set of reduction kernel types "
4176 "(accumulator,outcoverter,combiner,initializer"},
4177 {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument,
4178 nullptr, {}, 0, eArgTypeValue,
4179 "Set a breakpoint on a single invocation of the kernel with specified "
4181 "Coordinate takes the form 'x[,y][,z] where x,y,z are positive "
4182 "integers representing kernel dimensions. "
4183 "Any unset dimensions will be defaulted to zero."}};
4185 class CommandObjectRenderScriptRuntimeReductionBreakpointSet
4186 : public CommandObjectParsed {
4188 CommandObjectRenderScriptRuntimeReductionBreakpointSet(
4189 CommandInterpreter &interpreter)
4190 : CommandObjectParsed(
4191 interpreter, "renderscript reduction breakpoint set",
4192 "Set a breakpoint on named RenderScript general reductions",
4193 "renderscript reduction breakpoint set <kernel_name> [-t "
4194 "<reduction_kernel_type,...>]",
4195 eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4196 eCommandProcessMustBePaused),
4199 class CommandOptions : public Options {
4203 m_kernel_types(RSReduceBreakpointResolver::eKernelTypeAll) {}
4205 ~CommandOptions() override = default;
4207 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4208 ExecutionContext *exe_ctx) override {
4210 StreamString err_str;
4211 const int short_option = m_getopt_table[option_idx].val;
4212 switch (short_option) {
4214 if (!ParseReductionTypes(option_arg, err_str))
4215 err.SetErrorStringWithFormat(
4216 "Unable to deduce reduction types for %s: %s",
4217 option_arg.str().c_str(), err_str.GetData());
4220 auto coord = RSCoordinate{};
4221 if (!ParseCoordinate(option_arg, coord))
4222 err.SetErrorStringWithFormat("unable to parse coordinate for %s",
4223 option_arg.str().c_str());
4225 m_have_coord = true;
4231 err.SetErrorStringWithFormat("Invalid option '-%c'", short_option);
4236 void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4237 m_have_coord = false;
4240 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4241 return llvm::makeArrayRef(g_renderscript_reduction_bp_set_options);
4244 bool ParseReductionTypes(llvm::StringRef option_val,
4245 StreamString &err_str) {
4246 m_kernel_types = RSReduceBreakpointResolver::eKernelTypeNone;
4247 const auto reduce_name_to_type = [](llvm::StringRef name) -> int {
4248 return llvm::StringSwitch<int>(name)
4249 .Case("accumulator", RSReduceBreakpointResolver::eKernelTypeAccum)
4250 .Case("initializer", RSReduceBreakpointResolver::eKernelTypeInit)
4251 .Case("outconverter", RSReduceBreakpointResolver::eKernelTypeOutC)
4252 .Case("combiner", RSReduceBreakpointResolver::eKernelTypeComb)
4253 .Case("all", RSReduceBreakpointResolver::eKernelTypeAll)
4254 // Currently not exposed by the runtime
4255 // .Case("halter", RSReduceBreakpointResolver::eKernelTypeHalter)
4259 // Matching a comma separated list of known words is fairly
4260 // straightforward with PCRE, but we're using ERE, so we end up with a
4261 // little ugliness...
4262 RegularExpression::Match match(/* max_matches */ 5);
4263 RegularExpression match_type_list(
4264 llvm::StringRef("^([[:alpha:]]+)(,[[:alpha:]]+){0,4}$"));
4266 assert(match_type_list.IsValid());
4268 if (!match_type_list.Execute(option_val, &match)) {
4270 "a comma-separated list of kernel types is required");
4274 // splitting on commas is much easier with llvm::StringRef than regex
4275 llvm::SmallVector<llvm::StringRef, 5> type_names;
4276 llvm::StringRef(option_val).split(type_names, ',');
4278 for (const auto &name : type_names) {
4279 const int type = reduce_name_to_type(name);
4281 err_str.Printf("unknown kernel type name %s", name.str().c_str());
4284 m_kernel_types |= type;
4291 llvm::StringRef m_reduce_name;
4292 RSCoordinate m_coord;
4296 Options *GetOptions() override { return &m_options; }
4298 bool DoExecute(Args &command, CommandReturnObject &result) override {
4299 const size_t argc = command.GetArgumentCount();
4301 result.AppendErrorWithFormat("'%s' takes 1 argument of reduction name, "
4302 "and an optional kernel type list",
4303 m_cmd_name.c_str());
4304 result.SetStatus(eReturnStatusFailed);
4308 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4309 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4310 eLanguageTypeExtRenderScript));
4312 auto &outstream = result.GetOutputStream();
4313 auto name = command.GetArgumentAtIndex(0);
4314 auto &target = m_exe_ctx.GetTargetSP();
4315 auto coord = m_options.m_have_coord ? &m_options.m_coord : nullptr;
4316 if (!runtime->PlaceBreakpointOnReduction(target, outstream, name, coord,
4317 m_options.m_kernel_types)) {
4318 result.SetStatus(eReturnStatusFailed);
4319 result.AppendError("Error: unable to place breakpoint on reduction");
4322 result.AppendMessage("Breakpoint(s) created");
4323 result.SetStatus(eReturnStatusSuccessFinishResult);
4328 CommandOptions m_options;
4331 static constexpr OptionDefinition g_renderscript_kernel_bp_set_options[] = {
4332 {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument,
4333 nullptr, {}, 0, eArgTypeValue,
4334 "Set a breakpoint on a single invocation of the kernel with specified "
4336 "Coordinate takes the form 'x[,y][,z] where x,y,z are positive "
4337 "integers representing kernel dimensions. "
4338 "Any unset dimensions will be defaulted to zero."}};
4340 class CommandObjectRenderScriptRuntimeKernelBreakpointSet
4341 : public CommandObjectParsed {
4343 CommandObjectRenderScriptRuntimeKernelBreakpointSet(
4344 CommandInterpreter &interpreter)
4345 : CommandObjectParsed(
4346 interpreter, "renderscript kernel breakpoint set",
4347 "Sets a breakpoint on a renderscript kernel.",
4348 "renderscript kernel breakpoint set <kernel_name> [-c x,y,z]",
4349 eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4350 eCommandProcessMustBePaused),
4353 ~CommandObjectRenderScriptRuntimeKernelBreakpointSet() override = default;
4355 Options *GetOptions() override { return &m_options; }
4357 class CommandOptions : public Options {
4359 CommandOptions() : Options() {}
4361 ~CommandOptions() override = default;
4363 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4364 ExecutionContext *exe_ctx) override {
4366 const int short_option = m_getopt_table[option_idx].val;
4368 switch (short_option) {
4370 auto coord = RSCoordinate{};
4371 if (!ParseCoordinate(option_arg, coord))
4372 err.SetErrorStringWithFormat(
4373 "Couldn't parse coordinate '%s', should be in format 'x,y,z'.",
4374 option_arg.str().c_str());
4376 m_have_coord = true;
4382 err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4388 void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4389 m_have_coord = false;
4392 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4393 return llvm::makeArrayRef(g_renderscript_kernel_bp_set_options);
4396 RSCoordinate m_coord;
4400 bool DoExecute(Args &command, CommandReturnObject &result) override {
4401 const size_t argc = command.GetArgumentCount();
4403 result.AppendErrorWithFormat(
4404 "'%s' takes 1 argument of kernel name, and an optional coordinate.",
4405 m_cmd_name.c_str());
4406 result.SetStatus(eReturnStatusFailed);
4410 RenderScriptRuntime *runtime =
4411 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4412 eLanguageTypeExtRenderScript);
4414 auto &outstream = result.GetOutputStream();
4415 auto &target = m_exe_ctx.GetTargetSP();
4416 auto name = command.GetArgumentAtIndex(0);
4417 auto coord = m_options.m_have_coord ? &m_options.m_coord : nullptr;
4418 if (!runtime->PlaceBreakpointOnKernel(target, outstream, name, coord)) {
4419 result.SetStatus(eReturnStatusFailed);
4420 result.AppendErrorWithFormat(
4421 "Error: unable to set breakpoint on kernel '%s'", name);
4425 result.AppendMessage("Breakpoint(s) created");
4426 result.SetStatus(eReturnStatusSuccessFinishResult);
4431 CommandOptions m_options;
4434 class CommandObjectRenderScriptRuntimeKernelBreakpointAll
4435 : public CommandObjectParsed {
4437 CommandObjectRenderScriptRuntimeKernelBreakpointAll(
4438 CommandInterpreter &interpreter)
4439 : CommandObjectParsed(
4440 interpreter, "renderscript kernel breakpoint all",
4441 "Automatically sets a breakpoint on all renderscript kernels that "
4442 "are or will be loaded.\n"
4443 "Disabling option means breakpoints will no longer be set on any "
4444 "kernels loaded in the future, "
4445 "but does not remove currently set breakpoints.",
4446 "renderscript kernel breakpoint all <enable/disable>",
4447 eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4448 eCommandProcessMustBePaused) {}
4450 ~CommandObjectRenderScriptRuntimeKernelBreakpointAll() override = default;
4452 bool DoExecute(Args &command, CommandReturnObject &result) override {
4453 const size_t argc = command.GetArgumentCount();
4455 result.AppendErrorWithFormat(
4456 "'%s' takes 1 argument of 'enable' or 'disable'", m_cmd_name.c_str());
4457 result.SetStatus(eReturnStatusFailed);
4461 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4462 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4463 eLanguageTypeExtRenderScript));
4465 bool do_break = false;
4466 const char *argument = command.GetArgumentAtIndex(0);
4467 if (strcmp(argument, "enable") == 0) {
4469 result.AppendMessage("Breakpoints will be set on all kernels.");
4470 } else if (strcmp(argument, "disable") == 0) {
4472 result.AppendMessage("Breakpoints will not be set on any new kernels.");
4474 result.AppendErrorWithFormat(
4475 "Argument must be either 'enable' or 'disable'");
4476 result.SetStatus(eReturnStatusFailed);
4480 runtime->SetBreakAllKernels(do_break, m_exe_ctx.GetTargetSP());
4482 result.SetStatus(eReturnStatusSuccessFinishResult);
4487 class CommandObjectRenderScriptRuntimeReductionBreakpoint
4488 : public CommandObjectMultiword {
4490 CommandObjectRenderScriptRuntimeReductionBreakpoint(
4491 CommandInterpreter &interpreter)
4492 : CommandObjectMultiword(interpreter, "renderscript reduction breakpoint",
4493 "Commands that manipulate breakpoints on "
4494 "renderscript general reductions.",
4497 "set", CommandObjectSP(
4498 new CommandObjectRenderScriptRuntimeReductionBreakpointSet(
4502 ~CommandObjectRenderScriptRuntimeReductionBreakpoint() override = default;
4505 class CommandObjectRenderScriptRuntimeKernelCoordinate
4506 : public CommandObjectParsed {
4508 CommandObjectRenderScriptRuntimeKernelCoordinate(
4509 CommandInterpreter &interpreter)
4510 : CommandObjectParsed(
4511 interpreter, "renderscript kernel coordinate",
4512 "Shows the (x,y,z) coordinate of the current kernel invocation.",
4513 "renderscript kernel coordinate",
4514 eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4515 eCommandProcessMustBePaused) {}
4517 ~CommandObjectRenderScriptRuntimeKernelCoordinate() override = default;
4519 bool DoExecute(Args &command, CommandReturnObject &result) override {
4520 RSCoordinate coord{};
4521 bool success = RenderScriptRuntime::GetKernelCoordinate(
4522 coord, m_exe_ctx.GetThreadPtr());
4523 Stream &stream = result.GetOutputStream();
4526 stream.Printf("Coordinate: " FMT_COORD, coord.x, coord.y, coord.z);
4528 result.SetStatus(eReturnStatusSuccessFinishResult);
4530 stream.Printf("Error: Coordinate could not be found.");
4532 result.SetStatus(eReturnStatusFailed);
4538 class CommandObjectRenderScriptRuntimeKernelBreakpoint
4539 : public CommandObjectMultiword {
4541 CommandObjectRenderScriptRuntimeKernelBreakpoint(
4542 CommandInterpreter &interpreter)
4543 : CommandObjectMultiword(
4544 interpreter, "renderscript kernel",
4545 "Commands that generate breakpoints on renderscript kernels.",
4549 CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointSet(
4553 CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointAll(
4557 ~CommandObjectRenderScriptRuntimeKernelBreakpoint() override = default;
4560 class CommandObjectRenderScriptRuntimeKernel : public CommandObjectMultiword {
4562 CommandObjectRenderScriptRuntimeKernel(CommandInterpreter &interpreter)
4563 : CommandObjectMultiword(interpreter, "renderscript kernel",
4564 "Commands that deal with RenderScript kernels.",
4567 "list", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelList(
4572 new CommandObjectRenderScriptRuntimeKernelCoordinate(interpreter)));
4576 new CommandObjectRenderScriptRuntimeKernelBreakpoint(interpreter)));
4579 ~CommandObjectRenderScriptRuntimeKernel() override = default;
4582 class CommandObjectRenderScriptRuntimeContextDump : public CommandObjectParsed {
4584 CommandObjectRenderScriptRuntimeContextDump(CommandInterpreter &interpreter)
4585 : CommandObjectParsed(interpreter, "renderscript context dump",
4586 "Dumps renderscript context information.",
4587 "renderscript context dump",
4588 eCommandRequiresProcess |
4589 eCommandProcessMustBeLaunched) {}
4591 ~CommandObjectRenderScriptRuntimeContextDump() override = default;
4593 bool DoExecute(Args &command, CommandReturnObject &result) override {
4594 RenderScriptRuntime *runtime =
4595 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4596 eLanguageTypeExtRenderScript);
4597 runtime->DumpContexts(result.GetOutputStream());
4598 result.SetStatus(eReturnStatusSuccessFinishResult);
4603 static constexpr OptionDefinition g_renderscript_runtime_alloc_dump_options[] = {
4604 {LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument,
4605 nullptr, {}, 0, eArgTypeFilename,
4606 "Print results to specified file instead of command line."}};
4608 class CommandObjectRenderScriptRuntimeContext : public CommandObjectMultiword {
4610 CommandObjectRenderScriptRuntimeContext(CommandInterpreter &interpreter)
4611 : CommandObjectMultiword(interpreter, "renderscript context",
4612 "Commands that deal with RenderScript contexts.",
4615 "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeContextDump(
4619 ~CommandObjectRenderScriptRuntimeContext() override = default;
4622 class CommandObjectRenderScriptRuntimeAllocationDump
4623 : public CommandObjectParsed {
4625 CommandObjectRenderScriptRuntimeAllocationDump(
4626 CommandInterpreter &interpreter)
4627 : CommandObjectParsed(interpreter, "renderscript allocation dump",
4628 "Displays the contents of a particular allocation",
4629 "renderscript allocation dump <ID>",
4630 eCommandRequiresProcess |
4631 eCommandProcessMustBeLaunched),
4634 ~CommandObjectRenderScriptRuntimeAllocationDump() override = default;
4636 Options *GetOptions() override { return &m_options; }
4638 class CommandOptions : public Options {
4640 CommandOptions() : Options() {}
4642 ~CommandOptions() override = default;
4644 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4645 ExecutionContext *exe_ctx) override {
4647 const int short_option = m_getopt_table[option_idx].val;
4649 switch (short_option) {
4651 m_outfile.SetFile(option_arg, FileSpec::Style::native);
4652 FileSystem::Instance().Resolve(m_outfile);
4653 if (FileSystem::Instance().Exists(m_outfile)) {
4655 err.SetErrorStringWithFormat("file already exists: '%s'",
4656 option_arg.str().c_str());
4660 err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4666 void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4670 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4671 return llvm::makeArrayRef(g_renderscript_runtime_alloc_dump_options);
4677 bool DoExecute(Args &command, CommandReturnObject &result) override {
4678 const size_t argc = command.GetArgumentCount();
4680 result.AppendErrorWithFormat("'%s' takes 1 argument, an allocation ID. "
4681 "As well as an optional -f argument",
4682 m_cmd_name.c_str());
4683 result.SetStatus(eReturnStatusFailed);
4687 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4688 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4689 eLanguageTypeExtRenderScript));
4691 const char *id_cstr = command.GetArgumentAtIndex(0);
4692 bool success = false;
4694 StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
4696 result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4698 result.SetStatus(eReturnStatusFailed);
4702 Stream *output_strm = nullptr;
4703 StreamFile outfile_stream;
4704 const FileSpec &outfile_spec =
4705 m_options.m_outfile; // Dump allocation to file instead
4708 std::string path = outfile_spec.GetPath();
4709 auto error = FileSystem::Instance().Open(
4710 outfile_stream.GetFile(), outfile_spec,
4711 File::eOpenOptionWrite | File::eOpenOptionCanCreate);
4712 if (error.Success()) {
4713 output_strm = &outfile_stream;
4714 result.GetOutputStream().Printf("Results written to '%s'",
4716 result.GetOutputStream().EOL();
4718 result.AppendErrorWithFormat("Couldn't open file '%s'", path.c_str());
4719 result.SetStatus(eReturnStatusFailed);
4723 output_strm = &result.GetOutputStream();
4725 assert(output_strm != nullptr);
4727 runtime->DumpAllocation(*output_strm, m_exe_ctx.GetFramePtr(), id);
4730 result.SetStatus(eReturnStatusSuccessFinishResult);
4732 result.SetStatus(eReturnStatusFailed);
4738 CommandOptions m_options;
4741 static constexpr OptionDefinition g_renderscript_runtime_alloc_list_options[] = {
4742 {LLDB_OPT_SET_1, false, "id", 'i', OptionParser::eRequiredArgument, nullptr,
4743 {}, 0, eArgTypeIndex,
4744 "Only show details of a single allocation with specified id."}};
4746 class CommandObjectRenderScriptRuntimeAllocationList
4747 : public CommandObjectParsed {
4749 CommandObjectRenderScriptRuntimeAllocationList(
4750 CommandInterpreter &interpreter)
4751 : CommandObjectParsed(
4752 interpreter, "renderscript allocation list",
4753 "List renderscript allocations and their information.",
4754 "renderscript allocation list",
4755 eCommandRequiresProcess | eCommandProcessMustBeLaunched),
4758 ~CommandObjectRenderScriptRuntimeAllocationList() override = default;
4760 Options *GetOptions() override { return &m_options; }
4762 class CommandOptions : public Options {
4764 CommandOptions() : Options(), m_id(0) {}
4766 ~CommandOptions() override = default;
4768 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4769 ExecutionContext *exe_ctx) override {
4771 const int short_option = m_getopt_table[option_idx].val;
4773 switch (short_option) {
4775 if (option_arg.getAsInteger(0, m_id))
4776 err.SetErrorStringWithFormat("invalid integer value for option '%c'",
4780 err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4786 void OptionParsingStarting(ExecutionContext *exe_ctx) override { m_id = 0; }
4788 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4789 return llvm::makeArrayRef(g_renderscript_runtime_alloc_list_options);
4795 bool DoExecute(Args &command, CommandReturnObject &result) override {
4796 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4797 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4798 eLanguageTypeExtRenderScript));
4799 runtime->ListAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr(),
4801 result.SetStatus(eReturnStatusSuccessFinishResult);
4806 CommandOptions m_options;
4809 class CommandObjectRenderScriptRuntimeAllocationLoad
4810 : public CommandObjectParsed {
4812 CommandObjectRenderScriptRuntimeAllocationLoad(
4813 CommandInterpreter &interpreter)
4814 : CommandObjectParsed(
4815 interpreter, "renderscript allocation load",
4816 "Loads renderscript allocation contents from a file.",
4817 "renderscript allocation load <ID> <filename>",
4818 eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
4820 ~CommandObjectRenderScriptRuntimeAllocationLoad() override = default;
4822 bool DoExecute(Args &command, CommandReturnObject &result) override {
4823 const size_t argc = command.GetArgumentCount();
4825 result.AppendErrorWithFormat(
4826 "'%s' takes 2 arguments, an allocation ID and filename to read from.",
4827 m_cmd_name.c_str());
4828 result.SetStatus(eReturnStatusFailed);
4832 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4833 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4834 eLanguageTypeExtRenderScript));
4836 const char *id_cstr = command.GetArgumentAtIndex(0);
4837 bool success = false;
4839 StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
4841 result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4843 result.SetStatus(eReturnStatusFailed);
4847 const char *path = command.GetArgumentAtIndex(1);
4848 bool loaded = runtime->LoadAllocation(result.GetOutputStream(), id, path,
4849 m_exe_ctx.GetFramePtr());
4852 result.SetStatus(eReturnStatusSuccessFinishResult);
4854 result.SetStatus(eReturnStatusFailed);
4860 class CommandObjectRenderScriptRuntimeAllocationSave
4861 : public CommandObjectParsed {
4863 CommandObjectRenderScriptRuntimeAllocationSave(
4864 CommandInterpreter &interpreter)
4865 : CommandObjectParsed(interpreter, "renderscript allocation save",
4866 "Write renderscript allocation contents to a file.",
4867 "renderscript allocation save <ID> <filename>",
4868 eCommandRequiresProcess |
4869 eCommandProcessMustBeLaunched) {}
4871 ~CommandObjectRenderScriptRuntimeAllocationSave() override = default;
4873 bool DoExecute(Args &command, CommandReturnObject &result) override {
4874 const size_t argc = command.GetArgumentCount();
4876 result.AppendErrorWithFormat(
4877 "'%s' takes 2 arguments, an allocation ID and filename to read from.",
4878 m_cmd_name.c_str());
4879 result.SetStatus(eReturnStatusFailed);
4883 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4884 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4885 eLanguageTypeExtRenderScript));
4887 const char *id_cstr = command.GetArgumentAtIndex(0);
4888 bool success = false;
4890 StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
4892 result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4894 result.SetStatus(eReturnStatusFailed);
4898 const char *path = command.GetArgumentAtIndex(1);
4899 bool saved = runtime->SaveAllocation(result.GetOutputStream(), id, path,
4900 m_exe_ctx.GetFramePtr());
4903 result.SetStatus(eReturnStatusSuccessFinishResult);
4905 result.SetStatus(eReturnStatusFailed);
4911 class CommandObjectRenderScriptRuntimeAllocationRefresh
4912 : public CommandObjectParsed {
4914 CommandObjectRenderScriptRuntimeAllocationRefresh(
4915 CommandInterpreter &interpreter)
4916 : CommandObjectParsed(interpreter, "renderscript allocation refresh",
4917 "Recomputes the details of all allocations.",
4918 "renderscript allocation refresh",
4919 eCommandRequiresProcess |
4920 eCommandProcessMustBeLaunched) {}
4922 ~CommandObjectRenderScriptRuntimeAllocationRefresh() override = default;
4924 bool DoExecute(Args &command, CommandReturnObject &result) override {
4925 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4926 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4927 eLanguageTypeExtRenderScript));
4929 bool success = runtime->RecomputeAllAllocations(result.GetOutputStream(),
4930 m_exe_ctx.GetFramePtr());
4933 result.SetStatus(eReturnStatusSuccessFinishResult);
4936 result.SetStatus(eReturnStatusFailed);
4942 class CommandObjectRenderScriptRuntimeAllocation
4943 : public CommandObjectMultiword {
4945 CommandObjectRenderScriptRuntimeAllocation(CommandInterpreter &interpreter)
4946 : CommandObjectMultiword(
4947 interpreter, "renderscript allocation",
4948 "Commands that deal with RenderScript allocations.", nullptr) {
4952 new CommandObjectRenderScriptRuntimeAllocationList(interpreter)));
4956 new CommandObjectRenderScriptRuntimeAllocationDump(interpreter)));
4960 new CommandObjectRenderScriptRuntimeAllocationSave(interpreter)));
4964 new CommandObjectRenderScriptRuntimeAllocationLoad(interpreter)));
4967 CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationRefresh(
4971 ~CommandObjectRenderScriptRuntimeAllocation() override = default;
4974 class CommandObjectRenderScriptRuntimeStatus : public CommandObjectParsed {
4976 CommandObjectRenderScriptRuntimeStatus(CommandInterpreter &interpreter)
4977 : CommandObjectParsed(interpreter, "renderscript status",
4978 "Displays current RenderScript runtime status.",
4979 "renderscript status",
4980 eCommandRequiresProcess |
4981 eCommandProcessMustBeLaunched) {}
4983 ~CommandObjectRenderScriptRuntimeStatus() override = default;
4985 bool DoExecute(Args &command, CommandReturnObject &result) override {
4986 RenderScriptRuntime *runtime =
4987 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4988 eLanguageTypeExtRenderScript);
4989 runtime->DumpStatus(result.GetOutputStream());
4990 result.SetStatus(eReturnStatusSuccessFinishResult);
4995 class CommandObjectRenderScriptRuntimeReduction
4996 : public CommandObjectMultiword {
4998 CommandObjectRenderScriptRuntimeReduction(CommandInterpreter &interpreter)
4999 : CommandObjectMultiword(interpreter, "renderscript reduction",
5000 "Commands that handle general reduction kernels",
5004 CommandObjectSP(new CommandObjectRenderScriptRuntimeReductionBreakpoint(
5007 ~CommandObjectRenderScriptRuntimeReduction() override = default;
5010 class CommandObjectRenderScriptRuntime : public CommandObjectMultiword {
5012 CommandObjectRenderScriptRuntime(CommandInterpreter &interpreter)
5013 : CommandObjectMultiword(
5014 interpreter, "renderscript",
5015 "Commands for operating on the RenderScript runtime.",
5016 "renderscript <subcommand> [<subcommand-options>]") {
5018 "module", CommandObjectSP(
5019 new CommandObjectRenderScriptRuntimeModule(interpreter)));
5021 "status", CommandObjectSP(
5022 new CommandObjectRenderScriptRuntimeStatus(interpreter)));
5024 "kernel", CommandObjectSP(
5025 new CommandObjectRenderScriptRuntimeKernel(interpreter)));
5026 LoadSubCommand("context",
5027 CommandObjectSP(new CommandObjectRenderScriptRuntimeContext(
5032 new CommandObjectRenderScriptRuntimeAllocation(interpreter)));
5033 LoadSubCommand("scriptgroup",
5034 NewCommandObjectRenderScriptScriptGroup(interpreter));
5038 new CommandObjectRenderScriptRuntimeReduction(interpreter)));
5041 ~CommandObjectRenderScriptRuntime() override = default;
5044 void RenderScriptRuntime::Initiate() { assert(!m_initiated); }
5046 RenderScriptRuntime::RenderScriptRuntime(Process *process)
5047 : lldb_private::CPPLanguageRuntime(process), m_initiated(false),
5048 m_debuggerPresentFlagged(false), m_breakAllKernels(false),
5049 m_ir_passes(nullptr) {
5050 ModulesDidLoad(process->GetTarget().GetImages());
5053 lldb::CommandObjectSP RenderScriptRuntime::GetCommandObject(
5054 lldb_private::CommandInterpreter &interpreter) {
5055 return CommandObjectSP(new CommandObjectRenderScriptRuntime(interpreter));
5058 RenderScriptRuntime::~RenderScriptRuntime() = default;