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