1 //===-- RenderScriptRuntime.cpp -------------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "RenderScriptRuntime.h"
10 #include "RenderScriptScriptGroup.h"
12 #include "lldb/Breakpoint/StoppointCallbackContext.h"
13 #include "lldb/Core/Debugger.h"
14 #include "lldb/Core/DumpDataExtractor.h"
15 #include "lldb/Core/PluginManager.h"
16 #include "lldb/Core/ValueObjectVariable.h"
17 #include "lldb/DataFormatters/DumpValueObjectOptions.h"
18 #include "lldb/Expression/UserExpression.h"
19 #include "lldb/Host/OptionParser.h"
20 #include "lldb/Interpreter/CommandInterpreter.h"
21 #include "lldb/Interpreter/CommandObjectMultiword.h"
22 #include "lldb/Interpreter/CommandReturnObject.h"
23 #include "lldb/Interpreter/Options.h"
24 #include "lldb/Symbol/Function.h"
25 #include "lldb/Symbol/Symbol.h"
26 #include "lldb/Symbol/Type.h"
27 #include "lldb/Symbol/VariableList.h"
28 #include "lldb/Target/Process.h"
29 #include "lldb/Target/RegisterContext.h"
30 #include "lldb/Target/SectionLoadList.h"
31 #include "lldb/Target/Target.h"
32 #include "lldb/Target/Thread.h"
33 #include "lldb/Utility/Args.h"
34 #include "lldb/Utility/ConstString.h"
35 #include "lldb/Utility/LLDBLog.h"
36 #include "lldb/Utility/Log.h"
37 #include "lldb/Utility/RegisterValue.h"
38 #include "lldb/Utility/RegularExpression.h"
39 #include "lldb/Utility/Status.h"
41 #include "llvm/ADT/StringSwitch.h"
46 using namespace lldb_private;
47 using namespace lldb_renderscript;
49 LLDB_PLUGIN_DEFINE(RenderScriptRuntime)
51 #define FMT_COORD "(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ")"
53 char RenderScriptRuntime::ID = 0;
57 // The empirical_type adds a basic level of validation to arbitrary data
58 // allowing us to track if data has been discovered and stored or not. An
59 // empirical_type will be marked as valid only if it has been explicitly
61 template <typename type_t> class empirical_type {
63 // Ctor. Contents is invalid when constructed.
64 empirical_type() = default;
66 // Return true and copy contents to out if valid, else return false.
67 bool get(type_t &out) const {
73 // Return a pointer to the contents or nullptr if it was not valid.
74 const type_t *get() const { return valid ? &data : nullptr; }
76 // Assign data explicitly.
77 void set(const type_t in) {
82 // Mark contents as invalid.
83 void invalidate() { valid = false; }
85 // Returns true if this type contains valid data.
86 bool isValid() const { return valid; }
88 // Assignment operator.
89 empirical_type<type_t> &operator=(const type_t in) {
94 // Dereference operator returns contents.
95 // Warning: Will assert if not valid so use only when you know data is valid.
96 const type_t &operator*() const {
106 // ArgItem is used by the GetArgs() function when reading function arguments
109 enum { ePointer, eInt32, eInt64, eLong, eBool } type;
113 explicit operator uint64_t() const { return value; }
116 // Context structure to be passed into GetArgsXXX(), argument reading functions
119 RegisterContext *reg_ctx;
123 bool GetArgsX86(const GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
124 Log *log = GetLog(LLDBLog::Language);
128 // get the current stack pointer
129 uint64_t sp = ctx.reg_ctx->GetSP();
131 for (size_t i = 0; i < num_args; ++i) {
132 ArgItem &arg = arg_list[i];
133 // advance up the stack by one argument
134 sp += sizeof(uint32_t);
135 // get the argument type size
136 size_t arg_size = sizeof(uint32_t);
137 // read the argument from memory
141 ctx.process->ReadMemory(sp, &arg.value, sizeof(uint32_t), err);
142 if (read != arg_size || !err.Success()) {
143 LLDB_LOGF(log, "%s - error reading argument: %" PRIu64 " '%s'",
144 __FUNCTION__, uint64_t(i), err.AsCString());
151 bool GetArgsX86_64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
152 Log *log = GetLog(LLDBLog::Language);
154 // number of arguments passed in registers
155 static const uint32_t args_in_reg = 6;
156 // register passing order
157 static const std::array<const char *, args_in_reg> reg_names{
158 {"rdi", "rsi", "rdx", "rcx", "r8", "r9"}};
159 // argument type to size mapping
160 static const std::array<size_t, 5> arg_size{{
170 // get the current stack pointer
171 uint64_t sp = ctx.reg_ctx->GetSP();
172 // step over the return address
173 sp += sizeof(uint64_t);
175 // check the stack alignment was correct (16 byte aligned)
176 if ((sp & 0xf) != 0x0) {
177 LLDB_LOGF(log, "%s - stack misaligned", __FUNCTION__);
181 // find the start of arguments on the stack
182 uint64_t sp_offset = 0;
183 for (uint32_t i = args_in_reg; i < num_args; ++i) {
184 sp_offset += arg_size[arg_list[i].type];
186 // round up to multiple of 16
187 sp_offset = (sp_offset + 0xf) & 0xf;
190 for (size_t i = 0; i < num_args; ++i) {
191 bool success = false;
192 ArgItem &arg = arg_list[i];
193 // arguments passed in registers
194 if (i < args_in_reg) {
195 const RegisterInfo *reg =
196 ctx.reg_ctx->GetRegisterInfoByName(reg_names[i]);
197 RegisterValue reg_val;
198 if (ctx.reg_ctx->ReadRegister(reg, reg_val))
199 arg.value = reg_val.GetAsUInt64(0, &success);
201 // arguments passed on the stack
203 // get the argument type size
204 const size_t size = arg_size[arg_list[i].type];
205 // read the argument from memory
207 // note: due to little endian layout reading 4 or 8 bytes will give the
209 size_t read = ctx.process->ReadMemory(sp, &arg.value, size, err);
210 success = (err.Success() && read == size);
211 // advance past this argument
214 // fail if we couldn't read this argument
216 LLDB_LOGF(log, "%s - error reading argument: %" PRIu64 ", reason: %s",
217 __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
224 bool GetArgsArm(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
225 // number of arguments passed in registers
226 static const uint32_t args_in_reg = 4;
228 Log *log = GetLog(LLDBLog::Language);
232 // get the current stack pointer
233 uint64_t sp = ctx.reg_ctx->GetSP();
235 for (size_t i = 0; i < num_args; ++i) {
236 bool success = false;
237 ArgItem &arg = arg_list[i];
238 // arguments passed in registers
239 if (i < args_in_reg) {
240 const RegisterInfo *reg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
241 RegisterValue reg_val;
242 if (ctx.reg_ctx->ReadRegister(reg, reg_val))
243 arg.value = reg_val.GetAsUInt32(0, &success);
245 // arguments passed on the stack
247 // get the argument type size
248 const size_t arg_size = sizeof(uint32_t);
251 // read this argument from memory
253 ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
254 success = (err.Success() && bytes_read == arg_size);
255 // advance the stack pointer
256 sp += sizeof(uint32_t);
258 // fail if we couldn't read this argument
260 LLDB_LOGF(log, "%s - error reading argument: %" PRIu64 ", reason: %s",
261 __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
268 bool GetArgsAarch64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
269 // number of arguments passed in registers
270 static const uint32_t args_in_reg = 8;
272 Log *log = GetLog(LLDBLog::Language);
274 for (size_t i = 0; i < num_args; ++i) {
275 bool success = false;
276 ArgItem &arg = arg_list[i];
277 // arguments passed in registers
278 if (i < args_in_reg) {
279 const RegisterInfo *reg = ctx.reg_ctx->GetRegisterInfoAtIndex(i);
280 RegisterValue reg_val;
281 if (ctx.reg_ctx->ReadRegister(reg, reg_val))
282 arg.value = reg_val.GetAsUInt64(0, &success);
284 // arguments passed on the stack
286 LLDB_LOGF(log, "%s - reading arguments spilled to stack not implemented",
289 // fail if we couldn't read this argument
291 LLDB_LOGF(log, "%s - error reading argument: %" PRIu64, __FUNCTION__,
299 bool GetArgsMipsel(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
300 // number of arguments passed in registers
301 static const uint32_t args_in_reg = 4;
302 // register file offset to first argument
303 static const uint32_t reg_offset = 4;
305 Log *log = GetLog(LLDBLog::Language);
309 // find offset to arguments on the stack (+16 to skip over a0-a3 shadow
311 uint64_t sp = ctx.reg_ctx->GetSP() + 16;
313 for (size_t i = 0; i < num_args; ++i) {
314 bool success = false;
315 ArgItem &arg = arg_list[i];
316 // arguments passed in registers
317 if (i < args_in_reg) {
318 const RegisterInfo *reg =
319 ctx.reg_ctx->GetRegisterInfoAtIndex(i + reg_offset);
320 RegisterValue reg_val;
321 if (ctx.reg_ctx->ReadRegister(reg, reg_val))
322 arg.value = reg_val.GetAsUInt64(0, &success);
324 // arguments passed on the stack
326 const size_t arg_size = sizeof(uint32_t);
329 ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
330 success = (err.Success() && bytes_read == arg_size);
331 // advance the stack pointer
334 // fail if we couldn't read this argument
336 LLDB_LOGF(log, "%s - error reading argument: %" PRIu64 ", reason: %s",
337 __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
344 bool GetArgsMips64el(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) {
345 // number of arguments passed in registers
346 static const uint32_t args_in_reg = 8;
347 // register file offset to first argument
348 static const uint32_t reg_offset = 4;
350 Log *log = GetLog(LLDBLog::Language);
354 // get the current stack pointer
355 uint64_t sp = ctx.reg_ctx->GetSP();
357 for (size_t i = 0; i < num_args; ++i) {
358 bool success = false;
359 ArgItem &arg = arg_list[i];
360 // arguments passed in registers
361 if (i < args_in_reg) {
362 const RegisterInfo *reg =
363 ctx.reg_ctx->GetRegisterInfoAtIndex(i + reg_offset);
364 RegisterValue reg_val;
365 if (ctx.reg_ctx->ReadRegister(reg, reg_val))
366 arg.value = reg_val.GetAsUInt64(0, &success);
368 // arguments passed on the stack
370 // get the argument type size
371 const size_t arg_size = sizeof(uint64_t);
374 // read this argument from memory
376 ctx.process->ReadMemory(sp, &arg.value, arg_size, err);
377 success = (err.Success() && bytes_read == arg_size);
378 // advance the stack pointer
381 // fail if we couldn't read this argument
383 LLDB_LOGF(log, "%s - error reading argument: %" PRIu64 ", reason: %s",
384 __FUNCTION__, uint64_t(i), err.AsCString("n/a"));
391 bool GetArgs(ExecutionContext &exe_ctx, ArgItem *arg_list, size_t num_args) {
392 Log *log = GetLog(LLDBLog::Language);
394 // verify that we have a target
395 if (!exe_ctx.GetTargetPtr()) {
396 LLDB_LOGF(log, "%s - invalid target", __FUNCTION__);
400 GetArgsCtx ctx = {exe_ctx.GetRegisterContext(), exe_ctx.GetProcessPtr()};
401 assert(ctx.reg_ctx && ctx.process);
403 // dispatch based on architecture
404 switch (exe_ctx.GetTargetPtr()->GetArchitecture().GetMachine()) {
405 case llvm::Triple::ArchType::x86:
406 return GetArgsX86(ctx, arg_list, num_args);
408 case llvm::Triple::ArchType::x86_64:
409 return GetArgsX86_64(ctx, arg_list, num_args);
411 case llvm::Triple::ArchType::arm:
412 return GetArgsArm(ctx, arg_list, num_args);
414 case llvm::Triple::ArchType::aarch64:
415 return GetArgsAarch64(ctx, arg_list, num_args);
417 case llvm::Triple::ArchType::mipsel:
418 return GetArgsMipsel(ctx, arg_list, num_args);
420 case llvm::Triple::ArchType::mips64el:
421 return GetArgsMips64el(ctx, arg_list, num_args);
424 // unsupported architecture
426 LLDB_LOGF(log, "%s - architecture not supported: '%s'", __FUNCTION__,
427 exe_ctx.GetTargetRef().GetArchitecture().GetArchitectureName());
433 bool IsRenderScriptScriptModule(ModuleSP module) {
436 return module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"),
437 eSymbolTypeData) != nullptr;
440 bool ParseCoordinate(llvm::StringRef coord_s, RSCoordinate &coord) {
441 // takes an argument of the form 'num[,num][,num]'. Where 'coord_s' is a
442 // comma separated 1,2 or 3-dimensional coordinate with the whitespace
443 // trimmed. Missing coordinates are defaulted to zero. If parsing of any
444 // elements fails the contents of &coord are undefined and `false` is
445 // returned, `true` otherwise
447 llvm::SmallVector<llvm::StringRef, 4> matches;
449 if (!RegularExpression("^([0-9]+),([0-9]+),([0-9]+)$")
450 .Execute(coord_s, &matches) &&
451 !RegularExpression("^([0-9]+),([0-9]+)$").Execute(coord_s, &matches) &&
452 !RegularExpression("^([0-9]+)$").Execute(coord_s, &matches))
455 auto get_index = [&](size_t idx, uint32_t &i) -> bool {
458 if (idx + 1 < matches.size()) {
459 return !llvm::StringRef(matches[idx + 1]).getAsInteger<uint32_t>(10, i);
464 return get_index(0, coord.x) && get_index(1, coord.y) &&
465 get_index(2, coord.z);
468 bool SkipPrologue(lldb::ModuleSP &module, Address &addr) {
469 Log *log = GetLog(LLDBLog::Language);
471 uint32_t resolved_flags =
472 module->ResolveSymbolContextForAddress(addr, eSymbolContextFunction, sc);
473 if (resolved_flags & eSymbolContextFunction) {
475 const uint32_t offset = sc.function->GetPrologueByteSize();
476 ConstString name = sc.GetFunctionName();
479 LLDB_LOGF(log, "%s: Prologue offset for %s is %" PRIu32, __FUNCTION__,
480 name.AsCString(), offset);
486 } // anonymous namespace
488 // The ScriptDetails class collects data associated with a single script
490 struct RenderScriptRuntime::ScriptDetails {
491 ~ScriptDetails() = default;
493 enum ScriptType { eScript, eScriptC };
495 // The derived type of the script.
496 empirical_type<ScriptType> type;
497 // The name of the original source file.
498 empirical_type<std::string> res_name;
499 // Path to script .so file on the device.
500 empirical_type<std::string> shared_lib;
501 // Directory where kernel objects are cached on device.
502 empirical_type<std::string> cache_dir;
503 // Pointer to the context which owns this script.
504 empirical_type<lldb::addr_t> context;
505 // Pointer to the script object itself.
506 empirical_type<lldb::addr_t> script;
509 // This Element class represents the Element object in RS, defining the type
510 // associated with an Allocation.
511 struct RenderScriptRuntime::Element {
512 // Taken from rsDefines.h
522 RS_KIND_INVALID = 100
525 // Taken from rsDefines.h
541 RS_TYPE_UNSIGNED_5_6_5,
542 RS_TYPE_UNSIGNED_5_5_5_1,
543 RS_TYPE_UNSIGNED_4_4_4_4,
549 RS_TYPE_ELEMENT = 1000,
555 RS_TYPE_PROGRAM_FRAGMENT,
556 RS_TYPE_PROGRAM_VERTEX,
557 RS_TYPE_PROGRAM_RASTER,
558 RS_TYPE_PROGRAM_STORE,
561 RS_TYPE_INVALID = 10000
564 std::vector<Element> children; // Child Element fields for structs
565 empirical_type<lldb::addr_t>
566 element_ptr; // Pointer to the RS Element of the Type
567 empirical_type<DataType>
568 type; // Type of each data pointer stored by the allocation
569 empirical_type<DataKind>
570 type_kind; // Defines pixel type if Allocation is created from an image
571 empirical_type<uint32_t>
572 type_vec_size; // Vector size of each data point, e.g '4' for uchar4
573 empirical_type<uint32_t> field_count; // Number of Subelements
574 empirical_type<uint32_t> datum_size; // Size of a single Element with padding
575 empirical_type<uint32_t> padding; // Number of padding bytes
576 empirical_type<uint32_t>
577 array_size; // Number of items in array, only needed for structs
578 ConstString type_name; // Name of type, only needed for structs
581 GetFallbackStructName(); // Print this as the type name of a struct Element
582 // If we can't resolve the actual struct name
584 bool ShouldRefresh() const {
585 const bool valid_ptr = element_ptr.isValid() && *element_ptr.get() != 0x0;
586 const bool valid_type =
587 type.isValid() && type_vec_size.isValid() && type_kind.isValid();
588 return !valid_ptr || !valid_type || !datum_size.isValid();
592 // This AllocationDetails class collects data associated with a single
593 // allocation instance.
594 struct RenderScriptRuntime::AllocationDetails {
609 // The FileHeader struct specifies the header we use for writing allocations
610 // to a binary file. Our format begins with the ASCII characters "RSAD",
611 // identifying the file as an allocation dump. Member variables dims and
612 // hdr_size are then written consecutively, immediately followed by an
613 // instance of the ElementHeader struct. Because Elements can contain
614 // subelements, there may be more than one instance of the ElementHeader
615 // struct. With this first instance being the root element, and the other
616 // instances being the root's descendants. To identify which instances are an
617 // ElementHeader's children, each struct is immediately followed by a
618 // sequence of consecutive offsets to the start of its child structs. These
620 // 4 bytes in size, and the 0 offset signifies no more children.
622 uint8_t ident[4]; // ASCII 'RSAD' identifying the file
623 uint32_t dims[3]; // Dimensions
624 uint16_t hdr_size; // Header size in bytes, including all element headers
627 struct ElementHeader {
628 uint16_t type; // DataType enum
629 uint32_t kind; // DataKind enum
630 uint32_t element_size; // Size of a single element, including padding
631 uint16_t vector_size; // Vector width
632 uint32_t array_size; // Number of elements in array
635 // Monotonically increasing from 1
638 // Maps Allocation DataType enum and vector size to printable strings using
639 // mapping from RenderScript numerical types summary documentation
640 static const char *RsDataTypeToString[][4];
642 // Maps Allocation DataKind enum to printable strings
643 static const char *RsDataKindToString[];
645 // Maps allocation types to format sizes for printing.
646 static const uint32_t RSTypeToFormat[][3];
648 // Give each allocation an ID as a way
649 // for commands to reference it.
652 // Allocation Element type
653 RenderScriptRuntime::Element element;
654 // Dimensions of the Allocation
655 empirical_type<Dimension> dimension;
656 // Pointer to address of the RS Allocation
657 empirical_type<lldb::addr_t> address;
658 // Pointer to the data held by the Allocation
659 empirical_type<lldb::addr_t> data_ptr;
660 // Pointer to the RS Type of the Allocation
661 empirical_type<lldb::addr_t> type_ptr;
662 // Pointer to the RS Context of the Allocation
663 empirical_type<lldb::addr_t> context;
664 // Size of the allocation
665 empirical_type<uint32_t> size;
666 // Stride between rows of the allocation
667 empirical_type<uint32_t> stride;
669 // Give each allocation an id, so we can reference it in user commands.
670 AllocationDetails() : id(ID++) {}
672 bool ShouldRefresh() const {
673 bool valid_ptrs = data_ptr.isValid() && *data_ptr.get() != 0x0;
674 valid_ptrs = valid_ptrs && type_ptr.isValid() && *type_ptr.get() != 0x0;
675 return !valid_ptrs || !dimension.isValid() || !size.isValid() ||
676 element.ShouldRefresh();
680 ConstString 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[] = {
688 "User", "Undefined", "Undefined", "Undefined",
689 "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",
724 "RS Program Fragment"},
725 {"RS Program Vertex", "RS Program Vertex", "RS Program Vertex",
726 "RS Program Vertex"},
727 {"RS Program Raster", "RS Program Raster", "RS Program Raster",
728 "RS Program Raster"},
729 {"RS Program Store", "RS Program Store", "RS Program Store",
731 {"RS Font", "RS Font", "RS Font", "RS Font"}};
733 // Used as an index into the RSTypeToFormat array elements
734 enum TypeToFormatIndex { eFormatSingle = 0, eFormatVector, eElementSize };
736 // { format enum of single element, format enum of element vector, size of
738 const uint32_t RenderScriptRuntime::AllocationDetails::RSTypeToFormat[][3] = {
740 {eFormatHex, eFormatHex, 1},
742 {eFormatFloat, eFormatVectorOfFloat16, 2},
744 {eFormatFloat, eFormatVectorOfFloat32, sizeof(float)},
746 {eFormatFloat, eFormatVectorOfFloat64, sizeof(double)},
748 {eFormatDecimal, eFormatVectorOfSInt8, sizeof(int8_t)},
750 {eFormatDecimal, eFormatVectorOfSInt16, sizeof(int16_t)},
752 {eFormatDecimal, eFormatVectorOfSInt32, sizeof(int32_t)},
754 {eFormatDecimal, eFormatVectorOfSInt64, sizeof(int64_t)},
755 // RS_TYPE_UNSIGNED_8
756 {eFormatDecimal, eFormatVectorOfUInt8, sizeof(uint8_t)},
757 // RS_TYPE_UNSIGNED_16
758 {eFormatDecimal, eFormatVectorOfUInt16, sizeof(uint16_t)},
759 // RS_TYPE_UNSIGNED_32
760 {eFormatDecimal, eFormatVectorOfUInt32, sizeof(uint32_t)},
761 // RS_TYPE_UNSIGNED_64
762 {eFormatDecimal, eFormatVectorOfUInt64, sizeof(uint64_t)},
764 {eFormatBoolean, eFormatBoolean, 1},
765 // RS_TYPE_UNSIGNED_5_6_5
766 {eFormatHex, eFormatHex, sizeof(uint16_t)},
767 // RS_TYPE_UNSIGNED_5_5_5_1
768 {eFormatHex, eFormatHex, sizeof(uint16_t)},
769 // RS_TYPE_UNSIGNED_4_4_4_4
770 {eFormatHex, eFormatHex, sizeof(uint16_t)},
771 // RS_TYPE_MATRIX_4X4
772 {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 16},
773 // RS_TYPE_MATRIX_3X3
774 {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 9},
775 // RS_TYPE_MATRIX_2X2
776 {eFormatVectorOfFloat32, eFormatVectorOfFloat32, sizeof(float) * 4}};
780 RenderScriptRuntime::CreateInstance(Process *process,
781 lldb::LanguageType language) {
783 if (language == eLanguageTypeExtRenderScript)
784 return new RenderScriptRuntime(process);
789 // Callback with a module to search for matching symbols. We first check that
790 // the module contains RS kernels. Then look for a symbol which matches our
791 // kernel name. The breakpoint address is finally set using the address of this
793 Searcher::CallbackReturn
794 RSBreakpointResolver::SearchCallback(SearchFilter &filter,
795 SymbolContext &context, Address *) {
796 BreakpointSP breakpoint_sp = GetBreakpoint();
797 assert(breakpoint_sp);
799 ModuleSP module = context.module_sp;
801 if (!module || !IsRenderScriptScriptModule(module))
802 return Searcher::eCallbackReturnContinue;
804 // Attempt to set a breakpoint on the kernel name symbol within the module
805 // library. If it's not found, it's likely debug info is unavailable - try to
806 // set a breakpoint on <name>.expand.
807 const Symbol *kernel_sym =
808 module->FindFirstSymbolWithNameAndType(m_kernel_name, eSymbolTypeCode);
810 std::string kernel_name_expanded(m_kernel_name.AsCString());
811 kernel_name_expanded.append(".expand");
812 kernel_sym = module->FindFirstSymbolWithNameAndType(
813 ConstString(kernel_name_expanded.c_str()), eSymbolTypeCode);
817 Address bp_addr = kernel_sym->GetAddress();
818 if (filter.AddressPasses(bp_addr))
819 breakpoint_sp->AddLocation(bp_addr);
822 return Searcher::eCallbackReturnContinue;
825 Searcher::CallbackReturn
826 RSReduceBreakpointResolver::SearchCallback(lldb_private::SearchFilter &filter,
827 lldb_private::SymbolContext &context,
829 BreakpointSP breakpoint_sp = GetBreakpoint();
830 assert(breakpoint_sp);
832 // We need to have access to the list of reductions currently parsed, as
833 // reduce names don't actually exist as symbols in a module. They are only
834 // identifiable by parsing the .rs.info packet, or finding the expand symbol.
835 // We therefore need access to the list of parsed rs modules to properly
836 // resolve reduction names.
837 Log *log = GetLog(LLDBLog::Breakpoints);
838 ModuleSP module = context.module_sp;
840 if (!module || !IsRenderScriptScriptModule(module))
841 return Searcher::eCallbackReturnContinue;
844 return Searcher::eCallbackReturnContinue;
846 for (const auto &module_desc : *m_rsmodules) {
847 if (module_desc->m_module != module)
850 for (const auto &reduction : module_desc->m_reductions) {
851 if (reduction.m_reduce_name != m_reduce_name)
854 std::array<std::pair<ConstString, int>, 5> funcs{
855 {{reduction.m_init_name, eKernelTypeInit},
856 {reduction.m_accum_name, eKernelTypeAccum},
857 {reduction.m_comb_name, eKernelTypeComb},
858 {reduction.m_outc_name, eKernelTypeOutC},
859 {reduction.m_halter_name, eKernelTypeHalter}}};
861 for (const auto &kernel : funcs) {
862 // Skip constituent functions that don't match our spec
863 if (!(m_kernel_types & kernel.second))
866 const auto kernel_name = kernel.first;
867 const auto symbol = module->FindFirstSymbolWithNameAndType(
868 kernel_name, eSymbolTypeCode);
872 auto address = symbol->GetAddress();
873 if (filter.AddressPasses(address)) {
875 if (!SkipPrologue(module, address)) {
876 LLDB_LOGF(log, "%s: Error trying to skip prologue", __FUNCTION__);
878 breakpoint_sp->AddLocation(address, &new_bp);
879 LLDB_LOGF(log, "%s: %s reduction breakpoint on %s in %s",
880 __FUNCTION__, new_bp ? "new" : "existing",
881 kernel_name.GetCString(),
882 address.GetModule()->GetFileSpec().GetCString());
887 return eCallbackReturnContinue;
890 Searcher::CallbackReturn RSScriptGroupBreakpointResolver::SearchCallback(
891 SearchFilter &filter, SymbolContext &context, Address *addr) {
893 BreakpointSP breakpoint_sp = GetBreakpoint();
895 return eCallbackReturnContinue;
897 Log *log = GetLog(LLDBLog::Breakpoints);
898 ModuleSP &module = context.module_sp;
900 if (!module || !IsRenderScriptScriptModule(module))
901 return Searcher::eCallbackReturnContinue;
903 std::vector<std::string> names;
904 Breakpoint& breakpoint = *breakpoint_sp;
905 breakpoint.GetNames(names);
907 return eCallbackReturnContinue;
909 for (auto &name : names) {
910 const RSScriptGroupDescriptorSP sg = FindScriptGroup(ConstString(name));
912 LLDB_LOGF(log, "%s: could not find script group for %s", __FUNCTION__,
917 LLDB_LOGF(log, "%s: Found ScriptGroup for %s", __FUNCTION__, name.c_str());
919 for (const RSScriptGroupDescriptor::Kernel &k : sg->m_kernels) {
921 LLDB_LOGF(log, "%s: Adding breakpoint for %s", __FUNCTION__,
922 k.m_name.AsCString());
923 LLDB_LOGF(log, "%s: Kernel address 0x%" PRIx64, __FUNCTION__, k.m_addr);
926 const lldb_private::Symbol *sym =
927 module->FindFirstSymbolWithNameAndType(k.m_name, eSymbolTypeCode);
929 LLDB_LOGF(log, "%s: Unable to find symbol for %s", __FUNCTION__,
930 k.m_name.AsCString());
935 LLDB_LOGF(log, "%s: Found symbol name is %s", __FUNCTION__,
936 sym->GetName().AsCString());
939 auto address = sym->GetAddress();
940 if (!SkipPrologue(module, address)) {
941 LLDB_LOGF(log, "%s: Error trying to skip prologue", __FUNCTION__);
945 breakpoint.AddLocation(address, &new_bp);
947 LLDB_LOGF(log, "%s: Placed %sbreakpoint on %s", __FUNCTION__,
948 new_bp ? "new " : "", k.m_name.AsCString());
950 // exit after placing the first breakpoint if we do not intend to stop on
951 // all kernels making up this script group
957 return eCallbackReturnContinue;
960 void RenderScriptRuntime::Initialize() {
961 PluginManager::RegisterPlugin(GetPluginNameStatic(),
962 "RenderScript language support", CreateInstance,
966 void RenderScriptRuntime::Terminate() {
967 PluginManager::UnregisterPlugin(CreateInstance);
970 RenderScriptRuntime::ModuleKind
971 RenderScriptRuntime::GetModuleKind(const lldb::ModuleSP &module_sp) {
973 if (IsRenderScriptScriptModule(module_sp))
974 return eModuleKindKernelObj;
976 // Is this the main RS runtime library
977 const ConstString rs_lib("libRS.so");
978 if (module_sp->GetFileSpec().GetFilename() == rs_lib) {
979 return eModuleKindLibRS;
982 const ConstString rs_driverlib("libRSDriver.so");
983 if (module_sp->GetFileSpec().GetFilename() == rs_driverlib) {
984 return eModuleKindDriver;
987 const ConstString rs_cpureflib("libRSCpuRef.so");
988 if (module_sp->GetFileSpec().GetFilename() == rs_cpureflib) {
989 return eModuleKindImpl;
992 return eModuleKindIgnored;
995 bool RenderScriptRuntime::IsRenderScriptModule(
996 const lldb::ModuleSP &module_sp) {
997 return GetModuleKind(module_sp) != eModuleKindIgnored;
1000 void RenderScriptRuntime::ModulesDidLoad(const ModuleList &module_list) {
1001 std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
1003 size_t num_modules = module_list.GetSize();
1004 for (size_t i = 0; i < num_modules; i++) {
1005 auto mod = module_list.GetModuleAtIndex(i);
1006 if (IsRenderScriptModule(mod)) {
1012 bool RenderScriptRuntime::GetDynamicTypeAndAddress(
1013 ValueObject &in_value, lldb::DynamicValueType use_dynamic,
1014 TypeAndOrName &class_type_or_name, Address &address,
1015 Value::ValueType &value_type) {
1020 RenderScriptRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name,
1021 ValueObject &static_value) {
1022 return type_and_or_name;
1025 bool RenderScriptRuntime::CouldHaveDynamicValue(ValueObject &in_value) {
1029 lldb::BreakpointResolverSP
1030 RenderScriptRuntime::CreateExceptionResolver(const lldb::BreakpointSP &bp,
1031 bool catch_bp, bool throw_bp) {
1032 BreakpointResolverSP resolver_sp;
1036 const RenderScriptRuntime::HookDefn RenderScriptRuntime::s_runtimeHookDefns[] =
1039 {"rsdScriptInit", "_Z13rsdScriptInitPKN7android12renderscript7ContextEP"
1040 "NS0_7ScriptCEPKcS7_PKhjj",
1041 "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_"
1042 "7ScriptCEPKcS7_PKhmj",
1043 0, RenderScriptRuntime::eModuleKindDriver,
1044 &lldb_private::RenderScriptRuntime::CaptureScriptInit},
1045 {"rsdScriptInvokeForEachMulti",
1046 "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
1047 "_6ScriptEjPPKNS0_10AllocationEjPS6_PKvjPK12RsScriptCall",
1048 "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0"
1049 "_6ScriptEjPPKNS0_10AllocationEmPS6_PKvmPK12RsScriptCall",
1050 0, RenderScriptRuntime::eModuleKindDriver,
1051 &lldb_private::RenderScriptRuntime::CaptureScriptInvokeForEachMulti},
1052 {"rsdScriptSetGlobalVar", "_Z21rsdScriptSetGlobalVarPKN7android12render"
1053 "script7ContextEPKNS0_6ScriptEjPvj",
1054 "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_"
1056 0, RenderScriptRuntime::eModuleKindDriver,
1057 &lldb_private::RenderScriptRuntime::CaptureSetGlobalVar},
1060 {"rsdAllocationInit", "_Z17rsdAllocationInitPKN7android12renderscript7C"
1061 "ontextEPNS0_10AllocationEb",
1062 "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_"
1064 0, RenderScriptRuntime::eModuleKindDriver,
1065 &lldb_private::RenderScriptRuntime::CaptureAllocationInit},
1066 {"rsdAllocationRead2D",
1067 "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
1068 "10AllocationEjjj23RsAllocationCubemapFacejjPvjj",
1069 "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_"
1070 "10AllocationEjjj23RsAllocationCubemapFacejjPvmm",
1071 0, RenderScriptRuntime::eModuleKindDriver, nullptr},
1072 {"rsdAllocationDestroy", "_Z20rsdAllocationDestroyPKN7android12rendersc"
1073 "ript7ContextEPNS0_10AllocationE",
1074 "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_"
1076 0, RenderScriptRuntime::eModuleKindDriver,
1077 &lldb_private::RenderScriptRuntime::CaptureAllocationDestroy},
1079 // renderscript script groups
1080 {"rsdDebugHintScriptGroup2", "_ZN7android12renderscript21debugHintScrip"
1081 "tGroup2EPKcjPKPFvPK24RsExpandKernelDriver"
1083 "_ZN7android12renderscript21debugHintScriptGroup2EPKcjPKPFvPK24RsExpan"
1084 "dKernelDriverInfojjjEj",
1085 0, RenderScriptRuntime::eModuleKindImpl,
1086 &lldb_private::RenderScriptRuntime::CaptureDebugHintScriptGroup2}};
1088 const size_t RenderScriptRuntime::s_runtimeHookCount =
1089 sizeof(s_runtimeHookDefns) / sizeof(s_runtimeHookDefns[0]);
1091 bool RenderScriptRuntime::HookCallback(void *baton,
1092 StoppointCallbackContext *ctx,
1093 lldb::user_id_t break_id,
1094 lldb::user_id_t break_loc_id) {
1095 RuntimeHook *hook = (RuntimeHook *)baton;
1096 ExecutionContext exe_ctx(ctx->exe_ctx_ref);
1098 RenderScriptRuntime *lang_rt = llvm::cast<RenderScriptRuntime>(
1099 exe_ctx.GetProcessPtr()->GetLanguageRuntime(
1100 eLanguageTypeExtRenderScript));
1102 lang_rt->HookCallback(hook, exe_ctx);
1107 void RenderScriptRuntime::HookCallback(RuntimeHook *hook,
1108 ExecutionContext &exe_ctx) {
1109 Log *log = GetLog(LLDBLog::Language);
1111 LLDB_LOGF(log, "%s - '%s'", __FUNCTION__, hook->defn->name);
1113 if (hook->defn->grabber) {
1114 (this->*(hook->defn->grabber))(hook, exe_ctx);
1118 void RenderScriptRuntime::CaptureDebugHintScriptGroup2(
1119 RuntimeHook *hook_info, ExecutionContext &context) {
1120 Log *log = GetLog(LLDBLog::Language);
1129 std::array<ArgItem, 4> args{{
1130 {ArgItem::ePointer, 0}, // const char *groupName
1131 {ArgItem::eInt32, 0}, // const uint32_t groupNameSize
1132 {ArgItem::ePointer, 0}, // const ExpandFuncTy *kernel
1133 {ArgItem::eInt32, 0}, // const uint32_t kernelCount
1136 if (!GetArgs(context, args.data(), args.size())) {
1137 LLDB_LOGF(log, "%s - Error while reading the function parameters",
1141 LLDB_LOGF(log, "%s - groupName : 0x%" PRIx64, __FUNCTION__,
1142 addr_t(args[eGroupName]));
1143 LLDB_LOGF(log, "%s - groupNameSize: %" PRIu64, __FUNCTION__,
1144 uint64_t(args[eGroupNameSize]));
1145 LLDB_LOGF(log, "%s - kernel : 0x%" PRIx64, __FUNCTION__,
1146 addr_t(args[eKernel]));
1147 LLDB_LOGF(log, "%s - kernelCount : %" PRIu64, __FUNCTION__,
1148 uint64_t(args[eKernelCount]));
1151 // parse script group name
1152 ConstString group_name;
1155 const uint64_t len = uint64_t(args[eGroupNameSize]);
1156 std::unique_ptr<char[]> buffer(new char[uint32_t(len + 1)]);
1157 m_process->ReadMemory(addr_t(args[eGroupName]), buffer.get(), len, err);
1158 buffer.get()[len] = '\0';
1159 if (!err.Success()) {
1160 LLDB_LOGF(log, "Error reading scriptgroup name from target");
1163 LLDB_LOGF(log, "Extracted scriptgroup name %s", buffer.get());
1165 // write back the script group name
1166 group_name.SetCString(buffer.get());
1169 // create or access existing script group
1170 RSScriptGroupDescriptorSP group;
1172 // search for existing script group
1173 for (auto sg : m_scriptGroups) {
1174 if (sg->m_name == group_name) {
1180 group = std::make_shared<RSScriptGroupDescriptor>();
1181 group->m_name = group_name;
1182 m_scriptGroups.push_back(group);
1184 // already have this script group
1185 LLDB_LOGF(log, "Attempt to add duplicate script group %s",
1186 group_name.AsCString());
1192 const uint32_t target_ptr_size = m_process->GetAddressByteSize();
1193 std::vector<addr_t> kernels;
1194 // parse kernel addresses in script group
1195 for (uint64_t i = 0; i < uint64_t(args[eKernelCount]); ++i) {
1196 RSScriptGroupDescriptor::Kernel kernel;
1197 // extract script group kernel addresses from the target
1198 const addr_t ptr_addr = addr_t(args[eKernel]) + i * target_ptr_size;
1199 uint64_t kernel_addr = 0;
1202 m_process->ReadMemory(ptr_addr, &kernel_addr, target_ptr_size, err);
1203 if (!err.Success() || read != target_ptr_size) {
1204 LLDB_LOGF(log, "Error parsing kernel address %" PRIu64 " in script group",
1208 LLDB_LOGF(log, "Extracted scriptgroup kernel address - 0x%" PRIx64,
1210 kernel.m_addr = kernel_addr;
1212 // try to resolve the associated kernel name
1213 if (!ResolveKernelName(kernel.m_addr, kernel.m_name)) {
1214 LLDB_LOGF(log, "Parsed scriptgroup kernel %" PRIu64 " - 0x%" PRIx64, i,
1219 // try to find the non '.expand' function
1221 const llvm::StringRef expand(".expand");
1222 const llvm::StringRef name_ref = kernel.m_name.GetStringRef();
1223 if (name_ref.endswith(expand)) {
1224 const ConstString base_kernel(name_ref.drop_back(expand.size()));
1225 // verify this function is a valid kernel
1226 if (IsKnownKernel(base_kernel)) {
1227 kernel.m_name = base_kernel;
1228 LLDB_LOGF(log, "%s - found non expand version '%s'", __FUNCTION__,
1229 base_kernel.GetCString());
1233 // add to a list of script group kernels we know about
1234 group->m_kernels.push_back(kernel);
1237 // Resolve any pending scriptgroup breakpoints
1239 Target &target = m_process->GetTarget();
1240 const BreakpointList &list = target.GetBreakpointList();
1241 const size_t num_breakpoints = list.GetSize();
1242 LLDB_LOGF(log, "Resolving %zu breakpoints", num_breakpoints);
1243 for (size_t i = 0; i < num_breakpoints; ++i) {
1244 const BreakpointSP bp = list.GetBreakpointAtIndex(i);
1246 if (bp->MatchesName(group_name.AsCString())) {
1247 LLDB_LOGF(log, "Found breakpoint with name %s",
1248 group_name.AsCString());
1249 bp->ResolveBreakpoint();
1256 void RenderScriptRuntime::CaptureScriptInvokeForEachMulti(
1257 RuntimeHook *hook, ExecutionContext &exe_ctx) {
1258 Log *log = GetLog(LLDBLog::Language);
1272 std::array<ArgItem, 9> args{{
1273 ArgItem{ArgItem::ePointer, 0}, // const Context *rsc
1274 ArgItem{ArgItem::ePointer, 0}, // Script *s
1275 ArgItem{ArgItem::eInt32, 0}, // uint32_t slot
1276 ArgItem{ArgItem::ePointer, 0}, // const Allocation **aIns
1277 ArgItem{ArgItem::eInt32, 0}, // size_t inLen
1278 ArgItem{ArgItem::ePointer, 0}, // Allocation *aout
1279 ArgItem{ArgItem::ePointer, 0}, // const void *usr
1280 ArgItem{ArgItem::eInt32, 0}, // size_t usrLen
1281 ArgItem{ArgItem::ePointer, 0}, // const RsScriptCall *sc
1284 bool success = GetArgs(exe_ctx, &args[0], args.size());
1286 LLDB_LOGF(log, "%s - Error while reading the function parameters",
1291 const uint32_t target_ptr_size = m_process->GetAddressByteSize();
1293 std::vector<uint64_t> allocs;
1295 // traverse allocation list
1296 for (uint64_t i = 0; i < uint64_t(args[eRsInLen]); ++i) {
1297 // calculate offest to allocation pointer
1298 const addr_t addr = addr_t(args[eRsAIns]) + i * target_ptr_size;
1300 // Note: due to little endian layout, reading 32bits or 64bits into res
1301 // will give the correct results.
1302 uint64_t result = 0;
1303 size_t read = m_process->ReadMemory(addr, &result, target_ptr_size, err);
1304 if (read != target_ptr_size || !err.Success()) {
1306 "%s - Error while reading allocation list argument %" PRIu64,
1309 allocs.push_back(result);
1313 // if there is an output allocation track it
1314 if (uint64_t alloc_out = uint64_t(args[eRsAOut])) {
1315 allocs.push_back(alloc_out);
1318 // for all allocations we have found
1319 for (const uint64_t alloc_addr : allocs) {
1320 AllocationDetails *alloc = LookUpAllocation(alloc_addr);
1322 alloc = CreateAllocation(alloc_addr);
1325 // save the allocation address
1326 if (alloc->address.isValid()) {
1327 // check the allocation address we already have matches
1328 assert(*alloc->address.get() == alloc_addr);
1330 alloc->address = alloc_addr;
1335 if (alloc->context.isValid() &&
1336 *alloc->context.get() != addr_t(args[eRsContext]))
1337 LLDB_LOGF(log, "%s - Allocation used by multiple contexts",
1340 alloc->context = addr_t(args[eRsContext]);
1344 // make sure we track this script object
1345 if (lldb_private::RenderScriptRuntime::ScriptDetails *script =
1346 LookUpScript(addr_t(args[eRsScript]), true)) {
1348 if (script->context.isValid() &&
1349 *script->context.get() != addr_t(args[eRsContext]))
1350 LLDB_LOGF(log, "%s - Script used by multiple contexts", __FUNCTION__);
1352 script->context = addr_t(args[eRsContext]);
1356 void RenderScriptRuntime::CaptureSetGlobalVar(RuntimeHook *hook,
1357 ExecutionContext &context) {
1358 Log *log = GetLog(LLDBLog::Language);
1368 std::array<ArgItem, 5> args{{
1369 ArgItem{ArgItem::ePointer, 0}, // eRsContext
1370 ArgItem{ArgItem::ePointer, 0}, // eRsScript
1371 ArgItem{ArgItem::eInt32, 0}, // eRsId
1372 ArgItem{ArgItem::ePointer, 0}, // eRsData
1373 ArgItem{ArgItem::eInt32, 0}, // eRsLength
1376 bool success = GetArgs(context, &args[0], args.size());
1378 LLDB_LOGF(log, "%s - error reading the function parameters.", __FUNCTION__);
1384 "%s - 0x%" PRIx64 ",0x%" PRIx64 " slot %" PRIu64 " = 0x%" PRIx64
1385 ":%" PRIu64 "bytes.",
1386 __FUNCTION__, uint64_t(args[eRsContext]),
1387 uint64_t(args[eRsScript]), uint64_t(args[eRsId]),
1388 uint64_t(args[eRsData]), uint64_t(args[eRsLength]));
1390 addr_t script_addr = addr_t(args[eRsScript]);
1391 if (m_scriptMappings.find(script_addr) != m_scriptMappings.end()) {
1392 auto rsm = m_scriptMappings[script_addr];
1393 if (uint64_t(args[eRsId]) < rsm->m_globals.size()) {
1394 auto rsg = rsm->m_globals[uint64_t(args[eRsId])];
1395 LLDB_LOGF(log, "%s - Setting of '%s' within '%s' inferred",
1396 __FUNCTION__, rsg.m_name.AsCString(),
1397 rsm->m_module->GetFileSpec().GetFilename().AsCString());
1403 void RenderScriptRuntime::CaptureAllocationInit(RuntimeHook *hook,
1404 ExecutionContext &exe_ctx) {
1405 Log *log = GetLog(LLDBLog::Language);
1407 enum { eRsContext, eRsAlloc, eRsForceZero };
1409 std::array<ArgItem, 3> args{{
1410 ArgItem{ArgItem::ePointer, 0}, // eRsContext
1411 ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
1412 ArgItem{ArgItem::eBool, 0}, // eRsForceZero
1415 bool success = GetArgs(exe_ctx, &args[0], args.size());
1417 LLDB_LOGF(log, "%s - error while reading the function parameters",
1422 LLDB_LOGF(log, "%s - 0x%" PRIx64 ",0x%" PRIx64 ",0x%" PRIx64 " .",
1423 __FUNCTION__, uint64_t(args[eRsContext]), uint64_t(args[eRsAlloc]),
1424 uint64_t(args[eRsForceZero]));
1426 AllocationDetails *alloc = CreateAllocation(uint64_t(args[eRsAlloc]));
1428 alloc->context = uint64_t(args[eRsContext]);
1431 void RenderScriptRuntime::CaptureAllocationDestroy(RuntimeHook *hook,
1432 ExecutionContext &exe_ctx) {
1433 Log *log = GetLog(LLDBLog::Language);
1440 std::array<ArgItem, 2> args{{
1441 ArgItem{ArgItem::ePointer, 0}, // eRsContext
1442 ArgItem{ArgItem::ePointer, 0}, // eRsAlloc
1445 bool success = GetArgs(exe_ctx, &args[0], args.size());
1447 LLDB_LOGF(log, "%s - error while reading the function parameters.",
1452 LLDB_LOGF(log, "%s - 0x%" PRIx64 ", 0x%" PRIx64 ".", __FUNCTION__,
1453 uint64_t(args[eRsContext]), uint64_t(args[eRsAlloc]));
1455 for (auto iter = m_allocations.begin(); iter != m_allocations.end(); ++iter) {
1456 auto &allocation_up = *iter; // get the unique pointer
1457 if (allocation_up->address.isValid() &&
1458 *allocation_up->address.get() == addr_t(args[eRsAlloc])) {
1459 m_allocations.erase(iter);
1460 LLDB_LOGF(log, "%s - deleted allocation entry.", __FUNCTION__);
1465 LLDB_LOGF(log, "%s - couldn't find destroyed allocation.", __FUNCTION__);
1468 void RenderScriptRuntime::CaptureScriptInit(RuntimeHook *hook,
1469 ExecutionContext &exe_ctx) {
1470 Log *log = GetLog(LLDBLog::Language);
1473 Process *process = exe_ctx.GetProcessPtr();
1475 enum { eRsContext, eRsScript, eRsResNamePtr, eRsCachedDirPtr };
1477 std::array<ArgItem, 4> args{
1478 {ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0},
1479 ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0}}};
1480 bool success = GetArgs(exe_ctx, &args[0], args.size());
1482 LLDB_LOGF(log, "%s - error while reading the function parameters.",
1487 std::string res_name;
1488 process->ReadCStringFromMemory(addr_t(args[eRsResNamePtr]), res_name, err);
1490 LLDB_LOGF(log, "%s - error reading res_name: %s.", __FUNCTION__,
1494 std::string cache_dir;
1495 process->ReadCStringFromMemory(addr_t(args[eRsCachedDirPtr]), cache_dir, err);
1497 LLDB_LOGF(log, "%s - error reading cache_dir: %s.", __FUNCTION__,
1501 LLDB_LOGF(log, "%s - 0x%" PRIx64 ",0x%" PRIx64 " => '%s' at '%s' .",
1502 __FUNCTION__, uint64_t(args[eRsContext]), uint64_t(args[eRsScript]),
1503 res_name.c_str(), cache_dir.c_str());
1505 if (res_name.size() > 0) {
1507 strm.Printf("librs.%s.so", res_name.c_str());
1509 ScriptDetails *script = LookUpScript(addr_t(args[eRsScript]), true);
1511 script->type = ScriptDetails::eScriptC;
1512 script->cache_dir = cache_dir;
1513 script->res_name = res_name;
1514 script->shared_lib = std::string(strm.GetString());
1515 script->context = addr_t(args[eRsContext]);
1519 "%s - '%s' tagged with context 0x%" PRIx64
1520 " and script 0x%" PRIx64 ".",
1521 __FUNCTION__, strm.GetData(), uint64_t(args[eRsContext]),
1522 uint64_t(args[eRsScript]));
1524 LLDB_LOGF(log, "%s - resource name invalid, Script not tagged.",
1529 void RenderScriptRuntime::LoadRuntimeHooks(lldb::ModuleSP module,
1531 Log *log = GetLog(LLDBLog::Language);
1537 Target &target = GetProcess()->GetTarget();
1538 const llvm::Triple::ArchType machine = target.GetArchitecture().GetMachine();
1540 if (machine != llvm::Triple::ArchType::x86 &&
1541 machine != llvm::Triple::ArchType::arm &&
1542 machine != llvm::Triple::ArchType::aarch64 &&
1543 machine != llvm::Triple::ArchType::mipsel &&
1544 machine != llvm::Triple::ArchType::mips64el &&
1545 machine != llvm::Triple::ArchType::x86_64) {
1546 LLDB_LOGF(log, "%s - unable to hook runtime functions.", __FUNCTION__);
1550 const uint32_t target_ptr_size =
1551 target.GetArchitecture().GetAddressByteSize();
1553 std::array<bool, s_runtimeHookCount> hook_placed;
1554 hook_placed.fill(false);
1556 for (size_t idx = 0; idx < s_runtimeHookCount; idx++) {
1557 const HookDefn *hook_defn = &s_runtimeHookDefns[idx];
1558 if (hook_defn->kind != kind) {
1562 const char *symbol_name = (target_ptr_size == 4)
1563 ? hook_defn->symbol_name_m32
1564 : hook_defn->symbol_name_m64;
1566 const Symbol *sym = module->FindFirstSymbolWithNameAndType(
1567 ConstString(symbol_name), eSymbolTypeCode);
1570 LLDB_LOGF(log, "%s - symbol '%s' related to the function %s not found",
1571 __FUNCTION__, symbol_name, hook_defn->name);
1576 addr_t addr = sym->GetLoadAddress(&target);
1577 if (addr == LLDB_INVALID_ADDRESS) {
1579 "%s - unable to resolve the address of hook function '%s' "
1580 "with symbol '%s'.",
1581 __FUNCTION__, hook_defn->name, symbol_name);
1584 LLDB_LOGF(log, "%s - function %s, address resolved at 0x%" PRIx64,
1585 __FUNCTION__, hook_defn->name, addr);
1588 RuntimeHookSP hook(new RuntimeHook());
1589 hook->address = addr;
1590 hook->defn = hook_defn;
1591 hook->bp_sp = target.CreateBreakpoint(addr, true, false);
1592 hook->bp_sp->SetCallback(HookCallback, hook.get(), true);
1593 m_runtimeHooks[addr] = hook;
1596 "%s - successfully hooked '%s' in '%s' version %" PRIu64
1597 " at 0x%" PRIx64 ".",
1598 __FUNCTION__, hook_defn->name,
1599 module->GetFileSpec().GetFilename().AsCString(),
1600 (uint64_t)hook_defn->version, (uint64_t)addr);
1602 hook_placed[idx] = true;
1605 // log any unhooked function
1607 for (size_t i = 0; i < hook_placed.size(); ++i) {
1610 const HookDefn &hook_defn = s_runtimeHookDefns[i];
1611 if (hook_defn.kind != kind)
1613 LLDB_LOGF(log, "%s - function %s was not hooked", __FUNCTION__,
1619 void RenderScriptRuntime::FixupScriptDetails(RSModuleDescriptorSP rsmodule_sp) {
1623 Log *log = GetLog(LLDBLog::Language);
1625 const ModuleSP module = rsmodule_sp->m_module;
1626 const FileSpec &file = module->GetPlatformFileSpec();
1628 // Iterate over all of the scripts that we currently know of. Note: We cant
1629 // push or pop to m_scripts here or it may invalidate rs_script.
1630 for (const auto &rs_script : m_scripts) {
1631 // Extract the expected .so file path for this script.
1632 std::string shared_lib;
1633 if (!rs_script->shared_lib.get(shared_lib))
1636 // Only proceed if the module that has loaded corresponds to this script.
1637 if (file.GetFilename() != ConstString(shared_lib.c_str()))
1640 // Obtain the script address which we use as a key.
1641 lldb::addr_t script;
1642 if (!rs_script->script.get(script))
1645 // If we have a script mapping for the current script.
1646 if (m_scriptMappings.find(script) != m_scriptMappings.end()) {
1647 // if the module we have stored is different to the one we just received.
1648 if (m_scriptMappings[script] != rsmodule_sp) {
1651 "%s - script %" PRIx64 " wants reassigned to new rsmodule '%s'.",
1652 __FUNCTION__, (uint64_t)script,
1653 rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
1656 // We don't have a script mapping for the current script.
1658 // Obtain the script resource name.
1659 std::string res_name;
1660 if (rs_script->res_name.get(res_name))
1661 // Set the modules resource name.
1662 rsmodule_sp->m_resname = res_name;
1663 // Add Script/Module pair to map.
1664 m_scriptMappings[script] = rsmodule_sp;
1665 LLDB_LOGF(log, "%s - script %" PRIx64 " associated with rsmodule '%s'.",
1666 __FUNCTION__, (uint64_t)script,
1667 rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
1672 // Uses the Target API to evaluate the expression passed as a parameter to the
1673 // function The result of that expression is returned an unsigned 64 bit int,
1674 // via the result* parameter. Function returns true on success, and false on
1676 bool RenderScriptRuntime::EvalRSExpression(const char *expr,
1677 StackFrame *frame_ptr,
1679 Log *log = GetLog(LLDBLog::Language);
1680 LLDB_LOGF(log, "%s(%s)", __FUNCTION__, expr);
1682 ValueObjectSP expr_result;
1683 EvaluateExpressionOptions options;
1684 options.SetLanguage(lldb::eLanguageTypeC_plus_plus);
1685 // Perform the actual expression evaluation
1686 auto &target = GetProcess()->GetTarget();
1687 target.EvaluateExpression(expr, frame_ptr, expr_result, options);
1690 LLDB_LOGF(log, "%s: couldn't evaluate expression.", __FUNCTION__);
1694 // The result of the expression is invalid
1695 if (!expr_result->GetError().Success()) {
1696 Status err = expr_result->GetError();
1697 // Expression returned is void, so this is actually a success
1698 if (err.GetError() == UserExpression::kNoResult) {
1699 LLDB_LOGF(log, "%s - expression returned void.", __FUNCTION__);
1705 LLDB_LOGF(log, "%s - error evaluating expression result: %s", __FUNCTION__,
1710 bool success = false;
1711 // We only read the result as an uint32_t.
1712 *result = expr_result->GetValueAsUnsigned(0, &success);
1715 LLDB_LOGF(log, "%s - couldn't convert expression result to uint32_t",
1724 // Used to index expression format strings
1725 enum ExpressionStrings {
1726 eExprGetOffsetPtr = 0,
1735 eExprElementFieldCount,
1737 eExprSubelementsName,
1738 eExprSubelementsArrSize,
1740 _eExprLast // keep at the end, implicit size of the array runtime_expressions
1743 // max length of an expanded expression
1744 const int jit_max_expr_size = 512;
1746 // Retrieve the string to JIT for the given expression
1747 #define JIT_TEMPLATE_CONTEXT "void* ctxt = (void*)rsDebugGetContextWrapper(0x%" PRIx64 "); "
1748 const char *JITTemplate(ExpressionStrings e) {
1749 // Format strings containing the expressions we may need to evaluate.
1750 static std::array<const char *, _eExprLast> runtime_expressions = {
1751 {// Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap)
1753 "Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocation"
1755 "(0x%" PRIx64 ", %" PRIu32 ", %" PRIu32 ", %" PRIu32 ", 0, 0)", // eExprGetOffsetPtr
1757 // Type* rsaAllocationGetType(Context*, Allocation*)
1758 JIT_TEMPLATE_CONTEXT "(void*)rsaAllocationGetType(ctxt, 0x%" PRIx64 ")", // eExprAllocGetType
1760 // rsaTypeGetNativeData(Context*, Type*, void* typeData, size) Pack the
1761 // data in the following way mHal.state.dimX; mHal.state.dimY;
1762 // mHal.state.dimZ; mHal.state.lodCount; mHal.state.faces; mElement;
1763 // into typeData Need to specify 32 or 64 bit for uint_t since this
1764 // differs between devices
1765 JIT_TEMPLATE_CONTEXT
1766 "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
1767 ", 0x%" PRIx64 ", data, 6); data[0]", // eExprTypeDimX
1768 JIT_TEMPLATE_CONTEXT
1769 "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
1770 ", 0x%" PRIx64 ", data, 6); data[1]", // eExprTypeDimY
1771 JIT_TEMPLATE_CONTEXT
1772 "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
1773 ", 0x%" PRIx64 ", data, 6); data[2]", // eExprTypeDimZ
1774 JIT_TEMPLATE_CONTEXT
1775 "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(ctxt"
1776 ", 0x%" PRIx64 ", data, 6); data[5]", // eExprTypeElemPtr
1778 // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size)
1779 // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into
1781 JIT_TEMPLATE_CONTEXT
1782 "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
1783 ", 0x%" PRIx64 ", data, 5); data[0]", // eExprElementType
1784 JIT_TEMPLATE_CONTEXT
1785 "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
1786 ", 0x%" PRIx64 ", data, 5); data[1]", // eExprElementKind
1787 JIT_TEMPLATE_CONTEXT
1788 "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
1789 ", 0x%" PRIx64 ", data, 5); data[3]", // eExprElementVec
1790 JIT_TEMPLATE_CONTEXT
1791 "uint32_t data[5]; (void*)rsaElementGetNativeData(ctxt"
1792 ", 0x%" PRIx64 ", data, 5); data[4]", // eExprElementFieldCount
1794 // rsaElementGetSubElements(RsContext con, RsElement elem, uintptr_t
1795 // *ids, const char **names, size_t *arraySizes, uint32_t dataSize)
1796 // Needed for Allocations of structs to gather details about
1797 // fields/Subelements Element* of field
1798 JIT_TEMPLATE_CONTEXT "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1799 "]; size_t arr_size[%" PRIu32 "];"
1800 "(void*)rsaElementGetSubElements(ctxt, 0x%" PRIx64
1801 ", ids, names, arr_size, %" PRIu32 "); ids[%" PRIu32 "]", // eExprSubelementsId
1804 JIT_TEMPLATE_CONTEXT "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1805 "]; size_t arr_size[%" PRIu32 "];"
1806 "(void*)rsaElementGetSubElements(ctxt, 0x%" PRIx64
1807 ", ids, names, arr_size, %" PRIu32 "); names[%" PRIu32 "]", // eExprSubelementsName
1809 // Array size of field
1810 JIT_TEMPLATE_CONTEXT "void* ids[%" PRIu32 "]; const char* names[%" PRIu32
1811 "]; size_t arr_size[%" PRIu32 "];"
1812 "(void*)rsaElementGetSubElements(ctxt, 0x%" PRIx64
1813 ", ids, names, arr_size, %" PRIu32 "); arr_size[%" PRIu32 "]"}}; // eExprSubelementsArrSize
1815 return runtime_expressions[e];
1817 } // end of the anonymous namespace
1819 // JITs the RS runtime for the internal data pointer of an allocation. Is
1820 // passed x,y,z coordinates for the pointer to a specific element. Then sets
1821 // the data_ptr member in Allocation with the result. Returns true on success,
1823 bool RenderScriptRuntime::JITDataPointer(AllocationDetails *alloc,
1824 StackFrame *frame_ptr, uint32_t x,
1825 uint32_t y, uint32_t z) {
1826 Log *log = GetLog(LLDBLog::Language);
1828 if (!alloc->address.isValid()) {
1829 LLDB_LOGF(log, "%s - failed to find allocation details.", __FUNCTION__);
1833 const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
1834 char expr_buf[jit_max_expr_size];
1836 int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
1837 *alloc->address.get(), x, y, z);
1839 LLDB_LOGF(log, "%s - encoding error in snprintf().", __FUNCTION__);
1841 } else if (written >= jit_max_expr_size) {
1842 LLDB_LOGF(log, "%s - expression too long.", __FUNCTION__);
1846 uint64_t result = 0;
1847 if (!EvalRSExpression(expr_buf, frame_ptr, &result))
1850 addr_t data_ptr = static_cast<lldb::addr_t>(result);
1851 alloc->data_ptr = data_ptr;
1856 // JITs the RS runtime for the internal pointer to the RS Type of an allocation
1857 // Then sets the type_ptr member in Allocation with the result. Returns true on
1858 // success, false otherwise
1859 bool RenderScriptRuntime::JITTypePointer(AllocationDetails *alloc,
1860 StackFrame *frame_ptr) {
1861 Log *log = GetLog(LLDBLog::Language);
1863 if (!alloc->address.isValid() || !alloc->context.isValid()) {
1864 LLDB_LOGF(log, "%s - failed to find allocation details.", __FUNCTION__);
1868 const char *fmt_str = JITTemplate(eExprAllocGetType);
1869 char expr_buf[jit_max_expr_size];
1871 int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
1872 *alloc->context.get(), *alloc->address.get());
1874 LLDB_LOGF(log, "%s - encoding error in snprintf().", __FUNCTION__);
1876 } else if (written >= jit_max_expr_size) {
1877 LLDB_LOGF(log, "%s - expression too long.", __FUNCTION__);
1881 uint64_t result = 0;
1882 if (!EvalRSExpression(expr_buf, frame_ptr, &result))
1885 addr_t type_ptr = static_cast<lldb::addr_t>(result);
1886 alloc->type_ptr = type_ptr;
1891 // JITs the RS runtime for information about the dimensions and type of an
1892 // allocation Then sets dimension and element_ptr members in Allocation with
1893 // the result. Returns true on success, false otherwise
1894 bool RenderScriptRuntime::JITTypePacked(AllocationDetails *alloc,
1895 StackFrame *frame_ptr) {
1896 Log *log = GetLog(LLDBLog::Language);
1898 if (!alloc->type_ptr.isValid() || !alloc->context.isValid()) {
1899 LLDB_LOGF(log, "%s - Failed to find allocation details.", __FUNCTION__);
1903 // Expression is different depending on if device is 32 or 64 bit
1904 uint32_t target_ptr_size =
1905 GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
1906 const uint32_t bits = target_ptr_size == 4 ? 32 : 64;
1908 // We want 4 elements from packed data
1909 const uint32_t num_exprs = 4;
1910 static_assert(num_exprs == (eExprTypeElemPtr - eExprTypeDimX + 1),
1911 "Invalid number of expressions");
1913 char expr_bufs[num_exprs][jit_max_expr_size];
1914 uint64_t results[num_exprs];
1916 for (uint32_t i = 0; i < num_exprs; ++i) {
1917 const char *fmt_str = JITTemplate(ExpressionStrings(eExprTypeDimX + i));
1918 int written = snprintf(expr_bufs[i], jit_max_expr_size, fmt_str,
1919 *alloc->context.get(), bits, *alloc->type_ptr.get());
1921 LLDB_LOGF(log, "%s - encoding error in snprintf().", __FUNCTION__);
1923 } else if (written >= jit_max_expr_size) {
1924 LLDB_LOGF(log, "%s - expression too long.", __FUNCTION__);
1928 // Perform expression evaluation
1929 if (!EvalRSExpression(expr_bufs[i], frame_ptr, &results[i]))
1933 // Assign results to allocation members
1934 AllocationDetails::Dimension dims;
1935 dims.dim_1 = static_cast<uint32_t>(results[0]);
1936 dims.dim_2 = static_cast<uint32_t>(results[1]);
1937 dims.dim_3 = static_cast<uint32_t>(results[2]);
1938 alloc->dimension = dims;
1940 addr_t element_ptr = static_cast<lldb::addr_t>(results[3]);
1941 alloc->element.element_ptr = element_ptr;
1944 "%s - dims (%" PRIu32 ", %" PRIu32 ", %" PRIu32
1945 ") Element*: 0x%" PRIx64 ".",
1946 __FUNCTION__, dims.dim_1, dims.dim_2, dims.dim_3, element_ptr);
1951 // JITs the RS runtime for information about the Element of an allocation Then
1952 // sets type, type_vec_size, field_count and type_kind members in Element with
1953 // the result. Returns true on success, false otherwise
1954 bool RenderScriptRuntime::JITElementPacked(Element &elem,
1955 const lldb::addr_t context,
1956 StackFrame *frame_ptr) {
1957 Log *log = GetLog(LLDBLog::Language);
1959 if (!elem.element_ptr.isValid()) {
1960 LLDB_LOGF(log, "%s - failed to find allocation details.", __FUNCTION__);
1964 // We want 4 elements from packed data
1965 const uint32_t num_exprs = 4;
1966 static_assert(num_exprs == (eExprElementFieldCount - eExprElementType + 1),
1967 "Invalid number of expressions");
1969 char expr_bufs[num_exprs][jit_max_expr_size];
1970 uint64_t results[num_exprs];
1972 for (uint32_t i = 0; i < num_exprs; i++) {
1973 const char *fmt_str = JITTemplate(ExpressionStrings(eExprElementType + i));
1974 int written = snprintf(expr_bufs[i], jit_max_expr_size, fmt_str, context,
1975 *elem.element_ptr.get());
1977 LLDB_LOGF(log, "%s - encoding error in snprintf().", __FUNCTION__);
1979 } else if (written >= jit_max_expr_size) {
1980 LLDB_LOGF(log, "%s - expression too long.", __FUNCTION__);
1984 // Perform expression evaluation
1985 if (!EvalRSExpression(expr_bufs[i], frame_ptr, &results[i]))
1989 // Assign results to allocation members
1990 elem.type = static_cast<RenderScriptRuntime::Element::DataType>(results[0]);
1992 static_cast<RenderScriptRuntime::Element::DataKind>(results[1]);
1993 elem.type_vec_size = static_cast<uint32_t>(results[2]);
1994 elem.field_count = static_cast<uint32_t>(results[3]);
1997 "%s - data type %" PRIu32 ", pixel type %" PRIu32
1998 ", vector size %" PRIu32 ", field count %" PRIu32,
1999 __FUNCTION__, *elem.type.get(), *elem.type_kind.get(),
2000 *elem.type_vec_size.get(), *elem.field_count.get());
2002 // If this Element has subelements then JIT rsaElementGetSubElements() for
2003 // details about its fields
2004 return !(*elem.field_count.get() > 0 &&
2005 !JITSubelements(elem, context, frame_ptr));
2008 // JITs the RS runtime for information about the subelements/fields of a struct
2009 // allocation This is necessary for infering the struct type so we can pretty
2010 // print the allocation's contents. Returns true on success, false otherwise
2011 bool RenderScriptRuntime::JITSubelements(Element &elem,
2012 const lldb::addr_t context,
2013 StackFrame *frame_ptr) {
2014 Log *log = GetLog(LLDBLog::Language);
2016 if (!elem.element_ptr.isValid() || !elem.field_count.isValid()) {
2017 LLDB_LOGF(log, "%s - failed to find allocation details.", __FUNCTION__);
2021 const short num_exprs = 3;
2022 static_assert(num_exprs == (eExprSubelementsArrSize - eExprSubelementsId + 1),
2023 "Invalid number of expressions");
2025 char expr_buffer[jit_max_expr_size];
2028 // Iterate over struct fields.
2029 const uint32_t field_count = *elem.field_count.get();
2030 for (uint32_t field_index = 0; field_index < field_count; ++field_index) {
2032 for (uint32_t expr_index = 0; expr_index < num_exprs; ++expr_index) {
2033 const char *fmt_str =
2034 JITTemplate(ExpressionStrings(eExprSubelementsId + expr_index));
2035 int written = snprintf(expr_buffer, jit_max_expr_size, fmt_str,
2036 context, field_count, field_count, field_count,
2037 *elem.element_ptr.get(), field_count, field_index);
2039 LLDB_LOGF(log, "%s - encoding error in snprintf().", __FUNCTION__);
2041 } else if (written >= jit_max_expr_size) {
2042 LLDB_LOGF(log, "%s - expression too long.", __FUNCTION__);
2046 // Perform expression evaluation
2047 if (!EvalRSExpression(expr_buffer, frame_ptr, &results))
2050 LLDB_LOGF(log, "%s - expr result 0x%" PRIx64 ".", __FUNCTION__, results);
2052 switch (expr_index) {
2053 case 0: // Element* of child
2054 child.element_ptr = static_cast<addr_t>(results);
2056 case 1: // Name of child
2058 lldb::addr_t address = static_cast<addr_t>(results);
2061 GetProcess()->ReadCStringFromMemory(address, name, err);
2063 child.type_name = ConstString(name);
2065 LLDB_LOGF(log, "%s - warning: Couldn't read field name.",
2070 case 2: // Array size of child
2071 child.array_size = static_cast<uint32_t>(results);
2076 // We need to recursively JIT each Element field of the struct since
2077 // structs can be nested inside structs.
2078 if (!JITElementPacked(child, context, frame_ptr))
2080 elem.children.push_back(child);
2083 // Try to infer the name of the struct type so we can pretty print the
2084 // allocation contents.
2085 FindStructTypeName(elem, frame_ptr);
2090 // JITs the RS runtime for the address of the last element in the allocation.
2091 // The `elem_size` parameter represents the size of a single element, including
2092 // padding. Which is needed as an offset from the last element pointer. Using
2093 // this offset minus the starting address we can calculate the size of the
2094 // allocation. Returns true on success, false otherwise
2095 bool RenderScriptRuntime::JITAllocationSize(AllocationDetails *alloc,
2096 StackFrame *frame_ptr) {
2097 Log *log = GetLog(LLDBLog::Language);
2099 if (!alloc->address.isValid() || !alloc->dimension.isValid() ||
2100 !alloc->data_ptr.isValid() || !alloc->element.datum_size.isValid()) {
2101 LLDB_LOGF(log, "%s - failed to find allocation details.", __FUNCTION__);
2106 uint32_t dim_x = alloc->dimension.get()->dim_1;
2107 uint32_t dim_y = alloc->dimension.get()->dim_2;
2108 uint32_t dim_z = alloc->dimension.get()->dim_3;
2110 // Our plan of jitting the last element address doesn't seem to work for
2111 // struct Allocations` Instead try to infer the size ourselves without any
2112 // inter element padding.
2113 if (alloc->element.children.size() > 0) {
2121 alloc->size = dim_x * dim_y * dim_z * *alloc->element.datum_size.get();
2123 LLDB_LOGF(log, "%s - inferred size of struct allocation %" PRIu32 ".",
2124 __FUNCTION__, *alloc->size.get());
2128 const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
2129 char expr_buf[jit_max_expr_size];
2131 // Calculate last element
2132 dim_x = dim_x == 0 ? 0 : dim_x - 1;
2133 dim_y = dim_y == 0 ? 0 : dim_y - 1;
2134 dim_z = dim_z == 0 ? 0 : dim_z - 1;
2136 int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
2137 *alloc->address.get(), dim_x, dim_y, dim_z);
2139 LLDB_LOGF(log, "%s - encoding error in snprintf().", __FUNCTION__);
2141 } else if (written >= jit_max_expr_size) {
2142 LLDB_LOGF(log, "%s - expression too long.", __FUNCTION__);
2146 uint64_t result = 0;
2147 if (!EvalRSExpression(expr_buf, frame_ptr, &result))
2150 addr_t mem_ptr = static_cast<lldb::addr_t>(result);
2151 // Find pointer to last element and add on size of an element
2152 alloc->size = static_cast<uint32_t>(mem_ptr - *alloc->data_ptr.get()) +
2153 *alloc->element.datum_size.get();
2158 // JITs the RS runtime for information about the stride between rows in the
2159 // allocation. This is done to detect padding, since allocated memory is
2160 // 16-byte aligned. Returns true on success, false otherwise
2161 bool RenderScriptRuntime::JITAllocationStride(AllocationDetails *alloc,
2162 StackFrame *frame_ptr) {
2163 Log *log = GetLog(LLDBLog::Language);
2165 if (!alloc->address.isValid() || !alloc->data_ptr.isValid()) {
2166 LLDB_LOGF(log, "%s - failed to find allocation details.", __FUNCTION__);
2170 const char *fmt_str = JITTemplate(eExprGetOffsetPtr);
2171 char expr_buf[jit_max_expr_size];
2173 int written = snprintf(expr_buf, jit_max_expr_size, fmt_str,
2174 *alloc->address.get(), 0, 1, 0);
2176 LLDB_LOGF(log, "%s - encoding error in snprintf().", __FUNCTION__);
2178 } else if (written >= jit_max_expr_size) {
2179 LLDB_LOGF(log, "%s - expression too long.", __FUNCTION__);
2183 uint64_t result = 0;
2184 if (!EvalRSExpression(expr_buf, frame_ptr, &result))
2187 addr_t mem_ptr = static_cast<lldb::addr_t>(result);
2188 alloc->stride = static_cast<uint32_t>(mem_ptr - *alloc->data_ptr.get());
2193 // JIT all the current runtime info regarding an allocation
2194 bool RenderScriptRuntime::RefreshAllocation(AllocationDetails *alloc,
2195 StackFrame *frame_ptr) {
2196 // GetOffsetPointer()
2197 if (!JITDataPointer(alloc, frame_ptr))
2200 // rsaAllocationGetType()
2201 if (!JITTypePointer(alloc, frame_ptr))
2204 // rsaTypeGetNativeData()
2205 if (!JITTypePacked(alloc, frame_ptr))
2208 // rsaElementGetNativeData()
2209 if (!JITElementPacked(alloc->element, *alloc->context.get(), frame_ptr))
2212 // Sets the datum_size member in Element
2213 SetElementSize(alloc->element);
2215 // Use GetOffsetPointer() to infer size of the allocation
2216 return JITAllocationSize(alloc, frame_ptr);
2219 // Function attempts to set the type_name member of the parameterised Element
2220 // object. This string should be the name of the struct type the Element
2221 // represents. We need this string for pretty printing the Element to users.
2222 void RenderScriptRuntime::FindStructTypeName(Element &elem,
2223 StackFrame *frame_ptr) {
2224 Log *log = GetLog(LLDBLog::Language);
2226 if (!elem.type_name.IsEmpty()) // Name already set
2229 elem.type_name = Element::GetFallbackStructName(); // Default type name if
2232 // Find all the global variables from the script rs modules
2233 VariableList var_list;
2234 for (auto module_sp : m_rsmodules)
2235 module_sp->m_module->FindGlobalVariables(
2236 RegularExpression(llvm::StringRef(".")), UINT32_MAX, var_list);
2238 // Iterate over all the global variables looking for one with a matching type
2239 // to the Element. We make the assumption a match exists since there needs to
2240 // be a global variable to reflect the struct type back into java host code.
2241 for (const VariableSP &var_sp : var_list) {
2245 ValueObjectSP valobj_sp = ValueObjectVariable::Create(frame_ptr, var_sp);
2249 // Find the number of variable fields.
2250 // If it has no fields, or more fields than our Element, then it can't be
2251 // the struct we're looking for. Don't check for equality since RS can add
2252 // extra struct members for padding.
2253 size_t num_children = valobj_sp->GetNumChildren();
2254 if (num_children > elem.children.size() || num_children == 0)
2257 // Iterate over children looking for members with matching field names. If
2258 // all the field names match, this is likely the struct we want.
2259 // TODO: This could be made more robust by also checking children data
2260 // sizes, or array size
2262 for (size_t i = 0; i < num_children; ++i) {
2263 ValueObjectSP child = valobj_sp->GetChildAtIndex(i, true);
2264 if (!child || (child->GetName() != elem.children[i].type_name)) {
2270 // RS can add extra struct members for padding in the format
2271 // '#rs_padding_[0-9]+'
2272 if (found && num_children < elem.children.size()) {
2273 const uint32_t size_diff = elem.children.size() - num_children;
2274 LLDB_LOGF(log, "%s - %" PRIu32 " padding struct entries", __FUNCTION__,
2277 for (uint32_t i = 0; i < size_diff; ++i) {
2278 ConstString name = elem.children[num_children + i].type_name;
2279 if (strcmp(name.AsCString(), "#rs_padding") < 0)
2284 // We've found a global variable with matching type
2286 // Dereference since our Element type isn't a pointer.
2287 if (valobj_sp->IsPointerType()) {
2289 ValueObjectSP deref_valobj = valobj_sp->Dereference(err);
2291 valobj_sp = deref_valobj;
2294 // Save name of variable in Element.
2295 elem.type_name = valobj_sp->GetTypeName();
2296 LLDB_LOGF(log, "%s - element name set to %s", __FUNCTION__,
2297 elem.type_name.AsCString());
2304 // Function sets the datum_size member of Element. Representing the size of a
2305 // single instance including padding. Assumes the relevant allocation
2306 // information has already been jitted.
2307 void RenderScriptRuntime::SetElementSize(Element &elem) {
2308 Log *log = GetLog(LLDBLog::Language);
2309 const Element::DataType type = *elem.type.get();
2310 assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
2311 "Invalid allocation type");
2313 const uint32_t vec_size = *elem.type_vec_size.get();
2314 uint32_t data_size = 0;
2315 uint32_t padding = 0;
2317 // Element is of a struct type, calculate size recursively.
2318 if ((type == Element::RS_TYPE_NONE) && (elem.children.size() > 0)) {
2319 for (Element &child : elem.children) {
2320 SetElementSize(child);
2321 const uint32_t array_size =
2322 child.array_size.isValid() ? *child.array_size.get() : 1;
2323 data_size += *child.datum_size.get() * array_size;
2326 // These have been packed already
2327 else if (type == Element::RS_TYPE_UNSIGNED_5_6_5 ||
2328 type == Element::RS_TYPE_UNSIGNED_5_5_5_1 ||
2329 type == Element::RS_TYPE_UNSIGNED_4_4_4_4) {
2330 data_size = AllocationDetails::RSTypeToFormat[type][eElementSize];
2331 } else if (type < Element::RS_TYPE_ELEMENT) {
2333 vec_size * AllocationDetails::RSTypeToFormat[type][eElementSize];
2335 padding = AllocationDetails::RSTypeToFormat[type][eElementSize];
2338 GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
2340 elem.padding = padding;
2341 elem.datum_size = data_size + padding;
2342 LLDB_LOGF(log, "%s - element size set to %" PRIu32, __FUNCTION__,
2343 data_size + padding);
2346 // Given an allocation, this function copies the allocation contents from
2347 // device into a buffer on the heap. Returning a shared pointer to the buffer
2348 // containing the data.
2349 std::shared_ptr<uint8_t>
2350 RenderScriptRuntime::GetAllocationData(AllocationDetails *alloc,
2351 StackFrame *frame_ptr) {
2352 Log *log = GetLog(LLDBLog::Language);
2354 // JIT all the allocation details
2355 if (alloc->ShouldRefresh()) {
2356 LLDB_LOGF(log, "%s - allocation details not calculated yet, jitting info",
2359 if (!RefreshAllocation(alloc, frame_ptr)) {
2360 LLDB_LOGF(log, "%s - couldn't JIT allocation details", __FUNCTION__);
2365 assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2366 alloc->element.type_vec_size.isValid() && alloc->size.isValid() &&
2367 "Allocation information not available");
2369 // Allocate a buffer to copy data into
2370 const uint32_t size = *alloc->size.get();
2371 std::shared_ptr<uint8_t> buffer(new uint8_t[size]);
2373 LLDB_LOGF(log, "%s - couldn't allocate a %" PRIu32 " byte buffer",
2374 __FUNCTION__, size);
2378 // Read the inferior memory
2380 lldb::addr_t data_ptr = *alloc->data_ptr.get();
2381 GetProcess()->ReadMemory(data_ptr, buffer.get(), size, err);
2384 "%s - '%s' Couldn't read %" PRIu32
2385 " bytes of allocation data from 0x%" PRIx64,
2386 __FUNCTION__, err.AsCString(), size, data_ptr);
2393 // Function copies data from a binary file into an allocation. There is a
2394 // header at the start of the file, FileHeader, before the data content itself.
2395 // Information from this header is used to display warnings to the user about
2396 // incompatibilities
2397 bool RenderScriptRuntime::LoadAllocation(Stream &strm, const uint32_t alloc_id,
2399 StackFrame *frame_ptr) {
2400 Log *log = GetLog(LLDBLog::Language);
2402 // Find allocation with the given id
2403 AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
2407 LLDB_LOGF(log, "%s - found allocation 0x%" PRIx64, __FUNCTION__,
2408 *alloc->address.get());
2410 // JIT all the allocation details
2411 if (alloc->ShouldRefresh()) {
2412 LLDB_LOGF(log, "%s - allocation details not calculated yet, jitting info.",
2415 if (!RefreshAllocation(alloc, frame_ptr)) {
2416 LLDB_LOGF(log, "%s - couldn't JIT allocation details", __FUNCTION__);
2421 assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2422 alloc->element.type_vec_size.isValid() && alloc->size.isValid() &&
2423 alloc->element.datum_size.isValid() &&
2424 "Allocation information not available");
2426 // Check we can read from file
2427 FileSpec file(path);
2428 FileSystem::Instance().Resolve(file);
2429 if (!FileSystem::Instance().Exists(file)) {
2430 strm.Printf("Error: File %s does not exist", path);
2435 if (!FileSystem::Instance().Readable(file)) {
2436 strm.Printf("Error: File %s does not have readable permissions", path);
2441 // Read file into data buffer
2442 auto data_sp = FileSystem::Instance().CreateDataBuffer(file.GetPath());
2444 // Cast start of buffer to FileHeader and use pointer to read metadata
2445 const void *file_buf = data_sp->GetBytes();
2446 if (file_buf == nullptr ||
2447 data_sp->GetByteSize() < (sizeof(AllocationDetails::FileHeader) +
2448 sizeof(AllocationDetails::ElementHeader))) {
2449 strm.Printf("Error: File %s does not contain enough data for header", path);
2453 const AllocationDetails::FileHeader *file_header =
2454 static_cast<const AllocationDetails::FileHeader *>(file_buf);
2456 // Check file starts with ascii characters "RSAD"
2457 if (memcmp(file_header->ident, "RSAD", 4)) {
2458 strm.Printf("Error: File doesn't contain identifier for an RS allocation "
2459 "dump. Are you sure this is the correct file?");
2464 // Look at the type of the root element in the header
2465 AllocationDetails::ElementHeader root_el_hdr;
2466 memcpy(&root_el_hdr,
2467 static_cast<const uint8_t *>(file_buf) +
2468 sizeof(AllocationDetails::FileHeader),
2469 sizeof(AllocationDetails::ElementHeader));
2471 LLDB_LOGF(log, "%s - header type %" PRIu32 ", element size %" PRIu32,
2472 __FUNCTION__, root_el_hdr.type, root_el_hdr.element_size);
2474 // Check if the target allocation and file both have the same number of bytes
2476 if (*alloc->element.datum_size.get() != root_el_hdr.element_size) {
2477 strm.Printf("Warning: Mismatched Element sizes - file %" PRIu32
2478 " bytes, allocation %" PRIu32 " bytes",
2479 root_el_hdr.element_size, *alloc->element.datum_size.get());
2483 // Check if the target allocation and file both have the same type
2484 const uint32_t alloc_type = static_cast<uint32_t>(*alloc->element.type.get());
2485 const uint32_t file_type = root_el_hdr.type;
2487 if (file_type > Element::RS_TYPE_FONT) {
2488 strm.Printf("Warning: File has unknown allocation type");
2490 } else if (alloc_type != file_type) {
2491 // Enum value isn't monotonous, so doesn't always index RsDataTypeToString
2493 uint32_t target_type_name_idx = alloc_type;
2494 uint32_t head_type_name_idx = file_type;
2495 if (alloc_type >= Element::RS_TYPE_ELEMENT &&
2496 alloc_type <= Element::RS_TYPE_FONT)
2497 target_type_name_idx = static_cast<Element::DataType>(
2498 (alloc_type - Element::RS_TYPE_ELEMENT) +
2499 Element::RS_TYPE_MATRIX_2X2 + 1);
2501 if (file_type >= Element::RS_TYPE_ELEMENT &&
2502 file_type <= Element::RS_TYPE_FONT)
2503 head_type_name_idx = static_cast<Element::DataType>(
2504 (file_type - Element::RS_TYPE_ELEMENT) + Element::RS_TYPE_MATRIX_2X2 +
2507 const char *head_type_name =
2508 AllocationDetails::RsDataTypeToString[head_type_name_idx][0];
2509 const char *target_type_name =
2510 AllocationDetails::RsDataTypeToString[target_type_name_idx][0];
2513 "Warning: Mismatched Types - file '%s' type, allocation '%s' type",
2514 head_type_name, target_type_name);
2518 // Advance buffer past header
2519 file_buf = static_cast<const uint8_t *>(file_buf) + file_header->hdr_size;
2521 // Calculate size of allocation data in file
2522 size_t size = data_sp->GetByteSize() - file_header->hdr_size;
2524 // Check if the target allocation and file both have the same total data
2526 const uint32_t alloc_size = *alloc->size.get();
2527 if (alloc_size != size) {
2528 strm.Printf("Warning: Mismatched allocation sizes - file 0x%" PRIx64
2529 " bytes, allocation 0x%" PRIx32 " bytes",
2530 (uint64_t)size, alloc_size);
2532 // Set length to copy to minimum
2533 size = alloc_size < size ? alloc_size : size;
2536 // Copy file data from our buffer into the target allocation.
2537 lldb::addr_t alloc_data = *alloc->data_ptr.get();
2539 size_t written = GetProcess()->WriteMemory(alloc_data, file_buf, size, err);
2540 if (!err.Success() || written != size) {
2541 strm.Printf("Error: Couldn't write data to allocation %s", err.AsCString());
2546 strm.Printf("Contents of file '%s' read into allocation %" PRIu32, path,
2553 // Function takes as parameters a byte buffer, which will eventually be written
2554 // to file as the element header, an offset into that buffer, and an Element
2555 // that will be saved into the buffer at the parametrised offset. Return value
2556 // is the new offset after writing the element into the buffer. Elements are
2557 // saved to the file as the ElementHeader struct followed by offsets to the
2558 // structs of all the element's children.
2559 size_t RenderScriptRuntime::PopulateElementHeaders(
2560 const std::shared_ptr<uint8_t> header_buffer, size_t offset,
2561 const Element &elem) {
2562 // File struct for an element header with all the relevant details copied
2563 // from elem. We assume members are valid already.
2564 AllocationDetails::ElementHeader elem_header;
2565 elem_header.type = *elem.type.get();
2566 elem_header.kind = *elem.type_kind.get();
2567 elem_header.element_size = *elem.datum_size.get();
2568 elem_header.vector_size = *elem.type_vec_size.get();
2569 elem_header.array_size =
2570 elem.array_size.isValid() ? *elem.array_size.get() : 0;
2571 const size_t elem_header_size = sizeof(AllocationDetails::ElementHeader);
2573 // Copy struct into buffer and advance offset We assume that header_buffer
2574 // has been checked for nullptr before this method is called
2575 memcpy(header_buffer.get() + offset, &elem_header, elem_header_size);
2576 offset += elem_header_size;
2578 // Starting offset of child ElementHeader struct
2579 size_t child_offset =
2580 offset + ((elem.children.size() + 1) * sizeof(uint32_t));
2581 for (const RenderScriptRuntime::Element &child : elem.children) {
2582 // Recursively populate the buffer with the element header structs of
2583 // children. Then save the offsets where they were set after the parent
2585 memcpy(header_buffer.get() + offset, &child_offset, sizeof(uint32_t));
2586 offset += sizeof(uint32_t);
2588 child_offset = PopulateElementHeaders(header_buffer, child_offset, child);
2591 // Zero indicates no more children
2592 memset(header_buffer.get() + offset, 0, sizeof(uint32_t));
2594 return child_offset;
2597 // Given an Element object this function returns the total size needed in the
2598 // file header to store the element's details. Taking into account the size of
2599 // the element header struct, plus the offsets to all the element's children.
2600 // Function is recursive so that the size of all ancestors is taken into
2602 size_t RenderScriptRuntime::CalculateElementHeaderSize(const Element &elem) {
2603 // Offsets to children plus zero terminator
2604 size_t size = (elem.children.size() + 1) * sizeof(uint32_t);
2605 // Size of header struct with type details
2606 size += sizeof(AllocationDetails::ElementHeader);
2608 // Calculate recursively for all descendants
2609 for (const Element &child : elem.children)
2610 size += CalculateElementHeaderSize(child);
2615 // Function copies allocation contents into a binary file. This file can then
2616 // be loaded later into a different allocation. There is a header, FileHeader,
2617 // before the allocation data containing meta-data.
2618 bool RenderScriptRuntime::SaveAllocation(Stream &strm, const uint32_t alloc_id,
2620 StackFrame *frame_ptr) {
2621 Log *log = GetLog(LLDBLog::Language);
2623 // Find allocation with the given id
2624 AllocationDetails *alloc = FindAllocByID(strm, alloc_id);
2628 LLDB_LOGF(log, "%s - found allocation 0x%" PRIx64 ".", __FUNCTION__,
2629 *alloc->address.get());
2631 // JIT all the allocation details
2632 if (alloc->ShouldRefresh()) {
2633 LLDB_LOGF(log, "%s - allocation details not calculated yet, jitting info.",
2636 if (!RefreshAllocation(alloc, frame_ptr)) {
2637 LLDB_LOGF(log, "%s - couldn't JIT allocation details.", __FUNCTION__);
2642 assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() &&
2643 alloc->element.type_vec_size.isValid() &&
2644 alloc->element.datum_size.get() &&
2645 alloc->element.type_kind.isValid() && alloc->dimension.isValid() &&
2646 "Allocation information not available");
2648 // Check we can create writable file
2649 FileSpec file_spec(path);
2650 FileSystem::Instance().Resolve(file_spec);
2651 auto file = FileSystem::Instance().Open(
2652 file_spec, File::eOpenOptionWriteOnly | File::eOpenOptionCanCreate |
2653 File::eOpenOptionTruncate);
2656 std::string error = llvm::toString(file.takeError());
2657 strm.Printf("Error: Failed to open '%s' for writing: %s", path,
2663 // Read allocation into buffer of heap memory
2664 const std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
2666 strm.Printf("Error: Couldn't read allocation data into buffer");
2671 // Create the file header
2672 AllocationDetails::FileHeader head;
2673 memcpy(head.ident, "RSAD", 4);
2674 head.dims[0] = static_cast<uint32_t>(alloc->dimension.get()->dim_1);
2675 head.dims[1] = static_cast<uint32_t>(alloc->dimension.get()->dim_2);
2676 head.dims[2] = static_cast<uint32_t>(alloc->dimension.get()->dim_3);
2678 const size_t element_header_size = CalculateElementHeaderSize(alloc->element);
2679 assert((sizeof(AllocationDetails::FileHeader) + element_header_size) <
2681 "Element header too large");
2682 head.hdr_size = static_cast<uint16_t>(sizeof(AllocationDetails::FileHeader) +
2683 element_header_size);
2685 // Write the file header
2686 size_t num_bytes = sizeof(AllocationDetails::FileHeader);
2687 LLDB_LOGF(log, "%s - writing File Header, 0x%" PRIx64 " bytes", __FUNCTION__,
2688 (uint64_t)num_bytes);
2690 Status err = file.get()->Write(&head, num_bytes);
2691 if (!err.Success()) {
2692 strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
2697 // Create the headers describing the element type of the allocation.
2698 std::shared_ptr<uint8_t> element_header_buffer(
2699 new uint8_t[element_header_size]);
2700 if (element_header_buffer == nullptr) {
2701 strm.Printf("Internal Error: Couldn't allocate %" PRIu64
2702 " bytes on the heap",
2703 (uint64_t)element_header_size);
2708 PopulateElementHeaders(element_header_buffer, 0, alloc->element);
2710 // Write headers for allocation element type to file
2711 num_bytes = element_header_size;
2712 LLDB_LOGF(log, "%s - writing element headers, 0x%" PRIx64 " bytes.",
2713 __FUNCTION__, (uint64_t)num_bytes);
2715 err = file.get()->Write(element_header_buffer.get(), num_bytes);
2716 if (!err.Success()) {
2717 strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
2722 // Write allocation data to file
2723 num_bytes = static_cast<size_t>(*alloc->size.get());
2724 LLDB_LOGF(log, "%s - writing 0x%" PRIx64 " bytes", __FUNCTION__,
2725 (uint64_t)num_bytes);
2727 err = file.get()->Write(buffer.get(), num_bytes);
2728 if (!err.Success()) {
2729 strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), path);
2734 strm.Printf("Allocation written to file '%s'", path);
2739 bool RenderScriptRuntime::LoadModule(const lldb::ModuleSP &module_sp) {
2740 Log *log = GetLog(LLDBLog::Language);
2743 for (const auto &rs_module : m_rsmodules) {
2744 if (rs_module->m_module == module_sp) {
2745 // Check if the user has enabled automatically breaking on all RS
2747 if (m_breakAllKernels)
2748 BreakOnModuleKernels(rs_module);
2753 bool module_loaded = false;
2754 switch (GetModuleKind(module_sp)) {
2755 case eModuleKindKernelObj: {
2756 RSModuleDescriptorSP module_desc;
2757 module_desc = std::make_shared<RSModuleDescriptor>(module_sp);
2758 if (module_desc->ParseRSInfo()) {
2759 m_rsmodules.push_back(module_desc);
2760 module_desc->WarnIfVersionMismatch(GetProcess()
2763 .GetAsyncOutputStream()
2765 module_loaded = true;
2767 if (module_loaded) {
2768 FixupScriptDetails(module_desc);
2772 case eModuleKindDriver: {
2773 if (!m_libRSDriver) {
2774 m_libRSDriver = module_sp;
2775 LoadRuntimeHooks(m_libRSDriver, RenderScriptRuntime::eModuleKindDriver);
2779 case eModuleKindImpl: {
2780 if (!m_libRSCpuRef) {
2781 m_libRSCpuRef = module_sp;
2782 LoadRuntimeHooks(m_libRSCpuRef, RenderScriptRuntime::eModuleKindImpl);
2786 case eModuleKindLibRS: {
2788 m_libRS = module_sp;
2789 static ConstString gDbgPresentStr("gDebuggerPresent");
2790 const Symbol *debug_present = m_libRS->FindFirstSymbolWithNameAndType(
2791 gDbgPresentStr, eSymbolTypeData);
2792 if (debug_present) {
2794 uint32_t flag = 0x00000001U;
2795 Target &target = GetProcess()->GetTarget();
2796 addr_t addr = debug_present->GetLoadAddress(&target);
2797 GetProcess()->WriteMemory(addr, &flag, sizeof(flag), err);
2798 if (err.Success()) {
2799 LLDB_LOGF(log, "%s - debugger present flag set on debugee.",
2802 m_debuggerPresentFlagged = true;
2804 LLDB_LOGF(log, "%s - error writing debugger present flags '%s' ",
2805 __FUNCTION__, err.AsCString());
2810 "%s - error writing debugger present flags - symbol not found",
2821 return module_loaded;
2826 void RenderScriptRuntime::Update() {
2827 if (m_rsmodules.size() > 0) {
2834 void RSModuleDescriptor::WarnIfVersionMismatch(lldb_private::Stream *s) const {
2838 if (m_slang_version.empty() || m_bcc_version.empty()) {
2839 s->PutCString("WARNING: Unknown bcc or slang (llvm-rs-cc) version; debug "
2840 "experience may be unreliable");
2842 } else if (m_slang_version != m_bcc_version) {
2843 s->Printf("WARNING: The debug info emitted by the slang frontend "
2844 "(llvm-rs-cc) used to build this module (%s) does not match the "
2845 "version of bcc used to generate the debug information (%s). "
2846 "This is an unsupported configuration and may result in a poor "
2847 "debugging experience; proceed with caution",
2848 m_slang_version.c_str(), m_bcc_version.c_str());
2853 bool RSModuleDescriptor::ParsePragmaCount(llvm::StringRef *lines,
2855 // Skip the pragma prototype line
2857 for (; n_lines--; ++lines) {
2858 const auto kv_pair = lines->split(" - ");
2859 m_pragmas[kv_pair.first.trim().str()] = kv_pair.second.trim().str();
2864 bool RSModuleDescriptor::ParseExportReduceCount(llvm::StringRef *lines,
2866 // The list of reduction kernels in the `.rs.info` symbol is of the form
2867 // "signature - accumulatordatasize - reduction_name - initializer_name -
2868 // accumulator_name - combiner_name - outconverter_name - halter_name" Where
2869 // a function is not explicitly named by the user, or is not generated by the
2870 // compiler, it is named "." so the dash separated list should always be 8
2872 Log *log = GetLog(LLDBLog::Language);
2873 // Skip the exportReduceCount line
2875 for (; n_lines--; ++lines) {
2876 llvm::SmallVector<llvm::StringRef, 8> spec;
2877 lines->split(spec, " - ");
2878 if (spec.size() != 8) {
2879 if (spec.size() < 8) {
2881 log->Error("Error parsing RenderScript reduction spec. wrong number "
2885 log->Warning("Extraneous members in reduction spec: '%s'",
2886 lines->str().c_str());
2889 const auto sig_s = spec[0];
2891 if (sig_s.getAsInteger(10, sig)) {
2893 log->Error("Error parsing Renderscript reduction spec: invalid kernel "
2895 sig_s.str().c_str());
2899 const auto accum_data_size_s = spec[1];
2900 uint32_t accum_data_size;
2901 if (accum_data_size_s.getAsInteger(10, accum_data_size)) {
2903 log->Error("Error parsing Renderscript reduction spec: invalid "
2904 "accumulator data size %s",
2905 accum_data_size_s.str().c_str());
2909 LLDB_LOGF(log, "Found RenderScript reduction '%s'", spec[2].str().c_str());
2911 m_reductions.push_back(RSReductionDescriptor(this, sig, accum_data_size,
2912 spec[2], spec[3], spec[4],
2913 spec[5], spec[6], spec[7]));
2918 bool RSModuleDescriptor::ParseVersionInfo(llvm::StringRef *lines,
2920 // Skip the versionInfo line
2922 for (; n_lines--; ++lines) {
2923 // We're only interested in bcc and slang versions, and ignore all other
2924 // versionInfo lines
2925 const auto kv_pair = lines->split(" - ");
2926 if (kv_pair.first == "slang")
2927 m_slang_version = kv_pair.second.str();
2928 else if (kv_pair.first == "bcc")
2929 m_bcc_version = kv_pair.second.str();
2934 bool RSModuleDescriptor::ParseExportForeachCount(llvm::StringRef *lines,
2936 // Skip the exportForeachCount line
2938 for (; n_lines--; ++lines) {
2940 // `forEach` kernels are listed in the `.rs.info` packet as a "slot - name"
2942 const auto kv_pair = lines->split(" - ");
2943 if (kv_pair.first.getAsInteger(10, slot))
2945 m_kernels.push_back(RSKernelDescriptor(this, kv_pair.second, slot));
2950 bool RSModuleDescriptor::ParseExportVarCount(llvm::StringRef *lines,
2952 // Skip the ExportVarCount line
2954 for (; n_lines--; ++lines)
2955 m_globals.push_back(RSGlobalDescriptor(this, *lines));
2959 // The .rs.info symbol in renderscript modules contains a string which needs to
2960 // be parsed. The string is basic and is parsed on a line by line basis.
2961 bool RSModuleDescriptor::ParseRSInfo() {
2963 Log *log = GetLog(LLDBLog::Language);
2964 const Symbol *info_sym = m_module->FindFirstSymbolWithNameAndType(
2965 ConstString(".rs.info"), eSymbolTypeData);
2969 const addr_t addr = info_sym->GetAddressRef().GetFileAddress();
2970 if (addr == LLDB_INVALID_ADDRESS)
2973 const addr_t size = info_sym->GetByteSize();
2974 const FileSpec fs = m_module->GetFileSpec();
2977 FileSystem::Instance().CreateDataBuffer(fs.GetPath(), size, addr);
2981 // split rs.info. contents into lines
2982 llvm::SmallVector<llvm::StringRef, 128> info_lines;
2984 const llvm::StringRef raw_rs_info((const char *)buffer->GetBytes());
2985 raw_rs_info.split(info_lines, '\n');
2986 LLDB_LOGF(log, "'.rs.info symbol for '%s':\n%s",
2987 m_module->GetFileSpec().GetCString(), raw_rs_info.str().c_str());
3000 const auto rs_info_handler = [](llvm::StringRef name) -> int {
3001 return llvm::StringSwitch<int>(name)
3002 // The number of visible global variables in the script
3003 .Case("exportVarCount", eExportVar)
3004 // The number of RenderScrip `forEach` kernels __attribute__((kernel))
3005 .Case("exportForEachCount", eExportForEach)
3006 // The number of generalreductions: This marked in the script by
3007 // `#pragma reduce()`
3008 .Case("exportReduceCount", eExportReduce)
3009 // Total count of all RenderScript specific `#pragmas` used in the
3011 .Case("pragmaCount", ePragma)
3012 .Case("objectSlotCount", eObjectSlot)
3013 .Case("versionInfo", eVersionInfo)
3017 // parse all text lines of .rs.info
3018 for (auto line = info_lines.begin(); line != info_lines.end(); ++line) {
3019 const auto kv_pair = line->split(": ");
3020 const auto key = kv_pair.first;
3021 const auto val = kv_pair.second.trim();
3023 const auto handler = rs_info_handler(key);
3026 // getAsInteger returns `true` on an error condition - we're only
3027 // interested in numeric fields at the moment
3029 if (val.getAsInteger(10, n_lines)) {
3030 LLDB_LOGV(log, "Failed to parse non-numeric '.rs.info' section {0}",
3034 if (info_lines.end() - (line + 1) < (ptrdiff_t)n_lines)
3037 bool success = false;
3040 success = ParseExportVarCount(line, n_lines);
3042 case eExportForEach:
3043 success = ParseExportForeachCount(line, n_lines);
3046 success = ParseExportReduceCount(line, n_lines);
3049 success = ParsePragmaCount(line, n_lines);
3052 success = ParseVersionInfo(line, n_lines);
3055 LLDB_LOGF(log, "%s - skipping .rs.info field '%s'", __FUNCTION__,
3056 line->str().c_str());
3064 return info_lines.size() > 0;
3067 void RenderScriptRuntime::DumpStatus(Stream &strm) const {
3069 strm.Printf("Runtime Library discovered.");
3072 if (m_libRSDriver) {
3073 strm.Printf("Runtime Driver discovered.");
3076 if (m_libRSCpuRef) {
3077 strm.Printf("CPU Reference Implementation discovered.");
3081 if (m_runtimeHooks.size()) {
3082 strm.Printf("Runtime functions hooked:");
3084 for (auto b : m_runtimeHooks) {
3085 strm.Indent(b.second->defn->name);
3089 strm.Printf("Runtime is not hooked.");
3094 void RenderScriptRuntime::DumpContexts(Stream &strm) const {
3095 strm.Printf("Inferred RenderScript Contexts:");
3099 std::map<addr_t, uint64_t> contextReferences;
3101 // Iterate over all of the currently discovered scripts. Note: We cant push
3102 // or pop from m_scripts inside this loop or it may invalidate script.
3103 for (const auto &script : m_scripts) {
3104 if (!script->context.isValid())
3106 lldb::addr_t context = *script->context;
3108 if (contextReferences.find(context) != contextReferences.end()) {
3109 contextReferences[context]++;
3111 contextReferences[context] = 1;
3115 for (const auto &cRef : contextReferences) {
3116 strm.Printf("Context 0x%" PRIx64 ": %" PRIu64 " script instances",
3117 cRef.first, cRef.second);
3123 void RenderScriptRuntime::DumpKernels(Stream &strm) const {
3124 strm.Printf("RenderScript Kernels:");
3127 for (const auto &module : m_rsmodules) {
3128 strm.Printf("Resource '%s':", module->m_resname.c_str());
3130 for (const auto &kernel : module->m_kernels) {
3131 strm.Indent(kernel.m_name.GetStringRef());
3138 RenderScriptRuntime::AllocationDetails *
3139 RenderScriptRuntime::FindAllocByID(Stream &strm, const uint32_t alloc_id) {
3140 AllocationDetails *alloc = nullptr;
3142 // See if we can find allocation using id as an index;
3143 if (alloc_id <= m_allocations.size() && alloc_id != 0 &&
3144 m_allocations[alloc_id - 1]->id == alloc_id) {
3145 alloc = m_allocations[alloc_id - 1].get();
3149 // Fallback to searching
3150 for (const auto &a : m_allocations) {
3151 if (a->id == alloc_id) {
3157 if (alloc == nullptr) {
3158 strm.Printf("Error: Couldn't find allocation with id matching %" PRIu32,
3166 // Prints the contents of an allocation to the output stream, which may be a
3168 bool RenderScriptRuntime::DumpAllocation(Stream &strm, StackFrame *frame_ptr,
3169 const uint32_t id) {
3170 Log *log = GetLog(LLDBLog::Language);
3172 // Check we can find the desired allocation
3173 AllocationDetails *alloc = FindAllocByID(strm, id);
3175 return false; // FindAllocByID() will print error message for us here
3177 LLDB_LOGF(log, "%s - found allocation 0x%" PRIx64, __FUNCTION__,
3178 *alloc->address.get());
3180 // Check we have information about the allocation, if not calculate it
3181 if (alloc->ShouldRefresh()) {
3182 LLDB_LOGF(log, "%s - allocation details not calculated yet, jitting info.",
3185 // JIT all the allocation information
3186 if (!RefreshAllocation(alloc, frame_ptr)) {
3187 strm.Printf("Error: Couldn't JIT allocation details");
3193 // Establish format and size of each data element
3194 const uint32_t vec_size = *alloc->element.type_vec_size.get();
3195 const Element::DataType type = *alloc->element.type.get();
3197 assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT &&
3198 "Invalid allocation type");
3200 lldb::Format format;
3201 if (type >= Element::RS_TYPE_ELEMENT)
3202 format = eFormatHex;
3204 format = vec_size == 1
3205 ? static_cast<lldb::Format>(
3206 AllocationDetails::RSTypeToFormat[type][eFormatSingle])
3207 : static_cast<lldb::Format>(
3208 AllocationDetails::RSTypeToFormat[type][eFormatVector]);
3210 const uint32_t data_size = *alloc->element.datum_size.get();
3212 LLDB_LOGF(log, "%s - element size %" PRIu32 " bytes, including padding",
3213 __FUNCTION__, data_size);
3215 // Allocate a buffer to copy data into
3216 std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
3218 strm.Printf("Error: Couldn't read allocation data");
3223 // Calculate stride between rows as there may be padding at end of rows since
3224 // allocated memory is 16-byte aligned
3225 if (!alloc->stride.isValid()) {
3226 if (alloc->dimension.get()->dim_2 == 0) // We only have one dimension
3228 else if (!JITAllocationStride(alloc, frame_ptr)) {
3229 strm.Printf("Error: Couldn't calculate allocation row stride");
3234 const uint32_t stride = *alloc->stride.get();
3235 const uint32_t size = *alloc->size.get(); // Size of whole allocation
3236 const uint32_t padding =
3237 alloc->element.padding.isValid() ? *alloc->element.padding.get() : 0;
3239 "%s - stride %" PRIu32 " bytes, size %" PRIu32
3240 " bytes, padding %" PRIu32,
3241 __FUNCTION__, stride, size, padding);
3243 // Find dimensions used to index loops, so need to be non-zero
3244 uint32_t dim_x = alloc->dimension.get()->dim_1;
3245 dim_x = dim_x == 0 ? 1 : dim_x;
3247 uint32_t dim_y = alloc->dimension.get()->dim_2;
3248 dim_y = dim_y == 0 ? 1 : dim_y;
3250 uint32_t dim_z = alloc->dimension.get()->dim_3;
3251 dim_z = dim_z == 0 ? 1 : dim_z;
3253 // Use data extractor to format output
3254 const uint32_t target_ptr_size =
3255 GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
3256 DataExtractor alloc_data(buffer.get(), size, GetProcess()->GetByteOrder(),
3259 uint32_t offset = 0; // Offset in buffer to next element to be printed
3260 uint32_t prev_row = 0; // Offset to the start of the previous row
3262 // Iterate over allocation dimensions, printing results to user
3263 strm.Printf("Data (X, Y, Z):");
3264 for (uint32_t z = 0; z < dim_z; ++z) {
3265 for (uint32_t y = 0; y < dim_y; ++y) {
3266 // Use stride to index start of next row.
3267 if (!(y == 0 && z == 0))
3268 offset = prev_row + stride;
3271 // Print each element in the row individually
3272 for (uint32_t x = 0; x < dim_x; ++x) {
3273 strm.Printf("\n(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ") = ", x, y, z);
3274 if ((type == Element::RS_TYPE_NONE) &&
3275 (alloc->element.children.size() > 0) &&
3276 (alloc->element.type_name != Element::GetFallbackStructName())) {
3277 // Here we are dumping an Element of struct type. This is done using
3278 // expression evaluation with the name of the struct type and pointer
3279 // to element. Don't print the name of the resulting expression,
3280 // since this will be '$[0-9]+'
3281 DumpValueObjectOptions expr_options;
3282 expr_options.SetHideName(true);
3284 // Setup expression as dereferencing a pointer cast to element
3286 char expr_char_buffer[jit_max_expr_size];
3288 snprintf(expr_char_buffer, jit_max_expr_size, "*(%s*) 0x%" PRIx64,
3289 alloc->element.type_name.AsCString(),
3290 *alloc->data_ptr.get() + offset);
3292 if (written < 0 || written >= jit_max_expr_size) {
3293 LLDB_LOGF(log, "%s - error in snprintf().", __FUNCTION__);
3297 // Evaluate expression
3298 ValueObjectSP expr_result;
3299 GetProcess()->GetTarget().EvaluateExpression(expr_char_buffer,
3300 frame_ptr, expr_result);
3302 // Print the results to our stream.
3303 expr_result->Dump(strm, expr_options);
3305 DumpDataExtractor(alloc_data, &strm, offset, format,
3306 data_size - padding, 1, 1, LLDB_INVALID_ADDRESS, 0,
3309 offset += data_size;
3318 // Function recalculates all our cached information about allocations by
3319 // jitting the RS runtime regarding each allocation we know about. Returns true
3320 // if all allocations could be recomputed, false otherwise.
3321 bool RenderScriptRuntime::RecomputeAllAllocations(Stream &strm,
3322 StackFrame *frame_ptr) {
3323 bool success = true;
3324 for (auto &alloc : m_allocations) {
3325 // JIT current allocation information
3326 if (!RefreshAllocation(alloc.get(), frame_ptr)) {
3327 strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32
3335 strm.Printf("All allocations successfully recomputed");
3341 // Prints information regarding currently loaded allocations. These details are
3342 // gathered by jitting the runtime, which has as latency. Index parameter
3343 // specifies a single allocation ID to print, or a zero value to print them all
3344 void RenderScriptRuntime::ListAllocations(Stream &strm, StackFrame *frame_ptr,
3345 const uint32_t index) {
3346 strm.Printf("RenderScript Allocations:");
3350 for (auto &alloc : m_allocations) {
3351 // index will only be zero if we want to print all allocations
3352 if (index != 0 && index != alloc->id)
3355 // JIT current allocation information
3356 if (alloc->ShouldRefresh() && !RefreshAllocation(alloc.get(), frame_ptr)) {
3357 strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32,
3363 strm.Printf("%" PRIu32 ":", alloc->id);
3367 strm.Indent("Context: ");
3368 if (!alloc->context.isValid())
3369 strm.Printf("unknown\n");
3371 strm.Printf("0x%" PRIx64 "\n", *alloc->context.get());
3373 strm.Indent("Address: ");
3374 if (!alloc->address.isValid())
3375 strm.Printf("unknown\n");
3377 strm.Printf("0x%" PRIx64 "\n", *alloc->address.get());
3379 strm.Indent("Data pointer: ");
3380 if (!alloc->data_ptr.isValid())
3381 strm.Printf("unknown\n");
3383 strm.Printf("0x%" PRIx64 "\n", *alloc->data_ptr.get());
3385 strm.Indent("Dimensions: ");
3386 if (!alloc->dimension.isValid())
3387 strm.Printf("unknown\n");
3389 strm.Printf("(%" PRId32 ", %" PRId32 ", %" PRId32 ")\n",
3390 alloc->dimension.get()->dim_1, alloc->dimension.get()->dim_2,
3391 alloc->dimension.get()->dim_3);
3393 strm.Indent("Data Type: ");
3394 if (!alloc->element.type.isValid() ||
3395 !alloc->element.type_vec_size.isValid())
3396 strm.Printf("unknown\n");
3398 const int vector_size = *alloc->element.type_vec_size.get();
3399 Element::DataType type = *alloc->element.type.get();
3401 if (!alloc->element.type_name.IsEmpty())
3402 strm.Printf("%s\n", alloc->element.type_name.AsCString());
3404 // Enum value isn't monotonous, so doesn't always index
3405 // RsDataTypeToString array
3406 if (type >= Element::RS_TYPE_ELEMENT && type <= Element::RS_TYPE_FONT)
3408 static_cast<Element::DataType>((type - Element::RS_TYPE_ELEMENT) +
3409 Element::RS_TYPE_MATRIX_2X2 + 1);
3411 if (type >= (sizeof(AllocationDetails::RsDataTypeToString) /
3412 sizeof(AllocationDetails::RsDataTypeToString[0])) ||
3413 vector_size > 4 || vector_size < 1)
3414 strm.Printf("invalid type\n");
3418 AllocationDetails::RsDataTypeToString[static_cast<uint32_t>(type)]
3423 strm.Indent("Data Kind: ");
3424 if (!alloc->element.type_kind.isValid())
3425 strm.Printf("unknown\n");
3427 const Element::DataKind kind = *alloc->element.type_kind.get();
3428 if (kind < Element::RS_KIND_USER || kind > Element::RS_KIND_PIXEL_YUV)
3429 strm.Printf("invalid kind\n");
3433 AllocationDetails::RsDataKindToString[static_cast<uint32_t>(kind)]);
3442 // Set breakpoints on every kernel found in RS module
3443 void RenderScriptRuntime::BreakOnModuleKernels(
3444 const RSModuleDescriptorSP rsmodule_sp) {
3445 for (const auto &kernel : rsmodule_sp->m_kernels) {
3446 // Don't set breakpoint on 'root' kernel
3447 if (strcmp(kernel.m_name.AsCString(), "root") == 0)
3450 CreateKernelBreakpoint(kernel.m_name);
3454 // Method is internally called by the 'kernel breakpoint all' command to enable
3455 // or disable breaking on all kernels. When do_break is true we want to enable
3456 // this functionality. When do_break is false we want to disable it.
3457 void RenderScriptRuntime::SetBreakAllKernels(bool do_break, TargetSP target) {
3458 Log *log = GetLog(LLDBLog::Language | LLDBLog::Breakpoints);
3460 InitSearchFilter(target);
3462 // Set breakpoints on all the kernels
3463 if (do_break && !m_breakAllKernels) {
3464 m_breakAllKernels = true;
3466 for (const auto &module : m_rsmodules)
3467 BreakOnModuleKernels(module);
3470 "%s(True) - breakpoints set on all currently loaded kernels.",
3472 } else if (!do_break &&
3473 m_breakAllKernels) // Breakpoints won't be set on any new kernels.
3475 m_breakAllKernels = false;
3477 LLDB_LOGF(log, "%s(False) - breakpoints no longer automatically set.",
3482 // Given the name of a kernel this function creates a breakpoint using our own
3483 // breakpoint resolver, and returns the Breakpoint shared pointer.
3485 RenderScriptRuntime::CreateKernelBreakpoint(ConstString name) {
3486 Log *log = GetLog(LLDBLog::Language | LLDBLog::Breakpoints);
3489 LLDB_LOGF(log, "%s - error, no breakpoint search filter set.",
3494 BreakpointResolverSP resolver_sp(new RSBreakpointResolver(nullptr, name));
3495 Target &target = GetProcess()->GetTarget();
3496 BreakpointSP bp = target.CreateBreakpoint(
3497 m_filtersp, resolver_sp, false, false, false);
3499 // Give RS breakpoints a specific name, so the user can manipulate them as a
3502 target.AddNameToBreakpoint(bp, "RenderScriptKernel", err);
3503 if (err.Fail() && log)
3504 LLDB_LOGF(log, "%s - error setting break name, '%s'.", __FUNCTION__,
3511 RenderScriptRuntime::CreateReductionBreakpoint(ConstString name,
3513 Log *log = GetLog(LLDBLog::Language | LLDBLog::Breakpoints);
3516 LLDB_LOGF(log, "%s - error, no breakpoint search filter set.",
3521 BreakpointResolverSP resolver_sp(new RSReduceBreakpointResolver(
3522 nullptr, name, &m_rsmodules, kernel_types));
3523 Target &target = GetProcess()->GetTarget();
3524 BreakpointSP bp = target.CreateBreakpoint(
3525 m_filtersp, resolver_sp, false, false, false);
3527 // Give RS breakpoints a specific name, so the user can manipulate them as a
3530 target.AddNameToBreakpoint(bp, "RenderScriptReduction", err);
3531 if (err.Fail() && log)
3532 LLDB_LOGF(log, "%s - error setting break name, '%s'.", __FUNCTION__,
3538 // Given an expression for a variable this function tries to calculate the
3539 // variable's value. If this is possible it returns true and sets the uint64_t
3540 // parameter to the variables unsigned value. Otherwise function returns false.
3541 bool RenderScriptRuntime::GetFrameVarAsUnsigned(const StackFrameSP frame_sp,
3542 const char *var_name,
3544 Log *log = GetLog(LLDBLog::Language);
3548 // Find variable in stack frame
3549 ValueObjectSP value_sp(frame_sp->GetValueForVariableExpressionPath(
3550 var_name, eNoDynamicValues,
3551 StackFrame::eExpressionPathOptionCheckPtrVsMember |
3552 StackFrame::eExpressionPathOptionsAllowDirectIVarAccess,
3554 if (!err.Success()) {
3555 LLDB_LOGF(log, "%s - error, couldn't find '%s' in frame", __FUNCTION__,
3560 // Find the uint32_t value for the variable
3561 bool success = false;
3562 val = value_sp->GetValueAsUnsigned(0, &success);
3564 LLDB_LOGF(log, "%s - error, couldn't parse '%s' as an uint32_t.",
3565 __FUNCTION__, var_name);
3572 // Function attempts to find the current coordinate of a kernel invocation by
3573 // investigating the values of frame variables in the .expand function. These
3574 // coordinates are returned via the coord array reference parameter. Returns
3575 // true if the coordinates could be found, and false otherwise.
3576 bool RenderScriptRuntime::GetKernelCoordinate(RSCoordinate &coord,
3577 Thread *thread_ptr) {
3578 static const char *const x_expr = "rsIndex";
3579 static const char *const y_expr = "p->current.y";
3580 static const char *const z_expr = "p->current.z";
3582 Log *log = GetLog(LLDBLog::Language);
3585 LLDB_LOGF(log, "%s - Error, No thread pointer", __FUNCTION__);
3590 // Walk the call stack looking for a function whose name has the suffix
3591 // '.expand' and contains the variables we're looking for.
3592 for (uint32_t i = 0; i < thread_ptr->GetStackFrameCount(); ++i) {
3593 if (!thread_ptr->SetSelectedFrameByIndex(i))
3596 StackFrameSP frame_sp = thread_ptr->GetSelectedFrame();
3600 // Find the function name
3601 const SymbolContext sym_ctx =
3602 frame_sp->GetSymbolContext(eSymbolContextFunction);
3603 const ConstString func_name = sym_ctx.GetFunctionName();
3607 LLDB_LOGF(log, "%s - Inspecting function '%s'", __FUNCTION__,
3608 func_name.GetCString());
3610 // Check if function name has .expand suffix
3611 if (!func_name.GetStringRef().endswith(".expand"))
3614 LLDB_LOGF(log, "%s - Found .expand function '%s'", __FUNCTION__,
3615 func_name.GetCString());
3617 // Get values for variables in .expand frame that tell us the current
3618 // kernel invocation
3620 bool found = GetFrameVarAsUnsigned(frame_sp, x_expr, x) &&
3621 GetFrameVarAsUnsigned(frame_sp, y_expr, y) &&
3622 GetFrameVarAsUnsigned(frame_sp, z_expr, z);
3625 // The RenderScript runtime uses uint32_t for these vars. If they're not
3626 // within bounds, our frame parsing is garbage
3627 assert(x <= UINT32_MAX && y <= UINT32_MAX && z <= UINT32_MAX);
3628 coord.x = (uint32_t)x;
3629 coord.y = (uint32_t)y;
3630 coord.z = (uint32_t)z;
3637 // Callback when a kernel breakpoint hits and we're looking for a specific
3638 // coordinate. Baton parameter contains a pointer to the target coordinate we
3639 // want to break on. Function then checks the .expand frame for the current
3640 // coordinate and breaks to user if it matches. Parameter 'break_id' is the id
3641 // of the Breakpoint which made the callback. Parameter 'break_loc_id' is the
3642 // id for the BreakpointLocation which was hit, a single logical breakpoint can
3643 // have multiple addresses.
3644 bool RenderScriptRuntime::KernelBreakpointHit(void *baton,
3645 StoppointCallbackContext *ctx,
3647 user_id_t break_loc_id) {
3648 Log *log = GetLog(LLDBLog::Language | LLDBLog::Breakpoints);
3651 "Error: null baton in conditional kernel breakpoint callback");
3653 // Coordinate we want to stop on
3654 RSCoordinate target_coord = *static_cast<RSCoordinate *>(baton);
3656 LLDB_LOGF(log, "%s - Break ID %" PRIu64 ", " FMT_COORD, __FUNCTION__,
3657 break_id, target_coord.x, target_coord.y, target_coord.z);
3659 // Select current thread
3660 ExecutionContext context(ctx->exe_ctx_ref);
3661 Thread *thread_ptr = context.GetThreadPtr();
3662 assert(thread_ptr && "Null thread pointer");
3664 // Find current kernel invocation from .expand frame variables
3665 RSCoordinate current_coord{};
3666 if (!GetKernelCoordinate(current_coord, thread_ptr)) {
3667 LLDB_LOGF(log, "%s - Error, couldn't select .expand stack frame",
3672 LLDB_LOGF(log, "%s - " FMT_COORD, __FUNCTION__, current_coord.x,
3673 current_coord.y, current_coord.z);
3675 // Check if the current kernel invocation coordinate matches our target
3677 if (target_coord == current_coord) {
3678 LLDB_LOGF(log, "%s, BREAKING " FMT_COORD, __FUNCTION__, current_coord.x,
3679 current_coord.y, current_coord.z);
3681 BreakpointSP breakpoint_sp =
3682 context.GetTargetPtr()->GetBreakpointByID(break_id);
3683 assert(breakpoint_sp != nullptr &&
3684 "Error: Couldn't find breakpoint matching break id for callback");
3685 breakpoint_sp->SetEnabled(false); // Optimise since conditional breakpoint
3686 // should only be hit once.
3690 // No match on coordinate
3694 void RenderScriptRuntime::SetConditional(BreakpointSP bp, Stream &messages,
3695 const RSCoordinate &coord) {
3696 messages.Printf("Conditional kernel breakpoint on coordinate " FMT_COORD,
3697 coord.x, coord.y, coord.z);
3700 // Allocate memory for the baton, and copy over coordinate
3701 RSCoordinate *baton = new RSCoordinate(coord);
3703 // Create a callback that will be invoked every time the breakpoint is hit.
3704 // The baton object passed to the handler is the target coordinate we want to
3706 bp->SetCallback(KernelBreakpointHit, baton, true);
3708 // Store a shared pointer to the baton, so the memory will eventually be
3709 // cleaned up after destruction
3710 m_conditional_breaks[bp->GetID()] = std::unique_ptr<RSCoordinate>(baton);
3713 // Tries to set a breakpoint on the start of a kernel, resolved using the
3714 // kernel name. Argument 'coords', represents a three dimensional coordinate
3715 // which can be used to specify a single kernel instance to break on. If this
3716 // is set then we add a callback to the breakpoint.
3717 bool RenderScriptRuntime::PlaceBreakpointOnKernel(TargetSP target,
3720 const RSCoordinate *coord) {
3724 InitSearchFilter(target);
3726 ConstString kernel_name(name);
3727 BreakpointSP bp = CreateKernelBreakpoint(kernel_name);
3731 // We have a conditional breakpoint on a specific coordinate
3733 SetConditional(bp, messages, *coord);
3735 bp->GetDescription(&messages, lldb::eDescriptionLevelInitial, false);
3741 RenderScriptRuntime::CreateScriptGroupBreakpoint(ConstString name,
3743 Log *log = GetLog(LLDBLog::Language | LLDBLog::Breakpoints);
3746 LLDB_LOGF(log, "%s - error, no breakpoint search filter set.",
3751 BreakpointResolverSP resolver_sp(new RSScriptGroupBreakpointResolver(
3752 nullptr, name, m_scriptGroups, stop_on_all));
3753 Target &target = GetProcess()->GetTarget();
3754 BreakpointSP bp = target.CreateBreakpoint(
3755 m_filtersp, resolver_sp, false, false, false);
3756 // Give RS breakpoints a specific name, so the user can manipulate them as a
3759 target.AddNameToBreakpoint(bp, name.GetCString(), err);
3760 if (err.Fail() && log)
3761 LLDB_LOGF(log, "%s - error setting break name, '%s'.", __FUNCTION__,
3763 // ask the breakpoint to resolve itself
3764 bp->ResolveBreakpoint();
3768 bool RenderScriptRuntime::PlaceBreakpointOnScriptGroup(TargetSP target,
3772 InitSearchFilter(target);
3773 BreakpointSP bp = CreateScriptGroupBreakpoint(name, multi);
3775 bp->GetDescription(&strm, lldb::eDescriptionLevelInitial, false);
3779 bool RenderScriptRuntime::PlaceBreakpointOnReduction(TargetSP target,
3781 const char *reduce_name,
3782 const RSCoordinate *coord,
3787 InitSearchFilter(target);
3789 CreateReductionBreakpoint(ConstString(reduce_name), kernel_types);
3794 SetConditional(bp, messages, *coord);
3796 bp->GetDescription(&messages, lldb::eDescriptionLevelInitial, false);
3801 void RenderScriptRuntime::DumpModules(Stream &strm) const {
3802 strm.Printf("RenderScript Modules:");
3805 for (const auto &module : m_rsmodules) {
3811 RenderScriptRuntime::ScriptDetails *
3812 RenderScriptRuntime::LookUpScript(addr_t address, bool create) {
3813 for (const auto &s : m_scripts) {
3814 if (s->script.isValid())
3815 if (*s->script == address)
3819 std::unique_ptr<ScriptDetails> s(new ScriptDetails);
3820 s->script = address;
3821 m_scripts.push_back(std::move(s));
3822 return m_scripts.back().get();
3827 RenderScriptRuntime::AllocationDetails *
3828 RenderScriptRuntime::LookUpAllocation(addr_t address) {
3829 for (const auto &a : m_allocations) {
3830 if (a->address.isValid())
3831 if (*a->address == address)
3837 RenderScriptRuntime::AllocationDetails *
3838 RenderScriptRuntime::CreateAllocation(addr_t address) {
3839 Log *log = GetLog(LLDBLog::Language);
3841 // Remove any previous allocation which contains the same address
3842 auto it = m_allocations.begin();
3843 while (it != m_allocations.end()) {
3844 if (*((*it)->address) == address) {
3845 LLDB_LOGF(log, "%s - Removing allocation id: %d, address: 0x%" PRIx64,
3846 __FUNCTION__, (*it)->id, address);
3848 it = m_allocations.erase(it);
3854 std::unique_ptr<AllocationDetails> a(new AllocationDetails);
3855 a->address = address;
3856 m_allocations.push_back(std::move(a));
3857 return m_allocations.back().get();
3860 bool RenderScriptRuntime::ResolveKernelName(lldb::addr_t kernel_addr,
3861 ConstString &name) {
3862 Log *log = GetLog(LLDBLog::Symbols);
3864 Target &target = GetProcess()->GetTarget();
3866 // RenderScript module
3867 if (!target.GetSectionLoadList().ResolveLoadAddress(kernel_addr, resolved)) {
3868 LLDB_LOGF(log, "%s: unable to resolve 0x%" PRIx64 " to a loaded symbol",
3869 __FUNCTION__, kernel_addr);
3873 Symbol *sym = resolved.CalculateSymbolContextSymbol();
3877 name = sym->GetName();
3878 assert(IsRenderScriptModule(resolved.CalculateSymbolContextModule()));
3879 LLDB_LOGF(log, "%s: 0x%" PRIx64 " resolved to the symbol '%s'", __FUNCTION__,
3880 kernel_addr, name.GetCString());
3884 void RSModuleDescriptor::Dump(Stream &strm) const {
3885 int indent = strm.GetIndentLevel();
3888 m_module->GetFileSpec().Dump(strm.AsRawOstream());
3889 strm.Indent(m_module->GetNumCompileUnits() ? "Debug info loaded."
3890 : "Debug info does not exist.");
3895 strm.Printf("Globals: %" PRIu64, static_cast<uint64_t>(m_globals.size()));
3898 for (const auto &global : m_globals) {
3904 strm.Printf("Kernels: %" PRIu64, static_cast<uint64_t>(m_kernels.size()));
3907 for (const auto &kernel : m_kernels) {
3913 strm.Printf("Pragmas: %" PRIu64, static_cast<uint64_t>(m_pragmas.size()));
3916 for (const auto &key_val : m_pragmas) {
3918 strm.Printf("%s: %s", key_val.first.c_str(), key_val.second.c_str());
3924 strm.Printf("Reductions: %" PRIu64,
3925 static_cast<uint64_t>(m_reductions.size()));
3928 for (const auto &reduction : m_reductions) {
3929 reduction.Dump(strm);
3932 strm.SetIndentLevel(indent);
3935 void RSGlobalDescriptor::Dump(Stream &strm) const {
3936 strm.Indent(m_name.GetStringRef());
3937 VariableList var_list;
3938 m_module->m_module->FindGlobalVariables(m_name, CompilerDeclContext(), 1U,
3940 if (var_list.GetSize() == 1) {
3941 auto var = var_list.GetVariableAtIndex(0);
3942 auto type = var->GetType();
3945 type->DumpTypeName(&strm);
3947 strm.Printf(" - Unknown Type");
3950 strm.Printf(" - variable identified, but not found in binary");
3951 const Symbol *s = m_module->m_module->FindFirstSymbolWithNameAndType(
3952 m_name, eSymbolTypeData);
3954 strm.Printf(" (symbol exists) ");
3961 void RSKernelDescriptor::Dump(Stream &strm) const {
3962 strm.Indent(m_name.GetStringRef());
3966 void RSReductionDescriptor::Dump(lldb_private::Stream &stream) const {
3967 stream.Indent(m_reduce_name.GetStringRef());
3968 stream.IndentMore();
3971 stream.Printf("accumulator: %s", m_accum_name.AsCString());
3974 stream.Printf("initializer: %s", m_init_name.AsCString());
3977 stream.Printf("combiner: %s", m_comb_name.AsCString());
3980 stream.Printf("outconverter: %s", m_outc_name.AsCString());
3982 // XXX This is currently unspecified by RenderScript, and unused
3984 // stream.Printf("halter: '%s'", m_init_name.AsCString());
3986 stream.IndentLess();
3989 class CommandObjectRenderScriptRuntimeModuleDump : public CommandObjectParsed {
3991 CommandObjectRenderScriptRuntimeModuleDump(CommandInterpreter &interpreter)
3992 : CommandObjectParsed(
3993 interpreter, "renderscript module dump",
3994 "Dumps renderscript specific information for all modules.",
3995 "renderscript module dump",
3996 eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
3998 ~CommandObjectRenderScriptRuntimeModuleDump() override = default;
4000 bool DoExecute(Args &command, CommandReturnObject &result) override {
4001 RenderScriptRuntime *runtime = llvm::cast<RenderScriptRuntime>(
4002 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4003 eLanguageTypeExtRenderScript));
4004 runtime->DumpModules(result.GetOutputStream());
4005 result.SetStatus(eReturnStatusSuccessFinishResult);
4010 class CommandObjectRenderScriptRuntimeModule : public CommandObjectMultiword {
4012 CommandObjectRenderScriptRuntimeModule(CommandInterpreter &interpreter)
4013 : CommandObjectMultiword(interpreter, "renderscript module",
4014 "Commands that deal with RenderScript modules.",
4017 "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleDump(
4021 ~CommandObjectRenderScriptRuntimeModule() override = default;
4024 class CommandObjectRenderScriptRuntimeKernelList : public CommandObjectParsed {
4026 CommandObjectRenderScriptRuntimeKernelList(CommandInterpreter &interpreter)
4027 : CommandObjectParsed(
4028 interpreter, "renderscript kernel list",
4029 "Lists renderscript kernel names and associated script resources.",
4030 "renderscript kernel list",
4031 eCommandRequiresProcess | eCommandProcessMustBeLaunched) {}
4033 ~CommandObjectRenderScriptRuntimeKernelList() override = default;
4035 bool DoExecute(Args &command, CommandReturnObject &result) override {
4036 RenderScriptRuntime *runtime = llvm::cast<RenderScriptRuntime>(
4037 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4038 eLanguageTypeExtRenderScript));
4039 runtime->DumpKernels(result.GetOutputStream());
4040 result.SetStatus(eReturnStatusSuccessFinishResult);
4045 static constexpr OptionDefinition g_renderscript_reduction_bp_set_options[] = {
4046 {LLDB_OPT_SET_1, false, "function-role", 't',
4047 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeOneLiner,
4048 "Break on a comma separated set of reduction kernel types "
4049 "(accumulator,outcoverter,combiner,initializer"},
4050 {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument,
4051 nullptr, {}, 0, eArgTypeValue,
4052 "Set a breakpoint on a single invocation of the kernel with specified "
4054 "Coordinate takes the form 'x[,y][,z] where x,y,z are positive "
4055 "integers representing kernel dimensions. "
4056 "Any unset dimensions will be defaulted to zero."}};
4058 class CommandObjectRenderScriptRuntimeReductionBreakpointSet
4059 : public CommandObjectParsed {
4061 CommandObjectRenderScriptRuntimeReductionBreakpointSet(
4062 CommandInterpreter &interpreter)
4063 : CommandObjectParsed(
4064 interpreter, "renderscript reduction breakpoint set",
4065 "Set a breakpoint on named RenderScript general reductions",
4066 "renderscript reduction breakpoint set <kernel_name> [-t "
4067 "<reduction_kernel_type,...>]",
4068 eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4069 eCommandProcessMustBePaused),
4071 CommandArgumentData name_arg{eArgTypeName, eArgRepeatPlain};
4072 m_arguments.push_back({name_arg});
4075 class CommandOptions : public Options {
4077 CommandOptions() : Options() {}
4079 ~CommandOptions() override = default;
4081 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4082 ExecutionContext *exe_ctx) override {
4084 StreamString err_str;
4085 const int short_option = m_getopt_table[option_idx].val;
4086 switch (short_option) {
4088 if (!ParseReductionTypes(option_arg, err_str))
4089 err.SetErrorStringWithFormat(
4090 "Unable to deduce reduction types for %s: %s",
4091 option_arg.str().c_str(), err_str.GetData());
4094 auto coord = RSCoordinate{};
4095 if (!ParseCoordinate(option_arg, coord))
4096 err.SetErrorStringWithFormat("unable to parse coordinate for %s",
4097 option_arg.str().c_str());
4099 m_have_coord = true;
4105 err.SetErrorStringWithFormat("Invalid option '-%c'", short_option);
4110 void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4111 m_have_coord = false;
4114 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4115 return llvm::makeArrayRef(g_renderscript_reduction_bp_set_options);
4118 bool ParseReductionTypes(llvm::StringRef option_val,
4119 StreamString &err_str) {
4120 m_kernel_types = RSReduceBreakpointResolver::eKernelTypeNone;
4121 const auto reduce_name_to_type = [](llvm::StringRef name) -> int {
4122 return llvm::StringSwitch<int>(name)
4123 .Case("accumulator", RSReduceBreakpointResolver::eKernelTypeAccum)
4124 .Case("initializer", RSReduceBreakpointResolver::eKernelTypeInit)
4125 .Case("outconverter", RSReduceBreakpointResolver::eKernelTypeOutC)
4126 .Case("combiner", RSReduceBreakpointResolver::eKernelTypeComb)
4127 .Case("all", RSReduceBreakpointResolver::eKernelTypeAll)
4128 // Currently not exposed by the runtime
4129 // .Case("halter", RSReduceBreakpointResolver::eKernelTypeHalter)
4133 // Matching a comma separated list of known words is fairly
4134 // straightforward with PCRE, but we're using ERE, so we end up with a
4135 // little ugliness...
4136 RegularExpression match_type_list(
4137 llvm::StringRef("^([[:alpha:]]+)(,[[:alpha:]]+){0,4}$"));
4139 assert(match_type_list.IsValid());
4141 if (!match_type_list.Execute(option_val)) {
4143 "a comma-separated list of kernel types is required");
4147 // splitting on commas is much easier with llvm::StringRef than regex
4148 llvm::SmallVector<llvm::StringRef, 5> type_names;
4149 llvm::StringRef(option_val).split(type_names, ',');
4151 for (const auto &name : type_names) {
4152 const int type = reduce_name_to_type(name);
4154 err_str.Printf("unknown kernel type name %s", name.str().c_str());
4157 m_kernel_types |= type;
4163 int m_kernel_types = RSReduceBreakpointResolver::eKernelTypeAll;
4164 llvm::StringRef m_reduce_name;
4165 RSCoordinate m_coord;
4166 bool m_have_coord = false;
4169 Options *GetOptions() override { return &m_options; }
4171 bool DoExecute(Args &command, CommandReturnObject &result) override {
4172 const size_t argc = command.GetArgumentCount();
4174 result.AppendErrorWithFormat("'%s' takes 1 argument of reduction name, "
4175 "and an optional kernel type list",
4176 m_cmd_name.c_str());
4180 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4181 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4182 eLanguageTypeExtRenderScript));
4184 auto &outstream = result.GetOutputStream();
4185 auto name = command.GetArgumentAtIndex(0);
4186 auto &target = m_exe_ctx.GetTargetSP();
4187 auto coord = m_options.m_have_coord ? &m_options.m_coord : nullptr;
4188 if (!runtime->PlaceBreakpointOnReduction(target, outstream, name, coord,
4189 m_options.m_kernel_types)) {
4190 result.AppendError("Error: unable to place breakpoint on reduction");
4193 result.AppendMessage("Breakpoint(s) created");
4194 result.SetStatus(eReturnStatusSuccessFinishResult);
4199 CommandOptions m_options;
4202 static constexpr OptionDefinition g_renderscript_kernel_bp_set_options[] = {
4203 {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument,
4204 nullptr, {}, 0, eArgTypeValue,
4205 "Set a breakpoint on a single invocation of the kernel with specified "
4207 "Coordinate takes the form 'x[,y][,z] where x,y,z are positive "
4208 "integers representing kernel dimensions. "
4209 "Any unset dimensions will be defaulted to zero."}};
4211 class CommandObjectRenderScriptRuntimeKernelBreakpointSet
4212 : public CommandObjectParsed {
4214 CommandObjectRenderScriptRuntimeKernelBreakpointSet(
4215 CommandInterpreter &interpreter)
4216 : CommandObjectParsed(
4217 interpreter, "renderscript kernel breakpoint set",
4218 "Sets a breakpoint on a renderscript kernel.",
4219 "renderscript kernel breakpoint set <kernel_name> [-c x,y,z]",
4220 eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4221 eCommandProcessMustBePaused),
4223 CommandArgumentData name_arg{eArgTypeName, eArgRepeatPlain};
4224 m_arguments.push_back({name_arg});
4227 ~CommandObjectRenderScriptRuntimeKernelBreakpointSet() override = default;
4229 Options *GetOptions() override { return &m_options; }
4231 class CommandOptions : public Options {
4233 CommandOptions() : Options() {}
4235 ~CommandOptions() override = default;
4237 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4238 ExecutionContext *exe_ctx) override {
4240 const int short_option = m_getopt_table[option_idx].val;
4242 switch (short_option) {
4244 auto coord = RSCoordinate{};
4245 if (!ParseCoordinate(option_arg, coord))
4246 err.SetErrorStringWithFormat(
4247 "Couldn't parse coordinate '%s', should be in format 'x,y,z'.",
4248 option_arg.str().c_str());
4250 m_have_coord = true;
4256 err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4262 void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4263 m_have_coord = false;
4266 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4267 return llvm::makeArrayRef(g_renderscript_kernel_bp_set_options);
4270 RSCoordinate m_coord;
4271 bool m_have_coord = false;
4274 bool DoExecute(Args &command, CommandReturnObject &result) override {
4275 const size_t argc = command.GetArgumentCount();
4277 result.AppendErrorWithFormat(
4278 "'%s' takes 1 argument of kernel name, and an optional coordinate.",
4279 m_cmd_name.c_str());
4283 RenderScriptRuntime *runtime = llvm::cast<RenderScriptRuntime>(
4284 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4285 eLanguageTypeExtRenderScript));
4287 auto &outstream = result.GetOutputStream();
4288 auto &target = m_exe_ctx.GetTargetSP();
4289 auto name = command.GetArgumentAtIndex(0);
4290 auto coord = m_options.m_have_coord ? &m_options.m_coord : nullptr;
4291 if (!runtime->PlaceBreakpointOnKernel(target, outstream, name, coord)) {
4292 result.AppendErrorWithFormat(
4293 "Error: unable to set breakpoint on kernel '%s'", name);
4297 result.AppendMessage("Breakpoint(s) created");
4298 result.SetStatus(eReturnStatusSuccessFinishResult);
4303 CommandOptions m_options;
4306 class CommandObjectRenderScriptRuntimeKernelBreakpointAll
4307 : public CommandObjectParsed {
4309 CommandObjectRenderScriptRuntimeKernelBreakpointAll(
4310 CommandInterpreter &interpreter)
4311 : CommandObjectParsed(
4312 interpreter, "renderscript kernel breakpoint all",
4313 "Automatically sets a breakpoint on all renderscript kernels that "
4314 "are or will be loaded.\n"
4315 "Disabling option means breakpoints will no longer be set on any "
4316 "kernels loaded in the future, "
4317 "but does not remove currently set breakpoints.",
4318 "renderscript kernel breakpoint all <enable/disable>",
4319 eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4320 eCommandProcessMustBePaused) {
4321 CommandArgumentData enable_arg{eArgTypeNone, eArgRepeatPlain};
4322 m_arguments.push_back({enable_arg});
4325 ~CommandObjectRenderScriptRuntimeKernelBreakpointAll() override = default;
4327 bool DoExecute(Args &command, CommandReturnObject &result) override {
4328 const size_t argc = command.GetArgumentCount();
4330 result.AppendErrorWithFormat(
4331 "'%s' takes 1 argument of 'enable' or 'disable'", m_cmd_name.c_str());
4335 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4336 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4337 eLanguageTypeExtRenderScript));
4339 bool do_break = false;
4340 const char *argument = command.GetArgumentAtIndex(0);
4341 if (strcmp(argument, "enable") == 0) {
4343 result.AppendMessage("Breakpoints will be set on all kernels.");
4344 } else if (strcmp(argument, "disable") == 0) {
4346 result.AppendMessage("Breakpoints will not be set on any new kernels.");
4348 result.AppendErrorWithFormat(
4349 "Argument must be either 'enable' or 'disable'");
4353 runtime->SetBreakAllKernels(do_break, m_exe_ctx.GetTargetSP());
4355 result.SetStatus(eReturnStatusSuccessFinishResult);
4360 class CommandObjectRenderScriptRuntimeReductionBreakpoint
4361 : public CommandObjectMultiword {
4363 CommandObjectRenderScriptRuntimeReductionBreakpoint(
4364 CommandInterpreter &interpreter)
4365 : CommandObjectMultiword(interpreter, "renderscript reduction breakpoint",
4366 "Commands that manipulate breakpoints on "
4367 "renderscript general reductions.",
4370 "set", CommandObjectSP(
4371 new CommandObjectRenderScriptRuntimeReductionBreakpointSet(
4375 ~CommandObjectRenderScriptRuntimeReductionBreakpoint() override = default;
4378 class CommandObjectRenderScriptRuntimeKernelCoordinate
4379 : public CommandObjectParsed {
4381 CommandObjectRenderScriptRuntimeKernelCoordinate(
4382 CommandInterpreter &interpreter)
4383 : CommandObjectParsed(
4384 interpreter, "renderscript kernel coordinate",
4385 "Shows the (x,y,z) coordinate of the current kernel invocation.",
4386 "renderscript kernel coordinate",
4387 eCommandRequiresProcess | eCommandProcessMustBeLaunched |
4388 eCommandProcessMustBePaused) {}
4390 ~CommandObjectRenderScriptRuntimeKernelCoordinate() override = default;
4392 bool DoExecute(Args &command, CommandReturnObject &result) override {
4393 RSCoordinate coord{};
4394 bool success = RenderScriptRuntime::GetKernelCoordinate(
4395 coord, m_exe_ctx.GetThreadPtr());
4396 Stream &stream = result.GetOutputStream();
4399 stream.Printf("Coordinate: " FMT_COORD, coord.x, coord.y, coord.z);
4401 result.SetStatus(eReturnStatusSuccessFinishResult);
4403 stream.Printf("Error: Coordinate could not be found.");
4405 result.SetStatus(eReturnStatusFailed);
4411 class CommandObjectRenderScriptRuntimeKernelBreakpoint
4412 : public CommandObjectMultiword {
4414 CommandObjectRenderScriptRuntimeKernelBreakpoint(
4415 CommandInterpreter &interpreter)
4416 : CommandObjectMultiword(
4417 interpreter, "renderscript kernel",
4418 "Commands that generate breakpoints on renderscript kernels.",
4422 CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointSet(
4426 CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointAll(
4430 ~CommandObjectRenderScriptRuntimeKernelBreakpoint() override = default;
4433 class CommandObjectRenderScriptRuntimeKernel : public CommandObjectMultiword {
4435 CommandObjectRenderScriptRuntimeKernel(CommandInterpreter &interpreter)
4436 : CommandObjectMultiword(interpreter, "renderscript kernel",
4437 "Commands that deal with RenderScript kernels.",
4440 "list", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelList(
4445 new CommandObjectRenderScriptRuntimeKernelCoordinate(interpreter)));
4449 new CommandObjectRenderScriptRuntimeKernelBreakpoint(interpreter)));
4452 ~CommandObjectRenderScriptRuntimeKernel() override = default;
4455 class CommandObjectRenderScriptRuntimeContextDump : public CommandObjectParsed {
4457 CommandObjectRenderScriptRuntimeContextDump(CommandInterpreter &interpreter)
4458 : CommandObjectParsed(interpreter, "renderscript context dump",
4459 "Dumps renderscript context information.",
4460 "renderscript context dump",
4461 eCommandRequiresProcess |
4462 eCommandProcessMustBeLaunched) {}
4464 ~CommandObjectRenderScriptRuntimeContextDump() override = default;
4466 bool DoExecute(Args &command, CommandReturnObject &result) override {
4467 RenderScriptRuntime *runtime = llvm::cast<RenderScriptRuntime>(
4468 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4469 eLanguageTypeExtRenderScript));
4470 runtime->DumpContexts(result.GetOutputStream());
4471 result.SetStatus(eReturnStatusSuccessFinishResult);
4476 static constexpr OptionDefinition g_renderscript_runtime_alloc_dump_options[] = {
4477 {LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument,
4478 nullptr, {}, 0, eArgTypeFilename,
4479 "Print results to specified file instead of command line."}};
4481 class CommandObjectRenderScriptRuntimeContext : public CommandObjectMultiword {
4483 CommandObjectRenderScriptRuntimeContext(CommandInterpreter &interpreter)
4484 : CommandObjectMultiword(interpreter, "renderscript context",
4485 "Commands that deal with RenderScript contexts.",
4488 "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeContextDump(
4492 ~CommandObjectRenderScriptRuntimeContext() override = default;
4495 class CommandObjectRenderScriptRuntimeAllocationDump
4496 : public CommandObjectParsed {
4498 CommandObjectRenderScriptRuntimeAllocationDump(
4499 CommandInterpreter &interpreter)
4500 : CommandObjectParsed(interpreter, "renderscript allocation dump",
4501 "Displays the contents of a particular allocation",
4502 "renderscript allocation dump <ID>",
4503 eCommandRequiresProcess |
4504 eCommandProcessMustBeLaunched),
4506 CommandArgumentData id_arg{eArgTypeUnsignedInteger, eArgRepeatPlain};
4507 m_arguments.push_back({id_arg});
4510 ~CommandObjectRenderScriptRuntimeAllocationDump() override = default;
4512 Options *GetOptions() override { return &m_options; }
4514 class CommandOptions : public Options {
4516 CommandOptions() : Options() {}
4518 ~CommandOptions() override = default;
4520 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4521 ExecutionContext *exe_ctx) override {
4523 const int short_option = m_getopt_table[option_idx].val;
4525 switch (short_option) {
4527 m_outfile.SetFile(option_arg, FileSpec::Style::native);
4528 FileSystem::Instance().Resolve(m_outfile);
4529 if (FileSystem::Instance().Exists(m_outfile)) {
4531 err.SetErrorStringWithFormat("file already exists: '%s'",
4532 option_arg.str().c_str());
4536 err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4542 void OptionParsingStarting(ExecutionContext *exe_ctx) override {
4546 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4547 return llvm::makeArrayRef(g_renderscript_runtime_alloc_dump_options);
4553 bool DoExecute(Args &command, CommandReturnObject &result) override {
4554 const size_t argc = command.GetArgumentCount();
4556 result.AppendErrorWithFormat("'%s' takes 1 argument, an allocation ID. "
4557 "As well as an optional -f argument",
4558 m_cmd_name.c_str());
4562 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4563 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4564 eLanguageTypeExtRenderScript));
4566 const char *id_cstr = command.GetArgumentAtIndex(0);
4568 if (!llvm::to_integer(id_cstr, id)) {
4569 result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4574 Stream *output_stream_p = nullptr;
4575 std::unique_ptr<Stream> output_stream_storage;
4577 const FileSpec &outfile_spec =
4578 m_options.m_outfile; // Dump allocation to file instead
4581 std::string path = outfile_spec.GetPath();
4582 auto file = FileSystem::Instance().Open(outfile_spec,
4583 File::eOpenOptionWriteOnly |
4584 File::eOpenOptionCanCreate);
4586 output_stream_storage =
4587 std::make_unique<StreamFile>(std::move(file.get()));
4588 output_stream_p = output_stream_storage.get();
4589 result.GetOutputStream().Printf("Results written to '%s'",
4591 result.GetOutputStream().EOL();
4593 std::string error = llvm::toString(file.takeError());
4594 result.AppendErrorWithFormat("Couldn't open file '%s': %s",
4595 path.c_str(), error.c_str());
4599 output_stream_p = &result.GetOutputStream();
4601 assert(output_stream_p != nullptr);
4603 runtime->DumpAllocation(*output_stream_p, m_exe_ctx.GetFramePtr(), id);
4606 result.SetStatus(eReturnStatusSuccessFinishResult);
4608 result.SetStatus(eReturnStatusFailed);
4614 CommandOptions m_options;
4617 static constexpr OptionDefinition g_renderscript_runtime_alloc_list_options[] = {
4618 {LLDB_OPT_SET_1, false, "id", 'i', OptionParser::eRequiredArgument, nullptr,
4619 {}, 0, eArgTypeIndex,
4620 "Only show details of a single allocation with specified id."}};
4622 class CommandObjectRenderScriptRuntimeAllocationList
4623 : public CommandObjectParsed {
4625 CommandObjectRenderScriptRuntimeAllocationList(
4626 CommandInterpreter &interpreter)
4627 : CommandObjectParsed(
4628 interpreter, "renderscript allocation list",
4629 "List renderscript allocations and their information.",
4630 "renderscript allocation list",
4631 eCommandRequiresProcess | eCommandProcessMustBeLaunched),
4634 ~CommandObjectRenderScriptRuntimeAllocationList() override = default;
4636 Options *GetOptions() override { return &m_options; }
4638 class CommandOptions : public Options {
4640 CommandOptions() : Options() {}
4642 ~CommandOptions() override = default;
4644 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
4645 ExecutionContext *exe_ctx) override {
4647 const int short_option = m_getopt_table[option_idx].val;
4649 switch (short_option) {
4651 if (option_arg.getAsInteger(0, m_id))
4652 err.SetErrorStringWithFormat("invalid integer value for option '%c'",
4656 err.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
4662 void OptionParsingStarting(ExecutionContext *exe_ctx) override { m_id = 0; }
4664 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
4665 return llvm::makeArrayRef(g_renderscript_runtime_alloc_list_options);
4671 bool DoExecute(Args &command, CommandReturnObject &result) override {
4672 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4673 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4674 eLanguageTypeExtRenderScript));
4675 runtime->ListAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr(),
4677 result.SetStatus(eReturnStatusSuccessFinishResult);
4682 CommandOptions m_options;
4685 class CommandObjectRenderScriptRuntimeAllocationLoad
4686 : public CommandObjectParsed {
4688 CommandObjectRenderScriptRuntimeAllocationLoad(
4689 CommandInterpreter &interpreter)
4690 : CommandObjectParsed(
4691 interpreter, "renderscript allocation load",
4692 "Loads renderscript allocation contents from a file.",
4693 "renderscript allocation load <ID> <filename>",
4694 eCommandRequiresProcess | eCommandProcessMustBeLaunched) {
4695 CommandArgumentData id_arg{eArgTypeUnsignedInteger, eArgRepeatPlain};
4696 CommandArgumentData name_arg{eArgTypeFilename, eArgRepeatPlain};
4697 m_arguments.push_back({id_arg});
4698 m_arguments.push_back({name_arg});
4701 ~CommandObjectRenderScriptRuntimeAllocationLoad() override = default;
4703 bool DoExecute(Args &command, CommandReturnObject &result) override {
4704 const size_t argc = command.GetArgumentCount();
4706 result.AppendErrorWithFormat(
4707 "'%s' takes 2 arguments, an allocation ID and filename to read from.",
4708 m_cmd_name.c_str());
4712 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4713 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4714 eLanguageTypeExtRenderScript));
4716 const char *id_cstr = command.GetArgumentAtIndex(0);
4718 if (!llvm::to_integer(id_cstr, id)) {
4719 result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4724 const char *path = command.GetArgumentAtIndex(1);
4725 bool loaded = runtime->LoadAllocation(result.GetOutputStream(), id, path,
4726 m_exe_ctx.GetFramePtr());
4729 result.SetStatus(eReturnStatusSuccessFinishResult);
4731 result.SetStatus(eReturnStatusFailed);
4737 class CommandObjectRenderScriptRuntimeAllocationSave
4738 : public CommandObjectParsed {
4740 CommandObjectRenderScriptRuntimeAllocationSave(
4741 CommandInterpreter &interpreter)
4742 : CommandObjectParsed(interpreter, "renderscript allocation save",
4743 "Write renderscript allocation contents to a file.",
4744 "renderscript allocation save <ID> <filename>",
4745 eCommandRequiresProcess |
4746 eCommandProcessMustBeLaunched) {
4747 CommandArgumentData id_arg{eArgTypeUnsignedInteger, eArgRepeatPlain};
4748 CommandArgumentData name_arg{eArgTypeFilename, eArgRepeatPlain};
4749 m_arguments.push_back({id_arg});
4750 m_arguments.push_back({name_arg});
4753 ~CommandObjectRenderScriptRuntimeAllocationSave() override = default;
4755 bool DoExecute(Args &command, CommandReturnObject &result) override {
4756 const size_t argc = command.GetArgumentCount();
4758 result.AppendErrorWithFormat(
4759 "'%s' takes 2 arguments, an allocation ID and filename to read from.",
4760 m_cmd_name.c_str());
4764 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4765 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4766 eLanguageTypeExtRenderScript));
4768 const char *id_cstr = command.GetArgumentAtIndex(0);
4770 if (!llvm::to_integer(id_cstr, id)) {
4771 result.AppendErrorWithFormat("invalid allocation id argument '%s'",
4776 const char *path = command.GetArgumentAtIndex(1);
4777 bool saved = runtime->SaveAllocation(result.GetOutputStream(), id, path,
4778 m_exe_ctx.GetFramePtr());
4781 result.SetStatus(eReturnStatusSuccessFinishResult);
4783 result.SetStatus(eReturnStatusFailed);
4789 class CommandObjectRenderScriptRuntimeAllocationRefresh
4790 : public CommandObjectParsed {
4792 CommandObjectRenderScriptRuntimeAllocationRefresh(
4793 CommandInterpreter &interpreter)
4794 : CommandObjectParsed(interpreter, "renderscript allocation refresh",
4795 "Recomputes the details of all allocations.",
4796 "renderscript allocation refresh",
4797 eCommandRequiresProcess |
4798 eCommandProcessMustBeLaunched) {}
4800 ~CommandObjectRenderScriptRuntimeAllocationRefresh() override = default;
4802 bool DoExecute(Args &command, CommandReturnObject &result) override {
4803 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>(
4804 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4805 eLanguageTypeExtRenderScript));
4807 bool success = runtime->RecomputeAllAllocations(result.GetOutputStream(),
4808 m_exe_ctx.GetFramePtr());
4811 result.SetStatus(eReturnStatusSuccessFinishResult);
4814 result.SetStatus(eReturnStatusFailed);
4820 class CommandObjectRenderScriptRuntimeAllocation
4821 : public CommandObjectMultiword {
4823 CommandObjectRenderScriptRuntimeAllocation(CommandInterpreter &interpreter)
4824 : CommandObjectMultiword(
4825 interpreter, "renderscript allocation",
4826 "Commands that deal with RenderScript allocations.", nullptr) {
4830 new CommandObjectRenderScriptRuntimeAllocationList(interpreter)));
4834 new CommandObjectRenderScriptRuntimeAllocationDump(interpreter)));
4838 new CommandObjectRenderScriptRuntimeAllocationSave(interpreter)));
4842 new CommandObjectRenderScriptRuntimeAllocationLoad(interpreter)));
4845 CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationRefresh(
4849 ~CommandObjectRenderScriptRuntimeAllocation() override = default;
4852 class CommandObjectRenderScriptRuntimeStatus : public CommandObjectParsed {
4854 CommandObjectRenderScriptRuntimeStatus(CommandInterpreter &interpreter)
4855 : CommandObjectParsed(interpreter, "renderscript status",
4856 "Displays current RenderScript runtime status.",
4857 "renderscript status",
4858 eCommandRequiresProcess |
4859 eCommandProcessMustBeLaunched) {}
4861 ~CommandObjectRenderScriptRuntimeStatus() override = default;
4863 bool DoExecute(Args &command, CommandReturnObject &result) override {
4864 RenderScriptRuntime *runtime = llvm::cast<RenderScriptRuntime>(
4865 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(
4866 eLanguageTypeExtRenderScript));
4867 runtime->DumpStatus(result.GetOutputStream());
4868 result.SetStatus(eReturnStatusSuccessFinishResult);
4873 class CommandObjectRenderScriptRuntimeReduction
4874 : public CommandObjectMultiword {
4876 CommandObjectRenderScriptRuntimeReduction(CommandInterpreter &interpreter)
4877 : CommandObjectMultiword(interpreter, "renderscript reduction",
4878 "Commands that handle general reduction kernels",
4882 CommandObjectSP(new CommandObjectRenderScriptRuntimeReductionBreakpoint(
4885 ~CommandObjectRenderScriptRuntimeReduction() override = default;
4888 class CommandObjectRenderScriptRuntime : public CommandObjectMultiword {
4890 CommandObjectRenderScriptRuntime(CommandInterpreter &interpreter)
4891 : CommandObjectMultiword(
4892 interpreter, "renderscript",
4893 "Commands for operating on the RenderScript runtime.",
4894 "renderscript <subcommand> [<subcommand-options>]") {
4896 "module", CommandObjectSP(
4897 new CommandObjectRenderScriptRuntimeModule(interpreter)));
4899 "status", CommandObjectSP(
4900 new CommandObjectRenderScriptRuntimeStatus(interpreter)));
4902 "kernel", CommandObjectSP(
4903 new CommandObjectRenderScriptRuntimeKernel(interpreter)));
4904 LoadSubCommand("context",
4905 CommandObjectSP(new CommandObjectRenderScriptRuntimeContext(
4910 new CommandObjectRenderScriptRuntimeAllocation(interpreter)));
4911 LoadSubCommand("scriptgroup",
4912 NewCommandObjectRenderScriptScriptGroup(interpreter));
4916 new CommandObjectRenderScriptRuntimeReduction(interpreter)));
4919 ~CommandObjectRenderScriptRuntime() override = default;
4922 void RenderScriptRuntime::Initiate() { assert(!m_initiated); }
4924 RenderScriptRuntime::RenderScriptRuntime(Process *process)
4925 : lldb_private::CPPLanguageRuntime(process), m_initiated(false),
4926 m_debuggerPresentFlagged(false), m_breakAllKernels(false),
4927 m_ir_passes(nullptr) {
4928 ModulesDidLoad(process->GetTarget().GetImages());
4931 lldb::CommandObjectSP RenderScriptRuntime::GetCommandObject(
4932 lldb_private::CommandInterpreter &interpreter) {
4933 return CommandObjectSP(new CommandObjectRenderScriptRuntime(interpreter));
4936 RenderScriptRuntime::~RenderScriptRuntime() = default;