1 //===-- RenderScriptRuntime.cpp ---------------------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "RenderScriptRuntime.h"
10 #include "RenderScriptScriptGroup.h"
12 #include "lldb/Breakpoint/StoppointCallbackContext.h"
13 #include "lldb/Core/Debugger.h"
14 #include "lldb/Core/DumpDataExtractor.h"
15 #include "lldb/Core/PluginManager.h"
16 #include "lldb/Core/ValueObjectVariable.h"
17 #include "lldb/DataFormatters/DumpValueObjectOptions.h"
18 #include "lldb/Expression/UserExpression.h"
19 #include "lldb/Host/OptionParser.h"
20 #include "lldb/Host/StringConvert.h"
21 #include "lldb/Interpreter/CommandInterpreter.h"
22 #include "lldb/Interpreter/CommandObjectMultiword.h"
23 #include "lldb/Interpreter/CommandReturnObject.h"
24 #include "lldb/Interpreter/Options.h"
25 #include "lldb/Symbol/Function.h"
26 #include "lldb/Symbol/Symbol.h"
27 #include "lldb/Symbol/Type.h"
28 #include "lldb/Symbol/VariableList.h"
29 #include "lldb/Target/Process.h"
30 #include "lldb/Target/RegisterContext.h"
31 #include "lldb/Target/SectionLoadList.h"
32 #include "lldb/Target/Target.h"
33 #include "lldb/Target/Thread.h"
34 #include "lldb/Utility/Args.h"
35 #include "lldb/Utility/ConstString.h"
36 #include "lldb/Utility/Log.h"
37 #include "lldb/Utility/RegisterValue.h"
38 #include "lldb/Utility/RegularExpression.h"
39 #include "lldb/Utility/Status.h"
41 #include "llvm/ADT/StringSwitch.h"
46 using namespace lldb_private;
47 using namespace lldb_renderscript;
49 #define FMT_COORD "(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ")"
51 char RenderScriptRuntime::ID = 0;
55 // The empirical_type adds a basic level of validation to arbitrary data
56 // allowing us to track if data has been discovered and stored or not. An
57 // empirical_type will be marked as valid only if it has been explicitly
59 template <typename type_t> class empirical_type {
61 // Ctor. Contents is invalid when constructed.
62 empirical_type() : valid(false) {}
64 // Return true and copy contents to out if valid, else return false.
65 bool get(type_t &out) const {
71 // Return a pointer to the contents or nullptr if it was not valid.
72 const type_t *get() const { return valid ? &data : nullptr; }
74 // Assign data explicitly.
75 void set(const type_t in) {
80 // Mark contents as invalid.
81 void invalidate() { valid = false; }
83 // Returns true if this type contains valid data.
84 bool isValid() const { return valid; }
86 // Assignment operator.
87 empirical_type<type_t> &operator=(const type_t in) {
92 // Dereference operator returns contents.
93 // Warning: Will assert if not valid so use only when you know data is valid.
94 const type_t &operator*() const {
104 // ArgItem is used by the GetArgs() function when reading function arguments
107 enum { ePointer, eInt32, eInt64, eLong, eBool } type;
111 explicit operator uint64_t() const { return value; }
114 // Context structure to be passed into GetArgsXXX(), argument reading functions
117 RegisterContext *reg_ctx;
121 bool GetArgsX86(const GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
122 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
126 // get the current stack pointer
127 uint64_t sp = ctx.reg_ctx->GetSP();
129 for (size_t i = 0; i < num_args; ++i) {
130 ArgItem &arg = arg_list[i];
131 // advance up the stack by one argument
132 sp += sizeof(uint32_t);
133 // get the argument type size
134 size_t arg_size = sizeof(uint32_t);
135 // read the argument from memory
139 ctx.process->ReadMemory(sp, &arg.value, sizeof(uint32_t), err);
140 if (read != arg_size || !err.Success()) {
142 log->Printf("%s - error reading argument: %" PRIu64 " '%s'",
143 __FUNCTION__, uint64_t(i), err.AsCString());
150 bool GetArgsX86_64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
151 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
153 // number of arguments passed in registers
154 static const uint32_t args_in_reg = 6;
155 // register passing order
156 static const std::array<const char *, args_in_reg> reg_names{
157 {"rdi", "rsi", "rdx", "rcx", "r8", "r9"}};
158 // argument type to size mapping
159 static const std::array<size_t, 5> arg_size{{
169 // get the current stack pointer
170 uint64_t sp = ctx.reg_ctx->GetSP();
171 // step over the return address
172 sp += sizeof(uint64_t);
174 // check the stack alignment was correct (16 byte aligned)
175 if ((sp & 0xf) != 0x0) {
177 log->Printf("%s - stack misaligned", __FUNCTION__);
181 // find the start of arguments on the stack
182 uint64_t sp_offset = 0;
183 for (uint32_t i = args_in_reg; i < num_args; ++i) {
184 sp_offset += arg_size[arg_list[i].type];
186 // round up to multiple of 16
187 sp_offset = (sp_offset + 0xf) & 0xf;
190 for (size_t i = 0; i < num_args; ++i) {
191 bool success = false;
192 ArgItem &arg = arg_list[i];
193 // arguments passed in registers
194 if (i < args_in_reg) {
195 const RegisterInfo *reg =
196 ctx.reg_ctx->GetRegisterInfoByName(reg_names[i]);
197 RegisterValue reg_val;
198 if (ctx.reg_ctx->ReadRegister(reg, reg_val))
199 arg.value = reg_val.GetAsUInt64(0, &success);
201 // arguments passed on the stack
203 // get the argument type size
204 const size_t size = arg_size[arg_list[i].type];
205 // read the argument from memory
207 // note: due to little endian layout reading 4 or 8 bytes will give the
209 size_t read = ctx.process->ReadMemory(sp, &arg.value, size, err);
210 success = (err.Success() && read == size);
211 // advance past this argument
214 // fail if we couldn't read this argument
217 log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
218 __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
225 bool GetArgsArm(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
226 // number of arguments passed in registers
227 static const uint32_t args_in_reg = 4;
229 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
233 // get the current stack pointer
234 uint64_t sp = ctx.reg_ctx->GetSP();
236 for (size_t i = 0; i < num_args; ++i) {
237 bool success = false;
238 ArgItem &arg = arg_list[i];
239 // arguments passed in registers
240 if (i < args_in_reg) {
241 const RegisterInfo *reg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
242 RegisterValue reg_val;
243 if (ctx.reg_ctx->ReadRegister(reg, reg_val))
244 arg.value = reg_val.GetAsUInt32(0, &success);
246 // arguments passed on the stack
248 // get the argument type size
249 const size_t arg_size = sizeof(uint32_t);
252 // read this argument from memory
254 ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
255 success = (err.Success() && bytes_read == arg_size);
256 // advance the stack pointer
257 sp += sizeof(uint32_t);
259 // fail if we couldn't read this argument
262 log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
263 __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
270 bool GetArgsAarch64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
271 // number of arguments passed in registers
272 static const uint32_t args_in_reg = 8;
274 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
276 for (size_t i = 0; i < num_args; ++i) {
277 bool success = false;
278 ArgItem &arg = arg_list[i];
279 // arguments passed in registers
280 if (i < args_in_reg) {
281 const RegisterInfo *reg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
282 RegisterValue reg_val;
283 if (ctx.reg_ctx->ReadRegister(reg, reg_val))
284 arg.value = reg_val.GetAsUInt64(0, &success);
286 // arguments passed on the stack
289 log->Printf("%s - reading arguments spilled to stack not implemented",
292 // fail if we couldn't read this argument
295 log->Printf("%s - error reading argument: %" PRIu64, __FUNCTION__,
303 bool GetArgsMipsel(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
304 // number of arguments passed in registers
305 static const uint32_t args_in_reg = 4;
306 // register file offset to first argument
307 static const uint32_t reg_offset = 4;
309 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
313 // find offset to arguments on the stack (+16 to skip over a0-a3 shadow
315 uint64_t sp = ctx.reg_ctx->GetSP() + 16;
317 for (size_t i = 0; i < num_args; ++i) {
318 bool success = false;
319 ArgItem &arg = arg_list[i];
320 // arguments passed in registers
321 if (i < args_in_reg) {
322 const RegisterInfo *reg =
323 ctx.reg_ctx->GetRegisterInfoAtIndex(i + reg_offset);
324 RegisterValue reg_val;
325 if (ctx.reg_ctx->ReadRegister(reg, reg_val))
326 arg.value = reg_val.GetAsUInt64(0, &success);
328 // arguments passed on the stack
330 const size_t arg_size = sizeof(uint32_t);
333 ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
334 success = (err.Success() && bytes_read == arg_size);
335 // advance the stack pointer
338 // fail if we couldn't read this argument
341 log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
342 __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
349 bool GetArgsMips64el(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
350 // number of arguments passed in registers
351 static const uint32_t args_in_reg = 8;
352 // register file offset to first argument
353 static const uint32_t reg_offset = 4;
355 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
359 // get the current stack pointer
360 uint64_t sp = ctx.reg_ctx->GetSP();
362 for (size_t i = 0; i < num_args; ++i) {
363 bool success = false;
364 ArgItem &arg = arg_list[i];
365 // arguments passed in registers
366 if (i < args_in_reg) {
367 const RegisterInfo *reg =
368 ctx.reg_ctx->GetRegisterInfoAtIndex(i + reg_offset);
369 RegisterValue reg_val;
370 if (ctx.reg_ctx->ReadRegister(reg, reg_val))
371 arg.value = reg_val.GetAsUInt64(0, &success);
373 // arguments passed on the stack
375 // get the argument type size
376 const size_t arg_size = sizeof(uint64_t);
379 // read this argument from memory
381 ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
382 success = (err.Success() && bytes_read == arg_size);
383 // advance the stack pointer
386 // fail if we couldn't read this argument
389 log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
390 __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
397 bool GetArgs(ExecutionContext &exe_ctx, ArgItem *arg_list, size_t num_args) {
398 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
400 // verify that we have a target
401 if (!exe_ctx.GetTargetPtr()) {
403 log->Printf("%s - invalid target", __FUNCTION__);
407 GetArgsCtx ctx = {exe_ctx.GetRegisterContext(), exe_ctx.GetProcessPtr()};
408 assert(ctx.reg_ctx && ctx.process);
410 // dispatch based on architecture
411 switch (exe_ctx.GetTargetPtr()->GetArchitecture().GetMachine()) {
412 case llvm::Triple::ArchType::x86:
413 return GetArgsX86(ctx, arg_list, num_args);
415 case llvm::Triple::ArchType::x86_64:
416 return GetArgsX86_64(ctx, arg_list, num_args);
418 case llvm::Triple::ArchType::arm:
419 return GetArgsArm(ctx, arg_list, num_args);
421 case llvm::Triple::ArchType::aarch64:
422 return GetArgsAarch64(ctx, arg_list, num_args);
424 case llvm::Triple::ArchType::mipsel:
425 return GetArgsMipsel(ctx, arg_list, num_args);
427 case llvm::Triple::ArchType::mips64el:
428 return GetArgsMips64el(ctx, arg_list, num_args);
431 // unsupported architecture
434 "%s - architecture not supported: '%s'", __FUNCTION__,
435 exe_ctx.GetTargetRef().GetArchitecture().GetArchitectureName());
441 bool IsRenderScriptScriptModule(ModuleSP module) {
444 return module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"),
445 eSymbolTypeData) != nullptr;
448 bool ParseCoordinate(llvm::StringRef coord_s, RSCoordinate &coord) {
449 // takes an argument of the form 'num[,num][,num]'. Where 'coord_s' is a
450 // comma separated 1,2 or 3-dimensional coordinate with the whitespace
451 // trimmed. Missing coordinates are defaulted to zero. If parsing of any
452 // elements fails the contents of &coord are undefined and `false` is
453 // returned, `true` otherwise
455 RegularExpression regex;
456 RegularExpression::Match regex_match(3);
458 bool matched = false;
459 if (regex.Compile(llvm::StringRef("^([0-9]+),([0-9]+),([0-9]+)$")) &&
460 regex.Execute(coord_s, ®ex_match))
462 else if (regex.Compile(llvm::StringRef("^([0-9]+),([0-9]+)$")) &&
463 regex.Execute(coord_s, ®ex_match))
465 else if (regex.Compile(llvm::StringRef("^([0-9]+)$")) &&
466 regex.Execute(coord_s, ®ex_match))
472 auto get_index = [&](int idx, uint32_t &i) -> bool {
475 if (regex_match.GetMatchAtIndex(coord_s.str().c_str(), idx + 1, group))
476 return !llvm::StringRef(group).getAsInteger<uint32_t>(10, i);
480 return get_index(0, coord.x) && get_index(1, coord.y) &&
481 get_index(2, coord.z);
484 bool SkipPrologue(lldb::ModuleSP &module, Address &addr) {
485 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
487 uint32_t resolved_flags =
488 module->ResolveSymbolContextForAddress(addr, eSymbolContextFunction, sc);
489 if (resolved_flags & eSymbolContextFunction) {
491 const uint32_t offset = sc.function->GetPrologueByteSize();
492 ConstString name = sc.GetFunctionName();
496 log->Printf("%s: Prologue offset for %s is %" PRIu32, __FUNCTION__,
497 name.AsCString(), offset);
503 } // anonymous namespace
505 // The ScriptDetails class collects data associated with a single script
507 struct RenderScriptRuntime::ScriptDetails {
508 ~ScriptDetails() = default;
510 enum ScriptType { eScript, eScriptC };
512 // The derived type of the script.
513 empirical_type<ScriptType> type;
514 // The name of the original source file.
515 empirical_type<std::string> res_name;
516 // Path to script .so file on the device.
517 empirical_type<std::string> shared_lib;
518 // Directory where kernel objects are cached on device.
519 empirical_type<std::string> cache_dir;
520 // Pointer to the context which owns this script.
521 empirical_type<lldb::addr_t> context;
522 // Pointer to the script object itself.
523 empirical_type<lldb::addr_t> script;
526 // This Element class represents the Element object in RS, defining the type
527 // associated with an Allocation.
528 struct RenderScriptRuntime::Element {
529 // Taken from rsDefines.h
539 RS_KIND_INVALID = 100
542 // Taken from rsDefines.h
558 RS_TYPE_UNSIGNED_5_6_5,
559 RS_TYPE_UNSIGNED_5_5_5_1,
560 RS_TYPE_UNSIGNED_4_4_4_4,
566 RS_TYPE_ELEMENT = 1000,
572 RS_TYPE_PROGRAM_FRAGMENT,
573 RS_TYPE_PROGRAM_VERTEX,
574 RS_TYPE_PROGRAM_RASTER,
575 RS_TYPE_PROGRAM_STORE,
578 RS_TYPE_INVALID = 10000
581 std::vector<Element> children; // Child Element fields for structs
582 empirical_type<lldb::addr_t>
583 element_ptr; // Pointer to the RS Element of the Type
584 empirical_type<DataType>
585 type; // Type of each data pointer stored by the allocation
586 empirical_type<DataKind>
587 type_kind; // Defines pixel type if Allocation is created from an image
588 empirical_type<uint32_t>
589 type_vec_size; // Vector size of each data point, e.g '4' for uchar4
590 empirical_type<uint32_t> field_count; // Number of Subelements
591 empirical_type<uint32_t> datum_size; // Size of a single Element with padding
592 empirical_type<uint32_t> padding; // Number of padding bytes
593 empirical_type<uint32_t>
594 array_size; // Number of items in array, only needed for structs
595 ConstString type_name; // Name of type, only needed for structs
598 GetFallbackStructName(); // Print this as the type name of a struct Element
599 // If we can't resolve the actual struct name
601 bool ShouldRefresh() const {
602 const bool valid_ptr = element_ptr.isValid() && *element_ptr.get() != 0x0;
603 const bool valid_type =
604 type.isValid() && type_vec_size.isValid() && type_kind.isValid();
605 return !valid_ptr || !valid_type || !datum_size.isValid();
609 // This AllocationDetails class collects data associated with a single
610 // allocation instance.
611 struct RenderScriptRuntime::AllocationDetails {
626 // The FileHeader struct specifies the header we use for writing allocations
627 // to a binary file. Our format begins with the ASCII characters "RSAD",
628 // identifying the file as an allocation dump. Member variables dims and
629 // hdr_size are then written consecutively, immediately followed by an
630 // instance of the ElementHeader struct. Because Elements can contain
631 // subelements, there may be more than one instance of the ElementHeader
632 // struct. With this first instance being the root element, and the other
633 // instances being the root's descendants. To identify which instances are an
634 // ElementHeader's children, each struct is immediately followed by a
635 // sequence of consecutive offsets to the start of its child structs. These
637 // 4 bytes in size, and the 0 offset signifies no more children.
639 uint8_t ident[4]; // ASCII 'RSAD' identifying the file
640 uint32_t dims[3]; // Dimensions
641 uint16_t hdr_size; // Header size in bytes, including all element headers
644 struct ElementHeader {
645 uint16_t type; // DataType enum
646 uint32_t kind; // DataKind enum
647 uint32_t element_size; // Size of a single element, including padding
648 uint16_t vector_size; // Vector width
649 uint32_t array_size; // Number of elements in array
652 // Monotonically increasing from 1
655 // Maps Allocation DataType enum and vector size to printable strings using
656 // mapping from RenderScript numerical types summary documentation
657 static const char *RsDataTypeToString[][4];
659 // Maps Allocation DataKind enum to printable strings
660 static const char *RsDataKindToString[];
662 // Maps allocation types to format sizes for printing.
663 static const uint32_t RSTypeToFormat[][3];
665 // Give each allocation an ID as a way
666 // for commands to reference it.
669 // Allocation Element type
670 RenderScriptRuntime::Element element;
671 // Dimensions of the Allocation
672 empirical_type<Dimension> dimension;
673 // Pointer to address of the RS Allocation
674 empirical_type<lldb::addr_t> address;
675 // Pointer to the data held by the Allocation
676 empirical_type<lldb::addr_t> data_ptr;
677 // Pointer to the RS Type of the Allocation
678 empirical_type<lldb::addr_t> type_ptr;
679 // Pointer to the RS Context of the Allocation
680 empirical_type<lldb::addr_t> context;
681 // Size of the allocation
682 empirical_type<uint32_t> size;
683 // Stride between rows of the allocation
684 empirical_type<uint32_t> stride;
686 // Give each allocation an id, so we can reference it in user commands.
687 AllocationDetails() : id(ID++) {}
689 bool ShouldRefresh() const {
690 bool valid_ptrs = data_ptr.isValid() && *data_ptr.get() != 0x0;
691 valid_ptrs = valid_ptrs && type_ptr.isValid() && *type_ptr.get() != 0x0;
692 return !valid_ptrs || !dimension.isValid() || !size.isValid() ||
693 element.ShouldRefresh();
697 ConstString RenderScriptRuntime::Element::GetFallbackStructName() {
698 static const ConstString FallbackStructName("struct");
699 return FallbackStructName;
702 uint32_t RenderScriptRuntime::AllocationDetails::ID = 1;
704 const char *RenderScriptRuntime::AllocationDetails::RsDataKindToString[] = {
705 "User", "Undefined", "Undefined", "Undefined",
706 "Undefined", "Undefined", "Undefined", // Enum jumps from 0 to 7
707 "L Pixel", "A Pixel", "LA Pixel", "RGB Pixel",
708 "RGBA Pixel", "Pixel Depth", "YUV Pixel"};
710 const char *RenderScriptRuntime::AllocationDetails::RsDataTypeToString[][4] = {
711 {"None", "None", "None", "None"},
712 {"half", "half2", "half3", "half4"},
713 {"float", "float2", "float3", "float4"},
714 {"double", "double2", "double3", "double4"},
715 {"char", "char2", "char3", "char4"},
716 {"short", "short2", "short3", "short4"},
717 {"int", "int2", "int3", "int4"},
718 {"long", "long2", "long3", "long4"},
719 {"uchar", "uchar2", "uchar3", "uchar4"},
720 {"ushort", "ushort2", "ushort3", "ushort4"},
721 {"uint", "uint2", "uint3", "uint4"},
722 {"ulong", "ulong2", "ulong3", "ulong4"},
723 {"bool", "bool2", "bool3", "bool4"},
724 {"packed_565", "packed_565", "packed_565", "packed_565"},
725 {"packed_5551", "packed_5551", "packed_5551", "packed_5551"},
726 {"packed_4444", "packed_4444", "packed_4444", "packed_4444"},
727 {"rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4"},
728 {"rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3"},
729 {"rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2"},
732 {"RS Element", "RS Element", "RS Element", "RS Element"},
733 {"RS Type", "RS Type", "RS Type", "RS Type"},
734 {"RS Allocation", "RS Allocation", "RS Allocation", "RS Allocation"},
735 {"RS Sampler", "RS Sampler", "RS Sampler", "RS Sampler"},
736 {"RS Script", "RS Script", "RS Script", "RS Script"},
739 {"RS Mesh", "RS Mesh", "RS Mesh", "RS Mesh"},
740 {"RS Program Fragment", "RS Program Fragment", "RS Program Fragment",
741 "RS Program Fragment"},
742 {"RS Program Vertex", "RS Program Vertex", "RS Program Vertex",
743 "RS Program Vertex"},
744 {"RS Program Raster", "RS Program Raster", "RS Program Raster",
745 "RS Program Raster"},
746 {"RS Program Store", "RS Program Store", "RS Program Store",
748 {"RS Font", "RS Font", "RS Font", "RS Font"}};
750 // Used as an index into the RSTypeToFormat array elements
751 enum TypeToFormatIndex { eFormatSingle = 0, eFormatVector, eElementSize };
753 // { format enum of single element, format enum of element vector, size of
755 const uint32_t RenderScriptRuntime::AllocationDetails::RSTypeToFormat[][3] = {
757 {eFormatHex, eFormatHex, 1},
759 {eFormatFloat, eFormatVectorOfFloat16, 2},
761 {eFormatFloat, eFormatVectorOfFloat32, sizeof(float)},
763 {eFormatFloat, eFormatVectorOfFloat64, sizeof(double)},
765 {eFormatDecimal, eFormatVectorOfSInt8, sizeof(int8_t)},
767 {eFormatDecimal, eFormatVectorOfSInt16, sizeof(int16_t)},
769 {eFormatDecimal, eFormatVectorOfSInt32, sizeof(int32_t)},
771 {eFormatDecimal, eFormatVectorOfSInt64, sizeof(int64_t)},
772 // RS_TYPE_UNSIGNED_8
773 {eFormatDecimal, eFormatVectorOfUInt8, sizeof(uint8_t)},
774 // RS_TYPE_UNSIGNED_16
775 {eFormatDecimal, eFormatVectorOfUInt16, sizeof(uint16_t)},
776 // RS_TYPE_UNSIGNED_32
777 {eFormatDecimal, eFormatVectorOfUInt32, sizeof(uint32_t)},
778 // RS_TYPE_UNSIGNED_64
779 {eFormatDecimal, eFormatVectorOfUInt64, sizeof(uint64_t)},
781 {eFormatBoolean, eFormatBoolean, 1},
782 // RS_TYPE_UNSIGNED_5_6_5
783 {eFormatHex, eFormatHex, sizeof(uint16_t)},
784 // RS_TYPE_UNSIGNED_5_5_5_1
785 {eFormatHex, eFormatHex, sizeof(uint16_t)},
786 // RS_TYPE_UNSIGNED_4_4_4_4
787 {eFormatHex, eFormatHex, sizeof(uint16_t)},
788 // RS_TYPE_MATRIX_4X4
789 {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 16},
790 // RS_TYPE_MATRIX_3X3
791 {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 9},
792 // RS_TYPE_MATRIX_2X2
793 {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 4}};
797 RenderScriptRuntime::CreateInstance(Process *process,
798 lldb::LanguageType language) {
800 if (language == eLanguageTypeExtRenderScript)
801 return new RenderScriptRuntime(process);
806 // Callback with a module to search for matching symbols. We first check that
807 // the module contains RS kernels. Then look for a symbol which matches our
808 // kernel name. The breakpoint address is finally set using the address of this
810 Searcher::CallbackReturn
811 RSBreakpointResolver::SearchCallback(SearchFilter &filter,
812 SymbolContext &context, Address *, bool) {
813 ModuleSP module = context.module_sp;
815 if (!module || !IsRenderScriptScriptModule(module))
816 return Searcher::eCallbackReturnContinue;
818 // Attempt to set a breakpoint on the kernel name symbol within the module
819 // library. If it's not found, it's likely debug info is unavailable - try to
820 // set a breakpoint on <name>.expand.
821 const Symbol *kernel_sym =
822 module->FindFirstSymbolWithNameAndType(m_kernel_name, eSymbolTypeCode);
824 std::string kernel_name_expanded(m_kernel_name.AsCString());
825 kernel_name_expanded.append(".expand");
826 kernel_sym = module->FindFirstSymbolWithNameAndType(
827 ConstString(kernel_name_expanded.c_str()), eSymbolTypeCode);
831 Address bp_addr = kernel_sym->GetAddress();
832 if (filter.AddressPasses(bp_addr))
833 m_breakpoint->AddLocation(bp_addr);
836 return Searcher::eCallbackReturnContinue;
839 Searcher::CallbackReturn
840 RSReduceBreakpointResolver::SearchCallback(lldb_private::SearchFilter &filter,
841 lldb_private::SymbolContext &context,
843 // We need to have access to the list of reductions currently parsed, as
844 // reduce names don't actually exist as symbols in a module. They are only
845 // identifiable by parsing the .rs.info packet, or finding the expand symbol.
846 // We therefore need access to the list of parsed rs modules to properly
847 // resolve reduction names.
848 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
849 ModuleSP module = context.module_sp;
851 if (!module || !IsRenderScriptScriptModule(module))
852 return Searcher::eCallbackReturnContinue;
855 return Searcher::eCallbackReturnContinue;
857 for (const auto &module_desc : *m_rsmodules) {
858 if (module_desc->m_module != module)
861 for (const auto &reduction : module_desc->m_reductions) {
862 if (reduction.m_reduce_name != m_reduce_name)
865 std::array<std::pair<ConstString, int>, 5> funcs{
866 {{reduction.m_init_name, eKernelTypeInit},
867 {reduction.m_accum_name, eKernelTypeAccum},
868 {reduction.m_comb_name, eKernelTypeComb},
869 {reduction.m_outc_name, eKernelTypeOutC},
870 {reduction.m_halter_name, eKernelTypeHalter}}};
872 for (const auto &kernel : funcs) {
873 // Skip constituent functions that don't match our spec
874 if (!(m_kernel_types & kernel.second))
877 const auto kernel_name = kernel.first;
878 const auto symbol = module->FindFirstSymbolWithNameAndType(
879 kernel_name, eSymbolTypeCode);
883 auto address = symbol->GetAddress();
884 if (filter.AddressPasses(address)) {
886 if (!SkipPrologue(module, address)) {
888 log->Printf("%s: Error trying to skip prologue", __FUNCTION__);
890 m_breakpoint->AddLocation(address, &new_bp);
892 log->Printf("%s: %s reduction breakpoint on %s in %s", __FUNCTION__,
893 new_bp ? "new" : "existing", kernel_name.GetCString(),
894 address.GetModule()->GetFileSpec().GetCString());
899 return eCallbackReturnContinue;
902 Searcher::CallbackReturn RSScriptGroupBreakpointResolver::SearchCallback(
903 SearchFilter &filter, SymbolContext &context, Address *addr,
907 return eCallbackReturnContinue;
909 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
910 ModuleSP &module = context.module_sp;
912 if (!module || !IsRenderScriptScriptModule(module))
913 return Searcher::eCallbackReturnContinue;
915 std::vector<std::string> names;
916 m_breakpoint->GetNames(names);
918 return eCallbackReturnContinue;
920 for (auto &name : names) {
921 const RSScriptGroupDescriptorSP sg = FindScriptGroup(ConstString(name));
924 log->Printf("%s: could not find script group for %s", __FUNCTION__,
930 log->Printf("%s: Found ScriptGroup for %s", __FUNCTION__, name.c_str());
932 for (const RSScriptGroupDescriptor::Kernel &k : sg->m_kernels) {
934 log->Printf("%s: Adding breakpoint for %s", __FUNCTION__,
935 k.m_name.AsCString());
936 log->Printf("%s: Kernel address 0x%" PRIx64, __FUNCTION__, k.m_addr);
939 const lldb_private::Symbol *sym =
940 module->FindFirstSymbolWithNameAndType(k.m_name, eSymbolTypeCode);
943 log->Printf("%s: Unable to find symbol for %s", __FUNCTION__,
944 k.m_name.AsCString());
949 log->Printf("%s: Found symbol name is %s", __FUNCTION__,
950 sym->GetName().AsCString());
953 auto address = sym->GetAddress();
954 if (!SkipPrologue(module, address)) {
956 log->Printf("%s: Error trying to skip prologue", __FUNCTION__);
960 m_breakpoint->AddLocation(address, &new_bp);
963 log->Printf("%s: Placed %sbreakpoint on %s", __FUNCTION__,
964 new_bp ? "new " : "", k.m_name.AsCString());
966 // exit after placing the first breakpoint if we do not intend to stop on
967 // all kernels making up this script group
973 return eCallbackReturnContinue;
976 void RenderScriptRuntime::Initialize() {
977 PluginManager::RegisterPlugin(GetPluginNameStatic(),
978 "RenderScript language support", CreateInstance,
982 void RenderScriptRuntime::Terminate() {
983 PluginManager::UnregisterPlugin(CreateInstance);
986 lldb_private::ConstString RenderScriptRuntime::GetPluginNameStatic() {
987 static ConstString plugin_name("renderscript");
991 RenderScriptRuntime::ModuleKind
992 RenderScriptRuntime::GetModuleKind(const lldb::ModuleSP &module_sp) {
994 if (IsRenderScriptScriptModule(module_sp))
995 return eModuleKindKernelObj;
997 // Is this the main RS runtime library
998 const ConstString rs_lib("libRS.so");
999 if (module_sp->GetFileSpec().GetFilename() == rs_lib) {
1000 return eModuleKindLibRS;
1003 const ConstString rs_driverlib("libRSDriver.so");
1004 if (module_sp->GetFileSpec().GetFilename() == rs_driverlib) {
1005 return eModuleKindDriver;
1008 const ConstString rs_cpureflib("libRSCpuRef.so");
1009 if (module_sp->GetFileSpec().GetFilename() == rs_cpureflib) {
1010 return eModuleKindImpl;
1013 return eModuleKindIgnored;
1016 bool RenderScriptRuntime::IsRenderScriptModule(
1017 const lldb::ModuleSP &module_sp) {
1018 return GetModuleKind(module_sp) != eModuleKindIgnored;
1021 void RenderScriptRuntime::ModulesDidLoad(const ModuleList &module_list) {
1022 std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
1024 size_t num_modules = module_list.GetSize();
1025 for (size_t i = 0; i < num_modules; i++) {
1026 auto mod = module_list.GetModuleAtIndex(i);
1027 if (IsRenderScriptModule(mod)) {
1033 // PluginInterface protocol
1034 lldb_private::ConstString RenderScriptRuntime::GetPluginName() {
1035 return GetPluginNameStatic();
1038 uint32_t RenderScriptRuntime::GetPluginVersion() { return 1; }
1040 bool RenderScriptRuntime::GetDynamicTypeAndAddress(
1041 ValueObject &in_value, lldb::DynamicValueType use_dynamic,
1042 TypeAndOrName &class_type_or_name, Address &address,
1043 Value::ValueType &value_type) {
1048 RenderScriptRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name,
1049 ValueObject &static_value) {
1050 return type_and_or_name;
1053 bool RenderScriptRuntime::CouldHaveDynamicValue(ValueObject &in_value) {
1057 lldb::BreakpointResolverSP
1058 RenderScriptRuntime::CreateExceptionResolver(Breakpoint *bp, bool catch_bp,
1060 BreakpointResolverSP resolver_sp;
1064 const RenderScriptRuntime::HookDefn RenderScriptRuntime::s_runtimeHookDefns[] =
1067 {"rsdScriptInit", "_Z13rsdScriptInitPKN7android12renderscript7ContextEP"
1068 "NS0_7ScriptCEPKcS7_PKhjj",
1069 "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_"
1070 "7ScriptCEPKcS7_PKhmj",
1071 0, RenderScriptRuntime::eModuleKindDriver,
1072 &lldb_private::RenderScriptRuntime::CaptureScriptInit},
1073 {"rsdScriptInvokeForEachMulti",
1074 "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
1075 "_6ScriptEjPPKNS0_10AllocationEjPS6_PKvjPK12RsScriptCall",
1076 "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
1077 "_6ScriptEjPPKNS0_10AllocationEmPS6_PKvmPK12RsScriptCall",
1078 0, RenderScriptRuntime::eModuleKindDriver,
1079 &lldb_private::RenderScriptRuntime::CaptureScriptInvokeForEachMulti},
1080 {"rsdScriptSetGlobalVar", "_Z21rsdScriptSetGlobalVarPKN7android12render"
1081 "script7ContextEPKNS0_6ScriptEjPvj",
1082 "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_"
1084 0, RenderScriptRuntime::eModuleKindDriver,
1085 &lldb_private::RenderScriptRuntime::CaptureSetGlobalVar},
1088 {"rsdAllocationInit", "_Z17rsdAllocationInitPKN7android12renderscript7C"
1089 "ontextEPNS0_10AllocationEb",
1090 "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_"
1092 0, RenderScriptRuntime::eModuleKindDriver,
1093 &lldb_private::RenderScriptRuntime::CaptureAllocationInit},
1094 {"rsdAllocationRead2D",
1095 "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
1096 "10AllocationEjjj23RsAllocationCubemapFacejjPvjj",
1097 "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
1098 "10AllocationEjjj23RsAllocationCubemapFacejjPvmm",
1099 0, RenderScriptRuntime::eModuleKindDriver, nullptr},
1100 {"rsdAllocationDestroy", "_Z20rsdAllocationDestroyPKN7android12rendersc"
1101 "ript7ContextEPNS0_10AllocationE",
1102 "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_"
1104 0, RenderScriptRuntime::eModuleKindDriver,
1105 &lldb_private::RenderScriptRuntime::CaptureAllocationDestroy},
1107 // renderscript script groups
1108 {"rsdDebugHintScriptGroup2", "_ZN7android12renderscript21debugHintScrip"
1109 "tGroup2EPKcjPKPFvPK24RsExpandKernelDriver"
1111 "_ZN7android12renderscript21debugHintScriptGroup2EPKcjPKPFvPK24RsExpan"
1112 "dKernelDriverInfojjjEj",
1113 0, RenderScriptRuntime::eModuleKindImpl,
1114 &lldb_private::RenderScriptRuntime::CaptureDebugHintScriptGroup2}};
1116 const size_t RenderScriptRuntime::s_runtimeHookCount =
1117 sizeof(s_runtimeHookDefns) / sizeof(s_runtimeHookDefns[0]);
1119 bool RenderScriptRuntime::HookCallback(void *baton,
1120 StoppointCallbackContext *ctx,
1121 lldb::user_id_t break_id,
1122 lldb::user_id_t break_loc_id) {
1123 RuntimeHook *hook = (RuntimeHook *)baton;
1124 ExecutionContext exe_ctx(ctx->exe_ctx_ref);
1126 RenderScriptRuntime *lang_rt = llvm::cast<RenderScriptRuntime>(
1127 exe_ctx.GetProcessPtr()->GetLanguageRuntime(
1128 eLanguageTypeExtRenderScript));
1130 lang_rt->HookCallback(hook, exe_ctx);
1135 void RenderScriptRuntime::HookCallback(RuntimeHook *hook,
1136 ExecutionContext &exe_ctx) {
1137 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1140 log->Printf("%s - '%s'", __FUNCTION__, hook->defn->name);
1142 if (hook->defn->grabber) {
1143 (this->*(hook->defn->grabber))(hook, exe_ctx);
1147 void RenderScriptRuntime::CaptureDebugHintScriptGroup2(
1148 RuntimeHook *hook_info, ExecutionContext &context) {
1149 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1158 std::array<ArgItem, 4> args{{
1159 {ArgItem::ePointer, 0}, // const char *groupName
1160 {ArgItem::eInt32, 0}, // const uint32_t groupNameSize
1161 {ArgItem::ePointer, 0}, // const ExpandFuncTy *kernel
1162 {ArgItem::eInt32, 0}, // const uint32_t kernelCount
1165 if (!GetArgs(context, args.data(), args.size())) {
1167 log->Printf("%s - Error while reading the function parameters",
1171 log->Printf("%s - groupName : 0x%" PRIx64, __FUNCTION__,
1172 addr_t(args[eGroupName]));
1173 log->Printf("%s - groupNameSize: %" PRIu64, __FUNCTION__,
1174 uint64_t(args[eGroupNameSize]));
1175 log->Printf("%s - kernel : 0x%" PRIx64, __FUNCTION__,
1176 addr_t(args[eKernel]));
1177 log->Printf("%s - kernelCount : %" PRIu64, __FUNCTION__,
1178 uint64_t(args[eKernelCount]));
1181 // parse script group name
1182 ConstString group_name;
1185 const uint64_t len = uint64_t(args[eGroupNameSize]);
1186 std::unique_ptr<char[]> buffer(new char[uint32_t(len + 1)]);
1187 m_process->ReadMemory(addr_t(args[eGroupName]), buffer.get(), len, err);
1188 buffer.get()[len] = '\0';
1189 if (!err.Success()) {
1191 log->Printf("Error reading scriptgroup name from target");
1195 log->Printf("Extracted scriptgroup name %s", buffer.get());
1197 // write back the script group name
1198 group_name.SetCString(buffer.get());
1201 // create or access existing script group
1202 RSScriptGroupDescriptorSP group;
1204 // search for existing script group
1205 for (auto sg : m_scriptGroups) {
1206 if (sg->m_name == group_name) {
1212 group = std::make_shared<RSScriptGroupDescriptor>();
1213 group->m_name = group_name;
1214 m_scriptGroups.push_back(group);
1216 // already have this script group
1218 log->Printf("Attempt to add duplicate script group %s",
1219 group_name.AsCString());
1225 const uint32_t target_ptr_size = m_process->GetAddressByteSize();
1226 std::vector<addr_t> kernels;
1227 // parse kernel addresses in script group
1228 for (uint64_t i = 0; i < uint64_t(args[eKernelCount]); ++i) {
1229 RSScriptGroupDescriptor::Kernel kernel;
1230 // extract script group kernel addresses from the target
1231 const addr_t ptr_addr = addr_t(args[eKernel]) + i * target_ptr_size;
1232 uint64_t kernel_addr = 0;
1235 m_process->ReadMemory(ptr_addr, &kernel_addr, target_ptr_size, err);
1236 if (!err.Success() || read != target_ptr_size) {
1238 log->Printf("Error parsing kernel address %" PRIu64 " in script group",
1243 log->Printf("Extracted scriptgroup kernel address - 0x%" PRIx64,
1245 kernel.m_addr = kernel_addr;
1247 // try to resolve the associated kernel name
1248 if (!ResolveKernelName(kernel.m_addr, kernel.m_name)) {
1250 log->Printf("Parsed scriptgroup kernel %" PRIu64 " - 0x%" PRIx64, i,
1255 // try to find the non '.expand' function
1257 const llvm::StringRef expand(".expand");
1258 const llvm::StringRef name_ref = kernel.m_name.GetStringRef();
1259 if (name_ref.endswith(expand)) {
1260 const ConstString base_kernel(name_ref.drop_back(expand.size()));
1261 // verify this function is a valid kernel
1262 if (IsKnownKernel(base_kernel)) {
1263 kernel.m_name = base_kernel;
1265 log->Printf("%s - found non expand version '%s'", __FUNCTION__,
1266 base_kernel.GetCString());
1270 // add to a list of script group kernels we know about
1271 group->m_kernels.push_back(kernel);
1274 // Resolve any pending scriptgroup breakpoints
1276 Target &target = m_process->GetTarget();
1277 const BreakpointList &list = target.GetBreakpointList();
1278 const size_t num_breakpoints = list.GetSize();
1280 log->Printf("Resolving %zu breakpoints", num_breakpoints);
1281 for (size_t i = 0; i < num_breakpoints; ++i) {
1282 const BreakpointSP bp = list.GetBreakpointAtIndex(i);
1284 if (bp->MatchesName(group_name.AsCString())) {
1286 log->Printf("Found breakpoint with name %s",
1287 group_name.AsCString());
1288 bp->ResolveBreakpoint();
1295 void RenderScriptRuntime::CaptureScriptInvokeForEachMulti(
1296 RuntimeHook *hook, ExecutionContext &exe_ctx) {
1297 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1311 std::array<ArgItem, 9> args{{
1312 ArgItem{ArgItem::ePointer, 0}, // const Context *rsc
1313 ArgItem{ArgItem::ePointer, 0}, // Script *s
1314 ArgItem{ArgItem::eInt32, 0}, // uint32_t slot
1315 ArgItem{ArgItem::ePointer, 0}, // const Allocation **aIns
1316 ArgItem{ArgItem::eInt32, 0}, // size_t inLen
1317 ArgItem{ArgItem::ePointer, 0}, // Allocation *aout
1318 ArgItem{ArgItem::ePointer, 0}, // const void *usr
1319 ArgItem{ArgItem::eInt32, 0}, // size_t usrLen
1320 ArgItem{ArgItem::ePointer, 0}, // const RsScriptCall *sc
1323 bool success = GetArgs(exe_ctx, &args[0], args.size());
1326 log->Printf("%s - Error while reading the function parameters",
1331 const uint32_t target_ptr_size = m_process->GetAddressByteSize();
1333 std::vector<uint64_t> allocs;
1335 // traverse allocation list
1336 for (uint64_t i = 0; i < uint64_t(args[eRsInLen]); ++i) {
1337 // calculate offest to allocation pointer
1338 const addr_t addr = addr_t(args[eRsAIns]) + i * target_ptr_size;
1340 // Note: due to little endian layout, reading 32bits or 64bits into res
1341 // will give the correct results.
1342 uint64_t result = 0;
1343 size_t read = m_process->ReadMemory(addr, &result, target_ptr_size, err);
1344 if (read != target_ptr_size || !err.Success()) {
1347 "%s - Error while reading allocation list argument %" PRIu64,
1350 allocs.push_back(result);
1354 // if there is an output allocation track it
1355 if (uint64_t alloc_out = uint64_t(args[eRsAOut])) {
1356 allocs.push_back(alloc_out);
1359 // for all allocations we have found
1360 for (const uint64_t alloc_addr : allocs) {
1361 AllocationDetails *alloc = LookUpAllocation(alloc_addr);
1363 alloc = CreateAllocation(alloc_addr);
1366 // save the allocation address
1367 if (alloc->address.isValid()) {
1368 // check the allocation address we already have matches
1369 assert(*alloc->address.get() == alloc_addr);
1371 alloc->address = alloc_addr;
1376 if (alloc->context.isValid() &&
1377 *alloc->context.get() != addr_t(args[eRsContext]))
1378 log->Printf("%s - Allocation used by multiple contexts",
1381 alloc->context = addr_t(args[eRsContext]);
1385 // make sure we track this script object
1386 if (lldb_private::RenderScriptRuntime::ScriptDetails *script =
1387 LookUpScript(addr_t(args[eRsScript]), true)) {
1389 if (script->context.isValid() &&
1390 *script->context.get() != addr_t(args[eRsContext]))
1391 log->Printf("%s - Script used by multiple contexts", __FUNCTION__);
1393 script->context = addr_t(args[eRsContext]);
1397 void RenderScriptRuntime::CaptureSetGlobalVar(RuntimeHook *hook,
1398 ExecutionContext &context) {
1399 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1409 std::array<ArgItem, 5> args{{
1410 ArgItem{ArgItem::ePointer, 0}, // eRsContext
1411 ArgItem{ArgItem::ePointer, 0}, // eRsScript
1412 ArgItem{ArgItem::eInt32, 0}, // eRsId
1413 ArgItem{ArgItem::ePointer, 0}, // eRsData
1414 ArgItem{ArgItem::eInt32, 0}, // eRsLength
1417 bool success = GetArgs(context, &args[0], args.size());
1420 log->Printf("%s - error reading the function parameters.", __FUNCTION__);
1425 log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " slot %" PRIu64 " = 0x%" PRIx64
1426 ":%" PRIu64 "bytes.",
1427 __FUNCTION__, uint64_t(args[eRsContext]),
1428 uint64_t(args[eRsScript]), uint64_t(args[eRsId]),
1429 uint64_t(args[eRsData]), uint64_t(args[eRsLength]));
1431 addr_t script_addr = addr_t(args[eRsScript]);
1432 if (m_scriptMappings.find(script_addr) != m_scriptMappings.end()) {
1433 auto rsm = m_scriptMappings[script_addr];
1434 if (uint64_t(args[eRsId]) < rsm->m_globals.size()) {
1435 auto rsg = rsm->m_globals[uint64_t(args[eRsId])];
1436 log->Printf("%s - Setting of '%s' within '%s' inferred", __FUNCTION__,
1437 rsg.m_name.AsCString(),
1438 rsm->m_module->GetFileSpec().GetFilename().AsCString());
1444 void RenderScriptRuntime::CaptureAllocationInit(RuntimeHook *hook,
1445 ExecutionContext &exe_ctx) {
1446 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1448 enum { eRsContext, eRsAlloc, eRsForceZero };
1450 std::array<ArgItem, 3> args{{
1451 ArgItem{ArgItem::ePointer, 0}, // eRsContext
1452 ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
1453 ArgItem{ArgItem::eBool, 0}, // eRsForceZero
1456 bool success = GetArgs(exe_ctx, &args[0], args.size());
1459 log->Printf("%s - error while reading the function parameters",
1465 log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 ",0x%" PRIx64 " .",
1466 __FUNCTION__, uint64_t(args[eRsContext]),
1467 uint64_t(args[eRsAlloc]), uint64_t(args[eRsForceZero]));
1469 AllocationDetails *alloc = CreateAllocation(uint64_t(args[eRsAlloc]));
1471 alloc->context = uint64_t(args[eRsContext]);
1474 void RenderScriptRuntime::CaptureAllocationDestroy(RuntimeHook *hook,
1475 ExecutionContext &exe_ctx) {
1476 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1483 std::array<ArgItem, 2> args{{
1484 ArgItem{ArgItem::ePointer, 0}, // eRsContext
1485 ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
1488 bool success = GetArgs(exe_ctx, &args[0], args.size());
1491 log->Printf("%s - error while reading the function parameters.",
1497 log->Printf("%s - 0x%" PRIx64 ", 0x%" PRIx64 ".", __FUNCTION__,
1498 uint64_t(args[eRsContext]), uint64_t(args[eRsAlloc]));
1500 for (auto iter = m_allocations.begin(); iter != m_allocations.end(); ++iter) {
1501 auto &allocation_up = *iter; // get the unique pointer
1502 if (allocation_up->address.isValid() &&
1503 *allocation_up->address.get() == addr_t(args[eRsAlloc])) {
1504 m_allocations.erase(iter);
1506 log->Printf("%s - deleted allocation entry.", __FUNCTION__);
1512 log->Printf("%s - couldn't find destroyed allocation.", __FUNCTION__);
1515 void RenderScriptRuntime::CaptureScriptInit(RuntimeHook *hook,
1516 ExecutionContext &exe_ctx) {
1517 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1520 Process *process = exe_ctx.GetProcessPtr();
1522 enum { eRsContext, eRsScript, eRsResNamePtr, eRsCachedDirPtr };
1524 std::array<ArgItem, 4> args{
1525 {ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0},
1526 ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0}}};
1527 bool success = GetArgs(exe_ctx, &args[0], args.size());
1530 log->Printf("%s - error while reading the function parameters.",
1535 std::string res_name;
1536 process->ReadCStringFromMemory(addr_t(args[eRsResNamePtr]), res_name, err);
1539 log->Printf("%s - error reading res_name: %s.", __FUNCTION__,
1543 std::string cache_dir;
1544 process->ReadCStringFromMemory(addr_t(args[eRsCachedDirPtr]), cache_dir, err);
1547 log->Printf("%s - error reading cache_dir: %s.", __FUNCTION__,
1552 log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " => '%s' at '%s' .",
1553 __FUNCTION__, uint64_t(args[eRsContext]),
1554 uint64_t(args[eRsScript]), res_name.c_str(), cache_dir.c_str());
1556 if (res_name.size() > 0) {
1558 strm.Printf("librs.%s.so", res_name.c_str());
1560 ScriptDetails *script = LookUpScript(addr_t(args[eRsScript]), true);
1562 script->type = ScriptDetails::eScriptC;
1563 script->cache_dir = cache_dir;
1564 script->res_name = res_name;
1565 script->shared_lib = strm.GetString();
1566 script->context = addr_t(args[eRsContext]);
1570 log->Printf("%s - '%s' tagged with context 0x%" PRIx64
1571 " and script 0x%" PRIx64 ".",
1572 __FUNCTION__, strm.GetData(), uint64_t(args[eRsContext]),
1573 uint64_t(args[eRsScript]));
1575 log->Printf("%s - resource name invalid, Script not tagged.", __FUNCTION__);
1579 void RenderScriptRuntime::LoadRuntimeHooks(lldb::ModuleSP module,
1581 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1587 Target &target = GetProcess()->GetTarget();
1588 const llvm::Triple::ArchType machine = target.GetArchitecture().GetMachine();
1590 if (machine != llvm::Triple::ArchType::x86 &&
1591 machine != llvm::Triple::ArchType::arm &&
1592 machine != llvm::Triple::ArchType::aarch64 &&
1593 machine != llvm::Triple::ArchType::mipsel &&
1594 machine != llvm::Triple::ArchType::mips64el &&
1595 machine != llvm::Triple::ArchType::x86_64) {
1597 log->Printf("%s - unable to hook runtime functions.", __FUNCTION__);
1601 const uint32_t target_ptr_size =
1602 target.GetArchitecture().GetAddressByteSize();
1604 std::array<bool, s_runtimeHookCount> hook_placed;
1605 hook_placed.fill(false);
1607 for (size_t idx = 0; idx < s_runtimeHookCount; idx++) {
1608 const HookDefn *hook_defn = &s_runtimeHookDefns[idx];
1609 if (hook_defn->kind != kind) {
1613 const char *symbol_name = (target_ptr_size == 4)
1614 ? hook_defn->symbol_name_m32
1615 : hook_defn->symbol_name_m64;
1617 const Symbol *sym = module->FindFirstSymbolWithNameAndType(
1618 ConstString(symbol_name), eSymbolTypeCode);
1621 log->Printf("%s - symbol '%s' related to the function %s not found",
1622 __FUNCTION__, symbol_name, hook_defn->name);
1627 addr_t addr = sym->GetLoadAddress(&target);
1628 if (addr == LLDB_INVALID_ADDRESS) {
1630 log->Printf("%s - unable to resolve the address of hook function '%s' "
1631 "with symbol '%s'.",
1632 __FUNCTION__, hook_defn->name, symbol_name);
1636 log->Printf("%s - function %s, address resolved at 0x%" PRIx64,
1637 __FUNCTION__, hook_defn->name, addr);
1640 RuntimeHookSP hook(new RuntimeHook());
1641 hook->address = addr;
1642 hook->defn = hook_defn;
1643 hook->bp_sp = target.CreateBreakpoint(addr, true, false);
1644 hook->bp_sp->SetCallback(HookCallback, hook.get(), true);
1645 m_runtimeHooks[addr] = hook;
1647 log->Printf("%s - successfully hooked '%s' in '%s' version %" PRIu64
1648 " at 0x%" PRIx64 ".",
1649 __FUNCTION__, hook_defn->name,
1650 module->GetFileSpec().GetFilename().AsCString(),
1651 (uint64_t)hook_defn->version, (uint64_t)addr);
1653 hook_placed[idx] = true;
1656 // log any unhooked function
1658 for (size_t i = 0; i < hook_placed.size(); ++i) {
1661 const HookDefn &hook_defn = s_runtimeHookDefns[i];
1662 if (hook_defn.kind != kind)
1664 log->Printf("%s - function %s was not hooked", __FUNCTION__,
1670 void RenderScriptRuntime::FixupScriptDetails(RSModuleDescriptorSP rsmodule_sp) {
1674 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1676 const ModuleSP module = rsmodule_sp->m_module;
1677 const FileSpec &file = module->GetPlatformFileSpec();
1679 // Iterate over all of the scripts that we currently know of. Note: We cant
1680 // push or pop to m_scripts here or it may invalidate rs_script.
1681 for (const auto &rs_script : m_scripts) {
1682 // Extract the expected .so file path for this script.
1683 std::string shared_lib;
1684 if (!rs_script->shared_lib.get(shared_lib))
1687 // Only proceed if the module that has loaded corresponds to this script.
1688 if (file.GetFilename() != ConstString(shared_lib.c_str()))
1691 // Obtain the script address which we use as a key.
1692 lldb::addr_t script;
1693 if (!rs_script->script.get(script))
1696 // If we have a script mapping for the current script.
1697 if (m_scriptMappings.find(script) != m_scriptMappings.end()) {
1698 // if the module we have stored is different to the one we just received.
1699 if (m_scriptMappings[script] != rsmodule_sp) {
1702 "%s - script %" PRIx64 " wants reassigned to new rsmodule '%s'.",
1703 __FUNCTION__, (uint64_t)script,
1704 rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
1707 // We don't have a script mapping for the current script.
1709 // Obtain the script resource name.
1710 std::string res_name;
1711 if (rs_script->res_name.get(res_name))
1712 // Set the modules resource name.
1713 rsmodule_sp->m_resname = res_name;
1714 // Add Script/Module pair to map.
1715 m_scriptMappings[script] = rsmodule_sp;
1718 "%s - script %" PRIx64 " associated with rsmodule '%s'.",
1719 __FUNCTION__, (uint64_t)script,
1720 rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
1725 // Uses the Target API to evaluate the expression passed as a parameter to the
1726 // function The result of that expression is returned an unsigned 64 bit int,
1727 // via the result* parameter. Function returns true on success, and false on
1729 bool RenderScriptRuntime::EvalRSExpression(const char *expr,
1730 StackFrame *frame_ptr,
1732 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1734 log->Printf("%s(%s)", __FUNCTION__, expr);
1736 ValueObjectSP expr_result;
1737 EvaluateExpressionOptions options;
1738 options.SetLanguage(lldb::eLanguageTypeC_plus_plus);
1739 // Perform the actual expression evaluation
1740 auto &target = GetProcess()->GetTarget();
1741 target.EvaluateExpression(expr, frame_ptr, expr_result, options);
1745 log->Printf("%s: couldn't evaluate expression.", __FUNCTION__);
1749 // The result of the expression is invalid
1750 if (!expr_result->GetError().Success()) {
1751 Status err = expr_result->GetError();
1752 // Expression returned is void, so this is actually a success
1753 if (err.GetError() == UserExpression::kNoResult) {
1755 log->Printf("%s - expression returned void.", __FUNCTION__);
1762 log->Printf("%s - error evaluating expression result: %s", __FUNCTION__,
1767 bool success = false;
1768 // We only read the result as an uint32_t.
1769 *result = expr_result->GetValueAsUnsigned(0, &success);
1773 log->Printf("%s - couldn't convert expression result to uint32_t",
1782 // Used to index expression format strings
1783 enum ExpressionStrings {
1784 eExprGetOffsetPtr = 0,
1793 eExprElementFieldCount,
1795 eExprSubelementsName,
1796 eExprSubelementsArrSize,
1798 _eExprLast // keep at the end, implicit size of the array runtime_expressions
1801 // max length of an expanded expression
1802 const int jit_max_expr_size = 512;
1804 // Retrieve the string to JIT for the given expression
1805 #define JIT_TEMPLATE_CONTEXT "void* ctxt = (void*)rsDebugGetContextWrapper(0x%" PRIx64 "); "
1806 const char *JITTemplate(ExpressionStrings e) {
1807 // Format strings containing the expressions we may need to evaluate.
1808 static std::array<const char *, _eExprLast> runtime_expressions = {
1809 {// Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap)
1811 "Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocation"
1813 "(0x%" PRIx64 ", %" PRIu32 ", %" PRIu32 ", %" PRIu32 ", 0, 0)", // eExprGetOffsetPtr
1815 // Type* rsaAllocationGetType(Context*, Allocation*)
1816 JIT_TEMPLATE_CONTEXT "(void*)rsaAllocationGetType(ctxt, 0x%" PRIx64 ")", // eExprAllocGetType
1818 // rsaTypeGetNativeData(Context*, Type*, void* typeData, size) Pack the
1819 // data in the following way mHal.state.dimX; mHal.state.dimY;
1820 // mHal.state.dimZ; mHal.state.lodCount; mHal.state.faces; mElement;
1821 // into typeData Need to specify 32 or 64 bit for uint_t since this
1822 // differs between devices
1823 JIT_TEMPLATE_CONTEXT
1824 "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
1825 ", 0x%" PRIx64 ", data, 6); data[0]", // eExprTypeDimX
1826 JIT_TEMPLATE_CONTEXT
1827 "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
1828 ", 0x%" PRIx64 ", data, 6); data[1]", // eExprTypeDimY
1829 JIT_TEMPLATE_CONTEXT
1830 "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
1831 ", 0x%" PRIx64 ", data, 6); data[2]", // eExprTypeDimZ
1832 JIT_TEMPLATE_CONTEXT
1833 "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
1834 ", 0x%" PRIx64 ", data, 6); data[5]", // eExprTypeElemPtr
1836 // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size)
1837 // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into
1839 JIT_TEMPLATE_CONTEXT
1840 "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
1841 ", 0x%" PRIx64 ", data, 5); data[0]", // eExprElementType
1842 JIT_TEMPLATE_CONTEXT
1843 "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
1844 ", 0x%" PRIx64 ", data, 5); data[1]", // eExprElementKind
1845 JIT_TEMPLATE_CONTEXT
1846 "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
1847 ", 0x%" PRIx64 ", data, 5); data[3]", // eExprElementVec
1848 JIT_TEMPLATE_CONTEXT
1849 "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
1850 ", 0x%" PRIx64 ", data, 5); data[4]", // eExprElementFieldCount
1852 // rsaElementGetSubElements(RsContext con, RsElement elem, uintptr_t
1853 // *ids, const char **names, size_t *arraySizes, uint32_t dataSize)
1854 // Needed for Allocations of structs to gather details about
1855 // fields/Subelements Element* of field
1856 JIT_TEMPLATE_CONTEXT "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1857 "]; size_t arr_size[%" PRIu32 "];"
1858 "(void*)rsaElementGetSubElements(ctxt, 0x%" PRIx64
1859 ", ids, names, arr_size, %" PRIu32 "); ids[%" PRIu32 "]", // eExprSubelementsId
1862 JIT_TEMPLATE_CONTEXT "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1863 "]; size_t arr_size[%" PRIu32 "];"
1864 "(void*)rsaElementGetSubElements(ctxt, 0x%" PRIx64
1865 ", ids, names, arr_size, %" PRIu32 "); names[%" PRIu32 "]", // eExprSubelementsName
1867 // Array size of field
1868 JIT_TEMPLATE_CONTEXT "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1869 "]; size_t arr_size[%" PRIu32 "];"
1870 "(void*)rsaElementGetSubElements(ctxt, 0x%" PRIx64
1871 ", ids, names, arr_size, %" PRIu32 "); arr_size[%" PRIu32 "]"}}; // eExprSubelementsArrSize
1873 return runtime_expressions[e];
1875 } // end of the anonymous namespace
1877 // JITs the RS runtime for the internal data pointer of an allocation. Is
1878 // passed x,y,z coordinates for the pointer to a specific element. Then sets
1879 // the data_ptr member in Allocation with the result. Returns true on success,
1881 bool RenderScriptRuntime::JITDataPointer(AllocationDetails *alloc,
1882 StackFrame *frame_ptr, uint32_t x,
1883 uint32_t y, uint32_t z) {
1884 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1886 if (!alloc->address.isValid()) {
1888 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
1892 const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
1893 char expr_buf[jit_max_expr_size];
1895 int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
1896 *alloc->address.get(), x, y, z);
1899 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1901 } else if (written >= jit_max_expr_size) {
1903 log->Printf("%s - expression too long.", __FUNCTION__);
1907 uint64_t result = 0;
1908 if (!EvalRSExpression(expr_buf, frame_ptr, &result))
1911 addr_t data_ptr = static_cast<lldb::addr_t>(result);
1912 alloc->data_ptr = data_ptr;
1917 // JITs the RS runtime for the internal pointer to the RS Type of an allocation
1918 // Then sets the type_ptr member in Allocation with the result. Returns true on
1919 // success, false otherwise
1920 bool RenderScriptRuntime::JITTypePointer(AllocationDetails *alloc,
1921 StackFrame *frame_ptr) {
1922 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1924 if (!alloc->address.isValid() || !alloc->context.isValid()) {
1926 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
1930 const char *fmt_str = JITTemplate(eExprAllocGetType);
1931 char expr_buf[jit_max_expr_size];
1933 int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
1934 *alloc->context.get(), *alloc->address.get());
1937 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1939 } else if (written >= jit_max_expr_size) {
1941 log->Printf("%s - expression too long.", __FUNCTION__);
1945 uint64_t result = 0;
1946 if (!EvalRSExpression(expr_buf, frame_ptr, &result))
1949 addr_t type_ptr = static_cast<lldb::addr_t>(result);
1950 alloc->type_ptr = type_ptr;
1955 // JITs the RS runtime for information about the dimensions and type of an
1956 // allocation Then sets dimension and element_ptr members in Allocation with
1957 // the result. Returns true on success, false otherwise
1958 bool RenderScriptRuntime::JITTypePacked(AllocationDetails *alloc,
1959 StackFrame *frame_ptr) {
1960 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1962 if (!alloc->type_ptr.isValid() || !alloc->context.isValid()) {
1964 log->Printf("%s - Failed to find allocation details.", __FUNCTION__);
1968 // Expression is different depending on if device is 32 or 64 bit
1969 uint32_t target_ptr_size =
1970 GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
1971 const uint32_t bits = target_ptr_size == 4 ? 32 : 64;
1973 // We want 4 elements from packed data
1974 const uint32_t num_exprs = 4;
1975 static_assert(num_exprs == (eExprTypeElemPtr - eExprTypeDimX + 1),
1976 "Invalid number of expressions");
1978 char expr_bufs[num_exprs][jit_max_expr_size];
1979 uint64_t results[num_exprs];
1981 for (uint32_t i = 0; i < num_exprs; ++i) {
1982 const char *fmt_str = JITTemplate(ExpressionStrings(eExprTypeDimX + i));
1983 int written = snprintf(expr_bufs[i], jit_max_expr_size, fmt_str,
1984 *alloc->context.get(), bits, *alloc->type_ptr.get());
1987 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1989 } else if (written >= jit_max_expr_size) {
1991 log->Printf("%s - expression too long.", __FUNCTION__);
1995 // Perform expression evaluation
1996 if (!EvalRSExpression(expr_bufs[i], frame_ptr, &results[i]))
2000 // Assign results to allocation members
2001 AllocationDetails::Dimension dims;
2002 dims.dim_1 = static_cast<uint32_t>(results[0]);
2003 dims.dim_2 = static_cast<uint32_t>(results[1]);
2004 dims.dim_3 = static_cast<uint32_t>(results[2]);
2005 alloc->dimension = dims;
2007 addr_t element_ptr = static_cast<lldb::addr_t>(results[3]);
2008 alloc->element.element_ptr = element_ptr;
2011 log->Printf("%s - dims (%" PRIu32 ", %" PRIu32 ", %" PRIu32
2012 ") Element*: 0x%" PRIx64 ".",
2013 __FUNCTION__, dims.dim_1, dims.dim_2, dims.dim_3, element_ptr);
2018 // JITs the RS runtime for information about the Element of an allocation Then
2019 // sets type, type_vec_size, field_count and type_kind members in Element with
2020 // the result. Returns true on success, false otherwise
2021 bool RenderScriptRuntime::JITElementPacked(Element &elem,
2022 const lldb::addr_t context,
2023 StackFrame *frame_ptr) {
2024 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2026 if (!elem.element_ptr.isValid()) {
2028 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
2032 // We want 4 elements from packed data
2033 const uint32_t num_exprs = 4;
2034 static_assert(num_exprs == (eExprElementFieldCount - eExprElementType + 1),
2035 "Invalid number of expressions");
2037 char expr_bufs[num_exprs][jit_max_expr_size];
2038 uint64_t results[num_exprs];
2040 for (uint32_t i = 0; i < num_exprs; i++) {
2041 const char *fmt_str = JITTemplate(ExpressionStrings(eExprElementType + i));
2042 int written = snprintf(expr_bufs[i], jit_max_expr_size, fmt_str, context,
2043 *elem.element_ptr.get());
2046 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
2048 } else if (written >= jit_max_expr_size) {
2050 log->Printf("%s - expression too long.", __FUNCTION__);
2054 // Perform expression evaluation
2055 if (!EvalRSExpression(expr_bufs[i], frame_ptr, &results[i]))
2059 // Assign results to allocation members
2060 elem.type = static_cast<RenderScriptRuntime::Element::DataType>(results[0]);
2062 static_cast<RenderScriptRuntime::Element::DataKind>(results[1]);
2063 elem.type_vec_size = static_cast<uint32_t>(results[2]);
2064 elem.field_count = static_cast<uint32_t>(results[3]);
2067 log->Printf("%s - data type %" PRIu32 ", pixel type %" PRIu32
2068 ", vector size %" PRIu32 ", field count %" PRIu32,
2069 __FUNCTION__, *elem.type.get(), *elem.type_kind.get(),
2070 *elem.type_vec_size.get(), *elem.field_count.get());
2072 // If this Element has subelements then JIT rsaElementGetSubElements() for
2073 // details about its fields
2074 return !(*elem.field_count.get() > 0 &&
2075 !JITSubelements(elem, context, frame_ptr));
2078 // JITs the RS runtime for information about the subelements/fields of a struct
2079 // allocation This is necessary for infering the struct type so we can pretty
2080 // print the allocation's contents. Returns true on success, false otherwise
2081 bool RenderScriptRuntime::JITSubelements(Element &elem,
2082 const lldb::addr_t context,
2083 StackFrame *frame_ptr) {
2084 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2086 if (!elem.element_ptr.isValid() || !elem.field_count.isValid()) {
2088 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
2092 const short num_exprs = 3;
2093 static_assert(num_exprs == (eExprSubelementsArrSize - eExprSubelementsId + 1),
2094 "Invalid number of expressions");
2096 char expr_buffer[jit_max_expr_size];
2099 // Iterate over struct fields.
2100 const uint32_t field_count = *elem.field_count.get();
2101 for (uint32_t field_index = 0; field_index < field_count; ++field_index) {
2103 for (uint32_t expr_index = 0; expr_index < num_exprs; ++expr_index) {
2104 const char *fmt_str =
2105 JITTemplate(ExpressionStrings(eExprSubelementsId + expr_index));
2106 int written = snprintf(expr_buffer, jit_max_expr_size, fmt_str,
2107 context, field_count, field_count, field_count,
2108 *elem.element_ptr.get(), field_count, field_index);
2111 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
2113 } else if (written >= jit_max_expr_size) {
2115 log->Printf("%s - expression too long.", __FUNCTION__);
2119 // Perform expression evaluation
2120 if (!EvalRSExpression(expr_buffer, frame_ptr, &results))
2124 log->Printf("%s - expr result 0x%" PRIx64 ".", __FUNCTION__, results);
2126 switch (expr_index) {
2127 case 0: // Element* of child
2128 child.element_ptr = static_cast<addr_t>(results);
2130 case 1: // Name of child
2132 lldb::addr_t address = static_cast<addr_t>(results);
2135 GetProcess()->ReadCStringFromMemory(address, name, err);
2137 child.type_name = ConstString(name);
2140 log->Printf("%s - warning: Couldn't read field name.",
2145 case 2: // Array size of child
2146 child.array_size = static_cast<uint32_t>(results);
2151 // We need to recursively JIT each Element field of the struct since
2152 // structs can be nested inside structs.
2153 if (!JITElementPacked(child, context, frame_ptr))
2155 elem.children.push_back(child);
2158 // Try to infer the name of the struct type so we can pretty print the
2159 // allocation contents.
2160 FindStructTypeName(elem, frame_ptr);
2165 // JITs the RS runtime for the address of the last element in the allocation.
2166 // The `elem_size` parameter represents the size of a single element, including
2167 // padding. Which is needed as an offset from the last element pointer. Using
2168 // this offset minus the starting address we can calculate the size of the
2169 // allocation. Returns true on success, false otherwise
2170 bool RenderScriptRuntime::JITAllocationSize(AllocationDetails *alloc,
2171 StackFrame *frame_ptr) {
2172 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2174 if (!alloc->address.isValid() || !alloc->dimension.isValid() ||
2175 !alloc->data_ptr.isValid() || !alloc->element.datum_size.isValid()) {
2177 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
2182 uint32_t dim_x = alloc->dimension.get()->dim_1;
2183 uint32_t dim_y = alloc->dimension.get()->dim_2;
2184 uint32_t dim_z = alloc->dimension.get()->dim_3;
2186 // Our plan of jitting the last element address doesn't seem to work for
2187 // struct Allocations` Instead try to infer the size ourselves without any
2188 // inter element padding.
2189 if (alloc->element.children.size() > 0) {
2197 alloc->size = dim_x * dim_y * dim_z * *alloc->element.datum_size.get();
2200 log->Printf("%s - inferred size of struct allocation %" PRIu32 ".",
2201 __FUNCTION__, *alloc->size.get());
2205 const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
2206 char expr_buf[jit_max_expr_size];
2208 // Calculate last element
2209 dim_x = dim_x == 0 ? 0 : dim_x - 1;
2210 dim_y = dim_y == 0 ? 0 : dim_y - 1;
2211 dim_z = dim_z == 0 ? 0 : dim_z - 1;
2213 int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
2214 *alloc->address.get(), dim_x, dim_y, dim_z);
2217 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
2219 } else if (written >= jit_max_expr_size) {
2221 log->Printf("%s - expression too long.", __FUNCTION__);
2225 uint64_t result = 0;
2226 if (!EvalRSExpression(expr_buf, frame_ptr, &result))
2229 addr_t mem_ptr = static_cast<lldb::addr_t>(result);
2230 // Find pointer to last element and add on size of an element
2231 alloc->size = static_cast<uint32_t>(mem_ptr - *alloc->data_ptr.get()) +
2232 *alloc->element.datum_size.get();
2237 // JITs the RS runtime for information about the stride between rows in the
2238 // allocation. This is done to detect padding, since allocated memory is
2239 // 16-byte aligned. Returns true on success, false otherwise
2240 bool RenderScriptRuntime::JITAllocationStride(AllocationDetails *alloc,
2241 StackFrame *frame_ptr) {
2242 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2244 if (!alloc->address.isValid() || !alloc->data_ptr.isValid()) {
2246 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
2250 const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
2251 char expr_buf[jit_max_expr_size];
2253 int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
2254 *alloc->address.get(), 0, 1, 0);
2257 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
2259 } else if (written >= jit_max_expr_size) {
2261 log->Printf("%s - expression too long.", __FUNCTION__);
2265 uint64_t result = 0;
2266 if (!EvalRSExpression(expr_buf, frame_ptr, &result))
2269 addr_t mem_ptr = static_cast<lldb::addr_t>(result);
2270 alloc->stride = static_cast<uint32_t>(mem_ptr - *alloc->data_ptr.get());
2275 // JIT all the current runtime info regarding an allocation
2276 bool RenderScriptRuntime::RefreshAllocation(AllocationDetails *alloc,
2277 StackFrame *frame_ptr) {
2278 // GetOffsetPointer()
2279 if (!JITDataPointer(alloc, frame_ptr))
2282 // rsaAllocationGetType()
2283 if (!JITTypePointer(alloc, frame_ptr))
2286 // rsaTypeGetNativeData()
2287 if (!JITTypePacked(alloc, frame_ptr))
2290 // rsaElementGetNativeData()
2291 if (!JITElementPacked(alloc->element, *alloc->context.get(), frame_ptr))
2294 // Sets the datum_size member in Element
2295 SetElementSize(alloc->element);
2297 // Use GetOffsetPointer() to infer size of the allocation
2298 return JITAllocationSize(alloc, frame_ptr);
2301 // Function attempts to set the type_name member of the paramaterised Element
2302 // object. This string should be the name of the struct type the Element
2303 // represents. We need this string for pretty printing the Element to users.
2304 void RenderScriptRuntime::FindStructTypeName(Element &elem,
2305 StackFrame *frame_ptr) {
2306 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2308 if (!elem.type_name.IsEmpty()) // Name already set
2311 elem.type_name = Element::GetFallbackStructName(); // Default type name if
2314 // Find all the global variables from the script rs modules
2315 VariableList var_list;
2316 for (auto module_sp : m_rsmodules)
2317 module_sp->m_module->FindGlobalVariables(
2318 RegularExpression(llvm::StringRef(".")), UINT32_MAX, var_list);
2320 // Iterate over all the global variables looking for one with a matching type
2321 // to the Element. We make the assumption a match exists since there needs to
2322 // be a global variable to reflect the struct type back into java host code.
2323 for (uint32_t i = 0; i < var_list.GetSize(); ++i) {
2324 const VariableSP var_sp(var_list.GetVariableAtIndex(i));
2328 ValueObjectSP valobj_sp = ValueObjectVariable::Create(frame_ptr, var_sp);
2332 // Find the number of variable fields.
2333 // If it has no fields, or more fields than our Element, then it can't be
2334 // the struct we're looking for. Don't check for equality since RS can add
2335 // extra struct members for padding.
2336 size_t num_children = valobj_sp->GetNumChildren();
2337 if (num_children > elem.children.size() || num_children == 0)
2340 // Iterate over children looking for members with matching field names. If
2341 // all the field names match, this is likely the struct we want.
2342 // TODO: This could be made more robust by also checking children data
2343 // sizes, or array size
2345 for (size_t i = 0; i < num_children; ++i) {
2346 ValueObjectSP child = valobj_sp->GetChildAtIndex(i, true);
2347 if (!child || (child->GetName() != elem.children[i].type_name)) {
2353 // RS can add extra struct members for padding in the format
2354 // '#rs_padding_[0-9]+'
2355 if (found && num_children < elem.children.size()) {
2356 const uint32_t size_diff = elem.children.size() - num_children;
2358 log->Printf("%s - %" PRIu32 " padding struct entries", __FUNCTION__,
2361 for (uint32_t i = 0; i < size_diff; ++i) {
2362 ConstString name = elem.children[num_children + i].type_name;
2363 if (strcmp(name.AsCString(), "#rs_padding") < 0)
2368 // We've found a global variable with matching type
2370 // Dereference since our Element type isn't a pointer.
2371 if (valobj_sp->IsPointerType()) {
2373 ValueObjectSP deref_valobj = valobj_sp->Dereference(err);
2375 valobj_sp = deref_valobj;
2378 // Save name of variable in Element.
2379 elem.type_name = valobj_sp->GetTypeName();
2381 log->Printf("%s - element name set to %s", __FUNCTION__,
2382 elem.type_name.AsCString());
2389 // Function sets the datum_size member of Element. Representing the size of a
2390 // single instance including padding. Assumes the relevant allocation
2391 // information has already been jitted.
2392 void RenderScriptRuntime::SetElementSize(Element &elem) {
2393 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2394 const Element::DataType type = *elem.type.get();
2395 assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
2396 "Invalid allocation type");
2398 const uint32_t vec_size = *elem.type_vec_size.get();
2399 uint32_t data_size = 0;
2400 uint32_t padding = 0;
2402 // Element is of a struct type, calculate size recursively.
2403 if ((type == Element::RS_TYPE_NONE) && (elem.children.size() > 0)) {
2404 for (Element &child : elem.children) {
2405 SetElementSize(child);
2406 const uint32_t array_size =
2407 child.array_size.isValid() ? *child.array_size.get() : 1;
2408 data_size += *child.datum_size.get() * array_size;
2411 // These have been packed already
2412 else if (type == Element::RS_TYPE_UNSIGNED_5_6_5 ||
2413 type == Element::RS_TYPE_UNSIGNED_5_5_5_1 ||
2414 type == Element::RS_TYPE_UNSIGNED_4_4_4_4) {
2415 data_size = AllocationDetails::RSTypeToFormat[type][eElementSize];
2416 } else if (type < Element::RS_TYPE_ELEMENT) {
2418 vec_size * AllocationDetails::RSTypeToFormat[type][eElementSize];
2420 padding = AllocationDetails::RSTypeToFormat[type][eElementSize];
2423 GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
2425 elem.padding = padding;
2426 elem.datum_size = data_size + padding;
2428 log->Printf("%s - element size set to %" PRIu32, __FUNCTION__,
2429 data_size + padding);
2432 // Given an allocation, this function copies the allocation contents from
2433 // device into a buffer on the heap. Returning a shared pointer to the buffer
2434 // containing the data.
2435 std::shared_ptr<uint8_t>
2436 RenderScriptRuntime::GetAllocationData(AllocationDetails *alloc,
2437 StackFrame *frame_ptr) {
2438 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2440 // JIT all the allocation details
2441 if (alloc->ShouldRefresh()) {
2443 log->Printf("%s - allocation details not calculated yet, jitting info",
2446 if (!RefreshAllocation(alloc, frame_ptr)) {
2448 log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
2453 assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2454 alloc->element.type_vec_size.isValid() && alloc->size.isValid() &&
2455 "Allocation information not available");
2457 // Allocate a buffer to copy data into
2458 const uint32_t size = *alloc->size.get();
2459 std::shared_ptr<uint8_t> buffer(new uint8_t[size]);
2462 log->Printf("%s - couldn't allocate a %" PRIu32 " byte buffer",
2463 __FUNCTION__, size);
2467 // Read the inferior memory
2469 lldb::addr_t data_ptr = *alloc->data_ptr.get();
2470 GetProcess()->ReadMemory(data_ptr, buffer.get(), size, err);
2473 log->Printf("%s - '%s' Couldn't read %" PRIu32
2474 " bytes of allocation data from 0x%" PRIx64,
2475 __FUNCTION__, err.AsCString(), size, data_ptr);
2482 // Function copies data from a binary file into an allocation. There is a
2483 // header at the start of the file, FileHeader, before the data content itself.
2484 // Information from this header is used to display warnings to the user about
2485 // incompatibilities
2486 bool RenderScriptRuntime::LoadAllocation(Stream &strm, const uint32_t alloc_id,
2488 StackFrame *frame_ptr) {
2489 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2491 // Find allocation with the given id
2492 AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
2497 log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__,
2498 *alloc->address.get());
2500 // JIT all the allocation details
2501 if (alloc->ShouldRefresh()) {
2503 log->Printf("%s - allocation details not calculated yet, jitting info.",
2506 if (!RefreshAllocation(alloc, frame_ptr)) {
2508 log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
2513 assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2514 alloc->element.type_vec_size.isValid() && alloc->size.isValid() &&
2515 alloc->element.datum_size.isValid() &&
2516 "Allocation information not available");
2518 // Check we can read from file
2519 FileSpec file(path);
2520 FileSystem::Instance().Resolve(file);
2521 if (!FileSystem::Instance().Exists(file)) {
2522 strm.Printf("Error: File %s does not exist", path);
2527 if (!FileSystem::Instance().Readable(file)) {
2528 strm.Printf("Error: File %s does not have readable permissions", path);
2533 // Read file into data buffer
2534 auto data_sp = FileSystem::Instance().CreateDataBuffer(file.GetPath());
2536 // Cast start of buffer to FileHeader and use pointer to read metadata
2537 void *file_buf = data_sp->GetBytes();
2538 if (file_buf == nullptr ||
2539 data_sp->GetByteSize() < (sizeof(AllocationDetails::FileHeader) +
2540 sizeof(AllocationDetails::ElementHeader))) {
2541 strm.Printf("Error: File %s does not contain enough data for header", path);
2545 const AllocationDetails::FileHeader *file_header =
2546 static_cast<AllocationDetails::FileHeader *>(file_buf);
2548 // Check file starts with ascii characters "RSAD"
2549 if (memcmp(file_header->ident, "RSAD", 4)) {
2550 strm.Printf("Error: File doesn't contain identifier for an RS allocation "
2551 "dump. Are you sure this is the correct file?");
2556 // Look at the type of the root element in the header
2557 AllocationDetails::ElementHeader root_el_hdr;
2558 memcpy(&root_el_hdr, static_cast<uint8_t *>(file_buf) +
2559 sizeof(AllocationDetails::FileHeader),
2560 sizeof(AllocationDetails::ElementHeader));
2563 log->Printf("%s - header type %" PRIu32 ", element size %" PRIu32,
2564 __FUNCTION__, root_el_hdr.type, root_el_hdr.element_size);
2566 // Check if the target allocation and file both have the same number of bytes
2568 if (*alloc->element.datum_size.get() != root_el_hdr.element_size) {
2569 strm.Printf("Warning: Mismatched Element sizes - file %" PRIu32
2570 " bytes, allocation %" PRIu32 " bytes",
2571 root_el_hdr.element_size, *alloc->element.datum_size.get());
2575 // Check if the target allocation and file both have the same type
2576 const uint32_t alloc_type = static_cast<uint32_t>(*alloc->element.type.get());
2577 const uint32_t file_type = root_el_hdr.type;
2579 if (file_type > Element::RS_TYPE_FONT) {
2580 strm.Printf("Warning: File has unknown allocation type");
2582 } else if (alloc_type != file_type) {
2583 // Enum value isn't monotonous, so doesn't always index RsDataTypeToString
2585 uint32_t target_type_name_idx = alloc_type;
2586 uint32_t head_type_name_idx = file_type;
2587 if (alloc_type >= Element::RS_TYPE_ELEMENT &&
2588 alloc_type <= Element::RS_TYPE_FONT)
2589 target_type_name_idx = static_cast<Element::DataType>(
2590 (alloc_type - Element::RS_TYPE_ELEMENT) +
2591 Element::RS_TYPE_MATRIX_2X2 + 1);
2593 if (file_type >= Element::RS_TYPE_ELEMENT &&
2594 file_type <= Element::RS_TYPE_FONT)
2595 head_type_name_idx = static_cast<Element::DataType>(
2596 (file_type - Element::RS_TYPE_ELEMENT) + Element::RS_TYPE_MATRIX_2X2 +
2599 const char *head_type_name =
2600 AllocationDetails::RsDataTypeToString[head_type_name_idx][0];
2601 const char *target_type_name =
2602 AllocationDetails::RsDataTypeToString[target_type_name_idx][0];
2605 "Warning: Mismatched Types - file '%s' type, allocation '%s' type",
2606 head_type_name, target_type_name);
2610 // Advance buffer past header
2611 file_buf = static_cast<uint8_t *>(file_buf) + file_header->hdr_size;
2613 // Calculate size of allocation data in file
2614 size_t size = data_sp->GetByteSize() - file_header->hdr_size;
2616 // Check if the target allocation and file both have the same total data
2618 const uint32_t alloc_size = *alloc->size.get();
2619 if (alloc_size != size) {
2620 strm.Printf("Warning: Mismatched allocation sizes - file 0x%" PRIx64
2621 " bytes, allocation 0x%" PRIx32 " bytes",
2622 (uint64_t)size, alloc_size);
2624 // Set length to copy to minimum
2625 size = alloc_size < size ? alloc_size : size;
2628 // Copy file data from our buffer into the target allocation.
2629 lldb::addr_t alloc_data = *alloc->data_ptr.get();
2631 size_t written = GetProcess()->WriteMemory(alloc_data, file_buf, size, err);
2632 if (!err.Success() || written != size) {
2633 strm.Printf("Error: Couldn't write data to allocation %s", err.AsCString());
2638 strm.Printf("Contents of file '%s' read into allocation %" PRIu32, path,
2645 // Function takes as parameters a byte buffer, which will eventually be written
2646 // to file as the element header, an offset into that buffer, and an Element
2647 // that will be saved into the buffer at the parametrised offset. Return value
2648 // is the new offset after writing the element into the buffer. Elements are
2649 // saved to the file as the ElementHeader struct followed by offsets to the
2650 // structs of all the element's children.
2651 size_t RenderScriptRuntime::PopulateElementHeaders(
2652 const std::shared_ptr<uint8_t> header_buffer, size_t offset,
2653 const Element &elem) {
2654 // File struct for an element header with all the relevant details copied
2655 // from elem. We assume members are valid already.
2656 AllocationDetails::ElementHeader elem_header;
2657 elem_header.type = *elem.type.get();
2658 elem_header.kind = *elem.type_kind.get();
2659 elem_header.element_size = *elem.datum_size.get();
2660 elem_header.vector_size = *elem.type_vec_size.get();
2661 elem_header.array_size =
2662 elem.array_size.isValid() ? *elem.array_size.get() : 0;
2663 const size_t elem_header_size = sizeof(AllocationDetails::ElementHeader);
2665 // Copy struct into buffer and advance offset We assume that header_buffer
2666 // has been checked for nullptr before this method is called
2667 memcpy(header_buffer.get() + offset, &elem_header, elem_header_size);
2668 offset += elem_header_size;
2670 // Starting offset of child ElementHeader struct
2671 size_t child_offset =
2672 offset + ((elem.children.size() + 1) * sizeof(uint32_t));
2673 for (const RenderScriptRuntime::Element &child : elem.children) {
2674 // Recursively populate the buffer with the element header structs of
2675 // children. Then save the offsets where they were set after the parent
2677 memcpy(header_buffer.get() + offset, &child_offset, sizeof(uint32_t));
2678 offset += sizeof(uint32_t);
2680 child_offset = PopulateElementHeaders(header_buffer, child_offset, child);
2683 // Zero indicates no more children
2684 memset(header_buffer.get() + offset, 0, sizeof(uint32_t));
2686 return child_offset;
2689 // Given an Element object this function returns the total size needed in the
2690 // file header to store the element's details. Taking into account the size of
2691 // the element header struct, plus the offsets to all the element's children.
2692 // Function is recursive so that the size of all ancestors is taken into
2694 size_t RenderScriptRuntime::CalculateElementHeaderSize(const Element &elem) {
2695 // Offsets to children plus zero terminator
2696 size_t size = (elem.children.size() + 1) * sizeof(uint32_t);
2697 // Size of header struct with type details
2698 size += sizeof(AllocationDetails::ElementHeader);
2700 // Calculate recursively for all descendants
2701 for (const Element &child : elem.children)
2702 size += CalculateElementHeaderSize(child);
2707 // Function copies allocation contents into a binary file. This file can then
2708 // be loaded later into a different allocation. There is a header, FileHeader,
2709 // before the allocation data containing meta-data.
2710 bool RenderScriptRuntime::SaveAllocation(Stream &strm, const uint32_t alloc_id,
2712 StackFrame *frame_ptr) {
2713 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2715 // Find allocation with the given id
2716 AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
2721 log->Printf("%s - found allocation 0x%" PRIx64 ".", __FUNCTION__,
2722 *alloc->address.get());
2724 // JIT all the allocation details
2725 if (alloc->ShouldRefresh()) {
2727 log->Printf("%s - allocation details not calculated yet, jitting info.",
2730 if (!RefreshAllocation(alloc, frame_ptr)) {
2732 log->Printf("%s - couldn't JIT allocation details.", __FUNCTION__);
2737 assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2738 alloc->element.type_vec_size.isValid() &&
2739 alloc->element.datum_size.get() &&
2740 alloc->element.type_kind.isValid() && alloc->dimension.isValid() &&
2741 "Allocation information not available");
2743 // Check we can create writable file
2744 FileSpec file_spec(path);
2745 FileSystem::Instance().Resolve(file_spec);
2747 FileSystem::Instance().Open(file, file_spec,
2748 File::eOpenOptionWrite |
2749 File::eOpenOptionCanCreate |
2750 File::eOpenOptionTruncate);
2753 strm.Printf("Error: Failed to open '%s' for writing", path);
2758 // Read allocation into buffer of heap memory
2759 const std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
2761 strm.Printf("Error: Couldn't read allocation data into buffer");
2766 // Create the file header
2767 AllocationDetails::FileHeader head;
2768 memcpy(head.ident, "RSAD", 4);
2769 head.dims[0] = static_cast<uint32_t>(alloc->dimension.get()->dim_1);
2770 head.dims[1] = static_cast<uint32_t>(alloc->dimension.get()->dim_2);
2771 head.dims[2] = static_cast<uint32_t>(alloc->dimension.get()->dim_3);
2773 const size_t element_header_size = CalculateElementHeaderSize(alloc->element);
2774 assert((sizeof(AllocationDetails::FileHeader) + element_header_size) <
2776 "Element header too large");
2777 head.hdr_size = static_cast<uint16_t>(sizeof(AllocationDetails::FileHeader) +
2778 element_header_size);
2780 // Write the file header
2781 size_t num_bytes = sizeof(AllocationDetails::FileHeader);
2783 log->Printf("%s - writing File Header, 0x%" PRIx64 " bytes", __FUNCTION__,
2784 (uint64_t)num_bytes);
2786 Status err = file.Write(&head, num_bytes);
2787 if (!err.Success()) {
2788 strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
2793 // Create the headers describing the element type of the allocation.
2794 std::shared_ptr<uint8_t> element_header_buffer(
2795 new uint8_t[element_header_size]);
2796 if (element_header_buffer == nullptr) {
2797 strm.Printf("Internal Error: Couldn't allocate %" PRIu64
2798 " bytes on the heap",
2799 (uint64_t)element_header_size);
2804 PopulateElementHeaders(element_header_buffer, 0, alloc->element);
2806 // Write headers for allocation element type to file
2807 num_bytes = element_header_size;
2809 log->Printf("%s - writing element headers, 0x%" PRIx64 " bytes.",
2810 __FUNCTION__, (uint64_t)num_bytes);
2812 err = file.Write(element_header_buffer.get(), num_bytes);
2813 if (!err.Success()) {
2814 strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
2819 // Write allocation data to file
2820 num_bytes = static_cast<size_t>(*alloc->size.get());
2822 log->Printf("%s - writing 0x%" PRIx64 " bytes", __FUNCTION__,
2823 (uint64_t)num_bytes);
2825 err = file.Write(buffer.get(), num_bytes);
2826 if (!err.Success()) {
2827 strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
2832 strm.Printf("Allocation written to file '%s'", path);
2837 bool RenderScriptRuntime::LoadModule(const lldb::ModuleSP &module_sp) {
2838 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2841 for (const auto &rs_module : m_rsmodules) {
2842 if (rs_module->m_module == module_sp) {
2843 // Check if the user has enabled automatically breaking on all RS
2845 if (m_breakAllKernels)
2846 BreakOnModuleKernels(rs_module);
2851 bool module_loaded = false;
2852 switch (GetModuleKind(module_sp)) {
2853 case eModuleKindKernelObj: {
2854 RSModuleDescriptorSP module_desc;
2855 module_desc = std::make_shared<RSModuleDescriptor>(module_sp);
2856 if (module_desc->ParseRSInfo()) {
2857 m_rsmodules.push_back(module_desc);
2858 module_desc->WarnIfVersionMismatch(GetProcess()
2861 .GetAsyncOutputStream()
2863 module_loaded = true;
2865 if (module_loaded) {
2866 FixupScriptDetails(module_desc);
2870 case eModuleKindDriver: {
2871 if (!m_libRSDriver) {
2872 m_libRSDriver = module_sp;
2873 LoadRuntimeHooks(m_libRSDriver, RenderScriptRuntime::eModuleKindDriver);
2877 case eModuleKindImpl: {
2878 if (!m_libRSCpuRef) {
2879 m_libRSCpuRef = module_sp;
2880 LoadRuntimeHooks(m_libRSCpuRef, RenderScriptRuntime::eModuleKindImpl);
2884 case eModuleKindLibRS: {
2886 m_libRS = module_sp;
2887 static ConstString gDbgPresentStr("gDebuggerPresent");
2888 const Symbol *debug_present = m_libRS->FindFirstSymbolWithNameAndType(
2889 gDbgPresentStr, eSymbolTypeData);
2890 if (debug_present) {
2892 uint32_t flag = 0x00000001U;
2893 Target &target = GetProcess()->GetTarget();
2894 addr_t addr = debug_present->GetLoadAddress(&target);
2895 GetProcess()->WriteMemory(addr, &flag, sizeof(flag), err);
2896 if (err.Success()) {
2898 log->Printf("%s - debugger present flag set on debugee.",
2901 m_debuggerPresentFlagged = true;
2903 log->Printf("%s - error writing debugger present flags '%s' ",
2904 __FUNCTION__, err.AsCString());
2908 "%s - error writing debugger present flags - symbol not found",
2919 return module_loaded;
2924 void RenderScriptRuntime::Update() {
2925 if (m_rsmodules.size() > 0) {
2932 void RSModuleDescriptor::WarnIfVersionMismatch(lldb_private::Stream *s) const {
2936 if (m_slang_version.empty() || m_bcc_version.empty()) {
2937 s->PutCString("WARNING: Unknown bcc or slang (llvm-rs-cc) version; debug "
2938 "experience may be unreliable");
2940 } else if (m_slang_version != m_bcc_version) {
2941 s->Printf("WARNING: The debug info emitted by the slang frontend "
2942 "(llvm-rs-cc) used to build this module (%s) does not match the "
2943 "version of bcc used to generate the debug information (%s). "
2944 "This is an unsupported configuration and may result in a poor "
2945 "debugging experience; proceed with caution",
2946 m_slang_version.c_str(), m_bcc_version.c_str());
2951 bool RSModuleDescriptor::ParsePragmaCount(llvm::StringRef *lines,
2953 // Skip the pragma prototype line
2955 for (; n_lines--; ++lines) {
2956 const auto kv_pair = lines->split(" - ");
2957 m_pragmas[kv_pair.first.trim().str()] = kv_pair.second.trim().str();
2962 bool RSModuleDescriptor::ParseExportReduceCount(llvm::StringRef *lines,
2964 // The list of reduction kernels in the `.rs.info` symbol is of the form
2965 // "signature - accumulatordatasize - reduction_name - initializer_name -
2966 // accumulator_name - combiner_name - outconverter_name - halter_name" Where
2967 // a function is not explicitly named by the user, or is not generated by the
2968 // compiler, it is named "." so the dash separated list should always be 8
2970 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
2971 // Skip the exportReduceCount line
2973 for (; n_lines--; ++lines) {
2974 llvm::SmallVector<llvm::StringRef, 8> spec;
2975 lines->split(spec, " - ");
2976 if (spec.size() != 8) {
2977 if (spec.size() < 8) {
2979 log->Error("Error parsing RenderScript reduction spec. wrong number "
2983 log->Warning("Extraneous members in reduction spec: '%s'",
2984 lines->str().c_str());
2987 const auto sig_s = spec[0];
2989 if (sig_s.getAsInteger(10, sig)) {
2991 log->Error("Error parsing Renderscript reduction spec: invalid kernel "
2993 sig_s.str().c_str());
2997 const auto accum_data_size_s = spec[1];
2998 uint32_t accum_data_size;
2999 if (accum_data_size_s.getAsInteger(10, accum_data_size)) {
3001 log->Error("Error parsing Renderscript reduction spec: invalid "
3002 "accumulator data size %s",
3003 accum_data_size_s.str().c_str());
3008 log->Printf("Found RenderScript reduction '%s'", spec[2].str().c_str());
3010 m_reductions.push_back(RSReductionDescriptor(this, sig, accum_data_size,
3011 spec[2], spec[3], spec[4],
3012 spec[5], spec[6], spec[7]));
3017 bool RSModuleDescriptor::ParseVersionInfo(llvm::StringRef *lines,
3019 // Skip the versionInfo line
3021 for (; n_lines--; ++lines) {
3022 // We're only interested in bcc and slang versions, and ignore all other
3023 // versionInfo lines
3024 const auto kv_pair = lines->split(" - ");
3025 if (kv_pair.first == "slang")
3026 m_slang_version = kv_pair.second.str();
3027 else if (kv_pair.first == "bcc")
3028 m_bcc_version = kv_pair.second.str();
3033 bool RSModuleDescriptor::ParseExportForeachCount(llvm::StringRef *lines,
3035 // Skip the exportForeachCount line
3037 for (; n_lines--; ++lines) {
3039 // `forEach` kernels are listed in the `.rs.info` packet as a "slot - name"
3041 const auto kv_pair = lines->split(" - ");
3042 if (kv_pair.first.getAsInteger(10, slot))
3044 m_kernels.push_back(RSKernelDescriptor(this, kv_pair.second, slot));
3049 bool RSModuleDescriptor::ParseExportVarCount(llvm::StringRef *lines,
3051 // Skip the ExportVarCount line
3053 for (; n_lines--; ++lines)
3054 m_globals.push_back(RSGlobalDescriptor(this, *lines));
3058 // The .rs.info symbol in renderscript modules contains a string which needs to
3059 // be parsed. The string is basic and is parsed on a line by line basis.
3060 bool RSModuleDescriptor::ParseRSInfo() {
3062 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3063 const Symbol *info_sym = m_module->FindFirstSymbolWithNameAndType(
3064 ConstString(".rs.info"), eSymbolTypeData);
3068 const addr_t addr = info_sym->GetAddressRef().GetFileAddress();
3069 if (addr == LLDB_INVALID_ADDRESS)
3072 const addr_t size = info_sym->GetByteSize();
3073 const FileSpec fs = m_module->GetFileSpec();
3076 FileSystem::Instance().CreateDataBuffer(fs.GetPath(), size, addr);
3080 // split rs.info. contents into lines
3081 llvm::SmallVector<llvm::StringRef, 128> info_lines;
3083 const llvm::StringRef raw_rs_info((const char *)buffer->GetBytes());
3084 raw_rs_info.split(info_lines, '\n');
3086 log->Printf("'.rs.info symbol for '%s':\n%s",
3087 m_module->GetFileSpec().GetCString(),
3088 raw_rs_info.str().c_str());
3101 const auto rs_info_handler = [](llvm::StringRef name) -> int {
3102 return llvm::StringSwitch<int>(name)
3103 // The number of visible global variables in the script
3104 .Case("exportVarCount", eExportVar)
3105 // The number of RenderScrip `forEach` kernels __attribute__((kernel))
3106 .Case("exportForEachCount", eExportForEach)
3107 // The number of generalreductions: This marked in the script by
3108 // `#pragma reduce()`
3109 .Case("exportReduceCount", eExportReduce)
3110 // Total count of all RenderScript specific `#pragmas` used in the
3112 .Case("pragmaCount", ePragma)
3113 .Case("objectSlotCount", eObjectSlot)
3114 .Case("versionInfo", eVersionInfo)
3118 // parse all text lines of .rs.info
3119 for (auto line = info_lines.begin(); line != info_lines.end(); ++line) {
3120 const auto kv_pair = line->split(": ");
3121 const auto key = kv_pair.first;
3122 const auto val = kv_pair.second.trim();
3124 const auto handler = rs_info_handler(key);
3127 // getAsInteger returns `true` on an error condition - we're only
3128 // interested in numeric fields at the moment
3130 if (val.getAsInteger(10, n_lines)) {
3131 LLDB_LOGV(log, "Failed to parse non-numeric '.rs.info' section {0}",
3135 if (info_lines.end() - (line + 1) < (ptrdiff_t)n_lines)
3138 bool success = false;
3141 success = ParseExportVarCount(line, n_lines);
3143 case eExportForEach:
3144 success = ParseExportForeachCount(line, n_lines);
3147 success = ParseExportReduceCount(line, n_lines);
3150 success = ParsePragmaCount(line, n_lines);
3153 success = ParseVersionInfo(line, n_lines);
3157 log->Printf("%s - skipping .rs.info field '%s'", __FUNCTION__,
3158 line->str().c_str());
3166 return info_lines.size() > 0;
3169 void RenderScriptRuntime::DumpStatus(Stream &strm) const {
3171 strm.Printf("Runtime Library discovered.");
3174 if (m_libRSDriver) {
3175 strm.Printf("Runtime Driver discovered.");
3178 if (m_libRSCpuRef) {
3179 strm.Printf("CPU Reference Implementation discovered.");
3183 if (m_runtimeHooks.size()) {
3184 strm.Printf("Runtime functions hooked:");
3186 for (auto b : m_runtimeHooks) {
3187 strm.Indent(b.second->defn->name);
3191 strm.Printf("Runtime is not hooked.");
3196 void RenderScriptRuntime::DumpContexts(Stream &strm) const {
3197 strm.Printf("Inferred RenderScript Contexts:");
3201 std::map<addr_t, uint64_t> contextReferences;
3203 // Iterate over all of the currently discovered scripts. Note: We cant push
3204 // or pop from m_scripts inside this loop or it may invalidate script.
3205 for (const auto &script : m_scripts) {
3206 if (!script->context.isValid())
3208 lldb::addr_t context = *script->context;
3210 if (contextReferences.find(context) != contextReferences.end()) {
3211 contextReferences[context]++;
3213 contextReferences[context] = 1;
3217 for (const auto &cRef : contextReferences) {
3218 strm.Printf("Context 0x%" PRIx64 ": %" PRIu64 " script instances",
3219 cRef.first, cRef.second);
3225 void RenderScriptRuntime::DumpKernels(Stream &strm) const {
3226 strm.Printf("RenderScript Kernels:");
3229 for (const auto &module : m_rsmodules) {
3230 strm.Printf("Resource '%s':", module->m_resname.c_str());
3232 for (const auto &kernel : module->m_kernels) {
3233 strm.Indent(kernel.m_name.AsCString());
3240 RenderScriptRuntime::AllocationDetails *
3241 RenderScriptRuntime::FindAllocByID(Stream &strm, const uint32_t alloc_id) {
3242 AllocationDetails *alloc = nullptr;
3244 // See if we can find allocation using id as an index;
3245 if (alloc_id <= m_allocations.size() && alloc_id != 0 &&
3246 m_allocations[alloc_id - 1]->id == alloc_id) {
3247 alloc = m_allocations[alloc_id - 1].get();
3251 // Fallback to searching
3252 for (const auto &a : m_allocations) {
3253 if (a->id == alloc_id) {
3259 if (alloc == nullptr) {
3260 strm.Printf("Error: Couldn't find allocation with id matching %" PRIu32,
3268 // Prints the contents of an allocation to the output stream, which may be a
3270 bool RenderScriptRuntime::DumpAllocation(Stream &strm, StackFrame *frame_ptr,
3271 const uint32_t id) {
3272 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3274 // Check we can find the desired allocation
3275 AllocationDetails *alloc = FindAllocByID(strm, id);
3277 return false; // FindAllocByID() will print error message for us here
3280 log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__,
3281 *alloc->address.get());
3283 // Check we have information about the allocation, if not calculate it
3284 if (alloc->ShouldRefresh()) {
3286 log->Printf("%s - allocation details not calculated yet, jitting info.",
3289 // JIT all the allocation information
3290 if (!RefreshAllocation(alloc, frame_ptr)) {
3291 strm.Printf("Error: Couldn't JIT allocation details");
3297 // Establish format and size of each data element
3298 const uint32_t vec_size = *alloc->element.type_vec_size.get();
3299 const Element::DataType type = *alloc->element.type.get();
3301 assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
3302 "Invalid allocation type");
3304 lldb::Format format;
3305 if (type >= Element::RS_TYPE_ELEMENT)
3306 format = eFormatHex;
3308 format = vec_size == 1
3309 ? static_cast<lldb::Format>(
3310 AllocationDetails::RSTypeToFormat[type][eFormatSingle])
3311 : static_cast<lldb::Format>(
3312 AllocationDetails::RSTypeToFormat[type][eFormatVector]);
3314 const uint32_t data_size = *alloc->element.datum_size.get();
3317 log->Printf("%s - element size %" PRIu32 " bytes, including padding",
3318 __FUNCTION__, data_size);
3320 // Allocate a buffer to copy data into
3321 std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
3323 strm.Printf("Error: Couldn't read allocation data");
3328 // Calculate stride between rows as there may be padding at end of rows since
3329 // allocated memory is 16-byte aligned
3330 if (!alloc->stride.isValid()) {
3331 if (alloc->dimension.get()->dim_2 == 0) // We only have one dimension
3333 else if (!JITAllocationStride(alloc, frame_ptr)) {
3334 strm.Printf("Error: Couldn't calculate allocation row stride");
3339 const uint32_t stride = *alloc->stride.get();
3340 const uint32_t size = *alloc->size.get(); // Size of whole allocation
3341 const uint32_t padding =
3342 alloc->element.padding.isValid() ? *alloc->element.padding.get() : 0;
3344 log->Printf("%s - stride %" PRIu32 " bytes, size %" PRIu32
3345 " bytes, padding %" PRIu32,
3346 __FUNCTION__, stride, size, padding);
3348 // Find dimensions used to index loops, so need to be non-zero
3349 uint32_t dim_x = alloc->dimension.get()->dim_1;
3350 dim_x = dim_x == 0 ? 1 : dim_x;
3352 uint32_t dim_y = alloc->dimension.get()->dim_2;
3353 dim_y = dim_y == 0 ? 1 : dim_y;
3355 uint32_t dim_z = alloc->dimension.get()->dim_3;
3356 dim_z = dim_z == 0 ? 1 : dim_z;
3358 // Use data extractor to format output
3359 const uint32_t target_ptr_size =
3360 GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
3361 DataExtractor alloc_data(buffer.get(), size, GetProcess()->GetByteOrder(),
3364 uint32_t offset = 0; // Offset in buffer to next element to be printed
3365 uint32_t prev_row = 0; // Offset to the start of the previous row
3367 // Iterate over allocation dimensions, printing results to user
3368 strm.Printf("Data (X, Y, Z):");
3369 for (uint32_t z = 0; z < dim_z; ++z) {
3370 for (uint32_t y = 0; y < dim_y; ++y) {
3371 // Use stride to index start of next row.
3372 if (!(y == 0 && z == 0))
3373 offset = prev_row + stride;
3376 // Print each element in the row individually
3377 for (uint32_t x = 0; x < dim_x; ++x) {
3378 strm.Printf("\n(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ") = ", x, y, z);
3379 if ((type == Element::RS_TYPE_NONE) &&
3380 (alloc->element.children.size() > 0) &&
3381 (alloc->element.type_name != Element::GetFallbackStructName())) {
3382 // Here we are dumping an Element of struct type. This is done using
3383 // expression evaluation with the name of the struct type and pointer
3384 // to element. Don't print the name of the resulting expression,
3385 // since this will be '$[0-9]+'
3386 DumpValueObjectOptions expr_options;
3387 expr_options.SetHideName(true);
3389 // Setup expression as dereferencing a pointer cast to element
3391 char expr_char_buffer[jit_max_expr_size];
3393 snprintf(expr_char_buffer, jit_max_expr_size, "*(%s*) 0x%" PRIx64,
3394 alloc->element.type_name.AsCString(),
3395 *alloc->data_ptr.get() + offset);
3397 if (written < 0 || written >= jit_max_expr_size) {
3399 log->Printf("%s - error in snprintf().", __FUNCTION__);
3403 // Evaluate expression
3404 ValueObjectSP expr_result;
3405 GetProcess()->GetTarget().EvaluateExpression(expr_char_buffer,
3406 frame_ptr, expr_result);
3408 // Print the results to our stream.
3409 expr_result->Dump(strm, expr_options);
3411 DumpDataExtractor(alloc_data, &strm, offset, format,
3412 data_size - padding, 1, 1, LLDB_INVALID_ADDRESS, 0,
3415 offset += data_size;
3424 // Function recalculates all our cached information about allocations by
3425 // jitting the RS runtime regarding each allocation we know about. Returns true
3426 // if all allocations could be recomputed, false otherwise.
3427 bool RenderScriptRuntime::RecomputeAllAllocations(Stream &strm,
3428 StackFrame *frame_ptr) {
3429 bool success = true;
3430 for (auto &alloc : m_allocations) {
3431 // JIT current allocation information
3432 if (!RefreshAllocation(alloc.get(), frame_ptr)) {
3433 strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32
3441 strm.Printf("All allocations successfully recomputed");
3447 // Prints information regarding currently loaded allocations. These details are
3448 // gathered by jitting the runtime, which has as latency. Index parameter
3449 // specifies a single allocation ID to print, or a zero value to print them all
3450 void RenderScriptRuntime::ListAllocations(Stream &strm, StackFrame *frame_ptr,
3451 const uint32_t index) {
3452 strm.Printf("RenderScript Allocations:");
3456 for (auto &alloc : m_allocations) {
3457 // index will only be zero if we want to print all allocations
3458 if (index != 0 && index != alloc->id)
3461 // JIT current allocation information
3462 if (alloc->ShouldRefresh() && !RefreshAllocation(alloc.get(), frame_ptr)) {
3463 strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32,
3469 strm.Printf("%" PRIu32 ":", alloc->id);
3473 strm.Indent("Context: ");
3474 if (!alloc->context.isValid())
3475 strm.Printf("unknown\n");
3477 strm.Printf("0x%" PRIx64 "\n", *alloc->context.get());
3479 strm.Indent("Address: ");
3480 if (!alloc->address.isValid())
3481 strm.Printf("unknown\n");
3483 strm.Printf("0x%" PRIx64 "\n", *alloc->address.get());
3485 strm.Indent("Data pointer: ");
3486 if (!alloc->data_ptr.isValid())
3487 strm.Printf("unknown\n");
3489 strm.Printf("0x%" PRIx64 "\n", *alloc->data_ptr.get());
3491 strm.Indent("Dimensions: ");
3492 if (!alloc->dimension.isValid())
3493 strm.Printf("unknown\n");
3495 strm.Printf("(%" PRId32 ", %" PRId32 ", %" PRId32 ")\n",
3496 alloc->dimension.get()->dim_1, alloc->dimension.get()->dim_2,
3497 alloc->dimension.get()->dim_3);
3499 strm.Indent("Data Type: ");
3500 if (!alloc->element.type.isValid() ||
3501 !alloc->element.type_vec_size.isValid())
3502 strm.Printf("unknown\n");
3504 const int vector_size = *alloc->element.type_vec_size.get();
3505 Element::DataType type = *alloc->element.type.get();
3507 if (!alloc->element.type_name.IsEmpty())
3508 strm.Printf("%s\n", alloc->element.type_name.AsCString());
3510 // Enum value isn't monotonous, so doesn't always index
3511 // RsDataTypeToString array
3512 if (type >= Element::RS_TYPE_ELEMENT && type <= Element::RS_TYPE_FONT)
3514 static_cast<Element::DataType>((type - Element::RS_TYPE_ELEMENT) +
3515 Element::RS_TYPE_MATRIX_2X2 + 1);
3517 if (type >= (sizeof(AllocationDetails::RsDataTypeToString) /
3518 sizeof(AllocationDetails::RsDataTypeToString[0])) ||
3519 vector_size > 4 || vector_size < 1)
3520 strm.Printf("invalid type\n");
3524 AllocationDetails::RsDataTypeToString[static_cast<uint32_t>(type)]
3529 strm.Indent("Data Kind: ");
3530 if (!alloc->element.type_kind.isValid())
3531 strm.Printf("unknown\n");
3533 const Element::DataKind kind = *alloc->element.type_kind.get();
3534 if (kind < Element::RS_KIND_USER || kind > Element::RS_KIND_PIXEL_YUV)
3535 strm.Printf("invalid kind\n");
3539 AllocationDetails::RsDataKindToString[static_cast<uint32_t>(kind)]);
3548 // Set breakpoints on every kernel found in RS module
3549 void RenderScriptRuntime::BreakOnModuleKernels(
3550 const RSModuleDescriptorSP rsmodule_sp) {
3551 for (const auto &kernel : rsmodule_sp->m_kernels) {
3552 // Don't set breakpoint on 'root' kernel
3553 if (strcmp(kernel.m_name.AsCString(), "root") == 0)
3556 CreateKernelBreakpoint(kernel.m_name);
3560 // Method is internally called by the 'kernel breakpoint all' command to enable
3561 // or disable breaking on all kernels. When do_break is true we want to enable
3562 // this functionality. When do_break is false we want to disable it.
3563 void RenderScriptRuntime::SetBreakAllKernels(bool do_break, TargetSP target) {
3565 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3567 InitSearchFilter(target);
3569 // Set breakpoints on all the kernels
3570 if (do_break && !m_breakAllKernels) {
3571 m_breakAllKernels = true;
3573 for (const auto &module : m_rsmodules)
3574 BreakOnModuleKernels(module);
3577 log->Printf("%s(True) - breakpoints set on all currently loaded kernels.",
3579 } else if (!do_break &&
3580 m_breakAllKernels) // Breakpoints won't be set on any new kernels.
3582 m_breakAllKernels = false;
3585 log->Printf("%s(False) - breakpoints no longer automatically set.",
3590 // Given the name of a kernel this function creates a breakpoint using our own
3591 // breakpoint resolver, and returns the Breakpoint shared pointer.
3593 RenderScriptRuntime::CreateKernelBreakpoint(ConstString name) {
3595 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3599 log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
3603 BreakpointResolverSP resolver_sp(new RSBreakpointResolver(nullptr, name));
3604 Target &target = GetProcess()->GetTarget();
3605 BreakpointSP bp = target.CreateBreakpoint(
3606 m_filtersp, resolver_sp, false, false, false);
3608 // Give RS breakpoints a specific name, so the user can manipulate them as a
3611 target.AddNameToBreakpoint(bp, "RenderScriptKernel", err);
3612 if (err.Fail() && log)
3614 log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
3621 RenderScriptRuntime::CreateReductionBreakpoint(ConstString name,
3624 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3628 log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
3632 BreakpointResolverSP resolver_sp(new RSReduceBreakpointResolver(
3633 nullptr, name, &m_rsmodules, kernel_types));
3634 Target &target = GetProcess()->GetTarget();
3635 BreakpointSP bp = target.CreateBreakpoint(
3636 m_filtersp, resolver_sp, false, false, false);
3638 // Give RS breakpoints a specific name, so the user can manipulate them as a
3641 target.AddNameToBreakpoint(bp, "RenderScriptReduction", err);
3642 if (err.Fail() && log)
3643 log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
3649 // Given an expression for a variable this function tries to calculate the
3650 // variable's value. If this is possible it returns true and sets the uint64_t
3651 // parameter to the variables unsigned value. Otherwise function returns false.
3652 bool RenderScriptRuntime::GetFrameVarAsUnsigned(const StackFrameSP frame_sp,
3653 const char *var_name,
3655 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3659 // Find variable in stack frame
3660 ValueObjectSP value_sp(frame_sp->GetValueForVariableExpressionPath(
3661 var_name, eNoDynamicValues,
3662 StackFrame::eExpressionPathOptionCheckPtrVsMember |
3663 StackFrame::eExpressionPathOptionsAllowDirectIVarAccess,
3665 if (!err.Success()) {
3667 log->Printf("%s - error, couldn't find '%s' in frame", __FUNCTION__,
3672 // Find the uint32_t value for the variable
3673 bool success = false;
3674 val = value_sp->GetValueAsUnsigned(0, &success);
3677 log->Printf("%s - error, couldn't parse '%s' as an uint32_t.",
3678 __FUNCTION__, var_name);
3685 // Function attempts to find the current coordinate of a kernel invocation by
3686 // investigating the values of frame variables in the .expand function. These
3687 // coordinates are returned via the coord array reference parameter. Returns
3688 // true if the coordinates could be found, and false otherwise.
3689 bool RenderScriptRuntime::GetKernelCoordinate(RSCoordinate &coord,
3690 Thread *thread_ptr) {
3691 static const char *const x_expr = "rsIndex";
3692 static const char *const y_expr = "p->current.y";
3693 static const char *const z_expr = "p->current.z";
3695 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3699 log->Printf("%s - Error, No thread pointer", __FUNCTION__);
3704 // Walk the call stack looking for a function whose name has the suffix
3705 // '.expand' and contains the variables we're looking for.
3706 for (uint32_t i = 0; i < thread_ptr->GetStackFrameCount(); ++i) {
3707 if (!thread_ptr->SetSelectedFrameByIndex(i))
3710 StackFrameSP frame_sp = thread_ptr->GetSelectedFrame();
3714 // Find the function name
3715 const SymbolContext sym_ctx =
3716 frame_sp->GetSymbolContext(eSymbolContextFunction);
3717 const ConstString func_name = sym_ctx.GetFunctionName();
3722 log->Printf("%s - Inspecting function '%s'", __FUNCTION__,
3723 func_name.GetCString());
3725 // Check if function name has .expand suffix
3726 if (!func_name.GetStringRef().endswith(".expand"))
3730 log->Printf("%s - Found .expand function '%s'", __FUNCTION__,
3731 func_name.GetCString());
3733 // Get values for variables in .expand frame that tell us the current
3734 // kernel invocation
3736 bool found = GetFrameVarAsUnsigned(frame_sp, x_expr, x) &&
3737 GetFrameVarAsUnsigned(frame_sp, y_expr, y) &&
3738 GetFrameVarAsUnsigned(frame_sp, z_expr, z);
3741 // The RenderScript runtime uses uint32_t for these vars. If they're not
3742 // within bounds, our frame parsing is garbage
3743 assert(x <= UINT32_MAX && y <= UINT32_MAX && z <= UINT32_MAX);
3744 coord.x = (uint32_t)x;
3745 coord.y = (uint32_t)y;
3746 coord.z = (uint32_t)z;
3753 // Callback when a kernel breakpoint hits and we're looking for a specific
3754 // coordinate. Baton parameter contains a pointer to the target coordinate we
3755 // want to break on. Function then checks the .expand frame for the current
3756 // coordinate and breaks to user if it matches. Parameter 'break_id' is the id
3757 // of the Breakpoint which made the callback. Parameter 'break_loc_id' is the
3758 // id for the BreakpointLocation which was hit, a single logical breakpoint can
3759 // have multiple addresses.
3760 bool RenderScriptRuntime::KernelBreakpointHit(void *baton,
3761 StoppointCallbackContext *ctx,
3763 user_id_t break_loc_id) {
3765 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3768 "Error: null baton in conditional kernel breakpoint callback");
3770 // Coordinate we want to stop on
3771 RSCoordinate target_coord = *static_cast<RSCoordinate *>(baton);
3774 log->Printf("%s - Break ID %" PRIu64 ", " FMT_COORD, __FUNCTION__, break_id,
3775 target_coord.x, target_coord.y, target_coord.z);
3777 // Select current thread
3778 ExecutionContext context(ctx->exe_ctx_ref);
3779 Thread *thread_ptr = context.GetThreadPtr();
3780 assert(thread_ptr && "Null thread pointer");
3782 // Find current kernel invocation from .expand frame variables
3783 RSCoordinate current_coord{};
3784 if (!GetKernelCoordinate(current_coord, thread_ptr)) {
3786 log->Printf("%s - Error, couldn't select .expand stack frame",
3792 log->Printf("%s - " FMT_COORD, __FUNCTION__, current_coord.x,
3793 current_coord.y, current_coord.z);
3795 // Check if the current kernel invocation coordinate matches our target
3797 if (target_coord == current_coord) {
3799 log->Printf("%s, BREAKING " FMT_COORD, __FUNCTION__, current_coord.x,
3800 current_coord.y, current_coord.z);
3802 BreakpointSP breakpoint_sp =
3803 context.GetTargetPtr()->GetBreakpointByID(break_id);
3804 assert(breakpoint_sp != nullptr &&
3805 "Error: Couldn't find breakpoint matching break id for callback");
3806 breakpoint_sp->SetEnabled(false); // Optimise since conditional breakpoint
3807 // should only be hit once.
3811 // No match on coordinate
3815 void RenderScriptRuntime::SetConditional(BreakpointSP bp, Stream &messages,
3816 const RSCoordinate &coord) {
3817 messages.Printf("Conditional kernel breakpoint on coordinate " FMT_COORD,
3818 coord.x, coord.y, coord.z);
3821 // Allocate memory for the baton, and copy over coordinate
3822 RSCoordinate *baton = new RSCoordinate(coord);
3824 // Create a callback that will be invoked every time the breakpoint is hit.
3825 // The baton object passed to the handler is the target coordinate we want to
3827 bp->SetCallback(KernelBreakpointHit, baton, true);
3829 // Store a shared pointer to the baton, so the memory will eventually be
3830 // cleaned up after destruction
3831 m_conditional_breaks[bp->GetID()] = std::unique_ptr<RSCoordinate>(baton);
3834 // Tries to set a breakpoint on the start of a kernel, resolved using the
3835 // kernel name. Argument 'coords', represents a three dimensional coordinate
3836 // which can be used to specify a single kernel instance to break on. If this
3837 // is set then we add a callback to the breakpoint.
3838 bool RenderScriptRuntime::PlaceBreakpointOnKernel(TargetSP target,
3841 const RSCoordinate *coord) {
3845 InitSearchFilter(target);
3847 ConstString kernel_name(name);
3848 BreakpointSP bp = CreateKernelBreakpoint(kernel_name);
3852 // We have a conditional breakpoint on a specific coordinate
3854 SetConditional(bp, messages, *coord);
3856 bp->GetDescription(&messages, lldb::eDescriptionLevelInitial, false);
3862 RenderScriptRuntime::CreateScriptGroupBreakpoint(ConstString name,
3865 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3869 log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
3873 BreakpointResolverSP resolver_sp(new RSScriptGroupBreakpointResolver(
3874 nullptr, name, m_scriptGroups, stop_on_all));
3875 Target &target = GetProcess()->GetTarget();
3876 BreakpointSP bp = target.CreateBreakpoint(
3877 m_filtersp, resolver_sp, false, false, false);
3878 // Give RS breakpoints a specific name, so the user can manipulate them as a
3881 target.AddNameToBreakpoint(bp, name.GetCString(), err);
3882 if (err.Fail() && log)
3883 log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
3885 // ask the breakpoint to resolve itself
3886 bp->ResolveBreakpoint();
3890 bool RenderScriptRuntime::PlaceBreakpointOnScriptGroup(TargetSP target,
3894 InitSearchFilter(target);
3895 BreakpointSP bp = CreateScriptGroupBreakpoint(name, multi);
3897 bp->GetDescription(&strm, lldb::eDescriptionLevelInitial, false);
3901 bool RenderScriptRuntime::PlaceBreakpointOnReduction(TargetSP target,
3903 const char *reduce_name,
3904 const RSCoordinate *coord,
3909 InitSearchFilter(target);
3911 CreateReductionBreakpoint(ConstString(reduce_name), kernel_types);
3916 SetConditional(bp, messages, *coord);
3918 bp->GetDescription(&messages, lldb::eDescriptionLevelInitial, false);
3923 void RenderScriptRuntime::DumpModules(Stream &strm) const {
3924 strm.Printf("RenderScript Modules:");
3927 for (const auto &module : m_rsmodules) {
3933 RenderScriptRuntime::ScriptDetails *
3934 RenderScriptRuntime::LookUpScript(addr_t address, bool create) {
3935 for (const auto &s : m_scripts) {
3936 if (s->script.isValid())
3937 if (*s->script == address)
3941 std::unique_ptr<ScriptDetails> s(new ScriptDetails);
3942 s->script = address;
3943 m_scripts.push_back(std::move(s));
3944 return m_scripts.back().get();
3949 RenderScriptRuntime::AllocationDetails *
3950 RenderScriptRuntime::LookUpAllocation(addr_t address) {
3951 for (const auto &a : m_allocations) {
3952 if (a->address.isValid())
3953 if (*a->address == address)
3959 RenderScriptRuntime::AllocationDetails *
3960 RenderScriptRuntime::CreateAllocation(addr_t address) {
3961 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
3963 // Remove any previous allocation which contains the same address
3964 auto it = m_allocations.begin();
3965 while (it != m_allocations.end()) {
3966 if (*((*it)->address) == address) {
3968 log->Printf("%s - Removing allocation id: %d, address: 0x%" PRIx64,
3969 __FUNCTION__, (*it)->id, address);
3971 it = m_allocations.erase(it);
3977 std::unique_ptr<AllocationDetails> a(new AllocationDetails);
3978 a->address = address;
3979 m_allocations.push_back(std::move(a));
3980 return m_allocations.back().get();
3983 bool RenderScriptRuntime::ResolveKernelName(lldb::addr_t kernel_addr,
3984 ConstString &name) {
3985 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS);
3987 Target &target = GetProcess()->GetTarget();
3989 // RenderScript module
3990 if (!target.GetSectionLoadList().ResolveLoadAddress(kernel_addr, resolved)) {
3992 log->Printf("%s: unable to resolve 0x%" PRIx64 " to a loaded symbol",
3993 __FUNCTION__, kernel_addr);
3997 Symbol *sym = resolved.CalculateSymbolContextSymbol();
4001 name = sym->GetName();
4002 assert(IsRenderScriptModule(resolved.CalculateSymbolContextModule()));
4004 log->Printf("%s: 0x%" PRIx64 " resolved to the symbol '%s'", __FUNCTION__,
4005 kernel_addr, name.GetCString());
4009 void RSModuleDescriptor::Dump(Stream &strm) const {
4010 int indent = strm.GetIndentLevel();
4013 m_module->GetFileSpec().Dump(&strm);
4014 strm.Indent(m_module->GetNumCompileUnits() ? "Debug info loaded."
4015 : "Debug info does not exist.");
4020 strm.Printf("Globals: %" PRIu64, static_cast<uint64_t>(m_globals.size()));
4023 for (const auto &global : m_globals) {
4029 strm.Printf("Kernels: %" PRIu64, static_cast<uint64_t>(m_kernels.size()));
4032 for (const auto &kernel : m_kernels) {
4038 strm.Printf("Pragmas: %" PRIu64, static_cast<uint64_t>(m_pragmas.size()));
4041 for (const auto &key_val : m_pragmas) {
4043 strm.Printf("%s: %s", key_val.first.c_str(), key_val.second.c_str());
4049 strm.Printf("Reductions: %" PRIu64,
4050 static_cast<uint64_t>(m_reductions.size()));
4053 for (const auto &reduction : m_reductions) {
4054 reduction.Dump(strm);
4057 strm.SetIndentLevel(indent);
4060 void RSGlobalDescriptor::Dump(Stream &strm) const {
4061 strm.Indent(m_name.AsCString());
4062 VariableList var_list;
4063 m_module->m_module->FindGlobalVariables(m_name, nullptr, 1U, var_list);
4064 if (var_list.GetSize() == 1) {
4065 auto var = var_list.GetVariableAtIndex(0);
4066 auto type = var->GetType();
4069 type->DumpTypeName(&strm);
4071 strm.Printf(" - Unknown Type");
4074 strm.Printf(" - variable identified, but not found in binary");
4075 const Symbol *s = m_module->m_module->FindFirstSymbolWithNameAndType(
4076 m_name, eSymbolTypeData);
4078 strm.Printf(" (symbol exists) ");
4085 void RSKernelDescriptor::Dump(Stream &strm) const {
4086 strm.Indent(m_name.AsCString());
4090 void RSReductionDescriptor::Dump(lldb_private::Stream &stream) const {
4091 stream.Indent(m_reduce_name.AsCString());
4092 stream.IndentMore();
4095 stream.Printf("accumulator: %s", m_accum_name.AsCString());
4098 stream.Printf("initializer: %s", m_init_name.AsCString());
4101 stream.Printf("combiner: %s", m_comb_name.AsCString());
4104 stream.Printf("outconverter: %s", m_outc_name.AsCString());
4106 // XXX This is currently unspecified by RenderScript, and unused
4108 // stream.Printf("halter: '%s'", m_init_name.AsCString());
4110 stream.IndentLess();
4113 class CommandObjectRenderScriptRuntimeModuleDump : public CommandObjectParsed {
4115 CommandObjectRenderScriptRuntimeModuleDump(CommandInterpreter &interpreter)
4116 : CommandObjectParsed(
4117 interpreter, "renderscript module dump",
4118 "Dumps renderscript specific information for all modules.",
4119 "renderscript module dump",
4120 eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
4122 ~CommandObjectRenderScriptRuntimeModuleDump() override = default;
4124 bool DoExecute(Args &command, CommandReturnObject &result) override {
4125 RenderScriptRuntime *runtime = llvm::cast<RenderScriptRuntime>(
4126 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4127 eLanguageTypeExtRenderScript));
4128 runtime->DumpModules(result.GetOutputStream());
4129 result.SetStatus(eReturnStatusSuccessFinishResult);
4134 class CommandObjectRenderScriptRuntimeModule : public CommandObjectMultiword {
4136 CommandObjectRenderScriptRuntimeModule(CommandInterpreter &interpreter)
4137 : CommandObjectMultiword(interpreter, "renderscript module",
4138 "Commands that deal with RenderScript modules.",
4141 "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleDump(
4145 ~CommandObjectRenderScriptRuntimeModule() override = default;
4148 class CommandObjectRenderScriptRuntimeKernelList : public CommandObjectParsed {
4150 CommandObjectRenderScriptRuntimeKernelList(CommandInterpreter &interpreter)
4151 : CommandObjectParsed(
4152 interpreter, "renderscript kernel list",
4153 "Lists renderscript kernel names and associated script resources.",
4154 "renderscript kernel list",
4155 eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
4157 ~CommandObjectRenderScriptRuntimeKernelList() override = default;
4159 bool DoExecute(Args &command, CommandReturnObject &result) override {
4160 RenderScriptRuntime *runtime = llvm::cast<RenderScriptRuntime>(
4161 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4162 eLanguageTypeExtRenderScript));
4163 runtime->DumpKernels(result.GetOutputStream());
4164 result.SetStatus(eReturnStatusSuccessFinishResult);
4169 static constexpr OptionDefinition g_renderscript_reduction_bp_set_options[] = {
4170 {LLDB_OPT_SET_1, false, "function-role", 't',
4171 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeOneLiner,
4172 "Break on a comma separated set of reduction kernel types "
4173 "(accumulator,outcoverter,combiner,initializer"},
4174 {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument,
4175 nullptr, {}, 0, eArgTypeValue,
4176 "Set a breakpoint on a single invocation of the kernel with specified "
4178 "Coordinate takes the form 'x[,y][,z] where x,y,z are positive "
4179 "integers representing kernel dimensions. "
4180 "Any unset dimensions will be defaulted to zero."}};
4182 class CommandObjectRenderScriptRuntimeReductionBreakpointSet
4183 : public CommandObjectParsed {
4185 CommandObjectRenderScriptRuntimeReductionBreakpointSet(
4186 CommandInterpreter &interpreter)
4187 : CommandObjectParsed(
4188 interpreter, "renderscript reduction breakpoint set",
4189 "Set a breakpoint on named RenderScript general reductions",
4190 "renderscript reduction breakpoint set <kernel_name> [-t "
4191 "<reduction_kernel_type,...>]",
4192 eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4193 eCommandProcessMustBePaused),
4196 class CommandOptions : public Options {
4200 m_kernel_types(RSReduceBreakpointResolver::eKernelTypeAll) {}
4202 ~CommandOptions() override = default;
4204 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4205 ExecutionContext *exe_ctx) override {
4207 StreamString err_str;
4208 const int short_option = m_getopt_table[option_idx].val;
4209 switch (short_option) {
4211 if (!ParseReductionTypes(option_arg, err_str))
4212 err.SetErrorStringWithFormat(
4213 "Unable to deduce reduction types for %s: %s",
4214 option_arg.str().c_str(), err_str.GetData());
4217 auto coord = RSCoordinate{};
4218 if (!ParseCoordinate(option_arg, coord))
4219 err.SetErrorStringWithFormat("unable to parse coordinate for %s",
4220 option_arg.str().c_str());
4222 m_have_coord = true;
4228 err.SetErrorStringWithFormat("Invalid option '-%c'", short_option);
4233 void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4234 m_have_coord = false;
4237 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4238 return llvm::makeArrayRef(g_renderscript_reduction_bp_set_options);
4241 bool ParseReductionTypes(llvm::StringRef option_val,
4242 StreamString &err_str) {
4243 m_kernel_types = RSReduceBreakpointResolver::eKernelTypeNone;
4244 const auto reduce_name_to_type = [](llvm::StringRef name) -> int {
4245 return llvm::StringSwitch<int>(name)
4246 .Case("accumulator", RSReduceBreakpointResolver::eKernelTypeAccum)
4247 .Case("initializer", RSReduceBreakpointResolver::eKernelTypeInit)
4248 .Case("outconverter", RSReduceBreakpointResolver::eKernelTypeOutC)
4249 .Case("combiner", RSReduceBreakpointResolver::eKernelTypeComb)
4250 .Case("all", RSReduceBreakpointResolver::eKernelTypeAll)
4251 // Currently not exposed by the runtime
4252 // .Case("halter", RSReduceBreakpointResolver::eKernelTypeHalter)
4256 // Matching a comma separated list of known words is fairly
4257 // straightforward with PCRE, but we're using ERE, so we end up with a
4258 // little ugliness...
4259 RegularExpression::Match match(/* max_matches */ 5);
4260 RegularExpression match_type_list(
4261 llvm::StringRef("^([[:alpha:]]+)(,[[:alpha:]]+){0,4}$"));
4263 assert(match_type_list.IsValid());
4265 if (!match_type_list.Execute(option_val, &match)) {
4267 "a comma-separated list of kernel types is required");
4271 // splitting on commas is much easier with llvm::StringRef than regex
4272 llvm::SmallVector<llvm::StringRef, 5> type_names;
4273 llvm::StringRef(option_val).split(type_names, ',');
4275 for (const auto &name : type_names) {
4276 const int type = reduce_name_to_type(name);
4278 err_str.Printf("unknown kernel type name %s", name.str().c_str());
4281 m_kernel_types |= type;
4288 llvm::StringRef m_reduce_name;
4289 RSCoordinate m_coord;
4293 Options *GetOptions() override { return &m_options; }
4295 bool DoExecute(Args &command, CommandReturnObject &result) override {
4296 const size_t argc = command.GetArgumentCount();
4298 result.AppendErrorWithFormat("'%s' takes 1 argument of reduction name, "
4299 "and an optional kernel type list",
4300 m_cmd_name.c_str());
4301 result.SetStatus(eReturnStatusFailed);
4305 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4306 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4307 eLanguageTypeExtRenderScript));
4309 auto &outstream = result.GetOutputStream();
4310 auto name = command.GetArgumentAtIndex(0);
4311 auto &target = m_exe_ctx.GetTargetSP();
4312 auto coord = m_options.m_have_coord ? &m_options.m_coord : nullptr;
4313 if (!runtime->PlaceBreakpointOnReduction(target, outstream, name, coord,
4314 m_options.m_kernel_types)) {
4315 result.SetStatus(eReturnStatusFailed);
4316 result.AppendError("Error: unable to place breakpoint on reduction");
4319 result.AppendMessage("Breakpoint(s) created");
4320 result.SetStatus(eReturnStatusSuccessFinishResult);
4325 CommandOptions m_options;
4328 static constexpr OptionDefinition g_renderscript_kernel_bp_set_options[] = {
4329 {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument,
4330 nullptr, {}, 0, eArgTypeValue,
4331 "Set a breakpoint on a single invocation of the kernel with specified "
4333 "Coordinate takes the form 'x[,y][,z] where x,y,z are positive "
4334 "integers representing kernel dimensions. "
4335 "Any unset dimensions will be defaulted to zero."}};
4337 class CommandObjectRenderScriptRuntimeKernelBreakpointSet
4338 : public CommandObjectParsed {
4340 CommandObjectRenderScriptRuntimeKernelBreakpointSet(
4341 CommandInterpreter &interpreter)
4342 : CommandObjectParsed(
4343 interpreter, "renderscript kernel breakpoint set",
4344 "Sets a breakpoint on a renderscript kernel.",
4345 "renderscript kernel breakpoint set <kernel_name> [-c x,y,z]",
4346 eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4347 eCommandProcessMustBePaused),
4350 ~CommandObjectRenderScriptRuntimeKernelBreakpointSet() override = default;
4352 Options *GetOptions() override { return &m_options; }
4354 class CommandOptions : public Options {
4356 CommandOptions() : Options() {}
4358 ~CommandOptions() override = default;
4360 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4361 ExecutionContext *exe_ctx) override {
4363 const int short_option = m_getopt_table[option_idx].val;
4365 switch (short_option) {
4367 auto coord = RSCoordinate{};
4368 if (!ParseCoordinate(option_arg, coord))
4369 err.SetErrorStringWithFormat(
4370 "Couldn't parse coordinate '%s', should be in format 'x,y,z'.",
4371 option_arg.str().c_str());
4373 m_have_coord = true;
4379 err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4385 void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4386 m_have_coord = false;
4389 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4390 return llvm::makeArrayRef(g_renderscript_kernel_bp_set_options);
4393 RSCoordinate m_coord;
4397 bool DoExecute(Args &command, CommandReturnObject &result) override {
4398 const size_t argc = command.GetArgumentCount();
4400 result.AppendErrorWithFormat(
4401 "'%s' takes 1 argument of kernel name, and an optional coordinate.",
4402 m_cmd_name.c_str());
4403 result.SetStatus(eReturnStatusFailed);
4407 RenderScriptRuntime *runtime = llvm::cast<RenderScriptRuntime>(
4408 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4409 eLanguageTypeExtRenderScript));
4411 auto &outstream = result.GetOutputStream();
4412 auto &target = m_exe_ctx.GetTargetSP();
4413 auto name = command.GetArgumentAtIndex(0);
4414 auto coord = m_options.m_have_coord ? &m_options.m_coord : nullptr;
4415 if (!runtime->PlaceBreakpointOnKernel(target, outstream, name, coord)) {
4416 result.SetStatus(eReturnStatusFailed);
4417 result.AppendErrorWithFormat(
4418 "Error: unable to set breakpoint on kernel '%s'", name);
4422 result.AppendMessage("Breakpoint(s) created");
4423 result.SetStatus(eReturnStatusSuccessFinishResult);
4428 CommandOptions m_options;
4431 class CommandObjectRenderScriptRuntimeKernelBreakpointAll
4432 : public CommandObjectParsed {
4434 CommandObjectRenderScriptRuntimeKernelBreakpointAll(
4435 CommandInterpreter &interpreter)
4436 : CommandObjectParsed(
4437 interpreter, "renderscript kernel breakpoint all",
4438 "Automatically sets a breakpoint on all renderscript kernels that "
4439 "are or will be loaded.\n"
4440 "Disabling option means breakpoints will no longer be set on any "
4441 "kernels loaded in the future, "
4442 "but does not remove currently set breakpoints.",
4443 "renderscript kernel breakpoint all <enable/disable>",
4444 eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4445 eCommandProcessMustBePaused) {}
4447 ~CommandObjectRenderScriptRuntimeKernelBreakpointAll() override = default;
4449 bool DoExecute(Args &command, CommandReturnObject &result) override {
4450 const size_t argc = command.GetArgumentCount();
4452 result.AppendErrorWithFormat(
4453 "'%s' takes 1 argument of 'enable' or 'disable'", m_cmd_name.c_str());
4454 result.SetStatus(eReturnStatusFailed);
4458 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4459 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4460 eLanguageTypeExtRenderScript));
4462 bool do_break = false;
4463 const char *argument = command.GetArgumentAtIndex(0);
4464 if (strcmp(argument, "enable") == 0) {
4466 result.AppendMessage("Breakpoints will be set on all kernels.");
4467 } else if (strcmp(argument, "disable") == 0) {
4469 result.AppendMessage("Breakpoints will not be set on any new kernels.");
4471 result.AppendErrorWithFormat(
4472 "Argument must be either 'enable' or 'disable'");
4473 result.SetStatus(eReturnStatusFailed);
4477 runtime->SetBreakAllKernels(do_break, m_exe_ctx.GetTargetSP());
4479 result.SetStatus(eReturnStatusSuccessFinishResult);
4484 class CommandObjectRenderScriptRuntimeReductionBreakpoint
4485 : public CommandObjectMultiword {
4487 CommandObjectRenderScriptRuntimeReductionBreakpoint(
4488 CommandInterpreter &interpreter)
4489 : CommandObjectMultiword(interpreter, "renderscript reduction breakpoint",
4490 "Commands that manipulate breakpoints on "
4491 "renderscript general reductions.",
4494 "set", CommandObjectSP(
4495 new CommandObjectRenderScriptRuntimeReductionBreakpointSet(
4499 ~CommandObjectRenderScriptRuntimeReductionBreakpoint() override = default;
4502 class CommandObjectRenderScriptRuntimeKernelCoordinate
4503 : public CommandObjectParsed {
4505 CommandObjectRenderScriptRuntimeKernelCoordinate(
4506 CommandInterpreter &interpreter)
4507 : CommandObjectParsed(
4508 interpreter, "renderscript kernel coordinate",
4509 "Shows the (x,y,z) coordinate of the current kernel invocation.",
4510 "renderscript kernel coordinate",
4511 eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4512 eCommandProcessMustBePaused) {}
4514 ~CommandObjectRenderScriptRuntimeKernelCoordinate() override = default;
4516 bool DoExecute(Args &command, CommandReturnObject &result) override {
4517 RSCoordinate coord{};
4518 bool success = RenderScriptRuntime::GetKernelCoordinate(
4519 coord, m_exe_ctx.GetThreadPtr());
4520 Stream &stream = result.GetOutputStream();
4523 stream.Printf("Coordinate: " FMT_COORD, coord.x, coord.y, coord.z);
4525 result.SetStatus(eReturnStatusSuccessFinishResult);
4527 stream.Printf("Error: Coordinate could not be found.");
4529 result.SetStatus(eReturnStatusFailed);
4535 class CommandObjectRenderScriptRuntimeKernelBreakpoint
4536 : public CommandObjectMultiword {
4538 CommandObjectRenderScriptRuntimeKernelBreakpoint(
4539 CommandInterpreter &interpreter)
4540 : CommandObjectMultiword(
4541 interpreter, "renderscript kernel",
4542 "Commands that generate breakpoints on renderscript kernels.",
4546 CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointSet(
4550 CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointAll(
4554 ~CommandObjectRenderScriptRuntimeKernelBreakpoint() override = default;
4557 class CommandObjectRenderScriptRuntimeKernel : public CommandObjectMultiword {
4559 CommandObjectRenderScriptRuntimeKernel(CommandInterpreter &interpreter)
4560 : CommandObjectMultiword(interpreter, "renderscript kernel",
4561 "Commands that deal with RenderScript kernels.",
4564 "list", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelList(
4569 new CommandObjectRenderScriptRuntimeKernelCoordinate(interpreter)));
4573 new CommandObjectRenderScriptRuntimeKernelBreakpoint(interpreter)));
4576 ~CommandObjectRenderScriptRuntimeKernel() override = default;
4579 class CommandObjectRenderScriptRuntimeContextDump : public CommandObjectParsed {
4581 CommandObjectRenderScriptRuntimeContextDump(CommandInterpreter &interpreter)
4582 : CommandObjectParsed(interpreter, "renderscript context dump",
4583 "Dumps renderscript context information.",
4584 "renderscript context dump",
4585 eCommandRequiresProcess |
4586 eCommandProcessMustBeLaunched) {}
4588 ~CommandObjectRenderScriptRuntimeContextDump() override = default;
4590 bool DoExecute(Args &command, CommandReturnObject &result) override {
4591 RenderScriptRuntime *runtime = llvm::cast<RenderScriptRuntime>(
4592 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4593 eLanguageTypeExtRenderScript));
4594 runtime->DumpContexts(result.GetOutputStream());
4595 result.SetStatus(eReturnStatusSuccessFinishResult);
4600 static constexpr OptionDefinition g_renderscript_runtime_alloc_dump_options[] = {
4601 {LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument,
4602 nullptr, {}, 0, eArgTypeFilename,
4603 "Print results to specified file instead of command line."}};
4605 class CommandObjectRenderScriptRuntimeContext : public CommandObjectMultiword {
4607 CommandObjectRenderScriptRuntimeContext(CommandInterpreter &interpreter)
4608 : CommandObjectMultiword(interpreter, "renderscript context",
4609 "Commands that deal with RenderScript contexts.",
4612 "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeContextDump(
4616 ~CommandObjectRenderScriptRuntimeContext() override = default;
4619 class CommandObjectRenderScriptRuntimeAllocationDump
4620 : public CommandObjectParsed {
4622 CommandObjectRenderScriptRuntimeAllocationDump(
4623 CommandInterpreter &interpreter)
4624 : CommandObjectParsed(interpreter, "renderscript allocation dump",
4625 "Displays the contents of a particular allocation",
4626 "renderscript allocation dump <ID>",
4627 eCommandRequiresProcess |
4628 eCommandProcessMustBeLaunched),
4631 ~CommandObjectRenderScriptRuntimeAllocationDump() override = default;
4633 Options *GetOptions() override { return &m_options; }
4635 class CommandOptions : public Options {
4637 CommandOptions() : Options() {}
4639 ~CommandOptions() override = default;
4641 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4642 ExecutionContext *exe_ctx) override {
4644 const int short_option = m_getopt_table[option_idx].val;
4646 switch (short_option) {
4648 m_outfile.SetFile(option_arg, FileSpec::Style::native);
4649 FileSystem::Instance().Resolve(m_outfile);
4650 if (FileSystem::Instance().Exists(m_outfile)) {
4652 err.SetErrorStringWithFormat("file already exists: '%s'",
4653 option_arg.str().c_str());
4657 err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4663 void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4667 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4668 return llvm::makeArrayRef(g_renderscript_runtime_alloc_dump_options);
4674 bool DoExecute(Args &command, CommandReturnObject &result) override {
4675 const size_t argc = command.GetArgumentCount();
4677 result.AppendErrorWithFormat("'%s' takes 1 argument, an allocation ID. "
4678 "As well as an optional -f argument",
4679 m_cmd_name.c_str());
4680 result.SetStatus(eReturnStatusFailed);
4684 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4685 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4686 eLanguageTypeExtRenderScript));
4688 const char *id_cstr = command.GetArgumentAtIndex(0);
4689 bool success = false;
4691 StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
4693 result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4695 result.SetStatus(eReturnStatusFailed);
4699 Stream *output_strm = nullptr;
4700 StreamFile outfile_stream;
4701 const FileSpec &outfile_spec =
4702 m_options.m_outfile; // Dump allocation to file instead
4705 std::string path = outfile_spec.GetPath();
4706 auto error = FileSystem::Instance().Open(
4707 outfile_stream.GetFile(), outfile_spec,
4708 File::eOpenOptionWrite | File::eOpenOptionCanCreate);
4709 if (error.Success()) {
4710 output_strm = &outfile_stream;
4711 result.GetOutputStream().Printf("Results written to '%s'",
4713 result.GetOutputStream().EOL();
4715 result.AppendErrorWithFormat("Couldn't open file '%s'", path.c_str());
4716 result.SetStatus(eReturnStatusFailed);
4720 output_strm = &result.GetOutputStream();
4722 assert(output_strm != nullptr);
4724 runtime->DumpAllocation(*output_strm, m_exe_ctx.GetFramePtr(), id);
4727 result.SetStatus(eReturnStatusSuccessFinishResult);
4729 result.SetStatus(eReturnStatusFailed);
4735 CommandOptions m_options;
4738 static constexpr OptionDefinition g_renderscript_runtime_alloc_list_options[] = {
4739 {LLDB_OPT_SET_1, false, "id", 'i', OptionParser::eRequiredArgument, nullptr,
4740 {}, 0, eArgTypeIndex,
4741 "Only show details of a single allocation with specified id."}};
4743 class CommandObjectRenderScriptRuntimeAllocationList
4744 : public CommandObjectParsed {
4746 CommandObjectRenderScriptRuntimeAllocationList(
4747 CommandInterpreter &interpreter)
4748 : CommandObjectParsed(
4749 interpreter, "renderscript allocation list",
4750 "List renderscript allocations and their information.",
4751 "renderscript allocation list",
4752 eCommandRequiresProcess | eCommandProcessMustBeLaunched),
4755 ~CommandObjectRenderScriptRuntimeAllocationList() override = default;
4757 Options *GetOptions() override { return &m_options; }
4759 class CommandOptions : public Options {
4761 CommandOptions() : Options(), m_id(0) {}
4763 ~CommandOptions() override = default;
4765 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4766 ExecutionContext *exe_ctx) override {
4768 const int short_option = m_getopt_table[option_idx].val;
4770 switch (short_option) {
4772 if (option_arg.getAsInteger(0, m_id))
4773 err.SetErrorStringWithFormat("invalid integer value for option '%c'",
4777 err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4783 void OptionParsingStarting(ExecutionContext *exe_ctx) override { m_id = 0; }
4785 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4786 return llvm::makeArrayRef(g_renderscript_runtime_alloc_list_options);
4792 bool DoExecute(Args &command, CommandReturnObject &result) override {
4793 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4794 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4795 eLanguageTypeExtRenderScript));
4796 runtime->ListAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr(),
4798 result.SetStatus(eReturnStatusSuccessFinishResult);
4803 CommandOptions m_options;
4806 class CommandObjectRenderScriptRuntimeAllocationLoad
4807 : public CommandObjectParsed {
4809 CommandObjectRenderScriptRuntimeAllocationLoad(
4810 CommandInterpreter &interpreter)
4811 : CommandObjectParsed(
4812 interpreter, "renderscript allocation load",
4813 "Loads renderscript allocation contents from a file.",
4814 "renderscript allocation load <ID> <filename>",
4815 eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
4817 ~CommandObjectRenderScriptRuntimeAllocationLoad() override = default;
4819 bool DoExecute(Args &command, CommandReturnObject &result) override {
4820 const size_t argc = command.GetArgumentCount();
4822 result.AppendErrorWithFormat(
4823 "'%s' takes 2 arguments, an allocation ID and filename to read from.",
4824 m_cmd_name.c_str());
4825 result.SetStatus(eReturnStatusFailed);
4829 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4830 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4831 eLanguageTypeExtRenderScript));
4833 const char *id_cstr = command.GetArgumentAtIndex(0);
4834 bool success = false;
4836 StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
4838 result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4840 result.SetStatus(eReturnStatusFailed);
4844 const char *path = command.GetArgumentAtIndex(1);
4845 bool loaded = runtime->LoadAllocation(result.GetOutputStream(), id, path,
4846 m_exe_ctx.GetFramePtr());
4849 result.SetStatus(eReturnStatusSuccessFinishResult);
4851 result.SetStatus(eReturnStatusFailed);
4857 class CommandObjectRenderScriptRuntimeAllocationSave
4858 : public CommandObjectParsed {
4860 CommandObjectRenderScriptRuntimeAllocationSave(
4861 CommandInterpreter &interpreter)
4862 : CommandObjectParsed(interpreter, "renderscript allocation save",
4863 "Write renderscript allocation contents to a file.",
4864 "renderscript allocation save <ID> <filename>",
4865 eCommandRequiresProcess |
4866 eCommandProcessMustBeLaunched) {}
4868 ~CommandObjectRenderScriptRuntimeAllocationSave() override = default;
4870 bool DoExecute(Args &command, CommandReturnObject &result) override {
4871 const size_t argc = command.GetArgumentCount();
4873 result.AppendErrorWithFormat(
4874 "'%s' takes 2 arguments, an allocation ID and filename to read from.",
4875 m_cmd_name.c_str());
4876 result.SetStatus(eReturnStatusFailed);
4880 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4881 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4882 eLanguageTypeExtRenderScript));
4884 const char *id_cstr = command.GetArgumentAtIndex(0);
4885 bool success = false;
4887 StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
4889 result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4891 result.SetStatus(eReturnStatusFailed);
4895 const char *path = command.GetArgumentAtIndex(1);
4896 bool saved = runtime->SaveAllocation(result.GetOutputStream(), id, path,
4897 m_exe_ctx.GetFramePtr());
4900 result.SetStatus(eReturnStatusSuccessFinishResult);
4902 result.SetStatus(eReturnStatusFailed);
4908 class CommandObjectRenderScriptRuntimeAllocationRefresh
4909 : public CommandObjectParsed {
4911 CommandObjectRenderScriptRuntimeAllocationRefresh(
4912 CommandInterpreter &interpreter)
4913 : CommandObjectParsed(interpreter, "renderscript allocation refresh",
4914 "Recomputes the details of all allocations.",
4915 "renderscript allocation refresh",
4916 eCommandRequiresProcess |
4917 eCommandProcessMustBeLaunched) {}
4919 ~CommandObjectRenderScriptRuntimeAllocationRefresh() override = default;
4921 bool DoExecute(Args &command, CommandReturnObject &result) override {
4922 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4923 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4924 eLanguageTypeExtRenderScript));
4926 bool success = runtime->RecomputeAllAllocations(result.GetOutputStream(),
4927 m_exe_ctx.GetFramePtr());
4930 result.SetStatus(eReturnStatusSuccessFinishResult);
4933 result.SetStatus(eReturnStatusFailed);
4939 class CommandObjectRenderScriptRuntimeAllocation
4940 : public CommandObjectMultiword {
4942 CommandObjectRenderScriptRuntimeAllocation(CommandInterpreter &interpreter)
4943 : CommandObjectMultiword(
4944 interpreter, "renderscript allocation",
4945 "Commands that deal with RenderScript allocations.", nullptr) {
4949 new CommandObjectRenderScriptRuntimeAllocationList(interpreter)));
4953 new CommandObjectRenderScriptRuntimeAllocationDump(interpreter)));
4957 new CommandObjectRenderScriptRuntimeAllocationSave(interpreter)));
4961 new CommandObjectRenderScriptRuntimeAllocationLoad(interpreter)));
4964 CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationRefresh(
4968 ~CommandObjectRenderScriptRuntimeAllocation() override = default;
4971 class CommandObjectRenderScriptRuntimeStatus : public CommandObjectParsed {
4973 CommandObjectRenderScriptRuntimeStatus(CommandInterpreter &interpreter)
4974 : CommandObjectParsed(interpreter, "renderscript status",
4975 "Displays current RenderScript runtime status.",
4976 "renderscript status",
4977 eCommandRequiresProcess |
4978 eCommandProcessMustBeLaunched) {}
4980 ~CommandObjectRenderScriptRuntimeStatus() override = default;
4982 bool DoExecute(Args &command, CommandReturnObject &result) override {
4983 RenderScriptRuntime *runtime = llvm::cast<RenderScriptRuntime>(
4984 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4985 eLanguageTypeExtRenderScript));
4986 runtime->DumpStatus(result.GetOutputStream());
4987 result.SetStatus(eReturnStatusSuccessFinishResult);
4992 class CommandObjectRenderScriptRuntimeReduction
4993 : public CommandObjectMultiword {
4995 CommandObjectRenderScriptRuntimeReduction(CommandInterpreter &interpreter)
4996 : CommandObjectMultiword(interpreter, "renderscript reduction",
4997 "Commands that handle general reduction kernels",
5001 CommandObjectSP(new CommandObjectRenderScriptRuntimeReductionBreakpoint(
5004 ~CommandObjectRenderScriptRuntimeReduction() override = default;
5007 class CommandObjectRenderScriptRuntime : public CommandObjectMultiword {
5009 CommandObjectRenderScriptRuntime(CommandInterpreter &interpreter)
5010 : CommandObjectMultiword(
5011 interpreter, "renderscript",
5012 "Commands for operating on the RenderScript runtime.",
5013 "renderscript <subcommand> [<subcommand-options>]") {
5015 "module", CommandObjectSP(
5016 new CommandObjectRenderScriptRuntimeModule(interpreter)));
5018 "status", CommandObjectSP(
5019 new CommandObjectRenderScriptRuntimeStatus(interpreter)));
5021 "kernel", CommandObjectSP(
5022 new CommandObjectRenderScriptRuntimeKernel(interpreter)));
5023 LoadSubCommand("context",
5024 CommandObjectSP(new CommandObjectRenderScriptRuntimeContext(
5029 new CommandObjectRenderScriptRuntimeAllocation(interpreter)));
5030 LoadSubCommand("scriptgroup",
5031 NewCommandObjectRenderScriptScriptGroup(interpreter));
5035 new CommandObjectRenderScriptRuntimeReduction(interpreter)));
5038 ~CommandObjectRenderScriptRuntime() override = default;
5041 void RenderScriptRuntime::Initiate() { assert(!m_initiated); }
5043 RenderScriptRuntime::RenderScriptRuntime(Process *process)
5044 : lldb_private::CPPLanguageRuntime(process), m_initiated(false),
5045 m_debuggerPresentFlagged(false), m_breakAllKernels(false),
5046 m_ir_passes(nullptr) {
5047 ModulesDidLoad(process->GetTarget().GetImages());
5050 lldb::CommandObjectSP RenderScriptRuntime::GetCommandObject(
5051 lldb_private::CommandInterpreter &interpreter) {
5052 return CommandObjectSP(new CommandObjectRenderScriptRuntime(interpreter));
5055 RenderScriptRuntime::~RenderScriptRuntime() = default;