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