1 //===-- RenderScriptRuntime.cpp ---------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
12 // Other libraries and framework includes
13 #include "llvm/ADT/StringSwitch.h"
16 #include "RenderScriptRuntime.h"
17 #include "RenderScriptScriptGroup.h"
19 #include "lldb/Breakpoint/StoppointCallbackContext.h"
20 #include "lldb/Core/ConstString.h"
21 #include "lldb/Core/Debugger.h"
22 #include "lldb/Core/Error.h"
23 #include "lldb/Core/Log.h"
24 #include "lldb/Core/PluginManager.h"
25 #include "lldb/Core/RegularExpression.h"
26 #include "lldb/Core/ValueObjectVariable.h"
27 #include "lldb/DataFormatters/DumpValueObjectOptions.h"
28 #include "lldb/Expression/UserExpression.h"
29 #include "lldb/Host/StringConvert.h"
30 #include "lldb/Interpreter/Args.h"
31 #include "lldb/Interpreter/CommandInterpreter.h"
32 #include "lldb/Interpreter/CommandObjectMultiword.h"
33 #include "lldb/Interpreter/CommandReturnObject.h"
34 #include "lldb/Interpreter/Options.h"
35 #include "lldb/Symbol/Function.h"
36 #include "lldb/Symbol/Symbol.h"
37 #include "lldb/Symbol/Type.h"
38 #include "lldb/Symbol/VariableList.h"
39 #include "lldb/Target/Process.h"
40 #include "lldb/Target/RegisterContext.h"
41 #include "lldb/Target/SectionLoadList.h"
42 #include "lldb/Target/Target.h"
43 #include "lldb/Target/Thread.h"
46 using namespace lldb_private;
47 using namespace lldb_renderscript;
49 #define FMT_COORD "(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ")"
53 // The empirical_type adds a basic level of validation to arbitrary data
54 // allowing us to track if data has been discovered and stored or not. An
55 // empirical_type will be marked as valid only if it has been explicitly
57 template <typename type_t> class empirical_type {
59 // Ctor. Contents is invalid when constructed.
60 empirical_type() : valid(false) {}
62 // Return true and copy contents to out if valid, else return false.
63 bool get(type_t &out) const {
69 // Return a pointer to the contents or nullptr if it was not valid.
70 const type_t *get() const { return valid ? &data : nullptr; }
72 // Assign data explicitly.
73 void set(const type_t in) {
78 // Mark contents as invalid.
79 void invalidate() { valid = false; }
81 // Returns true if this type contains valid data.
82 bool isValid() const { return valid; }
84 // Assignment operator.
85 empirical_type<type_t> &operator=(const type_t in) {
90 // Dereference operator returns contents.
91 // Warning: Will assert if not valid so use only when you know data is valid.
92 const type_t &operator*() const {
102 // ArgItem is used by the GetArgs() function when reading function arguments
105 enum { ePointer, eInt32, eInt64, eLong, eBool } type;
109 explicit operator uint64_t() const { return value; }
112 // Context structure to be passed into GetArgsXXX(), argument reading functions
115 RegisterContext *reg_ctx;
119 bool GetArgsX86(const GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
120 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
124 // get the current stack pointer
125 uint64_t sp = ctx.reg_ctx->GetSP();
127 for (size_t i = 0; i < num_args; ++i) {
128 ArgItem &arg = arg_list[i];
129 // advance up the stack by one argument
130 sp += sizeof(uint32_t);
131 // get the argument type size
132 size_t arg_size = sizeof(uint32_t);
133 // read the argument from memory
137 ctx.process->ReadMemory(sp, &arg.value, sizeof(uint32_t), err);
138 if (read != arg_size || !err.Success()) {
140 log->Printf("%s - error reading argument: %" PRIu64 " '%s'",
141 __FUNCTION__, uint64_t(i), err.AsCString());
148 bool GetArgsX86_64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
149 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
151 // number of arguments passed in registers
152 static const uint32_t args_in_reg = 6;
153 // register passing order
154 static const std::array<const char *, args_in_reg> reg_names{
155 {"rdi", "rsi", "rdx", "rcx", "r8", "r9"}};
156 // argument type to size mapping
157 static const std::array<size_t, 5> arg_size{{
167 // get the current stack pointer
168 uint64_t sp = ctx.reg_ctx->GetSP();
169 // step over the return address
170 sp += sizeof(uint64_t);
172 // check the stack alignment was correct (16 byte aligned)
173 if ((sp & 0xf) != 0x0) {
175 log->Printf("%s - stack misaligned", __FUNCTION__);
179 // find the start of arguments on the stack
180 uint64_t sp_offset = 0;
181 for (uint32_t i = args_in_reg; i < num_args; ++i) {
182 sp_offset += arg_size[arg_list[i].type];
184 // round up to multiple of 16
185 sp_offset = (sp_offset + 0xf) & 0xf;
188 for (size_t i = 0; i < num_args; ++i) {
189 bool success = false;
190 ArgItem &arg = arg_list[i];
191 // arguments passed in registers
192 if (i < args_in_reg) {
193 const RegisterInfo *reg =
194 ctx.reg_ctx->GetRegisterInfoByName(reg_names[i]);
195 RegisterValue reg_val;
196 if (ctx.reg_ctx->ReadRegister(reg, reg_val))
197 arg.value = reg_val.GetAsUInt64(0, &success);
199 // arguments passed on the stack
201 // get the argument type size
202 const size_t size = arg_size[arg_list[i].type];
203 // read the argument from memory
205 // note: due to little endian layout reading 4 or 8 bytes will give the
207 size_t read = ctx.process->ReadMemory(sp, &arg.value, size, err);
208 success = (err.Success() && read == size);
209 // advance past this argument
212 // fail if we couldn't read this argument
215 log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
216 __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
223 bool GetArgsArm(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
224 // number of arguments passed in registers
225 static const uint32_t args_in_reg = 4;
227 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
231 // get the current stack pointer
232 uint64_t sp = ctx.reg_ctx->GetSP();
234 for (size_t i = 0; i < num_args; ++i) {
235 bool success = false;
236 ArgItem &arg = arg_list[i];
237 // arguments passed in registers
238 if (i < args_in_reg) {
239 const RegisterInfo *reg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
240 RegisterValue reg_val;
241 if (ctx.reg_ctx->ReadRegister(reg, reg_val))
242 arg.value = reg_val.GetAsUInt32(0, &success);
244 // arguments passed on the stack
246 // get the argument type size
247 const size_t arg_size = sizeof(uint32_t);
250 // read this argument from memory
252 ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
253 success = (err.Success() && bytes_read == arg_size);
254 // advance the stack pointer
255 sp += sizeof(uint32_t);
257 // fail if we couldn't read this argument
260 log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
261 __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
268 bool GetArgsAarch64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
269 // number of arguments passed in registers
270 static const uint32_t args_in_reg = 8;
272 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
274 for (size_t i = 0; i < num_args; ++i) {
275 bool success = false;
276 ArgItem &arg = arg_list[i];
277 // arguments passed in registers
278 if (i < args_in_reg) {
279 const RegisterInfo *reg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
280 RegisterValue reg_val;
281 if (ctx.reg_ctx->ReadRegister(reg, reg_val))
282 arg.value = reg_val.GetAsUInt64(0, &success);
284 // arguments passed on the stack
287 log->Printf("%s - reading arguments spilled to stack not implemented",
290 // fail if we couldn't read this argument
293 log->Printf("%s - error reading argument: %" PRIu64, __FUNCTION__,
301 bool GetArgsMipsel(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
302 // number of arguments passed in registers
303 static const uint32_t args_in_reg = 4;
304 // register file offset to first argument
305 static const uint32_t reg_offset = 4;
307 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
311 // find offset to arguments on the stack (+16 to skip over a0-a3 shadow space)
312 uint64_t sp = ctx.reg_ctx->GetSP() + 16;
314 for (size_t i = 0; i < num_args; ++i) {
315 bool success = false;
316 ArgItem &arg = arg_list[i];
317 // arguments passed in registers
318 if (i < args_in_reg) {
319 const RegisterInfo *reg =
320 ctx.reg_ctx->GetRegisterInfoAtIndex(i + reg_offset);
321 RegisterValue reg_val;
322 if (ctx.reg_ctx->ReadRegister(reg, reg_val))
323 arg.value = reg_val.GetAsUInt64(0, &success);
325 // arguments passed on the stack
327 const size_t arg_size = sizeof(uint32_t);
330 ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
331 success = (err.Success() && bytes_read == arg_size);
332 // advance the stack pointer
335 // fail if we couldn't read this argument
338 log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
339 __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
346 bool GetArgsMips64el(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
347 // number of arguments passed in registers
348 static const uint32_t args_in_reg = 8;
349 // register file offset to first argument
350 static const uint32_t reg_offset = 4;
352 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
356 // get the current stack pointer
357 uint64_t sp = ctx.reg_ctx->GetSP();
359 for (size_t i = 0; i < num_args; ++i) {
360 bool success = false;
361 ArgItem &arg = arg_list[i];
362 // arguments passed in registers
363 if (i < args_in_reg) {
364 const RegisterInfo *reg =
365 ctx.reg_ctx->GetRegisterInfoAtIndex(i + reg_offset);
366 RegisterValue reg_val;
367 if (ctx.reg_ctx->ReadRegister(reg, reg_val))
368 arg.value = reg_val.GetAsUInt64(0, &success);
370 // arguments passed on the stack
372 // get the argument type size
373 const size_t arg_size = sizeof(uint64_t);
376 // read this argument from memory
378 ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
379 success = (err.Success() && bytes_read == arg_size);
380 // advance the stack pointer
383 // fail if we couldn't read this argument
386 log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s",
387 __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
394 bool GetArgs(ExecutionContext &exe_ctx, ArgItem *arg_list, size_t num_args) {
395 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
397 // verify that we have a target
398 if (!exe_ctx.GetTargetPtr()) {
400 log->Printf("%s - invalid target", __FUNCTION__);
404 GetArgsCtx ctx = {exe_ctx.GetRegisterContext(), exe_ctx.GetProcessPtr()};
405 assert(ctx.reg_ctx && ctx.process);
407 // dispatch based on architecture
408 switch (exe_ctx.GetTargetPtr()->GetArchitecture().GetMachine()) {
409 case llvm::Triple::ArchType::x86:
410 return GetArgsX86(ctx, arg_list, num_args);
412 case llvm::Triple::ArchType::x86_64:
413 return GetArgsX86_64(ctx, arg_list, num_args);
415 case llvm::Triple::ArchType::arm:
416 return GetArgsArm(ctx, arg_list, num_args);
418 case llvm::Triple::ArchType::aarch64:
419 return GetArgsAarch64(ctx, arg_list, num_args);
421 case llvm::Triple::ArchType::mipsel:
422 return GetArgsMipsel(ctx, arg_list, num_args);
424 case llvm::Triple::ArchType::mips64el:
425 return GetArgsMips64el(ctx, arg_list, num_args);
428 // unsupported architecture
431 "%s - architecture not supported: '%s'", __FUNCTION__,
432 exe_ctx.GetTargetRef().GetArchitecture().GetArchitectureName());
438 bool IsRenderScriptScriptModule(ModuleSP module) {
441 return module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"),
442 eSymbolTypeData) != nullptr;
445 bool ParseCoordinate(llvm::StringRef coord_s, RSCoordinate &coord) {
446 // takes an argument of the form 'num[,num][,num]'.
447 // Where 'coord_s' is a comma separated 1,2 or 3-dimensional coordinate
448 // with the whitespace trimmed.
449 // Missing coordinates are defaulted to zero.
450 // If parsing of any elements fails the contents of &coord are undefined
451 // and `false` is returned, `true` otherwise
453 RegularExpression regex;
454 RegularExpression::Match regex_match(3);
456 bool matched = false;
457 if (regex.Compile(llvm::StringRef("^([0-9]+),([0-9]+),([0-9]+)$")) &&
458 regex.Execute(coord_s, ®ex_match))
460 else if (regex.Compile(llvm::StringRef("^([0-9]+),([0-9]+)$")) &&
461 regex.Execute(coord_s, ®ex_match))
463 else if (regex.Compile(llvm::StringRef("^([0-9]+)$")) &&
464 regex.Execute(coord_s, ®ex_match))
470 auto get_index = [&](int idx, uint32_t &i) -> bool {
473 if (regex_match.GetMatchAtIndex(coord_s.str().c_str(), idx + 1, group))
474 return !llvm::StringRef(group).getAsInteger<uint32_t>(10, i);
478 return get_index(0, coord.x) && get_index(1, coord.y) &&
479 get_index(2, coord.z);
482 bool SkipPrologue(lldb::ModuleSP &module, Address &addr) {
483 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
485 uint32_t resolved_flags =
486 module->ResolveSymbolContextForAddress(addr, eSymbolContextFunction, sc);
487 if (resolved_flags & eSymbolContextFunction) {
489 const uint32_t offset = sc.function->GetPrologueByteSize();
490 ConstString name = sc.GetFunctionName();
494 log->Printf("%s: Prologue offset for %s is %" PRIu32, __FUNCTION__,
495 name.AsCString(), offset);
501 } // anonymous namespace
503 // The ScriptDetails class collects data associated with a single script
505 struct RenderScriptRuntime::ScriptDetails {
506 ~ScriptDetails() = default;
508 enum ScriptType { eScript, eScriptC };
510 // The derived type of the script.
511 empirical_type<ScriptType> type;
512 // The name of the original source file.
513 empirical_type<std::string> res_name;
514 // Path to script .so file on the device.
515 empirical_type<std::string> shared_lib;
516 // Directory where kernel objects are cached on device.
517 empirical_type<std::string> cache_dir;
518 // Pointer to the context which owns this script.
519 empirical_type<lldb::addr_t> context;
520 // Pointer to the script object itself.
521 empirical_type<lldb::addr_t> script;
524 // This Element class represents the Element object in RS, defining the type
525 // associated with an Allocation.
526 struct RenderScriptRuntime::Element {
527 // Taken from rsDefines.h
537 RS_KIND_INVALID = 100
540 // Taken from rsDefines.h
556 RS_TYPE_UNSIGNED_5_6_5,
557 RS_TYPE_UNSIGNED_5_5_5_1,
558 RS_TYPE_UNSIGNED_4_4_4_4,
564 RS_TYPE_ELEMENT = 1000,
570 RS_TYPE_PROGRAM_FRAGMENT,
571 RS_TYPE_PROGRAM_VERTEX,
572 RS_TYPE_PROGRAM_RASTER,
573 RS_TYPE_PROGRAM_STORE,
576 RS_TYPE_INVALID = 10000
579 std::vector<Element> children; // Child Element fields for structs
580 empirical_type<lldb::addr_t>
581 element_ptr; // Pointer to the RS Element of the Type
582 empirical_type<DataType>
583 type; // Type of each data pointer stored by the allocation
584 empirical_type<DataKind>
585 type_kind; // Defines pixel type if Allocation is created from an image
586 empirical_type<uint32_t>
587 type_vec_size; // Vector size of each data point, e.g '4' for uchar4
588 empirical_type<uint32_t> field_count; // Number of Subelements
589 empirical_type<uint32_t> datum_size; // Size of a single Element with padding
590 empirical_type<uint32_t> padding; // Number of padding bytes
591 empirical_type<uint32_t>
592 array_size; // Number of items in array, only needed for strucrs
593 ConstString type_name; // Name of type, only needed for structs
595 static const ConstString &
596 GetFallbackStructName(); // Print this as the type name of a struct Element
597 // If we can't resolve the actual struct name
599 bool ShouldRefresh() const {
600 const bool valid_ptr = element_ptr.isValid() && *element_ptr.get() != 0x0;
601 const bool valid_type =
602 type.isValid() && type_vec_size.isValid() && type_kind.isValid();
603 return !valid_ptr || !valid_type || !datum_size.isValid();
607 // This AllocationDetails class collects data associated with a single
608 // allocation instance.
609 struct RenderScriptRuntime::AllocationDetails {
624 // The FileHeader struct specifies the header we use for writing allocations
625 // to a binary file. Our format begins with the ASCII characters "RSAD",
626 // identifying the file as an allocation dump. Member variables dims and
627 // hdr_size are then written consecutively, immediately followed by an
628 // instance of the ElementHeader struct. Because Elements can contain
629 // subelements, there may be more than one instance of the ElementHeader
630 // struct. With this first instance being the root element, and the other
631 // instances being the root's descendants. To identify which instances are an
632 // ElementHeader's children, each struct is immediately followed by a sequence
633 // of consecutive offsets to the start of its child structs. These offsets are
634 // 4 bytes in size, and the 0 offset signifies no more children.
636 uint8_t ident[4]; // ASCII 'RSAD' identifying the file
637 uint32_t dims[3]; // Dimensions
638 uint16_t hdr_size; // Header size in bytes, including all element headers
641 struct ElementHeader {
642 uint16_t type; // DataType enum
643 uint32_t kind; // DataKind enum
644 uint32_t element_size; // Size of a single element, including padding
645 uint16_t vector_size; // Vector width
646 uint32_t array_size; // Number of elements in array
649 // Monotonically increasing from 1
652 // Maps Allocation DataType enum and vector size to printable strings
653 // using mapping from RenderScript numerical types summary documentation
654 static const char *RsDataTypeToString[][4];
656 // Maps Allocation DataKind enum to printable strings
657 static const char *RsDataKindToString[];
659 // Maps allocation types to format sizes for printing.
660 static const uint32_t RSTypeToFormat[][3];
662 // Give each allocation an ID as a way
663 // for commands to reference it.
666 // Allocation Element type
667 RenderScriptRuntime::Element element;
668 // Dimensions of the Allocation
669 empirical_type<Dimension> dimension;
670 // Pointer to address of the RS Allocation
671 empirical_type<lldb::addr_t> address;
672 // Pointer to the data held by the Allocation
673 empirical_type<lldb::addr_t> data_ptr;
674 // Pointer to the RS Type of the Allocation
675 empirical_type<lldb::addr_t> type_ptr;
676 // Pointer to the RS Context of the Allocation
677 empirical_type<lldb::addr_t> context;
678 // Size of the allocation
679 empirical_type<uint32_t> size;
680 // Stride between rows of the allocation
681 empirical_type<uint32_t> stride;
683 // Give each allocation an id, so we can reference it in user commands.
684 AllocationDetails() : id(ID++) {}
686 bool ShouldRefresh() const {
687 bool valid_ptrs = data_ptr.isValid() && *data_ptr.get() != 0x0;
688 valid_ptrs = valid_ptrs && type_ptr.isValid() && *type_ptr.get() != 0x0;
689 return !valid_ptrs || !dimension.isValid() || !size.isValid() ||
690 element.ShouldRefresh();
694 const ConstString &RenderScriptRuntime::Element::GetFallbackStructName() {
695 static const ConstString FallbackStructName("struct");
696 return FallbackStructName;
699 uint32_t RenderScriptRuntime::AllocationDetails::ID = 1;
701 const char *RenderScriptRuntime::AllocationDetails::RsDataKindToString[] = {
702 "User", "Undefined", "Undefined", "Undefined",
703 "Undefined", "Undefined", "Undefined", // Enum jumps from 0 to 7
704 "L Pixel", "A Pixel", "LA Pixel", "RGB Pixel",
705 "RGBA Pixel", "Pixel Depth", "YUV Pixel"};
707 const char *RenderScriptRuntime::AllocationDetails::RsDataTypeToString[][4] = {
708 {"None", "None", "None", "None"},
709 {"half", "half2", "half3", "half4"},
710 {"float", "float2", "float3", "float4"},
711 {"double", "double2", "double3", "double4"},
712 {"char", "char2", "char3", "char4"},
713 {"short", "short2", "short3", "short4"},
714 {"int", "int2", "int3", "int4"},
715 {"long", "long2", "long3", "long4"},
716 {"uchar", "uchar2", "uchar3", "uchar4"},
717 {"ushort", "ushort2", "ushort3", "ushort4"},
718 {"uint", "uint2", "uint3", "uint4"},
719 {"ulong", "ulong2", "ulong3", "ulong4"},
720 {"bool", "bool2", "bool3", "bool4"},
721 {"packed_565", "packed_565", "packed_565", "packed_565"},
722 {"packed_5551", "packed_5551", "packed_5551", "packed_5551"},
723 {"packed_4444", "packed_4444", "packed_4444", "packed_4444"},
724 {"rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4"},
725 {"rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3"},
726 {"rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2"},
729 {"RS Element", "RS Element", "RS Element", "RS Element"},
730 {"RS Type", "RS Type", "RS Type", "RS Type"},
731 {"RS Allocation", "RS Allocation", "RS Allocation", "RS Allocation"},
732 {"RS Sampler", "RS Sampler", "RS Sampler", "RS Sampler"},
733 {"RS Script", "RS Script", "RS Script", "RS Script"},
736 {"RS Mesh", "RS Mesh", "RS Mesh", "RS Mesh"},
737 {"RS Program Fragment", "RS Program Fragment", "RS Program Fragment",
738 "RS Program Fragment"},
739 {"RS Program Vertex", "RS Program Vertex", "RS Program Vertex",
740 "RS Program Vertex"},
741 {"RS Program Raster", "RS Program Raster", "RS Program Raster",
742 "RS Program Raster"},
743 {"RS Program Store", "RS Program Store", "RS Program Store",
745 {"RS Font", "RS Font", "RS Font", "RS Font"}};
747 // Used as an index into the RSTypeToFormat array elements
748 enum TypeToFormatIndex { eFormatSingle = 0, eFormatVector, eElementSize };
750 // { format enum of single element, format enum of element vector, size of
752 const uint32_t RenderScriptRuntime::AllocationDetails::RSTypeToFormat[][3] = {
754 {eFormatHex, eFormatHex, 1},
756 {eFormatFloat, eFormatVectorOfFloat16, 2},
758 {eFormatFloat, eFormatVectorOfFloat32, sizeof(float)},
760 {eFormatFloat, eFormatVectorOfFloat64, sizeof(double)},
762 {eFormatDecimal, eFormatVectorOfSInt8, sizeof(int8_t)},
764 {eFormatDecimal, eFormatVectorOfSInt16, sizeof(int16_t)},
766 {eFormatDecimal, eFormatVectorOfSInt32, sizeof(int32_t)},
768 {eFormatDecimal, eFormatVectorOfSInt64, sizeof(int64_t)},
769 // RS_TYPE_UNSIGNED_8
770 {eFormatDecimal, eFormatVectorOfUInt8, sizeof(uint8_t)},
771 // RS_TYPE_UNSIGNED_16
772 {eFormatDecimal, eFormatVectorOfUInt16, sizeof(uint16_t)},
773 // RS_TYPE_UNSIGNED_32
774 {eFormatDecimal, eFormatVectorOfUInt32, sizeof(uint32_t)},
775 // RS_TYPE_UNSIGNED_64
776 {eFormatDecimal, eFormatVectorOfUInt64, sizeof(uint64_t)},
778 {eFormatBoolean, eFormatBoolean, 1},
779 // RS_TYPE_UNSIGNED_5_6_5
780 {eFormatHex, eFormatHex, sizeof(uint16_t)},
781 // RS_TYPE_UNSIGNED_5_5_5_1
782 {eFormatHex, eFormatHex, sizeof(uint16_t)},
783 // RS_TYPE_UNSIGNED_4_4_4_4
784 {eFormatHex, eFormatHex, sizeof(uint16_t)},
785 // RS_TYPE_MATRIX_4X4
786 {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 16},
787 // RS_TYPE_MATRIX_3X3
788 {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 9},
789 // RS_TYPE_MATRIX_2X2
790 {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 4}};
792 //------------------------------------------------------------------
794 //------------------------------------------------------------------
796 RenderScriptRuntime::CreateInstance(Process *process,
797 lldb::LanguageType language) {
799 if (language == eLanguageTypeExtRenderScript)
800 return new RenderScriptRuntime(process);
805 // Callback with a module to search for matching symbols. We first check that
806 // the module contains RS kernels. Then look for a symbol which matches our
807 // kernel name. The breakpoint address is finally set using the address of this
809 Searcher::CallbackReturn
810 RSBreakpointResolver::SearchCallback(SearchFilter &filter,
811 SymbolContext &context, Address *, bool) {
812 ModuleSP module = context.module_sp;
814 if (!module || !IsRenderScriptScriptModule(module))
815 return Searcher::eCallbackReturnContinue;
817 // Attempt to set a breakpoint on the kernel name symbol within the module
818 // library. If it's not found, it's likely debug info is unavailable - try to
819 // set a breakpoint on <name>.expand.
820 const Symbol *kernel_sym =
821 module->FindFirstSymbolWithNameAndType(m_kernel_name, eSymbolTypeCode);
823 std::string kernel_name_expanded(m_kernel_name.AsCString());
824 kernel_name_expanded.append(".expand");
825 kernel_sym = module->FindFirstSymbolWithNameAndType(
826 ConstString(kernel_name_expanded.c_str()), eSymbolTypeCode);
830 Address bp_addr = kernel_sym->GetAddress();
831 if (filter.AddressPasses(bp_addr))
832 m_breakpoint->AddLocation(bp_addr);
835 return Searcher::eCallbackReturnContinue;
838 Searcher::CallbackReturn
839 RSReduceBreakpointResolver::SearchCallback(lldb_private::SearchFilter &filter,
840 lldb_private::SymbolContext &context,
842 // We need to have access to the list of reductions currently parsed, as
843 // reduce names don't actually exist as
844 // symbols in a module. They are only identifiable by parsing the .rs.info
845 // packet, or finding the expand symbol. We
846 // therefore need access to the list of parsed rs modules to properly resolve
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
967 // on 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 //------------------------------------------------------------------
1034 // PluginInterface protocol
1035 //------------------------------------------------------------------
1036 lldb_private::ConstString RenderScriptRuntime::GetPluginName() {
1037 return GetPluginNameStatic();
1040 uint32_t RenderScriptRuntime::GetPluginVersion() { return 1; }
1042 bool RenderScriptRuntime::IsVTableName(const char *name) { return false; }
1044 bool RenderScriptRuntime::GetDynamicTypeAndAddress(
1045 ValueObject &in_value, lldb::DynamicValueType use_dynamic,
1046 TypeAndOrName &class_type_or_name, Address &address,
1047 Value::ValueType &value_type) {
1052 RenderScriptRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name,
1053 ValueObject &static_value) {
1054 return type_and_or_name;
1057 bool RenderScriptRuntime::CouldHaveDynamicValue(ValueObject &in_value) {
1061 lldb::BreakpointResolverSP
1062 RenderScriptRuntime::CreateExceptionResolver(Breakpoint *bp, bool catch_bp,
1064 BreakpointResolverSP resolver_sp;
1068 const RenderScriptRuntime::HookDefn RenderScriptRuntime::s_runtimeHookDefns[] =
1071 {"rsdScriptInit", "_Z13rsdScriptInitPKN7android12renderscript7ContextEP"
1072 "NS0_7ScriptCEPKcS7_PKhjj",
1073 "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_"
1074 "7ScriptCEPKcS7_PKhmj",
1075 0, RenderScriptRuntime::eModuleKindDriver,
1076 &lldb_private::RenderScriptRuntime::CaptureScriptInit},
1077 {"rsdScriptInvokeForEachMulti",
1078 "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
1079 "_6ScriptEjPPKNS0_10AllocationEjPS6_PKvjPK12RsScriptCall",
1080 "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
1081 "_6ScriptEjPPKNS0_10AllocationEmPS6_PKvmPK12RsScriptCall",
1082 0, RenderScriptRuntime::eModuleKindDriver,
1083 &lldb_private::RenderScriptRuntime::CaptureScriptInvokeForEachMulti},
1084 {"rsdScriptSetGlobalVar", "_Z21rsdScriptSetGlobalVarPKN7android12render"
1085 "script7ContextEPKNS0_6ScriptEjPvj",
1086 "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_"
1088 0, RenderScriptRuntime::eModuleKindDriver,
1089 &lldb_private::RenderScriptRuntime::CaptureSetGlobalVar},
1092 {"rsdAllocationInit", "_Z17rsdAllocationInitPKN7android12renderscript7C"
1093 "ontextEPNS0_10AllocationEb",
1094 "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_"
1096 0, RenderScriptRuntime::eModuleKindDriver,
1097 &lldb_private::RenderScriptRuntime::CaptureAllocationInit},
1098 {"rsdAllocationRead2D",
1099 "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
1100 "10AllocationEjjj23RsAllocationCubemapFacejjPvjj",
1101 "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
1102 "10AllocationEjjj23RsAllocationCubemapFacejjPvmm",
1103 0, RenderScriptRuntime::eModuleKindDriver, nullptr},
1104 {"rsdAllocationDestroy", "_Z20rsdAllocationDestroyPKN7android12rendersc"
1105 "ript7ContextEPNS0_10AllocationE",
1106 "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_"
1108 0, RenderScriptRuntime::eModuleKindDriver,
1109 &lldb_private::RenderScriptRuntime::CaptureAllocationDestroy},
1111 // renderscript script groups
1112 {"rsdDebugHintScriptGroup2", "_ZN7android12renderscript21debugHintScrip"
1113 "tGroup2EPKcjPKPFvPK24RsExpandKernelDriver"
1115 "_ZN7android12renderscript21debugHintScriptGroup2EPKcjPKPFvPK24RsExpan"
1116 "dKernelDriverInfojjjEj",
1117 0, RenderScriptRuntime::eModuleKindImpl,
1118 &lldb_private::RenderScriptRuntime::CaptureDebugHintScriptGroup2}};
1120 const size_t RenderScriptRuntime::s_runtimeHookCount =
1121 sizeof(s_runtimeHookDefns) / sizeof(s_runtimeHookDefns[0]);
1123 bool RenderScriptRuntime::HookCallback(void *baton,
1124 StoppointCallbackContext *ctx,
1125 lldb::user_id_t break_id,
1126 lldb::user_id_t break_loc_id) {
1127 RuntimeHook *hook = (RuntimeHook *)baton;
1128 ExecutionContext exe_ctx(ctx->exe_ctx_ref);
1130 RenderScriptRuntime *lang_rt =
1131 (RenderScriptRuntime *)exe_ctx.GetProcessPtr()->GetLanguageRuntime(
1132 eLanguageTypeExtRenderScript);
1134 lang_rt->HookCallback(hook, exe_ctx);
1139 void RenderScriptRuntime::HookCallback(RuntimeHook *hook,
1140 ExecutionContext &exe_ctx) {
1141 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1144 log->Printf("%s - '%s'", __FUNCTION__, hook->defn->name);
1146 if (hook->defn->grabber) {
1147 (this->*(hook->defn->grabber))(hook, exe_ctx);
1151 void RenderScriptRuntime::CaptureDebugHintScriptGroup2(
1152 RuntimeHook *hook_info, ExecutionContext &context) {
1153 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1162 std::array<ArgItem, 4> args{{
1163 {ArgItem::ePointer, 0}, // const char *groupName
1164 {ArgItem::eInt32, 0}, // const uint32_t groupNameSize
1165 {ArgItem::ePointer, 0}, // const ExpandFuncTy *kernel
1166 {ArgItem::eInt32, 0}, // const uint32_t kernelCount
1169 if (!GetArgs(context, args.data(), args.size())) {
1171 log->Printf("%s - Error while reading the function parameters",
1175 log->Printf("%s - groupName : 0x%" PRIx64, __FUNCTION__,
1176 addr_t(args[eGroupName]));
1177 log->Printf("%s - groupNameSize: %" PRIu64, __FUNCTION__,
1178 uint64_t(args[eGroupNameSize]));
1179 log->Printf("%s - kernel : 0x%" PRIx64, __FUNCTION__,
1180 addr_t(args[eKernel]));
1181 log->Printf("%s - kernelCount : %" PRIu64, __FUNCTION__,
1182 uint64_t(args[eKernelCount]));
1185 // parse script group name
1186 ConstString group_name;
1189 const uint64_t len = uint64_t(args[eGroupNameSize]);
1190 std::unique_ptr<char[]> buffer(new char[uint32_t(len + 1)]);
1191 m_process->ReadMemory(addr_t(args[eGroupName]), buffer.get(), len, err);
1192 buffer.get()[len] = '\0';
1193 if (!err.Success()) {
1195 log->Printf("Error reading scriptgroup name from target");
1199 log->Printf("Extracted scriptgroup name %s", buffer.get());
1201 // write back the script group name
1202 group_name.SetCString(buffer.get());
1205 // create or access existing script group
1206 RSScriptGroupDescriptorSP group;
1208 // search for existing script group
1209 for (auto sg : m_scriptGroups) {
1210 if (sg->m_name == group_name) {
1216 group.reset(new RSScriptGroupDescriptor);
1217 group->m_name = group_name;
1218 m_scriptGroups.push_back(group);
1220 // already have this script group
1222 log->Printf("Attempt to add duplicate script group %s",
1223 group_name.AsCString());
1229 const uint32_t target_ptr_size = m_process->GetAddressByteSize();
1230 std::vector<addr_t> kernels;
1231 // parse kernel addresses in script group
1232 for (uint64_t i = 0; i < uint64_t(args[eKernelCount]); ++i) {
1233 RSScriptGroupDescriptor::Kernel kernel;
1234 // extract script group kernel addresses from the target
1235 const addr_t ptr_addr = addr_t(args[eKernel]) + i * target_ptr_size;
1236 uint64_t kernel_addr = 0;
1239 m_process->ReadMemory(ptr_addr, &kernel_addr, target_ptr_size, err);
1240 if (!err.Success() || read != target_ptr_size) {
1242 log->Printf("Error parsing kernel address %" PRIu64 " in script group",
1247 log->Printf("Extracted scriptgroup kernel address - 0x%" PRIx64,
1249 kernel.m_addr = kernel_addr;
1251 // try to resolve the associated kernel name
1252 if (!ResolveKernelName(kernel.m_addr, kernel.m_name)) {
1254 log->Printf("Parsed scriptgroup kernel %" PRIu64 " - 0x%" PRIx64, i,
1259 // try to find the non '.expand' function
1261 const llvm::StringRef expand(".expand");
1262 const llvm::StringRef name_ref = kernel.m_name.GetStringRef();
1263 if (name_ref.endswith(expand)) {
1264 const ConstString base_kernel(name_ref.drop_back(expand.size()));
1265 // verify this function is a valid kernel
1266 if (IsKnownKernel(base_kernel)) {
1267 kernel.m_name = base_kernel;
1269 log->Printf("%s - found non expand version '%s'", __FUNCTION__,
1270 base_kernel.GetCString());
1274 // add to a list of script group kernels we know about
1275 group->m_kernels.push_back(kernel);
1278 // Resolve any pending scriptgroup breakpoints
1280 Target &target = m_process->GetTarget();
1281 const BreakpointList &list = target.GetBreakpointList();
1282 const size_t num_breakpoints = list.GetSize();
1284 log->Printf("Resolving %zu breakpoints", num_breakpoints);
1285 for (size_t i = 0; i < num_breakpoints; ++i) {
1286 const BreakpointSP bp = list.GetBreakpointAtIndex(i);
1288 if (bp->MatchesName(group_name.AsCString())) {
1290 log->Printf("Found breakpoint with name %s",
1291 group_name.AsCString());
1292 bp->ResolveBreakpoint();
1299 void RenderScriptRuntime::CaptureScriptInvokeForEachMulti(
1300 RuntimeHook *hook, ExecutionContext &exe_ctx) {
1301 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1315 std::array<ArgItem, 9> args{{
1316 ArgItem{ArgItem::ePointer, 0}, // const Context *rsc
1317 ArgItem{ArgItem::ePointer, 0}, // Script *s
1318 ArgItem{ArgItem::eInt32, 0}, // uint32_t slot
1319 ArgItem{ArgItem::ePointer, 0}, // const Allocation **aIns
1320 ArgItem{ArgItem::eInt32, 0}, // size_t inLen
1321 ArgItem{ArgItem::ePointer, 0}, // Allocation *aout
1322 ArgItem{ArgItem::ePointer, 0}, // const void *usr
1323 ArgItem{ArgItem::eInt32, 0}, // size_t usrLen
1324 ArgItem{ArgItem::ePointer, 0}, // const RsScriptCall *sc
1327 bool success = GetArgs(exe_ctx, &args[0], args.size());
1330 log->Printf("%s - Error while reading the function parameters",
1335 const uint32_t target_ptr_size = m_process->GetAddressByteSize();
1337 std::vector<uint64_t> allocs;
1339 // traverse allocation list
1340 for (uint64_t i = 0; i < uint64_t(args[eRsInLen]); ++i) {
1341 // calculate offest to allocation pointer
1342 const addr_t addr = addr_t(args[eRsAIns]) + i * target_ptr_size;
1344 // Note: due to little endian layout, reading 32bits or 64bits into res
1345 // will give the correct results.
1346 uint64_t result = 0;
1347 size_t read = m_process->ReadMemory(addr, &result, target_ptr_size, err);
1348 if (read != target_ptr_size || !err.Success()) {
1351 "%s - Error while reading allocation list argument %" PRIu64,
1354 allocs.push_back(result);
1358 // if there is an output allocation track it
1359 if (uint64_t alloc_out = uint64_t(args[eRsAOut])) {
1360 allocs.push_back(alloc_out);
1363 // for all allocations we have found
1364 for (const uint64_t alloc_addr : allocs) {
1365 AllocationDetails *alloc = LookUpAllocation(alloc_addr);
1367 alloc = CreateAllocation(alloc_addr);
1370 // save the allocation address
1371 if (alloc->address.isValid()) {
1372 // check the allocation address we already have matches
1373 assert(*alloc->address.get() == alloc_addr);
1375 alloc->address = alloc_addr;
1380 if (alloc->context.isValid() &&
1381 *alloc->context.get() != addr_t(args[eRsContext]))
1382 log->Printf("%s - Allocation used by multiple contexts",
1385 alloc->context = addr_t(args[eRsContext]);
1389 // make sure we track this script object
1390 if (lldb_private::RenderScriptRuntime::ScriptDetails *script =
1391 LookUpScript(addr_t(args[eRsScript]), true)) {
1393 if (script->context.isValid() &&
1394 *script->context.get() != addr_t(args[eRsContext]))
1395 log->Printf("%s - Script used by multiple contexts", __FUNCTION__);
1397 script->context = addr_t(args[eRsContext]);
1401 void RenderScriptRuntime::CaptureSetGlobalVar(RuntimeHook *hook,
1402 ExecutionContext &context) {
1403 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1413 std::array<ArgItem, 5> args{{
1414 ArgItem{ArgItem::ePointer, 0}, // eRsContext
1415 ArgItem{ArgItem::ePointer, 0}, // eRsScript
1416 ArgItem{ArgItem::eInt32, 0}, // eRsId
1417 ArgItem{ArgItem::ePointer, 0}, // eRsData
1418 ArgItem{ArgItem::eInt32, 0}, // eRsLength
1421 bool success = GetArgs(context, &args[0], args.size());
1424 log->Printf("%s - error reading the function parameters.", __FUNCTION__);
1429 log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " slot %" PRIu64 " = 0x%" PRIx64
1430 ":%" PRIu64 "bytes.",
1431 __FUNCTION__, uint64_t(args[eRsContext]),
1432 uint64_t(args[eRsScript]), uint64_t(args[eRsId]),
1433 uint64_t(args[eRsData]), uint64_t(args[eRsLength]));
1435 addr_t script_addr = addr_t(args[eRsScript]);
1436 if (m_scriptMappings.find(script_addr) != m_scriptMappings.end()) {
1437 auto rsm = m_scriptMappings[script_addr];
1438 if (uint64_t(args[eRsId]) < rsm->m_globals.size()) {
1439 auto rsg = rsm->m_globals[uint64_t(args[eRsId])];
1440 log->Printf("%s - Setting of '%s' within '%s' inferred", __FUNCTION__,
1441 rsg.m_name.AsCString(),
1442 rsm->m_module->GetFileSpec().GetFilename().AsCString());
1448 void RenderScriptRuntime::CaptureAllocationInit(RuntimeHook *hook,
1449 ExecutionContext &exe_ctx) {
1450 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1452 enum { eRsContext, eRsAlloc, eRsForceZero };
1454 std::array<ArgItem, 3> args{{
1455 ArgItem{ArgItem::ePointer, 0}, // eRsContext
1456 ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
1457 ArgItem{ArgItem::eBool, 0}, // eRsForceZero
1460 bool success = GetArgs(exe_ctx, &args[0], args.size());
1463 log->Printf("%s - error while reading the function parameters",
1469 log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 ",0x%" PRIx64 " .",
1470 __FUNCTION__, uint64_t(args[eRsContext]),
1471 uint64_t(args[eRsAlloc]), uint64_t(args[eRsForceZero]));
1473 AllocationDetails *alloc = CreateAllocation(uint64_t(args[eRsAlloc]));
1475 alloc->context = uint64_t(args[eRsContext]);
1478 void RenderScriptRuntime::CaptureAllocationDestroy(RuntimeHook *hook,
1479 ExecutionContext &exe_ctx) {
1480 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1487 std::array<ArgItem, 2> args{{
1488 ArgItem{ArgItem::ePointer, 0}, // eRsContext
1489 ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
1492 bool success = GetArgs(exe_ctx, &args[0], args.size());
1495 log->Printf("%s - error while reading the function parameters.",
1501 log->Printf("%s - 0x%" PRIx64 ", 0x%" PRIx64 ".", __FUNCTION__,
1502 uint64_t(args[eRsContext]), uint64_t(args[eRsAlloc]));
1504 for (auto iter = m_allocations.begin(); iter != m_allocations.end(); ++iter) {
1505 auto &allocation_ap = *iter; // get the unique pointer
1506 if (allocation_ap->address.isValid() &&
1507 *allocation_ap->address.get() == addr_t(args[eRsAlloc])) {
1508 m_allocations.erase(iter);
1510 log->Printf("%s - deleted allocation entry.", __FUNCTION__);
1516 log->Printf("%s - couldn't find destroyed allocation.", __FUNCTION__);
1519 void RenderScriptRuntime::CaptureScriptInit(RuntimeHook *hook,
1520 ExecutionContext &exe_ctx) {
1521 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1524 Process *process = exe_ctx.GetProcessPtr();
1526 enum { eRsContext, eRsScript, eRsResNamePtr, eRsCachedDirPtr };
1528 std::array<ArgItem, 4> args{
1529 {ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0},
1530 ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0}}};
1531 bool success = GetArgs(exe_ctx, &args[0], args.size());
1534 log->Printf("%s - error while reading the function parameters.",
1539 std::string res_name;
1540 process->ReadCStringFromMemory(addr_t(args[eRsResNamePtr]), res_name, err);
1543 log->Printf("%s - error reading res_name: %s.", __FUNCTION__,
1547 std::string cache_dir;
1548 process->ReadCStringFromMemory(addr_t(args[eRsCachedDirPtr]), cache_dir, err);
1551 log->Printf("%s - error reading cache_dir: %s.", __FUNCTION__,
1556 log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " => '%s' at '%s' .",
1557 __FUNCTION__, uint64_t(args[eRsContext]),
1558 uint64_t(args[eRsScript]), res_name.c_str(), cache_dir.c_str());
1560 if (res_name.size() > 0) {
1562 strm.Printf("librs.%s.so", res_name.c_str());
1564 ScriptDetails *script = LookUpScript(addr_t(args[eRsScript]), true);
1566 script->type = ScriptDetails::eScriptC;
1567 script->cache_dir = cache_dir;
1568 script->res_name = res_name;
1569 script->shared_lib = strm.GetString();
1570 script->context = addr_t(args[eRsContext]);
1574 log->Printf("%s - '%s' tagged with context 0x%" PRIx64
1575 " and script 0x%" PRIx64 ".",
1576 __FUNCTION__, strm.GetData(), uint64_t(args[eRsContext]),
1577 uint64_t(args[eRsScript]));
1579 log->Printf("%s - resource name invalid, Script not tagged.", __FUNCTION__);
1583 void RenderScriptRuntime::LoadRuntimeHooks(lldb::ModuleSP module,
1585 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1591 Target &target = GetProcess()->GetTarget();
1592 const llvm::Triple::ArchType machine = target.GetArchitecture().GetMachine();
1594 if (machine != llvm::Triple::ArchType::x86 &&
1595 machine != llvm::Triple::ArchType::arm &&
1596 machine != llvm::Triple::ArchType::aarch64 &&
1597 machine != llvm::Triple::ArchType::mipsel &&
1598 machine != llvm::Triple::ArchType::mips64el &&
1599 machine != llvm::Triple::ArchType::x86_64) {
1601 log->Printf("%s - unable to hook runtime functions.", __FUNCTION__);
1605 const uint32_t target_ptr_size =
1606 target.GetArchitecture().GetAddressByteSize();
1608 std::array<bool, s_runtimeHookCount> hook_placed;
1609 hook_placed.fill(false);
1611 for (size_t idx = 0; idx < s_runtimeHookCount; idx++) {
1612 const HookDefn *hook_defn = &s_runtimeHookDefns[idx];
1613 if (hook_defn->kind != kind) {
1617 const char *symbol_name = (target_ptr_size == 4)
1618 ? hook_defn->symbol_name_m32
1619 : hook_defn->symbol_name_m64;
1621 const Symbol *sym = module->FindFirstSymbolWithNameAndType(
1622 ConstString(symbol_name), eSymbolTypeCode);
1625 log->Printf("%s - symbol '%s' related to the function %s not found",
1626 __FUNCTION__, symbol_name, hook_defn->name);
1631 addr_t addr = sym->GetLoadAddress(&target);
1632 if (addr == LLDB_INVALID_ADDRESS) {
1634 log->Printf("%s - unable to resolve the address of hook function '%s' "
1635 "with symbol '%s'.",
1636 __FUNCTION__, hook_defn->name, symbol_name);
1640 log->Printf("%s - function %s, address resolved at 0x%" PRIx64,
1641 __FUNCTION__, hook_defn->name, addr);
1644 RuntimeHookSP hook(new RuntimeHook());
1645 hook->address = addr;
1646 hook->defn = hook_defn;
1647 hook->bp_sp = target.CreateBreakpoint(addr, true, false);
1648 hook->bp_sp->SetCallback(HookCallback, hook.get(), true);
1649 m_runtimeHooks[addr] = hook;
1651 log->Printf("%s - successfully hooked '%s' in '%s' version %" PRIu64
1652 " at 0x%" PRIx64 ".",
1653 __FUNCTION__, hook_defn->name,
1654 module->GetFileSpec().GetFilename().AsCString(),
1655 (uint64_t)hook_defn->version, (uint64_t)addr);
1657 hook_placed[idx] = true;
1660 // log any unhooked function
1662 for (size_t i = 0; i < hook_placed.size(); ++i) {
1665 const HookDefn &hook_defn = s_runtimeHookDefns[i];
1666 if (hook_defn.kind != kind)
1668 log->Printf("%s - function %s was not hooked", __FUNCTION__,
1674 void RenderScriptRuntime::FixupScriptDetails(RSModuleDescriptorSP rsmodule_sp) {
1678 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1680 const ModuleSP module = rsmodule_sp->m_module;
1681 const FileSpec &file = module->GetPlatformFileSpec();
1683 // Iterate over all of the scripts that we currently know of.
1684 // Note: We cant push or pop to m_scripts here or it may invalidate rs_script.
1685 for (const auto &rs_script : m_scripts) {
1686 // Extract the expected .so file path for this script.
1687 std::string shared_lib;
1688 if (!rs_script->shared_lib.get(shared_lib))
1691 // Only proceed if the module that has loaded corresponds to this script.
1692 if (file.GetFilename() != ConstString(shared_lib.c_str()))
1695 // Obtain the script address which we use as a key.
1696 lldb::addr_t script;
1697 if (!rs_script->script.get(script))
1700 // If we have a script mapping for the current script.
1701 if (m_scriptMappings.find(script) != m_scriptMappings.end()) {
1702 // if the module we have stored is different to the one we just received.
1703 if (m_scriptMappings[script] != rsmodule_sp) {
1706 "%s - script %" PRIx64 " wants reassigned to new rsmodule '%s'.",
1707 __FUNCTION__, (uint64_t)script,
1708 rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
1711 // We don't have a script mapping for the current script.
1713 // Obtain the script resource name.
1714 std::string res_name;
1715 if (rs_script->res_name.get(res_name))
1716 // Set the modules resource name.
1717 rsmodule_sp->m_resname = res_name;
1718 // Add Script/Module pair to map.
1719 m_scriptMappings[script] = rsmodule_sp;
1722 "%s - script %" PRIx64 " associated with rsmodule '%s'.",
1723 __FUNCTION__, (uint64_t)script,
1724 rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
1729 // Uses the Target API to evaluate the expression passed as a parameter to the
1730 // function The result of that expression is returned an unsigned 64 bit int,
1731 // via the result* parameter. Function returns true on success, and false on
1733 bool RenderScriptRuntime::EvalRSExpression(const char *expr,
1734 StackFrame *frame_ptr,
1736 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1738 log->Printf("%s(%s)", __FUNCTION__, expr);
1740 ValueObjectSP expr_result;
1741 EvaluateExpressionOptions options;
1742 options.SetLanguage(lldb::eLanguageTypeC_plus_plus);
1743 // Perform the actual expression evaluation
1744 auto &target = GetProcess()->GetTarget();
1745 target.EvaluateExpression(expr, frame_ptr, expr_result, options);
1749 log->Printf("%s: couldn't evaluate expression.", __FUNCTION__);
1753 // The result of the expression is invalid
1754 if (!expr_result->GetError().Success()) {
1755 Error err = expr_result->GetError();
1756 // Expression returned is void, so this is actually a success
1757 if (err.GetError() == UserExpression::kNoResult) {
1759 log->Printf("%s - expression returned void.", __FUNCTION__);
1766 log->Printf("%s - error evaluating expression result: %s", __FUNCTION__,
1771 bool success = false;
1772 // We only read the result as an uint32_t.
1773 *result = expr_result->GetValueAsUnsigned(0, &success);
1777 log->Printf("%s - couldn't convert expression result to uint32_t",
1786 // Used to index expression format strings
1787 enum ExpressionStrings {
1788 eExprGetOffsetPtr = 0,
1797 eExprElementFieldCount,
1799 eExprSubelementsName,
1800 eExprSubelementsArrSize,
1802 _eExprLast // keep at the end, implicit size of the array runtime_expressions
1805 // max length of an expanded expression
1806 const int jit_max_expr_size = 512;
1808 // Retrieve the string to JIT for the given expression
1809 const char *JITTemplate(ExpressionStrings e) {
1810 // Format strings containing the expressions we may need to evaluate.
1811 static std::array<const char *, _eExprLast> runtime_expressions = {
1812 {// Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap)
1814 "Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocation"
1816 "(0x%" PRIx64 ", %" PRIu32 ", %" PRIu32 ", %" PRIu32 ", 0, 0)",
1818 // Type* rsaAllocationGetType(Context*, Allocation*)
1819 "(void*)rsaAllocationGetType(0x%" PRIx64 ", 0x%" PRIx64 ")",
1821 // rsaTypeGetNativeData(Context*, Type*, void* typeData, size) Pack the
1822 // data in the following way mHal.state.dimX; mHal.state.dimY;
1823 // mHal.state.dimZ; mHal.state.lodCount; mHal.state.faces; mElement; into
1824 // typeData Need to specify 32 or 64 bit for uint_t since this differs
1826 "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64
1827 ", 0x%" PRIx64 ", data, 6); data[0]", // X dim
1828 "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64
1829 ", 0x%" PRIx64 ", data, 6); data[1]", // Y dim
1830 "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64
1831 ", 0x%" PRIx64 ", data, 6); data[2]", // Z dim
1832 "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64
1833 ", 0x%" PRIx64 ", data, 6); data[5]", // Element ptr
1835 // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size)
1836 // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into
1838 "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64
1839 ", 0x%" PRIx64 ", data, 5); data[0]", // Type
1840 "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64
1841 ", 0x%" PRIx64 ", data, 5); data[1]", // Kind
1842 "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64
1843 ", 0x%" PRIx64 ", data, 5); data[3]", // Vector Size
1844 "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64
1845 ", 0x%" PRIx64 ", data, 5); data[4]", // Field Count
1847 // rsaElementGetSubElements(RsContext con, RsElement elem, uintptr_t
1848 // *ids, const char **names, size_t *arraySizes, uint32_t dataSize)
1849 // Needed for Allocations of structs to gather details about
1850 // fields/Subelements Element* of field
1851 "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1852 "]; size_t arr_size[%" PRIu32 "];"
1853 "(void*)rsaElementGetSubElements(0x%" PRIx64 ", 0x%" PRIx64
1854 ", ids, names, arr_size, %" PRIu32 "); ids[%" PRIu32 "]",
1857 "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1858 "]; size_t arr_size[%" PRIu32 "];"
1859 "(void*)rsaElementGetSubElements(0x%" PRIx64 ", 0x%" PRIx64
1860 ", ids, names, arr_size, %" PRIu32 "); names[%" PRIu32 "]",
1862 // Array size of field
1863 "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1864 "]; size_t arr_size[%" PRIu32 "];"
1865 "(void*)rsaElementGetSubElements(0x%" PRIx64 ", 0x%" PRIx64
1866 ", ids, names, arr_size, %" PRIu32 "); arr_size[%" PRIu32 "]"}};
1868 return runtime_expressions[e];
1870 } // end of the anonymous namespace
1872 // JITs the RS runtime for the internal data pointer of an allocation. Is passed
1873 // x,y,z coordinates for the pointer to a specific element. Then sets the
1874 // data_ptr member in Allocation with the result. Returns true on success, false
1876 bool RenderScriptRuntime::JITDataPointer(AllocationDetails *alloc,
1877 StackFrame *frame_ptr, uint32_t x,
1878 uint32_t y, uint32_t z) {
1879 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1881 if (!alloc->address.isValid()) {
1883 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
1887 const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
1888 char expr_buf[jit_max_expr_size];
1890 int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
1891 *alloc->address.get(), x, y, z);
1894 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1896 } else if (written >= jit_max_expr_size) {
1898 log->Printf("%s - expression too long.", __FUNCTION__);
1902 uint64_t result = 0;
1903 if (!EvalRSExpression(expr_buf, frame_ptr, &result))
1906 addr_t data_ptr = static_cast<lldb::addr_t>(result);
1907 alloc->data_ptr = data_ptr;
1912 // JITs the RS runtime for the internal pointer to the RS Type of an allocation
1913 // Then sets the type_ptr member in Allocation with the result. Returns true on
1914 // success, false otherwise
1915 bool RenderScriptRuntime::JITTypePointer(AllocationDetails *alloc,
1916 StackFrame *frame_ptr) {
1917 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1919 if (!alloc->address.isValid() || !alloc->context.isValid()) {
1921 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
1925 const char *fmt_str = JITTemplate(eExprAllocGetType);
1926 char expr_buf[jit_max_expr_size];
1928 int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
1929 *alloc->context.get(), *alloc->address.get());
1932 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1934 } else if (written >= jit_max_expr_size) {
1936 log->Printf("%s - expression too long.", __FUNCTION__);
1940 uint64_t result = 0;
1941 if (!EvalRSExpression(expr_buf, frame_ptr, &result))
1944 addr_t type_ptr = static_cast<lldb::addr_t>(result);
1945 alloc->type_ptr = type_ptr;
1950 // JITs the RS runtime for information about the dimensions and type of an
1951 // allocation Then sets dimension and element_ptr members in Allocation with the
1952 // result. Returns true on success, false otherwise
1953 bool RenderScriptRuntime::JITTypePacked(AllocationDetails *alloc,
1954 StackFrame *frame_ptr) {
1955 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1957 if (!alloc->type_ptr.isValid() || !alloc->context.isValid()) {
1959 log->Printf("%s - Failed to find allocation details.", __FUNCTION__);
1963 // Expression is different depending on if device is 32 or 64 bit
1964 uint32_t target_ptr_size =
1965 GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
1966 const uint32_t bits = target_ptr_size == 4 ? 32 : 64;
1968 // We want 4 elements from packed data
1969 const uint32_t num_exprs = 4;
1970 assert(num_exprs == (eExprTypeElemPtr - eExprTypeDimX + 1) &&
1971 "Invalid number of expressions");
1973 char expr_bufs[num_exprs][jit_max_expr_size];
1974 uint64_t results[num_exprs];
1976 for (uint32_t i = 0; i < num_exprs; ++i) {
1977 const char *fmt_str = JITTemplate(ExpressionStrings(eExprTypeDimX + i));
1978 int written = snprintf(expr_bufs[i], jit_max_expr_size, fmt_str, bits,
1979 *alloc->context.get(), *alloc->type_ptr.get());
1982 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1984 } else if (written >= jit_max_expr_size) {
1986 log->Printf("%s - expression too long.", __FUNCTION__);
1990 // Perform expression evaluation
1991 if (!EvalRSExpression(expr_bufs[i], frame_ptr, &results[i]))
1995 // Assign results to allocation members
1996 AllocationDetails::Dimension dims;
1997 dims.dim_1 = static_cast<uint32_t>(results[0]);
1998 dims.dim_2 = static_cast<uint32_t>(results[1]);
1999 dims.dim_3 = static_cast<uint32_t>(results[2]);
2000 alloc->dimension = dims;
2002 addr_t element_ptr = static_cast<lldb::addr_t>(results[3]);
2003 alloc->element.element_ptr = element_ptr;
2006 log->Printf("%s - dims (%" PRIu32 ", %" PRIu32 ", %" PRIu32
2007 ") Element*: 0x%" PRIx64 ".",
2008 __FUNCTION__, dims.dim_1, dims.dim_2, dims.dim_3, element_ptr);
2013 // JITs the RS runtime for information about the Element of an allocation Then
2014 // sets type, type_vec_size, field_count and type_kind members in Element with
2015 // the result. Returns true on success, false otherwise
2016 bool RenderScriptRuntime::JITElementPacked(Element &elem,
2017 const lldb::addr_t context,
2018 StackFrame *frame_ptr) {
2019 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2021 if (!elem.element_ptr.isValid()) {
2023 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
2027 // We want 4 elements from packed data
2028 const uint32_t num_exprs = 4;
2029 assert(num_exprs == (eExprElementFieldCount - eExprElementType + 1) &&
2030 "Invalid number of expressions");
2032 char expr_bufs[num_exprs][jit_max_expr_size];
2033 uint64_t results[num_exprs];
2035 for (uint32_t i = 0; i < num_exprs; i++) {
2036 const char *fmt_str = JITTemplate(ExpressionStrings(eExprElementType + i));
2037 int written = snprintf(expr_bufs[i], jit_max_expr_size, fmt_str, context,
2038 *elem.element_ptr.get());
2041 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
2043 } else if (written >= jit_max_expr_size) {
2045 log->Printf("%s - expression too long.", __FUNCTION__);
2049 // Perform expression evaluation
2050 if (!EvalRSExpression(expr_bufs[i], frame_ptr, &results[i]))
2054 // Assign results to allocation members
2055 elem.type = static_cast<RenderScriptRuntime::Element::DataType>(results[0]);
2057 static_cast<RenderScriptRuntime::Element::DataKind>(results[1]);
2058 elem.type_vec_size = static_cast<uint32_t>(results[2]);
2059 elem.field_count = static_cast<uint32_t>(results[3]);
2062 log->Printf("%s - data type %" PRIu32 ", pixel type %" PRIu32
2063 ", vector size %" PRIu32 ", field count %" PRIu32,
2064 __FUNCTION__, *elem.type.get(), *elem.type_kind.get(),
2065 *elem.type_vec_size.get(), *elem.field_count.get());
2067 // If this Element has subelements then JIT rsaElementGetSubElements() for
2068 // details about its fields
2069 if (*elem.field_count.get() > 0 && !JITSubelements(elem, context, frame_ptr))
2075 // JITs the RS runtime for information about the subelements/fields of a struct
2076 // allocation This is necessary for infering the struct type so we can pretty
2077 // print the allocation's contents. Returns true on success, false otherwise
2078 bool RenderScriptRuntime::JITSubelements(Element &elem,
2079 const lldb::addr_t context,
2080 StackFrame *frame_ptr) {
2081 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2083 if (!elem.element_ptr.isValid() || !elem.field_count.isValid()) {
2085 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
2089 const short num_exprs = 3;
2090 assert(num_exprs == (eExprSubelementsArrSize - eExprSubelementsId + 1) &&
2091 "Invalid number of expressions");
2093 char expr_buffer[jit_max_expr_size];
2096 // Iterate over struct fields.
2097 const uint32_t field_count = *elem.field_count.get();
2098 for (uint32_t field_index = 0; field_index < field_count; ++field_index) {
2100 for (uint32_t expr_index = 0; expr_index < num_exprs; ++expr_index) {
2101 const char *fmt_str =
2102 JITTemplate(ExpressionStrings(eExprSubelementsId + expr_index));
2103 int written = snprintf(expr_buffer, jit_max_expr_size, fmt_str,
2104 field_count, field_count, field_count, context,
2105 *elem.element_ptr.get(), field_count, field_index);
2108 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
2110 } else if (written >= jit_max_expr_size) {
2112 log->Printf("%s - expression too long.", __FUNCTION__);
2116 // Perform expression evaluation
2117 if (!EvalRSExpression(expr_buffer, frame_ptr, &results))
2121 log->Printf("%s - expr result 0x%" PRIx64 ".", __FUNCTION__, results);
2123 switch (expr_index) {
2124 case 0: // Element* of child
2125 child.element_ptr = static_cast<addr_t>(results);
2127 case 1: // Name of child
2129 lldb::addr_t address = static_cast<addr_t>(results);
2132 GetProcess()->ReadCStringFromMemory(address, name, err);
2134 child.type_name = ConstString(name);
2137 log->Printf("%s - warning: Couldn't read field name.",
2142 case 2: // Array size of child
2143 child.array_size = static_cast<uint32_t>(results);
2148 // We need to recursively JIT each Element field of the struct since
2149 // structs can be nested inside structs.
2150 if (!JITElementPacked(child, context, frame_ptr))
2152 elem.children.push_back(child);
2155 // Try to infer the name of the struct type so we can pretty print the
2156 // allocation contents.
2157 FindStructTypeName(elem, frame_ptr);
2162 // JITs the RS runtime for the address of the last element in the allocation.
2163 // The `elem_size` parameter represents the size of a single element, including
2164 // padding. Which is needed as an offset from the last element pointer. Using
2165 // this offset minus the starting address we can calculate the size of the
2166 // allocation. Returns true on success, false otherwise
2167 bool RenderScriptRuntime::JITAllocationSize(AllocationDetails *alloc,
2168 StackFrame *frame_ptr) {
2169 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2171 if (!alloc->address.isValid() || !alloc->dimension.isValid() ||
2172 !alloc->data_ptr.isValid() || !alloc->element.datum_size.isValid()) {
2174 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
2179 uint32_t dim_x = alloc->dimension.get()->dim_1;
2180 uint32_t dim_y = alloc->dimension.get()->dim_2;
2181 uint32_t dim_z = alloc->dimension.get()->dim_3;
2183 // Our plan of jitting the last element address doesn't seem to work for
2184 // struct Allocations` Instead try to infer the size ourselves without any
2185 // inter element padding.
2186 if (alloc->element.children.size() > 0) {
2194 alloc->size = dim_x * dim_y * dim_z * *alloc->element.datum_size.get();
2197 log->Printf("%s - inferred size of struct allocation %" PRIu32 ".",
2198 __FUNCTION__, *alloc->size.get());
2202 const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
2203 char expr_buf[jit_max_expr_size];
2205 // Calculate last element
2206 dim_x = dim_x == 0 ? 0 : dim_x - 1;
2207 dim_y = dim_y == 0 ? 0 : dim_y - 1;
2208 dim_z = dim_z == 0 ? 0 : dim_z - 1;
2210 int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
2211 *alloc->address.get(), dim_x, dim_y, dim_z);
2214 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
2216 } else if (written >= jit_max_expr_size) {
2218 log->Printf("%s - expression too long.", __FUNCTION__);
2222 uint64_t result = 0;
2223 if (!EvalRSExpression(expr_buf, frame_ptr, &result))
2226 addr_t mem_ptr = static_cast<lldb::addr_t>(result);
2227 // Find pointer to last element and add on size of an element
2228 alloc->size = static_cast<uint32_t>(mem_ptr - *alloc->data_ptr.get()) +
2229 *alloc->element.datum_size.get();
2234 // JITs the RS runtime for information about the stride between rows in the
2235 // allocation. This is done to detect padding, since allocated memory is 16-byte
2237 // Returns true on success, false otherwise
2238 bool RenderScriptRuntime::JITAllocationStride(AllocationDetails *alloc,
2239 StackFrame *frame_ptr) {
2240 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2242 if (!alloc->address.isValid() || !alloc->data_ptr.isValid()) {
2244 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
2248 const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
2249 char expr_buf[jit_max_expr_size];
2251 int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
2252 *alloc->address.get(), 0, 1, 0);
2255 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
2257 } else if (written >= jit_max_expr_size) {
2259 log->Printf("%s - expression too long.", __FUNCTION__);
2263 uint64_t result = 0;
2264 if (!EvalRSExpression(expr_buf, frame_ptr, &result))
2267 addr_t mem_ptr = static_cast<lldb::addr_t>(result);
2268 alloc->stride = static_cast<uint32_t>(mem_ptr - *alloc->data_ptr.get());
2273 // JIT all the current runtime info regarding an allocation
2274 bool RenderScriptRuntime::RefreshAllocation(AllocationDetails *alloc,
2275 StackFrame *frame_ptr) {
2276 // GetOffsetPointer()
2277 if (!JITDataPointer(alloc, frame_ptr))
2280 // rsaAllocationGetType()
2281 if (!JITTypePointer(alloc, frame_ptr))
2284 // rsaTypeGetNativeData()
2285 if (!JITTypePacked(alloc, frame_ptr))
2288 // rsaElementGetNativeData()
2289 if (!JITElementPacked(alloc->element, *alloc->context.get(), frame_ptr))
2292 // Sets the datum_size member in Element
2293 SetElementSize(alloc->element);
2295 // Use GetOffsetPointer() to infer size of the allocation
2296 if (!JITAllocationSize(alloc, frame_ptr))
2302 // Function attempts to set the type_name member of the paramaterised Element
2304 // This string should be the name of the struct type the Element represents.
2305 // We need this string for pretty printing the Element to users.
2306 void RenderScriptRuntime::FindStructTypeName(Element &elem,
2307 StackFrame *frame_ptr) {
2308 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2310 if (!elem.type_name.IsEmpty()) // Name already set
2313 elem.type_name = Element::GetFallbackStructName(); // Default type name if
2316 // Find all the global variables from the script rs modules
2317 VariableList var_list;
2318 for (auto module_sp : m_rsmodules)
2319 module_sp->m_module->FindGlobalVariables(
2320 RegularExpression(llvm::StringRef(".")), true, UINT32_MAX, var_list);
2322 // Iterate over all the global variables looking for one with a matching type
2324 // We make the assumption a match exists since there needs to be a global
2325 // variable to reflect the struct type back into java host code.
2326 for (uint32_t i = 0; i < var_list.GetSize(); ++i) {
2327 const VariableSP var_sp(var_list.GetVariableAtIndex(i));
2331 ValueObjectSP valobj_sp = ValueObjectVariable::Create(frame_ptr, var_sp);
2335 // Find the number of variable fields.
2336 // If it has no fields, or more fields than our Element, then it can't be
2337 // the struct we're looking for.
2338 // Don't check for equality since RS can add extra struct members for
2340 size_t num_children = valobj_sp->GetNumChildren();
2341 if (num_children > elem.children.size() || num_children == 0)
2344 // Iterate over children looking for members with matching field names.
2345 // If all the field names match, this is likely the struct we want.
2346 // TODO: This could be made more robust by also checking children data
2347 // sizes, or array size
2349 for (size_t i = 0; i < num_children; ++i) {
2350 ValueObjectSP child = valobj_sp->GetChildAtIndex(i, true);
2351 if (!child || (child->GetName() != elem.children[i].type_name)) {
2357 // RS can add extra struct members for padding in the format
2358 // '#rs_padding_[0-9]+'
2359 if (found && num_children < elem.children.size()) {
2360 const uint32_t size_diff = elem.children.size() - num_children;
2362 log->Printf("%s - %" PRIu32 " padding struct entries", __FUNCTION__,
2365 for (uint32_t i = 0; i < size_diff; ++i) {
2366 const ConstString &name = elem.children[num_children + i].type_name;
2367 if (strcmp(name.AsCString(), "#rs_padding") < 0)
2372 // We've found a global variable with matching type
2374 // Dereference since our Element type isn't a pointer.
2375 if (valobj_sp->IsPointerType()) {
2377 ValueObjectSP deref_valobj = valobj_sp->Dereference(err);
2379 valobj_sp = deref_valobj;
2382 // Save name of variable in Element.
2383 elem.type_name = valobj_sp->GetTypeName();
2385 log->Printf("%s - element name set to %s", __FUNCTION__,
2386 elem.type_name.AsCString());
2393 // Function sets the datum_size member of Element. Representing the size of a
2394 // single instance including padding.
2395 // Assumes the relevant allocation information has already been jitted.
2396 void RenderScriptRuntime::SetElementSize(Element &elem) {
2397 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2398 const Element::DataType type = *elem.type.get();
2399 assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
2400 "Invalid allocation type");
2402 const uint32_t vec_size = *elem.type_vec_size.get();
2403 uint32_t data_size = 0;
2404 uint32_t padding = 0;
2406 // Element is of a struct type, calculate size recursively.
2407 if ((type == Element::RS_TYPE_NONE) && (elem.children.size() > 0)) {
2408 for (Element &child : elem.children) {
2409 SetElementSize(child);
2410 const uint32_t array_size =
2411 child.array_size.isValid() ? *child.array_size.get() : 1;
2412 data_size += *child.datum_size.get() * array_size;
2415 // These have been packed already
2416 else if (type == Element::RS_TYPE_UNSIGNED_5_6_5 ||
2417 type == Element::RS_TYPE_UNSIGNED_5_5_5_1 ||
2418 type == Element::RS_TYPE_UNSIGNED_4_4_4_4) {
2419 data_size = AllocationDetails::RSTypeToFormat[type][eElementSize];
2420 } else if (type < Element::RS_TYPE_ELEMENT) {
2422 vec_size * AllocationDetails::RSTypeToFormat[type][eElementSize];
2424 padding = AllocationDetails::RSTypeToFormat[type][eElementSize];
2427 GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
2429 elem.padding = padding;
2430 elem.datum_size = data_size + padding;
2432 log->Printf("%s - element size set to %" PRIu32, __FUNCTION__,
2433 data_size + padding);
2436 // Given an allocation, this function copies the allocation contents from device
2437 // into a buffer on the heap.
2438 // Returning a shared pointer to the buffer containing the data.
2439 std::shared_ptr<uint8_t>
2440 RenderScriptRuntime::GetAllocationData(AllocationDetails *alloc,
2441 StackFrame *frame_ptr) {
2442 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2444 // JIT all the allocation details
2445 if (alloc->ShouldRefresh()) {
2447 log->Printf("%s - allocation details not calculated yet, jitting info",
2450 if (!RefreshAllocation(alloc, frame_ptr)) {
2452 log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
2457 assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2458 alloc->element.type_vec_size.isValid() && alloc->size.isValid() &&
2459 "Allocation information not available");
2461 // Allocate a buffer to copy data into
2462 const uint32_t size = *alloc->size.get();
2463 std::shared_ptr<uint8_t> buffer(new uint8_t[size]);
2466 log->Printf("%s - couldn't allocate a %" PRIu32 " byte buffer",
2467 __FUNCTION__, size);
2471 // Read the inferior memory
2473 lldb::addr_t data_ptr = *alloc->data_ptr.get();
2474 GetProcess()->ReadMemory(data_ptr, buffer.get(), size, err);
2477 log->Printf("%s - '%s' Couldn't read %" PRIu32
2478 " bytes of allocation data from 0x%" PRIx64,
2479 __FUNCTION__, err.AsCString(), size, data_ptr);
2486 // Function copies data from a binary file into an allocation.
2487 // There is a header at the start of the file, FileHeader, before the data
2489 // Information from this header is used to display warnings to the user about
2490 // incompatibilities
2491 bool RenderScriptRuntime::LoadAllocation(Stream &strm, const uint32_t alloc_id,
2493 StackFrame *frame_ptr) {
2494 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2496 // Find allocation with the given id
2497 AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
2502 log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__,
2503 *alloc->address.get());
2505 // JIT all the allocation details
2506 if (alloc->ShouldRefresh()) {
2508 log->Printf("%s - allocation details not calculated yet, jitting info.",
2511 if (!RefreshAllocation(alloc, frame_ptr)) {
2513 log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
2518 assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2519 alloc->element.type_vec_size.isValid() && alloc->size.isValid() &&
2520 alloc->element.datum_size.isValid() &&
2521 "Allocation information not available");
2523 // Check we can read from file
2524 FileSpec file(path, true);
2525 if (!file.Exists()) {
2526 strm.Printf("Error: File %s does not exist", path);
2531 if (!file.Readable()) {
2532 strm.Printf("Error: File %s does not have readable permissions", path);
2537 // Read file into data buffer
2538 DataBufferSP data_sp(file.ReadFileContents());
2540 // Cast start of buffer to FileHeader and use pointer to read metadata
2541 void *file_buf = data_sp->GetBytes();
2542 if (file_buf == nullptr ||
2543 data_sp->GetByteSize() < (sizeof(AllocationDetails::FileHeader) +
2544 sizeof(AllocationDetails::ElementHeader))) {
2545 strm.Printf("Error: File %s does not contain enough data for header", path);
2549 const AllocationDetails::FileHeader *file_header =
2550 static_cast<AllocationDetails::FileHeader *>(file_buf);
2552 // Check file starts with ascii characters "RSAD"
2553 if (memcmp(file_header->ident, "RSAD", 4)) {
2554 strm.Printf("Error: File doesn't contain identifier for an RS allocation "
2555 "dump. Are you sure this is the correct file?");
2560 // Look at the type of the root element in the header
2561 AllocationDetails::ElementHeader root_el_hdr;
2562 memcpy(&root_el_hdr, static_cast<uint8_t *>(file_buf) +
2563 sizeof(AllocationDetails::FileHeader),
2564 sizeof(AllocationDetails::ElementHeader));
2567 log->Printf("%s - header type %" PRIu32 ", element size %" PRIu32,
2568 __FUNCTION__, root_el_hdr.type, root_el_hdr.element_size);
2570 // Check if the target allocation and file both have the same number of bytes
2572 if (*alloc->element.datum_size.get() != root_el_hdr.element_size) {
2573 strm.Printf("Warning: Mismatched Element sizes - file %" PRIu32
2574 " bytes, allocation %" PRIu32 " bytes",
2575 root_el_hdr.element_size, *alloc->element.datum_size.get());
2579 // Check if the target allocation and file both have the same type
2580 const uint32_t alloc_type = static_cast<uint32_t>(*alloc->element.type.get());
2581 const uint32_t file_type = root_el_hdr.type;
2583 if (file_type > Element::RS_TYPE_FONT) {
2584 strm.Printf("Warning: File has unknown allocation type");
2586 } else if (alloc_type != file_type) {
2587 // Enum value isn't monotonous, so doesn't always index RsDataTypeToString
2589 uint32_t target_type_name_idx = alloc_type;
2590 uint32_t head_type_name_idx = file_type;
2591 if (alloc_type >= Element::RS_TYPE_ELEMENT &&
2592 alloc_type <= Element::RS_TYPE_FONT)
2593 target_type_name_idx = static_cast<Element::DataType>(
2594 (alloc_type - Element::RS_TYPE_ELEMENT) +
2595 Element::RS_TYPE_MATRIX_2X2 + 1);
2597 if (file_type >= Element::RS_TYPE_ELEMENT &&
2598 file_type <= Element::RS_TYPE_FONT)
2599 head_type_name_idx = static_cast<Element::DataType>(
2600 (file_type - Element::RS_TYPE_ELEMENT) + Element::RS_TYPE_MATRIX_2X2 +
2603 const char *head_type_name =
2604 AllocationDetails::RsDataTypeToString[head_type_name_idx][0];
2605 const char *target_type_name =
2606 AllocationDetails::RsDataTypeToString[target_type_name_idx][0];
2609 "Warning: Mismatched Types - file '%s' type, allocation '%s' type",
2610 head_type_name, target_type_name);
2614 // Advance buffer past header
2615 file_buf = static_cast<uint8_t *>(file_buf) + file_header->hdr_size;
2617 // Calculate size of allocation data in file
2618 size_t size = data_sp->GetByteSize() - file_header->hdr_size;
2620 // Check if the target allocation and file both have the same total data size.
2621 const uint32_t alloc_size = *alloc->size.get();
2622 if (alloc_size != size) {
2623 strm.Printf("Warning: Mismatched allocation sizes - file 0x%" PRIx64
2624 " bytes, allocation 0x%" PRIx32 " bytes",
2625 (uint64_t)size, alloc_size);
2627 // Set length to copy to minimum
2628 size = alloc_size < size ? alloc_size : size;
2631 // Copy file data from our buffer into the target allocation.
2632 lldb::addr_t alloc_data = *alloc->data_ptr.get();
2634 size_t written = GetProcess()->WriteMemory(alloc_data, file_buf, size, err);
2635 if (!err.Success() || written != size) {
2636 strm.Printf("Error: Couldn't write data to allocation %s", err.AsCString());
2641 strm.Printf("Contents of file '%s' read into allocation %" PRIu32, path,
2648 // Function takes as parameters a byte buffer, which will eventually be written
2649 // to file as the element header, an offset into that buffer, and an Element
2650 // that will be saved into the buffer at the parametrised offset.
2651 // Return value is the new offset after writing the element into the buffer.
2652 // Elements are saved to the file as the ElementHeader struct followed by
2653 // offsets to the structs of all the element's children.
2654 size_t RenderScriptRuntime::PopulateElementHeaders(
2655 const std::shared_ptr<uint8_t> header_buffer, size_t offset,
2656 const Element &elem) {
2657 // File struct for an element header with all the relevant details copied from
2658 // elem. We assume members are valid already.
2659 AllocationDetails::ElementHeader elem_header;
2660 elem_header.type = *elem.type.get();
2661 elem_header.kind = *elem.type_kind.get();
2662 elem_header.element_size = *elem.datum_size.get();
2663 elem_header.vector_size = *elem.type_vec_size.get();
2664 elem_header.array_size =
2665 elem.array_size.isValid() ? *elem.array_size.get() : 0;
2666 const size_t elem_header_size = sizeof(AllocationDetails::ElementHeader);
2668 // Copy struct into buffer and advance offset
2669 // We assume that header_buffer has been checked for nullptr before this
2671 memcpy(header_buffer.get() + offset, &elem_header, elem_header_size);
2672 offset += elem_header_size;
2674 // Starting offset of child ElementHeader struct
2675 size_t child_offset =
2676 offset + ((elem.children.size() + 1) * sizeof(uint32_t));
2677 for (const RenderScriptRuntime::Element &child : elem.children) {
2678 // Recursively populate the buffer with the element header structs of
2679 // children. Then save the offsets where they were set after the parent
2681 memcpy(header_buffer.get() + offset, &child_offset, sizeof(uint32_t));
2682 offset += sizeof(uint32_t);
2684 child_offset = PopulateElementHeaders(header_buffer, child_offset, child);
2687 // Zero indicates no more children
2688 memset(header_buffer.get() + offset, 0, sizeof(uint32_t));
2690 return child_offset;
2693 // Given an Element object this function returns the total size needed in the
2694 // file header to store the element's details. Taking into account the size of
2695 // the element header struct, plus the offsets to all the element's children.
2696 // Function is recursive so that the size of all ancestors is taken into
2698 size_t RenderScriptRuntime::CalculateElementHeaderSize(const Element &elem) {
2699 // Offsets to children plus zero terminator
2700 size_t size = (elem.children.size() + 1) * sizeof(uint32_t);
2701 // Size of header struct with type details
2702 size += sizeof(AllocationDetails::ElementHeader);
2704 // Calculate recursively for all descendants
2705 for (const Element &child : elem.children)
2706 size += CalculateElementHeaderSize(child);
2711 // Function copies allocation contents into a binary file. This file can then be
2712 // loaded later into a different allocation. There is a header, FileHeader,
2713 // before the allocation data containing meta-data.
2714 bool RenderScriptRuntime::SaveAllocation(Stream &strm, const uint32_t alloc_id,
2716 StackFrame *frame_ptr) {
2717 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2719 // Find allocation with the given id
2720 AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
2725 log->Printf("%s - found allocation 0x%" PRIx64 ".", __FUNCTION__,
2726 *alloc->address.get());
2728 // JIT all the allocation details
2729 if (alloc->ShouldRefresh()) {
2731 log->Printf("%s - allocation details not calculated yet, jitting info.",
2734 if (!RefreshAllocation(alloc, frame_ptr)) {
2736 log->Printf("%s - couldn't JIT allocation details.", __FUNCTION__);
2741 assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2742 alloc->element.type_vec_size.isValid() &&
2743 alloc->element.datum_size.get() &&
2744 alloc->element.type_kind.isValid() && alloc->dimension.isValid() &&
2745 "Allocation information not available");
2747 // Check we can create writable file
2748 FileSpec file_spec(path, true);
2749 File file(file_spec, File::eOpenOptionWrite | File::eOpenOptionCanCreate |
2750 File::eOpenOptionTruncate);
2752 strm.Printf("Error: Failed to open '%s' for writing", path);
2757 // Read allocation into buffer of heap memory
2758 const std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
2760 strm.Printf("Error: Couldn't read allocation data into buffer");
2765 // Create the file header
2766 AllocationDetails::FileHeader head;
2767 memcpy(head.ident, "RSAD", 4);
2768 head.dims[0] = static_cast<uint32_t>(alloc->dimension.get()->dim_1);
2769 head.dims[1] = static_cast<uint32_t>(alloc->dimension.get()->dim_2);
2770 head.dims[2] = static_cast<uint32_t>(alloc->dimension.get()->dim_3);
2772 const size_t element_header_size = CalculateElementHeaderSize(alloc->element);
2773 assert((sizeof(AllocationDetails::FileHeader) + element_header_size) <
2775 "Element header too large");
2776 head.hdr_size = static_cast<uint16_t>(sizeof(AllocationDetails::FileHeader) +
2777 element_header_size);
2779 // Write the file header
2780 size_t num_bytes = sizeof(AllocationDetails::FileHeader);
2782 log->Printf("%s - writing File Header, 0x%" PRIx64 " bytes", __FUNCTION__,
2783 (uint64_t)num_bytes);
2785 Error err = file.Write(&head, num_bytes);
2786 if (!err.Success()) {
2787 strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
2792 // Create the headers describing the element type of the allocation.
2793 std::shared_ptr<uint8_t> element_header_buffer(
2794 new uint8_t[element_header_size]);
2795 if (element_header_buffer == nullptr) {
2796 strm.Printf("Internal Error: Couldn't allocate %" PRIu64
2797 " bytes on the heap",
2798 (uint64_t)element_header_size);
2803 PopulateElementHeaders(element_header_buffer, 0, alloc->element);
2805 // Write headers for allocation element type to file
2806 num_bytes = element_header_size;
2808 log->Printf("%s - writing element headers, 0x%" PRIx64 " bytes.",
2809 __FUNCTION__, (uint64_t)num_bytes);
2811 err = file.Write(element_header_buffer.get(), num_bytes);
2812 if (!err.Success()) {
2813 strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
2818 // Write allocation data to file
2819 num_bytes = static_cast<size_t>(*alloc->size.get());
2821 log->Printf("%s - writing 0x%" PRIx64 " bytes", __FUNCTION__,
2822 (uint64_t)num_bytes);
2824 err = file.Write(buffer.get(), num_bytes);
2825 if (!err.Success()) {
2826 strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
2831 strm.Printf("Allocation written to file '%s'", path);
2836 bool RenderScriptRuntime::LoadModule(const lldb::ModuleSP &module_sp) {
2837 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2840 for (const auto &rs_module : m_rsmodules) {
2841 if (rs_module->m_module == module_sp) {
2842 // Check if the user has enabled automatically breaking on
2844 if (m_breakAllKernels)
2845 BreakOnModuleKernels(rs_module);
2850 bool module_loaded = false;
2851 switch (GetModuleKind(module_sp)) {
2852 case eModuleKindKernelObj: {
2853 RSModuleDescriptorSP module_desc;
2854 module_desc.reset(new RSModuleDescriptor(module_sp));
2855 if (module_desc->ParseRSInfo()) {
2856 m_rsmodules.push_back(module_desc);
2857 module_desc->WarnIfVersionMismatch(GetProcess()
2860 .GetAsyncOutputStream()
2862 module_loaded = true;
2864 if (module_loaded) {
2865 FixupScriptDetails(module_desc);
2869 case eModuleKindDriver: {
2870 if (!m_libRSDriver) {
2871 m_libRSDriver = module_sp;
2872 LoadRuntimeHooks(m_libRSDriver, RenderScriptRuntime::eModuleKindDriver);
2876 case eModuleKindImpl: {
2877 if (!m_libRSCpuRef) {
2878 m_libRSCpuRef = module_sp;
2879 LoadRuntimeHooks(m_libRSCpuRef, RenderScriptRuntime::eModuleKindImpl);
2883 case eModuleKindLibRS: {
2885 m_libRS = module_sp;
2886 static ConstString gDbgPresentStr("gDebuggerPresent");
2887 const Symbol *debug_present = m_libRS->FindFirstSymbolWithNameAndType(
2888 gDbgPresentStr, eSymbolTypeData);
2889 if (debug_present) {
2891 uint32_t flag = 0x00000001U;
2892 Target &target = GetProcess()->GetTarget();
2893 addr_t addr = debug_present->GetLoadAddress(&target);
2894 GetProcess()->WriteMemory(addr, &flag, sizeof(flag), err);
2895 if (err.Success()) {
2897 log->Printf("%s - debugger present flag set on debugee.",
2900 m_debuggerPresentFlagged = true;
2902 log->Printf("%s - error writing debugger present flags '%s' ",
2903 __FUNCTION__, err.AsCString());
2907 "%s - error writing debugger present flags - symbol not found",
2918 return module_loaded;
2923 void RenderScriptRuntime::Update() {
2924 if (m_rsmodules.size() > 0) {
2931 void RSModuleDescriptor::WarnIfVersionMismatch(lldb_private::Stream *s) const {
2935 if (m_slang_version.empty() || m_bcc_version.empty()) {
2936 s->PutCString("WARNING: Unknown bcc or slang (llvm-rs-cc) version; debug "
2937 "experience may be unreliable");
2939 } else if (m_slang_version != m_bcc_version) {
2940 s->Printf("WARNING: The debug info emitted by the slang frontend "
2941 "(llvm-rs-cc) used to build this module (%s) does not match the "
2942 "version of bcc used to generate the debug information (%s). "
2943 "This is an unsupported configuration and may result in a poor "
2944 "debugging experience; proceed with caution",
2945 m_slang_version.c_str(), m_bcc_version.c_str());
2950 bool RSModuleDescriptor::ParsePragmaCount(llvm::StringRef *lines,
2952 // Skip the pragma prototype line
2954 for (; n_lines--; ++lines) {
2955 const auto kv_pair = lines->split(" - ");
2956 m_pragmas[kv_pair.first.trim().str()] = kv_pair.second.trim().str();
2961 bool RSModuleDescriptor::ParseExportReduceCount(llvm::StringRef *lines,
2963 // The list of reduction kernels in the `.rs.info` symbol is of the form
2964 // "signature - accumulatordatasize - reduction_name - initializer_name -
2965 // accumulator_name - combiner_name -
2966 // outconverter_name - halter_name"
2967 // Where a function is not explicitly named by the user, or is not generated
2968 // by the compiler, it is named "." so the
2969 // dash separated list should always be 8 items long
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
3060 // The string is basic and is parsed on a line by line basis.
3061 bool RSModuleDescriptor::ParseRSInfo() {
3063 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3064 const Symbol *info_sym = m_module->FindFirstSymbolWithNameAndType(
3065 ConstString(".rs.info"), eSymbolTypeData);
3069 const addr_t addr = info_sym->GetAddressRef().GetFileAddress();
3070 if (addr == LLDB_INVALID_ADDRESS)
3073 const addr_t size = info_sym->GetByteSize();
3074 const FileSpec fs = m_module->GetFileSpec();
3076 const DataBufferSP buffer = fs.ReadFileContents(addr, size);
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 interested
3128 // in numeric fields at the moment
3130 if (val.getAsInteger(10, n_lines)) {
3132 log->Debug("Failed to parse non-numeric '.rs.info' section %s",
3133 line->str().c_str());
3136 if (info_lines.end() - (line + 1) < (ptrdiff_t)n_lines)
3139 bool success = false;
3142 success = ParseExportVarCount(line, n_lines);
3144 case eExportForEach:
3145 success = ParseExportForeachCount(line, n_lines);
3148 success = ParseExportReduceCount(line, n_lines);
3151 success = ParsePragmaCount(line, n_lines);
3154 success = ParseVersionInfo(line, n_lines);
3158 log->Printf("%s - skipping .rs.info field '%s'", __FUNCTION__,
3159 line->str().c_str());
3167 return info_lines.size() > 0;
3170 void RenderScriptRuntime::Status(Stream &strm) const {
3172 strm.Printf("Runtime Library discovered.");
3175 if (m_libRSDriver) {
3176 strm.Printf("Runtime Driver discovered.");
3179 if (m_libRSCpuRef) {
3180 strm.Printf("CPU Reference Implementation discovered.");
3184 if (m_runtimeHooks.size()) {
3185 strm.Printf("Runtime functions hooked:");
3187 for (auto b : m_runtimeHooks) {
3188 strm.Indent(b.second->defn->name);
3192 strm.Printf("Runtime is not hooked.");
3197 void RenderScriptRuntime::DumpContexts(Stream &strm) const {
3198 strm.Printf("Inferred RenderScript Contexts:");
3202 std::map<addr_t, uint64_t> contextReferences;
3204 // Iterate over all of the currently discovered scripts.
3205 // Note: We cant push or pop from m_scripts inside this loop or it may
3206 // invalidate script.
3207 for (const auto &script : m_scripts) {
3208 if (!script->context.isValid())
3210 lldb::addr_t context = *script->context;
3212 if (contextReferences.find(context) != contextReferences.end()) {
3213 contextReferences[context]++;
3215 contextReferences[context] = 1;
3219 for (const auto &cRef : contextReferences) {
3220 strm.Printf("Context 0x%" PRIx64 ": %" PRIu64 " script instances",
3221 cRef.first, cRef.second);
3227 void RenderScriptRuntime::DumpKernels(Stream &strm) const {
3228 strm.Printf("RenderScript Kernels:");
3231 for (const auto &module : m_rsmodules) {
3232 strm.Printf("Resource '%s':", module->m_resname.c_str());
3234 for (const auto &kernel : module->m_kernels) {
3235 strm.Indent(kernel.m_name.AsCString());
3242 RenderScriptRuntime::AllocationDetails *
3243 RenderScriptRuntime::FindAllocByID(Stream &strm, const uint32_t alloc_id) {
3244 AllocationDetails *alloc = nullptr;
3246 // See if we can find allocation using id as an index;
3247 if (alloc_id <= m_allocations.size() && alloc_id != 0 &&
3248 m_allocations[alloc_id - 1]->id == alloc_id) {
3249 alloc = m_allocations[alloc_id - 1].get();
3253 // Fallback to searching
3254 for (const auto &a : m_allocations) {
3255 if (a->id == alloc_id) {
3261 if (alloc == nullptr) {
3262 strm.Printf("Error: Couldn't find allocation with id matching %" PRIu32,
3270 // Prints the contents of an allocation to the output stream, which may be a
3272 bool RenderScriptRuntime::DumpAllocation(Stream &strm, StackFrame *frame_ptr,
3273 const uint32_t id) {
3274 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3276 // Check we can find the desired allocation
3277 AllocationDetails *alloc = FindAllocByID(strm, id);
3279 return false; // FindAllocByID() will print error message for us here
3282 log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__,
3283 *alloc->address.get());
3285 // Check we have information about the allocation, if not calculate it
3286 if (alloc->ShouldRefresh()) {
3288 log->Printf("%s - allocation details not calculated yet, jitting info.",
3291 // JIT all the allocation information
3292 if (!RefreshAllocation(alloc, frame_ptr)) {
3293 strm.Printf("Error: Couldn't JIT allocation details");
3299 // Establish format and size of each data element
3300 const uint32_t vec_size = *alloc->element.type_vec_size.get();
3301 const Element::DataType type = *alloc->element.type.get();
3303 assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
3304 "Invalid allocation type");
3306 lldb::Format format;
3307 if (type >= Element::RS_TYPE_ELEMENT)
3308 format = eFormatHex;
3310 format = vec_size == 1
3311 ? static_cast<lldb::Format>(
3312 AllocationDetails::RSTypeToFormat[type][eFormatSingle])
3313 : static_cast<lldb::Format>(
3314 AllocationDetails::RSTypeToFormat[type][eFormatVector]);
3316 const uint32_t data_size = *alloc->element.datum_size.get();
3319 log->Printf("%s - element size %" PRIu32 " bytes, including padding",
3320 __FUNCTION__, data_size);
3322 // Allocate a buffer to copy data into
3323 std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
3325 strm.Printf("Error: Couldn't read allocation data");
3330 // Calculate stride between rows as there may be padding at end of rows since
3331 // allocated memory is 16-byte aligned
3332 if (!alloc->stride.isValid()) {
3333 if (alloc->dimension.get()->dim_2 == 0) // We only have one dimension
3335 else if (!JITAllocationStride(alloc, frame_ptr)) {
3336 strm.Printf("Error: Couldn't calculate allocation row stride");
3341 const uint32_t stride = *alloc->stride.get();
3342 const uint32_t size = *alloc->size.get(); // Size of whole allocation
3343 const uint32_t padding =
3344 alloc->element.padding.isValid() ? *alloc->element.padding.get() : 0;
3346 log->Printf("%s - stride %" PRIu32 " bytes, size %" PRIu32
3347 " bytes, padding %" PRIu32,
3348 __FUNCTION__, stride, size, padding);
3350 // Find dimensions used to index loops, so need to be non-zero
3351 uint32_t dim_x = alloc->dimension.get()->dim_1;
3352 dim_x = dim_x == 0 ? 1 : dim_x;
3354 uint32_t dim_y = alloc->dimension.get()->dim_2;
3355 dim_y = dim_y == 0 ? 1 : dim_y;
3357 uint32_t dim_z = alloc->dimension.get()->dim_3;
3358 dim_z = dim_z == 0 ? 1 : dim_z;
3360 // Use data extractor to format output
3361 const uint32_t target_ptr_size =
3362 GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
3363 DataExtractor alloc_data(buffer.get(), size, GetProcess()->GetByteOrder(),
3366 uint32_t offset = 0; // Offset in buffer to next element to be printed
3367 uint32_t prev_row = 0; // Offset to the start of the previous row
3369 // Iterate over allocation dimensions, printing results to user
3370 strm.Printf("Data (X, Y, Z):");
3371 for (uint32_t z = 0; z < dim_z; ++z) {
3372 for (uint32_t y = 0; y < dim_y; ++y) {
3373 // Use stride to index start of next row.
3374 if (!(y == 0 && z == 0))
3375 offset = prev_row + stride;
3378 // Print each element in the row individually
3379 for (uint32_t x = 0; x < dim_x; ++x) {
3380 strm.Printf("\n(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ") = ", x, y, z);
3381 if ((type == Element::RS_TYPE_NONE) &&
3382 (alloc->element.children.size() > 0) &&
3383 (alloc->element.type_name != Element::GetFallbackStructName())) {
3384 // Here we are dumping an Element of struct type.
3385 // This is done using expression evaluation with the name of the
3386 // struct type and pointer to element.
3387 // Don't print the name of the resulting expression, since this will
3389 DumpValueObjectOptions expr_options;
3390 expr_options.SetHideName(true);
3392 // Setup expression as derefrencing a pointer cast to element address.
3393 char expr_char_buffer[jit_max_expr_size];
3395 snprintf(expr_char_buffer, jit_max_expr_size, "*(%s*) 0x%" PRIx64,
3396 alloc->element.type_name.AsCString(),
3397 *alloc->data_ptr.get() + offset);
3399 if (written < 0 || written >= jit_max_expr_size) {
3401 log->Printf("%s - error in snprintf().", __FUNCTION__);
3405 // Evaluate expression
3406 ValueObjectSP expr_result;
3407 GetProcess()->GetTarget().EvaluateExpression(expr_char_buffer,
3408 frame_ptr, expr_result);
3410 // Print the results to our stream.
3411 expr_result->Dump(strm, expr_options);
3413 alloc_data.Dump(&strm, offset, format, data_size - padding, 1, 1,
3414 LLDB_INVALID_ADDRESS, 0, 0);
3416 offset += data_size;
3425 // Function recalculates all our cached information about allocations by jitting
3426 // the RS runtime regarding each allocation we know about. Returns true if all
3427 // allocations could be recomputed, false otherwise.
3428 bool RenderScriptRuntime::RecomputeAllAllocations(Stream &strm,
3429 StackFrame *frame_ptr) {
3430 bool success = true;
3431 for (auto &alloc : m_allocations) {
3432 // JIT current allocation information
3433 if (!RefreshAllocation(alloc.get(), frame_ptr)) {
3434 strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32
3442 strm.Printf("All allocations successfully recomputed");
3448 // Prints information regarding currently loaded allocations. These details are
3449 // gathered by jitting the runtime, which has as latency. Index parameter
3450 // specifies a single allocation ID to print, or a zero value to print them all
3451 void RenderScriptRuntime::ListAllocations(Stream &strm, StackFrame *frame_ptr,
3452 const uint32_t index) {
3453 strm.Printf("RenderScript Allocations:");
3457 for (auto &alloc : m_allocations) {
3458 // index will only be zero if we want to print all allocations
3459 if (index != 0 && index != alloc->id)
3462 // JIT current allocation information
3463 if (alloc->ShouldRefresh() && !RefreshAllocation(alloc.get(), frame_ptr)) {
3464 strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32,
3470 strm.Printf("%" PRIu32 ":", alloc->id);
3474 strm.Indent("Context: ");
3475 if (!alloc->context.isValid())
3476 strm.Printf("unknown\n");
3478 strm.Printf("0x%" PRIx64 "\n", *alloc->context.get());
3480 strm.Indent("Address: ");
3481 if (!alloc->address.isValid())
3482 strm.Printf("unknown\n");
3484 strm.Printf("0x%" PRIx64 "\n", *alloc->address.get());
3486 strm.Indent("Data pointer: ");
3487 if (!alloc->data_ptr.isValid())
3488 strm.Printf("unknown\n");
3490 strm.Printf("0x%" PRIx64 "\n", *alloc->data_ptr.get());
3492 strm.Indent("Dimensions: ");
3493 if (!alloc->dimension.isValid())
3494 strm.Printf("unknown\n");
3496 strm.Printf("(%" PRId32 ", %" PRId32 ", %" PRId32 ")\n",
3497 alloc->dimension.get()->dim_1, alloc->dimension.get()->dim_2,
3498 alloc->dimension.get()->dim_3);
3500 strm.Indent("Data Type: ");
3501 if (!alloc->element.type.isValid() ||
3502 !alloc->element.type_vec_size.isValid())
3503 strm.Printf("unknown\n");
3505 const int vector_size = *alloc->element.type_vec_size.get();
3506 Element::DataType type = *alloc->element.type.get();
3508 if (!alloc->element.type_name.IsEmpty())
3509 strm.Printf("%s\n", alloc->element.type_name.AsCString());
3511 // Enum value isn't monotonous, so doesn't always index
3512 // RsDataTypeToString array
3513 if (type >= Element::RS_TYPE_ELEMENT && type <= Element::RS_TYPE_FONT)
3515 static_cast<Element::DataType>((type - Element::RS_TYPE_ELEMENT) +
3516 Element::RS_TYPE_MATRIX_2X2 + 1);
3518 if (type >= (sizeof(AllocationDetails::RsDataTypeToString) /
3519 sizeof(AllocationDetails::RsDataTypeToString[0])) ||
3520 vector_size > 4 || vector_size < 1)
3521 strm.Printf("invalid type\n");
3525 AllocationDetails::RsDataTypeToString[static_cast<uint32_t>(type)]
3530 strm.Indent("Data Kind: ");
3531 if (!alloc->element.type_kind.isValid())
3532 strm.Printf("unknown\n");
3534 const Element::DataKind kind = *alloc->element.type_kind.get();
3535 if (kind < Element::RS_KIND_USER || kind > Element::RS_KIND_PIXEL_YUV)
3536 strm.Printf("invalid kind\n");
3540 AllocationDetails::RsDataKindToString[static_cast<uint32_t>(kind)]);
3549 // Set breakpoints on every kernel found in RS module
3550 void RenderScriptRuntime::BreakOnModuleKernels(
3551 const RSModuleDescriptorSP rsmodule_sp) {
3552 for (const auto &kernel : rsmodule_sp->m_kernels) {
3553 // Don't set breakpoint on 'root' kernel
3554 if (strcmp(kernel.m_name.AsCString(), "root") == 0)
3557 CreateKernelBreakpoint(kernel.m_name);
3561 // Method is internally called by the 'kernel breakpoint all' command to enable
3562 // or disable breaking on all kernels. When do_break is true we want to enable
3563 // this functionality. When do_break is false we want to disable it.
3564 void RenderScriptRuntime::SetBreakAllKernels(bool do_break, TargetSP target) {
3566 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3568 InitSearchFilter(target);
3570 // Set breakpoints on all the kernels
3571 if (do_break && !m_breakAllKernels) {
3572 m_breakAllKernels = true;
3574 for (const auto &module : m_rsmodules)
3575 BreakOnModuleKernels(module);
3578 log->Printf("%s(True) - breakpoints set on all currently loaded kernels.",
3580 } else if (!do_break &&
3581 m_breakAllKernels) // Breakpoints won't be set on any new kernels.
3583 m_breakAllKernels = false;
3586 log->Printf("%s(False) - breakpoints no longer automatically set.",
3591 // Given the name of a kernel this function creates a breakpoint using our
3592 // own breakpoint resolver, and returns the Breakpoint shared pointer.
3594 RenderScriptRuntime::CreateKernelBreakpoint(const ConstString &name) {
3596 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3600 log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
3604 BreakpointResolverSP resolver_sp(new RSBreakpointResolver(nullptr, name));
3605 BreakpointSP bp = GetProcess()->GetTarget().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 if (!bp->AddName("RenderScriptKernel", err))
3613 log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
3620 RenderScriptRuntime::CreateReductionBreakpoint(const ConstString &name,
3623 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3627 log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
3631 BreakpointResolverSP resolver_sp(new RSReduceBreakpointResolver(
3632 nullptr, name, &m_rsmodules, kernel_types));
3633 BreakpointSP bp = GetProcess()->GetTarget().CreateBreakpoint(
3634 m_filtersp, resolver_sp, false, false, false);
3636 // Give RS breakpoints a specific name, so the user can manipulate them as a
3639 if (!bp->AddName("RenderScriptReduction", err))
3641 log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
3647 // Given an expression for a variable this function tries to calculate the
3648 // variable's value. If this is possible it returns true and sets the uint64_t
3649 // parameter to the variables unsigned value. Otherwise function returns false.
3650 bool RenderScriptRuntime::GetFrameVarAsUnsigned(const StackFrameSP frame_sp,
3651 const char *var_name,
3653 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3657 // Find variable in stack frame
3658 ValueObjectSP value_sp(frame_sp->GetValueForVariableExpressionPath(
3659 var_name, eNoDynamicValues,
3660 StackFrame::eExpressionPathOptionCheckPtrVsMember |
3661 StackFrame::eExpressionPathOptionsAllowDirectIVarAccess,
3663 if (!err.Success()) {
3665 log->Printf("%s - error, couldn't find '%s' in frame", __FUNCTION__,
3670 // Find the uint32_t value for the variable
3671 bool success = false;
3672 val = value_sp->GetValueAsUnsigned(0, &success);
3675 log->Printf("%s - error, couldn't parse '%s' as an uint32_t.",
3676 __FUNCTION__, var_name);
3683 // Function attempts to find the current coordinate of a kernel invocation by
3684 // investigating the values of frame variables in the .expand function. These
3685 // coordinates are returned via the coord array reference parameter. Returns
3686 // true if the coordinates could be found, and false otherwise.
3687 bool RenderScriptRuntime::GetKernelCoordinate(RSCoordinate &coord,
3688 Thread *thread_ptr) {
3689 static const char *const x_expr = "rsIndex";
3690 static const char *const y_expr = "p->current.y";
3691 static const char *const z_expr = "p->current.z";
3693 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3697 log->Printf("%s - Error, No thread pointer", __FUNCTION__);
3702 // Walk the call stack looking for a function whose name has the suffix
3703 // '.expand' and contains the variables we're looking for.
3704 for (uint32_t i = 0; i < thread_ptr->GetStackFrameCount(); ++i) {
3705 if (!thread_ptr->SetSelectedFrameByIndex(i))
3708 StackFrameSP frame_sp = thread_ptr->GetSelectedFrame();
3712 // Find the function name
3713 const SymbolContext sym_ctx = frame_sp->GetSymbolContext(false);
3714 const ConstString func_name = sym_ctx.GetFunctionName();
3719 log->Printf("%s - Inspecting function '%s'", __FUNCTION__,
3720 func_name.GetCString());
3722 // Check if function name has .expand suffix
3723 if (!func_name.GetStringRef().endswith(".expand"))
3727 log->Printf("%s - Found .expand function '%s'", __FUNCTION__,
3728 func_name.GetCString());
3730 // Get values for variables in .expand frame that tell us the current kernel
3733 bool found = GetFrameVarAsUnsigned(frame_sp, x_expr, x) &&
3734 GetFrameVarAsUnsigned(frame_sp, y_expr, y) &&
3735 GetFrameVarAsUnsigned(frame_sp, z_expr, z);
3738 // The RenderScript runtime uses uint32_t for these vars. If they're not
3739 // within bounds, our frame parsing is garbage
3740 assert(x <= UINT32_MAX && y <= UINT32_MAX && z <= UINT32_MAX);
3741 coord.x = (uint32_t)x;
3742 coord.y = (uint32_t)y;
3743 coord.z = (uint32_t)z;
3750 // Callback when a kernel breakpoint hits and we're looking for a specific
3751 // coordinate. Baton parameter contains a pointer to the target coordinate we
3752 // want to break on.
3753 // Function then checks the .expand frame for the current coordinate and breaks
3754 // to user if it matches.
3755 // Parameter 'break_id' is the id of the Breakpoint which made the callback.
3756 // Parameter 'break_loc_id' is the id for the BreakpointLocation which was hit,
3757 // a single logical breakpoint can have multiple addresses.
3758 bool RenderScriptRuntime::KernelBreakpointHit(void *baton,
3759 StoppointCallbackContext *ctx,
3761 user_id_t break_loc_id) {
3763 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3766 "Error: null baton in conditional kernel breakpoint callback");
3768 // Coordinate we want to stop on
3769 RSCoordinate target_coord = *static_cast<RSCoordinate *>(baton);
3772 log->Printf("%s - Break ID %" PRIu64 ", " FMT_COORD, __FUNCTION__, break_id,
3773 target_coord.x, target_coord.y, target_coord.z);
3775 // Select current thread
3776 ExecutionContext context(ctx->exe_ctx_ref);
3777 Thread *thread_ptr = context.GetThreadPtr();
3778 assert(thread_ptr && "Null thread pointer");
3780 // Find current kernel invocation from .expand frame variables
3781 RSCoordinate current_coord{};
3782 if (!GetKernelCoordinate(current_coord, thread_ptr)) {
3784 log->Printf("%s - Error, couldn't select .expand stack frame",
3790 log->Printf("%s - " FMT_COORD, __FUNCTION__, current_coord.x,
3791 current_coord.y, current_coord.z);
3793 // Check if the current kernel invocation coordinate matches our target
3795 if (target_coord == current_coord) {
3797 log->Printf("%s, BREAKING " FMT_COORD, __FUNCTION__, current_coord.x,
3798 current_coord.y, current_coord.z);
3800 BreakpointSP breakpoint_sp =
3801 context.GetTargetPtr()->GetBreakpointByID(break_id);
3802 assert(breakpoint_sp != nullptr &&
3803 "Error: Couldn't find breakpoint matching break id for callback");
3804 breakpoint_sp->SetEnabled(false); // Optimise since conditional breakpoint
3805 // should only be hit once.
3809 // No match on coordinate
3813 void RenderScriptRuntime::SetConditional(BreakpointSP bp, Stream &messages,
3814 const RSCoordinate &coord) {
3815 messages.Printf("Conditional kernel breakpoint on coordinate " FMT_COORD,
3816 coord.x, coord.y, coord.z);
3819 // Allocate memory for the baton, and copy over coordinate
3820 RSCoordinate *baton = new RSCoordinate(coord);
3822 // Create a callback that will be invoked every time the breakpoint is hit.
3823 // The baton object passed to the handler is the target coordinate we want to
3825 bp->SetCallback(KernelBreakpointHit, baton, true);
3827 // Store a shared pointer to the baton, so the memory will eventually be
3828 // cleaned up after destruction
3829 m_conditional_breaks[bp->GetID()] = std::unique_ptr<RSCoordinate>(baton);
3832 // Tries to set a breakpoint on the start of a kernel, resolved using the kernel
3833 // name. Argument 'coords', represents a three dimensional coordinate which can
3835 // used to specify a single kernel instance to break on. If this is set then we
3837 // 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(const 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 BreakpointSP bp = GetProcess()->GetTarget().CreateBreakpoint(
3876 m_filtersp, resolver_sp, false, false, false);
3877 // Give RS breakpoints a specific name, so the user can manipulate them as a
3880 if (!bp->AddName(name.AsCString(), err))
3882 log->Printf("%s - error setting break name, '%s'.", __FUNCTION__,
3884 // ask the breakpoint to resolve itself
3885 bp->ResolveBreakpoint();
3889 bool RenderScriptRuntime::PlaceBreakpointOnScriptGroup(TargetSP target,
3891 const ConstString &name,
3893 InitSearchFilter(target);
3894 BreakpointSP bp = CreateScriptGroupBreakpoint(name, multi);
3896 bp->GetDescription(&strm, lldb::eDescriptionLevelInitial, false);
3900 bool RenderScriptRuntime::PlaceBreakpointOnReduction(TargetSP target,
3902 const char *reduce_name,
3903 const RSCoordinate *coord,
3908 InitSearchFilter(target);
3910 CreateReductionBreakpoint(ConstString(reduce_name), kernel_types);
3915 SetConditional(bp, messages, *coord);
3917 bp->GetDescription(&messages, lldb::eDescriptionLevelInitial, false);
3922 void RenderScriptRuntime::DumpModules(Stream &strm) const {
3923 strm.Printf("RenderScript Modules:");
3926 for (const auto &module : m_rsmodules) {
3932 RenderScriptRuntime::ScriptDetails *
3933 RenderScriptRuntime::LookUpScript(addr_t address, bool create) {
3934 for (const auto &s : m_scripts) {
3935 if (s->script.isValid())
3936 if (*s->script == address)
3940 std::unique_ptr<ScriptDetails> s(new ScriptDetails);
3941 s->script = address;
3942 m_scripts.push_back(std::move(s));
3943 return m_scripts.back().get();
3948 RenderScriptRuntime::AllocationDetails *
3949 RenderScriptRuntime::LookUpAllocation(addr_t address) {
3950 for (const auto &a : m_allocations) {
3951 if (a->address.isValid())
3952 if (*a->address == address)
3958 RenderScriptRuntime::AllocationDetails *
3959 RenderScriptRuntime::CreateAllocation(addr_t address) {
3960 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
3962 // Remove any previous allocation which contains the same address
3963 auto it = m_allocations.begin();
3964 while (it != m_allocations.end()) {
3965 if (*((*it)->address) == address) {
3967 log->Printf("%s - Removing allocation id: %d, address: 0x%" PRIx64,
3968 __FUNCTION__, (*it)->id, address);
3970 it = m_allocations.erase(it);
3976 std::unique_ptr<AllocationDetails> a(new AllocationDetails);
3977 a->address = address;
3978 m_allocations.push_back(std::move(a));
3979 return m_allocations.back().get();
3982 bool RenderScriptRuntime::ResolveKernelName(lldb::addr_t kernel_addr,
3983 ConstString &name) {
3984 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS);
3986 Target &target = GetProcess()->GetTarget();
3988 // RenderScript module
3989 if (!target.GetSectionLoadList().ResolveLoadAddress(kernel_addr, resolved)) {
3991 log->Printf("%s: unable to resolve 0x%" PRIx64 " to a loaded symbol",
3992 __FUNCTION__, kernel_addr);
3996 Symbol *sym = resolved.CalculateSymbolContextSymbol();
4000 name = sym->GetName();
4001 assert(IsRenderScriptModule(resolved.CalculateSymbolContextModule()));
4003 log->Printf("%s: 0x%" PRIx64 " resolved to the symbol '%s'", __FUNCTION__,
4004 kernel_addr, name.GetCString());
4008 void RSModuleDescriptor::Dump(Stream &strm) const {
4009 int indent = strm.GetIndentLevel();
4012 m_module->GetFileSpec().Dump(&strm);
4013 strm.Indent(m_module->GetNumCompileUnits() ? "Debug info loaded."
4014 : "Debug info does not exist.");
4019 strm.Printf("Globals: %" PRIu64, static_cast<uint64_t>(m_globals.size()));
4022 for (const auto &global : m_globals) {
4028 strm.Printf("Kernels: %" PRIu64, static_cast<uint64_t>(m_kernels.size()));
4031 for (const auto &kernel : m_kernels) {
4037 strm.Printf("Pragmas: %" PRIu64, static_cast<uint64_t>(m_pragmas.size()));
4040 for (const auto &key_val : m_pragmas) {
4042 strm.Printf("%s: %s", key_val.first.c_str(), key_val.second.c_str());
4048 strm.Printf("Reductions: %" PRIu64,
4049 static_cast<uint64_t>(m_reductions.size()));
4052 for (const auto &reduction : m_reductions) {
4053 reduction.Dump(strm);
4056 strm.SetIndentLevel(indent);
4059 void RSGlobalDescriptor::Dump(Stream &strm) const {
4060 strm.Indent(m_name.AsCString());
4061 VariableList var_list;
4062 m_module->m_module->FindGlobalVariables(m_name, nullptr, true, 1U, var_list);
4063 if (var_list.GetSize() == 1) {
4064 auto var = var_list.GetVariableAtIndex(0);
4065 auto type = var->GetType();
4068 type->DumpTypeName(&strm);
4070 strm.Printf(" - Unknown Type");
4073 strm.Printf(" - variable identified, but not found in binary");
4074 const Symbol *s = m_module->m_module->FindFirstSymbolWithNameAndType(
4075 m_name, eSymbolTypeData);
4077 strm.Printf(" (symbol exists) ");
4084 void RSKernelDescriptor::Dump(Stream &strm) const {
4085 strm.Indent(m_name.AsCString());
4089 void RSReductionDescriptor::Dump(lldb_private::Stream &stream) const {
4090 stream.Indent(m_reduce_name.AsCString());
4091 stream.IndentMore();
4094 stream.Printf("accumulator: %s", m_accum_name.AsCString());
4097 stream.Printf("initializer: %s", m_init_name.AsCString());
4100 stream.Printf("combiner: %s", m_comb_name.AsCString());
4103 stream.Printf("outconverter: %s", m_outc_name.AsCString());
4105 // XXX This is currently unspecified by RenderScript, and unused
4107 // stream.Printf("halter: '%s'", m_init_name.AsCString());
4109 stream.IndentLess();
4112 class CommandObjectRenderScriptRuntimeModuleDump : public CommandObjectParsed {
4114 CommandObjectRenderScriptRuntimeModuleDump(CommandInterpreter &interpreter)
4115 : CommandObjectParsed(
4116 interpreter, "renderscript module dump",
4117 "Dumps renderscript specific information for all modules.",
4118 "renderscript module dump",
4119 eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
4121 ~CommandObjectRenderScriptRuntimeModuleDump() override = default;
4123 bool DoExecute(Args &command, CommandReturnObject &result) override {
4124 RenderScriptRuntime *runtime =
4125 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4126 eLanguageTypeExtRenderScript);
4127 runtime->DumpModules(result.GetOutputStream());
4128 result.SetStatus(eReturnStatusSuccessFinishResult);
4133 class CommandObjectRenderScriptRuntimeModule : public CommandObjectMultiword {
4135 CommandObjectRenderScriptRuntimeModule(CommandInterpreter &interpreter)
4136 : CommandObjectMultiword(interpreter, "renderscript module",
4137 "Commands that deal with RenderScript modules.",
4140 "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleDump(
4144 ~CommandObjectRenderScriptRuntimeModule() override = default;
4147 class CommandObjectRenderScriptRuntimeKernelList : public CommandObjectParsed {
4149 CommandObjectRenderScriptRuntimeKernelList(CommandInterpreter &interpreter)
4150 : CommandObjectParsed(
4151 interpreter, "renderscript kernel list",
4152 "Lists renderscript kernel names and associated script resources.",
4153 "renderscript kernel list",
4154 eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
4156 ~CommandObjectRenderScriptRuntimeKernelList() override = default;
4158 bool DoExecute(Args &command, CommandReturnObject &result) override {
4159 RenderScriptRuntime *runtime =
4160 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4161 eLanguageTypeExtRenderScript);
4162 runtime->DumpKernels(result.GetOutputStream());
4163 result.SetStatus(eReturnStatusSuccessFinishResult);
4168 static OptionDefinition g_renderscript_reduction_bp_set_options[] = {
4169 {LLDB_OPT_SET_1, false, "function-role", 't',
4170 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeOneLiner,
4171 "Break on a comma separated set of reduction kernel types "
4172 "(accumulator,outcoverter,combiner,initializer"},
4173 {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument,
4174 nullptr, nullptr, 0, eArgTypeValue,
4175 "Set a breakpoint on a single invocation of the kernel with specified "
4177 "Coordinate takes the form 'x[,y][,z] where x,y,z are positive "
4178 "integers representing kernel dimensions. "
4179 "Any unset dimensions will be defaulted to zero."}};
4181 class CommandObjectRenderScriptRuntimeReductionBreakpointSet
4182 : public CommandObjectParsed {
4184 CommandObjectRenderScriptRuntimeReductionBreakpointSet(
4185 CommandInterpreter &interpreter)
4186 : CommandObjectParsed(
4187 interpreter, "renderscript reduction breakpoint set",
4188 "Set a breakpoint on named RenderScript general reductions",
4189 "renderscript reduction breakpoint set <kernel_name> [-t "
4190 "<reduction_kernel_type,...>]",
4191 eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4192 eCommandProcessMustBePaused),
4195 class CommandOptions : public Options {
4199 m_kernel_types(RSReduceBreakpointResolver::eKernelTypeAll) {}
4201 ~CommandOptions() override = default;
4203 Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4204 ExecutionContext *exe_ctx) override {
4206 StreamString err_str;
4207 const int short_option = m_getopt_table[option_idx].val;
4208 switch (short_option) {
4210 if (!ParseReductionTypes(option_arg, err_str))
4211 err.SetErrorStringWithFormat(
4212 "Unable to deduce reduction types for %s: %s",
4213 option_arg.str().c_str(), err_str.GetData());
4216 auto coord = RSCoordinate{};
4217 if (!ParseCoordinate(option_arg, coord))
4218 err.SetErrorStringWithFormat("unable to parse coordinate for %s",
4219 option_arg.str().c_str());
4221 m_have_coord = true;
4227 err.SetErrorStringWithFormat("Invalid option '-%c'", short_option);
4232 void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4233 m_have_coord = false;
4236 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4237 return llvm::makeArrayRef(g_renderscript_reduction_bp_set_options);
4240 bool ParseReductionTypes(llvm::StringRef option_val,
4241 StreamString &err_str) {
4242 m_kernel_types = RSReduceBreakpointResolver::eKernelTypeNone;
4243 const auto reduce_name_to_type = [](llvm::StringRef name) -> int {
4244 return llvm::StringSwitch<int>(name)
4245 .Case("accumulator", RSReduceBreakpointResolver::eKernelTypeAccum)
4246 .Case("initializer", RSReduceBreakpointResolver::eKernelTypeInit)
4247 .Case("outconverter", RSReduceBreakpointResolver::eKernelTypeOutC)
4248 .Case("combiner", RSReduceBreakpointResolver::eKernelTypeComb)
4249 .Case("all", RSReduceBreakpointResolver::eKernelTypeAll)
4250 // Currently not exposed by the runtime
4251 // .Case("halter", RSReduceBreakpointResolver::eKernelTypeHalter)
4255 // Matching a comma separated list of known words is fairly
4256 // straightforward with PCRE, but we're
4257 // using ERE, so we end up with a little ugliness...
4258 RegularExpression::Match match(/* max_matches */ 5);
4259 RegularExpression match_type_list(
4260 llvm::StringRef("^([[:alpha:]]+)(,[[:alpha:]]+){0,4}$"));
4262 assert(match_type_list.IsValid());
4264 if (!match_type_list.Execute(option_val, &match)) {
4266 "a comma-separated list of kernel types is required");
4270 // splitting on commas is much easier with llvm::StringRef than regex
4271 llvm::SmallVector<llvm::StringRef, 5> type_names;
4272 llvm::StringRef(option_val).split(type_names, ',');
4274 for (const auto &name : type_names) {
4275 const int type = reduce_name_to_type(name);
4277 err_str.Printf("unknown kernel type name %s", name.str().c_str());
4280 m_kernel_types |= type;
4287 llvm::StringRef m_reduce_name;
4288 RSCoordinate m_coord;
4292 Options *GetOptions() override { return &m_options; }
4294 bool DoExecute(Args &command, CommandReturnObject &result) override {
4295 const size_t argc = command.GetArgumentCount();
4297 result.AppendErrorWithFormat("'%s' takes 1 argument of reduction name, "
4298 "and an optional kernel type list",
4299 m_cmd_name.c_str());
4300 result.SetStatus(eReturnStatusFailed);
4304 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4305 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4306 eLanguageTypeExtRenderScript));
4308 auto &outstream = result.GetOutputStream();
4309 auto name = command.GetArgumentAtIndex(0);
4310 auto &target = m_exe_ctx.GetTargetSP();
4311 auto coord = m_options.m_have_coord ? &m_options.m_coord : nullptr;
4312 if (!runtime->PlaceBreakpointOnReduction(target, outstream, name, coord,
4313 m_options.m_kernel_types)) {
4314 result.SetStatus(eReturnStatusFailed);
4315 result.AppendError("Error: unable to place breakpoint on reduction");
4318 result.AppendMessage("Breakpoint(s) created");
4319 result.SetStatus(eReturnStatusSuccessFinishResult);
4324 CommandOptions m_options;
4327 static OptionDefinition g_renderscript_kernel_bp_set_options[] = {
4328 {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument,
4329 nullptr, nullptr, 0, eArgTypeValue,
4330 "Set a breakpoint on a single invocation of the kernel with specified "
4332 "Coordinate takes the form 'x[,y][,z] where x,y,z are positive "
4333 "integers representing kernel dimensions. "
4334 "Any unset dimensions will be defaulted to zero."}};
4336 class CommandObjectRenderScriptRuntimeKernelBreakpointSet
4337 : public CommandObjectParsed {
4339 CommandObjectRenderScriptRuntimeKernelBreakpointSet(
4340 CommandInterpreter &interpreter)
4341 : CommandObjectParsed(
4342 interpreter, "renderscript kernel breakpoint set",
4343 "Sets a breakpoint on a renderscript kernel.",
4344 "renderscript kernel breakpoint set <kernel_name> [-c x,y,z]",
4345 eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4346 eCommandProcessMustBePaused),
4349 ~CommandObjectRenderScriptRuntimeKernelBreakpointSet() override = default;
4351 Options *GetOptions() override { return &m_options; }
4353 class CommandOptions : public Options {
4355 CommandOptions() : Options() {}
4357 ~CommandOptions() override = default;
4359 Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4360 ExecutionContext *exe_ctx) override {
4362 const int short_option = m_getopt_table[option_idx].val;
4364 switch (short_option) {
4366 auto coord = RSCoordinate{};
4367 if (!ParseCoordinate(option_arg, coord))
4368 err.SetErrorStringWithFormat(
4369 "Couldn't parse coordinate '%s', should be in format 'x,y,z'.",
4370 option_arg.str().c_str());
4372 m_have_coord = true;
4378 err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4384 void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4385 m_have_coord = false;
4388 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4389 return llvm::makeArrayRef(g_renderscript_kernel_bp_set_options);
4392 RSCoordinate m_coord;
4396 bool DoExecute(Args &command, CommandReturnObject &result) override {
4397 const size_t argc = command.GetArgumentCount();
4399 result.AppendErrorWithFormat(
4400 "'%s' takes 1 argument of kernel name, and an optional coordinate.",
4401 m_cmd_name.c_str());
4402 result.SetStatus(eReturnStatusFailed);
4406 RenderScriptRuntime *runtime =
4407 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4408 eLanguageTypeExtRenderScript);
4410 auto &outstream = result.GetOutputStream();
4411 auto &target = m_exe_ctx.GetTargetSP();
4412 auto name = command.GetArgumentAtIndex(0);
4413 auto coord = m_options.m_have_coord ? &m_options.m_coord : nullptr;
4414 if (!runtime->PlaceBreakpointOnKernel(target, outstream, name, coord)) {
4415 result.SetStatus(eReturnStatusFailed);
4416 result.AppendErrorWithFormat(
4417 "Error: unable to set breakpoint on kernel '%s'", name);
4421 result.AppendMessage("Breakpoint(s) created");
4422 result.SetStatus(eReturnStatusSuccessFinishResult);
4427 CommandOptions m_options;
4430 class CommandObjectRenderScriptRuntimeKernelBreakpointAll
4431 : public CommandObjectParsed {
4433 CommandObjectRenderScriptRuntimeKernelBreakpointAll(
4434 CommandInterpreter &interpreter)
4435 : CommandObjectParsed(
4436 interpreter, "renderscript kernel breakpoint all",
4437 "Automatically sets a breakpoint on all renderscript kernels that "
4438 "are or will be loaded.\n"
4439 "Disabling option means breakpoints will no longer be set on any "
4440 "kernels loaded in the future, "
4441 "but does not remove currently set breakpoints.",
4442 "renderscript kernel breakpoint all <enable/disable>",
4443 eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4444 eCommandProcessMustBePaused) {}
4446 ~CommandObjectRenderScriptRuntimeKernelBreakpointAll() override = default;
4448 bool DoExecute(Args &command, CommandReturnObject &result) override {
4449 const size_t argc = command.GetArgumentCount();
4451 result.AppendErrorWithFormat(
4452 "'%s' takes 1 argument of 'enable' or 'disable'", m_cmd_name.c_str());
4453 result.SetStatus(eReturnStatusFailed);
4457 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4458 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4459 eLanguageTypeExtRenderScript));
4461 bool do_break = false;
4462 const char *argument = command.GetArgumentAtIndex(0);
4463 if (strcmp(argument, "enable") == 0) {
4465 result.AppendMessage("Breakpoints will be set on all kernels.");
4466 } else if (strcmp(argument, "disable") == 0) {
4468 result.AppendMessage("Breakpoints will not be set on any new kernels.");
4470 result.AppendErrorWithFormat(
4471 "Argument must be either 'enable' or 'disable'");
4472 result.SetStatus(eReturnStatusFailed);
4476 runtime->SetBreakAllKernels(do_break, m_exe_ctx.GetTargetSP());
4478 result.SetStatus(eReturnStatusSuccessFinishResult);
4483 class CommandObjectRenderScriptRuntimeReductionBreakpoint
4484 : public CommandObjectMultiword {
4486 CommandObjectRenderScriptRuntimeReductionBreakpoint(
4487 CommandInterpreter &interpreter)
4488 : CommandObjectMultiword(interpreter, "renderscript reduction breakpoint",
4489 "Commands that manipulate breakpoints on "
4490 "renderscript general reductions.",
4493 "set", CommandObjectSP(
4494 new CommandObjectRenderScriptRuntimeReductionBreakpointSet(
4498 ~CommandObjectRenderScriptRuntimeReductionBreakpoint() override = default;
4501 class CommandObjectRenderScriptRuntimeKernelCoordinate
4502 : public CommandObjectParsed {
4504 CommandObjectRenderScriptRuntimeKernelCoordinate(
4505 CommandInterpreter &interpreter)
4506 : CommandObjectParsed(
4507 interpreter, "renderscript kernel coordinate",
4508 "Shows the (x,y,z) coordinate of the current kernel invocation.",
4509 "renderscript kernel coordinate",
4510 eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4511 eCommandProcessMustBePaused) {}
4513 ~CommandObjectRenderScriptRuntimeKernelCoordinate() override = default;
4515 bool DoExecute(Args &command, CommandReturnObject &result) override {
4516 RSCoordinate coord{};
4517 bool success = RenderScriptRuntime::GetKernelCoordinate(
4518 coord, m_exe_ctx.GetThreadPtr());
4519 Stream &stream = result.GetOutputStream();
4522 stream.Printf("Coordinate: " FMT_COORD, coord.x, coord.y, coord.z);
4524 result.SetStatus(eReturnStatusSuccessFinishResult);
4526 stream.Printf("Error: Coordinate could not be found.");
4528 result.SetStatus(eReturnStatusFailed);
4534 class CommandObjectRenderScriptRuntimeKernelBreakpoint
4535 : public CommandObjectMultiword {
4537 CommandObjectRenderScriptRuntimeKernelBreakpoint(
4538 CommandInterpreter &interpreter)
4539 : CommandObjectMultiword(
4540 interpreter, "renderscript kernel",
4541 "Commands that generate breakpoints on renderscript kernels.",
4545 CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointSet(
4549 CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointAll(
4553 ~CommandObjectRenderScriptRuntimeKernelBreakpoint() override = default;
4556 class CommandObjectRenderScriptRuntimeKernel : public CommandObjectMultiword {
4558 CommandObjectRenderScriptRuntimeKernel(CommandInterpreter &interpreter)
4559 : CommandObjectMultiword(interpreter, "renderscript kernel",
4560 "Commands that deal with RenderScript kernels.",
4563 "list", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelList(
4568 new CommandObjectRenderScriptRuntimeKernelCoordinate(interpreter)));
4572 new CommandObjectRenderScriptRuntimeKernelBreakpoint(interpreter)));
4575 ~CommandObjectRenderScriptRuntimeKernel() override = default;
4578 class CommandObjectRenderScriptRuntimeContextDump : public CommandObjectParsed {
4580 CommandObjectRenderScriptRuntimeContextDump(CommandInterpreter &interpreter)
4581 : CommandObjectParsed(interpreter, "renderscript context dump",
4582 "Dumps renderscript context information.",
4583 "renderscript context dump",
4584 eCommandRequiresProcess |
4585 eCommandProcessMustBeLaunched) {}
4587 ~CommandObjectRenderScriptRuntimeContextDump() override = default;
4589 bool DoExecute(Args &command, CommandReturnObject &result) override {
4590 RenderScriptRuntime *runtime =
4591 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4592 eLanguageTypeExtRenderScript);
4593 runtime->DumpContexts(result.GetOutputStream());
4594 result.SetStatus(eReturnStatusSuccessFinishResult);
4599 static OptionDefinition g_renderscript_runtime_alloc_dump_options[] = {
4600 {LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument,
4601 nullptr, nullptr, 0, eArgTypeFilename,
4602 "Print results to specified file instead of command line."}};
4604 class CommandObjectRenderScriptRuntimeContext : public CommandObjectMultiword {
4606 CommandObjectRenderScriptRuntimeContext(CommandInterpreter &interpreter)
4607 : CommandObjectMultiword(interpreter, "renderscript context",
4608 "Commands that deal with RenderScript contexts.",
4611 "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeContextDump(
4615 ~CommandObjectRenderScriptRuntimeContext() override = default;
4618 class CommandObjectRenderScriptRuntimeAllocationDump
4619 : public CommandObjectParsed {
4621 CommandObjectRenderScriptRuntimeAllocationDump(
4622 CommandInterpreter &interpreter)
4623 : CommandObjectParsed(interpreter, "renderscript allocation dump",
4624 "Displays the contents of a particular allocation",
4625 "renderscript allocation dump <ID>",
4626 eCommandRequiresProcess |
4627 eCommandProcessMustBeLaunched),
4630 ~CommandObjectRenderScriptRuntimeAllocationDump() override = default;
4632 Options *GetOptions() override { return &m_options; }
4634 class CommandOptions : public Options {
4636 CommandOptions() : Options() {}
4638 ~CommandOptions() override = default;
4640 Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4641 ExecutionContext *exe_ctx) override {
4643 const int short_option = m_getopt_table[option_idx].val;
4645 switch (short_option) {
4647 m_outfile.SetFile(option_arg, true);
4648 if (m_outfile.Exists()) {
4650 err.SetErrorStringWithFormat("file already exists: '%s'",
4651 option_arg.str().c_str());
4655 err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4661 void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4665 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4666 return llvm::makeArrayRef(g_renderscript_runtime_alloc_dump_options);
4672 bool DoExecute(Args &command, CommandReturnObject &result) override {
4673 const size_t argc = command.GetArgumentCount();
4675 result.AppendErrorWithFormat("'%s' takes 1 argument, an allocation ID. "
4676 "As well as an optional -f argument",
4677 m_cmd_name.c_str());
4678 result.SetStatus(eReturnStatusFailed);
4682 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4683 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4684 eLanguageTypeExtRenderScript));
4686 const char *id_cstr = command.GetArgumentAtIndex(0);
4687 bool success = false;
4689 StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
4691 result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4693 result.SetStatus(eReturnStatusFailed);
4697 Stream *output_strm = nullptr;
4698 StreamFile outfile_stream;
4699 const FileSpec &outfile_spec =
4700 m_options.m_outfile; // Dump allocation to file instead
4704 outfile_spec.GetPath(path, sizeof(path));
4705 if (outfile_stream.GetFile()
4706 .Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate)
4708 output_strm = &outfile_stream;
4709 result.GetOutputStream().Printf("Results written to '%s'", path);
4710 result.GetOutputStream().EOL();
4712 result.AppendErrorWithFormat("Couldn't open file '%s'", path);
4713 result.SetStatus(eReturnStatusFailed);
4717 output_strm = &result.GetOutputStream();
4719 assert(output_strm != nullptr);
4721 runtime->DumpAllocation(*output_strm, m_exe_ctx.GetFramePtr(), id);
4724 result.SetStatus(eReturnStatusSuccessFinishResult);
4726 result.SetStatus(eReturnStatusFailed);
4732 CommandOptions m_options;
4735 static OptionDefinition g_renderscript_runtime_alloc_list_options[] = {
4736 {LLDB_OPT_SET_1, false, "id", 'i', OptionParser::eRequiredArgument, nullptr,
4737 nullptr, 0, eArgTypeIndex,
4738 "Only show details of a single allocation with specified id."}};
4740 class CommandObjectRenderScriptRuntimeAllocationList
4741 : public CommandObjectParsed {
4743 CommandObjectRenderScriptRuntimeAllocationList(
4744 CommandInterpreter &interpreter)
4745 : CommandObjectParsed(
4746 interpreter, "renderscript allocation list",
4747 "List renderscript allocations and their information.",
4748 "renderscript allocation list",
4749 eCommandRequiresProcess | eCommandProcessMustBeLaunched),
4752 ~CommandObjectRenderScriptRuntimeAllocationList() override = default;
4754 Options *GetOptions() override { return &m_options; }
4756 class CommandOptions : public Options {
4758 CommandOptions() : Options(), m_id(0) {}
4760 ~CommandOptions() override = default;
4762 Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4763 ExecutionContext *exe_ctx) override {
4765 const int short_option = m_getopt_table[option_idx].val;
4767 switch (short_option) {
4769 if (option_arg.getAsInteger(0, m_id))
4770 err.SetErrorStringWithFormat("invalid integer value for option '%c'",
4774 err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4780 void OptionParsingStarting(ExecutionContext *exe_ctx) override { m_id = 0; }
4782 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4783 return llvm::makeArrayRef(g_renderscript_runtime_alloc_list_options);
4789 bool DoExecute(Args &command, CommandReturnObject &result) override {
4790 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4791 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4792 eLanguageTypeExtRenderScript));
4793 runtime->ListAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr(),
4795 result.SetStatus(eReturnStatusSuccessFinishResult);
4800 CommandOptions m_options;
4803 class CommandObjectRenderScriptRuntimeAllocationLoad
4804 : public CommandObjectParsed {
4806 CommandObjectRenderScriptRuntimeAllocationLoad(
4807 CommandInterpreter &interpreter)
4808 : CommandObjectParsed(
4809 interpreter, "renderscript allocation load",
4810 "Loads renderscript allocation contents from a file.",
4811 "renderscript allocation load <ID> <filename>",
4812 eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
4814 ~CommandObjectRenderScriptRuntimeAllocationLoad() override = default;
4816 bool DoExecute(Args &command, CommandReturnObject &result) override {
4817 const size_t argc = command.GetArgumentCount();
4819 result.AppendErrorWithFormat(
4820 "'%s' takes 2 arguments, an allocation ID and filename to read from.",
4821 m_cmd_name.c_str());
4822 result.SetStatus(eReturnStatusFailed);
4826 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4827 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4828 eLanguageTypeExtRenderScript));
4830 const char *id_cstr = command.GetArgumentAtIndex(0);
4831 bool success = false;
4833 StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
4835 result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4837 result.SetStatus(eReturnStatusFailed);
4841 const char *path = command.GetArgumentAtIndex(1);
4842 bool loaded = runtime->LoadAllocation(result.GetOutputStream(), id, path,
4843 m_exe_ctx.GetFramePtr());
4846 result.SetStatus(eReturnStatusSuccessFinishResult);
4848 result.SetStatus(eReturnStatusFailed);
4854 class CommandObjectRenderScriptRuntimeAllocationSave
4855 : public CommandObjectParsed {
4857 CommandObjectRenderScriptRuntimeAllocationSave(
4858 CommandInterpreter &interpreter)
4859 : CommandObjectParsed(interpreter, "renderscript allocation save",
4860 "Write renderscript allocation contents to a file.",
4861 "renderscript allocation save <ID> <filename>",
4862 eCommandRequiresProcess |
4863 eCommandProcessMustBeLaunched) {}
4865 ~CommandObjectRenderScriptRuntimeAllocationSave() override = default;
4867 bool DoExecute(Args &command, CommandReturnObject &result) override {
4868 const size_t argc = command.GetArgumentCount();
4870 result.AppendErrorWithFormat(
4871 "'%s' takes 2 arguments, an allocation ID and filename to read from.",
4872 m_cmd_name.c_str());
4873 result.SetStatus(eReturnStatusFailed);
4877 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4878 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4879 eLanguageTypeExtRenderScript));
4881 const char *id_cstr = command.GetArgumentAtIndex(0);
4882 bool success = false;
4884 StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &success);
4886 result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4888 result.SetStatus(eReturnStatusFailed);
4892 const char *path = command.GetArgumentAtIndex(1);
4893 bool saved = runtime->SaveAllocation(result.GetOutputStream(), id, path,
4894 m_exe_ctx.GetFramePtr());
4897 result.SetStatus(eReturnStatusSuccessFinishResult);
4899 result.SetStatus(eReturnStatusFailed);
4905 class CommandObjectRenderScriptRuntimeAllocationRefresh
4906 : public CommandObjectParsed {
4908 CommandObjectRenderScriptRuntimeAllocationRefresh(
4909 CommandInterpreter &interpreter)
4910 : CommandObjectParsed(interpreter, "renderscript allocation refresh",
4911 "Recomputes the details of all allocations.",
4912 "renderscript allocation refresh",
4913 eCommandRequiresProcess |
4914 eCommandProcessMustBeLaunched) {}
4916 ~CommandObjectRenderScriptRuntimeAllocationRefresh() override = default;
4918 bool DoExecute(Args &command, CommandReturnObject &result) override {
4919 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4920 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4921 eLanguageTypeExtRenderScript));
4923 bool success = runtime->RecomputeAllAllocations(result.GetOutputStream(),
4924 m_exe_ctx.GetFramePtr());
4927 result.SetStatus(eReturnStatusSuccessFinishResult);
4930 result.SetStatus(eReturnStatusFailed);
4936 class CommandObjectRenderScriptRuntimeAllocation
4937 : public CommandObjectMultiword {
4939 CommandObjectRenderScriptRuntimeAllocation(CommandInterpreter &interpreter)
4940 : CommandObjectMultiword(
4941 interpreter, "renderscript allocation",
4942 "Commands that deal with RenderScript allocations.", nullptr) {
4946 new CommandObjectRenderScriptRuntimeAllocationList(interpreter)));
4950 new CommandObjectRenderScriptRuntimeAllocationDump(interpreter)));
4954 new CommandObjectRenderScriptRuntimeAllocationSave(interpreter)));
4958 new CommandObjectRenderScriptRuntimeAllocationLoad(interpreter)));
4961 CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationRefresh(
4965 ~CommandObjectRenderScriptRuntimeAllocation() override = default;
4968 class CommandObjectRenderScriptRuntimeStatus : public CommandObjectParsed {
4970 CommandObjectRenderScriptRuntimeStatus(CommandInterpreter &interpreter)
4971 : CommandObjectParsed(interpreter, "renderscript status",
4972 "Displays current RenderScript runtime status.",
4973 "renderscript status",
4974 eCommandRequiresProcess |
4975 eCommandProcessMustBeLaunched) {}
4977 ~CommandObjectRenderScriptRuntimeStatus() override = default;
4979 bool DoExecute(Args &command, CommandReturnObject &result) override {
4980 RenderScriptRuntime *runtime =
4981 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4982 eLanguageTypeExtRenderScript);
4983 runtime->Status(result.GetOutputStream());
4984 result.SetStatus(eReturnStatusSuccessFinishResult);
4989 class CommandObjectRenderScriptRuntimeReduction
4990 : public CommandObjectMultiword {
4992 CommandObjectRenderScriptRuntimeReduction(CommandInterpreter &interpreter)
4993 : CommandObjectMultiword(interpreter, "renderscript reduction",
4994 "Commands that handle general reduction kernels",
4998 CommandObjectSP(new CommandObjectRenderScriptRuntimeReductionBreakpoint(
5001 ~CommandObjectRenderScriptRuntimeReduction() override = default;
5004 class CommandObjectRenderScriptRuntime : public CommandObjectMultiword {
5006 CommandObjectRenderScriptRuntime(CommandInterpreter &interpreter)
5007 : CommandObjectMultiword(
5008 interpreter, "renderscript",
5009 "Commands for operating on the RenderScript runtime.",
5010 "renderscript <subcommand> [<subcommand-options>]") {
5012 "module", CommandObjectSP(
5013 new CommandObjectRenderScriptRuntimeModule(interpreter)));
5015 "status", CommandObjectSP(
5016 new CommandObjectRenderScriptRuntimeStatus(interpreter)));
5018 "kernel", CommandObjectSP(
5019 new CommandObjectRenderScriptRuntimeKernel(interpreter)));
5020 LoadSubCommand("context",
5021 CommandObjectSP(new CommandObjectRenderScriptRuntimeContext(
5026 new CommandObjectRenderScriptRuntimeAllocation(interpreter)));
5027 LoadSubCommand("scriptgroup",
5028 NewCommandObjectRenderScriptScriptGroup(interpreter));
5032 new CommandObjectRenderScriptRuntimeReduction(interpreter)));
5035 ~CommandObjectRenderScriptRuntime() override = default;
5038 void RenderScriptRuntime::Initiate() { assert(!m_initiated); }
5040 RenderScriptRuntime::RenderScriptRuntime(Process *process)
5041 : lldb_private::CPPLanguageRuntime(process), m_initiated(false),
5042 m_debuggerPresentFlagged(false), m_breakAllKernels(false),
5043 m_ir_passes(nullptr) {
5044 ModulesDidLoad(process->GetTarget().GetImages());
5047 lldb::CommandObjectSP RenderScriptRuntime::GetCommandObject(
5048 lldb_private::CommandInterpreter &interpreter) {
5049 return CommandObjectSP(new CommandObjectRenderScriptRuntime(interpreter));
5052 RenderScriptRuntime::~RenderScriptRuntime() = default;