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