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