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