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