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