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