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