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