1 //===-- RenderScriptRuntime.cpp ---------------------------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 // C Includes 11 // C++ Includes 12 // Other libraries and framework includes 13 #include "llvm/ADT/StringMap.h" 14 15 // Project includes 16 #include "RenderScriptRuntime.h" 17 18 #include "lldb/Breakpoint/StoppointCallbackContext.h" 19 #include "lldb/Core/ConstString.h" 20 #include "lldb/Core/Debugger.h" 21 #include "lldb/Core/Error.h" 22 #include "lldb/Core/Log.h" 23 #include "lldb/Core/PluginManager.h" 24 #include "lldb/Core/RegularExpression.h" 25 #include "lldb/Core/ValueObjectVariable.h" 26 #include "lldb/DataFormatters/DumpValueObjectOptions.h" 27 #include "lldb/Expression/UserExpression.h" 28 #include "lldb/Host/StringConvert.h" 29 #include "lldb/Interpreter/Args.h" 30 #include "lldb/Interpreter/CommandInterpreter.h" 31 #include "lldb/Interpreter/CommandObjectMultiword.h" 32 #include "lldb/Interpreter/CommandReturnObject.h" 33 #include "lldb/Interpreter/Options.h" 34 #include "lldb/Symbol/Symbol.h" 35 #include "lldb/Symbol/Type.h" 36 #include "lldb/Symbol/VariableList.h" 37 #include "lldb/Target/Process.h" 38 #include "lldb/Target/RegisterContext.h" 39 #include "lldb/Target/Target.h" 40 #include "lldb/Target/Thread.h" 41 42 using namespace lldb; 43 using namespace lldb_private; 44 using namespace lldb_renderscript; 45 46 namespace { 47 48 // The empirical_type adds a basic level of validation to arbitrary data 49 // allowing us to track if data has been discovered and stored or not. 50 // An empirical_type will be marked as valid only if it has been explicitly 51 // assigned to. 52 template <typename type_t> class empirical_type { 53 public: 54 // Ctor. Contents is invalid when constructed. 55 empirical_type() : valid(false) {} 56 57 // Return true and copy contents to out if valid, else return false. 58 bool get(type_t &out) const { 59 if (valid) 60 out = data; 61 return valid; 62 } 63 64 // Return a pointer to the contents or nullptr if it was not valid. 65 const type_t *get() const { return valid ? &data : nullptr; } 66 67 // Assign data explicitly. 68 void set(const type_t in) { 69 data = in; 70 valid = true; 71 } 72 73 // Mark contents as invalid. 74 void invalidate() { valid = false; } 75 76 // Returns true if this type contains valid data. 77 bool isValid() const { return valid; } 78 79 // Assignment operator. 80 empirical_type<type_t> &operator=(const type_t in) { 81 set(in); 82 return *this; 83 } 84 85 // Dereference operator returns contents. 86 // Warning: Will assert if not valid so use only when you know data is valid. 87 const type_t &operator*() const { 88 assert(valid); 89 return data; 90 } 91 92 protected: 93 bool valid; 94 type_t data; 95 }; 96 97 // ArgItem is used by the GetArgs() function when reading function arguments 98 // from the target. 99 struct ArgItem { 100 enum { ePointer, eInt32, eInt64, eLong, eBool } type; 101 102 uint64_t value; 103 104 explicit operator uint64_t() const { return value; } 105 }; 106 107 // Context structure to be passed into GetArgsXXX(), argument reading functions 108 // below. 109 struct GetArgsCtx { 110 RegisterContext *reg_ctx; 111 Process *process; 112 }; 113 114 bool GetArgsX86(const GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) { 115 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE); 116 117 Error error; 118 119 // get the current stack pointer 120 uint64_t sp = ctx.reg_ctx->GetSP(); 121 122 for (size_t i = 0; i < num_args; ++i) { 123 ArgItem &arg = arg_list[i]; 124 // advance up the stack by one argument 125 sp += sizeof(uint32_t); 126 // get the argument type size 127 size_t arg_size = sizeof(uint32_t); 128 // read the argument from memory 129 arg.value = 0; 130 Error error; 131 size_t read = 132 ctx.process->ReadMemory(sp, &arg.value, sizeof(uint32_t), error); 133 if (read != arg_size || !error.Success()) { 134 if (log) 135 log->Printf("%s - error reading argument: %" PRIu64 " '%s'", 136 __FUNCTION__, uint64_t(i), error.AsCString()); 137 return false; 138 } 139 } 140 return true; 141 } 142 143 bool GetArgsX86_64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) { 144 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE); 145 146 // number of arguments passed in registers 147 static const uint32_t c_args_in_reg = 6; 148 // register passing order 149 static const std::array<const char *, c_args_in_reg> c_reg_names{ 150 {"rdi", "rsi", "rdx", "rcx", "r8", "r9"}}; 151 // argument type to size mapping 152 static const std::array<size_t, 5> arg_size{{ 153 8, // ePointer, 154 4, // eInt32, 155 8, // eInt64, 156 8, // eLong, 157 4, // eBool, 158 }}; 159 160 Error error; 161 162 // get the current stack pointer 163 uint64_t sp = ctx.reg_ctx->GetSP(); 164 // step over the return address 165 sp += sizeof(uint64_t); 166 167 // check the stack alignment was correct (16 byte aligned) 168 if ((sp & 0xf) != 0x0) { 169 if (log) 170 log->Printf("%s - stack misaligned", __FUNCTION__); 171 return false; 172 } 173 174 // find the start of arguments on the stack 175 uint64_t sp_offset = 0; 176 for (uint32_t i = c_args_in_reg; i < num_args; ++i) { 177 sp_offset += arg_size[arg_list[i].type]; 178 } 179 // round up to multiple of 16 180 sp_offset = (sp_offset + 0xf) & 0xf; 181 sp += sp_offset; 182 183 for (size_t i = 0; i < num_args; ++i) { 184 bool success = false; 185 ArgItem &arg = arg_list[i]; 186 // arguments passed in registers 187 if (i < c_args_in_reg) { 188 const RegisterInfo *rArg = 189 ctx.reg_ctx->GetRegisterInfoByName(c_reg_names[i]); 190 RegisterValue rVal; 191 if (ctx.reg_ctx->ReadRegister(rArg, rVal)) 192 arg.value = rVal.GetAsUInt64(0, &success); 193 } 194 // arguments passed on the stack 195 else { 196 // get the argument type size 197 const size_t size = arg_size[arg_list[i].type]; 198 // read the argument from memory 199 arg.value = 0; 200 // note: due to little endian layout reading 4 or 8 bytes will give the 201 // correct value. 202 size_t read = ctx.process->ReadMemory(sp, &arg.value, size, error); 203 success = (error.Success() && read == size); 204 // advance past this argument 205 sp -= size; 206 } 207 // fail if we couldn't read this argument 208 if (!success) { 209 if (log) 210 log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s", 211 __FUNCTION__, uint64_t(i), error.AsCString("n/a")); 212 return false; 213 } 214 } 215 return true; 216 } 217 218 bool GetArgsArm(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) { 219 // number of arguments passed in registers 220 static const uint32_t c_args_in_reg = 4; 221 222 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE); 223 224 Error error; 225 226 // get the current stack pointer 227 uint64_t sp = ctx.reg_ctx->GetSP(); 228 229 for (size_t i = 0; i < num_args; ++i) { 230 bool success = false; 231 ArgItem &arg = arg_list[i]; 232 // arguments passed in registers 233 if (i < c_args_in_reg) { 234 const RegisterInfo *rArg = ctx.reg_ctx->GetRegisterInfoAtIndex(i); 235 RegisterValue rVal; 236 if (ctx.reg_ctx->ReadRegister(rArg, rVal)) 237 arg.value = rVal.GetAsUInt32(0, &success); 238 } 239 // arguments passed on the stack 240 else { 241 // get the argument type size 242 const size_t arg_size = sizeof(uint32_t); 243 // clear all 64bits 244 arg.value = 0; 245 // read this argument from memory 246 size_t bytes_read = 247 ctx.process->ReadMemory(sp, &arg.value, arg_size, error); 248 success = (error.Success() && bytes_read == arg_size); 249 // advance the stack pointer 250 sp += sizeof(uint32_t); 251 } 252 // fail if we couldn't read this argument 253 if (!success) { 254 if (log) 255 log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s", 256 __FUNCTION__, uint64_t(i), error.AsCString("n/a")); 257 return false; 258 } 259 } 260 return true; 261 } 262 263 bool GetArgsAarch64(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) { 264 // number of arguments passed in registers 265 static const uint32_t c_args_in_reg = 8; 266 267 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE); 268 269 for (size_t i = 0; i < num_args; ++i) { 270 bool success = false; 271 ArgItem &arg = arg_list[i]; 272 // arguments passed in registers 273 if (i < c_args_in_reg) { 274 const RegisterInfo *rArg = ctx.reg_ctx->GetRegisterInfoAtIndex(i); 275 RegisterValue rVal; 276 if (ctx.reg_ctx->ReadRegister(rArg, rVal)) 277 arg.value = rVal.GetAsUInt64(0, &success); 278 } 279 // arguments passed on the stack 280 else { 281 if (log) 282 log->Printf("%s - reading arguments spilled to stack not implemented", 283 __FUNCTION__); 284 } 285 // fail if we couldn't read this argument 286 if (!success) { 287 if (log) 288 log->Printf("%s - error reading argument: %" PRIu64, __FUNCTION__, 289 uint64_t(i)); 290 return false; 291 } 292 } 293 return true; 294 } 295 296 bool GetArgsMipsel(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) { 297 // number of arguments passed in registers 298 static const uint32_t c_args_in_reg = 4; 299 // register file offset to first argument 300 static const uint32_t c_reg_offset = 4; 301 302 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE); 303 304 Error error; 305 306 // find offset to arguments on the stack (+16 to skip over a0-a3 shadow space) 307 uint64_t sp = ctx.reg_ctx->GetSP() + 16; 308 309 for (size_t i = 0; i < num_args; ++i) { 310 bool success = false; 311 ArgItem &arg = arg_list[i]; 312 // arguments passed in registers 313 if (i < c_args_in_reg) { 314 const RegisterInfo *rArg = 315 ctx.reg_ctx->GetRegisterInfoAtIndex(i + c_reg_offset); 316 RegisterValue rVal; 317 if (ctx.reg_ctx->ReadRegister(rArg, rVal)) 318 arg.value = rVal.GetAsUInt64(0, &success); 319 } 320 // arguments passed on the stack 321 else { 322 const size_t arg_size = sizeof(uint32_t); 323 arg.value = 0; 324 size_t bytes_read = 325 ctx.process->ReadMemory(sp, &arg.value, arg_size, error); 326 success = (error.Success() && bytes_read == arg_size); 327 // advance the stack pointer 328 sp += arg_size; 329 } 330 // fail if we couldn't read this argument 331 if (!success) { 332 if (log) 333 log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s", 334 __FUNCTION__, uint64_t(i), error.AsCString("n/a")); 335 return false; 336 } 337 } 338 return true; 339 } 340 341 bool GetArgsMips64el(GetArgsCtx &ctx, ArgItem *arg_list, size_t num_args) { 342 // number of arguments passed in registers 343 static const uint32_t c_args_in_reg = 8; 344 // register file offset to first argument 345 static const uint32_t c_reg_offset = 4; 346 347 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE); 348 349 Error error; 350 351 // get the current stack pointer 352 uint64_t sp = ctx.reg_ctx->GetSP(); 353 354 for (size_t i = 0; i < num_args; ++i) { 355 bool success = false; 356 ArgItem &arg = arg_list[i]; 357 // arguments passed in registers 358 if (i < c_args_in_reg) { 359 const RegisterInfo *rArg = 360 ctx.reg_ctx->GetRegisterInfoAtIndex(i + c_reg_offset); 361 RegisterValue rVal; 362 if (ctx.reg_ctx->ReadRegister(rArg, rVal)) 363 arg.value = rVal.GetAsUInt64(0, &success); 364 } 365 // arguments passed on the stack 366 else { 367 // get the argument type size 368 const size_t arg_size = sizeof(uint64_t); 369 // clear all 64bits 370 arg.value = 0; 371 // read this argument from memory 372 size_t bytes_read = 373 ctx.process->ReadMemory(sp, &arg.value, arg_size, error); 374 success = (error.Success() && bytes_read == arg_size); 375 // advance the stack pointer 376 sp += arg_size; 377 } 378 // fail if we couldn't read this argument 379 if (!success) { 380 if (log) 381 log->Printf("%s - error reading argument: %" PRIu64 ", reason: %s", 382 __FUNCTION__, uint64_t(i), error.AsCString("n/a")); 383 return false; 384 } 385 } 386 return true; 387 } 388 389 bool GetArgs(ExecutionContext &context, ArgItem *arg_list, size_t num_args) { 390 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE); 391 392 // verify that we have a target 393 if (!context.GetTargetPtr()) { 394 if (log) 395 log->Printf("%s - invalid target", __FUNCTION__); 396 return false; 397 } 398 399 GetArgsCtx ctx = {context.GetRegisterContext(), context.GetProcessPtr()}; 400 assert(ctx.reg_ctx && ctx.process); 401 402 // dispatch based on architecture 403 switch (context.GetTargetPtr()->GetArchitecture().GetMachine()) { 404 case llvm::Triple::ArchType::x86: 405 return GetArgsX86(ctx, arg_list, num_args); 406 407 case llvm::Triple::ArchType::x86_64: 408 return GetArgsX86_64(ctx, arg_list, num_args); 409 410 case llvm::Triple::ArchType::arm: 411 return GetArgsArm(ctx, arg_list, num_args); 412 413 case llvm::Triple::ArchType::aarch64: 414 return GetArgsAarch64(ctx, arg_list, num_args); 415 416 case llvm::Triple::ArchType::mipsel: 417 return GetArgsMipsel(ctx, arg_list, num_args); 418 419 case llvm::Triple::ArchType::mips64el: 420 return GetArgsMips64el(ctx, arg_list, num_args); 421 422 default: 423 // unsupported architecture 424 if (log) { 425 log->Printf( 426 "%s - architecture not supported: '%s'", __FUNCTION__, 427 context.GetTargetRef().GetArchitecture().GetArchitectureName()); 428 } 429 return false; 430 } 431 } 432 } // anonymous namespace 433 434 // The ScriptDetails class collects data associated with a single script 435 // instance. 436 struct RenderScriptRuntime::ScriptDetails { 437 ~ScriptDetails() = default; 438 439 enum ScriptType { eScript, eScriptC }; 440 441 // The derived type of the script. 442 empirical_type<ScriptType> type; 443 // The name of the original source file. 444 empirical_type<std::string> resName; 445 // Path to script .so file on the device. 446 empirical_type<std::string> scriptDyLib; 447 // Directory where kernel objects are cached on device. 448 empirical_type<std::string> cacheDir; 449 // Pointer to the context which owns this script. 450 empirical_type<lldb::addr_t> context; 451 // Pointer to the script object itself. 452 empirical_type<lldb::addr_t> script; 453 }; 454 455 // This Element class represents the Element object in RS, 456 // defining the type associated with an Allocation. 457 struct RenderScriptRuntime::Element { 458 // Taken from rsDefines.h 459 enum DataKind { 460 RS_KIND_USER, 461 RS_KIND_PIXEL_L = 7, 462 RS_KIND_PIXEL_A, 463 RS_KIND_PIXEL_LA, 464 RS_KIND_PIXEL_RGB, 465 RS_KIND_PIXEL_RGBA, 466 RS_KIND_PIXEL_DEPTH, 467 RS_KIND_PIXEL_YUV, 468 RS_KIND_INVALID = 100 469 }; 470 471 // Taken from rsDefines.h 472 enum DataType { 473 RS_TYPE_NONE = 0, 474 RS_TYPE_FLOAT_16, 475 RS_TYPE_FLOAT_32, 476 RS_TYPE_FLOAT_64, 477 RS_TYPE_SIGNED_8, 478 RS_TYPE_SIGNED_16, 479 RS_TYPE_SIGNED_32, 480 RS_TYPE_SIGNED_64, 481 RS_TYPE_UNSIGNED_8, 482 RS_TYPE_UNSIGNED_16, 483 RS_TYPE_UNSIGNED_32, 484 RS_TYPE_UNSIGNED_64, 485 RS_TYPE_BOOLEAN, 486 487 RS_TYPE_UNSIGNED_5_6_5, 488 RS_TYPE_UNSIGNED_5_5_5_1, 489 RS_TYPE_UNSIGNED_4_4_4_4, 490 491 RS_TYPE_MATRIX_4X4, 492 RS_TYPE_MATRIX_3X3, 493 RS_TYPE_MATRIX_2X2, 494 495 RS_TYPE_ELEMENT = 1000, 496 RS_TYPE_TYPE, 497 RS_TYPE_ALLOCATION, 498 RS_TYPE_SAMPLER, 499 RS_TYPE_SCRIPT, 500 RS_TYPE_MESH, 501 RS_TYPE_PROGRAM_FRAGMENT, 502 RS_TYPE_PROGRAM_VERTEX, 503 RS_TYPE_PROGRAM_RASTER, 504 RS_TYPE_PROGRAM_STORE, 505 RS_TYPE_FONT, 506 507 RS_TYPE_INVALID = 10000 508 }; 509 510 std::vector<Element> children; // Child Element fields for structs 511 empirical_type<lldb::addr_t> 512 element_ptr; // Pointer to the RS Element of the Type 513 empirical_type<DataType> 514 type; // Type of each data pointer stored by the allocation 515 empirical_type<DataKind> 516 type_kind; // Defines pixel type if Allocation is created from an image 517 empirical_type<uint32_t> 518 type_vec_size; // Vector size of each data point, e.g '4' for uchar4 519 empirical_type<uint32_t> field_count; // Number of Subelements 520 empirical_type<uint32_t> datum_size; // Size of a single Element with padding 521 empirical_type<uint32_t> padding; // Number of padding bytes 522 empirical_type<uint32_t> 523 array_size; // Number of items in array, only needed for strucrs 524 ConstString type_name; // Name of type, only needed for structs 525 526 static const ConstString & 527 GetFallbackStructName(); // Print this as the type name of a struct Element 528 // If we can't resolve the actual struct name 529 530 bool shouldRefresh() const { 531 const bool valid_ptr = element_ptr.isValid() && *element_ptr.get() != 0x0; 532 const bool valid_type = 533 type.isValid() && type_vec_size.isValid() && type_kind.isValid(); 534 return !valid_ptr || !valid_type || !datum_size.isValid(); 535 } 536 }; 537 538 // This AllocationDetails class collects data associated with a single 539 // allocation instance. 540 struct RenderScriptRuntime::AllocationDetails { 541 struct Dimension { 542 uint32_t dim_1; 543 uint32_t dim_2; 544 uint32_t dim_3; 545 uint32_t cubeMap; 546 547 Dimension() { 548 dim_1 = 0; 549 dim_2 = 0; 550 dim_3 = 0; 551 cubeMap = 0; 552 } 553 }; 554 555 // The FileHeader struct specifies the header we use for writing allocations 556 // to a binary file. 557 // Our format begins with the ASCII characters "RSAD", identifying the file as 558 // an allocation dump. 559 // Member variables dims and hdr_size are then written consecutively, 560 // immediately followed by an instance of 561 // the ElementHeader struct. Because Elements can contain subelements, there 562 // may be more than one instance 563 // of the ElementHeader struct. With this first instance being the root 564 // element, and the other instances being 565 // the root's descendants. To identify which instances are an ElementHeader's 566 // children, each struct 567 // is immediately followed by a sequence of consecutive offsets to the start 568 // of its child structs. 569 // These offsets are 4 bytes in size, and the 0 offset signifies no more 570 // children. 571 struct FileHeader { 572 uint8_t ident[4]; // ASCII 'RSAD' identifying the file 573 uint32_t dims[3]; // Dimensions 574 uint16_t hdr_size; // Header size in bytes, including all element headers 575 }; 576 577 struct ElementHeader { 578 uint16_t type; // DataType enum 579 uint32_t kind; // DataKind enum 580 uint32_t element_size; // Size of a single element, including padding 581 uint16_t vector_size; // Vector width 582 uint32_t array_size; // Number of elements in array 583 }; 584 585 // Monotonically increasing from 1 586 static uint32_t ID; 587 588 // Maps Allocation DataType enum and vector size to printable strings 589 // using mapping from RenderScript numerical types summary documentation 590 static const char *RsDataTypeToString[][4]; 591 592 // Maps Allocation DataKind enum to printable strings 593 static const char *RsDataKindToString[]; 594 595 // Maps allocation types to format sizes for printing. 596 static const uint32_t RSTypeToFormat[][3]; 597 598 // Give each allocation an ID as a way 599 // for commands to reference it. 600 const uint32_t id; 601 602 RenderScriptRuntime::Element element; // Allocation Element type 603 empirical_type<Dimension> dimension; // Dimensions of the Allocation 604 empirical_type<lldb::addr_t> 605 address; // Pointer to address of the RS Allocation 606 empirical_type<lldb::addr_t> 607 data_ptr; // Pointer to the data held by the Allocation 608 empirical_type<lldb::addr_t> 609 type_ptr; // Pointer to the RS Type of the Allocation 610 empirical_type<lldb::addr_t> 611 context; // Pointer to the RS Context of the Allocation 612 empirical_type<uint32_t> size; // Size of the allocation 613 empirical_type<uint32_t> stride; // Stride between rows of the allocation 614 615 // Give each allocation an id, so we can reference it in user commands. 616 AllocationDetails() : id(ID++) {} 617 618 bool shouldRefresh() const { 619 bool valid_ptrs = data_ptr.isValid() && *data_ptr.get() != 0x0; 620 valid_ptrs = valid_ptrs && type_ptr.isValid() && *type_ptr.get() != 0x0; 621 return !valid_ptrs || !dimension.isValid() || !size.isValid() || 622 element.shouldRefresh(); 623 } 624 }; 625 626 const ConstString &RenderScriptRuntime::Element::GetFallbackStructName() { 627 static const ConstString FallbackStructName("struct"); 628 return FallbackStructName; 629 } 630 631 uint32_t RenderScriptRuntime::AllocationDetails::ID = 1; 632 633 const char *RenderScriptRuntime::AllocationDetails::RsDataKindToString[] = { 634 "User", "Undefined", "Undefined", "Undefined", 635 "Undefined", "Undefined", "Undefined", // Enum jumps from 0 to 7 636 "L Pixel", "A Pixel", "LA Pixel", "RGB Pixel", 637 "RGBA Pixel", "Pixel Depth", "YUV Pixel"}; 638 639 const char *RenderScriptRuntime::AllocationDetails::RsDataTypeToString[][4] = { 640 {"None", "None", "None", "None"}, 641 {"half", "half2", "half3", "half4"}, 642 {"float", "float2", "float3", "float4"}, 643 {"double", "double2", "double3", "double4"}, 644 {"char", "char2", "char3", "char4"}, 645 {"short", "short2", "short3", "short4"}, 646 {"int", "int2", "int3", "int4"}, 647 {"long", "long2", "long3", "long4"}, 648 {"uchar", "uchar2", "uchar3", "uchar4"}, 649 {"ushort", "ushort2", "ushort3", "ushort4"}, 650 {"uint", "uint2", "uint3", "uint4"}, 651 {"ulong", "ulong2", "ulong3", "ulong4"}, 652 {"bool", "bool2", "bool3", "bool4"}, 653 {"packed_565", "packed_565", "packed_565", "packed_565"}, 654 {"packed_5551", "packed_5551", "packed_5551", "packed_5551"}, 655 {"packed_4444", "packed_4444", "packed_4444", "packed_4444"}, 656 {"rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4", "rs_matrix4x4"}, 657 {"rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3", "rs_matrix3x3"}, 658 {"rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2", "rs_matrix2x2"}, 659 660 // Handlers 661 {"RS Element", "RS Element", "RS Element", "RS Element"}, 662 {"RS Type", "RS Type", "RS Type", "RS Type"}, 663 {"RS Allocation", "RS Allocation", "RS Allocation", "RS Allocation"}, 664 {"RS Sampler", "RS Sampler", "RS Sampler", "RS Sampler"}, 665 {"RS Script", "RS Script", "RS Script", "RS Script"}, 666 667 // Deprecated 668 {"RS Mesh", "RS Mesh", "RS Mesh", "RS Mesh"}, 669 {"RS Program Fragment", "RS Program Fragment", "RS Program Fragment", 670 "RS Program Fragment"}, 671 {"RS Program Vertex", "RS Program Vertex", "RS Program Vertex", 672 "RS Program Vertex"}, 673 {"RS Program Raster", "RS Program Raster", "RS Program Raster", 674 "RS Program Raster"}, 675 {"RS Program Store", "RS Program Store", "RS Program Store", 676 "RS Program Store"}, 677 {"RS Font", "RS Font", "RS Font", "RS Font"}}; 678 679 // Used as an index into the RSTypeToFormat array elements 680 enum TypeToFormatIndex { eFormatSingle = 0, eFormatVector, eElementSize }; 681 682 // { format enum of single element, format enum of element vector, size of 683 // element} 684 const uint32_t RenderScriptRuntime::AllocationDetails::RSTypeToFormat[][3] = { 685 {eFormatHex, eFormatHex, 1}, // RS_TYPE_NONE 686 {eFormatFloat, eFormatVectorOfFloat16, 2}, // RS_TYPE_FLOAT_16 687 {eFormatFloat, eFormatVectorOfFloat32, sizeof(float)}, // RS_TYPE_FLOAT_32 688 {eFormatFloat, eFormatVectorOfFloat64, sizeof(double)}, // RS_TYPE_FLOAT_64 689 {eFormatDecimal, eFormatVectorOfSInt8, sizeof(int8_t)}, // RS_TYPE_SIGNED_8 690 {eFormatDecimal, eFormatVectorOfSInt16, 691 sizeof(int16_t)}, // RS_TYPE_SIGNED_16 692 {eFormatDecimal, eFormatVectorOfSInt32, 693 sizeof(int32_t)}, // RS_TYPE_SIGNED_32 694 {eFormatDecimal, eFormatVectorOfSInt64, 695 sizeof(int64_t)}, // RS_TYPE_SIGNED_64 696 {eFormatDecimal, eFormatVectorOfUInt8, 697 sizeof(uint8_t)}, // RS_TYPE_UNSIGNED_8 698 {eFormatDecimal, eFormatVectorOfUInt16, 699 sizeof(uint16_t)}, // RS_TYPE_UNSIGNED_16 700 {eFormatDecimal, eFormatVectorOfUInt32, 701 sizeof(uint32_t)}, // RS_TYPE_UNSIGNED_32 702 {eFormatDecimal, eFormatVectorOfUInt64, 703 sizeof(uint64_t)}, // RS_TYPE_UNSIGNED_64 704 {eFormatBoolean, eFormatBoolean, 1}, // RS_TYPE_BOOL 705 {eFormatHex, eFormatHex, sizeof(uint16_t)}, // RS_TYPE_UNSIGNED_5_6_5 706 {eFormatHex, eFormatHex, sizeof(uint16_t)}, // RS_TYPE_UNSIGNED_5_5_5_1 707 {eFormatHex, eFormatHex, sizeof(uint16_t)}, // RS_TYPE_UNSIGNED_4_4_4_4 708 {eFormatVectorOfFloat32, eFormatVectorOfFloat32, 709 sizeof(float) * 16}, // RS_TYPE_MATRIX_4X4 710 {eFormatVectorOfFloat32, eFormatVectorOfFloat32, 711 sizeof(float) * 9}, // RS_TYPE_MATRIX_3X3 712 {eFormatVectorOfFloat32, eFormatVectorOfFloat32, 713 sizeof(float) * 4} // RS_TYPE_MATRIX_2X2 714 }; 715 716 //------------------------------------------------------------------ 717 // Static Functions 718 //------------------------------------------------------------------ 719 LanguageRuntime * 720 RenderScriptRuntime::CreateInstance(Process *process, 721 lldb::LanguageType language) { 722 723 if (language == eLanguageTypeExtRenderScript) 724 return new RenderScriptRuntime(process); 725 else 726 return nullptr; 727 } 728 729 // Callback with a module to search for matching symbols. 730 // We first check that the module contains RS kernels. 731 // Then look for a symbol which matches our kernel name. 732 // The breakpoint address is finally set using the address of this symbol. 733 Searcher::CallbackReturn 734 RSBreakpointResolver::SearchCallback(SearchFilter &filter, 735 SymbolContext &context, Address *, bool) { 736 ModuleSP module = context.module_sp; 737 738 if (!module) 739 return Searcher::eCallbackReturnContinue; 740 741 // Is this a module containing renderscript kernels? 742 if (nullptr == 743 module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), 744 eSymbolTypeData)) 745 return Searcher::eCallbackReturnContinue; 746 747 // Attempt to set a breakpoint on the kernel name symbol within the module 748 // library. 749 // If it's not found, it's likely debug info is unavailable - try to set a 750 // breakpoint on <name>.expand. 751 752 const Symbol *kernel_sym = 753 module->FindFirstSymbolWithNameAndType(m_kernel_name, eSymbolTypeCode); 754 if (!kernel_sym) { 755 std::string kernel_name_expanded(m_kernel_name.AsCString()); 756 kernel_name_expanded.append(".expand"); 757 kernel_sym = module->FindFirstSymbolWithNameAndType( 758 ConstString(kernel_name_expanded.c_str()), eSymbolTypeCode); 759 } 760 761 if (kernel_sym) { 762 Address bp_addr = kernel_sym->GetAddress(); 763 if (filter.AddressPasses(bp_addr)) 764 m_breakpoint->AddLocation(bp_addr); 765 } 766 767 return Searcher::eCallbackReturnContinue; 768 } 769 770 void RenderScriptRuntime::Initialize() { 771 PluginManager::RegisterPlugin(GetPluginNameStatic(), 772 "RenderScript language support", CreateInstance, 773 GetCommandObject); 774 } 775 776 void RenderScriptRuntime::Terminate() { 777 PluginManager::UnregisterPlugin(CreateInstance); 778 } 779 780 lldb_private::ConstString RenderScriptRuntime::GetPluginNameStatic() { 781 static ConstString g_name("renderscript"); 782 return g_name; 783 } 784 785 RenderScriptRuntime::ModuleKind 786 RenderScriptRuntime::GetModuleKind(const lldb::ModuleSP &module_sp) { 787 if (module_sp) { 788 // Is this a module containing renderscript kernels? 789 const Symbol *info_sym = module_sp->FindFirstSymbolWithNameAndType( 790 ConstString(".rs.info"), eSymbolTypeData); 791 if (info_sym) { 792 return eModuleKindKernelObj; 793 } 794 795 // Is this the main RS runtime library 796 const ConstString rs_lib("libRS.so"); 797 if (module_sp->GetFileSpec().GetFilename() == rs_lib) { 798 return eModuleKindLibRS; 799 } 800 801 const ConstString rs_driverlib("libRSDriver.so"); 802 if (module_sp->GetFileSpec().GetFilename() == rs_driverlib) { 803 return eModuleKindDriver; 804 } 805 806 const ConstString rs_cpureflib("libRSCpuRef.so"); 807 if (module_sp->GetFileSpec().GetFilename() == rs_cpureflib) { 808 return eModuleKindImpl; 809 } 810 } 811 return eModuleKindIgnored; 812 } 813 814 bool RenderScriptRuntime::IsRenderScriptModule( 815 const lldb::ModuleSP &module_sp) { 816 return GetModuleKind(module_sp) != eModuleKindIgnored; 817 } 818 819 void RenderScriptRuntime::ModulesDidLoad(const ModuleList &module_list) { 820 std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex()); 821 822 size_t num_modules = module_list.GetSize(); 823 for (size_t i = 0; i < num_modules; i++) { 824 auto mod = module_list.GetModuleAtIndex(i); 825 if (IsRenderScriptModule(mod)) { 826 LoadModule(mod); 827 } 828 } 829 } 830 831 //------------------------------------------------------------------ 832 // PluginInterface protocol 833 //------------------------------------------------------------------ 834 lldb_private::ConstString RenderScriptRuntime::GetPluginName() { 835 return GetPluginNameStatic(); 836 } 837 838 uint32_t RenderScriptRuntime::GetPluginVersion() { return 1; } 839 840 bool RenderScriptRuntime::IsVTableName(const char *name) { return false; } 841 842 bool RenderScriptRuntime::GetDynamicTypeAndAddress( 843 ValueObject &in_value, lldb::DynamicValueType use_dynamic, 844 TypeAndOrName &class_type_or_name, Address &address, 845 Value::ValueType &value_type) { 846 return false; 847 } 848 849 TypeAndOrName 850 RenderScriptRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name, 851 ValueObject &static_value) { 852 return type_and_or_name; 853 } 854 855 bool RenderScriptRuntime::CouldHaveDynamicValue(ValueObject &in_value) { 856 return false; 857 } 858 859 lldb::BreakpointResolverSP 860 RenderScriptRuntime::CreateExceptionResolver(Breakpoint *bkpt, bool catch_bp, 861 bool throw_bp) { 862 BreakpointResolverSP resolver_sp; 863 return resolver_sp; 864 } 865 866 const RenderScriptRuntime::HookDefn RenderScriptRuntime::s_runtimeHookDefns[] = 867 { 868 // rsdScript 869 {"rsdScriptInit", "_Z13rsdScriptInitPKN7android12renderscript7ContextEP" 870 "NS0_7ScriptCEPKcS7_PKhjj", 871 "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_" 872 "7ScriptCEPKcS7_PKhmj", 873 0, RenderScriptRuntime::eModuleKindDriver, 874 &lldb_private::RenderScriptRuntime::CaptureScriptInit}, 875 {"rsdScriptInvokeForEachMulti", 876 "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0" 877 "_6ScriptEjPPKNS0_10AllocationEjPS6_PKvjPK12RsScriptCall", 878 "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0" 879 "_6ScriptEjPPKNS0_10AllocationEmPS6_PKvmPK12RsScriptCall", 880 0, RenderScriptRuntime::eModuleKindDriver, 881 &lldb_private::RenderScriptRuntime::CaptureScriptInvokeForEachMulti}, 882 {"rsdScriptSetGlobalVar", "_Z21rsdScriptSetGlobalVarPKN7android12render" 883 "script7ContextEPKNS0_6ScriptEjPvj", 884 "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_" 885 "6ScriptEjPvm", 886 0, RenderScriptRuntime::eModuleKindDriver, 887 &lldb_private::RenderScriptRuntime::CaptureSetGlobalVar}, 888 889 // rsdAllocation 890 {"rsdAllocationInit", "_Z17rsdAllocationInitPKN7android12renderscript7C" 891 "ontextEPNS0_10AllocationEb", 892 "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_" 893 "10AllocationEb", 894 0, RenderScriptRuntime::eModuleKindDriver, 895 &lldb_private::RenderScriptRuntime::CaptureAllocationInit}, 896 {"rsdAllocationRead2D", 897 "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_" 898 "10AllocationEjjj23RsAllocationCubemapFacejjPvjj", 899 "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_" 900 "10AllocationEjjj23RsAllocationCubemapFacejjPvmm", 901 0, RenderScriptRuntime::eModuleKindDriver, nullptr}, 902 {"rsdAllocationDestroy", "_Z20rsdAllocationDestroyPKN7android12rendersc" 903 "ript7ContextEPNS0_10AllocationE", 904 "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_" 905 "10AllocationE", 906 0, RenderScriptRuntime::eModuleKindDriver, 907 &lldb_private::RenderScriptRuntime::CaptureAllocationDestroy}, 908 }; 909 910 const size_t RenderScriptRuntime::s_runtimeHookCount = 911 sizeof(s_runtimeHookDefns) / sizeof(s_runtimeHookDefns[0]); 912 913 bool RenderScriptRuntime::HookCallback(void *baton, 914 StoppointCallbackContext *ctx, 915 lldb::user_id_t break_id, 916 lldb::user_id_t break_loc_id) { 917 RuntimeHook *hook_info = (RuntimeHook *)baton; 918 ExecutionContext context(ctx->exe_ctx_ref); 919 920 RenderScriptRuntime *lang_rt = 921 (RenderScriptRuntime *)context.GetProcessPtr()->GetLanguageRuntime( 922 eLanguageTypeExtRenderScript); 923 924 lang_rt->HookCallback(hook_info, context); 925 926 return false; 927 } 928 929 void RenderScriptRuntime::HookCallback(RuntimeHook *hook_info, 930 ExecutionContext &context) { 931 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 932 933 if (log) 934 log->Printf("%s - '%s'", __FUNCTION__, hook_info->defn->name); 935 936 if (hook_info->defn->grabber) { 937 (this->*(hook_info->defn->grabber))(hook_info, context); 938 } 939 } 940 941 void RenderScriptRuntime::CaptureScriptInvokeForEachMulti( 942 RuntimeHook *hook_info, ExecutionContext &context) { 943 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 944 945 enum { 946 eRsContext = 0, 947 eRsScript, 948 eRsSlot, 949 eRsAIns, 950 eRsInLen, 951 eRsAOut, 952 eRsUsr, 953 eRsUsrLen, 954 eRsSc, 955 }; 956 957 std::array<ArgItem, 9> args{{ 958 ArgItem{ArgItem::ePointer, 0}, // const Context *rsc 959 ArgItem{ArgItem::ePointer, 0}, // Script *s 960 ArgItem{ArgItem::eInt32, 0}, // uint32_t slot 961 ArgItem{ArgItem::ePointer, 0}, // const Allocation **aIns 962 ArgItem{ArgItem::eInt32, 0}, // size_t inLen 963 ArgItem{ArgItem::ePointer, 0}, // Allocation *aout 964 ArgItem{ArgItem::ePointer, 0}, // const void *usr 965 ArgItem{ArgItem::eInt32, 0}, // size_t usrLen 966 ArgItem{ArgItem::ePointer, 0}, // const RsScriptCall *sc 967 }}; 968 969 bool success = GetArgs(context, &args[0], args.size()); 970 if (!success) { 971 if (log) 972 log->Printf("%s - Error while reading the function parameters", 973 __FUNCTION__); 974 return; 975 } 976 977 const uint32_t target_ptr_size = m_process->GetAddressByteSize(); 978 Error error; 979 std::vector<uint64_t> allocs; 980 981 // traverse allocation list 982 for (uint64_t i = 0; i < uint64_t(args[eRsInLen]); ++i) { 983 // calculate offest to allocation pointer 984 const addr_t addr = addr_t(args[eRsAIns]) + i * target_ptr_size; 985 986 // Note: due to little endian layout, reading 32bits or 64bits into res64 987 // will 988 // give the correct results. 989 990 uint64_t res64 = 0; 991 size_t read = m_process->ReadMemory(addr, &res64, target_ptr_size, error); 992 if (read != target_ptr_size || !error.Success()) { 993 if (log) 994 log->Printf( 995 "%s - Error while reading allocation list argument %" PRIu64, 996 __FUNCTION__, i); 997 } else { 998 allocs.push_back(res64); 999 } 1000 } 1001 1002 // if there is an output allocation track it 1003 if (uint64_t aOut = uint64_t(args[eRsAOut])) { 1004 allocs.push_back(aOut); 1005 } 1006 1007 // for all allocations we have found 1008 for (const uint64_t alloc_addr : allocs) { 1009 AllocationDetails *alloc = LookUpAllocation(alloc_addr); 1010 if (!alloc) 1011 alloc = CreateAllocation(alloc_addr); 1012 1013 if (alloc) { 1014 // save the allocation address 1015 if (alloc->address.isValid()) { 1016 // check the allocation address we already have matches 1017 assert(*alloc->address.get() == alloc_addr); 1018 } else { 1019 alloc->address = alloc_addr; 1020 } 1021 1022 // save the context 1023 if (log) { 1024 if (alloc->context.isValid() && 1025 *alloc->context.get() != addr_t(args[eRsContext])) 1026 log->Printf("%s - Allocation used by multiple contexts", 1027 __FUNCTION__); 1028 } 1029 alloc->context = addr_t(args[eRsContext]); 1030 } 1031 } 1032 1033 // make sure we track this script object 1034 if (lldb_private::RenderScriptRuntime::ScriptDetails *script = 1035 LookUpScript(addr_t(args[eRsScript]), true)) { 1036 if (log) { 1037 if (script->context.isValid() && 1038 *script->context.get() != addr_t(args[eRsContext])) 1039 log->Printf("%s - Script used by multiple contexts", __FUNCTION__); 1040 } 1041 script->context = addr_t(args[eRsContext]); 1042 } 1043 } 1044 1045 void RenderScriptRuntime::CaptureSetGlobalVar(RuntimeHook *hook_info, 1046 ExecutionContext &context) { 1047 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 1048 1049 enum { 1050 eRsContext, 1051 eRsScript, 1052 eRsId, 1053 eRsData, 1054 eRsLength, 1055 }; 1056 1057 std::array<ArgItem, 5> args{{ 1058 ArgItem{ArgItem::ePointer, 0}, // eRsContext 1059 ArgItem{ArgItem::ePointer, 0}, // eRsScript 1060 ArgItem{ArgItem::eInt32, 0}, // eRsId 1061 ArgItem{ArgItem::ePointer, 0}, // eRsData 1062 ArgItem{ArgItem::eInt32, 0}, // eRsLength 1063 }}; 1064 1065 bool success = GetArgs(context, &args[0], args.size()); 1066 if (!success) { 1067 if (log) 1068 log->Printf("%s - error reading the function parameters.", __FUNCTION__); 1069 return; 1070 } 1071 1072 if (log) { 1073 log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " slot %" PRIu64 " = 0x%" PRIx64 1074 ":%" PRIu64 "bytes.", 1075 __FUNCTION__, uint64_t(args[eRsContext]), 1076 uint64_t(args[eRsScript]), uint64_t(args[eRsId]), 1077 uint64_t(args[eRsData]), uint64_t(args[eRsLength])); 1078 1079 addr_t script_addr = addr_t(args[eRsScript]); 1080 if (m_scriptMappings.find(script_addr) != m_scriptMappings.end()) { 1081 auto rsm = m_scriptMappings[script_addr]; 1082 if (uint64_t(args[eRsId]) < rsm->m_globals.size()) { 1083 auto rsg = rsm->m_globals[uint64_t(args[eRsId])]; 1084 log->Printf("%s - Setting of '%s' within '%s' inferred", __FUNCTION__, 1085 rsg.m_name.AsCString(), 1086 rsm->m_module->GetFileSpec().GetFilename().AsCString()); 1087 } 1088 } 1089 } 1090 } 1091 1092 void RenderScriptRuntime::CaptureAllocationInit(RuntimeHook *hook_info, 1093 ExecutionContext &context) { 1094 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 1095 1096 enum { eRsContext, eRsAlloc, eRsForceZero }; 1097 1098 std::array<ArgItem, 3> args{{ 1099 ArgItem{ArgItem::ePointer, 0}, // eRsContext 1100 ArgItem{ArgItem::ePointer, 0}, // eRsAlloc 1101 ArgItem{ArgItem::eBool, 0}, // eRsForceZero 1102 }}; 1103 1104 bool success = GetArgs(context, &args[0], args.size()); 1105 if (!success) // error case 1106 { 1107 if (log) 1108 log->Printf("%s - error while reading the function parameters", 1109 __FUNCTION__); 1110 return; // abort 1111 } 1112 1113 if (log) 1114 log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 ",0x%" PRIx64 " .", 1115 __FUNCTION__, uint64_t(args[eRsContext]), 1116 uint64_t(args[eRsAlloc]), uint64_t(args[eRsForceZero])); 1117 1118 AllocationDetails *alloc = CreateAllocation(uint64_t(args[eRsAlloc])); 1119 if (alloc) 1120 alloc->context = uint64_t(args[eRsContext]); 1121 } 1122 1123 void RenderScriptRuntime::CaptureAllocationDestroy(RuntimeHook *hook_info, 1124 ExecutionContext &context) { 1125 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 1126 1127 enum { 1128 eRsContext, 1129 eRsAlloc, 1130 }; 1131 1132 std::array<ArgItem, 2> args{{ 1133 ArgItem{ArgItem::ePointer, 0}, // eRsContext 1134 ArgItem{ArgItem::ePointer, 0}, // eRsAlloc 1135 }}; 1136 1137 bool success = GetArgs(context, &args[0], args.size()); 1138 if (!success) { 1139 if (log) 1140 log->Printf("%s - error while reading the function parameters.", 1141 __FUNCTION__); 1142 return; 1143 } 1144 1145 if (log) 1146 log->Printf("%s - 0x%" PRIx64 ", 0x%" PRIx64 ".", __FUNCTION__, 1147 uint64_t(args[eRsContext]), uint64_t(args[eRsAlloc])); 1148 1149 for (auto iter = m_allocations.begin(); iter != m_allocations.end(); ++iter) { 1150 auto &allocation_ap = *iter; // get the unique pointer 1151 if (allocation_ap->address.isValid() && 1152 *allocation_ap->address.get() == addr_t(args[eRsAlloc])) { 1153 m_allocations.erase(iter); 1154 if (log) 1155 log->Printf("%s - deleted allocation entry.", __FUNCTION__); 1156 return; 1157 } 1158 } 1159 1160 if (log) 1161 log->Printf("%s - couldn't find destroyed allocation.", __FUNCTION__); 1162 } 1163 1164 void RenderScriptRuntime::CaptureScriptInit(RuntimeHook *hook_info, 1165 ExecutionContext &context) { 1166 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 1167 1168 Error error; 1169 Process *process = context.GetProcessPtr(); 1170 1171 enum { eRsContext, eRsScript, eRsResNamePtr, eRsCachedDirPtr }; 1172 1173 std::array<ArgItem, 4> args{ 1174 {ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0}, 1175 ArgItem{ArgItem::ePointer, 0}, ArgItem{ArgItem::ePointer, 0}}}; 1176 bool success = GetArgs(context, &args[0], args.size()); 1177 if (!success) { 1178 if (log) 1179 log->Printf("%s - error while reading the function parameters.", 1180 __FUNCTION__); 1181 return; 1182 } 1183 1184 std::string resname; 1185 process->ReadCStringFromMemory(addr_t(args[eRsResNamePtr]), resname, error); 1186 if (error.Fail()) { 1187 if (log) 1188 log->Printf("%s - error reading resname: %s.", __FUNCTION__, 1189 error.AsCString()); 1190 } 1191 1192 std::string cachedir; 1193 process->ReadCStringFromMemory(addr_t(args[eRsCachedDirPtr]), cachedir, 1194 error); 1195 if (error.Fail()) { 1196 if (log) 1197 log->Printf("%s - error reading cachedir: %s.", __FUNCTION__, 1198 error.AsCString()); 1199 } 1200 1201 if (log) 1202 log->Printf("%s - 0x%" PRIx64 ",0x%" PRIx64 " => '%s' at '%s' .", 1203 __FUNCTION__, uint64_t(args[eRsContext]), 1204 uint64_t(args[eRsScript]), resname.c_str(), cachedir.c_str()); 1205 1206 if (resname.size() > 0) { 1207 StreamString strm; 1208 strm.Printf("librs.%s.so", resname.c_str()); 1209 1210 ScriptDetails *script = LookUpScript(addr_t(args[eRsScript]), true); 1211 if (script) { 1212 script->type = ScriptDetails::eScriptC; 1213 script->cacheDir = cachedir; 1214 script->resName = resname; 1215 script->scriptDyLib = strm.GetData(); 1216 script->context = addr_t(args[eRsContext]); 1217 } 1218 1219 if (log) 1220 log->Printf("%s - '%s' tagged with context 0x%" PRIx64 1221 " and script 0x%" PRIx64 ".", 1222 __FUNCTION__, strm.GetData(), uint64_t(args[eRsContext]), 1223 uint64_t(args[eRsScript])); 1224 } else if (log) { 1225 log->Printf("%s - resource name invalid, Script not tagged.", __FUNCTION__); 1226 } 1227 } 1228 1229 void RenderScriptRuntime::LoadRuntimeHooks(lldb::ModuleSP module, 1230 ModuleKind kind) { 1231 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 1232 1233 if (!module) { 1234 return; 1235 } 1236 1237 Target &target = GetProcess()->GetTarget(); 1238 llvm::Triple::ArchType targetArchType = target.GetArchitecture().GetMachine(); 1239 1240 if (targetArchType != llvm::Triple::ArchType::x86 && 1241 targetArchType != llvm::Triple::ArchType::arm && 1242 targetArchType != llvm::Triple::ArchType::aarch64 && 1243 targetArchType != llvm::Triple::ArchType::mipsel && 1244 targetArchType != llvm::Triple::ArchType::mips64el && 1245 targetArchType != llvm::Triple::ArchType::x86_64) { 1246 if (log) 1247 log->Printf("%s - unable to hook runtime functions.", __FUNCTION__); 1248 return; 1249 } 1250 1251 uint32_t archByteSize = target.GetArchitecture().GetAddressByteSize(); 1252 1253 for (size_t idx = 0; idx < s_runtimeHookCount; idx++) { 1254 const HookDefn *hook_defn = &s_runtimeHookDefns[idx]; 1255 if (hook_defn->kind != kind) { 1256 continue; 1257 } 1258 1259 const char *symbol_name = (archByteSize == 4) ? hook_defn->symbol_name_m32 1260 : hook_defn->symbol_name_m64; 1261 1262 const Symbol *sym = module->FindFirstSymbolWithNameAndType( 1263 ConstString(symbol_name), eSymbolTypeCode); 1264 if (!sym) { 1265 if (log) { 1266 log->Printf("%s - symbol '%s' related to the function %s not found", 1267 __FUNCTION__, symbol_name, hook_defn->name); 1268 } 1269 continue; 1270 } 1271 1272 addr_t addr = sym->GetLoadAddress(&target); 1273 if (addr == LLDB_INVALID_ADDRESS) { 1274 if (log) 1275 log->Printf("%s - unable to resolve the address of hook function '%s' " 1276 "with symbol '%s'.", 1277 __FUNCTION__, hook_defn->name, symbol_name); 1278 continue; 1279 } else { 1280 if (log) 1281 log->Printf("%s - function %s, address resolved at 0x%" PRIx64, 1282 __FUNCTION__, hook_defn->name, addr); 1283 } 1284 1285 RuntimeHookSP hook(new RuntimeHook()); 1286 hook->address = addr; 1287 hook->defn = hook_defn; 1288 hook->bp_sp = target.CreateBreakpoint(addr, true, false); 1289 hook->bp_sp->SetCallback(HookCallback, hook.get(), true); 1290 m_runtimeHooks[addr] = hook; 1291 if (log) { 1292 log->Printf("%s - successfully hooked '%s' in '%s' version %" PRIu64 1293 " at 0x%" PRIx64 ".", 1294 __FUNCTION__, hook_defn->name, 1295 module->GetFileSpec().GetFilename().AsCString(), 1296 (uint64_t)hook_defn->version, (uint64_t)addr); 1297 } 1298 } 1299 } 1300 1301 void RenderScriptRuntime::FixupScriptDetails(RSModuleDescriptorSP rsmodule_sp) { 1302 if (!rsmodule_sp) 1303 return; 1304 1305 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 1306 1307 const ModuleSP module = rsmodule_sp->m_module; 1308 const FileSpec &file = module->GetPlatformFileSpec(); 1309 1310 // Iterate over all of the scripts that we currently know of. 1311 // Note: We cant push or pop to m_scripts here or it may invalidate rs_script. 1312 for (const auto &rs_script : m_scripts) { 1313 // Extract the expected .so file path for this script. 1314 std::string dylib; 1315 if (!rs_script->scriptDyLib.get(dylib)) 1316 continue; 1317 1318 // Only proceed if the module that has loaded corresponds to this script. 1319 if (file.GetFilename() != ConstString(dylib.c_str())) 1320 continue; 1321 1322 // Obtain the script address which we use as a key. 1323 lldb::addr_t script; 1324 if (!rs_script->script.get(script)) 1325 continue; 1326 1327 // If we have a script mapping for the current script. 1328 if (m_scriptMappings.find(script) != m_scriptMappings.end()) { 1329 // if the module we have stored is different to the one we just received. 1330 if (m_scriptMappings[script] != rsmodule_sp) { 1331 if (log) 1332 log->Printf( 1333 "%s - script %" PRIx64 " wants reassigned to new rsmodule '%s'.", 1334 __FUNCTION__, (uint64_t)script, 1335 rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString()); 1336 } 1337 } 1338 // We don't have a script mapping for the current script. 1339 else { 1340 // Obtain the script resource name. 1341 std::string resName; 1342 if (rs_script->resName.get(resName)) 1343 // Set the modules resource name. 1344 rsmodule_sp->m_resname = resName; 1345 // Add Script/Module pair to map. 1346 m_scriptMappings[script] = rsmodule_sp; 1347 if (log) 1348 log->Printf( 1349 "%s - script %" PRIx64 " associated with rsmodule '%s'.", 1350 __FUNCTION__, (uint64_t)script, 1351 rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString()); 1352 } 1353 } 1354 } 1355 1356 // Uses the Target API to evaluate the expression passed as a parameter to the 1357 // function 1358 // The result of that expression is returned an unsigned 64 bit int, via the 1359 // result* parameter. 1360 // Function returns true on success, and false on failure 1361 bool RenderScriptRuntime::EvalRSExpression(const char *expression, 1362 StackFrame *frame_ptr, 1363 uint64_t *result) { 1364 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 1365 if (log) 1366 log->Printf("%s(%s)", __FUNCTION__, expression); 1367 1368 ValueObjectSP expr_result; 1369 EvaluateExpressionOptions options; 1370 options.SetLanguage(lldb::eLanguageTypeC_plus_plus); 1371 // Perform the actual expression evaluation 1372 GetProcess()->GetTarget().EvaluateExpression(expression, frame_ptr, 1373 expr_result, options); 1374 1375 if (!expr_result) { 1376 if (log) 1377 log->Printf("%s: couldn't evaluate expression.", __FUNCTION__); 1378 return false; 1379 } 1380 1381 // The result of the expression is invalid 1382 if (!expr_result->GetError().Success()) { 1383 Error err = expr_result->GetError(); 1384 if (err.GetError() == UserExpression::kNoResult) // Expression returned 1385 // void, so this is 1386 // actually a success 1387 { 1388 if (log) 1389 log->Printf("%s - expression returned void.", __FUNCTION__); 1390 1391 result = nullptr; 1392 return true; 1393 } 1394 1395 if (log) 1396 log->Printf("%s - error evaluating expression result: %s", __FUNCTION__, 1397 err.AsCString()); 1398 return false; 1399 } 1400 1401 bool success = false; 1402 *result = expr_result->GetValueAsUnsigned( 1403 0, &success); // We only read the result as an uint32_t. 1404 1405 if (!success) { 1406 if (log) 1407 log->Printf("%s - couldn't convert expression result to uint32_t", 1408 __FUNCTION__); 1409 return false; 1410 } 1411 1412 return true; 1413 } 1414 1415 namespace { 1416 // Used to index expression format strings 1417 enum ExpressionStrings { 1418 eExprGetOffsetPtr = 0, 1419 eExprAllocGetType, 1420 eExprTypeDimX, 1421 eExprTypeDimY, 1422 eExprTypeDimZ, 1423 eExprTypeElemPtr, 1424 eExprElementType, 1425 eExprElementKind, 1426 eExprElementVec, 1427 eExprElementFieldCount, 1428 eExprSubelementsId, 1429 eExprSubelementsName, 1430 eExprSubelementsArrSize, 1431 1432 _eExprLast // keep at the end, implicit size of the array runtimeExpressions 1433 }; 1434 1435 // max length of an expanded expression 1436 const int jit_max_expr_size = 512; 1437 1438 // Retrieve the string to JIT for the given expression 1439 const char *JITTemplate(ExpressionStrings e) { 1440 // Format strings containing the expressions we may need to evaluate. 1441 static std::array<const char *, _eExprLast> runtimeExpressions = { 1442 {// Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap) 1443 "(int*)_" 1444 "Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocation" 1445 "CubemapFace" 1446 "(0x%" PRIx64 ", %" PRIu32 ", %" PRIu32 ", %" PRIu32 ", 0, 0)", 1447 1448 // Type* rsaAllocationGetType(Context*, Allocation*) 1449 "(void*)rsaAllocationGetType(0x%" PRIx64 ", 0x%" PRIx64 ")", 1450 1451 // rsaTypeGetNativeData(Context*, Type*, void* typeData, size) 1452 // Pack the data in the following way mHal.state.dimX; mHal.state.dimY; 1453 // mHal.state.dimZ; 1454 // mHal.state.lodCount; mHal.state.faces; mElement; into typeData 1455 // Need to specify 32 or 64 bit for uint_t since this differs between 1456 // devices 1457 "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64 1458 ", 0x%" PRIx64 ", data, 6); data[0]", // X dim 1459 "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64 1460 ", 0x%" PRIx64 ", data, 6); data[1]", // Y dim 1461 "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64 1462 ", 0x%" PRIx64 ", data, 6); data[2]", // Z dim 1463 "uint%" PRIu32 "_t data[6]; (void*)rsaTypeGetNativeData(0x%" PRIx64 1464 ", 0x%" PRIx64 ", data, 6); data[5]", // Element ptr 1465 1466 // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size) 1467 // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into 1468 // elemData 1469 "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64 1470 ", 0x%" PRIx64 ", data, 5); data[0]", // Type 1471 "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64 1472 ", 0x%" PRIx64 ", data, 5); data[1]", // Kind 1473 "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64 1474 ", 0x%" PRIx64 ", data, 5); data[3]", // Vector Size 1475 "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%" PRIx64 1476 ", 0x%" PRIx64 ", data, 5); data[4]", // Field Count 1477 1478 // rsaElementGetSubElements(RsContext con, RsElement elem, uintptr_t 1479 // *ids, const char **names, 1480 // size_t *arraySizes, uint32_t dataSize) 1481 // Needed for Allocations of structs to gather details about 1482 // fields/Subelements 1483 // Element* of field 1484 "void* ids[%" PRIu32 "]; const char* names[%" PRIu32 1485 "]; size_t arr_size[%" PRIu32 "];" 1486 "(void*)rsaElementGetSubElements(0x%" PRIx64 ", 0x%" PRIx64 1487 ", ids, names, arr_size, %" PRIu32 "); ids[%" PRIu32 "]", 1488 1489 // Name of field 1490 "void* ids[%" PRIu32 "]; const char* names[%" PRIu32 1491 "]; size_t arr_size[%" PRIu32 "];" 1492 "(void*)rsaElementGetSubElements(0x%" PRIx64 ", 0x%" PRIx64 1493 ", ids, names, arr_size, %" PRIu32 "); names[%" PRIu32 "]", 1494 1495 // Array size of field 1496 "void* ids[%" PRIu32 "]; const char* names[%" PRIu32 1497 "]; size_t arr_size[%" PRIu32 "];" 1498 "(void*)rsaElementGetSubElements(0x%" PRIx64 ", 0x%" PRIx64 1499 ", ids, names, arr_size, %" PRIu32 "); arr_size[%" PRIu32 "]"}}; 1500 1501 return runtimeExpressions[e]; 1502 } 1503 } // end of the anonymous namespace 1504 1505 // JITs the RS runtime for the internal data pointer of an allocation. 1506 // Is passed x,y,z coordinates for the pointer to a specific element. 1507 // Then sets the data_ptr member in Allocation with the result. 1508 // Returns true on success, false otherwise 1509 bool RenderScriptRuntime::JITDataPointer(AllocationDetails *allocation, 1510 StackFrame *frame_ptr, uint32_t x, 1511 uint32_t y, uint32_t z) { 1512 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 1513 1514 if (!allocation->address.isValid()) { 1515 if (log) 1516 log->Printf("%s - failed to find allocation details.", __FUNCTION__); 1517 return false; 1518 } 1519 1520 const char *expr_cstr = JITTemplate(eExprGetOffsetPtr); 1521 char buffer[jit_max_expr_size]; 1522 1523 int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr, 1524 *allocation->address.get(), x, y, z); 1525 if (chars_written < 0) { 1526 if (log) 1527 log->Printf("%s - encoding error in snprintf().", __FUNCTION__); 1528 return false; 1529 } else if (chars_written >= jit_max_expr_size) { 1530 if (log) 1531 log->Printf("%s - expression too long.", __FUNCTION__); 1532 return false; 1533 } 1534 1535 uint64_t result = 0; 1536 if (!EvalRSExpression(buffer, frame_ptr, &result)) 1537 return false; 1538 1539 addr_t mem_ptr = static_cast<lldb::addr_t>(result); 1540 allocation->data_ptr = mem_ptr; 1541 1542 return true; 1543 } 1544 1545 // JITs the RS runtime for the internal pointer to the RS Type of an allocation 1546 // Then sets the type_ptr member in Allocation with the result. 1547 // Returns true on success, false otherwise 1548 bool RenderScriptRuntime::JITTypePointer(AllocationDetails *allocation, 1549 StackFrame *frame_ptr) { 1550 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 1551 1552 if (!allocation->address.isValid() || !allocation->context.isValid()) { 1553 if (log) 1554 log->Printf("%s - failed to find allocation details.", __FUNCTION__); 1555 return false; 1556 } 1557 1558 const char *expr_cstr = JITTemplate(eExprAllocGetType); 1559 char buffer[jit_max_expr_size]; 1560 1561 int chars_written = 1562 snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->context.get(), 1563 *allocation->address.get()); 1564 if (chars_written < 0) { 1565 if (log) 1566 log->Printf("%s - encoding error in snprintf().", __FUNCTION__); 1567 return false; 1568 } else if (chars_written >= jit_max_expr_size) { 1569 if (log) 1570 log->Printf("%s - expression too long.", __FUNCTION__); 1571 return false; 1572 } 1573 1574 uint64_t result = 0; 1575 if (!EvalRSExpression(buffer, frame_ptr, &result)) 1576 return false; 1577 1578 addr_t type_ptr = static_cast<lldb::addr_t>(result); 1579 allocation->type_ptr = type_ptr; 1580 1581 return true; 1582 } 1583 1584 // JITs the RS runtime for information about the dimensions and type of an 1585 // allocation 1586 // Then sets dimension and element_ptr members in Allocation with the result. 1587 // Returns true on success, false otherwise 1588 bool RenderScriptRuntime::JITTypePacked(AllocationDetails *allocation, 1589 StackFrame *frame_ptr) { 1590 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 1591 1592 if (!allocation->type_ptr.isValid() || !allocation->context.isValid()) { 1593 if (log) 1594 log->Printf("%s - Failed to find allocation details.", __FUNCTION__); 1595 return false; 1596 } 1597 1598 // Expression is different depending on if device is 32 or 64 bit 1599 uint32_t archByteSize = 1600 GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize(); 1601 const uint32_t bits = archByteSize == 4 ? 32 : 64; 1602 1603 // We want 4 elements from packed data 1604 const uint32_t num_exprs = 4; 1605 assert(num_exprs == (eExprTypeElemPtr - eExprTypeDimX + 1) && 1606 "Invalid number of expressions"); 1607 1608 char buffer[num_exprs][jit_max_expr_size]; 1609 uint64_t results[num_exprs]; 1610 1611 for (uint32_t i = 0; i < num_exprs; ++i) { 1612 const char *expr_cstr = JITTemplate(ExpressionStrings(eExprTypeDimX + i)); 1613 int chars_written = 1614 snprintf(buffer[i], jit_max_expr_size, expr_cstr, bits, 1615 *allocation->context.get(), *allocation->type_ptr.get()); 1616 if (chars_written < 0) { 1617 if (log) 1618 log->Printf("%s - encoding error in snprintf().", __FUNCTION__); 1619 return false; 1620 } else if (chars_written >= jit_max_expr_size) { 1621 if (log) 1622 log->Printf("%s - expression too long.", __FUNCTION__); 1623 return false; 1624 } 1625 1626 // Perform expression evaluation 1627 if (!EvalRSExpression(buffer[i], frame_ptr, &results[i])) 1628 return false; 1629 } 1630 1631 // Assign results to allocation members 1632 AllocationDetails::Dimension dims; 1633 dims.dim_1 = static_cast<uint32_t>(results[0]); 1634 dims.dim_2 = static_cast<uint32_t>(results[1]); 1635 dims.dim_3 = static_cast<uint32_t>(results[2]); 1636 allocation->dimension = dims; 1637 1638 addr_t elem_ptr = static_cast<lldb::addr_t>(results[3]); 1639 allocation->element.element_ptr = elem_ptr; 1640 1641 if (log) 1642 log->Printf("%s - dims (%" PRIu32 ", %" PRIu32 ", %" PRIu32 1643 ") Element*: 0x%" PRIx64 ".", 1644 __FUNCTION__, dims.dim_1, dims.dim_2, dims.dim_3, elem_ptr); 1645 1646 return true; 1647 } 1648 1649 // JITs the RS runtime for information about the Element of an allocation 1650 // Then sets type, type_vec_size, field_count and type_kind members in Element 1651 // with the result. 1652 // Returns true on success, false otherwise 1653 bool RenderScriptRuntime::JITElementPacked(Element &elem, 1654 const lldb::addr_t context, 1655 StackFrame *frame_ptr) { 1656 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 1657 1658 if (!elem.element_ptr.isValid()) { 1659 if (log) 1660 log->Printf("%s - failed to find allocation details.", __FUNCTION__); 1661 return false; 1662 } 1663 1664 // We want 4 elements from packed data 1665 const uint32_t num_exprs = 4; 1666 assert(num_exprs == (eExprElementFieldCount - eExprElementType + 1) && 1667 "Invalid number of expressions"); 1668 1669 char buffer[num_exprs][jit_max_expr_size]; 1670 uint64_t results[num_exprs]; 1671 1672 for (uint32_t i = 0; i < num_exprs; i++) { 1673 const char *expr_cstr = 1674 JITTemplate(ExpressionStrings(eExprElementType + i)); 1675 int chars_written = snprintf(buffer[i], jit_max_expr_size, expr_cstr, 1676 context, *elem.element_ptr.get()); 1677 if (chars_written < 0) { 1678 if (log) 1679 log->Printf("%s - encoding error in snprintf().", __FUNCTION__); 1680 return false; 1681 } else if (chars_written >= jit_max_expr_size) { 1682 if (log) 1683 log->Printf("%s - expression too long.", __FUNCTION__); 1684 return false; 1685 } 1686 1687 // Perform expression evaluation 1688 if (!EvalRSExpression(buffer[i], frame_ptr, &results[i])) 1689 return false; 1690 } 1691 1692 // Assign results to allocation members 1693 elem.type = static_cast<RenderScriptRuntime::Element::DataType>(results[0]); 1694 elem.type_kind = 1695 static_cast<RenderScriptRuntime::Element::DataKind>(results[1]); 1696 elem.type_vec_size = static_cast<uint32_t>(results[2]); 1697 elem.field_count = static_cast<uint32_t>(results[3]); 1698 1699 if (log) 1700 log->Printf("%s - data type %" PRIu32 ", pixel type %" PRIu32 1701 ", vector size %" PRIu32 ", field count %" PRIu32, 1702 __FUNCTION__, *elem.type.get(), *elem.type_kind.get(), 1703 *elem.type_vec_size.get(), *elem.field_count.get()); 1704 1705 // If this Element has subelements then JIT rsaElementGetSubElements() for 1706 // details about its fields 1707 if (*elem.field_count.get() > 0 && !JITSubelements(elem, context, frame_ptr)) 1708 return false; 1709 1710 return true; 1711 } 1712 1713 // JITs the RS runtime for information about the subelements/fields of a struct 1714 // allocation 1715 // This is necessary for infering the struct type so we can pretty print the 1716 // allocation's contents. 1717 // Returns true on success, false otherwise 1718 bool RenderScriptRuntime::JITSubelements(Element &elem, 1719 const lldb::addr_t context, 1720 StackFrame *frame_ptr) { 1721 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 1722 1723 if (!elem.element_ptr.isValid() || !elem.field_count.isValid()) { 1724 if (log) 1725 log->Printf("%s - failed to find allocation details.", __FUNCTION__); 1726 return false; 1727 } 1728 1729 const short num_exprs = 3; 1730 assert(num_exprs == (eExprSubelementsArrSize - eExprSubelementsId + 1) && 1731 "Invalid number of expressions"); 1732 1733 char expr_buffer[jit_max_expr_size]; 1734 uint64_t results; 1735 1736 // Iterate over struct fields. 1737 const uint32_t field_count = *elem.field_count.get(); 1738 for (uint32_t field_index = 0; field_index < field_count; ++field_index) { 1739 Element child; 1740 for (uint32_t expr_index = 0; expr_index < num_exprs; ++expr_index) { 1741 const char *expr_cstr = 1742 JITTemplate(ExpressionStrings(eExprSubelementsId + expr_index)); 1743 int chars_written = 1744 snprintf(expr_buffer, jit_max_expr_size, expr_cstr, field_count, 1745 field_count, field_count, context, *elem.element_ptr.get(), 1746 field_count, field_index); 1747 if (chars_written < 0) { 1748 if (log) 1749 log->Printf("%s - encoding error in snprintf().", __FUNCTION__); 1750 return false; 1751 } else if (chars_written >= jit_max_expr_size) { 1752 if (log) 1753 log->Printf("%s - expression too long.", __FUNCTION__); 1754 return false; 1755 } 1756 1757 // Perform expression evaluation 1758 if (!EvalRSExpression(expr_buffer, frame_ptr, &results)) 1759 return false; 1760 1761 if (log) 1762 log->Printf("%s - expr result 0x%" PRIx64 ".", __FUNCTION__, results); 1763 1764 switch (expr_index) { 1765 case 0: // Element* of child 1766 child.element_ptr = static_cast<addr_t>(results); 1767 break; 1768 case 1: // Name of child 1769 { 1770 lldb::addr_t address = static_cast<addr_t>(results); 1771 Error err; 1772 std::string name; 1773 GetProcess()->ReadCStringFromMemory(address, name, err); 1774 if (!err.Fail()) 1775 child.type_name = ConstString(name); 1776 else { 1777 if (log) 1778 log->Printf("%s - warning: Couldn't read field name.", 1779 __FUNCTION__); 1780 } 1781 break; 1782 } 1783 case 2: // Array size of child 1784 child.array_size = static_cast<uint32_t>(results); 1785 break; 1786 } 1787 } 1788 1789 // We need to recursively JIT each Element field of the struct since 1790 // structs can be nested inside structs. 1791 if (!JITElementPacked(child, context, frame_ptr)) 1792 return false; 1793 elem.children.push_back(child); 1794 } 1795 1796 // Try to infer the name of the struct type so we can pretty print the 1797 // allocation contents. 1798 FindStructTypeName(elem, frame_ptr); 1799 1800 return true; 1801 } 1802 1803 // JITs the RS runtime for the address of the last element in the allocation. 1804 // The `elem_size` parameter represents the size of a single element, including 1805 // padding. 1806 // Which is needed as an offset from the last element pointer. 1807 // Using this offset minus the starting address we can calculate the size of the 1808 // allocation. 1809 // Returns true on success, false otherwise 1810 bool RenderScriptRuntime::JITAllocationSize(AllocationDetails *allocation, 1811 StackFrame *frame_ptr) { 1812 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 1813 1814 if (!allocation->address.isValid() || !allocation->dimension.isValid() || 1815 !allocation->data_ptr.isValid() || 1816 !allocation->element.datum_size.isValid()) { 1817 if (log) 1818 log->Printf("%s - failed to find allocation details.", __FUNCTION__); 1819 return false; 1820 } 1821 1822 // Find dimensions 1823 uint32_t dim_x = allocation->dimension.get()->dim_1; 1824 uint32_t dim_y = allocation->dimension.get()->dim_2; 1825 uint32_t dim_z = allocation->dimension.get()->dim_3; 1826 1827 // Our plan of jitting the last element address doesn't seem to work for 1828 // struct Allocations 1829 // Instead try to infer the size ourselves without any inter element padding. 1830 if (allocation->element.children.size() > 0) { 1831 if (dim_x == 0) 1832 dim_x = 1; 1833 if (dim_y == 0) 1834 dim_y = 1; 1835 if (dim_z == 0) 1836 dim_z = 1; 1837 1838 allocation->size = 1839 dim_x * dim_y * dim_z * *allocation->element.datum_size.get(); 1840 1841 if (log) 1842 log->Printf("%s - inferred size of struct allocation %" PRIu32 ".", 1843 __FUNCTION__, *allocation->size.get()); 1844 return true; 1845 } 1846 1847 const char *expr_cstr = JITTemplate(eExprGetOffsetPtr); 1848 char buffer[jit_max_expr_size]; 1849 1850 // Calculate last element 1851 dim_x = dim_x == 0 ? 0 : dim_x - 1; 1852 dim_y = dim_y == 0 ? 0 : dim_y - 1; 1853 dim_z = dim_z == 0 ? 0 : dim_z - 1; 1854 1855 int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr, 1856 *allocation->address.get(), dim_x, dim_y, dim_z); 1857 if (chars_written < 0) { 1858 if (log) 1859 log->Printf("%s - encoding error in snprintf().", __FUNCTION__); 1860 return false; 1861 } else if (chars_written >= jit_max_expr_size) { 1862 if (log) 1863 log->Printf("%s - expression too long.", __FUNCTION__); 1864 return false; 1865 } 1866 1867 uint64_t result = 0; 1868 if (!EvalRSExpression(buffer, frame_ptr, &result)) 1869 return false; 1870 1871 addr_t mem_ptr = static_cast<lldb::addr_t>(result); 1872 // Find pointer to last element and add on size of an element 1873 allocation->size = 1874 static_cast<uint32_t>(mem_ptr - *allocation->data_ptr.get()) + 1875 *allocation->element.datum_size.get(); 1876 1877 return true; 1878 } 1879 1880 // JITs the RS runtime for information about the stride between rows in the 1881 // allocation. 1882 // This is done to detect padding, since allocated memory is 16-byte aligned. 1883 // Returns true on success, false otherwise 1884 bool RenderScriptRuntime::JITAllocationStride(AllocationDetails *allocation, 1885 StackFrame *frame_ptr) { 1886 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 1887 1888 if (!allocation->address.isValid() || !allocation->data_ptr.isValid()) { 1889 if (log) 1890 log->Printf("%s - failed to find allocation details.", __FUNCTION__); 1891 return false; 1892 } 1893 1894 const char *expr_cstr = JITTemplate(eExprGetOffsetPtr); 1895 char buffer[jit_max_expr_size]; 1896 1897 int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr, 1898 *allocation->address.get(), 0, 1, 0); 1899 if (chars_written < 0) { 1900 if (log) 1901 log->Printf("%s - encoding error in snprintf().", __FUNCTION__); 1902 return false; 1903 } else if (chars_written >= jit_max_expr_size) { 1904 if (log) 1905 log->Printf("%s - expression too long.", __FUNCTION__); 1906 return false; 1907 } 1908 1909 uint64_t result = 0; 1910 if (!EvalRSExpression(buffer, frame_ptr, &result)) 1911 return false; 1912 1913 addr_t mem_ptr = static_cast<lldb::addr_t>(result); 1914 allocation->stride = 1915 static_cast<uint32_t>(mem_ptr - *allocation->data_ptr.get()); 1916 1917 return true; 1918 } 1919 1920 // JIT all the current runtime info regarding an allocation 1921 bool RenderScriptRuntime::RefreshAllocation(AllocationDetails *allocation, 1922 StackFrame *frame_ptr) { 1923 // GetOffsetPointer() 1924 if (!JITDataPointer(allocation, frame_ptr)) 1925 return false; 1926 1927 // rsaAllocationGetType() 1928 if (!JITTypePointer(allocation, frame_ptr)) 1929 return false; 1930 1931 // rsaTypeGetNativeData() 1932 if (!JITTypePacked(allocation, frame_ptr)) 1933 return false; 1934 1935 // rsaElementGetNativeData() 1936 if (!JITElementPacked(allocation->element, *allocation->context.get(), 1937 frame_ptr)) 1938 return false; 1939 1940 // Sets the datum_size member in Element 1941 SetElementSize(allocation->element); 1942 1943 // Use GetOffsetPointer() to infer size of the allocation 1944 if (!JITAllocationSize(allocation, frame_ptr)) 1945 return false; 1946 1947 return true; 1948 } 1949 1950 // Function attempts to set the type_name member of the paramaterised Element 1951 // object. 1952 // This string should be the name of the struct type the Element represents. 1953 // We need this string for pretty printing the Element to users. 1954 void RenderScriptRuntime::FindStructTypeName(Element &elem, 1955 StackFrame *frame_ptr) { 1956 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 1957 1958 if (!elem.type_name.IsEmpty()) // Name already set 1959 return; 1960 else 1961 elem.type_name = Element::GetFallbackStructName(); // Default type name if 1962 // we don't succeed 1963 1964 // Find all the global variables from the script rs modules 1965 VariableList variable_list; 1966 for (auto module_sp : m_rsmodules) 1967 module_sp->m_module->FindGlobalVariables( 1968 RegularExpression(llvm::StringRef(".")), true, UINT32_MAX, 1969 variable_list); 1970 1971 // Iterate over all the global variables looking for one with a matching type 1972 // to the Element. 1973 // We make the assumption a match exists since there needs to be a global 1974 // variable to reflect the 1975 // struct type back into java host code. 1976 for (uint32_t var_index = 0; var_index < variable_list.GetSize(); 1977 ++var_index) { 1978 const VariableSP var_sp(variable_list.GetVariableAtIndex(var_index)); 1979 if (!var_sp) 1980 continue; 1981 1982 ValueObjectSP valobj_sp = ValueObjectVariable::Create(frame_ptr, var_sp); 1983 if (!valobj_sp) 1984 continue; 1985 1986 // Find the number of variable fields. 1987 // If it has no fields, or more fields than our Element, then it can't be 1988 // the struct we're looking for. 1989 // Don't check for equality since RS can add extra struct members for 1990 // padding. 1991 size_t num_children = valobj_sp->GetNumChildren(); 1992 if (num_children > elem.children.size() || num_children == 0) 1993 continue; 1994 1995 // Iterate over children looking for members with matching field names. 1996 // If all the field names match, this is likely the struct we want. 1997 // 1998 // TODO: This could be made more robust by also checking children data 1999 // sizes, or array size 2000 bool found = true; 2001 for (size_t child_index = 0; child_index < num_children; ++child_index) { 2002 ValueObjectSP child = valobj_sp->GetChildAtIndex(child_index, true); 2003 if (!child || 2004 (child->GetName() != elem.children[child_index].type_name)) { 2005 found = false; 2006 break; 2007 } 2008 } 2009 2010 // RS can add extra struct members for padding in the format 2011 // '#rs_padding_[0-9]+' 2012 if (found && num_children < elem.children.size()) { 2013 const uint32_t size_diff = elem.children.size() - num_children; 2014 if (log) 2015 log->Printf("%s - %" PRIu32 " padding struct entries", __FUNCTION__, 2016 size_diff); 2017 2018 for (uint32_t padding_index = 0; padding_index < size_diff; 2019 ++padding_index) { 2020 const ConstString &name = 2021 elem.children[num_children + padding_index].type_name; 2022 if (strcmp(name.AsCString(), "#rs_padding") < 0) 2023 found = false; 2024 } 2025 } 2026 2027 // We've found a global var with matching type 2028 if (found) { 2029 // Dereference since our Element type isn't a pointer. 2030 if (valobj_sp->IsPointerType()) { 2031 Error err; 2032 ValueObjectSP deref_valobj = valobj_sp->Dereference(err); 2033 if (!err.Fail()) 2034 valobj_sp = deref_valobj; 2035 } 2036 2037 // Save name of variable in Element. 2038 elem.type_name = valobj_sp->GetTypeName(); 2039 if (log) 2040 log->Printf("%s - element name set to %s", __FUNCTION__, 2041 elem.type_name.AsCString()); 2042 2043 return; 2044 } 2045 } 2046 } 2047 2048 // Function sets the datum_size member of Element. Representing the size of a 2049 // single instance including padding. 2050 // Assumes the relevant allocation information has already been jitted. 2051 void RenderScriptRuntime::SetElementSize(Element &elem) { 2052 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 2053 const Element::DataType type = *elem.type.get(); 2054 assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT && 2055 "Invalid allocation type"); 2056 2057 const uint32_t vec_size = *elem.type_vec_size.get(); 2058 uint32_t data_size = 0; 2059 uint32_t padding = 0; 2060 2061 // Element is of a struct type, calculate size recursively. 2062 if ((type == Element::RS_TYPE_NONE) && (elem.children.size() > 0)) { 2063 for (Element &child : elem.children) { 2064 SetElementSize(child); 2065 const uint32_t array_size = 2066 child.array_size.isValid() ? *child.array_size.get() : 1; 2067 data_size += *child.datum_size.get() * array_size; 2068 } 2069 } 2070 // These have been packed already 2071 else if (type == Element::RS_TYPE_UNSIGNED_5_6_5 || 2072 type == Element::RS_TYPE_UNSIGNED_5_5_5_1 || 2073 type == Element::RS_TYPE_UNSIGNED_4_4_4_4) { 2074 data_size = AllocationDetails::RSTypeToFormat[type][eElementSize]; 2075 } else if (type < Element::RS_TYPE_ELEMENT) { 2076 data_size = 2077 vec_size * AllocationDetails::RSTypeToFormat[type][eElementSize]; 2078 if (vec_size == 3) 2079 padding = AllocationDetails::RSTypeToFormat[type][eElementSize]; 2080 } else 2081 data_size = 2082 GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize(); 2083 2084 elem.padding = padding; 2085 elem.datum_size = data_size + padding; 2086 if (log) 2087 log->Printf("%s - element size set to %" PRIu32, __FUNCTION__, 2088 data_size + padding); 2089 } 2090 2091 // Given an allocation, this function copies the allocation contents from device 2092 // into a buffer on the heap. 2093 // Returning a shared pointer to the buffer containing the data. 2094 std::shared_ptr<uint8_t> 2095 RenderScriptRuntime::GetAllocationData(AllocationDetails *allocation, 2096 StackFrame *frame_ptr) { 2097 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 2098 2099 // JIT all the allocation details 2100 if (allocation->shouldRefresh()) { 2101 if (log) 2102 log->Printf("%s - allocation details not calculated yet, jitting info", 2103 __FUNCTION__); 2104 2105 if (!RefreshAllocation(allocation, frame_ptr)) { 2106 if (log) 2107 log->Printf("%s - couldn't JIT allocation details", __FUNCTION__); 2108 return nullptr; 2109 } 2110 } 2111 2112 assert(allocation->data_ptr.isValid() && allocation->element.type.isValid() && 2113 allocation->element.type_vec_size.isValid() && 2114 allocation->size.isValid() && "Allocation information not available"); 2115 2116 // Allocate a buffer to copy data into 2117 const uint32_t size = *allocation->size.get(); 2118 std::shared_ptr<uint8_t> buffer(new uint8_t[size]); 2119 if (!buffer) { 2120 if (log) 2121 log->Printf("%s - couldn't allocate a %" PRIu32 " byte buffer", 2122 __FUNCTION__, size); 2123 return nullptr; 2124 } 2125 2126 // Read the inferior memory 2127 Error error; 2128 lldb::addr_t data_ptr = *allocation->data_ptr.get(); 2129 GetProcess()->ReadMemory(data_ptr, buffer.get(), size, error); 2130 if (error.Fail()) { 2131 if (log) 2132 log->Printf("%s - '%s' Couldn't read %" PRIu32 2133 " bytes of allocation data from 0x%" PRIx64, 2134 __FUNCTION__, error.AsCString(), size, data_ptr); 2135 return nullptr; 2136 } 2137 2138 return buffer; 2139 } 2140 2141 // Function copies data from a binary file into an allocation. 2142 // There is a header at the start of the file, FileHeader, before the data 2143 // content itself. 2144 // Information from this header is used to display warnings to the user about 2145 // incompatibilities 2146 bool RenderScriptRuntime::LoadAllocation(Stream &strm, const uint32_t alloc_id, 2147 const char *filename, 2148 StackFrame *frame_ptr) { 2149 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 2150 2151 // Find allocation with the given id 2152 AllocationDetails *alloc = FindAllocByID(strm, alloc_id); 2153 if (!alloc) 2154 return false; 2155 2156 if (log) 2157 log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__, 2158 *alloc->address.get()); 2159 2160 // JIT all the allocation details 2161 if (alloc->shouldRefresh()) { 2162 if (log) 2163 log->Printf("%s - allocation details not calculated yet, jitting info.", 2164 __FUNCTION__); 2165 2166 if (!RefreshAllocation(alloc, frame_ptr)) { 2167 if (log) 2168 log->Printf("%s - couldn't JIT allocation details", __FUNCTION__); 2169 return false; 2170 } 2171 } 2172 2173 assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() && 2174 alloc->element.type_vec_size.isValid() && alloc->size.isValid() && 2175 alloc->element.datum_size.isValid() && 2176 "Allocation information not available"); 2177 2178 // Check we can read from file 2179 FileSpec file(filename, true); 2180 if (!file.Exists()) { 2181 strm.Printf("Error: File %s does not exist", filename); 2182 strm.EOL(); 2183 return false; 2184 } 2185 2186 if (!file.Readable()) { 2187 strm.Printf("Error: File %s does not have readable permissions", filename); 2188 strm.EOL(); 2189 return false; 2190 } 2191 2192 // Read file into data buffer 2193 DataBufferSP data_sp(file.ReadFileContents()); 2194 2195 // Cast start of buffer to FileHeader and use pointer to read metadata 2196 void *file_buffer = data_sp->GetBytes(); 2197 if (file_buffer == nullptr || 2198 data_sp->GetByteSize() < (sizeof(AllocationDetails::FileHeader) + 2199 sizeof(AllocationDetails::ElementHeader))) { 2200 strm.Printf("Error: File %s does not contain enough data for header", 2201 filename); 2202 strm.EOL(); 2203 return false; 2204 } 2205 const AllocationDetails::FileHeader *file_header = 2206 static_cast<AllocationDetails::FileHeader *>(file_buffer); 2207 2208 // Check file starts with ascii characters "RSAD" 2209 if (memcmp(file_header->ident, "RSAD", 4)) { 2210 strm.Printf("Error: File doesn't contain identifier for an RS allocation " 2211 "dump. Are you sure this is the correct file?"); 2212 strm.EOL(); 2213 return false; 2214 } 2215 2216 // Look at the type of the root element in the header 2217 AllocationDetails::ElementHeader root_element_header; 2218 memcpy(&root_element_header, static_cast<uint8_t *>(file_buffer) + 2219 sizeof(AllocationDetails::FileHeader), 2220 sizeof(AllocationDetails::ElementHeader)); 2221 2222 if (log) 2223 log->Printf("%s - header type %" PRIu32 ", element size %" PRIu32, 2224 __FUNCTION__, root_element_header.type, 2225 root_element_header.element_size); 2226 2227 // Check if the target allocation and file both have the same number of bytes 2228 // for an Element 2229 if (*alloc->element.datum_size.get() != root_element_header.element_size) { 2230 strm.Printf("Warning: Mismatched Element sizes - file %" PRIu32 2231 " bytes, allocation %" PRIu32 " bytes", 2232 root_element_header.element_size, 2233 *alloc->element.datum_size.get()); 2234 strm.EOL(); 2235 } 2236 2237 // Check if the target allocation and file both have the same type 2238 const uint32_t alloc_type = static_cast<uint32_t>(*alloc->element.type.get()); 2239 const uint32_t file_type = root_element_header.type; 2240 2241 if (file_type > Element::RS_TYPE_FONT) { 2242 strm.Printf("Warning: File has unknown allocation type"); 2243 strm.EOL(); 2244 } else if (alloc_type != file_type) { 2245 // Enum value isn't monotonous, so doesn't always index RsDataTypeToString 2246 // array 2247 uint32_t printable_target_type_index = alloc_type; 2248 uint32_t printable_head_type_index = file_type; 2249 if (alloc_type >= Element::RS_TYPE_ELEMENT && 2250 alloc_type <= Element::RS_TYPE_FONT) 2251 printable_target_type_index = static_cast<Element::DataType>( 2252 (alloc_type - Element::RS_TYPE_ELEMENT) + 2253 Element::RS_TYPE_MATRIX_2X2 + 1); 2254 2255 if (file_type >= Element::RS_TYPE_ELEMENT && 2256 file_type <= Element::RS_TYPE_FONT) 2257 printable_head_type_index = static_cast<Element::DataType>( 2258 (file_type - Element::RS_TYPE_ELEMENT) + Element::RS_TYPE_MATRIX_2X2 + 2259 1); 2260 2261 const char *file_type_cstr = 2262 AllocationDetails::RsDataTypeToString[printable_head_type_index][0]; 2263 const char *target_type_cstr = 2264 AllocationDetails::RsDataTypeToString[printable_target_type_index][0]; 2265 2266 strm.Printf( 2267 "Warning: Mismatched Types - file '%s' type, allocation '%s' type", 2268 file_type_cstr, target_type_cstr); 2269 strm.EOL(); 2270 } 2271 2272 // Advance buffer past header 2273 file_buffer = static_cast<uint8_t *>(file_buffer) + file_header->hdr_size; 2274 2275 // Calculate size of allocation data in file 2276 size_t length = data_sp->GetByteSize() - file_header->hdr_size; 2277 2278 // Check if the target allocation and file both have the same total data size. 2279 const uint32_t alloc_size = *alloc->size.get(); 2280 if (alloc_size != length) { 2281 strm.Printf("Warning: Mismatched allocation sizes - file 0x%" PRIx64 2282 " bytes, allocation 0x%" PRIx32 " bytes", 2283 (uint64_t)length, alloc_size); 2284 strm.EOL(); 2285 length = alloc_size < length ? alloc_size 2286 : length; // Set length to copy to minimum 2287 } 2288 2289 // Copy file data from our buffer into the target allocation. 2290 lldb::addr_t alloc_data = *alloc->data_ptr.get(); 2291 Error error; 2292 size_t bytes_written = 2293 GetProcess()->WriteMemory(alloc_data, file_buffer, length, error); 2294 if (!error.Success() || bytes_written != length) { 2295 strm.Printf("Error: Couldn't write data to allocation %s", 2296 error.AsCString()); 2297 strm.EOL(); 2298 return false; 2299 } 2300 2301 strm.Printf("Contents of file '%s' read into allocation %" PRIu32, filename, 2302 alloc->id); 2303 strm.EOL(); 2304 2305 return true; 2306 } 2307 2308 // Function takes as parameters a byte buffer, which will eventually be written 2309 // to file as the element header, 2310 // an offset into that buffer, and an Element that will be saved into the buffer 2311 // at the parametrised offset. 2312 // Return value is the new offset after writing the element into the buffer. 2313 // Elements are saved to the file as the ElementHeader struct followed by 2314 // offsets to the structs of all the element's 2315 // children. 2316 size_t RenderScriptRuntime::PopulateElementHeaders( 2317 const std::shared_ptr<uint8_t> header_buffer, size_t offset, 2318 const Element &elem) { 2319 // File struct for an element header with all the relevant details copied from 2320 // elem. 2321 // We assume members are valid already. 2322 AllocationDetails::ElementHeader elem_header; 2323 elem_header.type = *elem.type.get(); 2324 elem_header.kind = *elem.type_kind.get(); 2325 elem_header.element_size = *elem.datum_size.get(); 2326 elem_header.vector_size = *elem.type_vec_size.get(); 2327 elem_header.array_size = 2328 elem.array_size.isValid() ? *elem.array_size.get() : 0; 2329 const size_t elem_header_size = sizeof(AllocationDetails::ElementHeader); 2330 2331 // Copy struct into buffer and advance offset 2332 // We assume that header_buffer has been checked for nullptr before this 2333 // method is called 2334 memcpy(header_buffer.get() + offset, &elem_header, elem_header_size); 2335 offset += elem_header_size; 2336 2337 // Starting offset of child ElementHeader struct 2338 size_t child_offset = 2339 offset + ((elem.children.size() + 1) * sizeof(uint32_t)); 2340 for (const RenderScriptRuntime::Element &child : elem.children) { 2341 // Recursively populate the buffer with the element header structs of 2342 // children. 2343 // Then save the offsets where they were set after the parent element 2344 // header. 2345 memcpy(header_buffer.get() + offset, &child_offset, sizeof(uint32_t)); 2346 offset += sizeof(uint32_t); 2347 2348 child_offset = PopulateElementHeaders(header_buffer, child_offset, child); 2349 } 2350 2351 // Zero indicates no more children 2352 memset(header_buffer.get() + offset, 0, sizeof(uint32_t)); 2353 2354 return child_offset; 2355 } 2356 2357 // Given an Element object this function returns the total size needed in the 2358 // file header to store the element's 2359 // details. 2360 // Taking into account the size of the element header struct, plus the offsets 2361 // to all the element's children. 2362 // Function is recursive so that the size of all ancestors is taken into 2363 // account. 2364 size_t RenderScriptRuntime::CalculateElementHeaderSize(const Element &elem) { 2365 size_t size = (elem.children.size() + 1) * 2366 sizeof(uint32_t); // Offsets to children plus zero terminator 2367 size += sizeof(AllocationDetails::ElementHeader); // Size of header struct 2368 // with type details 2369 2370 // Calculate recursively for all descendants 2371 for (const Element &child : elem.children) 2372 size += CalculateElementHeaderSize(child); 2373 2374 return size; 2375 } 2376 2377 // Function copies allocation contents into a binary file. 2378 // This file can then be loaded later into a different allocation. 2379 // There is a header, FileHeader, before the allocation data containing 2380 // meta-data. 2381 bool RenderScriptRuntime::SaveAllocation(Stream &strm, const uint32_t alloc_id, 2382 const char *filename, 2383 StackFrame *frame_ptr) { 2384 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 2385 2386 // Find allocation with the given id 2387 AllocationDetails *alloc = FindAllocByID(strm, alloc_id); 2388 if (!alloc) 2389 return false; 2390 2391 if (log) 2392 log->Printf("%s - found allocation 0x%" PRIx64 ".", __FUNCTION__, 2393 *alloc->address.get()); 2394 2395 // JIT all the allocation details 2396 if (alloc->shouldRefresh()) { 2397 if (log) 2398 log->Printf("%s - allocation details not calculated yet, jitting info.", 2399 __FUNCTION__); 2400 2401 if (!RefreshAllocation(alloc, frame_ptr)) { 2402 if (log) 2403 log->Printf("%s - couldn't JIT allocation details.", __FUNCTION__); 2404 return false; 2405 } 2406 } 2407 2408 assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() && 2409 alloc->element.type_vec_size.isValid() && 2410 alloc->element.datum_size.get() && 2411 alloc->element.type_kind.isValid() && alloc->dimension.isValid() && 2412 "Allocation information not available"); 2413 2414 // Check we can create writable file 2415 FileSpec file_spec(filename, true); 2416 File file(file_spec, File::eOpenOptionWrite | File::eOpenOptionCanCreate | 2417 File::eOpenOptionTruncate); 2418 if (!file) { 2419 strm.Printf("Error: Failed to open '%s' for writing", filename); 2420 strm.EOL(); 2421 return false; 2422 } 2423 2424 // Read allocation into buffer of heap memory 2425 const std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr); 2426 if (!buffer) { 2427 strm.Printf("Error: Couldn't read allocation data into buffer"); 2428 strm.EOL(); 2429 return false; 2430 } 2431 2432 // Create the file header 2433 AllocationDetails::FileHeader head; 2434 memcpy(head.ident, "RSAD", 4); 2435 head.dims[0] = static_cast<uint32_t>(alloc->dimension.get()->dim_1); 2436 head.dims[1] = static_cast<uint32_t>(alloc->dimension.get()->dim_2); 2437 head.dims[2] = static_cast<uint32_t>(alloc->dimension.get()->dim_3); 2438 2439 const size_t element_header_size = CalculateElementHeaderSize(alloc->element); 2440 assert((sizeof(AllocationDetails::FileHeader) + element_header_size) < 2441 UINT16_MAX && 2442 "Element header too large"); 2443 head.hdr_size = static_cast<uint16_t>(sizeof(AllocationDetails::FileHeader) + 2444 element_header_size); 2445 2446 // Write the file header 2447 size_t num_bytes = sizeof(AllocationDetails::FileHeader); 2448 if (log) 2449 log->Printf("%s - writing File Header, 0x%" PRIx64 " bytes", __FUNCTION__, 2450 (uint64_t)num_bytes); 2451 2452 Error err = file.Write(&head, num_bytes); 2453 if (!err.Success()) { 2454 strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), 2455 filename); 2456 strm.EOL(); 2457 return false; 2458 } 2459 2460 // Create the headers describing the element type of the allocation. 2461 std::shared_ptr<uint8_t> element_header_buffer( 2462 new uint8_t[element_header_size]); 2463 if (element_header_buffer == nullptr) { 2464 strm.Printf("Internal Error: Couldn't allocate %" PRIu64 2465 " bytes on the heap", 2466 (uint64_t)element_header_size); 2467 strm.EOL(); 2468 return false; 2469 } 2470 2471 PopulateElementHeaders(element_header_buffer, 0, alloc->element); 2472 2473 // Write headers for allocation element type to file 2474 num_bytes = element_header_size; 2475 if (log) 2476 log->Printf("%s - writing element headers, 0x%" PRIx64 " bytes.", 2477 __FUNCTION__, (uint64_t)num_bytes); 2478 2479 err = file.Write(element_header_buffer.get(), num_bytes); 2480 if (!err.Success()) { 2481 strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), 2482 filename); 2483 strm.EOL(); 2484 return false; 2485 } 2486 2487 // Write allocation data to file 2488 num_bytes = static_cast<size_t>(*alloc->size.get()); 2489 if (log) 2490 log->Printf("%s - writing 0x%" PRIx64 " bytes", __FUNCTION__, 2491 (uint64_t)num_bytes); 2492 2493 err = file.Write(buffer.get(), num_bytes); 2494 if (!err.Success()) { 2495 strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), 2496 filename); 2497 strm.EOL(); 2498 return false; 2499 } 2500 2501 strm.Printf("Allocation written to file '%s'", filename); 2502 strm.EOL(); 2503 return true; 2504 } 2505 2506 bool RenderScriptRuntime::LoadModule(const lldb::ModuleSP &module_sp) { 2507 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 2508 2509 if (module_sp) { 2510 for (const auto &rs_module : m_rsmodules) { 2511 if (rs_module->m_module == module_sp) { 2512 // Check if the user has enabled automatically breaking on 2513 // all RS kernels. 2514 if (m_breakAllKernels) 2515 BreakOnModuleKernels(rs_module); 2516 2517 return false; 2518 } 2519 } 2520 bool module_loaded = false; 2521 switch (GetModuleKind(module_sp)) { 2522 case eModuleKindKernelObj: { 2523 RSModuleDescriptorSP module_desc; 2524 module_desc.reset(new RSModuleDescriptor(module_sp)); 2525 if (module_desc->ParseRSInfo()) { 2526 m_rsmodules.push_back(module_desc); 2527 module_loaded = true; 2528 } 2529 if (module_loaded) { 2530 FixupScriptDetails(module_desc); 2531 } 2532 break; 2533 } 2534 case eModuleKindDriver: { 2535 if (!m_libRSDriver) { 2536 m_libRSDriver = module_sp; 2537 LoadRuntimeHooks(m_libRSDriver, RenderScriptRuntime::eModuleKindDriver); 2538 } 2539 break; 2540 } 2541 case eModuleKindImpl: { 2542 m_libRSCpuRef = module_sp; 2543 break; 2544 } 2545 case eModuleKindLibRS: { 2546 if (!m_libRS) { 2547 m_libRS = module_sp; 2548 static ConstString gDbgPresentStr("gDebuggerPresent"); 2549 const Symbol *debug_present = m_libRS->FindFirstSymbolWithNameAndType( 2550 gDbgPresentStr, eSymbolTypeData); 2551 if (debug_present) { 2552 Error error; 2553 uint32_t flag = 0x00000001U; 2554 Target &target = GetProcess()->GetTarget(); 2555 addr_t addr = debug_present->GetLoadAddress(&target); 2556 GetProcess()->WriteMemory(addr, &flag, sizeof(flag), error); 2557 if (error.Success()) { 2558 if (log) 2559 log->Printf("%s - debugger present flag set on debugee.", 2560 __FUNCTION__); 2561 2562 m_debuggerPresentFlagged = true; 2563 } else if (log) { 2564 log->Printf("%s - error writing debugger present flags '%s' ", 2565 __FUNCTION__, error.AsCString()); 2566 } 2567 } else if (log) { 2568 log->Printf( 2569 "%s - error writing debugger present flags - symbol not found", 2570 __FUNCTION__); 2571 } 2572 } 2573 break; 2574 } 2575 default: 2576 break; 2577 } 2578 if (module_loaded) 2579 Update(); 2580 return module_loaded; 2581 } 2582 return false; 2583 } 2584 2585 void RenderScriptRuntime::Update() { 2586 if (m_rsmodules.size() > 0) { 2587 if (!m_initiated) { 2588 Initiate(); 2589 } 2590 } 2591 } 2592 2593 bool RSModuleDescriptor::ParsePragmaCount(llvm::StringRef *lines, 2594 size_t n_lines) { 2595 // Skip the pragma prototype line 2596 ++lines; 2597 for (; n_lines--; ++lines) { 2598 const auto kv_pair = lines->split(" - "); 2599 m_pragmas[kv_pair.first.trim().str()] = kv_pair.second.trim().str(); 2600 } 2601 return true; 2602 } 2603 2604 bool RSModuleDescriptor::ParseExportReduceCount(llvm::StringRef *lines, 2605 size_t n_lines) { 2606 // The list of reduction kernels in the `.rs.info` symbol is of the form 2607 // "signature - accumulatordatasize - reduction_name - initializer_name - 2608 // accumulator_name - combiner_name - 2609 // outconverter_name - halter_name" 2610 // Where a function is not explicitly named by the user, or is not generated 2611 // by the compiler, it is named "." so the 2612 // dash separated list should always be 8 items long 2613 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE); 2614 // Skip the exportReduceCount line 2615 ++lines; 2616 for (; n_lines--; ++lines) { 2617 llvm::SmallVector<llvm::StringRef, 8> spec; 2618 lines->split(spec, " - "); 2619 if (spec.size() != 8) { 2620 if (spec.size() < 8) { 2621 if (log) 2622 log->Error("Error parsing RenderScript reduction spec. wrong number " 2623 "of fields"); 2624 return false; 2625 } else if (log) 2626 log->Warning("Extraneous members in reduction spec: '%s'", 2627 lines->str().c_str()); 2628 } 2629 2630 const auto sig_s = spec[0]; 2631 uint32_t sig; 2632 if (sig_s.getAsInteger(10, sig)) { 2633 if (log) 2634 log->Error("Error parsing Renderscript reduction spec: invalid kernel " 2635 "signature: '%s'", 2636 sig_s.str().c_str()); 2637 return false; 2638 } 2639 2640 const auto accum_data_size_s = spec[1]; 2641 uint32_t accum_data_size; 2642 if (accum_data_size_s.getAsInteger(10, accum_data_size)) { 2643 if (log) 2644 log->Error("Error parsing Renderscript reduction spec: invalid " 2645 "accumulator data size %s", 2646 accum_data_size_s.str().c_str()); 2647 return false; 2648 } 2649 2650 if (log) 2651 log->Printf("Found RenderScript reduction '%s'", spec[2].str().c_str()); 2652 2653 m_reductions.push_back(RSReductionDescriptor(this, sig, accum_data_size, 2654 spec[2], spec[3], spec[4], 2655 spec[5], spec[6], spec[7])); 2656 } 2657 return true; 2658 } 2659 2660 bool RSModuleDescriptor::ParseExportForeachCount(llvm::StringRef *lines, 2661 size_t n_lines) { 2662 // Skip the exportForeachCount line 2663 ++lines; 2664 for (; n_lines--; ++lines) { 2665 uint32_t slot; 2666 // `forEach` kernels are listed in the `.rs.info` packet as a "slot - name" 2667 // pair per line 2668 const auto kv_pair = lines->split(" - "); 2669 if (kv_pair.first.getAsInteger(10, slot)) 2670 return false; 2671 m_kernels.push_back(RSKernelDescriptor(this, kv_pair.second, slot)); 2672 } 2673 return true; 2674 } 2675 2676 bool RSModuleDescriptor::ParseExportVarCount(llvm::StringRef *lines, 2677 size_t n_lines) { 2678 // Skip the ExportVarCount line 2679 ++lines; 2680 for (; n_lines--; ++lines) 2681 m_globals.push_back(RSGlobalDescriptor(this, *lines)); 2682 return true; 2683 } 2684 2685 // The .rs.info symbol in renderscript modules contains a string which needs to 2686 // be parsed. 2687 // The string is basic and is parsed on a line by line basis. 2688 bool RSModuleDescriptor::ParseRSInfo() { 2689 assert(m_module); 2690 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 2691 const Symbol *info_sym = m_module->FindFirstSymbolWithNameAndType( 2692 ConstString(".rs.info"), eSymbolTypeData); 2693 if (!info_sym) 2694 return false; 2695 2696 const addr_t addr = info_sym->GetAddressRef().GetFileAddress(); 2697 if (addr == LLDB_INVALID_ADDRESS) 2698 return false; 2699 2700 const addr_t size = info_sym->GetByteSize(); 2701 const FileSpec fs = m_module->GetFileSpec(); 2702 2703 const DataBufferSP buffer = fs.ReadFileContents(addr, size); 2704 if (!buffer) 2705 return false; 2706 2707 // split rs.info. contents into lines 2708 llvm::SmallVector<llvm::StringRef, 128> info_lines; 2709 { 2710 const llvm::StringRef raw_rs_info((const char *)buffer->GetBytes()); 2711 raw_rs_info.split(info_lines, '\n'); 2712 if (log) 2713 log->Printf("'.rs.info symbol for '%s':\n%s", 2714 m_module->GetFileSpec().GetCString(), 2715 raw_rs_info.str().c_str()); 2716 } 2717 2718 enum { 2719 eExportVar, 2720 eExportForEach, 2721 eExportReduce, 2722 ePragma, 2723 eBuildChecksum, 2724 eObjectSlot 2725 }; 2726 2727 static const llvm::StringMap<int> rs_info_handlers{ 2728 {// The number of visible global variables in the script 2729 {"exportVarCount", eExportVar}, 2730 // The number of RenderScrip `forEach` kernels __attribute__((kernel)) 2731 {"exportForEachCount", eExportForEach}, 2732 // The number of generalreductions: This marked in the script by `#pragma 2733 // reduce()` 2734 {"exportReduceCount", eExportReduce}, 2735 // Total count of all RenderScript specific `#pragmas` used in the script 2736 {"pragmaCount", ePragma}, 2737 {"objectSlotCount", eObjectSlot}}}; 2738 2739 // parse all text lines of .rs.info 2740 for (auto line = info_lines.begin(); line != info_lines.end(); ++line) { 2741 const auto kv_pair = line->split(": "); 2742 const auto key = kv_pair.first; 2743 const auto val = kv_pair.second.trim(); 2744 2745 const auto handler = rs_info_handlers.find(key); 2746 if (handler == rs_info_handlers.end()) 2747 continue; 2748 // getAsInteger returns `true` on an error condition - we're only interested 2749 // in 2750 // numeric fields at the moment 2751 uint64_t n_lines; 2752 if (val.getAsInteger(10, n_lines)) { 2753 if (log) 2754 log->Debug("Failed to parse non-numeric '.rs.info' section %s", 2755 line->str().c_str()); 2756 continue; 2757 } 2758 if (info_lines.end() - (line + 1) < (ptrdiff_t)n_lines) 2759 return false; 2760 2761 bool success = false; 2762 switch (handler->getValue()) { 2763 case eExportVar: 2764 success = ParseExportVarCount(line, n_lines); 2765 break; 2766 case eExportForEach: 2767 success = ParseExportForeachCount(line, n_lines); 2768 break; 2769 case eExportReduce: 2770 success = ParseExportReduceCount(line, n_lines); 2771 break; 2772 case ePragma: 2773 success = ParsePragmaCount(line, n_lines); 2774 break; 2775 default: { 2776 if (log) 2777 log->Printf("%s - skipping .rs.info field '%s'", __FUNCTION__, 2778 line->str().c_str()); 2779 continue; 2780 } 2781 } 2782 if (!success) 2783 return false; 2784 line += n_lines; 2785 } 2786 return info_lines.size() > 0; 2787 } 2788 2789 void RenderScriptRuntime::Status(Stream &strm) const { 2790 if (m_libRS) { 2791 strm.Printf("Runtime Library discovered."); 2792 strm.EOL(); 2793 } 2794 if (m_libRSDriver) { 2795 strm.Printf("Runtime Driver discovered."); 2796 strm.EOL(); 2797 } 2798 if (m_libRSCpuRef) { 2799 strm.Printf("CPU Reference Implementation discovered."); 2800 strm.EOL(); 2801 } 2802 2803 if (m_runtimeHooks.size()) { 2804 strm.Printf("Runtime functions hooked:"); 2805 strm.EOL(); 2806 for (auto b : m_runtimeHooks) { 2807 strm.Indent(b.second->defn->name); 2808 strm.EOL(); 2809 } 2810 } else { 2811 strm.Printf("Runtime is not hooked."); 2812 strm.EOL(); 2813 } 2814 } 2815 2816 void RenderScriptRuntime::DumpContexts(Stream &strm) const { 2817 strm.Printf("Inferred RenderScript Contexts:"); 2818 strm.EOL(); 2819 strm.IndentMore(); 2820 2821 std::map<addr_t, uint64_t> contextReferences; 2822 2823 // Iterate over all of the currently discovered scripts. 2824 // Note: We cant push or pop from m_scripts inside this loop or it may 2825 // invalidate script. 2826 for (const auto &script : m_scripts) { 2827 if (!script->context.isValid()) 2828 continue; 2829 lldb::addr_t context = *script->context; 2830 2831 if (contextReferences.find(context) != contextReferences.end()) { 2832 contextReferences[context]++; 2833 } else { 2834 contextReferences[context] = 1; 2835 } 2836 } 2837 2838 for (const auto &cRef : contextReferences) { 2839 strm.Printf("Context 0x%" PRIx64 ": %" PRIu64 " script instances", 2840 cRef.first, cRef.second); 2841 strm.EOL(); 2842 } 2843 strm.IndentLess(); 2844 } 2845 2846 void RenderScriptRuntime::DumpKernels(Stream &strm) const { 2847 strm.Printf("RenderScript Kernels:"); 2848 strm.EOL(); 2849 strm.IndentMore(); 2850 for (const auto &module : m_rsmodules) { 2851 strm.Printf("Resource '%s':", module->m_resname.c_str()); 2852 strm.EOL(); 2853 for (const auto &kernel : module->m_kernels) { 2854 strm.Indent(kernel.m_name.AsCString()); 2855 strm.EOL(); 2856 } 2857 } 2858 strm.IndentLess(); 2859 } 2860 2861 RenderScriptRuntime::AllocationDetails * 2862 RenderScriptRuntime::FindAllocByID(Stream &strm, const uint32_t alloc_id) { 2863 AllocationDetails *alloc = nullptr; 2864 2865 // See if we can find allocation using id as an index; 2866 if (alloc_id <= m_allocations.size() && alloc_id != 0 && 2867 m_allocations[alloc_id - 1]->id == alloc_id) { 2868 alloc = m_allocations[alloc_id - 1].get(); 2869 return alloc; 2870 } 2871 2872 // Fallback to searching 2873 for (const auto &a : m_allocations) { 2874 if (a->id == alloc_id) { 2875 alloc = a.get(); 2876 break; 2877 } 2878 } 2879 2880 if (alloc == nullptr) { 2881 strm.Printf("Error: Couldn't find allocation with id matching %" PRIu32, 2882 alloc_id); 2883 strm.EOL(); 2884 } 2885 2886 return alloc; 2887 } 2888 2889 // Prints the contents of an allocation to the output stream, which may be a 2890 // file 2891 bool RenderScriptRuntime::DumpAllocation(Stream &strm, StackFrame *frame_ptr, 2892 const uint32_t id) { 2893 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 2894 2895 // Check we can find the desired allocation 2896 AllocationDetails *alloc = FindAllocByID(strm, id); 2897 if (!alloc) 2898 return false; // FindAllocByID() will print error message for us here 2899 2900 if (log) 2901 log->Printf("%s - found allocation 0x%" PRIx64, __FUNCTION__, 2902 *alloc->address.get()); 2903 2904 // Check we have information about the allocation, if not calculate it 2905 if (alloc->shouldRefresh()) { 2906 if (log) 2907 log->Printf("%s - allocation details not calculated yet, jitting info.", 2908 __FUNCTION__); 2909 2910 // JIT all the allocation information 2911 if (!RefreshAllocation(alloc, frame_ptr)) { 2912 strm.Printf("Error: Couldn't JIT allocation details"); 2913 strm.EOL(); 2914 return false; 2915 } 2916 } 2917 2918 // Establish format and size of each data element 2919 const uint32_t vec_size = *alloc->element.type_vec_size.get(); 2920 const Element::DataType type = *alloc->element.type.get(); 2921 2922 assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_FONT && 2923 "Invalid allocation type"); 2924 2925 lldb::Format format; 2926 if (type >= Element::RS_TYPE_ELEMENT) 2927 format = eFormatHex; 2928 else 2929 format = vec_size == 1 2930 ? static_cast<lldb::Format>( 2931 AllocationDetails::RSTypeToFormat[type][eFormatSingle]) 2932 : static_cast<lldb::Format>( 2933 AllocationDetails::RSTypeToFormat[type][eFormatVector]); 2934 2935 const uint32_t data_size = *alloc->element.datum_size.get(); 2936 2937 if (log) 2938 log->Printf("%s - element size %" PRIu32 " bytes, including padding", 2939 __FUNCTION__, data_size); 2940 2941 // Allocate a buffer to copy data into 2942 std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr); 2943 if (!buffer) { 2944 strm.Printf("Error: Couldn't read allocation data"); 2945 strm.EOL(); 2946 return false; 2947 } 2948 2949 // Calculate stride between rows as there may be padding at end of rows since 2950 // allocated memory is 16-byte aligned 2951 if (!alloc->stride.isValid()) { 2952 if (alloc->dimension.get()->dim_2 == 0) // We only have one dimension 2953 alloc->stride = 0; 2954 else if (!JITAllocationStride(alloc, frame_ptr)) { 2955 strm.Printf("Error: Couldn't calculate allocation row stride"); 2956 strm.EOL(); 2957 return false; 2958 } 2959 } 2960 const uint32_t stride = *alloc->stride.get(); 2961 const uint32_t size = *alloc->size.get(); // Size of whole allocation 2962 const uint32_t padding = 2963 alloc->element.padding.isValid() ? *alloc->element.padding.get() : 0; 2964 if (log) 2965 log->Printf("%s - stride %" PRIu32 " bytes, size %" PRIu32 2966 " bytes, padding %" PRIu32, 2967 __FUNCTION__, stride, size, padding); 2968 2969 // Find dimensions used to index loops, so need to be non-zero 2970 uint32_t dim_x = alloc->dimension.get()->dim_1; 2971 dim_x = dim_x == 0 ? 1 : dim_x; 2972 2973 uint32_t dim_y = alloc->dimension.get()->dim_2; 2974 dim_y = dim_y == 0 ? 1 : dim_y; 2975 2976 uint32_t dim_z = alloc->dimension.get()->dim_3; 2977 dim_z = dim_z == 0 ? 1 : dim_z; 2978 2979 // Use data extractor to format output 2980 const uint32_t archByteSize = 2981 GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize(); 2982 DataExtractor alloc_data(buffer.get(), size, GetProcess()->GetByteOrder(), 2983 archByteSize); 2984 2985 uint32_t offset = 0; // Offset in buffer to next element to be printed 2986 uint32_t prev_row = 0; // Offset to the start of the previous row 2987 2988 // Iterate over allocation dimensions, printing results to user 2989 strm.Printf("Data (X, Y, Z):"); 2990 for (uint32_t z = 0; z < dim_z; ++z) { 2991 for (uint32_t y = 0; y < dim_y; ++y) { 2992 // Use stride to index start of next row. 2993 if (!(y == 0 && z == 0)) 2994 offset = prev_row + stride; 2995 prev_row = offset; 2996 2997 // Print each element in the row individually 2998 for (uint32_t x = 0; x < dim_x; ++x) { 2999 strm.Printf("\n(%" PRIu32 ", %" PRIu32 ", %" PRIu32 ") = ", x, y, z); 3000 if ((type == Element::RS_TYPE_NONE) && 3001 (alloc->element.children.size() > 0) && 3002 (alloc->element.type_name != Element::GetFallbackStructName())) { 3003 // Here we are dumping an Element of struct type. 3004 // This is done using expression evaluation with the name of the 3005 // struct type and pointer to element. 3006 3007 // Don't print the name of the resulting expression, since this will 3008 // be '$[0-9]+' 3009 DumpValueObjectOptions expr_options; 3010 expr_options.SetHideName(true); 3011 3012 // Setup expression as derefrencing a pointer cast to element address. 3013 char expr_char_buffer[jit_max_expr_size]; 3014 int chars_written = 3015 snprintf(expr_char_buffer, jit_max_expr_size, "*(%s*) 0x%" PRIx64, 3016 alloc->element.type_name.AsCString(), 3017 *alloc->data_ptr.get() + offset); 3018 3019 if (chars_written < 0 || chars_written >= jit_max_expr_size) { 3020 if (log) 3021 log->Printf("%s - error in snprintf().", __FUNCTION__); 3022 continue; 3023 } 3024 3025 // Evaluate expression 3026 ValueObjectSP expr_result; 3027 GetProcess()->GetTarget().EvaluateExpression(expr_char_buffer, 3028 frame_ptr, expr_result); 3029 3030 // Print the results to our stream. 3031 expr_result->Dump(strm, expr_options); 3032 } else { 3033 alloc_data.Dump(&strm, offset, format, data_size - padding, 1, 1, 3034 LLDB_INVALID_ADDRESS, 0, 0); 3035 } 3036 offset += data_size; 3037 } 3038 } 3039 } 3040 strm.EOL(); 3041 3042 return true; 3043 } 3044 3045 // Function recalculates all our cached information about allocations by jitting 3046 // the 3047 // RS runtime regarding each allocation we know about. 3048 // Returns true if all allocations could be recomputed, false otherwise. 3049 bool RenderScriptRuntime::RecomputeAllAllocations(Stream &strm, 3050 StackFrame *frame_ptr) { 3051 bool success = true; 3052 for (auto &alloc : m_allocations) { 3053 // JIT current allocation information 3054 if (!RefreshAllocation(alloc.get(), frame_ptr)) { 3055 strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32 3056 "\n", 3057 alloc->id); 3058 success = false; 3059 } 3060 } 3061 3062 if (success) 3063 strm.Printf("All allocations successfully recomputed"); 3064 strm.EOL(); 3065 3066 return success; 3067 } 3068 3069 // Prints information regarding currently loaded allocations. 3070 // These details are gathered by jitting the runtime, which has as latency. 3071 // Index parameter specifies a single allocation ID to print, or a zero value to 3072 // print them all 3073 void RenderScriptRuntime::ListAllocations(Stream &strm, StackFrame *frame_ptr, 3074 const uint32_t index) { 3075 strm.Printf("RenderScript Allocations:"); 3076 strm.EOL(); 3077 strm.IndentMore(); 3078 3079 for (auto &alloc : m_allocations) { 3080 // index will only be zero if we want to print all allocations 3081 if (index != 0 && index != alloc->id) 3082 continue; 3083 3084 // JIT current allocation information 3085 if (alloc->shouldRefresh() && !RefreshAllocation(alloc.get(), frame_ptr)) { 3086 strm.Printf("Error: Couldn't evaluate details for allocation %" PRIu32, 3087 alloc->id); 3088 strm.EOL(); 3089 continue; 3090 } 3091 3092 strm.Printf("%" PRIu32 ":", alloc->id); 3093 strm.EOL(); 3094 strm.IndentMore(); 3095 3096 strm.Indent("Context: "); 3097 if (!alloc->context.isValid()) 3098 strm.Printf("unknown\n"); 3099 else 3100 strm.Printf("0x%" PRIx64 "\n", *alloc->context.get()); 3101 3102 strm.Indent("Address: "); 3103 if (!alloc->address.isValid()) 3104 strm.Printf("unknown\n"); 3105 else 3106 strm.Printf("0x%" PRIx64 "\n", *alloc->address.get()); 3107 3108 strm.Indent("Data pointer: "); 3109 if (!alloc->data_ptr.isValid()) 3110 strm.Printf("unknown\n"); 3111 else 3112 strm.Printf("0x%" PRIx64 "\n", *alloc->data_ptr.get()); 3113 3114 strm.Indent("Dimensions: "); 3115 if (!alloc->dimension.isValid()) 3116 strm.Printf("unknown\n"); 3117 else 3118 strm.Printf("(%" PRId32 ", %" PRId32 ", %" PRId32 ")\n", 3119 alloc->dimension.get()->dim_1, alloc->dimension.get()->dim_2, 3120 alloc->dimension.get()->dim_3); 3121 3122 strm.Indent("Data Type: "); 3123 if (!alloc->element.type.isValid() || 3124 !alloc->element.type_vec_size.isValid()) 3125 strm.Printf("unknown\n"); 3126 else { 3127 const int vector_size = *alloc->element.type_vec_size.get(); 3128 Element::DataType type = *alloc->element.type.get(); 3129 3130 if (!alloc->element.type_name.IsEmpty()) 3131 strm.Printf("%s\n", alloc->element.type_name.AsCString()); 3132 else { 3133 // Enum value isn't monotonous, so doesn't always index 3134 // RsDataTypeToString array 3135 if (type >= Element::RS_TYPE_ELEMENT && type <= Element::RS_TYPE_FONT) 3136 type = 3137 static_cast<Element::DataType>((type - Element::RS_TYPE_ELEMENT) + 3138 Element::RS_TYPE_MATRIX_2X2 + 1); 3139 3140 if (type >= (sizeof(AllocationDetails::RsDataTypeToString) / 3141 sizeof(AllocationDetails::RsDataTypeToString[0])) || 3142 vector_size > 4 || vector_size < 1) 3143 strm.Printf("invalid type\n"); 3144 else 3145 strm.Printf( 3146 "%s\n", 3147 AllocationDetails::RsDataTypeToString[static_cast<uint32_t>(type)] 3148 [vector_size - 1]); 3149 } 3150 } 3151 3152 strm.Indent("Data Kind: "); 3153 if (!alloc->element.type_kind.isValid()) 3154 strm.Printf("unknown\n"); 3155 else { 3156 const Element::DataKind kind = *alloc->element.type_kind.get(); 3157 if (kind < Element::RS_KIND_USER || kind > Element::RS_KIND_PIXEL_YUV) 3158 strm.Printf("invalid kind\n"); 3159 else 3160 strm.Printf( 3161 "%s\n", 3162 AllocationDetails::RsDataKindToString[static_cast<uint32_t>(kind)]); 3163 } 3164 3165 strm.EOL(); 3166 strm.IndentLess(); 3167 } 3168 strm.IndentLess(); 3169 } 3170 3171 // Set breakpoints on every kernel found in RS module 3172 void RenderScriptRuntime::BreakOnModuleKernels( 3173 const RSModuleDescriptorSP rsmodule_sp) { 3174 for (const auto &kernel : rsmodule_sp->m_kernels) { 3175 // Don't set breakpoint on 'root' kernel 3176 if (strcmp(kernel.m_name.AsCString(), "root") == 0) 3177 continue; 3178 3179 CreateKernelBreakpoint(kernel.m_name); 3180 } 3181 } 3182 3183 // Method is internally called by the 'kernel breakpoint all' command to 3184 // enable or disable breaking on all kernels. 3185 // 3186 // When do_break is true we want to enable this functionality. 3187 // When do_break is false we want to disable it. 3188 void RenderScriptRuntime::SetBreakAllKernels(bool do_break, TargetSP target) { 3189 Log *log( 3190 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS)); 3191 3192 InitSearchFilter(target); 3193 3194 // Set breakpoints on all the kernels 3195 if (do_break && !m_breakAllKernels) { 3196 m_breakAllKernels = true; 3197 3198 for (const auto &module : m_rsmodules) 3199 BreakOnModuleKernels(module); 3200 3201 if (log) 3202 log->Printf("%s(True) - breakpoints set on all currently loaded kernels.", 3203 __FUNCTION__); 3204 } else if (!do_break && 3205 m_breakAllKernels) // Breakpoints won't be set on any new kernels. 3206 { 3207 m_breakAllKernels = false; 3208 3209 if (log) 3210 log->Printf("%s(False) - breakpoints no longer automatically set.", 3211 __FUNCTION__); 3212 } 3213 } 3214 3215 // Given the name of a kernel this function creates a breakpoint using our 3216 // own breakpoint resolver, and returns the Breakpoint shared pointer. 3217 BreakpointSP 3218 RenderScriptRuntime::CreateKernelBreakpoint(const ConstString &name) { 3219 Log *log( 3220 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS)); 3221 3222 if (!m_filtersp) { 3223 if (log) 3224 log->Printf("%s - error, no breakpoint search filter set.", __FUNCTION__); 3225 return nullptr; 3226 } 3227 3228 BreakpointResolverSP resolver_sp(new RSBreakpointResolver(nullptr, name)); 3229 BreakpointSP bp = GetProcess()->GetTarget().CreateBreakpoint( 3230 m_filtersp, resolver_sp, false, false, false); 3231 3232 // Give RS breakpoints a specific name, so the user can manipulate them as a 3233 // group. 3234 Error err; 3235 if (!bp->AddName("RenderScriptKernel", err) && log) 3236 log->Printf("%s - error setting break name, '%s'.", __FUNCTION__, 3237 err.AsCString()); 3238 3239 return bp; 3240 } 3241 3242 // Given an expression for a variable this function tries to calculate the 3243 // variable's value. 3244 // If this is possible it returns true and sets the uint64_t parameter to the 3245 // variables unsigned value. 3246 // Otherwise function returns false. 3247 bool RenderScriptRuntime::GetFrameVarAsUnsigned(const StackFrameSP frame_sp, 3248 const char *var_name, 3249 uint64_t &val) { 3250 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 3251 Error error; 3252 VariableSP var_sp; 3253 3254 // Find variable in stack frame 3255 ValueObjectSP value_sp(frame_sp->GetValueForVariableExpressionPath( 3256 var_name, eNoDynamicValues, 3257 StackFrame::eExpressionPathOptionCheckPtrVsMember | 3258 StackFrame::eExpressionPathOptionsAllowDirectIVarAccess, 3259 var_sp, error)); 3260 if (!error.Success()) { 3261 if (log) 3262 log->Printf("%s - error, couldn't find '%s' in frame", __FUNCTION__, 3263 var_name); 3264 return false; 3265 } 3266 3267 // Find the uint32_t value for the variable 3268 bool success = false; 3269 val = value_sp->GetValueAsUnsigned(0, &success); 3270 if (!success) { 3271 if (log) 3272 log->Printf("%s - error, couldn't parse '%s' as an uint32_t.", 3273 __FUNCTION__, var_name); 3274 return false; 3275 } 3276 3277 return true; 3278 } 3279 3280 // Function attempts to find the current coordinate of a kernel invocation by 3281 // investigating the 3282 // values of frame variables in the .expand function. These coordinates are 3283 // returned via the coord 3284 // array reference parameter. Returns true if the coordinates could be found, 3285 // and false otherwise. 3286 bool RenderScriptRuntime::GetKernelCoordinate(RSCoordinate &coord, 3287 Thread *thread_ptr) { 3288 static const std::string s_runtimeExpandSuffix(".expand"); 3289 static const std::array<const char *, 3> s_runtimeCoordVars{ 3290 {"rsIndex", "p->current.y", "p->current.z"}}; 3291 3292 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 3293 3294 if (!thread_ptr) { 3295 if (log) 3296 log->Printf("%s - Error, No thread pointer", __FUNCTION__); 3297 3298 return false; 3299 } 3300 3301 // Walk the call stack looking for a function whose name has the suffix 3302 // '.expand' 3303 // and contains the variables we're looking for. 3304 for (uint32_t i = 0; i < thread_ptr->GetStackFrameCount(); ++i) { 3305 if (!thread_ptr->SetSelectedFrameByIndex(i)) 3306 continue; 3307 3308 StackFrameSP frame_sp = thread_ptr->GetSelectedFrame(); 3309 if (!frame_sp) 3310 continue; 3311 3312 // Find the function name 3313 const SymbolContext sym_ctx = frame_sp->GetSymbolContext(false); 3314 const char *func_name_cstr = sym_ctx.GetFunctionName().AsCString(); 3315 if (!func_name_cstr) 3316 continue; 3317 3318 if (log) 3319 log->Printf("%s - Inspecting function '%s'", __FUNCTION__, 3320 func_name_cstr); 3321 3322 // Check if function name has .expand suffix 3323 std::string func_name(func_name_cstr); 3324 const int length_difference = 3325 func_name.length() - s_runtimeExpandSuffix.length(); 3326 if (length_difference <= 0) 3327 continue; 3328 3329 const int32_t has_expand_suffix = 3330 func_name.compare(length_difference, s_runtimeExpandSuffix.length(), 3331 s_runtimeExpandSuffix); 3332 3333 if (has_expand_suffix != 0) 3334 continue; 3335 3336 if (log) 3337 log->Printf("%s - Found .expand function '%s'", __FUNCTION__, 3338 func_name_cstr); 3339 3340 // Get values for variables in .expand frame that tell us the current kernel 3341 // invocation 3342 bool found_coord_variables = true; 3343 assert(s_runtimeCoordVars.size() == coord.size()); 3344 3345 for (uint32_t i = 0; i < coord.size(); ++i) { 3346 uint64_t value = 0; 3347 if (!GetFrameVarAsUnsigned(frame_sp, s_runtimeCoordVars[i], value)) { 3348 found_coord_variables = false; 3349 break; 3350 } 3351 coord[i] = value; 3352 } 3353 3354 if (found_coord_variables) 3355 return true; 3356 } 3357 return false; 3358 } 3359 3360 // Callback when a kernel breakpoint hits and we're looking for a specific 3361 // coordinate. 3362 // Baton parameter contains a pointer to the target coordinate we want to break 3363 // on. 3364 // Function then checks the .expand frame for the current coordinate and breaks 3365 // to user if it matches. 3366 // Parameter 'break_id' is the id of the Breakpoint which made the callback. 3367 // Parameter 'break_loc_id' is the id for the BreakpointLocation which was hit, 3368 // a single logical breakpoint can have multiple addresses. 3369 bool RenderScriptRuntime::KernelBreakpointHit(void *baton, 3370 StoppointCallbackContext *ctx, 3371 user_id_t break_id, 3372 user_id_t break_loc_id) { 3373 Log *log( 3374 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS)); 3375 3376 assert(baton && 3377 "Error: null baton in conditional kernel breakpoint callback"); 3378 3379 // Coordinate we want to stop on 3380 const uint32_t *target_coord = static_cast<const uint32_t *>(baton); 3381 3382 if (log) 3383 log->Printf("%s - Break ID %" PRIu64 ", (%" PRIu32 ", %" PRIu32 ", %" PRIu32 3384 ")", 3385 __FUNCTION__, break_id, target_coord[0], target_coord[1], 3386 target_coord[2]); 3387 3388 // Select current thread 3389 ExecutionContext context(ctx->exe_ctx_ref); 3390 Thread *thread_ptr = context.GetThreadPtr(); 3391 assert(thread_ptr && "Null thread pointer"); 3392 3393 // Find current kernel invocation from .expand frame variables 3394 RSCoordinate current_coord{}; // Zero initialise array 3395 if (!GetKernelCoordinate(current_coord, thread_ptr)) { 3396 if (log) 3397 log->Printf("%s - Error, couldn't select .expand stack frame", 3398 __FUNCTION__); 3399 return false; 3400 } 3401 3402 if (log) 3403 log->Printf("%s - (%" PRIu32 ",%" PRIu32 ",%" PRIu32 ")", __FUNCTION__, 3404 current_coord[0], current_coord[1], current_coord[2]); 3405 3406 // Check if the current kernel invocation coordinate matches our target 3407 // coordinate 3408 if (current_coord[0] == target_coord[0] && 3409 current_coord[1] == target_coord[1] && 3410 current_coord[2] == target_coord[2]) { 3411 if (log) 3412 log->Printf("%s, BREAKING (%" PRIu32 ",%" PRIu32 ",%" PRIu32 ")", 3413 __FUNCTION__, current_coord[0], current_coord[1], 3414 current_coord[2]); 3415 3416 BreakpointSP breakpoint_sp = 3417 context.GetTargetPtr()->GetBreakpointByID(break_id); 3418 assert(breakpoint_sp != nullptr && 3419 "Error: Couldn't find breakpoint matching break id for callback"); 3420 breakpoint_sp->SetEnabled(false); // Optimise since conditional breakpoint 3421 // should only be hit once. 3422 return true; 3423 } 3424 3425 // No match on coordinate 3426 return false; 3427 } 3428 3429 // Tries to set a breakpoint on the start of a kernel, resolved using the kernel 3430 // name. 3431 // Argument 'coords', represents a three dimensional coordinate which can be 3432 // used to specify 3433 // a single kernel instance to break on. If this is set then we add a callback 3434 // to the breakpoint. 3435 void RenderScriptRuntime::PlaceBreakpointOnKernel( 3436 Stream &strm, const char *name, const std::array<int, 3> coords, 3437 Error &error, TargetSP target) { 3438 if (!name) { 3439 error.SetErrorString("invalid kernel name"); 3440 return; 3441 } 3442 3443 InitSearchFilter(target); 3444 3445 ConstString kernel_name(name); 3446 BreakpointSP bp = CreateKernelBreakpoint(kernel_name); 3447 3448 // We have a conditional breakpoint on a specific coordinate 3449 if (coords[0] != -1) { 3450 strm.Printf("Conditional kernel breakpoint on coordinate %" PRId32 3451 ", %" PRId32 ", %" PRId32, 3452 coords[0], coords[1], coords[2]); 3453 strm.EOL(); 3454 3455 // Allocate memory for the baton, and copy over coordinate 3456 uint32_t *baton = new uint32_t[coords.size()]; 3457 baton[0] = coords[0]; 3458 baton[1] = coords[1]; 3459 baton[2] = coords[2]; 3460 3461 // Create a callback that will be invoked every time the breakpoint is hit. 3462 // The baton object passed to the handler is the target coordinate we want 3463 // to break on. 3464 bp->SetCallback(KernelBreakpointHit, baton, true); 3465 3466 // Store a shared pointer to the baton, so the memory will eventually be 3467 // cleaned up after destruction 3468 m_conditional_breaks[bp->GetID()] = std::shared_ptr<uint32_t>(baton); 3469 } 3470 3471 if (bp) 3472 bp->GetDescription(&strm, lldb::eDescriptionLevelInitial, false); 3473 } 3474 3475 void RenderScriptRuntime::DumpModules(Stream &strm) const { 3476 strm.Printf("RenderScript Modules:"); 3477 strm.EOL(); 3478 strm.IndentMore(); 3479 for (const auto &module : m_rsmodules) { 3480 module->Dump(strm); 3481 } 3482 strm.IndentLess(); 3483 } 3484 3485 RenderScriptRuntime::ScriptDetails * 3486 RenderScriptRuntime::LookUpScript(addr_t address, bool create) { 3487 for (const auto &s : m_scripts) { 3488 if (s->script.isValid()) 3489 if (*s->script == address) 3490 return s.get(); 3491 } 3492 if (create) { 3493 std::unique_ptr<ScriptDetails> s(new ScriptDetails); 3494 s->script = address; 3495 m_scripts.push_back(std::move(s)); 3496 return m_scripts.back().get(); 3497 } 3498 return nullptr; 3499 } 3500 3501 RenderScriptRuntime::AllocationDetails * 3502 RenderScriptRuntime::LookUpAllocation(addr_t address) { 3503 for (const auto &a : m_allocations) { 3504 if (a->address.isValid()) 3505 if (*a->address == address) 3506 return a.get(); 3507 } 3508 return nullptr; 3509 } 3510 3511 RenderScriptRuntime::AllocationDetails * 3512 RenderScriptRuntime::CreateAllocation(addr_t address) { 3513 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE); 3514 3515 // Remove any previous allocation which contains the same address 3516 auto it = m_allocations.begin(); 3517 while (it != m_allocations.end()) { 3518 if (*((*it)->address) == address) { 3519 if (log) 3520 log->Printf("%s - Removing allocation id: %d, address: 0x%" PRIx64, 3521 __FUNCTION__, (*it)->id, address); 3522 3523 it = m_allocations.erase(it); 3524 } else { 3525 it++; 3526 } 3527 } 3528 3529 std::unique_ptr<AllocationDetails> a(new AllocationDetails); 3530 a->address = address; 3531 m_allocations.push_back(std::move(a)); 3532 return m_allocations.back().get(); 3533 } 3534 3535 void RSModuleDescriptor::Dump(Stream &strm) const { 3536 int indent = strm.GetIndentLevel(); 3537 3538 strm.Indent(); 3539 m_module->GetFileSpec().Dump(&strm); 3540 strm.Indent(m_module->GetNumCompileUnits() ? "Debug info loaded." 3541 : "Debug info does not exist."); 3542 strm.EOL(); 3543 strm.IndentMore(); 3544 3545 strm.Indent(); 3546 strm.Printf("Globals: %" PRIu64, static_cast<uint64_t>(m_globals.size())); 3547 strm.EOL(); 3548 strm.IndentMore(); 3549 for (const auto &global : m_globals) { 3550 global.Dump(strm); 3551 } 3552 strm.IndentLess(); 3553 3554 strm.Indent(); 3555 strm.Printf("Kernels: %" PRIu64, static_cast<uint64_t>(m_kernels.size())); 3556 strm.EOL(); 3557 strm.IndentMore(); 3558 for (const auto &kernel : m_kernels) { 3559 kernel.Dump(strm); 3560 } 3561 strm.IndentLess(); 3562 3563 strm.Indent(); 3564 strm.Printf("Pragmas: %" PRIu64, static_cast<uint64_t>(m_pragmas.size())); 3565 strm.EOL(); 3566 strm.IndentMore(); 3567 for (const auto &key_val : m_pragmas) { 3568 strm.Indent(); 3569 strm.Printf("%s: %s", key_val.first.c_str(), key_val.second.c_str()); 3570 strm.EOL(); 3571 } 3572 strm.IndentLess(); 3573 3574 strm.Indent(); 3575 strm.Printf("Reductions: %" PRIu64, 3576 static_cast<uint64_t>(m_reductions.size())); 3577 strm.EOL(); 3578 strm.IndentMore(); 3579 for (const auto &reduction : m_reductions) { 3580 reduction.Dump(strm); 3581 } 3582 3583 strm.SetIndentLevel(indent); 3584 } 3585 3586 void RSGlobalDescriptor::Dump(Stream &strm) const { 3587 strm.Indent(m_name.AsCString()); 3588 VariableList var_list; 3589 m_module->m_module->FindGlobalVariables(m_name, nullptr, true, 1U, var_list); 3590 if (var_list.GetSize() == 1) { 3591 auto var = var_list.GetVariableAtIndex(0); 3592 auto type = var->GetType(); 3593 if (type) { 3594 strm.Printf(" - "); 3595 type->DumpTypeName(&strm); 3596 } else { 3597 strm.Printf(" - Unknown Type"); 3598 } 3599 } else { 3600 strm.Printf(" - variable identified, but not found in binary"); 3601 const Symbol *s = m_module->m_module->FindFirstSymbolWithNameAndType( 3602 m_name, eSymbolTypeData); 3603 if (s) { 3604 strm.Printf(" (symbol exists) "); 3605 } 3606 } 3607 3608 strm.EOL(); 3609 } 3610 3611 void RSKernelDescriptor::Dump(Stream &strm) const { 3612 strm.Indent(m_name.AsCString()); 3613 strm.EOL(); 3614 } 3615 3616 void RSReductionDescriptor::Dump(lldb_private::Stream &stream) const { 3617 stream.Indent(m_reduce_name.AsCString()); 3618 stream.IndentMore(); 3619 stream.EOL(); 3620 stream.Indent(); 3621 stream.Printf("accumulator: %s", m_accum_name.AsCString()); 3622 stream.EOL(); 3623 stream.Indent(); 3624 stream.Printf("initializer: %s", m_init_name.AsCString()); 3625 stream.EOL(); 3626 stream.Indent(); 3627 stream.Printf("combiner: %s", m_comb_name.AsCString()); 3628 stream.EOL(); 3629 stream.Indent(); 3630 stream.Printf("outconverter: %s", m_outc_name.AsCString()); 3631 stream.EOL(); 3632 // XXX This is currently unspecified by RenderScript, and unused 3633 // stream.Indent(); 3634 // stream.Printf("halter: '%s'", m_init_name.AsCString()); 3635 // stream.EOL(); 3636 stream.IndentLess(); 3637 } 3638 3639 class CommandObjectRenderScriptRuntimeModuleDump : public CommandObjectParsed { 3640 public: 3641 CommandObjectRenderScriptRuntimeModuleDump(CommandInterpreter &interpreter) 3642 : CommandObjectParsed( 3643 interpreter, "renderscript module dump", 3644 "Dumps renderscript specific information for all modules.", 3645 "renderscript module dump", 3646 eCommandRequiresProcess | eCommandProcessMustBeLaunched) {} 3647 3648 ~CommandObjectRenderScriptRuntimeModuleDump() override = default; 3649 3650 bool DoExecute(Args &command, CommandReturnObject &result) override { 3651 RenderScriptRuntime *runtime = 3652 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime( 3653 eLanguageTypeExtRenderScript); 3654 runtime->DumpModules(result.GetOutputStream()); 3655 result.SetStatus(eReturnStatusSuccessFinishResult); 3656 return true; 3657 } 3658 }; 3659 3660 class CommandObjectRenderScriptRuntimeModule : public CommandObjectMultiword { 3661 public: 3662 CommandObjectRenderScriptRuntimeModule(CommandInterpreter &interpreter) 3663 : CommandObjectMultiword(interpreter, "renderscript module", 3664 "Commands that deal with RenderScript modules.", 3665 nullptr) { 3666 LoadSubCommand( 3667 "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleDump( 3668 interpreter))); 3669 } 3670 3671 ~CommandObjectRenderScriptRuntimeModule() override = default; 3672 }; 3673 3674 class CommandObjectRenderScriptRuntimeKernelList : public CommandObjectParsed { 3675 public: 3676 CommandObjectRenderScriptRuntimeKernelList(CommandInterpreter &interpreter) 3677 : CommandObjectParsed( 3678 interpreter, "renderscript kernel list", 3679 "Lists renderscript kernel names and associated script resources.", 3680 "renderscript kernel list", 3681 eCommandRequiresProcess | eCommandProcessMustBeLaunched) {} 3682 3683 ~CommandObjectRenderScriptRuntimeKernelList() override = default; 3684 3685 bool DoExecute(Args &command, CommandReturnObject &result) override { 3686 RenderScriptRuntime *runtime = 3687 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime( 3688 eLanguageTypeExtRenderScript); 3689 runtime->DumpKernels(result.GetOutputStream()); 3690 result.SetStatus(eReturnStatusSuccessFinishResult); 3691 return true; 3692 } 3693 }; 3694 3695 static OptionDefinition g_renderscript_kernel_bp_set_options[] = { 3696 {LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument, 3697 nullptr, nullptr, 0, eArgTypeValue, 3698 "Set a breakpoint on a single invocation of the kernel with specified " 3699 "coordinate.\n" 3700 "Coordinate takes the form 'x[,y][,z] where x,y,z are positive " 3701 "integers representing kernel dimensions. " 3702 "Any unset dimensions will be defaulted to zero."}}; 3703 3704 class CommandObjectRenderScriptRuntimeKernelBreakpointSet 3705 : public CommandObjectParsed { 3706 public: 3707 CommandObjectRenderScriptRuntimeKernelBreakpointSet( 3708 CommandInterpreter &interpreter) 3709 : CommandObjectParsed( 3710 interpreter, "renderscript kernel breakpoint set", 3711 "Sets a breakpoint on a renderscript kernel.", 3712 "renderscript kernel breakpoint set <kernel_name> [-c x,y,z]", 3713 eCommandRequiresProcess | eCommandProcessMustBeLaunched | 3714 eCommandProcessMustBePaused), 3715 m_options() {} 3716 3717 ~CommandObjectRenderScriptRuntimeKernelBreakpointSet() override = default; 3718 3719 Options *GetOptions() override { return &m_options; } 3720 3721 class CommandOptions : public Options { 3722 public: 3723 CommandOptions() : Options() {} 3724 3725 ~CommandOptions() override = default; 3726 3727 Error SetOptionValue(uint32_t option_idx, const char *option_arg, 3728 ExecutionContext *execution_context) override { 3729 Error error; 3730 const int short_option = m_getopt_table[option_idx].val; 3731 3732 switch (short_option) { 3733 case 'c': 3734 if (!ParseCoordinate(option_arg)) 3735 error.SetErrorStringWithFormat( 3736 "Couldn't parse coordinate '%s', should be in format 'x,y,z'.", 3737 option_arg); 3738 break; 3739 default: 3740 error.SetErrorStringWithFormat("unrecognized option '%c'", 3741 short_option); 3742 break; 3743 } 3744 return error; 3745 } 3746 3747 // -c takes an argument of the form 'num[,num][,num]'. 3748 // Where 'id_cstr' is this argument with the whitespace trimmed. 3749 // Missing coordinates are defaulted to zero. 3750 bool ParseCoordinate(const char *id_cstr) { 3751 RegularExpression regex; 3752 RegularExpression::Match regex_match(3); 3753 3754 llvm::StringRef id_ref = llvm::StringRef::withNullAsEmpty(id_cstr); 3755 bool matched = false; 3756 if (regex.Compile(llvm::StringRef("^([0-9]+),([0-9]+),([0-9]+)$")) && 3757 regex.Execute(id_ref, ®ex_match)) 3758 matched = true; 3759 else if (regex.Compile(llvm::StringRef("^([0-9]+),([0-9]+)$")) && 3760 regex.Execute(id_ref, ®ex_match)) 3761 matched = true; 3762 else if (regex.Compile(llvm::StringRef("^([0-9]+)$")) && 3763 regex.Execute(id_ref, ®ex_match)) 3764 matched = true; 3765 for (uint32_t i = 0; i < 3; i++) { 3766 std::string group; 3767 if (regex_match.GetMatchAtIndex(id_cstr, i + 1, group)) 3768 m_coord[i] = (uint32_t)strtoul(group.c_str(), nullptr, 0); 3769 else 3770 m_coord[i] = 0; 3771 } 3772 return matched; 3773 } 3774 3775 void OptionParsingStarting(ExecutionContext *execution_context) override { 3776 // -1 means the -c option hasn't been set 3777 m_coord[0] = -1; 3778 m_coord[1] = -1; 3779 m_coord[2] = -1; 3780 } 3781 3782 llvm::ArrayRef<OptionDefinition> GetDefinitions() override { 3783 return llvm::makeArrayRef(g_renderscript_kernel_bp_set_options); 3784 } 3785 3786 std::array<int, 3> m_coord; 3787 }; 3788 3789 bool DoExecute(Args &command, CommandReturnObject &result) override { 3790 const size_t argc = command.GetArgumentCount(); 3791 if (argc < 1) { 3792 result.AppendErrorWithFormat( 3793 "'%s' takes 1 argument of kernel name, and an optional coordinate.", 3794 m_cmd_name.c_str()); 3795 result.SetStatus(eReturnStatusFailed); 3796 return false; 3797 } 3798 3799 RenderScriptRuntime *runtime = 3800 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime( 3801 eLanguageTypeExtRenderScript); 3802 3803 Error error; 3804 runtime->PlaceBreakpointOnKernel( 3805 result.GetOutputStream(), command.GetArgumentAtIndex(0), 3806 m_options.m_coord, error, m_exe_ctx.GetTargetSP()); 3807 3808 if (error.Success()) { 3809 result.AppendMessage("Breakpoint(s) created"); 3810 result.SetStatus(eReturnStatusSuccessFinishResult); 3811 return true; 3812 } 3813 result.SetStatus(eReturnStatusFailed); 3814 result.AppendErrorWithFormat("Error: %s", error.AsCString()); 3815 return false; 3816 } 3817 3818 private: 3819 CommandOptions m_options; 3820 }; 3821 3822 class CommandObjectRenderScriptRuntimeKernelBreakpointAll 3823 : public CommandObjectParsed { 3824 public: 3825 CommandObjectRenderScriptRuntimeKernelBreakpointAll( 3826 CommandInterpreter &interpreter) 3827 : CommandObjectParsed( 3828 interpreter, "renderscript kernel breakpoint all", 3829 "Automatically sets a breakpoint on all renderscript kernels that " 3830 "are or will be loaded.\n" 3831 "Disabling option means breakpoints will no longer be set on any " 3832 "kernels loaded in the future, " 3833 "but does not remove currently set breakpoints.", 3834 "renderscript kernel breakpoint all <enable/disable>", 3835 eCommandRequiresProcess | eCommandProcessMustBeLaunched | 3836 eCommandProcessMustBePaused) {} 3837 3838 ~CommandObjectRenderScriptRuntimeKernelBreakpointAll() override = default; 3839 3840 bool DoExecute(Args &command, CommandReturnObject &result) override { 3841 const size_t argc = command.GetArgumentCount(); 3842 if (argc != 1) { 3843 result.AppendErrorWithFormat( 3844 "'%s' takes 1 argument of 'enable' or 'disable'", m_cmd_name.c_str()); 3845 result.SetStatus(eReturnStatusFailed); 3846 return false; 3847 } 3848 3849 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>( 3850 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime( 3851 eLanguageTypeExtRenderScript)); 3852 3853 bool do_break = false; 3854 const char *argument = command.GetArgumentAtIndex(0); 3855 if (strcmp(argument, "enable") == 0) { 3856 do_break = true; 3857 result.AppendMessage("Breakpoints will be set on all kernels."); 3858 } else if (strcmp(argument, "disable") == 0) { 3859 do_break = false; 3860 result.AppendMessage("Breakpoints will not be set on any new kernels."); 3861 } else { 3862 result.AppendErrorWithFormat( 3863 "Argument must be either 'enable' or 'disable'"); 3864 result.SetStatus(eReturnStatusFailed); 3865 return false; 3866 } 3867 3868 runtime->SetBreakAllKernels(do_break, m_exe_ctx.GetTargetSP()); 3869 3870 result.SetStatus(eReturnStatusSuccessFinishResult); 3871 return true; 3872 } 3873 }; 3874 3875 class CommandObjectRenderScriptRuntimeKernelCoordinate 3876 : public CommandObjectParsed { 3877 public: 3878 CommandObjectRenderScriptRuntimeKernelCoordinate( 3879 CommandInterpreter &interpreter) 3880 : CommandObjectParsed( 3881 interpreter, "renderscript kernel coordinate", 3882 "Shows the (x,y,z) coordinate of the current kernel invocation.", 3883 "renderscript kernel coordinate", 3884 eCommandRequiresProcess | eCommandProcessMustBeLaunched | 3885 eCommandProcessMustBePaused) {} 3886 3887 ~CommandObjectRenderScriptRuntimeKernelCoordinate() override = default; 3888 3889 bool DoExecute(Args &command, CommandReturnObject &result) override { 3890 RSCoordinate coord{}; // Zero initialize array 3891 bool success = RenderScriptRuntime::GetKernelCoordinate( 3892 coord, m_exe_ctx.GetThreadPtr()); 3893 Stream &stream = result.GetOutputStream(); 3894 3895 if (success) { 3896 stream.Printf("Coordinate: (%" PRIu32 ", %" PRIu32 ", %" PRIu32 ")", 3897 coord[0], coord[1], coord[2]); 3898 stream.EOL(); 3899 result.SetStatus(eReturnStatusSuccessFinishResult); 3900 } else { 3901 stream.Printf("Error: Coordinate could not be found."); 3902 stream.EOL(); 3903 result.SetStatus(eReturnStatusFailed); 3904 } 3905 return true; 3906 } 3907 }; 3908 3909 class CommandObjectRenderScriptRuntimeKernelBreakpoint 3910 : public CommandObjectMultiword { 3911 public: 3912 CommandObjectRenderScriptRuntimeKernelBreakpoint( 3913 CommandInterpreter &interpreter) 3914 : CommandObjectMultiword( 3915 interpreter, "renderscript kernel", 3916 "Commands that generate breakpoints on renderscript kernels.", 3917 nullptr) { 3918 LoadSubCommand( 3919 "set", 3920 CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointSet( 3921 interpreter))); 3922 LoadSubCommand( 3923 "all", 3924 CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointAll( 3925 interpreter))); 3926 } 3927 3928 ~CommandObjectRenderScriptRuntimeKernelBreakpoint() override = default; 3929 }; 3930 3931 class CommandObjectRenderScriptRuntimeKernel : public CommandObjectMultiword { 3932 public: 3933 CommandObjectRenderScriptRuntimeKernel(CommandInterpreter &interpreter) 3934 : CommandObjectMultiword(interpreter, "renderscript kernel", 3935 "Commands that deal with RenderScript kernels.", 3936 nullptr) { 3937 LoadSubCommand( 3938 "list", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelList( 3939 interpreter))); 3940 LoadSubCommand( 3941 "coordinate", 3942 CommandObjectSP( 3943 new CommandObjectRenderScriptRuntimeKernelCoordinate(interpreter))); 3944 LoadSubCommand( 3945 "breakpoint", 3946 CommandObjectSP( 3947 new CommandObjectRenderScriptRuntimeKernelBreakpoint(interpreter))); 3948 } 3949 3950 ~CommandObjectRenderScriptRuntimeKernel() override = default; 3951 }; 3952 3953 class CommandObjectRenderScriptRuntimeContextDump : public CommandObjectParsed { 3954 public: 3955 CommandObjectRenderScriptRuntimeContextDump(CommandInterpreter &interpreter) 3956 : CommandObjectParsed(interpreter, "renderscript context dump", 3957 "Dumps renderscript context information.", 3958 "renderscript context dump", 3959 eCommandRequiresProcess | 3960 eCommandProcessMustBeLaunched) {} 3961 3962 ~CommandObjectRenderScriptRuntimeContextDump() override = default; 3963 3964 bool DoExecute(Args &command, CommandReturnObject &result) override { 3965 RenderScriptRuntime *runtime = 3966 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime( 3967 eLanguageTypeExtRenderScript); 3968 runtime->DumpContexts(result.GetOutputStream()); 3969 result.SetStatus(eReturnStatusSuccessFinishResult); 3970 return true; 3971 } 3972 }; 3973 3974 static OptionDefinition g_renderscript_runtime_alloc_dump_options[] = { 3975 {LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument, 3976 nullptr, nullptr, 0, eArgTypeFilename, 3977 "Print results to specified file instead of command line."}}; 3978 3979 class CommandObjectRenderScriptRuntimeContext : public CommandObjectMultiword { 3980 public: 3981 CommandObjectRenderScriptRuntimeContext(CommandInterpreter &interpreter) 3982 : CommandObjectMultiword(interpreter, "renderscript context", 3983 "Commands that deal with RenderScript contexts.", 3984 nullptr) { 3985 LoadSubCommand( 3986 "dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeContextDump( 3987 interpreter))); 3988 } 3989 3990 ~CommandObjectRenderScriptRuntimeContext() override = default; 3991 }; 3992 3993 class CommandObjectRenderScriptRuntimeAllocationDump 3994 : public CommandObjectParsed { 3995 public: 3996 CommandObjectRenderScriptRuntimeAllocationDump( 3997 CommandInterpreter &interpreter) 3998 : CommandObjectParsed(interpreter, "renderscript allocation dump", 3999 "Displays the contents of a particular allocation", 4000 "renderscript allocation dump <ID>", 4001 eCommandRequiresProcess | 4002 eCommandProcessMustBeLaunched), 4003 m_options() {} 4004 4005 ~CommandObjectRenderScriptRuntimeAllocationDump() override = default; 4006 4007 Options *GetOptions() override { return &m_options; } 4008 4009 class CommandOptions : public Options { 4010 public: 4011 CommandOptions() : Options() {} 4012 4013 ~CommandOptions() override = default; 4014 4015 Error SetOptionValue(uint32_t option_idx, const char *option_arg, 4016 ExecutionContext *execution_context) override { 4017 Error error; 4018 const int short_option = m_getopt_table[option_idx].val; 4019 4020 switch (short_option) { 4021 case 'f': 4022 m_outfile.SetFile(option_arg, true); 4023 if (m_outfile.Exists()) { 4024 m_outfile.Clear(); 4025 error.SetErrorStringWithFormat("file already exists: '%s'", 4026 option_arg); 4027 } 4028 break; 4029 default: 4030 error.SetErrorStringWithFormat("unrecognized option '%c'", 4031 short_option); 4032 break; 4033 } 4034 return error; 4035 } 4036 4037 void OptionParsingStarting(ExecutionContext *execution_context) override { 4038 m_outfile.Clear(); 4039 } 4040 4041 llvm::ArrayRef<OptionDefinition> GetDefinitions() override { 4042 return llvm::makeArrayRef(g_renderscript_runtime_alloc_dump_options); 4043 } 4044 4045 FileSpec m_outfile; 4046 }; 4047 4048 bool DoExecute(Args &command, CommandReturnObject &result) override { 4049 const size_t argc = command.GetArgumentCount(); 4050 if (argc < 1) { 4051 result.AppendErrorWithFormat("'%s' takes 1 argument, an allocation ID. " 4052 "As well as an optional -f argument", 4053 m_cmd_name.c_str()); 4054 result.SetStatus(eReturnStatusFailed); 4055 return false; 4056 } 4057 4058 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>( 4059 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime( 4060 eLanguageTypeExtRenderScript)); 4061 4062 const char *id_cstr = command.GetArgumentAtIndex(0); 4063 bool convert_complete = false; 4064 const uint32_t id = 4065 StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete); 4066 if (!convert_complete) { 4067 result.AppendErrorWithFormat("invalid allocation id argument '%s'", 4068 id_cstr); 4069 result.SetStatus(eReturnStatusFailed); 4070 return false; 4071 } 4072 4073 Stream *output_strm = nullptr; 4074 StreamFile outfile_stream; 4075 const FileSpec &outfile_spec = 4076 m_options.m_outfile; // Dump allocation to file instead 4077 if (outfile_spec) { 4078 // Open output file 4079 char path[256]; 4080 outfile_spec.GetPath(path, sizeof(path)); 4081 if (outfile_stream.GetFile() 4082 .Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate) 4083 .Success()) { 4084 output_strm = &outfile_stream; 4085 result.GetOutputStream().Printf("Results written to '%s'", path); 4086 result.GetOutputStream().EOL(); 4087 } else { 4088 result.AppendErrorWithFormat("Couldn't open file '%s'", path); 4089 result.SetStatus(eReturnStatusFailed); 4090 return false; 4091 } 4092 } else 4093 output_strm = &result.GetOutputStream(); 4094 4095 assert(output_strm != nullptr); 4096 bool success = 4097 runtime->DumpAllocation(*output_strm, m_exe_ctx.GetFramePtr(), id); 4098 4099 if (success) 4100 result.SetStatus(eReturnStatusSuccessFinishResult); 4101 else 4102 result.SetStatus(eReturnStatusFailed); 4103 4104 return true; 4105 } 4106 4107 private: 4108 CommandOptions m_options; 4109 }; 4110 4111 static OptionDefinition g_renderscript_runtime_alloc_list_options[] = { 4112 {LLDB_OPT_SET_1, false, "id", 'i', OptionParser::eRequiredArgument, nullptr, 4113 nullptr, 0, eArgTypeIndex, 4114 "Only show details of a single allocation with specified id."}}; 4115 4116 class CommandObjectRenderScriptRuntimeAllocationList 4117 : public CommandObjectParsed { 4118 public: 4119 CommandObjectRenderScriptRuntimeAllocationList( 4120 CommandInterpreter &interpreter) 4121 : CommandObjectParsed( 4122 interpreter, "renderscript allocation list", 4123 "List renderscript allocations and their information.", 4124 "renderscript allocation list", 4125 eCommandRequiresProcess | eCommandProcessMustBeLaunched), 4126 m_options() {} 4127 4128 ~CommandObjectRenderScriptRuntimeAllocationList() override = default; 4129 4130 Options *GetOptions() override { return &m_options; } 4131 4132 class CommandOptions : public Options { 4133 public: 4134 CommandOptions() : Options(), m_id(0) {} 4135 4136 ~CommandOptions() override = default; 4137 4138 Error SetOptionValue(uint32_t option_idx, const char *option_arg, 4139 ExecutionContext *execution_context) override { 4140 Error error; 4141 const int short_option = m_getopt_table[option_idx].val; 4142 4143 switch (short_option) { 4144 case 'i': 4145 bool success; 4146 m_id = StringConvert::ToUInt32(option_arg, 0, 0, &success); 4147 if (!success) 4148 error.SetErrorStringWithFormat( 4149 "invalid integer value for option '%c'", short_option); 4150 break; 4151 default: 4152 error.SetErrorStringWithFormat("unrecognized option '%c'", 4153 short_option); 4154 break; 4155 } 4156 return error; 4157 } 4158 4159 void OptionParsingStarting(ExecutionContext *execution_context) override { 4160 m_id = 0; 4161 } 4162 4163 llvm::ArrayRef<OptionDefinition> GetDefinitions() override { 4164 return llvm::makeArrayRef(g_renderscript_runtime_alloc_list_options); 4165 } 4166 4167 uint32_t m_id; 4168 }; 4169 4170 bool DoExecute(Args &command, CommandReturnObject &result) override { 4171 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>( 4172 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime( 4173 eLanguageTypeExtRenderScript)); 4174 runtime->ListAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr(), 4175 m_options.m_id); 4176 result.SetStatus(eReturnStatusSuccessFinishResult); 4177 return true; 4178 } 4179 4180 private: 4181 CommandOptions m_options; 4182 }; 4183 4184 class CommandObjectRenderScriptRuntimeAllocationLoad 4185 : public CommandObjectParsed { 4186 public: 4187 CommandObjectRenderScriptRuntimeAllocationLoad( 4188 CommandInterpreter &interpreter) 4189 : CommandObjectParsed( 4190 interpreter, "renderscript allocation load", 4191 "Loads renderscript allocation contents from a file.", 4192 "renderscript allocation load <ID> <filename>", 4193 eCommandRequiresProcess | eCommandProcessMustBeLaunched) {} 4194 4195 ~CommandObjectRenderScriptRuntimeAllocationLoad() override = default; 4196 4197 bool DoExecute(Args &command, CommandReturnObject &result) override { 4198 const size_t argc = command.GetArgumentCount(); 4199 if (argc != 2) { 4200 result.AppendErrorWithFormat( 4201 "'%s' takes 2 arguments, an allocation ID and filename to read from.", 4202 m_cmd_name.c_str()); 4203 result.SetStatus(eReturnStatusFailed); 4204 return false; 4205 } 4206 4207 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>( 4208 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime( 4209 eLanguageTypeExtRenderScript)); 4210 4211 const char *id_cstr = command.GetArgumentAtIndex(0); 4212 bool convert_complete = false; 4213 const uint32_t id = 4214 StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete); 4215 if (!convert_complete) { 4216 result.AppendErrorWithFormat("invalid allocation id argument '%s'", 4217 id_cstr); 4218 result.SetStatus(eReturnStatusFailed); 4219 return false; 4220 } 4221 4222 const char *filename = command.GetArgumentAtIndex(1); 4223 bool success = runtime->LoadAllocation(result.GetOutputStream(), id, 4224 filename, m_exe_ctx.GetFramePtr()); 4225 4226 if (success) 4227 result.SetStatus(eReturnStatusSuccessFinishResult); 4228 else 4229 result.SetStatus(eReturnStatusFailed); 4230 4231 return true; 4232 } 4233 }; 4234 4235 class CommandObjectRenderScriptRuntimeAllocationSave 4236 : public CommandObjectParsed { 4237 public: 4238 CommandObjectRenderScriptRuntimeAllocationSave( 4239 CommandInterpreter &interpreter) 4240 : CommandObjectParsed(interpreter, "renderscript allocation save", 4241 "Write renderscript allocation contents to a file.", 4242 "renderscript allocation save <ID> <filename>", 4243 eCommandRequiresProcess | 4244 eCommandProcessMustBeLaunched) {} 4245 4246 ~CommandObjectRenderScriptRuntimeAllocationSave() override = default; 4247 4248 bool DoExecute(Args &command, CommandReturnObject &result) override { 4249 const size_t argc = command.GetArgumentCount(); 4250 if (argc != 2) { 4251 result.AppendErrorWithFormat( 4252 "'%s' takes 2 arguments, an allocation ID and filename to read from.", 4253 m_cmd_name.c_str()); 4254 result.SetStatus(eReturnStatusFailed); 4255 return false; 4256 } 4257 4258 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>( 4259 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime( 4260 eLanguageTypeExtRenderScript)); 4261 4262 const char *id_cstr = command.GetArgumentAtIndex(0); 4263 bool convert_complete = false; 4264 const uint32_t id = 4265 StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete); 4266 if (!convert_complete) { 4267 result.AppendErrorWithFormat("invalid allocation id argument '%s'", 4268 id_cstr); 4269 result.SetStatus(eReturnStatusFailed); 4270 return false; 4271 } 4272 4273 const char *filename = command.GetArgumentAtIndex(1); 4274 bool success = runtime->SaveAllocation(result.GetOutputStream(), id, 4275 filename, m_exe_ctx.GetFramePtr()); 4276 4277 if (success) 4278 result.SetStatus(eReturnStatusSuccessFinishResult); 4279 else 4280 result.SetStatus(eReturnStatusFailed); 4281 4282 return true; 4283 } 4284 }; 4285 4286 class CommandObjectRenderScriptRuntimeAllocationRefresh 4287 : public CommandObjectParsed { 4288 public: 4289 CommandObjectRenderScriptRuntimeAllocationRefresh( 4290 CommandInterpreter &interpreter) 4291 : CommandObjectParsed(interpreter, "renderscript allocation refresh", 4292 "Recomputes the details of all allocations.", 4293 "renderscript allocation refresh", 4294 eCommandRequiresProcess | 4295 eCommandProcessMustBeLaunched) {} 4296 4297 ~CommandObjectRenderScriptRuntimeAllocationRefresh() override = default; 4298 4299 bool DoExecute(Args &command, CommandReturnObject &result) override { 4300 RenderScriptRuntime *runtime = static_cast<RenderScriptRuntime *>( 4301 m_exe_ctx.GetProcessPtr()->GetLanguageRuntime( 4302 eLanguageTypeExtRenderScript)); 4303 4304 bool success = runtime->RecomputeAllAllocations(result.GetOutputStream(), 4305 m_exe_ctx.GetFramePtr()); 4306 4307 if (success) { 4308 result.SetStatus(eReturnStatusSuccessFinishResult); 4309 return true; 4310 } else { 4311 result.SetStatus(eReturnStatusFailed); 4312 return false; 4313 } 4314 } 4315 }; 4316 4317 class CommandObjectRenderScriptRuntimeAllocation 4318 : public CommandObjectMultiword { 4319 public: 4320 CommandObjectRenderScriptRuntimeAllocation(CommandInterpreter &interpreter) 4321 : CommandObjectMultiword( 4322 interpreter, "renderscript allocation", 4323 "Commands that deal with RenderScript allocations.", nullptr) { 4324 LoadSubCommand( 4325 "list", 4326 CommandObjectSP( 4327 new CommandObjectRenderScriptRuntimeAllocationList(interpreter))); 4328 LoadSubCommand( 4329 "dump", 4330 CommandObjectSP( 4331 new CommandObjectRenderScriptRuntimeAllocationDump(interpreter))); 4332 LoadSubCommand( 4333 "save", 4334 CommandObjectSP( 4335 new CommandObjectRenderScriptRuntimeAllocationSave(interpreter))); 4336 LoadSubCommand( 4337 "load", 4338 CommandObjectSP( 4339 new CommandObjectRenderScriptRuntimeAllocationLoad(interpreter))); 4340 LoadSubCommand( 4341 "refresh", 4342 CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationRefresh( 4343 interpreter))); 4344 } 4345 4346 ~CommandObjectRenderScriptRuntimeAllocation() override = default; 4347 }; 4348 4349 class CommandObjectRenderScriptRuntimeStatus : public CommandObjectParsed { 4350 public: 4351 CommandObjectRenderScriptRuntimeStatus(CommandInterpreter &interpreter) 4352 : CommandObjectParsed(interpreter, "renderscript status", 4353 "Displays current RenderScript runtime status.", 4354 "renderscript status", 4355 eCommandRequiresProcess | 4356 eCommandProcessMustBeLaunched) {} 4357 4358 ~CommandObjectRenderScriptRuntimeStatus() override = default; 4359 4360 bool DoExecute(Args &command, CommandReturnObject &result) override { 4361 RenderScriptRuntime *runtime = 4362 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime( 4363 eLanguageTypeExtRenderScript); 4364 runtime->Status(result.GetOutputStream()); 4365 result.SetStatus(eReturnStatusSuccessFinishResult); 4366 return true; 4367 } 4368 }; 4369 4370 class CommandObjectRenderScriptRuntime : public CommandObjectMultiword { 4371 public: 4372 CommandObjectRenderScriptRuntime(CommandInterpreter &interpreter) 4373 : CommandObjectMultiword( 4374 interpreter, "renderscript", 4375 "Commands for operating on the RenderScript runtime.", 4376 "renderscript <subcommand> [<subcommand-options>]") { 4377 LoadSubCommand( 4378 "module", CommandObjectSP( 4379 new CommandObjectRenderScriptRuntimeModule(interpreter))); 4380 LoadSubCommand( 4381 "status", CommandObjectSP( 4382 new CommandObjectRenderScriptRuntimeStatus(interpreter))); 4383 LoadSubCommand( 4384 "kernel", CommandObjectSP( 4385 new CommandObjectRenderScriptRuntimeKernel(interpreter))); 4386 LoadSubCommand("context", 4387 CommandObjectSP(new CommandObjectRenderScriptRuntimeContext( 4388 interpreter))); 4389 LoadSubCommand( 4390 "allocation", 4391 CommandObjectSP( 4392 new CommandObjectRenderScriptRuntimeAllocation(interpreter))); 4393 } 4394 4395 ~CommandObjectRenderScriptRuntime() override = default; 4396 }; 4397 4398 void RenderScriptRuntime::Initiate() { assert(!m_initiated); } 4399 4400 RenderScriptRuntime::RenderScriptRuntime(Process *process) 4401 : lldb_private::CPPLanguageRuntime(process), m_initiated(false), 4402 m_debuggerPresentFlagged(false), m_breakAllKernels(false), 4403 m_ir_passes(nullptr) { 4404 ModulesDidLoad(process->GetTarget().GetImages()); 4405 } 4406 4407 lldb::CommandObjectSP RenderScriptRuntime::GetCommandObject( 4408 lldb_private::CommandInterpreter &interpreter) { 4409 return CommandObjectSP(new CommandObjectRenderScriptRuntime(interpreter)); 4410 } 4411 4412 RenderScriptRuntime::~RenderScriptRuntime() = default; 4413