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