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
14 #include "RenderScriptRuntime.h"
16 #include "lldb/Breakpoint/StoppointCallbackContext.h"
17 #include "lldb/Core/ConstString.h"
18 #include "lldb/Core/Debugger.h"
19 #include "lldb/Core/Error.h"
20 #include "lldb/Core/Log.h"
21 #include "lldb/Core/PluginManager.h"
22 #include "lldb/Core/RegularExpression.h"
23 #include "lldb/Core/ValueObjectVariable.h"
24 #include "lldb/DataFormatters/DumpValueObjectOptions.h"
25 #include "lldb/Expression/UserExpression.h"
26 #include "lldb/Host/StringConvert.h"
27 #include "lldb/Interpreter/Args.h"
28 #include "lldb/Interpreter/CommandInterpreter.h"
29 #include "lldb/Interpreter/CommandObjectMultiword.h"
30 #include "lldb/Interpreter/CommandReturnObject.h"
31 #include "lldb/Interpreter/Options.h"
32 #include "lldb/Symbol/Symbol.h"
33 #include "lldb/Symbol/Type.h"
34 #include "lldb/Symbol/VariableList.h"
35 #include "lldb/Target/Process.h"
36 #include "lldb/Target/RegisterContext.h"
37 #include "lldb/Target/Target.h"
38 #include "lldb/Target/Thread.h"
41 using namespace lldb_private;
42 using namespace lldb_renderscript;
47 // The empirical_type adds a basic level of validation to arbitrary data
48 // allowing us to track if data has been discovered and stored or not.
49 // An empirical_type will be marked as valid only if it has been explicitly assigned to.
50 template <typename type_t> class empirical_type
53 // Ctor. Contents is invalid when constructed.
54 empirical_type() : valid(false) {}
56 // Return true and copy contents to out if valid, else return false.
58 get(type_t &out) const
65 // Return a pointer to the contents or nullptr if it was not valid.
69 return valid ? &data : nullptr;
72 // Assign data explicitly.
80 // Mark contents as invalid.
87 // Returns true if this type contains valid data.
94 // Assignment operator.
95 empirical_type<type_t> &
96 operator=(const type_t in)
102 // Dereference operator returns contents.
103 // Warning: Will assert if not valid so use only when you know data is valid.
104 const type_t &operator*() const
115 // ArgItem is used by the GetArgs() function when reading function arguments from the target.
129 explicit operator uint64_t() const { return value; }
132 // Context structure to be passed into GetArgsXXX(), argument reading functions below.
135 RegisterContext *reg_ctx;
140 GetArgsX86(const GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args)
142 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
146 // get the current stack pointer
147 uint64_t sp = ctx.reg_ctx->GetSP();
149 for (size_t i = 0; i < num_args; ++i)
151 ArgItem &arg = arg_list[i];
152 // advance up the stack by one argument
153 sp += sizeof(uint32_t);
154 // get the argument type size
155 size_t arg_size = sizeof(uint32_t);
156 // read the argument from memory
159 size_t read = ctx.process->ReadMemory(sp, &arg.value, sizeof(uint32_t), error);
160 if (read != arg_size || !error.Success())
163 log->Printf("%s - error reading argument: %" PRIu64 " '%s'", __FUNCTION__, uint64_t(i),
172 GetArgsX86_64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args)
174 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
176 // number of arguments passed in registers
177 static const uint32_t c_args_in_reg = 6;
178 // register passing order
179 static const std::array<const char *, c_args_in_reg> c_reg_names{{"rdi", "rsi", "rdx", "rcx", "r8", "r9"}};
180 // argument type to size mapping
181 static const std::array<size_t, 5> arg_size{{
191 // get the current stack pointer
192 uint64_t sp = ctx.reg_ctx->GetSP();
193 // step over the return address
194 sp += sizeof(uint64_t);
196 // check the stack alignment was correct (16 byte aligned)
197 if ((sp & 0xf) != 0x0)
200 log->Printf("%s - stack misaligned", __FUNCTION__);
204 // find the start of arguments on the stack
205 uint64_t sp_offset = 0;
206 for (uint32_t i = c_args_in_reg; i < num_args; ++i)
208 sp_offset += arg_size[arg_list[i].type];
210 // round up to multiple of 16
211 sp_offset = (sp_offset + 0xf) & 0xf;
214 for (size_t i = 0; i < num_args; ++i)
216 bool success = false;
217 ArgItem &arg = arg_list[i];
218 // arguments passed in registers
219 if (i < c_args_in_reg)
221 const RegisterInfo *rArg = ctx.reg_ctx->GetRegisterInfoByName(c_reg_names[i]);
223 if (ctx.reg_ctx->ReadRegister(rArg, rVal))
224 arg.value = rVal.GetAsUInt64(0, &success);
226 // arguments passed on the stack
229 // get the argument type size
230 const size_t size = arg_size[arg_list[i].type];
231 // read the argument from memory
233 // note: due to little endian layout reading 4 or 8 bytes will give the correct value.
234 size_t read = ctx.process->ReadMemory(sp, &arg.value, size, error);
235 success = (error.Success() && read==size);
236 // advance past this argument
239 // fail if we couldn't read this argument
243 log->Printf("%s - error reading argument: %" PRIu64", reason: %s",
244 __FUNCTION__, uint64_t(i), error.AsCString("n/a"));
252 GetArgsArm(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args)
254 // number of arguments passed in registers
255 static const uint32_t c_args_in_reg = 4;
257 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
261 // get the current stack pointer
262 uint64_t sp = ctx.reg_ctx->GetSP();
264 for (size_t i = 0; i < num_args; ++i)
266 bool success = false;
267 ArgItem &arg = arg_list[i];
268 // arguments passed in registers
269 if (i < c_args_in_reg)
271 const RegisterInfo *rArg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
273 if (ctx.reg_ctx->ReadRegister(rArg, rVal))
274 arg.value = rVal.GetAsUInt32(0, &success);
276 // arguments passed on the stack
279 // get the argument type size
280 const size_t arg_size = sizeof(uint32_t);
283 // read this argument from memory
284 size_t bytes_read = ctx.process->ReadMemory(sp, &arg.value, arg_size, error);
285 success = (error.Success() && bytes_read == arg_size);
286 // advance the stack pointer
287 sp += sizeof(uint32_t);
289 // fail if we couldn't read this argument
293 log->Printf("%s - error reading argument: %" PRIu64", reason: %s",
294 __FUNCTION__, uint64_t(i), error.AsCString("n/a"));
302 GetArgsAarch64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args)
304 // number of arguments passed in registers
305 static const uint32_t c_args_in_reg = 8;
307 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
309 for (size_t i = 0; i < num_args; ++i)
311 bool success = false;
312 ArgItem &arg = arg_list[i];
313 // arguments passed in registers
314 if (i < c_args_in_reg)
316 const RegisterInfo *rArg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
318 if (ctx.reg_ctx->ReadRegister(rArg, rVal))
319 arg.value = rVal.GetAsUInt64(0, &success);
321 // arguments passed on the stack
325 log->Printf("%s - reading arguments spilled to stack not implemented", __FUNCTION__);
327 // fail if we couldn't read this argument
331 log->Printf("%s - error reading argument: %" PRIu64, __FUNCTION__,
340 GetArgsMipsel(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args)
342 // number of arguments passed in registers
343 static const uint32_t c_args_in_reg = 4;
344 // register file offset to first argument
345 static const uint32_t c_reg_offset = 4;
347 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
351 // find offset to arguments on the stack (+16 to skip over a0-a3 shadow space)
352 uint64_t sp = ctx.reg_ctx->GetSP() + 16;
354 for (size_t i = 0; i < num_args; ++i)
356 bool success = false;
357 ArgItem &arg = arg_list[i];
358 // arguments passed in registers
359 if (i < c_args_in_reg)
361 const RegisterInfo *rArg = ctx.reg_ctx->GetRegisterInfoAtIndex(i + c_reg_offset);
363 if (ctx.reg_ctx->ReadRegister(rArg, rVal))
364 arg.value = rVal.GetAsUInt64(0, &success);
366 // arguments passed on the stack
369 const size_t arg_size = sizeof(uint32_t);
371 size_t bytes_read = ctx.process->ReadMemory(sp, &arg.value, arg_size, error);
372 success = (error.Success() && bytes_read == arg_size);
373 // advance the stack pointer
376 // fail if we couldn't read this argument
380 log->Printf("%s - error reading argument: %" PRIu64", reason: %s",
381 __FUNCTION__, uint64_t(i), error.AsCString("n/a"));
389 GetArgsMips64el(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args)
391 // number of arguments passed in registers
392 static const uint32_t c_args_in_reg = 8;
393 // register file offset to first argument
394 static const uint32_t c_reg_offset = 4;
396 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
400 // get the current stack pointer
401 uint64_t sp = ctx.reg_ctx->GetSP();
403 for (size_t i = 0; i < num_args; ++i)
405 bool success = false;
406 ArgItem &arg = arg_list[i];
407 // arguments passed in registers
408 if (i < c_args_in_reg)
410 const RegisterInfo *rArg = ctx.reg_ctx->GetRegisterInfoAtIndex(i + c_reg_offset);
412 if (ctx.reg_ctx->ReadRegister(rArg, rVal))
413 arg.value = rVal.GetAsUInt64(0, &success);
415 // arguments passed on the stack
418 // get the argument type size
419 const size_t arg_size = sizeof(uint64_t);
422 // read this argument from memory
423 size_t bytes_read = ctx.process->ReadMemory(sp, &arg.value, arg_size, error);
424 success = (error.Success() && bytes_read == arg_size);
425 // advance the stack pointer
428 // fail if we couldn't read this argument
432 log->Printf("%s - error reading argument: %" PRIu64", reason: %s",
433 __FUNCTION__, uint64_t(i), error.AsCString("n/a"));
441 GetArgs(ExecutionContext &context, ArgItem *arg_list, size_t num_args)
443 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE);
445 // verify that we have a target
446 if (!context.GetTargetPtr())
449 log->Printf("%s - invalid target", __FUNCTION__);
453 GetArgsCtx ctx = {context.GetRegisterContext(), context.GetProcessPtr()};
454 assert(ctx.reg_ctx && ctx.process);
456 // dispatch based on architecture
457 switch (context.GetTargetPtr()->GetArchitecture().GetMachine())
459 case llvm::Triple::ArchType::x86:
460 return GetArgsX86(ctx, arg_list, num_args);
462 case llvm::Triple::ArchType::x86_64:
463 return GetArgsX86_64(ctx, arg_list, num_args);
465 case llvm::Triple::ArchType::arm:
466 return GetArgsArm(ctx, arg_list, num_args);
468 case llvm::Triple::ArchType::aarch64:
469 return GetArgsAarch64(ctx, arg_list, num_args);
471 case llvm::Triple::ArchType::mipsel:
472 return GetArgsMipsel(ctx, arg_list, num_args);
474 case llvm::Triple::ArchType::mips64el:
475 return GetArgsMips64el(ctx, arg_list, num_args);
478 // unsupported architecture
481 log->Printf("%s - architecture not supported: '%s'", __FUNCTION__,
482 context.GetTargetRef().GetArchitecture().GetArchitectureName());
487 } // anonymous namespace
489 // The ScriptDetails class collects data associated with a single script instance.
490 struct RenderScriptRuntime::ScriptDetails
492 ~ScriptDetails() = default;
500 // The derived type of the script.
501 empirical_type<ScriptType> type;
502 // The name of the original source file.
503 empirical_type<std::string> resName;
504 // Path to script .so file on the device.
505 empirical_type<std::string> scriptDyLib;
506 // Directory where kernel objects are cached on device.
507 empirical_type<std::string> cacheDir;
508 // Pointer to the context which owns this script.
509 empirical_type<lldb::addr_t> context;
510 // Pointer to the script object itself.
511 empirical_type<lldb::addr_t> script;
514 // This Element class represents the Element object in RS,
515 // defining the type associated with an Allocation.
516 struct RenderScriptRuntime::Element
518 // Taken from rsDefines.h
529 RS_KIND_INVALID = 100
532 // Taken from rsDefines.h
549 RS_TYPE_UNSIGNED_5_6_5,
550 RS_TYPE_UNSIGNED_5_5_5_1,
551 RS_TYPE_UNSIGNED_4_4_4_4,
557 RS_TYPE_ELEMENT = 1000,
563 RS_TYPE_PROGRAM_FRAGMENT,
564 RS_TYPE_PROGRAM_VERTEX,
565 RS_TYPE_PROGRAM_RASTER,
566 RS_TYPE_PROGRAM_STORE,
569 RS_TYPE_INVALID = 10000
572 std::vector<Element> children; // Child Element fields for structs
573 empirical_type<lldb::addr_t> element_ptr; // Pointer to the RS Element of the Type
574 empirical_type<DataType> type; // Type of each data pointer stored by the allocation
575 empirical_type<DataKind> type_kind; // Defines pixel type if Allocation is created from an image
576 empirical_type<uint32_t> type_vec_size; // Vector size of each data point, e.g '4' for uchar4
577 empirical_type<uint32_t> field_count; // Number of Subelements
578 empirical_type<uint32_t> datum_size; // Size of a single Element with padding
579 empirical_type<uint32_t> padding; // Number of padding bytes
580 empirical_type<uint32_t> array_size; // Number of items in array, only needed for strucrs
581 ConstString type_name; // Name of type, only needed for structs
583 static const ConstString &
584 GetFallbackStructName(); // Print this as the type name of a struct Element
585 // If we can't resolve the actual struct name
588 shouldRefresh() const
590 const bool valid_ptr = element_ptr.isValid() && *element_ptr.get() != 0x0;
591 const bool valid_type = type.isValid() && type_vec_size.isValid() && type_kind.isValid();
592 return !valid_ptr || !valid_type || !datum_size.isValid();
596 // This AllocationDetails class collects data associated with a single
597 // allocation instance.
598 struct RenderScriptRuntime::AllocationDetails
616 // The FileHeader struct specifies the header we use for writing allocations to a binary file.
617 // Our format begins with the ASCII characters "RSAD", identifying the file as an allocation dump.
618 // Member variables dims and hdr_size are then written consecutively, immediately followed by an instance of
619 // the ElementHeader struct. Because Elements can contain subelements, there may be more than one instance
620 // of the ElementHeader struct. With this first instance being the root element, and the other instances being
621 // the root's descendants. To identify which instances are an ElementHeader's children, each struct
622 // is immediately followed by a sequence of consecutive offsets to the start of its child structs.
623 // These offsets are 4 bytes in size, and the 0 offset signifies no more children.
626 uint8_t ident[4]; // ASCII 'RSAD' identifying the file
627 uint32_t dims[3]; // Dimensions
628 uint16_t hdr_size; // Header size in bytes, including all element headers
633 uint16_t type; // DataType enum
634 uint32_t kind; // DataKind enum
635 uint32_t element_size; // Size of a single element, including padding
636 uint16_t vector_size; // Vector width
637 uint32_t array_size; // Number of elements in array
640 // Monotonically increasing from 1
643 // Maps Allocation DataType enum and vector size to printable strings
644 // using mapping from RenderScript numerical types summary documentation
645 static const char *RsDataTypeToString[][4];
647 // Maps Allocation DataKind enum to printable strings
648 static const char *RsDataKindToString[];
650 // Maps allocation types to format sizes for printing.
651 static const uint32_t RSTypeToFormat[][3];
653 // Give each allocation an ID as a way
654 // for commands to reference it.
657 RenderScriptRuntime::Element element; // Allocation Element type
658 empirical_type<Dimension> dimension; // Dimensions of the Allocation
659 empirical_type<lldb::addr_t> address; // Pointer to address of the RS Allocation
660 empirical_type<lldb::addr_t> data_ptr; // Pointer to the data held by the Allocation
661 empirical_type<lldb::addr_t> type_ptr; // Pointer to the RS Type of the Allocation
662 empirical_type<lldb::addr_t> context; // Pointer to the RS Context of the Allocation
663 empirical_type<uint32_t> size; // Size of the allocation
664 empirical_type<uint32_t> stride; // Stride between rows of the allocation
666 // Give each allocation an id, so we can reference it in user commands.
667 AllocationDetails() : id(ID++) {}
670 shouldRefresh() const
672 bool valid_ptrs = data_ptr.isValid() && *data_ptr.get() != 0x0;
673 valid_ptrs = valid_ptrs && type_ptr.isValid() && *type_ptr.get() != 0x0;
674 return !valid_ptrs || !dimension.isValid() || !size.isValid() || element.shouldRefresh();
679 RenderScriptRuntime::Element::GetFallbackStructName()
681 static const ConstString FallbackStructName("struct");
682 return FallbackStructName;
685 uint32_t RenderScriptRuntime::AllocationDetails::ID = 1;
687 const char *RenderScriptRuntime::AllocationDetails::RsDataKindToString[] = {
689 "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", // Enum jumps from 0 to 7
690 "L Pixel", "A Pixel", "LA Pixel", "RGB Pixel",
691 "RGBA Pixel", "Pixel Depth", "YUV Pixel"};
693 const char *RenderScriptRuntime::AllocationDetails::RsDataTypeToString[][4] = {
694 {"None", "None", "None", "None"},
695 {"half", "half2", "half3", "half4"},
696 {"float", "float2", "float3", "float4"},
697 {"double", "double2", "double3", "double4"},
698 {"char", "char2", "char3", "char4"},
699 {"short", "short2", "short3", "short4"},
700 {"int", "int2", "int3", "int4"},
701 {"long", "long2", "long3", "long4"},
702 {"uchar", "uchar2", "uchar3", "uchar4"},
703 {"ushort", "ushort2", "ushort3", "ushort4"},
704 {"uint", "uint2", "uint3", "uint4"},
705 {"ulong", "ulong2", "ulong3", "ulong4"},
706 {"bool", "bool2", "bool3", "bool4"},
707 {"packed_565", "packed_565", "packed_565", "packed_565"},
708 {"packed_5551", "packed_5551", "packed_5551", "packed_5551"},
709 {"packed_4444", "packed_4444", "packed_4444", "packed_4444"},
710 {"rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4"},
711 {"rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3"},
712 {"rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2"},
715 {"RS Element", "RS Element", "RS Element", "RS Element"},
716 {"RS Type", "RS Type", "RS Type", "RS Type"},
717 {"RS Allocation", "RS Allocation", "RS Allocation", "RS Allocation"},
718 {"RS Sampler", "RS Sampler", "RS Sampler", "RS Sampler"},
719 {"RS Script", "RS Script", "RS Script", "RS Script"},
722 {"RS Mesh", "RS Mesh", "RS Mesh", "RS Mesh"},
723 {"RS Program Fragment", "RS Program Fragment", "RS Program Fragment", "RS Program Fragment"},
724 {"RS Program Vertex", "RS Program Vertex", "RS Program Vertex", "RS Program Vertex"},
725 {"RS Program Raster", "RS Program Raster", "RS Program Raster", "RS Program Raster"},
726 {"RS Program Store", "RS Program Store", "RS Program Store", "RS Program Store"},
727 {"RS Font", "RS Font", "RS Font", "RS Font"}};
729 // Used as an index into the RSTypeToFormat array elements
730 enum TypeToFormatIndex
737 // { format enum of single element, format enum of element vector, size of element}
738 const uint32_t RenderScriptRuntime::AllocationDetails::RSTypeToFormat[][3] = {
739 {eFormatHex, eFormatHex, 1}, // RS_TYPE_NONE
740 {eFormatFloat, eFormatVectorOfFloat16, 2}, // RS_TYPE_FLOAT_16
741 {eFormatFloat, eFormatVectorOfFloat32, sizeof(float)}, // RS_TYPE_FLOAT_32
742 {eFormatFloat, eFormatVectorOfFloat64, sizeof(double)}, // RS_TYPE_FLOAT_64
743 {eFormatDecimal, eFormatVectorOfSInt8, sizeof(int8_t)}, // RS_TYPE_SIGNED_8
744 {eFormatDecimal, eFormatVectorOfSInt16, sizeof(int16_t)}, // RS_TYPE_SIGNED_16
745 {eFormatDecimal, eFormatVectorOfSInt32, sizeof(int32_t)}, // RS_TYPE_SIGNED_32
746 {eFormatDecimal, eFormatVectorOfSInt64, sizeof(int64_t)}, // RS_TYPE_SIGNED_64
747 {eFormatDecimal, eFormatVectorOfUInt8, sizeof(uint8_t)}, // RS_TYPE_UNSIGNED_8
748 {eFormatDecimal, eFormatVectorOfUInt16, sizeof(uint16_t)}, // RS_TYPE_UNSIGNED_16
749 {eFormatDecimal, eFormatVectorOfUInt32, sizeof(uint32_t)}, // RS_TYPE_UNSIGNED_32
750 {eFormatDecimal, eFormatVectorOfUInt64, sizeof(uint64_t)}, // RS_TYPE_UNSIGNED_64
751 {eFormatBoolean, eFormatBoolean, 1}, // RS_TYPE_BOOL
752 {eFormatHex, eFormatHex, sizeof(uint16_t)}, // RS_TYPE_UNSIGNED_5_6_5
753 {eFormatHex, eFormatHex, sizeof(uint16_t)}, // RS_TYPE_UNSIGNED_5_5_5_1
754 {eFormatHex, eFormatHex, sizeof(uint16_t)}, // RS_TYPE_UNSIGNED_4_4_4_4
755 {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 16}, // RS_TYPE_MATRIX_4X4
756 {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 9}, // RS_TYPE_MATRIX_3X3
757 {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 4} // RS_TYPE_MATRIX_2X2
760 //------------------------------------------------------------------
762 //------------------------------------------------------------------
764 RenderScriptRuntime::CreateInstance(Process *process, lldb::LanguageType language)
767 if (language == eLanguageTypeExtRenderScript)
768 return new RenderScriptRuntime(process);
773 // Callback with a module to search for matching symbols.
774 // We first check that the module contains RS kernels.
775 // Then look for a symbol which matches our kernel name.
776 // The breakpoint address is finally set using the address of this symbol.
777 Searcher::CallbackReturn
778 RSBreakpointResolver::SearchCallback(SearchFilter &filter, SymbolContext &context, Address *, bool)
780 ModuleSP module = context.module_sp;
783 return Searcher::eCallbackReturnContinue;
785 // Is this a module containing renderscript kernels?
786 if (nullptr == module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData))
787 return Searcher::eCallbackReturnContinue;
789 // Attempt to set a breakpoint on the kernel name symbol within the module library.
790 // If it's not found, it's likely debug info is unavailable - try to set a
791 // breakpoint on <name>.expand.
793 const Symbol *kernel_sym = module->FindFirstSymbolWithNameAndType(m_kernel_name, eSymbolTypeCode);
796 std::string kernel_name_expanded(m_kernel_name.AsCString());
797 kernel_name_expanded.append(".expand");
798 kernel_sym = module->FindFirstSymbolWithNameAndType(ConstString(kernel_name_expanded.c_str()), eSymbolTypeCode);
803 Address bp_addr = kernel_sym->GetAddress();
804 if (filter.AddressPasses(bp_addr))
805 m_breakpoint->AddLocation(bp_addr);
808 return Searcher::eCallbackReturnContinue;
812 RenderScriptRuntime::Initialize()
814 PluginManager::RegisterPlugin(GetPluginNameStatic(), "RenderScript language support", CreateInstance,
819 RenderScriptRuntime::Terminate()
821 PluginManager::UnregisterPlugin(CreateInstance);
824 lldb_private::ConstString
825 RenderScriptRuntime::GetPluginNameStatic()
827 static ConstString g_name("renderscript");
831 RenderScriptRuntime::ModuleKind
832 RenderScriptRuntime::GetModuleKind(const lldb::ModuleSP &module_sp)
836 // Is this a module containing renderscript kernels?
837 const Symbol *info_sym = module_sp->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData);
840 return eModuleKindKernelObj;
843 // Is this the main RS runtime library
844 const ConstString rs_lib("libRS.so");
845 if (module_sp->GetFileSpec().GetFilename() == rs_lib)
847 return eModuleKindLibRS;
850 const ConstString rs_driverlib("libRSDriver.so");
851 if (module_sp->GetFileSpec().GetFilename() == rs_driverlib)
853 return eModuleKindDriver;
856 const ConstString rs_cpureflib("libRSCpuRef.so");
857 if (module_sp->GetFileSpec().GetFilename() == rs_cpureflib)
859 return eModuleKindImpl;
862 return eModuleKindIgnored;
866 RenderScriptRuntime::IsRenderScriptModule(const lldb::ModuleSP &module_sp)
868 return GetModuleKind(module_sp) != eModuleKindIgnored;
872 RenderScriptRuntime::ModulesDidLoad(const ModuleList &module_list)
874 std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
876 size_t num_modules = module_list.GetSize();
877 for (size_t i = 0; i < num_modules; i++)
879 auto mod = module_list.GetModuleAtIndex(i);
880 if (IsRenderScriptModule(mod))
887 //------------------------------------------------------------------
888 // PluginInterface protocol
889 //------------------------------------------------------------------
890 lldb_private::ConstString
891 RenderScriptRuntime::GetPluginName()
893 return GetPluginNameStatic();
897 RenderScriptRuntime::GetPluginVersion()
903 RenderScriptRuntime::IsVTableName(const char *name)
909 RenderScriptRuntime::GetDynamicTypeAndAddress(ValueObject &in_value, lldb::DynamicValueType use_dynamic,
910 TypeAndOrName &class_type_or_name, Address &address,
911 Value::ValueType &value_type)
917 RenderScriptRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name, ValueObject &static_value)
919 return type_and_or_name;
923 RenderScriptRuntime::CouldHaveDynamicValue(ValueObject &in_value)
928 lldb::BreakpointResolverSP
929 RenderScriptRuntime::CreateExceptionResolver(Breakpoint *bkpt, bool catch_bp, bool throw_bp)
931 BreakpointResolverSP resolver_sp;
935 const RenderScriptRuntime::HookDefn RenderScriptRuntime::s_runtimeHookDefns[] = {
939 "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_7ScriptCEPKcS7_PKhjj",
940 "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_7ScriptCEPKcS7_PKhmj",
942 RenderScriptRuntime::eModuleKindDriver,
943 &lldb_private::RenderScriptRuntime::CaptureScriptInit
946 "rsdScriptInvokeForEachMulti",
947 "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0_6ScriptEjPPKNS0_10AllocationEjPS6_PKvjPK12RsScriptCall",
948 "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0_6ScriptEjPPKNS0_10AllocationEmPS6_PKvmPK12RsScriptCall",
950 RenderScriptRuntime::eModuleKindDriver,
951 &lldb_private::RenderScriptRuntime::CaptureScriptInvokeForEachMulti
954 "rsdScriptSetGlobalVar",
955 "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_6ScriptEjPvj",
956 "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_6ScriptEjPvm",
958 RenderScriptRuntime::eModuleKindDriver,
959 &lldb_private::RenderScriptRuntime::CaptureSetGlobalVar
965 "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_10AllocationEb",
966 "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_10AllocationEb",
968 RenderScriptRuntime::eModuleKindDriver,
969 &lldb_private::RenderScriptRuntime::CaptureAllocationInit
972 "rsdAllocationRead2D",
973 "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_10AllocationEjjj23RsAllocationCubemapFacejjPvjj",
974 "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_10AllocationEjjj23RsAllocationCubemapFacejjPvmm",
976 RenderScriptRuntime::eModuleKindDriver,
980 "rsdAllocationDestroy",
981 "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_10AllocationE",
982 "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_10AllocationE",
984 RenderScriptRuntime::eModuleKindDriver,
985 &lldb_private::RenderScriptRuntime::CaptureAllocationDestroy
989 const size_t RenderScriptRuntime::s_runtimeHookCount = sizeof(s_runtimeHookDefns) / sizeof(s_runtimeHookDefns[0]);
992 RenderScriptRuntime::HookCallback(void *baton, StoppointCallbackContext *ctx, lldb::user_id_t break_id,
993 lldb::user_id_t break_loc_id)
995 RuntimeHook *hook_info = (RuntimeHook *)baton;
996 ExecutionContext context(ctx->exe_ctx_ref);
998 RenderScriptRuntime *lang_rt =
999 (RenderScriptRuntime *)context.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
1001 lang_rt->HookCallback(hook_info, context);
1007 RenderScriptRuntime::HookCallback(RuntimeHook *hook_info, ExecutionContext &context)
1009 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1012 log->Printf("%s - '%s'", __FUNCTION__, hook_info->defn->name);
1014 if (hook_info->defn->grabber)
1016 (this->*(hook_info->defn->grabber))(hook_info, context);
1021 RenderScriptRuntime::CaptureScriptInvokeForEachMulti(RuntimeHook* hook_info,
1022 ExecutionContext& context)
1024 Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1039 std::array<ArgItem, 9> args{{
1040 ArgItem{ArgItem::ePointer, 0}, // const Context *rsc
1041 ArgItem{ArgItem::ePointer, 0}, // Script *s
1042 ArgItem{ArgItem::eInt32, 0}, // uint32_t slot
1043 ArgItem{ArgItem::ePointer, 0}, // const Allocation **aIns
1044 ArgItem{ArgItem::eInt32, 0}, // size_t inLen
1045 ArgItem{ArgItem::ePointer, 0}, // Allocation *aout
1046 ArgItem{ArgItem::ePointer, 0}, // const void *usr
1047 ArgItem{ArgItem::eInt32, 0}, // size_t usrLen
1048 ArgItem{ArgItem::ePointer, 0}, // const RsScriptCall *sc
1051 bool success = GetArgs(context, &args[0], args.size());
1055 log->Printf("%s - Error while reading the function parameters", __FUNCTION__);
1059 const uint32_t target_ptr_size = m_process->GetAddressByteSize();
1061 std::vector<uint64_t> allocs;
1063 // traverse allocation list
1064 for (uint64_t i = 0; i < uint64_t(args[eRsInLen]); ++i)
1066 // calculate offest to allocation pointer
1067 const addr_t addr = addr_t(args[eRsAIns]) + i * target_ptr_size;
1069 // Note: due to little endian layout, reading 32bits or 64bits into res64 will
1070 // give the correct results.
1073 size_t read = m_process->ReadMemory(addr, &res64, target_ptr_size, error);
1074 if (read != target_ptr_size || !error.Success())
1077 log->Printf("%s - Error while reading allocation list argument %" PRIu64, __FUNCTION__, i);
1081 allocs.push_back(res64);
1085 // if there is an output allocation track it
1086 if (uint64_t aOut = uint64_t(args[eRsAOut]))
1088 allocs.push_back(aOut);
1091 // for all allocations we have found
1092 for (const uint64_t alloc_addr : allocs)
1094 AllocationDetails* alloc = LookUpAllocation(alloc_addr, true);
1097 // save the allocation address
1098 if (alloc->address.isValid())
1100 // check the allocation address we already have matches
1101 assert(*alloc->address.get() == alloc_addr);
1105 alloc->address = alloc_addr;
1111 if (alloc->context.isValid() && *alloc->context.get() != addr_t(args[eRsContext]))
1112 log->Printf("%s - Allocation used by multiple contexts", __FUNCTION__);
1114 alloc->context = addr_t(args[eRsContext]);
1118 // make sure we track this script object
1119 if (lldb_private::RenderScriptRuntime::ScriptDetails *script = LookUpScript(addr_t(args[eRsScript]), true))
1123 if (script->context.isValid() && *script->context.get() != addr_t(args[eRsContext]))
1124 log->Printf("%s - Script used by multiple contexts", __FUNCTION__);
1126 script->context = addr_t(args[eRsContext]);
1131 RenderScriptRuntime::CaptureSetGlobalVar(RuntimeHook *hook_info, ExecutionContext &context)
1133 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1144 std::array<ArgItem, 5> args{{
1145 ArgItem{ArgItem::ePointer, 0}, // eRsContext
1146 ArgItem{ArgItem::ePointer, 0}, // eRsScript
1147 ArgItem{ArgItem::eInt32, 0}, // eRsId
1148 ArgItem{ArgItem::ePointer, 0}, // eRsData
1149 ArgItem{ArgItem::eInt32, 0}, // eRsLength
1152 bool success = GetArgs(context, &args[0], args.size());
1156 log->Printf("%s - error reading the function parameters.", __FUNCTION__);
1162 log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " slot %" PRIu64 " = 0x%" PRIx64 ":%" PRIu64 "bytes.", __FUNCTION__,
1163 uint64_t(args[eRsContext]), uint64_t(args[eRsScript]), uint64_t(args[eRsId]),
1164 uint64_t(args[eRsData]), uint64_t(args[eRsLength]));
1166 addr_t script_addr = addr_t(args[eRsScript]);
1167 if (m_scriptMappings.find(script_addr) != m_scriptMappings.end())
1169 auto rsm = m_scriptMappings[script_addr];
1170 if (uint64_t(args[eRsId]) < rsm->m_globals.size())
1172 auto rsg = rsm->m_globals[uint64_t(args[eRsId])];
1173 log->Printf("%s - Setting of '%s' within '%s' inferred", __FUNCTION__, rsg.m_name.AsCString(),
1174 rsm->m_module->GetFileSpec().GetFilename().AsCString());
1181 RenderScriptRuntime::CaptureAllocationInit(RuntimeHook *hook_info, ExecutionContext &context)
1183 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1192 std::array<ArgItem, 3> args{{
1193 ArgItem{ArgItem::ePointer, 0}, // eRsContext
1194 ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
1195 ArgItem{ArgItem::eBool, 0}, // eRsForceZero
1198 bool success = GetArgs(context, &args[0], args.size());
1199 if (!success) // error case
1202 log->Printf("%s - error while reading the function parameters", __FUNCTION__);
1207 log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 ",0x%" PRIx64 " .", __FUNCTION__, uint64_t(args[eRsContext]),
1208 uint64_t(args[eRsAlloc]), uint64_t(args[eRsForceZero]));
1210 AllocationDetails *alloc = LookUpAllocation(uint64_t(args[eRsAlloc]), true);
1212 alloc->context = uint64_t(args[eRsContext]);
1216 RenderScriptRuntime::CaptureAllocationDestroy(RuntimeHook *hook_info, ExecutionContext &context)
1218 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1226 std::array<ArgItem, 2> args{{
1227 ArgItem{ArgItem::ePointer, 0}, // eRsContext
1228 ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
1231 bool success = GetArgs(context, &args[0], args.size());
1235 log->Printf("%s - error while reading the function parameters.", __FUNCTION__);
1240 log->Printf("%s - 0x%" PRIx64 ", 0x%" PRIx64 ".", __FUNCTION__, uint64_t(args[eRsContext]),
1241 uint64_t(args[eRsAlloc]));
1243 for (auto iter = m_allocations.begin(); iter != m_allocations.end(); ++iter)
1245 auto &allocation_ap = *iter; // get the unique pointer
1246 if (allocation_ap->address.isValid() && *allocation_ap->address.get() == addr_t(args[eRsAlloc]))
1248 m_allocations.erase(iter);
1250 log->Printf("%s - deleted allocation entry.", __FUNCTION__);
1256 log->Printf("%s - couldn't find destroyed allocation.", __FUNCTION__);
1260 RenderScriptRuntime::CaptureScriptInit(RuntimeHook *hook_info, ExecutionContext &context)
1262 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1265 Process *process = context.GetProcessPtr();
1275 std::array<ArgItem, 4> args{{ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0},
1276 ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0}}};
1277 bool success = GetArgs(context, &args[0], args.size());
1281 log->Printf("%s - error while reading the function parameters.", __FUNCTION__);
1285 std::string resname;
1286 process->ReadCStringFromMemory(addr_t(args[eRsResNamePtr]), resname, error);
1290 log->Printf("%s - error reading resname: %s.", __FUNCTION__, error.AsCString());
1293 std::string cachedir;
1294 process->ReadCStringFromMemory(addr_t(args[eRsCachedDirPtr]), cachedir, error);
1298 log->Printf("%s - error reading cachedir: %s.", __FUNCTION__, error.AsCString());
1302 log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " => '%s' at '%s' .", __FUNCTION__, uint64_t(args[eRsContext]),
1303 uint64_t(args[eRsScript]), resname.c_str(), cachedir.c_str());
1305 if (resname.size() > 0)
1308 strm.Printf("librs.%s.so", resname.c_str());
1310 ScriptDetails *script = LookUpScript(addr_t(args[eRsScript]), true);
1313 script->type = ScriptDetails::eScriptC;
1314 script->cacheDir = cachedir;
1315 script->resName = resname;
1316 script->scriptDyLib = strm.GetData();
1317 script->context = addr_t(args[eRsContext]);
1321 log->Printf("%s - '%s' tagged with context 0x%" PRIx64 " and script 0x%" PRIx64 ".", __FUNCTION__,
1322 strm.GetData(), uint64_t(args[eRsContext]), uint64_t(args[eRsScript]));
1326 log->Printf("%s - resource name invalid, Script not tagged.", __FUNCTION__);
1331 RenderScriptRuntime::LoadRuntimeHooks(lldb::ModuleSP module, ModuleKind kind)
1333 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1340 Target &target = GetProcess()->GetTarget();
1341 llvm::Triple::ArchType targetArchType = target.GetArchitecture().GetMachine();
1343 if (targetArchType != llvm::Triple::ArchType::x86 &&
1344 targetArchType != llvm::Triple::ArchType::arm &&
1345 targetArchType != llvm::Triple::ArchType::aarch64 &&
1346 targetArchType != llvm::Triple::ArchType::mipsel &&
1347 targetArchType != llvm::Triple::ArchType::mips64el &&
1348 targetArchType != llvm::Triple::ArchType::x86_64)
1351 log->Printf("%s - unable to hook runtime functions.", __FUNCTION__);
1355 uint32_t archByteSize = target.GetArchitecture().GetAddressByteSize();
1357 for (size_t idx = 0; idx < s_runtimeHookCount; idx++)
1359 const HookDefn *hook_defn = &s_runtimeHookDefns[idx];
1360 if (hook_defn->kind != kind)
1365 const char *symbol_name = (archByteSize == 4) ? hook_defn->symbol_name_m32 : hook_defn->symbol_name_m64;
1367 const Symbol *sym = module->FindFirstSymbolWithNameAndType(ConstString(symbol_name), eSymbolTypeCode);
1372 log->Printf("%s - symbol '%s' related to the function %s not found",
1373 __FUNCTION__, symbol_name, hook_defn->name);
1378 addr_t addr = sym->GetLoadAddress(&target);
1379 if (addr == LLDB_INVALID_ADDRESS)
1382 log->Printf("%s - unable to resolve the address of hook function '%s' with symbol '%s'.",
1383 __FUNCTION__, hook_defn->name, symbol_name);
1389 log->Printf("%s - function %s, address resolved at 0x%" PRIx64,
1390 __FUNCTION__, hook_defn->name, addr);
1393 RuntimeHookSP hook(new RuntimeHook());
1394 hook->address = addr;
1395 hook->defn = hook_defn;
1396 hook->bp_sp = target.CreateBreakpoint(addr, true, false);
1397 hook->bp_sp->SetCallback(HookCallback, hook.get(), true);
1398 m_runtimeHooks[addr] = hook;
1401 log->Printf("%s - successfully hooked '%s' in '%s' version %" PRIu64 " at 0x%" PRIx64 ".",
1402 __FUNCTION__, hook_defn->name, module->GetFileSpec().GetFilename().AsCString(),
1403 (uint64_t)hook_defn->version, (uint64_t)addr);
1409 RenderScriptRuntime::FixupScriptDetails(RSModuleDescriptorSP rsmodule_sp)
1414 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1416 const ModuleSP module = rsmodule_sp->m_module;
1417 const FileSpec &file = module->GetPlatformFileSpec();
1419 // Iterate over all of the scripts that we currently know of.
1420 // Note: We cant push or pop to m_scripts here or it may invalidate rs_script.
1421 for (const auto &rs_script : m_scripts)
1423 // Extract the expected .so file path for this script.
1425 if (!rs_script->scriptDyLib.get(dylib))
1428 // Only proceed if the module that has loaded corresponds to this script.
1429 if (file.GetFilename() != ConstString(dylib.c_str()))
1432 // Obtain the script address which we use as a key.
1433 lldb::addr_t script;
1434 if (!rs_script->script.get(script))
1437 // If we have a script mapping for the current script.
1438 if (m_scriptMappings.find(script) != m_scriptMappings.end())
1440 // if the module we have stored is different to the one we just received.
1441 if (m_scriptMappings[script] != rsmodule_sp)
1444 log->Printf("%s - script %" PRIx64 " wants reassigned to new rsmodule '%s'.", __FUNCTION__,
1445 (uint64_t)script, rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
1448 // We don't have a script mapping for the current script.
1451 // Obtain the script resource name.
1452 std::string resName;
1453 if (rs_script->resName.get(resName))
1454 // Set the modules resource name.
1455 rsmodule_sp->m_resname = resName;
1456 // Add Script/Module pair to map.
1457 m_scriptMappings[script] = rsmodule_sp;
1459 log->Printf("%s - script %" PRIx64 " associated with rsmodule '%s'.", __FUNCTION__,
1460 (uint64_t)script, rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
1465 // Uses the Target API to evaluate the expression passed as a parameter to the function
1466 // The result of that expression is returned an unsigned 64 bit int, via the result* paramter.
1467 // Function returns true on success, and false on failure
1469 RenderScriptRuntime::EvalRSExpression(const char *expression, StackFrame *frame_ptr, uint64_t *result)
1471 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1473 log->Printf("%s(%s)", __FUNCTION__, expression);
1475 ValueObjectSP expr_result;
1476 EvaluateExpressionOptions options;
1477 options.SetLanguage(lldb::eLanguageTypeC_plus_plus);
1478 // Perform the actual expression evaluation
1479 GetProcess()->GetTarget().EvaluateExpression(expression, frame_ptr, expr_result, options);
1484 log->Printf("%s: couldn't evaluate expression.", __FUNCTION__);
1488 // The result of the expression is invalid
1489 if (!expr_result->GetError().Success())
1491 Error err = expr_result->GetError();
1492 if (err.GetError() == UserExpression::kNoResult) // Expression returned void, so this is actually a success
1495 log->Printf("%s - expression returned void.", __FUNCTION__);
1502 log->Printf("%s - error evaluating expression result: %s", __FUNCTION__,
1507 bool success = false;
1508 *result = expr_result->GetValueAsUnsigned(0, &success); // We only read the result as an uint32_t.
1513 log->Printf("%s - couldn't convert expression result to uint32_t", __FUNCTION__);
1522 // Used to index expression format strings
1523 enum ExpressionStrings
1525 eExprGetOffsetPtr = 0,
1534 eExprElementFieldCount,
1536 eExprSubelementsName,
1537 eExprSubelementsArrSize,
1539 _eExprLast // keep at the end, implicit size of the array runtimeExpressions
1542 // max length of an expanded expression
1543 const int jit_max_expr_size = 512;
1545 // Retrieve the string to JIT for the given expression
1547 JITTemplate(ExpressionStrings e)
1549 // Format strings containing the expressions we may need to evaluate.
1550 static std::array<const char*, _eExprLast> runtimeExpressions = {{
1551 // Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap)
1552 "(int*)_Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocationCubemapFace"
1553 "(0x%" PRIx64 ", %" PRIu32 ", %" PRIu32 ", %" PRIu32 ", 0, 0)",
1555 // Type* rsaAllocationGetType(Context*, Allocation*)
1556 "(void*)rsaAllocationGetType(0x%" PRIx64 ", 0x%" PRIx64 ")",
1558 // rsaTypeGetNativeData(Context*, Type*, void* typeData, size)
1559 // Pack the data in the following way mHal.state.dimX; mHal.state.dimY; mHal.state.dimZ;
1560 // mHal.state.lodCount; mHal.state.faces; mElement; into typeData
1561 // Need to specify 32 or 64 bit for uint_t since this differs between devices
1562 "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64 ", 0x%" PRIx64 ", data, 6); data[0]", // X dim
1563 "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64 ", 0x%" PRIx64 ", data, 6); data[1]", // Y dim
1564 "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64 ", 0x%" PRIx64 ", data, 6); data[2]", // Z dim
1565 "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64 ", 0x%" PRIx64 ", data, 6); data[5]", // Element ptr
1567 // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size)
1568 // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into elemData
1569 "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64 ", 0x%" PRIx64 ", data, 5); data[0]", // Type
1570 "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64 ", 0x%" PRIx64 ", data, 5); data[1]", // Kind
1571 "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64 ", 0x%" PRIx64 ", data, 5); data[3]", // Vector Size
1572 "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64 ", 0x%" PRIx64 ", data, 5); data[4]", // Field Count
1574 // rsaElementGetSubElements(RsContext con, RsElement elem, uintptr_t *ids, const char **names,
1575 // size_t *arraySizes, uint32_t dataSize)
1576 // Needed for Allocations of structs to gather details about fields/Subelements
1577 // Element* of field
1578 "void* ids[%" PRIu32 "]; const char* names[%" PRIu32 "]; size_t arr_size[%" PRIu32 "];"
1579 "(void*)rsaElementGetSubElements(0x%" PRIx64 ", 0x%" PRIx64 ", ids, names, arr_size, %" PRIu32 "); ids[%" PRIu32 "]",
1582 "void* ids[%" PRIu32 "]; const char* names[%" PRIu32 "]; size_t arr_size[%" PRIu32 "];"
1583 "(void*)rsaElementGetSubElements(0x%" PRIx64 ", 0x%" PRIx64 ", ids, names, arr_size, %" PRIu32 "); names[%" PRIu32 "]",
1585 // Array size of field
1586 "void* ids[%" PRIu32 "]; const char* names[%" PRIu32 "]; size_t arr_size[%" PRIu32 "];"
1587 "(void*)rsaElementGetSubElements(0x%" PRIx64 ", 0x%" PRIx64 ", ids, names, arr_size, %" PRIu32 "); arr_size[%" PRIu32 "]"
1590 return runtimeExpressions[e];
1592 } // end of the anonymous namespace
1595 // JITs the RS runtime for the internal data pointer of an allocation.
1596 // Is passed x,y,z coordinates for the pointer to a specific element.
1597 // Then sets the data_ptr member in Allocation with the result.
1598 // Returns true on success, false otherwise
1600 RenderScriptRuntime::JITDataPointer(AllocationDetails *allocation, StackFrame *frame_ptr, uint32_t x,
1601 uint32_t y, uint32_t z)
1603 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1605 if (!allocation->address.isValid())
1608 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
1612 const char *expr_cstr = JITTemplate(eExprGetOffsetPtr);
1613 char buffer[jit_max_expr_size];
1615 int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->address.get(), x, y, z);
1616 if (chars_written < 0)
1619 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1622 else if (chars_written >= jit_max_expr_size)
1625 log->Printf("%s - expression too long.", __FUNCTION__);
1629 uint64_t result = 0;
1630 if (!EvalRSExpression(buffer, frame_ptr, &result))
1633 addr_t mem_ptr = static_cast<lldb::addr_t>(result);
1634 allocation->data_ptr = mem_ptr;
1639 // JITs the RS runtime for the internal pointer to the RS Type of an allocation
1640 // Then sets the type_ptr member in Allocation with the result.
1641 // Returns true on success, false otherwise
1643 RenderScriptRuntime::JITTypePointer(AllocationDetails *allocation, StackFrame *frame_ptr)
1645 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1647 if (!allocation->address.isValid() || !allocation->context.isValid())
1650 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
1654 const char *expr_cstr = JITTemplate(eExprAllocGetType);
1655 char buffer[jit_max_expr_size];
1658 snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->context.get(), *allocation->address.get());
1659 if (chars_written < 0)
1662 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1665 else if (chars_written >= jit_max_expr_size)
1668 log->Printf("%s - expression too long.", __FUNCTION__);
1672 uint64_t result = 0;
1673 if (!EvalRSExpression(buffer, frame_ptr, &result))
1676 addr_t type_ptr = static_cast<lldb::addr_t>(result);
1677 allocation->type_ptr = type_ptr;
1682 // JITs the RS runtime for information about the dimensions and type of an allocation
1683 // Then sets dimension and element_ptr members in Allocation with the result.
1684 // Returns true on success, false otherwise
1686 RenderScriptRuntime::JITTypePacked(AllocationDetails *allocation, StackFrame *frame_ptr)
1688 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1690 if (!allocation->type_ptr.isValid() || !allocation->context.isValid())
1693 log->Printf("%s - Failed to find allocation details.", __FUNCTION__);
1697 // Expression is different depending on if device is 32 or 64 bit
1698 uint32_t archByteSize = GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
1699 const uint32_t bits = archByteSize == 4 ? 32 : 64;
1701 // We want 4 elements from packed data
1702 const uint32_t num_exprs = 4;
1703 assert(num_exprs == (eExprTypeElemPtr - eExprTypeDimX + 1) && "Invalid number of expressions");
1705 char buffer[num_exprs][jit_max_expr_size];
1706 uint64_t results[num_exprs];
1708 for (uint32_t i = 0; i < num_exprs; ++i)
1710 const char *expr_cstr = JITTemplate(ExpressionStrings(eExprTypeDimX + i));
1711 int chars_written = snprintf(buffer[i], jit_max_expr_size, expr_cstr, bits, *allocation->context.get(),
1712 *allocation->type_ptr.get());
1713 if (chars_written < 0)
1716 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1719 else if (chars_written >= jit_max_expr_size)
1722 log->Printf("%s - expression too long.", __FUNCTION__);
1726 // Perform expression evaluation
1727 if (!EvalRSExpression(buffer[i], frame_ptr, &results[i]))
1731 // Assign results to allocation members
1732 AllocationDetails::Dimension dims;
1733 dims.dim_1 = static_cast<uint32_t>(results[0]);
1734 dims.dim_2 = static_cast<uint32_t>(results[1]);
1735 dims.dim_3 = static_cast<uint32_t>(results[2]);
1736 allocation->dimension = dims;
1738 addr_t elem_ptr = static_cast<lldb::addr_t>(results[3]);
1739 allocation->element.element_ptr = elem_ptr;
1742 log->Printf("%s - dims (%" PRIu32 ", %" PRIu32 ", %" PRIu32 ") Element*: 0x%" PRIx64 ".", __FUNCTION__,
1743 dims.dim_1, dims.dim_2, dims.dim_3, elem_ptr);
1748 // JITs the RS runtime for information about the Element of an allocation
1749 // Then sets type, type_vec_size, field_count and type_kind members in Element with the result.
1750 // Returns true on success, false otherwise
1752 RenderScriptRuntime::JITElementPacked(Element &elem, const lldb::addr_t context, StackFrame *frame_ptr)
1754 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1756 if (!elem.element_ptr.isValid())
1759 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
1763 // We want 4 elements from packed data
1764 const uint32_t num_exprs = 4;
1765 assert(num_exprs == (eExprElementFieldCount - eExprElementType + 1) && "Invalid number of expressions");
1767 char buffer[num_exprs][jit_max_expr_size];
1768 uint64_t results[num_exprs];
1770 for (uint32_t i = 0; i < num_exprs; i++)
1772 const char *expr_cstr = JITTemplate(ExpressionStrings(eExprElementType + i));
1773 int chars_written = snprintf(buffer[i], jit_max_expr_size, expr_cstr, context, *elem.element_ptr.get());
1774 if (chars_written < 0)
1777 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1780 else if (chars_written >= jit_max_expr_size)
1783 log->Printf("%s - expression too long.", __FUNCTION__);
1787 // Perform expression evaluation
1788 if (!EvalRSExpression(buffer[i], frame_ptr, &results[i]))
1792 // Assign results to allocation members
1793 elem.type = static_cast<RenderScriptRuntime::Element::DataType>(results[0]);
1794 elem.type_kind = static_cast<RenderScriptRuntime::Element::DataKind>(results[1]);
1795 elem.type_vec_size = static_cast<uint32_t>(results[2]);
1796 elem.field_count = static_cast<uint32_t>(results[3]);
1799 log->Printf("%s - data type %" PRIu32 ", pixel type %" PRIu32 ", vector size %" PRIu32 ", field count %" PRIu32,
1800 __FUNCTION__, *elem.type.get(), *elem.type_kind.get(), *elem.type_vec_size.get(), *elem.field_count.get());
1802 // If this Element has subelements then JIT rsaElementGetSubElements() for details about its fields
1803 if (*elem.field_count.get() > 0 && !JITSubelements(elem, context, frame_ptr))
1809 // JITs the RS runtime for information about the subelements/fields of a struct allocation
1810 // This is necessary for infering the struct type so we can pretty print the allocation's contents.
1811 // Returns true on success, false otherwise
1813 RenderScriptRuntime::JITSubelements(Element &elem, const lldb::addr_t context, StackFrame *frame_ptr)
1815 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1817 if (!elem.element_ptr.isValid() || !elem.field_count.isValid())
1820 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
1824 const short num_exprs = 3;
1825 assert(num_exprs == (eExprSubelementsArrSize - eExprSubelementsId + 1) && "Invalid number of expressions");
1827 char expr_buffer[jit_max_expr_size];
1830 // Iterate over struct fields.
1831 const uint32_t field_count = *elem.field_count.get();
1832 for (uint32_t field_index = 0; field_index < field_count; ++field_index)
1835 for (uint32_t expr_index = 0; expr_index < num_exprs; ++expr_index)
1837 const char *expr_cstr = JITTemplate(ExpressionStrings(eExprSubelementsId + expr_index));
1838 int chars_written = snprintf(expr_buffer, jit_max_expr_size, expr_cstr,
1839 field_count, field_count, field_count,
1840 context, *elem.element_ptr.get(), field_count, field_index);
1841 if (chars_written < 0)
1844 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1847 else if (chars_written >= jit_max_expr_size)
1850 log->Printf("%s - expression too long.", __FUNCTION__);
1854 // Perform expression evaluation
1855 if (!EvalRSExpression(expr_buffer, frame_ptr, &results))
1859 log->Printf("%s - expr result 0x%" PRIx64 ".", __FUNCTION__, results);
1863 case 0: // Element* of child
1864 child.element_ptr = static_cast<addr_t>(results);
1866 case 1: // Name of child
1868 lldb::addr_t address = static_cast<addr_t>(results);
1871 GetProcess()->ReadCStringFromMemory(address, name, err);
1873 child.type_name = ConstString(name);
1877 log->Printf("%s - warning: Couldn't read field name.", __FUNCTION__);
1881 case 2: // Array size of child
1882 child.array_size = static_cast<uint32_t>(results);
1887 // We need to recursively JIT each Element field of the struct since
1888 // structs can be nested inside structs.
1889 if (!JITElementPacked(child, context, frame_ptr))
1891 elem.children.push_back(child);
1894 // Try to infer the name of the struct type so we can pretty print the allocation contents.
1895 FindStructTypeName(elem, frame_ptr);
1900 // JITs the RS runtime for the address of the last element in the allocation.
1901 // The `elem_size` paramter represents the size of a single element, including padding.
1902 // Which is needed as an offset from the last element pointer.
1903 // Using this offset minus the starting address we can calculate the size of the allocation.
1904 // Returns true on success, false otherwise
1906 RenderScriptRuntime::JITAllocationSize(AllocationDetails *allocation, StackFrame *frame_ptr)
1908 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1910 if (!allocation->address.isValid() || !allocation->dimension.isValid() || !allocation->data_ptr.isValid() ||
1911 !allocation->element.datum_size.isValid())
1914 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
1919 uint32_t dim_x = allocation->dimension.get()->dim_1;
1920 uint32_t dim_y = allocation->dimension.get()->dim_2;
1921 uint32_t dim_z = allocation->dimension.get()->dim_3;
1923 // Our plan of jitting the last element address doesn't seem to work for struct Allocations
1924 // Instead try to infer the size ourselves without any inter element padding.
1925 if (allocation->element.children.size() > 0)
1927 if (dim_x == 0) dim_x = 1;
1928 if (dim_y == 0) dim_y = 1;
1929 if (dim_z == 0) dim_z = 1;
1931 allocation->size = dim_x * dim_y * dim_z * *allocation->element.datum_size.get();
1934 log->Printf("%s - infered size of struct allocation %" PRIu32 ".", __FUNCTION__,
1935 *allocation->size.get());
1939 const char *expr_cstr = JITTemplate(eExprGetOffsetPtr);
1940 char buffer[jit_max_expr_size];
1942 // Calculate last element
1943 dim_x = dim_x == 0 ? 0 : dim_x - 1;
1944 dim_y = dim_y == 0 ? 0 : dim_y - 1;
1945 dim_z = dim_z == 0 ? 0 : dim_z - 1;
1947 int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->address.get(), dim_x, dim_y, dim_z);
1948 if (chars_written < 0)
1951 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1954 else if (chars_written >= jit_max_expr_size)
1957 log->Printf("%s - expression too long.", __FUNCTION__);
1961 uint64_t result = 0;
1962 if (!EvalRSExpression(buffer, frame_ptr, &result))
1965 addr_t mem_ptr = static_cast<lldb::addr_t>(result);
1966 // Find pointer to last element and add on size of an element
1968 static_cast<uint32_t>(mem_ptr - *allocation->data_ptr.get()) + *allocation->element.datum_size.get();
1973 // JITs the RS runtime for information about the stride between rows in the allocation.
1974 // This is done to detect padding, since allocated memory is 16-byte aligned.
1975 // Returns true on success, false otherwise
1977 RenderScriptRuntime::JITAllocationStride(AllocationDetails *allocation, StackFrame *frame_ptr)
1979 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1981 if (!allocation->address.isValid() || !allocation->data_ptr.isValid())
1984 log->Printf("%s - failed to find allocation details.", __FUNCTION__);
1988 const char *expr_cstr = JITTemplate(eExprGetOffsetPtr);
1989 char buffer[jit_max_expr_size];
1991 int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->address.get(), 0, 1, 0);
1992 if (chars_written < 0)
1995 log->Printf("%s - encoding error in snprintf().", __FUNCTION__);
1998 else if (chars_written >= jit_max_expr_size)
2001 log->Printf("%s - expression too long.", __FUNCTION__);
2005 uint64_t result = 0;
2006 if (!EvalRSExpression(buffer, frame_ptr, &result))
2009 addr_t mem_ptr = static_cast<lldb::addr_t>(result);
2010 allocation->stride = static_cast<uint32_t>(mem_ptr - *allocation->data_ptr.get());
2015 // JIT all the current runtime info regarding an allocation
2017 RenderScriptRuntime::RefreshAllocation(AllocationDetails *allocation, StackFrame *frame_ptr)
2019 // GetOffsetPointer()
2020 if (!JITDataPointer(allocation, frame_ptr))
2023 // rsaAllocationGetType()
2024 if (!JITTypePointer(allocation, frame_ptr))
2027 // rsaTypeGetNativeData()
2028 if (!JITTypePacked(allocation, frame_ptr))
2031 // rsaElementGetNativeData()
2032 if (!JITElementPacked(allocation->element, *allocation->context.get(), frame_ptr))
2035 // Sets the datum_size member in Element
2036 SetElementSize(allocation->element);
2038 // Use GetOffsetPointer() to infer size of the allocation
2039 if (!JITAllocationSize(allocation, frame_ptr))
2045 // Function attempts to set the type_name member of the paramaterised Element object.
2046 // This string should be the name of the struct type the Element represents.
2047 // We need this string for pretty printing the Element to users.
2049 RenderScriptRuntime::FindStructTypeName(Element &elem, StackFrame *frame_ptr)
2051 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2053 if (!elem.type_name.IsEmpty()) // Name already set
2056 elem.type_name = Element::GetFallbackStructName(); // Default type name if we don't succeed
2058 // Find all the global variables from the script rs modules
2059 VariableList variable_list;
2060 for (auto module_sp : m_rsmodules)
2061 module_sp->m_module->FindGlobalVariables(RegularExpression("."), true, UINT32_MAX, variable_list);
2063 // Iterate over all the global variables looking for one with a matching type to the Element.
2064 // We make the assumption a match exists since there needs to be a global variable to reflect the
2065 // struct type back into java host code.
2066 for (uint32_t var_index = 0; var_index < variable_list.GetSize(); ++var_index)
2068 const VariableSP var_sp(variable_list.GetVariableAtIndex(var_index));
2072 ValueObjectSP valobj_sp = ValueObjectVariable::Create(frame_ptr, var_sp);
2076 // Find the number of variable fields.
2077 // If it has no fields, or more fields than our Element, then it can't be the struct we're looking for.
2078 // Don't check for equality since RS can add extra struct members for padding.
2079 size_t num_children = valobj_sp->GetNumChildren();
2080 if (num_children > elem.children.size() || num_children == 0)
2083 // Iterate over children looking for members with matching field names.
2084 // If all the field names match, this is likely the struct we want.
2086 // TODO: This could be made more robust by also checking children data sizes, or array size
2088 for (size_t child_index = 0; child_index < num_children; ++child_index)
2090 ValueObjectSP child = valobj_sp->GetChildAtIndex(child_index, true);
2091 if (!child || (child->GetName() != elem.children[child_index].type_name))
2098 // RS can add extra struct members for padding in the format '#rs_padding_[0-9]+'
2099 if (found && num_children < elem.children.size())
2101 const uint32_t size_diff = elem.children.size() - num_children;
2103 log->Printf("%s - %" PRIu32 " padding struct entries", __FUNCTION__, size_diff);
2105 for (uint32_t padding_index = 0; padding_index < size_diff; ++padding_index)
2107 const ConstString &name = elem.children[num_children + padding_index].type_name;
2108 if (strcmp(name.AsCString(), "#rs_padding") < 0)
2113 // We've found a global var with matching type
2116 // Dereference since our Element type isn't a pointer.
2117 if (valobj_sp->IsPointerType())
2120 ValueObjectSP deref_valobj = valobj_sp->Dereference(err);
2122 valobj_sp = deref_valobj;
2125 // Save name of variable in Element.
2126 elem.type_name = valobj_sp->GetTypeName();
2128 log->Printf("%s - element name set to %s", __FUNCTION__, elem.type_name.AsCString());
2135 // Function sets the datum_size member of Element. Representing the size of a single instance including padding.
2136 // Assumes the relevant allocation information has already been jitted.
2138 RenderScriptRuntime::SetElementSize(Element &elem)
2140 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2141 const Element::DataType type = *elem.type.get();
2142 assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT && "Invalid allocation type");
2144 const uint32_t vec_size = *elem.type_vec_size.get();
2145 uint32_t data_size = 0;
2146 uint32_t padding = 0;
2148 // Element is of a struct type, calculate size recursively.
2149 if ((type == Element::RS_TYPE_NONE) && (elem.children.size() > 0))
2151 for (Element &child : elem.children)
2153 SetElementSize(child);
2154 const uint32_t array_size = child.array_size.isValid() ? *child.array_size.get() : 1;
2155 data_size += *child.datum_size.get() * array_size;
2158 // These have been packed already
2159 else if (type == Element::RS_TYPE_UNSIGNED_5_6_5 ||
2160 type == Element::RS_TYPE_UNSIGNED_5_5_5_1 ||
2161 type == Element::RS_TYPE_UNSIGNED_4_4_4_4)
2163 data_size = AllocationDetails::RSTypeToFormat[type][eElementSize];
2165 else if (type < Element::RS_TYPE_ELEMENT)
2167 data_size = vec_size * AllocationDetails::RSTypeToFormat[type][eElementSize];
2169 padding = AllocationDetails::RSTypeToFormat[type][eElementSize];
2172 data_size = GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
2174 elem.padding = padding;
2175 elem.datum_size = data_size + padding;
2177 log->Printf("%s - element size set to %" PRIu32, __FUNCTION__, data_size + padding);
2180 // Given an allocation, this function copies the allocation contents from device into a buffer on the heap.
2181 // Returning a shared pointer to the buffer containing the data.
2182 std::shared_ptr<uint8_t>
2183 RenderScriptRuntime::GetAllocationData(AllocationDetails *allocation, StackFrame *frame_ptr)
2185 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2187 // JIT all the allocation details
2188 if (allocation->shouldRefresh())
2191 log->Printf("%s - allocation details not calculated yet, jitting info", __FUNCTION__);
2193 if (!RefreshAllocation(allocation, frame_ptr))
2196 log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
2201 assert(allocation->data_ptr.isValid() && allocation->element.type.isValid() &&
2202 allocation->element.type_vec_size.isValid() && allocation->size.isValid() &&
2203 "Allocation information not available");
2205 // Allocate a buffer to copy data into
2206 const uint32_t size = *allocation->size.get();
2207 std::shared_ptr<uint8_t> buffer(new uint8_t[size]);
2211 log->Printf("%s - couldn't allocate a %" PRIu32 " byte buffer", __FUNCTION__, size);
2215 // Read the inferior memory
2217 lldb::addr_t data_ptr = *allocation->data_ptr.get();
2218 GetProcess()->ReadMemory(data_ptr, buffer.get(), size, error);
2222 log->Printf("%s - '%s' Couldn't read %" PRIu32 " bytes of allocation data from 0x%" PRIx64,
2223 __FUNCTION__, error.AsCString(), size, data_ptr);
2230 // Function copies data from a binary file into an allocation.
2231 // There is a header at the start of the file, FileHeader, before the data content itself.
2232 // Information from this header is used to display warnings to the user about incompatabilities
2234 RenderScriptRuntime::LoadAllocation(Stream &strm, const uint32_t alloc_id, const char *filename, StackFrame *frame_ptr)
2236 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2238 // Find allocation with the given id
2239 AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
2244 log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__, *alloc->address.get());
2246 // JIT all the allocation details
2247 if (alloc->shouldRefresh())
2250 log->Printf("%s - allocation details not calculated yet, jitting info.", __FUNCTION__);
2252 if (!RefreshAllocation(alloc, frame_ptr))
2255 log->Printf("%s - couldn't JIT allocation details", __FUNCTION__);
2260 assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() && alloc->element.type_vec_size.isValid() &&
2261 alloc->size.isValid() && alloc->element.datum_size.isValid() && "Allocation information not available");
2263 // Check we can read from file
2264 FileSpec file(filename, true);
2267 strm.Printf("Error: File %s does not exist", filename);
2272 if (!file.Readable())
2274 strm.Printf("Error: File %s does not have readable permissions", filename);
2279 // Read file into data buffer
2280 DataBufferSP data_sp(file.ReadFileContents());
2282 // Cast start of buffer to FileHeader and use pointer to read metadata
2283 void *file_buffer = data_sp->GetBytes();
2284 if (file_buffer == nullptr ||
2285 data_sp->GetByteSize() < (sizeof(AllocationDetails::FileHeader) + sizeof(AllocationDetails::ElementHeader)))
2287 strm.Printf("Error: File %s does not contain enough data for header", filename);
2291 const AllocationDetails::FileHeader *file_header = static_cast<AllocationDetails::FileHeader *>(file_buffer);
2293 // Check file starts with ascii characters "RSAD"
2294 if (memcmp(file_header->ident, "RSAD", 4))
2296 strm.Printf("Error: File doesn't contain identifier for an RS allocation dump. Are you sure this is the correct file?");
2301 // Look at the type of the root element in the header
2302 AllocationDetails::ElementHeader root_element_header;
2303 memcpy(&root_element_header, static_cast<uint8_t *>(file_buffer) + sizeof(AllocationDetails::FileHeader),
2304 sizeof(AllocationDetails::ElementHeader));
2307 log->Printf("%s - header type %" PRIu32 ", element size %" PRIu32, __FUNCTION__,
2308 root_element_header.type, root_element_header.element_size);
2310 // Check if the target allocation and file both have the same number of bytes for an Element
2311 if (*alloc->element.datum_size.get() != root_element_header.element_size)
2313 strm.Printf("Warning: Mismatched Element sizes - file %" PRIu32 " bytes, allocation %" PRIu32 " bytes",
2314 root_element_header.element_size, *alloc->element.datum_size.get());
2318 // Check if the target allocation and file both have the same type
2319 const uint32_t alloc_type = static_cast<uint32_t>(*alloc->element.type.get());
2320 const uint32_t file_type = root_element_header.type;
2322 if (file_type > Element::RS_TYPE_FONT)
2324 strm.Printf("Warning: File has unknown allocation type");
2327 else if (alloc_type != file_type)
2329 // Enum value isn't monotonous, so doesn't always index RsDataTypeToString array
2330 uint32_t printable_target_type_index = alloc_type;
2331 uint32_t printable_head_type_index = file_type;
2332 if (alloc_type >= Element::RS_TYPE_ELEMENT && alloc_type <= Element::RS_TYPE_FONT)
2333 printable_target_type_index = static_cast<Element::DataType>((alloc_type - Element::RS_TYPE_ELEMENT) +
2334 Element::RS_TYPE_MATRIX_2X2 + 1);
2336 if (file_type >= Element::RS_TYPE_ELEMENT && file_type <= Element::RS_TYPE_FONT)
2337 printable_head_type_index = static_cast<Element::DataType>((file_type - Element::RS_TYPE_ELEMENT) +
2338 Element::RS_TYPE_MATRIX_2X2 + 1);
2340 const char *file_type_cstr = AllocationDetails::RsDataTypeToString[printable_head_type_index][0];
2341 const char *target_type_cstr = AllocationDetails::RsDataTypeToString[printable_target_type_index][0];
2343 strm.Printf("Warning: Mismatched Types - file '%s' type, allocation '%s' type", file_type_cstr,
2348 // Advance buffer past header
2349 file_buffer = static_cast<uint8_t *>(file_buffer) + file_header->hdr_size;
2351 // Calculate size of allocation data in file
2352 size_t length = data_sp->GetByteSize() - file_header->hdr_size;
2354 // Check if the target allocation and file both have the same total data size.
2355 const uint32_t alloc_size = *alloc->size.get();
2356 if (alloc_size != length)
2358 strm.Printf("Warning: Mismatched allocation sizes - file 0x%" PRIx64 " bytes, allocation 0x%" PRIx32 " bytes",
2359 (uint64_t)length, alloc_size);
2361 length = alloc_size < length ? alloc_size : length; // Set length to copy to minimum
2364 // Copy file data from our buffer into the target allocation.
2365 lldb::addr_t alloc_data = *alloc->data_ptr.get();
2367 size_t bytes_written = GetProcess()->WriteMemory(alloc_data, file_buffer, length, error);
2368 if (!error.Success() || bytes_written != length)
2370 strm.Printf("Error: Couldn't write data to allocation %s", error.AsCString());
2375 strm.Printf("Contents of file '%s' read into allocation %" PRIu32, filename, alloc->id);
2381 // Function takes as parameters a byte buffer, which will eventually be written to file as the element header,
2382 // an offset into that buffer, and an Element that will be saved into the buffer at the parametrised offset.
2383 // Return value is the new offset after writing the element into the buffer.
2384 // Elements are saved to the file as the ElementHeader struct followed by offsets to the structs of all the element's
2387 RenderScriptRuntime::PopulateElementHeaders(const std::shared_ptr<uint8_t> header_buffer, size_t offset,
2388 const Element &elem)
2390 // File struct for an element header with all the relevant details copied from elem.
2391 // We assume members are valid already.
2392 AllocationDetails::ElementHeader elem_header;
2393 elem_header.type = *elem.type.get();
2394 elem_header.kind = *elem.type_kind.get();
2395 elem_header.element_size = *elem.datum_size.get();
2396 elem_header.vector_size = *elem.type_vec_size.get();
2397 elem_header.array_size = elem.array_size.isValid() ? *elem.array_size.get() : 0;
2398 const size_t elem_header_size = sizeof(AllocationDetails::ElementHeader);
2400 // Copy struct into buffer and advance offset
2401 // We assume that header_buffer has been checked for nullptr before this method is called
2402 memcpy(header_buffer.get() + offset, &elem_header, elem_header_size);
2403 offset += elem_header_size;
2405 // Starting offset of child ElementHeader struct
2406 size_t child_offset = offset + ((elem.children.size() + 1) * sizeof(uint32_t));
2407 for (const RenderScriptRuntime::Element &child : elem.children)
2409 // Recursively populate the buffer with the element header structs of children.
2410 // Then save the offsets where they were set after the parent element header.
2411 memcpy(header_buffer.get() + offset, &child_offset, sizeof(uint32_t));
2412 offset += sizeof(uint32_t);
2414 child_offset = PopulateElementHeaders(header_buffer, child_offset, child);
2417 // Zero indicates no more children
2418 memset(header_buffer.get() + offset, 0, sizeof(uint32_t));
2420 return child_offset;
2423 // Given an Element object this function returns the total size needed in the file header to store the element's
2425 // Taking into account the size of the element header struct, plus the offsets to all the element's children.
2426 // Function is recursive so that the size of all ancestors is taken into account.
2428 RenderScriptRuntime::CalculateElementHeaderSize(const Element &elem)
2430 size_t size = (elem.children.size() + 1) * sizeof(uint32_t); // Offsets to children plus zero terminator
2431 size += sizeof(AllocationDetails::ElementHeader); // Size of header struct with type details
2433 // Calculate recursively for all descendants
2434 for (const Element &child : elem.children)
2435 size += CalculateElementHeaderSize(child);
2440 // Function copies allocation contents into a binary file.
2441 // This file can then be loaded later into a different allocation.
2442 // There is a header, FileHeader, before the allocation data containing meta-data.
2444 RenderScriptRuntime::SaveAllocation(Stream &strm, const uint32_t alloc_id, const char *filename, StackFrame *frame_ptr)
2446 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2448 // Find allocation with the given id
2449 AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
2454 log->Printf("%s - found allocation 0x%" PRIx64 ".", __FUNCTION__, *alloc->address.get());
2456 // JIT all the allocation details
2457 if (alloc->shouldRefresh())
2460 log->Printf("%s - allocation details not calculated yet, jitting info.", __FUNCTION__);
2462 if (!RefreshAllocation(alloc, frame_ptr))
2465 log->Printf("%s - couldn't JIT allocation details.", __FUNCTION__);
2470 assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() && alloc->element.type_vec_size.isValid() &&
2471 alloc->element.datum_size.get() && alloc->element.type_kind.isValid() && alloc->dimension.isValid() &&
2472 "Allocation information not available");
2474 // Check we can create writable file
2475 FileSpec file_spec(filename, true);
2476 File file(file_spec, File::eOpenOptionWrite | File::eOpenOptionCanCreate | File::eOpenOptionTruncate);
2479 strm.Printf("Error: Failed to open '%s' for writing", filename);
2484 // Read allocation into buffer of heap memory
2485 const std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
2488 strm.Printf("Error: Couldn't read allocation data into buffer");
2493 // Create the file header
2494 AllocationDetails::FileHeader head;
2495 memcpy(head.ident, "RSAD", 4);
2496 head.dims[0] = static_cast<uint32_t>(alloc->dimension.get()->dim_1);
2497 head.dims[1] = static_cast<uint32_t>(alloc->dimension.get()->dim_2);
2498 head.dims[2] = static_cast<uint32_t>(alloc->dimension.get()->dim_3);
2500 const size_t element_header_size = CalculateElementHeaderSize(alloc->element);
2501 assert((sizeof(AllocationDetails::FileHeader) + element_header_size) < UINT16_MAX && "Element header too large");
2502 head.hdr_size = static_cast<uint16_t>(sizeof(AllocationDetails::FileHeader) + element_header_size);
2504 // Write the file header
2505 size_t num_bytes = sizeof(AllocationDetails::FileHeader);
2507 log->Printf("%s - writing File Header, 0x%" PRIx64 " bytes", __FUNCTION__, (uint64_t)num_bytes);
2509 Error err = file.Write(&head, num_bytes);
2512 strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), filename);
2517 // Create the headers describing the element type of the allocation.
2518 std::shared_ptr<uint8_t> element_header_buffer(new uint8_t[element_header_size]);
2519 if (element_header_buffer == nullptr)
2521 strm.Printf("Internal Error: Couldn't allocate %" PRIu64 " bytes on the heap", (uint64_t)element_header_size);
2526 PopulateElementHeaders(element_header_buffer, 0, alloc->element);
2528 // Write headers for allocation element type to file
2529 num_bytes = element_header_size;
2531 log->Printf("%s - writing element headers, 0x%" PRIx64 " bytes.", __FUNCTION__, (uint64_t)num_bytes);
2533 err = file.Write(element_header_buffer.get(), num_bytes);
2536 strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), filename);
2541 // Write allocation data to file
2542 num_bytes = static_cast<size_t>(*alloc->size.get());
2544 log->Printf("%s - writing 0x%" PRIx64 " bytes", __FUNCTION__, (uint64_t)num_bytes);
2546 err = file.Write(buffer.get(), num_bytes);
2549 strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), filename);
2554 strm.Printf("Allocation written to file '%s'", filename);
2560 RenderScriptRuntime::LoadModule(const lldb::ModuleSP &module_sp)
2562 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2566 for (const auto &rs_module : m_rsmodules)
2568 if (rs_module->m_module == module_sp)
2570 // Check if the user has enabled automatically breaking on
2572 if (m_breakAllKernels)
2573 BreakOnModuleKernels(rs_module);
2578 bool module_loaded = false;
2579 switch (GetModuleKind(module_sp))
2581 case eModuleKindKernelObj:
2583 RSModuleDescriptorSP module_desc;
2584 module_desc.reset(new RSModuleDescriptor(module_sp));
2585 if (module_desc->ParseRSInfo())
2587 m_rsmodules.push_back(module_desc);
2588 module_loaded = true;
2592 FixupScriptDetails(module_desc);
2596 case eModuleKindDriver:
2600 m_libRSDriver = module_sp;
2601 LoadRuntimeHooks(m_libRSDriver, RenderScriptRuntime::eModuleKindDriver);
2605 case eModuleKindImpl:
2607 m_libRSCpuRef = module_sp;
2610 case eModuleKindLibRS:
2614 m_libRS = module_sp;
2615 static ConstString gDbgPresentStr("gDebuggerPresent");
2616 const Symbol *debug_present =
2617 m_libRS->FindFirstSymbolWithNameAndType(gDbgPresentStr, eSymbolTypeData);
2621 uint32_t flag = 0x00000001U;
2622 Target &target = GetProcess()->GetTarget();
2623 addr_t addr = debug_present->GetLoadAddress(&target);
2624 GetProcess()->WriteMemory(addr, &flag, sizeof(flag), error);
2625 if (error.Success())
2628 log->Printf("%s - debugger present flag set on debugee.", __FUNCTION__);
2630 m_debuggerPresentFlagged = true;
2634 log->Printf("%s - error writing debugger present flags '%s' ", __FUNCTION__,
2640 log->Printf("%s - error writing debugger present flags - symbol not found", __FUNCTION__);
2650 return module_loaded;
2656 RenderScriptRuntime::Update()
2658 if (m_rsmodules.size() > 0)
2667 // The maximum line length of an .rs.info packet
2669 #define STRINGIFY(x) #x
2670 #define MAXLINESTR_(x) "%" STRINGIFY(x) "s"
2671 #define MAXLINESTR MAXLINESTR_(MAXLINE)
2673 // The .rs.info symbol in renderscript modules contains a string which needs to be parsed.
2674 // The string is basic and is parsed on a line by line basis.
2676 RSModuleDescriptor::ParseRSInfo()
2679 const Symbol *info_sym = m_module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData);
2683 const addr_t addr = info_sym->GetAddressRef().GetFileAddress();
2684 if (addr == LLDB_INVALID_ADDRESS)
2687 const addr_t size = info_sym->GetByteSize();
2688 const FileSpec fs = m_module->GetFileSpec();
2690 const DataBufferSP buffer = fs.ReadFileContents(addr, size);
2694 // split rs.info. contents into lines
2695 std::vector<std::string> info_lines;
2697 const std::string info((const char *)buffer->GetBytes());
2698 for (size_t tail = 0; tail < info.size();)
2700 // find next new line or end of string
2701 size_t head = info.find('\n', tail);
2702 head = (head == std::string::npos) ? info.size() : head;
2703 std::string line = info.substr(tail, head - tail);
2705 info_lines.push_back(line);
2710 std::array<char, MAXLINE> name{{'\0'}};
2711 std::array<char, MAXLINE> value{{'\0'}};
2713 // parse all text lines of .rs.info
2714 for (auto line = info_lines.begin(); line != info_lines.end(); ++line)
2716 uint32_t numDefns = 0;
2717 if (sscanf(line->c_str(), "exportVarCount: %" PRIu32 "", &numDefns) == 1)
2720 m_globals.push_back(RSGlobalDescriptor(this, (++line)->c_str()));
2722 else if (sscanf(line->c_str(), "exportForEachCount: %" PRIu32 "", &numDefns) == 1)
2728 static const char *fmt_s = "%" PRIu32 " - " MAXLINESTR;
2729 if (sscanf((++line)->c_str(), fmt_s, &slot, name.data()) == 2)
2731 if (name[0] != '\0')
2732 m_kernels.push_back(RSKernelDescriptor(this, name.data(), slot));
2736 else if (sscanf(line->c_str(), "pragmaCount: %" PRIu32 "", &numDefns) == 1)
2740 name[0] = value[0] = '\0';
2741 static const char *fmt_s = MAXLINESTR " - " MAXLINESTR;
2742 if (sscanf((++line)->c_str(), fmt_s, name.data(), value.data()) != 0)
2744 if (name[0] != '\0')
2745 m_pragmas[std::string(name.data())] = value.data();
2751 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2754 log->Printf("%s - skipping .rs.info field '%s'", __FUNCTION__, line->c_str());
2759 // 'root' kernel should always be present
2760 return m_kernels.size() > 0;
2764 RenderScriptRuntime::Status(Stream &strm) const
2768 strm.Printf("Runtime Library discovered.");
2773 strm.Printf("Runtime Driver discovered.");
2778 strm.Printf("CPU Reference Implementation discovered.");
2782 if (m_runtimeHooks.size())
2784 strm.Printf("Runtime functions hooked:");
2786 for (auto b : m_runtimeHooks)
2788 strm.Indent(b.second->defn->name);
2794 strm.Printf("Runtime is not hooked.");
2800 RenderScriptRuntime::DumpContexts(Stream &strm) const
2802 strm.Printf("Inferred RenderScript Contexts:");
2806 std::map<addr_t, uint64_t> contextReferences;
2808 // Iterate over all of the currently discovered scripts.
2809 // Note: We cant push or pop from m_scripts inside this loop or it may invalidate script.
2810 for (const auto &script : m_scripts)
2812 if (!script->context.isValid())
2814 lldb::addr_t context = *script->context;
2816 if (contextReferences.find(context) != contextReferences.end())
2818 contextReferences[context]++;
2822 contextReferences[context] = 1;
2826 for (const auto &cRef : contextReferences)
2828 strm.Printf("Context 0x%" PRIx64 ": %" PRIu64 " script instances", cRef.first, cRef.second);
2835 RenderScriptRuntime::DumpKernels(Stream &strm) const
2837 strm.Printf("RenderScript Kernels:");
2840 for (const auto &module : m_rsmodules)
2842 strm.Printf("Resource '%s':", module->m_resname.c_str());
2844 for (const auto &kernel : module->m_kernels)
2846 strm.Indent(kernel.m_name.AsCString());
2853 RenderScriptRuntime::AllocationDetails *
2854 RenderScriptRuntime::FindAllocByID(Stream &strm, const uint32_t alloc_id)
2856 AllocationDetails *alloc = nullptr;
2858 // See if we can find allocation using id as an index;
2859 if (alloc_id <= m_allocations.size() && alloc_id != 0 && m_allocations[alloc_id - 1]->id == alloc_id)
2861 alloc = m_allocations[alloc_id - 1].get();
2865 // Fallback to searching
2866 for (const auto &a : m_allocations)
2868 if (a->id == alloc_id)
2875 if (alloc == nullptr)
2877 strm.Printf("Error: Couldn't find allocation with id matching %" PRIu32, alloc_id);
2884 // Prints the contents of an allocation to the output stream, which may be a file
2886 RenderScriptRuntime::DumpAllocation(Stream &strm, StackFrame *frame_ptr, const uint32_t id)
2888 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2890 // Check we can find the desired allocation
2891 AllocationDetails *alloc = FindAllocByID(strm, id);
2893 return false; // FindAllocByID() will print error message for us here
2896 log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__, *alloc->address.get());
2898 // Check we have information about the allocation, if not calculate it
2899 if (alloc->shouldRefresh())
2902 log->Printf("%s - allocation details not calculated yet, jitting info.", __FUNCTION__);
2904 // JIT all the allocation information
2905 if (!RefreshAllocation(alloc, frame_ptr))
2907 strm.Printf("Error: Couldn't JIT allocation details");
2913 // Establish format and size of each data element
2914 const uint32_t vec_size = *alloc->element.type_vec_size.get();
2915 const Element::DataType type = *alloc->element.type.get();
2917 assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT && "Invalid allocation type");
2919 lldb::Format format;
2920 if (type >= Element::RS_TYPE_ELEMENT)
2921 format = eFormatHex;
2923 format = vec_size == 1 ? static_cast<lldb::Format>(AllocationDetails::RSTypeToFormat[type][eFormatSingle])
2924 : static_cast<lldb::Format>(AllocationDetails::RSTypeToFormat[type][eFormatVector]);
2926 const uint32_t data_size = *alloc->element.datum_size.get();
2929 log->Printf("%s - element size %" PRIu32 " bytes, including padding", __FUNCTION__, data_size);
2931 // Allocate a buffer to copy data into
2932 std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
2935 strm.Printf("Error: Couldn't read allocation data");
2940 // Calculate stride between rows as there may be padding at end of rows since
2941 // allocated memory is 16-byte aligned
2942 if (!alloc->stride.isValid())
2944 if (alloc->dimension.get()->dim_2 == 0) // We only have one dimension
2946 else if (!JITAllocationStride(alloc, frame_ptr))
2948 strm.Printf("Error: Couldn't calculate allocation row stride");
2953 const uint32_t stride = *alloc->stride.get();
2954 const uint32_t size = *alloc->size.get(); // Size of whole allocation
2955 const uint32_t padding = alloc->element.padding.isValid() ? *alloc->element.padding.get() : 0;
2957 log->Printf("%s - stride %" PRIu32 " bytes, size %" PRIu32 " bytes, padding %" PRIu32,
2958 __FUNCTION__, stride, size, padding);
2960 // Find dimensions used to index loops, so need to be non-zero
2961 uint32_t dim_x = alloc->dimension.get()->dim_1;
2962 dim_x = dim_x == 0 ? 1 : dim_x;
2964 uint32_t dim_y = alloc->dimension.get()->dim_2;
2965 dim_y = dim_y == 0 ? 1 : dim_y;
2967 uint32_t dim_z = alloc->dimension.get()->dim_3;
2968 dim_z = dim_z == 0 ? 1 : dim_z;
2970 // Use data extractor to format output
2971 const uint32_t archByteSize = GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
2972 DataExtractor alloc_data(buffer.get(), size, GetProcess()->GetByteOrder(), archByteSize);
2974 uint32_t offset = 0; // Offset in buffer to next element to be printed
2975 uint32_t prev_row = 0; // Offset to the start of the previous row
2977 // Iterate over allocation dimensions, printing results to user
2978 strm.Printf("Data (X, Y, Z):");
2979 for (uint32_t z = 0; z < dim_z; ++z)
2981 for (uint32_t y = 0; y < dim_y; ++y)
2983 // Use stride to index start of next row.
2984 if (!(y == 0 && z == 0))
2985 offset = prev_row + stride;
2988 // Print each element in the row individually
2989 for (uint32_t x = 0; x < dim_x; ++x)
2991 strm.Printf("\n(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ") = ", x, y, z);
2992 if ((type == Element::RS_TYPE_NONE) && (alloc->element.children.size() > 0) &&
2993 (alloc->element.type_name != Element::GetFallbackStructName()))
2995 // Here we are dumping an Element of struct type.
2996 // This is done using expression evaluation with the name of the struct type and pointer to element.
2998 // Don't print the name of the resulting expression, since this will be '$[0-9]+'
2999 DumpValueObjectOptions expr_options;
3000 expr_options.SetHideName(true);
3002 // Setup expression as derefrencing a pointer cast to element address.
3003 char expr_char_buffer[jit_max_expr_size];
3004 int chars_written = snprintf(expr_char_buffer, jit_max_expr_size, "*(%s*) 0x%" PRIx64,
3005 alloc->element.type_name.AsCString(), *alloc->data_ptr.get() + offset);
3007 if (chars_written < 0 || chars_written >= jit_max_expr_size)
3010 log->Printf("%s - error in snprintf().", __FUNCTION__);
3014 // Evaluate expression
3015 ValueObjectSP expr_result;
3016 GetProcess()->GetTarget().EvaluateExpression(expr_char_buffer, frame_ptr, expr_result);
3018 // Print the results to our stream.
3019 expr_result->Dump(strm, expr_options);
3023 alloc_data.Dump(&strm, offset, format, data_size - padding, 1, 1, LLDB_INVALID_ADDRESS, 0, 0);
3025 offset += data_size;
3034 // Function recalculates all our cached information about allocations by jitting the
3035 // RS runtime regarding each allocation we know about.
3036 // Returns true if all allocations could be recomputed, false otherwise.
3038 RenderScriptRuntime::RecomputeAllAllocations(Stream &strm, StackFrame *frame_ptr)
3040 bool success = true;
3041 for (auto &alloc : m_allocations)
3043 // JIT current allocation information
3044 if (!RefreshAllocation(alloc.get(), frame_ptr))
3046 strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32 "\n", alloc->id);
3052 strm.Printf("All allocations successfully recomputed");
3058 // Prints information regarding currently loaded allocations.
3059 // These details are gathered by jitting the runtime, which has as latency.
3060 // Index parameter specifies a single allocation ID to print, or a zero value to print them all
3062 RenderScriptRuntime::ListAllocations(Stream &strm, StackFrame *frame_ptr, const uint32_t index)
3064 strm.Printf("RenderScript Allocations:");
3068 for (auto &alloc : m_allocations)
3070 // index will only be zero if we want to print all allocations
3071 if (index != 0 && index != alloc->id)
3074 // JIT current allocation information
3075 if (alloc->shouldRefresh() && !RefreshAllocation(alloc.get(), frame_ptr))
3077 strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32, alloc->id);
3082 strm.Printf("%" PRIu32 ":", alloc->id);
3086 strm.Indent("Context: ");
3087 if (!alloc->context.isValid())
3088 strm.Printf("unknown\n");
3090 strm.Printf("0x%" PRIx64 "\n", *alloc->context.get());
3092 strm.Indent("Address: ");
3093 if (!alloc->address.isValid())
3094 strm.Printf("unknown\n");
3096 strm.Printf("0x%" PRIx64 "\n", *alloc->address.get());
3098 strm.Indent("Data pointer: ");
3099 if (!alloc->data_ptr.isValid())
3100 strm.Printf("unknown\n");
3102 strm.Printf("0x%" PRIx64 "\n", *alloc->data_ptr.get());
3104 strm.Indent("Dimensions: ");
3105 if (!alloc->dimension.isValid())
3106 strm.Printf("unknown\n");
3108 strm.Printf("(%" PRId32 ", %" PRId32 ", %" PRId32 ")\n",
3109 alloc->dimension.get()->dim_1, alloc->dimension.get()->dim_2, alloc->dimension.get()->dim_3);
3111 strm.Indent("Data Type: ");
3112 if (!alloc->element.type.isValid() || !alloc->element.type_vec_size.isValid())
3113 strm.Printf("unknown\n");
3116 const int vector_size = *alloc->element.type_vec_size.get();
3117 Element::DataType type = *alloc->element.type.get();
3119 if (!alloc->element.type_name.IsEmpty())
3120 strm.Printf("%s\n", alloc->element.type_name.AsCString());
3123 // Enum value isn't monotonous, so doesn't always index RsDataTypeToString array
3124 if (type >= Element::RS_TYPE_ELEMENT && type <= Element::RS_TYPE_FONT)
3125 type = static_cast<Element::DataType>((type - Element::RS_TYPE_ELEMENT) +
3126 Element::RS_TYPE_MATRIX_2X2 + 1);
3128 if (type >= (sizeof(AllocationDetails::RsDataTypeToString) /
3129 sizeof(AllocationDetails::RsDataTypeToString[0])) ||
3130 vector_size > 4 || vector_size < 1)
3131 strm.Printf("invalid type\n");
3133 strm.Printf("%s\n", AllocationDetails::RsDataTypeToString[static_cast<uint32_t>(type)]
3138 strm.Indent("Data Kind: ");
3139 if (!alloc->element.type_kind.isValid())
3140 strm.Printf("unknown\n");
3143 const Element::DataKind kind = *alloc->element.type_kind.get();
3144 if (kind < Element::RS_KIND_USER || kind > Element::RS_KIND_PIXEL_YUV)
3145 strm.Printf("invalid kind\n");
3147 strm.Printf("%s\n", AllocationDetails::RsDataKindToString[static_cast<uint32_t>(kind)]);
3156 // Set breakpoints on every kernel found in RS module
3158 RenderScriptRuntime::BreakOnModuleKernels(const RSModuleDescriptorSP rsmodule_sp)
3160 for (const auto &kernel : rsmodule_sp->m_kernels)
3162 // Don't set breakpoint on 'root' kernel
3163 if (strcmp(kernel.m_name.AsCString(), "root") == 0)
3166 CreateKernelBreakpoint(kernel.m_name);
3170 // Method is internally called by the 'kernel breakpoint all' command to
3171 // enable or disable breaking on all kernels.
3173 // When do_break is true we want to enable this functionality.
3174 // When do_break is false we want to disable it.
3176 RenderScriptRuntime::SetBreakAllKernels(bool do_break, TargetSP target)
3178 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3180 InitSearchFilter(target);
3182 // Set breakpoints on all the kernels
3183 if (do_break && !m_breakAllKernels)
3185 m_breakAllKernels = true;
3187 for (const auto &module : m_rsmodules)
3188 BreakOnModuleKernels(module);
3191 log->Printf("%s(True) - breakpoints set on all currently loaded kernels.", __FUNCTION__);
3193 else if (!do_break && m_breakAllKernels) // Breakpoints won't be set on any new kernels.
3195 m_breakAllKernels = false;
3198 log->Printf("%s(False) - breakpoints no longer automatically set.", __FUNCTION__);
3202 // Given the name of a kernel this function creates a breakpoint using our
3203 // own breakpoint resolver, and returns the Breakpoint shared pointer.
3205 RenderScriptRuntime::CreateKernelBreakpoint(const ConstString &name)
3207 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3212 log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__);
3216 BreakpointResolverSP resolver_sp(new RSBreakpointResolver(nullptr, name));
3217 BreakpointSP bp = GetProcess()->GetTarget().CreateBreakpoint(m_filtersp, resolver_sp, false, false, false);
3219 // Give RS breakpoints a specific name, so the user can manipulate them as a group.
3221 if (!bp->AddName("RenderScriptKernel", err) && log)
3222 log->Printf("%s - error setting break name, '%s'.", __FUNCTION__, err.AsCString());
3227 // Given an expression for a variable this function tries to calculate the variable's value.
3228 // If this is possible it returns true and sets the uint64_t parameter to the variables unsigned value.
3229 // Otherwise function returns false.
3231 RenderScriptRuntime::GetFrameVarAsUnsigned(const StackFrameSP frame_sp, const char *var_name, uint64_t &val)
3233 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3237 // Find variable in stack frame
3238 ValueObjectSP value_sp(frame_sp->GetValueForVariableExpressionPath(
3239 var_name, eNoDynamicValues,
3240 StackFrame::eExpressionPathOptionCheckPtrVsMember | StackFrame::eExpressionPathOptionsAllowDirectIVarAccess,
3242 if (!error.Success())
3245 log->Printf("%s - error, couldn't find '%s' in frame", __FUNCTION__, var_name);
3249 // Find the uint32_t value for the variable
3250 bool success = false;
3251 val = value_sp->GetValueAsUnsigned(0, &success);
3255 log->Printf("%s - error, couldn't parse '%s' as an uint32_t.", __FUNCTION__, var_name);
3262 // Function attempts to find the current coordinate of a kernel invocation by investigating the
3263 // values of frame variables in the .expand function. These coordinates are returned via the coord
3264 // array reference parameter. Returns true if the coordinates could be found, and false otherwise.
3266 RenderScriptRuntime::GetKernelCoordinate(RSCoordinate &coord, Thread *thread_ptr)
3268 static const std::string s_runtimeExpandSuffix(".expand");
3269 static const std::array<const char *, 3> s_runtimeCoordVars{{"rsIndex", "p->current.y", "p->current.z"}};
3271 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
3276 log->Printf("%s - Error, No thread pointer", __FUNCTION__);
3281 // Walk the call stack looking for a function whose name has the suffix '.expand'
3282 // and contains the variables we're looking for.
3283 for (uint32_t i = 0; i < thread_ptr->GetStackFrameCount(); ++i)
3285 if (!thread_ptr->SetSelectedFrameByIndex(i))
3288 StackFrameSP frame_sp = thread_ptr->GetSelectedFrame();
3292 // Find the function name
3293 const SymbolContext sym_ctx = frame_sp->GetSymbolContext(false);
3294 const char *func_name_cstr = sym_ctx.GetFunctionName().AsCString();
3295 if (!func_name_cstr)
3299 log->Printf("%s - Inspecting function '%s'", __FUNCTION__, func_name_cstr);
3301 // Check if function name has .expand suffix
3302 std::string func_name(func_name_cstr);
3303 const int length_difference = func_name.length() - s_runtimeExpandSuffix.length();
3304 if (length_difference <= 0)
3307 const int32_t has_expand_suffix = func_name.compare(length_difference,
3308 s_runtimeExpandSuffix.length(),
3309 s_runtimeExpandSuffix);
3311 if (has_expand_suffix != 0)
3315 log->Printf("%s - Found .expand function '%s'", __FUNCTION__, func_name_cstr);
3317 // Get values for variables in .expand frame that tell us the current kernel invocation
3318 bool found_coord_variables = true;
3319 assert(s_runtimeCoordVars.size() == coord.size());
3321 for (uint32_t i = 0; i < coord.size(); ++i)
3324 if (!GetFrameVarAsUnsigned(frame_sp, s_runtimeCoordVars[i], value))
3326 found_coord_variables = false;
3332 if (found_coord_variables)
3338 // Callback when a kernel breakpoint hits and we're looking for a specific coordinate.
3339 // Baton parameter contains a pointer to the target coordinate we want to break on.
3340 // Function then checks the .expand frame for the current coordinate and breaks to user if it matches.
3341 // Parameter 'break_id' is the id of the Breakpoint which made the callback.
3342 // Parameter 'break_loc_id' is the id for the BreakpointLocation which was hit,
3343 // a single logical breakpoint can have multiple addresses.
3345 RenderScriptRuntime::KernelBreakpointHit(void *baton, StoppointCallbackContext *ctx, user_id_t break_id,
3346 user_id_t break_loc_id)
3348 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
3350 assert(baton && "Error: null baton in conditional kernel breakpoint callback");
3352 // Coordinate we want to stop on
3353 const uint32_t *target_coord = static_cast<const uint32_t *>(baton);
3356 log->Printf("%s - Break ID %" PRIu64 ", (%" PRIu32 ", %" PRIu32 ", %" PRIu32 ")", __FUNCTION__, break_id,
3357 target_coord[0], target_coord[1], target_coord[2]);
3359 // Select current thread
3360 ExecutionContext context(ctx->exe_ctx_ref);
3361 Thread *thread_ptr = context.GetThreadPtr();
3362 assert(thread_ptr && "Null thread pointer");
3364 // Find current kernel invocation from .expand frame variables
3365 RSCoordinate current_coord{}; // Zero initialise array
3366 if (!GetKernelCoordinate(current_coord, thread_ptr))
3369 log->Printf("%s - Error, couldn't select .expand stack frame", __FUNCTION__);
3374 log->Printf("%s - (%" PRIu32 ",%" PRIu32 ",%" PRIu32 ")", __FUNCTION__, current_coord[0], current_coord[1],
3377 // Check if the current kernel invocation coordinate matches our target coordinate
3378 if (current_coord[0] == target_coord[0] &&
3379 current_coord[1] == target_coord[1] &&
3380 current_coord[2] == target_coord[2])
3383 log->Printf("%s, BREAKING (%" PRIu32 ",%" PRIu32 ",%" PRIu32 ")", __FUNCTION__, current_coord[0],
3384 current_coord[1], current_coord[2]);
3386 BreakpointSP breakpoint_sp = context.GetTargetPtr()->GetBreakpointByID(break_id);
3387 assert(breakpoint_sp != nullptr && "Error: Couldn't find breakpoint matching break id for callback");
3388 breakpoint_sp->SetEnabled(false); // Optimise since conditional breakpoint should only be hit once.
3392 // No match on coordinate
3396 // Tries to set a breakpoint on the start of a kernel, resolved using the kernel name.
3397 // Argument 'coords', represents a three dimensional coordinate which can be used to specify
3398 // a single kernel instance to break on. If this is set then we add a callback to the breakpoint.
3400 RenderScriptRuntime::PlaceBreakpointOnKernel(Stream &strm, const char *name, const std::array<int, 3> coords,
3401 Error &error, TargetSP target)
3405 error.SetErrorString("invalid kernel name");
3409 InitSearchFilter(target);
3411 ConstString kernel_name(name);
3412 BreakpointSP bp = CreateKernelBreakpoint(kernel_name);
3414 // We have a conditional breakpoint on a specific coordinate
3415 if (coords[0] != -1)
3417 strm.Printf("Conditional kernel breakpoint on coordinate %" PRId32 ", %" PRId32 ", %" PRId32,
3418 coords[0], coords[1], coords[2]);
3421 // Allocate memory for the baton, and copy over coordinate
3422 uint32_t *baton = new uint32_t[coords.size()];
3423 baton[0] = coords[0]; baton[1] = coords[1]; baton[2] = coords[2];
3425 // Create a callback that will be invoked everytime the breakpoint is hit.
3426 // The baton object passed to the handler is the target coordinate we want to break on.
3427 bp->SetCallback(KernelBreakpointHit, baton, true);
3429 // Store a shared pointer to the baton, so the memory will eventually be cleaned up after destruction
3430 m_conditional_breaks[bp->GetID()] = std::shared_ptr<uint32_t>(baton);
3434 bp->GetDescription(&strm, lldb::eDescriptionLevelInitial, false);
3438 RenderScriptRuntime::DumpModules(Stream &strm) const
3440 strm.Printf("RenderScript Modules:");
3443 for (const auto &module : m_rsmodules)
3450 RenderScriptRuntime::ScriptDetails *
3451 RenderScriptRuntime::LookUpScript(addr_t address, bool create)
3453 for (const auto &s : m_scripts)
3455 if (s->script.isValid())
3456 if (*s->script == address)
3461 std::unique_ptr<ScriptDetails> s(new ScriptDetails);
3462 s->script = address;
3463 m_scripts.push_back(std::move(s));
3464 return m_scripts.back().get();
3469 RenderScriptRuntime::AllocationDetails *
3470 RenderScriptRuntime::LookUpAllocation(addr_t address, bool create)
3472 for (const auto &a : m_allocations)
3474 if (a->address.isValid())
3475 if (*a->address == address)
3480 std::unique_ptr<AllocationDetails> a(new AllocationDetails);
3481 a->address = address;
3482 m_allocations.push_back(std::move(a));
3483 return m_allocations.back().get();
3489 RSModuleDescriptor::Dump(Stream &strm) const
3492 m_module->GetFileSpec().Dump(&strm);
3493 if (m_module->GetNumCompileUnits())
3495 strm.Indent("Debug info loaded.");
3499 strm.Indent("Debug info does not exist.");
3504 strm.Printf("Globals: %" PRIu64, static_cast<uint64_t>(m_globals.size()));
3507 for (const auto &global : m_globals)
3513 strm.Printf("Kernels: %" PRIu64, static_cast<uint64_t>(m_kernels.size()));
3516 for (const auto &kernel : m_kernels)
3520 strm.Printf("Pragmas: %" PRIu64, static_cast<uint64_t>(m_pragmas.size()));
3523 for (const auto &key_val : m_pragmas)
3525 strm.Printf("%s: %s", key_val.first.c_str(), key_val.second.c_str());
3532 RSGlobalDescriptor::Dump(Stream &strm) const
3534 strm.Indent(m_name.AsCString());
3535 VariableList var_list;
3536 m_module->m_module->FindGlobalVariables(m_name, nullptr, true, 1U, var_list);
3537 if (var_list.GetSize() == 1)
3539 auto var = var_list.GetVariableAtIndex(0);
3540 auto type = var->GetType();
3544 type->DumpTypeName(&strm);
3548 strm.Printf(" - Unknown Type");
3553 strm.Printf(" - variable identified, but not found in binary");
3554 const Symbol *s = m_module->m_module->FindFirstSymbolWithNameAndType(m_name, eSymbolTypeData);
3557 strm.Printf(" (symbol exists) ");
3565 RSKernelDescriptor::Dump(Stream &strm) const
3567 strm.Indent(m_name.AsCString());
3571 class CommandObjectRenderScriptRuntimeModuleDump : public CommandObjectParsed
3574 CommandObjectRenderScriptRuntimeModuleDump(CommandInterpreter &interpreter)
3575 : CommandObjectParsed(interpreter, "renderscript module dump",
3576 "Dumps renderscript specific information for all modules.", "renderscript module dump",
3577 eCommandRequiresProcess | eCommandProcessMustBeLaunched)
3581 ~CommandObjectRenderScriptRuntimeModuleDump() override = default;
3584 DoExecute(Args &command, CommandReturnObject &result) override
3586 RenderScriptRuntime *runtime =
3587 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
3588 runtime->DumpModules(result.GetOutputStream());
3589 result.SetStatus(eReturnStatusSuccessFinishResult);
3594 class CommandObjectRenderScriptRuntimeModule : public CommandObjectMultiword
3597 CommandObjectRenderScriptRuntimeModule(CommandInterpreter &interpreter)
3598 : CommandObjectMultiword(interpreter, "renderscript module", "Commands that deal with RenderScript modules.",
3601 LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleDump(interpreter)));
3604 ~CommandObjectRenderScriptRuntimeModule() override = default;
3607 class CommandObjectRenderScriptRuntimeKernelList : public CommandObjectParsed
3610 CommandObjectRenderScriptRuntimeKernelList(CommandInterpreter &interpreter)
3611 : CommandObjectParsed(interpreter, "renderscript kernel list",
3612 "Lists renderscript kernel names and associated script resources.",
3613 "renderscript kernel list", eCommandRequiresProcess | eCommandProcessMustBeLaunched)
3617 ~CommandObjectRenderScriptRuntimeKernelList() override = default;
3620 DoExecute(Args &command, CommandReturnObject &result) override
3622 RenderScriptRuntime *runtime =
3623 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
3624 runtime->DumpKernels(result.GetOutputStream());
3625 result.SetStatus(eReturnStatusSuccessFinishResult);
3630 class CommandObjectRenderScriptRuntimeKernelBreakpointSet : public CommandObjectParsed
3633 CommandObjectRenderScriptRuntimeKernelBreakpointSet(CommandInterpreter &interpreter)
3634 : CommandObjectParsed(interpreter, "renderscript kernel breakpoint set",
3635 "Sets a breakpoint on a renderscript kernel.",
3636 "renderscript kernel breakpoint set <kernel_name> [-c x,y,z]",
3637 eCommandRequiresProcess | eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
3638 m_options(interpreter)
3642 ~CommandObjectRenderScriptRuntimeKernelBreakpointSet() override = default;
3645 GetOptions() override
3650 class CommandOptions : public Options
3653 CommandOptions(CommandInterpreter &interpreter) : Options(interpreter) {}
3655 ~CommandOptions() override = default;
3658 SetOptionValue(uint32_t option_idx, const char *option_arg) override
3661 const int short_option = m_getopt_table[option_idx].val;
3663 switch (short_option)
3666 if (!ParseCoordinate(option_arg))
3667 error.SetErrorStringWithFormat("Couldn't parse coordinate '%s', should be in format 'x,y,z'.",
3671 error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
3677 // -c takes an argument of the form 'num[,num][,num]'.
3678 // Where 'id_cstr' is this argument with the whitespace trimmed.
3679 // Missing coordinates are defaulted to zero.
3681 ParseCoordinate(const char *id_cstr)
3683 RegularExpression regex;
3684 RegularExpression::Match regex_match(3);
3686 bool matched = false;
3687 if (regex.Compile("^([0-9]+),([0-9]+),([0-9]+)$") && regex.Execute(id_cstr, ®ex_match))
3689 else if (regex.Compile("^([0-9]+),([0-9]+)$") && regex.Execute(id_cstr, ®ex_match))
3691 else if (regex.Compile("^([0-9]+)$") && regex.Execute(id_cstr, ®ex_match))
3693 for (uint32_t i = 0; i < 3; i++)
3696 if (regex_match.GetMatchAtIndex(id_cstr, i + 1, group))
3697 m_coord[i] = (uint32_t)strtoul(group.c_str(), nullptr, 0);
3705 OptionParsingStarting() override
3707 // -1 means the -c option hasn't been set
3713 const OptionDefinition *
3714 GetDefinitions() override
3716 return g_option_table;
3719 static OptionDefinition g_option_table[];
3720 std::array<int, 3> m_coord;
3724 DoExecute(Args &command, CommandReturnObject &result) override
3726 const size_t argc = command.GetArgumentCount();
3729 result.AppendErrorWithFormat("'%s' takes 1 argument of kernel name, and an optional coordinate.",
3730 m_cmd_name.c_str());
3731 result.SetStatus(eReturnStatusFailed);
3735 RenderScriptRuntime *runtime =
3736 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
3739 runtime->PlaceBreakpointOnKernel(result.GetOutputStream(), command.GetArgumentAtIndex(0), m_options.m_coord,
3740 error, m_exe_ctx.GetTargetSP());
3742 if (error.Success())
3744 result.AppendMessage("Breakpoint(s) created");
3745 result.SetStatus(eReturnStatusSuccessFinishResult);
3748 result.SetStatus(eReturnStatusFailed);
3749 result.AppendErrorWithFormat("Error: %s", error.AsCString());
3754 CommandOptions m_options;
3757 OptionDefinition CommandObjectRenderScriptRuntimeKernelBreakpointSet::CommandOptions::g_option_table[] = {
3758 {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeValue,
3759 "Set a breakpoint on a single invocation of the kernel with specified coordinate.\n"
3760 "Coordinate takes the form 'x[,y][,z] where x,y,z are positive integers representing kernel dimensions. "
3761 "Any unset dimensions will be defaulted to zero."},
3762 {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr}};
3764 class CommandObjectRenderScriptRuntimeKernelBreakpointAll : public CommandObjectParsed
3767 CommandObjectRenderScriptRuntimeKernelBreakpointAll(CommandInterpreter &interpreter)
3768 : CommandObjectParsed(
3769 interpreter, "renderscript kernel breakpoint all",
3770 "Automatically sets a breakpoint on all renderscript kernels that are or will be loaded.\n"
3771 "Disabling option means breakpoints will no longer be set on any kernels loaded in the future, "
3772 "but does not remove currently set breakpoints.",
3773 "renderscript kernel breakpoint all <enable/disable>",
3774 eCommandRequiresProcess | eCommandProcessMustBeLaunched | eCommandProcessMustBePaused)
3778 ~CommandObjectRenderScriptRuntimeKernelBreakpointAll() override = default;
3781 DoExecute(Args &command, CommandReturnObject &result) override
3783 const size_t argc = command.GetArgumentCount();
3786 result.AppendErrorWithFormat("'%s' takes 1 argument of 'enable' or 'disable'", m_cmd_name.c_str());
3787 result.SetStatus(eReturnStatusFailed);
3791 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
3792 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
3794 bool do_break = false;
3795 const char *argument = command.GetArgumentAtIndex(0);
3796 if (strcmp(argument, "enable") == 0)
3799 result.AppendMessage("Breakpoints will be set on all kernels.");
3801 else if (strcmp(argument, "disable") == 0)
3804 result.AppendMessage("Breakpoints will not be set on any new kernels.");
3808 result.AppendErrorWithFormat("Argument must be either 'enable' or 'disable'");
3809 result.SetStatus(eReturnStatusFailed);
3813 runtime->SetBreakAllKernels(do_break, m_exe_ctx.GetTargetSP());
3815 result.SetStatus(eReturnStatusSuccessFinishResult);
3820 class CommandObjectRenderScriptRuntimeKernelCoordinate : public CommandObjectParsed
3823 CommandObjectRenderScriptRuntimeKernelCoordinate(CommandInterpreter &interpreter)
3824 : CommandObjectParsed(interpreter, "renderscript kernel coordinate",
3825 "Shows the (x,y,z) coordinate of the current kernel invocation.",
3826 "renderscript kernel coordinate",
3827 eCommandRequiresProcess | eCommandProcessMustBeLaunched | eCommandProcessMustBePaused)
3831 ~CommandObjectRenderScriptRuntimeKernelCoordinate() override = default;
3834 DoExecute(Args &command, CommandReturnObject &result) override
3836 RSCoordinate coord{}; // Zero initialize array
3837 bool success = RenderScriptRuntime::GetKernelCoordinate(coord, m_exe_ctx.GetThreadPtr());
3838 Stream &stream = result.GetOutputStream();
3842 stream.Printf("Coordinate: (%" PRIu32 ", %" PRIu32 ", %" PRIu32 ")", coord[0], coord[1], coord[2]);
3844 result.SetStatus(eReturnStatusSuccessFinishResult);
3848 stream.Printf("Error: Coordinate could not be found.");
3850 result.SetStatus(eReturnStatusFailed);
3856 class CommandObjectRenderScriptRuntimeKernelBreakpoint : public CommandObjectMultiword
3859 CommandObjectRenderScriptRuntimeKernelBreakpoint(CommandInterpreter &interpreter)
3860 : CommandObjectMultiword(interpreter, "renderscript kernel",
3861 "Commands that generate breakpoints on renderscript kernels.", nullptr)
3863 LoadSubCommand("set", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointSet(interpreter)));
3864 LoadSubCommand("all", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointAll(interpreter)));
3867 ~CommandObjectRenderScriptRuntimeKernelBreakpoint() override = default;
3870 class CommandObjectRenderScriptRuntimeKernel : public CommandObjectMultiword
3873 CommandObjectRenderScriptRuntimeKernel(CommandInterpreter &interpreter)
3874 : CommandObjectMultiword(interpreter, "renderscript kernel", "Commands that deal with RenderScript kernels.",
3877 LoadSubCommand("list", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelList(interpreter)));
3878 LoadSubCommand("coordinate",
3879 CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelCoordinate(interpreter)));
3880 LoadSubCommand("breakpoint",
3881 CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpoint(interpreter)));
3884 ~CommandObjectRenderScriptRuntimeKernel() override = default;
3887 class CommandObjectRenderScriptRuntimeContextDump : public CommandObjectParsed
3890 CommandObjectRenderScriptRuntimeContextDump(CommandInterpreter &interpreter)
3891 : CommandObjectParsed(interpreter, "renderscript context dump", "Dumps renderscript context information.",
3892 "renderscript context dump", eCommandRequiresProcess | eCommandProcessMustBeLaunched)
3896 ~CommandObjectRenderScriptRuntimeContextDump() override = default;
3899 DoExecute(Args &command, CommandReturnObject &result) override
3901 RenderScriptRuntime *runtime =
3902 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
3903 runtime->DumpContexts(result.GetOutputStream());
3904 result.SetStatus(eReturnStatusSuccessFinishResult);
3909 class CommandObjectRenderScriptRuntimeContext : public CommandObjectMultiword
3912 CommandObjectRenderScriptRuntimeContext(CommandInterpreter &interpreter)
3913 : CommandObjectMultiword(interpreter, "renderscript context", "Commands that deal with RenderScript contexts.",
3916 LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeContextDump(interpreter)));
3919 ~CommandObjectRenderScriptRuntimeContext() override = default;
3922 class CommandObjectRenderScriptRuntimeAllocationDump : public CommandObjectParsed
3925 CommandObjectRenderScriptRuntimeAllocationDump(CommandInterpreter &interpreter)
3926 : CommandObjectParsed(interpreter, "renderscript allocation dump",
3927 "Displays the contents of a particular allocation", "renderscript allocation dump <ID>",
3928 eCommandRequiresProcess | eCommandProcessMustBeLaunched),
3929 m_options(interpreter)
3933 ~CommandObjectRenderScriptRuntimeAllocationDump() override = default;
3936 GetOptions() override
3941 class CommandOptions : public Options
3944 CommandOptions(CommandInterpreter &interpreter) : Options(interpreter) {}
3946 ~CommandOptions() override = default;
3949 SetOptionValue(uint32_t option_idx, const char *option_arg) override
3952 const int short_option = m_getopt_table[option_idx].val;
3954 switch (short_option)
3957 m_outfile.SetFile(option_arg, true);
3958 if (m_outfile.Exists())
3961 error.SetErrorStringWithFormat("file already exists: '%s'", option_arg);
3965 error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
3972 OptionParsingStarting() override
3977 const OptionDefinition *
3978 GetDefinitions() override
3980 return g_option_table;
3983 static OptionDefinition g_option_table[];
3988 DoExecute(Args &command, CommandReturnObject &result) override
3990 const size_t argc = command.GetArgumentCount();
3993 result.AppendErrorWithFormat("'%s' takes 1 argument, an allocation ID. As well as an optional -f argument",
3994 m_cmd_name.c_str());
3995 result.SetStatus(eReturnStatusFailed);
3999 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4000 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
4002 const char *id_cstr = command.GetArgumentAtIndex(0);
4003 bool convert_complete = false;
4004 const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
4005 if (!convert_complete)
4007 result.AppendErrorWithFormat("invalid allocation id argument '%s'", id_cstr);
4008 result.SetStatus(eReturnStatusFailed);
4012 Stream *output_strm = nullptr;
4013 StreamFile outfile_stream;
4014 const FileSpec &outfile_spec = m_options.m_outfile; // Dump allocation to file instead
4019 outfile_spec.GetPath(path, sizeof(path));
4020 if (outfile_stream.GetFile().Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate).Success())
4022 output_strm = &outfile_stream;
4023 result.GetOutputStream().Printf("Results written to '%s'", path);
4024 result.GetOutputStream().EOL();
4028 result.AppendErrorWithFormat("Couldn't open file '%s'", path);
4029 result.SetStatus(eReturnStatusFailed);
4034 output_strm = &result.GetOutputStream();
4036 assert(output_strm != nullptr);
4037 bool success = runtime->DumpAllocation(*output_strm, m_exe_ctx.GetFramePtr(), id);
4040 result.SetStatus(eReturnStatusSuccessFinishResult);
4042 result.SetStatus(eReturnStatusFailed);
4048 CommandOptions m_options;
4051 OptionDefinition CommandObjectRenderScriptRuntimeAllocationDump::CommandOptions::g_option_table[] = {
4052 {LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeFilename,
4053 "Print results to specified file instead of command line."},
4054 {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr}};
4056 class CommandObjectRenderScriptRuntimeAllocationList : public CommandObjectParsed
4059 CommandObjectRenderScriptRuntimeAllocationList(CommandInterpreter &interpreter)
4060 : CommandObjectParsed(interpreter, "renderscript allocation list",
4061 "List renderscript allocations and their information.", "renderscript allocation list",
4062 eCommandRequiresProcess | eCommandProcessMustBeLaunched),
4063 m_options(interpreter)
4067 ~CommandObjectRenderScriptRuntimeAllocationList() override = default;
4070 GetOptions() override
4075 class CommandOptions : public Options
4078 CommandOptions(CommandInterpreter &interpreter) : Options(interpreter), m_id(0) {}
4080 ~CommandOptions() override = default;
4083 SetOptionValue(uint32_t option_idx, const char *option_arg) override
4086 const int short_option = m_getopt_table[option_idx].val;
4088 switch (short_option)
4092 m_id = StringConvert::ToUInt32(option_arg, 0, 0, &success);
4094 error.SetErrorStringWithFormat("invalid integer value for option '%c'", short_option);
4097 error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4104 OptionParsingStarting() override
4109 const OptionDefinition *
4110 GetDefinitions() override
4112 return g_option_table;
4115 static OptionDefinition g_option_table[];
4120 DoExecute(Args &command, CommandReturnObject &result) override
4122 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4123 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
4124 runtime->ListAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr(), m_options.m_id);
4125 result.SetStatus(eReturnStatusSuccessFinishResult);
4130 CommandOptions m_options;
4133 OptionDefinition CommandObjectRenderScriptRuntimeAllocationList::CommandOptions::g_option_table[] = {
4134 {LLDB_OPT_SET_1, false, "id", 'i', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeIndex,
4135 "Only show details of a single allocation with specified id."},
4136 {0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr}};
4138 class CommandObjectRenderScriptRuntimeAllocationLoad : public CommandObjectParsed
4141 CommandObjectRenderScriptRuntimeAllocationLoad(CommandInterpreter &interpreter)
4142 : CommandObjectParsed(
4143 interpreter, "renderscript allocation load", "Loads renderscript allocation contents from a file.",
4144 "renderscript allocation load <ID> <filename>", eCommandRequiresProcess | eCommandProcessMustBeLaunched)
4148 ~CommandObjectRenderScriptRuntimeAllocationLoad() override = default;
4151 DoExecute(Args &command, CommandReturnObject &result) override
4153 const size_t argc = command.GetArgumentCount();
4156 result.AppendErrorWithFormat("'%s' takes 2 arguments, an allocation ID and filename to read from.",
4157 m_cmd_name.c_str());
4158 result.SetStatus(eReturnStatusFailed);
4162 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4163 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
4165 const char *id_cstr = command.GetArgumentAtIndex(0);
4166 bool convert_complete = false;
4167 const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
4168 if (!convert_complete)
4170 result.AppendErrorWithFormat("invalid allocation id argument '%s'", id_cstr);
4171 result.SetStatus(eReturnStatusFailed);
4175 const char *filename = command.GetArgumentAtIndex(1);
4176 bool success = runtime->LoadAllocation(result.GetOutputStream(), id, filename, m_exe_ctx.GetFramePtr());
4179 result.SetStatus(eReturnStatusSuccessFinishResult);
4181 result.SetStatus(eReturnStatusFailed);
4187 class CommandObjectRenderScriptRuntimeAllocationSave : public CommandObjectParsed
4190 CommandObjectRenderScriptRuntimeAllocationSave(CommandInterpreter &interpreter)
4191 : CommandObjectParsed(
4192 interpreter, "renderscript allocation save", "Write renderscript allocation contents to a file.",
4193 "renderscript allocation save <ID> <filename>", eCommandRequiresProcess | eCommandProcessMustBeLaunched)
4197 ~CommandObjectRenderScriptRuntimeAllocationSave() override = default;
4200 DoExecute(Args &command, CommandReturnObject &result) override
4202 const size_t argc = command.GetArgumentCount();
4205 result.AppendErrorWithFormat("'%s' takes 2 arguments, an allocation ID and filename to read from.",
4206 m_cmd_name.c_str());
4207 result.SetStatus(eReturnStatusFailed);
4211 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4212 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
4214 const char *id_cstr = command.GetArgumentAtIndex(0);
4215 bool convert_complete = false;
4216 const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
4217 if (!convert_complete)
4219 result.AppendErrorWithFormat("invalid allocation id argument '%s'", id_cstr);
4220 result.SetStatus(eReturnStatusFailed);
4224 const char *filename = command.GetArgumentAtIndex(1);
4225 bool success = runtime->SaveAllocation(result.GetOutputStream(), id, filename, m_exe_ctx.GetFramePtr());
4228 result.SetStatus(eReturnStatusSuccessFinishResult);
4230 result.SetStatus(eReturnStatusFailed);
4236 class CommandObjectRenderScriptRuntimeAllocationRefresh : public CommandObjectParsed
4239 CommandObjectRenderScriptRuntimeAllocationRefresh(CommandInterpreter &interpreter)
4240 : CommandObjectParsed(interpreter, "renderscript allocation refresh",
4241 "Recomputes the details of all allocations.", "renderscript allocation refresh",
4242 eCommandRequiresProcess | eCommandProcessMustBeLaunched)
4246 ~CommandObjectRenderScriptRuntimeAllocationRefresh() override = default;
4249 DoExecute(Args &command, CommandReturnObject &result) override
4251 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4252 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
4254 bool success = runtime->RecomputeAllAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr());
4258 result.SetStatus(eReturnStatusSuccessFinishResult);
4263 result.SetStatus(eReturnStatusFailed);
4269 class CommandObjectRenderScriptRuntimeAllocation : public CommandObjectMultiword
4272 CommandObjectRenderScriptRuntimeAllocation(CommandInterpreter &interpreter)
4273 : CommandObjectMultiword(interpreter, "renderscript allocation",
4274 "Commands that deal with RenderScript allocations.", nullptr)
4276 LoadSubCommand("list", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationList(interpreter)));
4277 LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationDump(interpreter)));
4278 LoadSubCommand("save", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationSave(interpreter)));
4279 LoadSubCommand("load", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationLoad(interpreter)));
4280 LoadSubCommand("refresh", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationRefresh(interpreter)));
4283 ~CommandObjectRenderScriptRuntimeAllocation() override = default;
4286 class CommandObjectRenderScriptRuntimeStatus : public CommandObjectParsed
4289 CommandObjectRenderScriptRuntimeStatus(CommandInterpreter &interpreter)
4290 : CommandObjectParsed(interpreter, "renderscript status", "Displays current RenderScript runtime status.",
4291 "renderscript status", eCommandRequiresProcess | eCommandProcessMustBeLaunched)
4295 ~CommandObjectRenderScriptRuntimeStatus() override = default;
4298 DoExecute(Args &command, CommandReturnObject &result) override
4300 RenderScriptRuntime *runtime =
4301 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
4302 runtime->Status(result.GetOutputStream());
4303 result.SetStatus(eReturnStatusSuccessFinishResult);
4308 class CommandObjectRenderScriptRuntime : public CommandObjectMultiword
4311 CommandObjectRenderScriptRuntime(CommandInterpreter &interpreter)
4312 : CommandObjectMultiword(interpreter, "renderscript", "Commands for operating on the RenderScript runtime.",
4313 "renderscript <subcommand> [<subcommand-options>]")
4315 LoadSubCommand("module", CommandObjectSP(new CommandObjectRenderScriptRuntimeModule(interpreter)));
4316 LoadSubCommand("status", CommandObjectSP(new CommandObjectRenderScriptRuntimeStatus(interpreter)));
4317 LoadSubCommand("kernel", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernel(interpreter)));
4318 LoadSubCommand("context", CommandObjectSP(new CommandObjectRenderScriptRuntimeContext(interpreter)));
4319 LoadSubCommand("allocation", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocation(interpreter)));
4322 ~CommandObjectRenderScriptRuntime() override = default;
4326 RenderScriptRuntime::Initiate()
4328 assert(!m_initiated);
4331 RenderScriptRuntime::RenderScriptRuntime(Process *process)
4332 : lldb_private::CPPLanguageRuntime(process),
4334 m_debuggerPresentFlagged(false),
4335 m_breakAllKernels(false)
4337 ModulesDidLoad(process->GetTarget().GetImages());
4340 lldb::CommandObjectSP
4341 RenderScriptRuntime::GetCommandObject(lldb_private::CommandInterpreter &interpreter)
4343 return CommandObjectSP(new CommandObjectRenderScriptRuntime(interpreter));
4346 RenderScriptRuntime::~RenderScriptRuntime() = default;