1 //===-- RenderScriptRuntime.cpp ---------------------------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 // C Includes 11 // C++ Includes 12 // Other libraries and framework includes 13 // Project includes 14 #include "RenderScriptRuntime.h" 15 16 #include "lldb/Core/ConstString.h" 17 #include "lldb/Core/Debugger.h" 18 #include "lldb/Core/Error.h" 19 #include "lldb/Core/Log.h" 20 #include "lldb/Core/PluginManager.h" 21 #include "lldb/Core/ValueObjectVariable.h" 22 #include "lldb/Core/RegularExpression.h" 23 #include "lldb/DataFormatters/DumpValueObjectOptions.h" 24 #include "lldb/Host/StringConvert.h" 25 #include "lldb/Symbol/Symbol.h" 26 #include "lldb/Symbol/Type.h" 27 #include "lldb/Target/Process.h" 28 #include "lldb/Target/Target.h" 29 #include "lldb/Target/Thread.h" 30 #include "lldb/Interpreter/Args.h" 31 #include "lldb/Interpreter/Options.h" 32 #include "lldb/Interpreter/CommandInterpreter.h" 33 #include "lldb/Interpreter/CommandReturnObject.h" 34 #include "lldb/Interpreter/CommandObjectMultiword.h" 35 #include "lldb/Breakpoint/StoppointCallbackContext.h" 36 #include "lldb/Target/RegisterContext.h" 37 #include "lldb/Expression/UserExpression.h" 38 #include "lldb/Symbol/VariableList.h" 39 40 using namespace lldb; 41 using namespace lldb_private; 42 using namespace lldb_renderscript; 43 44 namespace { 45 46 // The empirical_type adds a basic level of validation to arbitrary data 47 // allowing us to track if data has been discovered and stored or not. 48 // An empirical_type will be marked as valid only if it has been explicitly assigned to. 49 template <typename type_t> 50 class empirical_type 51 { 52 public: 53 // Ctor. Contents is invalid when constructed. 54 empirical_type() 55 : valid(false) 56 {} 57 58 // Return true and copy contents to out if valid, else return false. 59 bool get(type_t& out) const 60 { 61 if (valid) 62 out = data; 63 return valid; 64 } 65 66 // Return a pointer to the contents or nullptr if it was not valid. 67 const type_t* get() const 68 { 69 return valid ? &data : nullptr; 70 } 71 72 // Assign data explicitly. 73 void set(const type_t in) 74 { 75 data = in; 76 valid = true; 77 } 78 79 // Mark contents as invalid. 80 void invalidate() 81 { 82 valid = false; 83 } 84 85 // Returns true if this type contains valid data. 86 bool isValid() const 87 { 88 return valid; 89 } 90 91 // Assignment operator. 92 empirical_type<type_t>& operator = (const type_t in) 93 { 94 set(in); 95 return *this; 96 } 97 98 // Dereference operator returns contents. 99 // Warning: Will assert if not valid so use only when you know data is valid. 100 const type_t& operator * () const 101 { 102 assert(valid); 103 return data; 104 } 105 106 protected: 107 bool valid; 108 type_t data; 109 }; 110 111 } // anonymous namespace 112 113 // The ScriptDetails class collects data associated with a single script instance. 114 struct RenderScriptRuntime::ScriptDetails 115 { 116 ~ScriptDetails() = default; 117 118 enum ScriptType 119 { 120 eScript, 121 eScriptC 122 }; 123 124 // The derived type of the script. 125 empirical_type<ScriptType> type; 126 // The name of the original source file. 127 empirical_type<std::string> resName; 128 // Path to script .so file on the device. 129 empirical_type<std::string> scriptDyLib; 130 // Directory where kernel objects are cached on device. 131 empirical_type<std::string> cacheDir; 132 // Pointer to the context which owns this script. 133 empirical_type<lldb::addr_t> context; 134 // Pointer to the script object itself. 135 empirical_type<lldb::addr_t> script; 136 }; 137 138 // This Element class represents the Element object in RS, 139 // defining the type associated with an Allocation. 140 struct RenderScriptRuntime::Element 141 { 142 // Taken from rsDefines.h 143 enum DataKind 144 { 145 RS_KIND_USER, 146 RS_KIND_PIXEL_L = 7, 147 RS_KIND_PIXEL_A, 148 RS_KIND_PIXEL_LA, 149 RS_KIND_PIXEL_RGB, 150 RS_KIND_PIXEL_RGBA, 151 RS_KIND_PIXEL_DEPTH, 152 RS_KIND_PIXEL_YUV, 153 RS_KIND_INVALID = 100 154 }; 155 156 // Taken from rsDefines.h 157 enum DataType 158 { 159 RS_TYPE_NONE = 0, 160 RS_TYPE_FLOAT_16, 161 RS_TYPE_FLOAT_32, 162 RS_TYPE_FLOAT_64, 163 RS_TYPE_SIGNED_8, 164 RS_TYPE_SIGNED_16, 165 RS_TYPE_SIGNED_32, 166 RS_TYPE_SIGNED_64, 167 RS_TYPE_UNSIGNED_8, 168 RS_TYPE_UNSIGNED_16, 169 RS_TYPE_UNSIGNED_32, 170 RS_TYPE_UNSIGNED_64, 171 RS_TYPE_BOOLEAN 172 }; 173 174 std::vector<Element> children; // Child Element fields for structs 175 empirical_type<lldb::addr_t> element_ptr; // Pointer to the RS Element of the Type 176 empirical_type<DataType> type; // Type of each data pointer stored by the allocation 177 empirical_type<DataKind> type_kind; // Defines pixel type if Allocation is created from an image 178 empirical_type<uint32_t> type_vec_size; // Vector size of each data point, e.g '4' for uchar4 179 empirical_type<uint32_t> field_count; // Number of Subelements 180 empirical_type<uint32_t> datum_size; // Size of a single Element with padding 181 empirical_type<uint32_t> padding; // Number of padding bytes 182 empirical_type<uint32_t> array_size; // Number of items in array, only needed for strucrs 183 ConstString type_name; // Name of type, only needed for structs 184 185 static const ConstString &GetFallbackStructName(); // Print this as the type name of a struct Element 186 // If we can't resolve the actual struct name 187 188 bool shouldRefresh() const 189 { 190 const bool valid_ptr = element_ptr.isValid() && *element_ptr.get() != 0x0; 191 const bool valid_type = type.isValid() && type_vec_size.isValid() && type_kind.isValid(); 192 return !valid_ptr || !valid_type || !datum_size.isValid(); 193 } 194 }; 195 196 // This AllocationDetails class collects data associated with a single 197 // allocation instance. 198 struct RenderScriptRuntime::AllocationDetails 199 { 200 struct Dimension 201 { 202 uint32_t dim_1; 203 uint32_t dim_2; 204 uint32_t dim_3; 205 uint32_t cubeMap; 206 207 Dimension() 208 { 209 dim_1 = 0; 210 dim_2 = 0; 211 dim_3 = 0; 212 cubeMap = 0; 213 } 214 }; 215 216 // Header for reading and writing allocation contents 217 // to a binary file. 218 struct FileHeader 219 { 220 uint8_t ident[4]; // ASCII 'RSAD' identifying the file 221 uint16_t hdr_size; // Header size in bytes, for backwards compatability 222 uint16_t type; // DataType enum 223 uint32_t kind; // DataKind enum 224 uint32_t dims[3]; // Dimensions 225 uint32_t element_size; // Size of a single element, including padding 226 }; 227 228 // Monotonically increasing from 1 229 static unsigned int ID; 230 231 // Maps Allocation DataType enum and vector size to printable strings 232 // using mapping from RenderScript numerical types summary documentation 233 static const char* RsDataTypeToString[][4]; 234 235 // Maps Allocation DataKind enum to printable strings 236 static const char* RsDataKindToString[]; 237 238 // Maps allocation types to format sizes for printing. 239 static const unsigned int RSTypeToFormat[][3]; 240 241 // Give each allocation an ID as a way 242 // for commands to reference it. 243 const unsigned int id; 244 245 RenderScriptRuntime::Element element; // Allocation Element type 246 empirical_type<Dimension> dimension; // Dimensions of the Allocation 247 empirical_type<lldb::addr_t> address; // Pointer to address of the RS Allocation 248 empirical_type<lldb::addr_t> data_ptr; // Pointer to the data held by the Allocation 249 empirical_type<lldb::addr_t> type_ptr; // Pointer to the RS Type of the Allocation 250 empirical_type<lldb::addr_t> context; // Pointer to the RS Context of the Allocation 251 empirical_type<uint32_t> size; // Size of the allocation 252 empirical_type<uint32_t> stride; // Stride between rows of the allocation 253 254 // Give each allocation an id, so we can reference it in user commands. 255 AllocationDetails(): id(ID++) 256 { 257 } 258 259 bool shouldRefresh() const 260 { 261 bool valid_ptrs = data_ptr.isValid() && *data_ptr.get() != 0x0; 262 valid_ptrs = valid_ptrs && type_ptr.isValid() && *type_ptr.get() != 0x0; 263 return !valid_ptrs || !dimension.isValid() || !size.isValid() || element.shouldRefresh(); 264 } 265 }; 266 267 268 const ConstString & 269 RenderScriptRuntime::Element::GetFallbackStructName() 270 { 271 static const ConstString FallbackStructName("struct"); 272 return FallbackStructName; 273 } 274 275 unsigned int RenderScriptRuntime::AllocationDetails::ID = 1; 276 277 const char* RenderScriptRuntime::AllocationDetails::RsDataKindToString[] = 278 { 279 "User", 280 "Undefined", "Undefined", "Undefined", // Enum jumps from 0 to 7 281 "Undefined", "Undefined", "Undefined", 282 "L Pixel", 283 "A Pixel", 284 "LA Pixel", 285 "RGB Pixel", 286 "RGBA Pixel", 287 "Pixel Depth", 288 "YUV Pixel" 289 }; 290 291 const char* RenderScriptRuntime::AllocationDetails::RsDataTypeToString[][4] = 292 { 293 {"None", "None", "None", "None"}, 294 {"half", "half2", "half3", "half4"}, 295 {"float", "float2", "float3", "float4"}, 296 {"double", "double2", "double3", "double4"}, 297 {"char", "char2", "char3", "char4"}, 298 {"short", "short2", "short3", "short4"}, 299 {"int", "int2", "int3", "int4"}, 300 {"long", "long2", "long3", "long4"}, 301 {"uchar", "uchar2", "uchar3", "uchar4"}, 302 {"ushort", "ushort2", "ushort3", "ushort4"}, 303 {"uint", "uint2", "uint3", "uint4"}, 304 {"ulong", "ulong2", "ulong3", "ulong4"}, 305 {"bool", "bool2", "bool3", "bool4"} 306 }; 307 308 // Used as an index into the RSTypeToFormat array elements 309 enum TypeToFormatIndex { 310 eFormatSingle = 0, 311 eFormatVector, 312 eElementSize 313 }; 314 315 // { format enum of single element, format enum of element vector, size of element} 316 const unsigned int RenderScriptRuntime::AllocationDetails::RSTypeToFormat[][3] = 317 { 318 {eFormatHex, eFormatHex, 1}, // RS_TYPE_NONE 319 {eFormatFloat, eFormatVectorOfFloat16, 2}, // RS_TYPE_FLOAT_16 320 {eFormatFloat, eFormatVectorOfFloat32, sizeof(float)}, // RS_TYPE_FLOAT_32 321 {eFormatFloat, eFormatVectorOfFloat64, sizeof(double)}, // RS_TYPE_FLOAT_64 322 {eFormatDecimal, eFormatVectorOfSInt8, sizeof(int8_t)}, // RS_TYPE_SIGNED_8 323 {eFormatDecimal, eFormatVectorOfSInt16, sizeof(int16_t)}, // RS_TYPE_SIGNED_16 324 {eFormatDecimal, eFormatVectorOfSInt32, sizeof(int32_t)}, // RS_TYPE_SIGNED_32 325 {eFormatDecimal, eFormatVectorOfSInt64, sizeof(int64_t)}, // RS_TYPE_SIGNED_64 326 {eFormatDecimal, eFormatVectorOfUInt8, sizeof(uint8_t)}, // RS_TYPE_UNSIGNED_8 327 {eFormatDecimal, eFormatVectorOfUInt16, sizeof(uint16_t)}, // RS_TYPE_UNSIGNED_16 328 {eFormatDecimal, eFormatVectorOfUInt32, sizeof(uint32_t)}, // RS_TYPE_UNSIGNED_32 329 {eFormatDecimal, eFormatVectorOfUInt64, sizeof(uint64_t)}, // RS_TYPE_UNSIGNED_64 330 {eFormatBoolean, eFormatBoolean, sizeof(bool)} // RS_TYPE_BOOL 331 }; 332 333 //------------------------------------------------------------------ 334 // Static Functions 335 //------------------------------------------------------------------ 336 LanguageRuntime * 337 RenderScriptRuntime::CreateInstance(Process *process, lldb::LanguageType language) 338 { 339 340 if (language == eLanguageTypeExtRenderScript) 341 return new RenderScriptRuntime(process); 342 else 343 return NULL; 344 } 345 346 // Callback with a module to search for matching symbols. 347 // We first check that the module contains RS kernels. 348 // Then look for a symbol which matches our kernel name. 349 // The breakpoint address is finally set using the address of this symbol. 350 Searcher::CallbackReturn 351 RSBreakpointResolver::SearchCallback(SearchFilter &filter, 352 SymbolContext &context, 353 Address*, 354 bool) 355 { 356 ModuleSP module = context.module_sp; 357 358 if (!module) 359 return Searcher::eCallbackReturnContinue; 360 361 // Is this a module containing renderscript kernels? 362 if (nullptr == module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData)) 363 return Searcher::eCallbackReturnContinue; 364 365 // Attempt to set a breakpoint on the kernel name symbol within the module library. 366 // If it's not found, it's likely debug info is unavailable - try to set a 367 // breakpoint on <name>.expand. 368 369 const Symbol* kernel_sym = module->FindFirstSymbolWithNameAndType(m_kernel_name, eSymbolTypeCode); 370 if (!kernel_sym) 371 { 372 std::string kernel_name_expanded(m_kernel_name.AsCString()); 373 kernel_name_expanded.append(".expand"); 374 kernel_sym = module->FindFirstSymbolWithNameAndType(ConstString(kernel_name_expanded.c_str()), eSymbolTypeCode); 375 } 376 377 if (kernel_sym) 378 { 379 Address bp_addr = kernel_sym->GetAddress(); 380 if (filter.AddressPasses(bp_addr)) 381 m_breakpoint->AddLocation(bp_addr); 382 } 383 384 return Searcher::eCallbackReturnContinue; 385 } 386 387 void 388 RenderScriptRuntime::Initialize() 389 { 390 PluginManager::RegisterPlugin(GetPluginNameStatic(), "RenderScript language support", CreateInstance, GetCommandObject); 391 } 392 393 void 394 RenderScriptRuntime::Terminate() 395 { 396 PluginManager::UnregisterPlugin(CreateInstance); 397 } 398 399 lldb_private::ConstString 400 RenderScriptRuntime::GetPluginNameStatic() 401 { 402 static ConstString g_name("renderscript"); 403 return g_name; 404 } 405 406 RenderScriptRuntime::ModuleKind 407 RenderScriptRuntime::GetModuleKind(const lldb::ModuleSP &module_sp) 408 { 409 if (module_sp) 410 { 411 // Is this a module containing renderscript kernels? 412 const Symbol *info_sym = module_sp->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData); 413 if (info_sym) 414 { 415 return eModuleKindKernelObj; 416 } 417 418 // Is this the main RS runtime library 419 const ConstString rs_lib("libRS.so"); 420 if (module_sp->GetFileSpec().GetFilename() == rs_lib) 421 { 422 return eModuleKindLibRS; 423 } 424 425 const ConstString rs_driverlib("libRSDriver.so"); 426 if (module_sp->GetFileSpec().GetFilename() == rs_driverlib) 427 { 428 return eModuleKindDriver; 429 } 430 431 const ConstString rs_cpureflib("libRSCpuRef.so"); 432 if (module_sp->GetFileSpec().GetFilename() == rs_cpureflib) 433 { 434 return eModuleKindImpl; 435 } 436 437 } 438 return eModuleKindIgnored; 439 } 440 441 bool 442 RenderScriptRuntime::IsRenderScriptModule(const lldb::ModuleSP &module_sp) 443 { 444 return GetModuleKind(module_sp) != eModuleKindIgnored; 445 } 446 447 void 448 RenderScriptRuntime::ModulesDidLoad(const ModuleList &module_list ) 449 { 450 Mutex::Locker locker (module_list.GetMutex ()); 451 452 size_t num_modules = module_list.GetSize(); 453 for (size_t i = 0; i < num_modules; i++) 454 { 455 auto mod = module_list.GetModuleAtIndex (i); 456 if (IsRenderScriptModule (mod)) 457 { 458 LoadModule(mod); 459 } 460 } 461 } 462 463 //------------------------------------------------------------------ 464 // PluginInterface protocol 465 //------------------------------------------------------------------ 466 lldb_private::ConstString 467 RenderScriptRuntime::GetPluginName() 468 { 469 return GetPluginNameStatic(); 470 } 471 472 uint32_t 473 RenderScriptRuntime::GetPluginVersion() 474 { 475 return 1; 476 } 477 478 bool 479 RenderScriptRuntime::IsVTableName(const char *name) 480 { 481 return false; 482 } 483 484 bool 485 RenderScriptRuntime::GetDynamicTypeAndAddress(ValueObject &in_value, lldb::DynamicValueType use_dynamic, 486 TypeAndOrName &class_type_or_name, Address &address, 487 Value::ValueType &value_type) 488 { 489 return false; 490 } 491 492 TypeAndOrName 493 RenderScriptRuntime::FixUpDynamicType (const TypeAndOrName& type_and_or_name, 494 ValueObject& static_value) 495 { 496 return type_and_or_name; 497 } 498 499 bool 500 RenderScriptRuntime::CouldHaveDynamicValue(ValueObject &in_value) 501 { 502 return false; 503 } 504 505 lldb::BreakpointResolverSP 506 RenderScriptRuntime::CreateExceptionResolver(Breakpoint *bkpt, bool catch_bp, bool throw_bp) 507 { 508 BreakpointResolverSP resolver_sp; 509 return resolver_sp; 510 } 511 512 const RenderScriptRuntime::HookDefn RenderScriptRuntime::s_runtimeHookDefns[] = 513 { 514 //rsdScript 515 { 516 "rsdScriptInit", //name 517 "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_7ScriptCEPKcS7_PKhjj", // symbol name 32 bit 518 "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_7ScriptCEPKcS7_PKhmj", // symbol name 64 bit 519 0, // version 520 RenderScriptRuntime::eModuleKindDriver, // type 521 &lldb_private::RenderScriptRuntime::CaptureScriptInit1 // handler 522 }, 523 { 524 "rsdScriptInvokeForEach", // name 525 "_Z22rsdScriptInvokeForEachPKN7android12renderscript7ContextEPNS0_6ScriptEjPKNS0_10AllocationEPS6_PKvjPK12RsScriptCall", // symbol name 32bit 526 "_Z22rsdScriptInvokeForEachPKN7android12renderscript7ContextEPNS0_6ScriptEjPKNS0_10AllocationEPS6_PKvmPK12RsScriptCall", // symbol name 64bit 527 0, // version 528 RenderScriptRuntime::eModuleKindDriver, // type 529 nullptr // handler 530 }, 531 { 532 "rsdScriptInvokeForEachMulti", // name 533 "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0_6ScriptEjPPKNS0_10AllocationEjPS6_PKvjPK12RsScriptCall", // symbol name 32bit 534 "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0_6ScriptEjPPKNS0_10AllocationEmPS6_PKvmPK12RsScriptCall", // symbol name 64bit 535 0, // version 536 RenderScriptRuntime::eModuleKindDriver, // type 537 nullptr // handler 538 }, 539 { 540 "rsdScriptInvokeFunction", // name 541 "_Z23rsdScriptInvokeFunctionPKN7android12renderscript7ContextEPNS0_6ScriptEjPKvj", // symbol name 32bit 542 "_Z23rsdScriptInvokeFunctionPKN7android12renderscript7ContextEPNS0_6ScriptEjPKvm", // symbol name 64bit 543 0, // version 544 RenderScriptRuntime::eModuleKindDriver, // type 545 nullptr // handler 546 }, 547 { 548 "rsdScriptSetGlobalVar", // name 549 "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_6ScriptEjPvj", // symbol name 32bit 550 "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_6ScriptEjPvm", // symbol name 64bit 551 0, // version 552 RenderScriptRuntime::eModuleKindDriver, // type 553 &lldb_private::RenderScriptRuntime::CaptureSetGlobalVar1 // handler 554 }, 555 556 //rsdAllocation 557 { 558 "rsdAllocationInit", // name 559 "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_10AllocationEb", // symbol name 32bit 560 "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_10AllocationEb", // symbol name 64bit 561 0, // version 562 RenderScriptRuntime::eModuleKindDriver, // type 563 &lldb_private::RenderScriptRuntime::CaptureAllocationInit1 // handler 564 }, 565 { 566 "rsdAllocationRead2D", //name 567 "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_10AllocationEjjj23RsAllocationCubemapFacejjPvjj", // symbol name 32bit 568 "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_10AllocationEjjj23RsAllocationCubemapFacejjPvmm", // symbol name 64bit 569 0, // version 570 RenderScriptRuntime::eModuleKindDriver, // type 571 nullptr // handler 572 }, 573 { 574 "rsdAllocationDestroy", // name 575 "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_10AllocationE", // symbol name 32bit 576 "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_10AllocationE", // symbol name 64bit 577 0, // version 578 RenderScriptRuntime::eModuleKindDriver, // type 579 &lldb_private::RenderScriptRuntime::CaptureAllocationDestroy // handler 580 }, 581 }; 582 583 const size_t RenderScriptRuntime::s_runtimeHookCount = sizeof(s_runtimeHookDefns)/sizeof(s_runtimeHookDefns[0]); 584 585 bool 586 RenderScriptRuntime::HookCallback(void *baton, StoppointCallbackContext *ctx, lldb::user_id_t break_id, lldb::user_id_t break_loc_id) 587 { 588 RuntimeHook* hook_info = (RuntimeHook*)baton; 589 ExecutionContext context(ctx->exe_ctx_ref); 590 591 RenderScriptRuntime *lang_rt = (RenderScriptRuntime *)context.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript); 592 593 lang_rt->HookCallback(hook_info, context); 594 595 return false; 596 } 597 598 void 599 RenderScriptRuntime::HookCallback(RuntimeHook* hook_info, ExecutionContext& context) 600 { 601 Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 602 603 if (log) 604 log->Printf ("RenderScriptRuntime::HookCallback - '%s' .", hook_info->defn->name); 605 606 if (hook_info->defn->grabber) 607 { 608 (this->*(hook_info->defn->grabber))(hook_info, context); 609 } 610 } 611 612 bool 613 RenderScriptRuntime::GetArgSimple(ExecutionContext &context, uint32_t arg, uint64_t *data) 614 { 615 if (!data) 616 return false; 617 618 Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 619 Error error; 620 RegisterContext* reg_ctx = context.GetRegisterContext(); 621 Process* process = context.GetProcessPtr(); 622 bool success = false; // return value 623 624 if (!context.GetTargetPtr()) 625 { 626 if (log) 627 log->Printf("RenderScriptRuntime::GetArgSimple - Invalid target"); 628 629 return false; 630 } 631 632 switch (context.GetTargetPtr()->GetArchitecture().GetMachine()) 633 { 634 case llvm::Triple::ArchType::x86: 635 { 636 uint64_t sp = reg_ctx->GetSP(); 637 uint32_t offset = (1 + arg) * sizeof(uint32_t); 638 uint32_t result = 0; 639 process->ReadMemory(sp + offset, &result, sizeof(uint32_t), error); 640 if (error.Fail()) 641 { 642 if (log) 643 log->Printf ("RenderScriptRuntime:: GetArgSimple - error reading X86 stack: %s.", error.AsCString()); 644 } 645 else 646 { 647 *data = result; 648 success = true; 649 } 650 651 break; 652 } 653 case llvm::Triple::ArchType::arm: 654 { 655 // arm 32 bit 656 if (arg < 4) 657 { 658 const RegisterInfo* rArg = reg_ctx->GetRegisterInfoAtIndex(arg); 659 RegisterValue rVal; 660 success = reg_ctx->ReadRegister(rArg, rVal); 661 if (success) 662 { 663 (*data) = rVal.GetAsUInt32(); 664 } 665 else 666 { 667 if (log) 668 log->Printf ("RenderScriptRuntime:: GetArgSimple - error reading ARM register: %d.", arg); 669 } 670 } 671 else 672 { 673 uint64_t sp = reg_ctx->GetSP(); 674 uint32_t offset = (arg-4) * sizeof(uint32_t); 675 process->ReadMemory(sp + offset, &data, sizeof(uint32_t), error); 676 if (error.Fail()) 677 { 678 if (log) 679 log->Printf ("RenderScriptRuntime:: GetArgSimple - error reading ARM stack: %s.", error.AsCString()); 680 } 681 else 682 { 683 success = true; 684 } 685 } 686 687 break; 688 } 689 case llvm::Triple::ArchType::aarch64: 690 { 691 // arm 64 bit 692 // first 8 arguments are in the registers 693 if (arg < 8) 694 { 695 const RegisterInfo* rArg = reg_ctx->GetRegisterInfoAtIndex(arg); 696 RegisterValue rVal; 697 success = reg_ctx->ReadRegister(rArg, rVal); 698 if (success) 699 { 700 *data = rVal.GetAsUInt64(); 701 } 702 else 703 { 704 if (log) 705 log->Printf("RenderScriptRuntime::GetArgSimple() - AARCH64 - Error while reading the argument #%d", arg); 706 } 707 } 708 else 709 { 710 // @TODO: need to find the argument in the stack 711 if (log) 712 log->Printf("RenderScriptRuntime::GetArgSimple - AARCH64 - FOR #ARG >= 8 NOT IMPLEMENTED YET. Argument number: %d", arg); 713 } 714 break; 715 } 716 case llvm::Triple::ArchType::mipsel: 717 { 718 719 // read from the registers 720 if (arg < 4){ 721 const RegisterInfo* rArg = reg_ctx->GetRegisterInfoAtIndex(arg + 4); 722 RegisterValue rVal; 723 success = reg_ctx->ReadRegister(rArg, rVal); 724 if (success) 725 { 726 *data = rVal.GetAsUInt64(); 727 } 728 else 729 { 730 if (log) 731 log->Printf("RenderScriptRuntime::GetArgSimple() - Mips - Error while reading the argument #%d", arg); 732 } 733 734 } 735 736 // read from the stack 737 else 738 { 739 uint64_t sp = reg_ctx->GetSP(); 740 uint32_t offset = arg * sizeof(uint32_t); 741 process->ReadMemory(sp + offset, &data, sizeof(uint32_t), error); 742 if (error.Fail()) 743 { 744 if (log) 745 log->Printf ("RenderScriptRuntime::GetArgSimple - error reading Mips stack: %s.", error.AsCString()); 746 } 747 else 748 { 749 success = true; 750 } 751 } 752 753 break; 754 } 755 case llvm::Triple::ArchType::mips64el: 756 { 757 // read from the registers 758 if (arg < 8) 759 { 760 const RegisterInfo* rArg = reg_ctx->GetRegisterInfoAtIndex(arg + 4); 761 RegisterValue rVal; 762 success = reg_ctx->ReadRegister(rArg, rVal); 763 if (success) 764 { 765 (*data) = rVal.GetAsUInt64(); 766 } 767 else 768 { 769 if (log) 770 log->Printf("RenderScriptRuntime::GetArgSimple - Mips64 - Error reading the argument #%d", arg); 771 } 772 } 773 774 // read from the stack 775 else 776 { 777 uint64_t sp = reg_ctx->GetSP(); 778 uint32_t offset = (arg - 8) * sizeof(uint64_t); 779 process->ReadMemory(sp + offset, &data, sizeof(uint64_t), error); 780 if (error.Fail()) 781 { 782 if (log) 783 log->Printf ("RenderScriptRuntime::GetArgSimple - Mips64 - Error reading Mips64 stack: %s.", error.AsCString()); 784 } 785 else 786 { 787 success = true; 788 } 789 } 790 791 break; 792 } 793 default: 794 { 795 // invalid architecture 796 if (log) 797 log->Printf("RenderScriptRuntime::GetArgSimple - Architecture not supported"); 798 799 } 800 } 801 802 return success; 803 } 804 805 void 806 RenderScriptRuntime::CaptureSetGlobalVar1(RuntimeHook* hook_info, ExecutionContext& context) 807 { 808 Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 809 810 //Context, Script, int, data, length 811 812 uint64_t rs_context_u64 = 0U; 813 uint64_t rs_script_u64 = 0U; 814 uint64_t rs_id_u64 = 0U; 815 uint64_t rs_data_u64 = 0U; 816 uint64_t rs_length_u64 = 0U; 817 818 bool success = 819 GetArgSimple(context, 0, &rs_context_u64) && 820 GetArgSimple(context, 1, &rs_script_u64) && 821 GetArgSimple(context, 2, &rs_id_u64) && 822 GetArgSimple(context, 3, &rs_data_u64) && 823 GetArgSimple(context, 4, &rs_length_u64); 824 825 if (!success) 826 { 827 if (log) 828 log->Printf("RenderScriptRuntime::CaptureSetGlobalVar1 - Error while reading the function parameters"); 829 return; 830 } 831 832 if (log) 833 { 834 log->Printf ("RenderScriptRuntime::CaptureSetGlobalVar1 - 0x%" PRIx64 ",0x%" PRIx64 " slot %" PRIu64 " = 0x%" PRIx64 ":%" PRIu64 "bytes.", 835 rs_context_u64, rs_script_u64, rs_id_u64, rs_data_u64, rs_length_u64); 836 837 addr_t script_addr = (addr_t)rs_script_u64; 838 if (m_scriptMappings.find( script_addr ) != m_scriptMappings.end()) 839 { 840 auto rsm = m_scriptMappings[script_addr]; 841 if (rs_id_u64 < rsm->m_globals.size()) 842 { 843 auto rsg = rsm->m_globals[rs_id_u64]; 844 log->Printf ("RenderScriptRuntime::CaptureSetGlobalVar1 - Setting of '%s' within '%s' inferred", rsg.m_name.AsCString(), 845 rsm->m_module->GetFileSpec().GetFilename().AsCString()); 846 } 847 } 848 } 849 } 850 851 void 852 RenderScriptRuntime::CaptureAllocationInit1(RuntimeHook* hook_info, ExecutionContext& context) 853 { 854 Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 855 856 //Context, Alloc, bool 857 858 uint64_t rs_context_u64 = 0U; 859 uint64_t rs_alloc_u64 = 0U; 860 uint64_t rs_forceZero_u64 = 0U; 861 862 bool success = 863 GetArgSimple(context, 0, &rs_context_u64) && 864 GetArgSimple(context, 1, &rs_alloc_u64) && 865 GetArgSimple(context, 2, &rs_forceZero_u64); 866 if (!success) // error case 867 { 868 if (log) 869 log->Printf("RenderScriptRuntime::CaptureAllocationInit1 - Error while reading the function parameters"); 870 return; // abort 871 } 872 873 if (log) 874 log->Printf ("RenderScriptRuntime::CaptureAllocationInit1 - 0x%" PRIx64 ",0x%" PRIx64 ",0x%" PRIx64 " .", 875 rs_context_u64, rs_alloc_u64, rs_forceZero_u64); 876 877 AllocationDetails* alloc = LookUpAllocation(rs_alloc_u64, true); 878 if (alloc) 879 alloc->context = rs_context_u64; 880 } 881 882 void 883 RenderScriptRuntime::CaptureAllocationDestroy(RuntimeHook* hook_info, ExecutionContext& context) 884 { 885 Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 886 887 // Context, Alloc 888 uint64_t rs_context_u64 = 0U; 889 uint64_t rs_alloc_u64 = 0U; 890 891 bool success = GetArgSimple(context, 0, &rs_context_u64) && GetArgSimple(context, 1, &rs_alloc_u64); 892 if (!success) // error case 893 { 894 if (log) 895 log->Printf("RenderScriptRuntime::CaptureAllocationDestroy - Error while reading the function parameters"); 896 return; // abort 897 } 898 899 if (log) 900 log->Printf("RenderScriptRuntime::CaptureAllocationDestroy - 0x%" PRIx64 ", 0x%" PRIx64 ".", 901 rs_context_u64, rs_alloc_u64); 902 903 for (auto iter = m_allocations.begin(); iter != m_allocations.end(); ++iter) 904 { 905 auto& allocation_ap = *iter; // get the unique pointer 906 if (allocation_ap->address.isValid() && *allocation_ap->address.get() == rs_alloc_u64) 907 { 908 m_allocations.erase(iter); 909 if (log) 910 log->Printf("RenderScriptRuntime::CaptureAllocationDestroy - Deleted allocation entry"); 911 return; 912 } 913 } 914 915 if (log) 916 log->Printf("RenderScriptRuntime::CaptureAllocationDestroy - Couldn't find destroyed allocation"); 917 } 918 919 void 920 RenderScriptRuntime::CaptureScriptInit1(RuntimeHook* hook_info, ExecutionContext& context) 921 { 922 Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 923 924 //Context, Script, resname Str, cachedir Str 925 Error error; 926 Process* process = context.GetProcessPtr(); 927 928 uint64_t rs_context_u64 = 0U; 929 uint64_t rs_script_u64 = 0U; 930 uint64_t rs_resnameptr_u64 = 0U; 931 uint64_t rs_cachedirptr_u64 = 0U; 932 933 std::string resname; 934 std::string cachedir; 935 936 // read the function parameters 937 bool success = 938 GetArgSimple(context, 0, &rs_context_u64) && 939 GetArgSimple(context, 1, &rs_script_u64) && 940 GetArgSimple(context, 2, &rs_resnameptr_u64) && 941 GetArgSimple(context, 3, &rs_cachedirptr_u64); 942 943 if (!success) 944 { 945 if (log) 946 log->Printf("RenderScriptRuntime::CaptureScriptInit1 - Error while reading the function parameters"); 947 return; 948 } 949 950 process->ReadCStringFromMemory((lldb::addr_t)rs_resnameptr_u64, resname, error); 951 if (error.Fail()) 952 { 953 if (log) 954 log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - error reading resname: %s.", error.AsCString()); 955 956 } 957 958 process->ReadCStringFromMemory((lldb::addr_t)rs_cachedirptr_u64, cachedir, error); 959 if (error.Fail()) 960 { 961 if (log) 962 log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - error reading cachedir: %s.", error.AsCString()); 963 } 964 965 if (log) 966 log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - 0x%" PRIx64 ",0x%" PRIx64 " => '%s' at '%s' .", 967 rs_context_u64, rs_script_u64, resname.c_str(), cachedir.c_str()); 968 969 if (resname.size() > 0) 970 { 971 StreamString strm; 972 strm.Printf("librs.%s.so", resname.c_str()); 973 974 ScriptDetails* script = LookUpScript(rs_script_u64, true); 975 if (script) 976 { 977 script->type = ScriptDetails::eScriptC; 978 script->cacheDir = cachedir; 979 script->resName = resname; 980 script->scriptDyLib = strm.GetData(); 981 script->context = addr_t(rs_context_u64); 982 } 983 984 if (log) 985 log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - '%s' tagged with context 0x%" PRIx64 " and script 0x%" PRIx64 ".", 986 strm.GetData(), rs_context_u64, rs_script_u64); 987 } 988 else if (log) 989 { 990 log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - resource name invalid, Script not tagged"); 991 } 992 } 993 994 void 995 RenderScriptRuntime::LoadRuntimeHooks(lldb::ModuleSP module, ModuleKind kind) 996 { 997 Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 998 999 if (!module) 1000 { 1001 return; 1002 } 1003 1004 Target &target = GetProcess()->GetTarget(); 1005 llvm::Triple::ArchType targetArchType = target.GetArchitecture().GetMachine(); 1006 1007 if (targetArchType != llvm::Triple::ArchType::x86 1008 && targetArchType != llvm::Triple::ArchType::arm 1009 && targetArchType != llvm::Triple::ArchType::aarch64 1010 && targetArchType != llvm::Triple::ArchType::mipsel 1011 && targetArchType != llvm::Triple::ArchType::mips64el 1012 ) 1013 { 1014 if (log) 1015 log->Printf ("RenderScriptRuntime::LoadRuntimeHooks - Unable to hook runtime. Only X86, ARM, Mips supported currently."); 1016 1017 return; 1018 } 1019 1020 uint32_t archByteSize = target.GetArchitecture().GetAddressByteSize(); 1021 1022 for (size_t idx = 0; idx < s_runtimeHookCount; idx++) 1023 { 1024 const HookDefn* hook_defn = &s_runtimeHookDefns[idx]; 1025 if (hook_defn->kind != kind) { 1026 continue; 1027 } 1028 1029 const char* symbol_name = (archByteSize == 4) ? hook_defn->symbol_name_m32 : hook_defn->symbol_name_m64; 1030 1031 const Symbol *sym = module->FindFirstSymbolWithNameAndType(ConstString(symbol_name), eSymbolTypeCode); 1032 if (!sym){ 1033 if (log){ 1034 log->Printf("RenderScriptRuntime::LoadRuntimeHooks - ERROR: Symbol '%s' related to the function %s not found", symbol_name, hook_defn->name); 1035 } 1036 continue; 1037 } 1038 1039 addr_t addr = sym->GetLoadAddress(&target); 1040 if (addr == LLDB_INVALID_ADDRESS) 1041 { 1042 if (log) 1043 log->Printf ("RenderScriptRuntime::LoadRuntimeHooks - Unable to resolve the address of hook function '%s' with symbol '%s'.", 1044 hook_defn->name, symbol_name); 1045 continue; 1046 } 1047 else 1048 { 1049 if (log) 1050 log->Printf("RenderScriptRuntime::LoadRuntimeHooks - Function %s, address resolved at 0x%" PRIx64, hook_defn->name, addr); 1051 } 1052 1053 RuntimeHookSP hook(new RuntimeHook()); 1054 hook->address = addr; 1055 hook->defn = hook_defn; 1056 hook->bp_sp = target.CreateBreakpoint(addr, true, false); 1057 hook->bp_sp->SetCallback(HookCallback, hook.get(), true); 1058 m_runtimeHooks[addr] = hook; 1059 if (log) 1060 { 1061 log->Printf ("RenderScriptRuntime::LoadRuntimeHooks - Successfully hooked '%s' in '%s' version %" PRIu64 " at 0x%" PRIx64 ".", 1062 hook_defn->name, module->GetFileSpec().GetFilename().AsCString(), (uint64_t)hook_defn->version, (uint64_t)addr); 1063 } 1064 } 1065 } 1066 1067 void 1068 RenderScriptRuntime::FixupScriptDetails(RSModuleDescriptorSP rsmodule_sp) 1069 { 1070 if (!rsmodule_sp) 1071 return; 1072 1073 Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 1074 1075 const ModuleSP module = rsmodule_sp->m_module; 1076 const FileSpec& file = module->GetPlatformFileSpec(); 1077 1078 // Iterate over all of the scripts that we currently know of. 1079 // Note: We cant push or pop to m_scripts here or it may invalidate rs_script. 1080 for (const auto & rs_script : m_scripts) 1081 { 1082 // Extract the expected .so file path for this script. 1083 std::string dylib; 1084 if (!rs_script->scriptDyLib.get(dylib)) 1085 continue; 1086 1087 // Only proceed if the module that has loaded corresponds to this script. 1088 if (file.GetFilename() != ConstString(dylib.c_str())) 1089 continue; 1090 1091 // Obtain the script address which we use as a key. 1092 lldb::addr_t script; 1093 if (!rs_script->script.get(script)) 1094 continue; 1095 1096 // If we have a script mapping for the current script. 1097 if (m_scriptMappings.find(script) != m_scriptMappings.end()) 1098 { 1099 // if the module we have stored is different to the one we just received. 1100 if (m_scriptMappings[script] != rsmodule_sp) 1101 { 1102 if (log) 1103 log->Printf ("RenderScriptRuntime::FixupScriptDetails - Error: script %" PRIx64 " wants reassigned to new rsmodule '%s'.", 1104 (uint64_t)script, rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString()); 1105 } 1106 } 1107 // We don't have a script mapping for the current script. 1108 else 1109 { 1110 // Obtain the script resource name. 1111 std::string resName; 1112 if (rs_script->resName.get(resName)) 1113 // Set the modules resource name. 1114 rsmodule_sp->m_resname = resName; 1115 // Add Script/Module pair to map. 1116 m_scriptMappings[script] = rsmodule_sp; 1117 if (log) 1118 log->Printf ("RenderScriptRuntime::FixupScriptDetails - script %" PRIx64 " associated with rsmodule '%s'.", 1119 (uint64_t)script, rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString()); 1120 } 1121 } 1122 } 1123 1124 // Uses the Target API to evaluate the expression passed as a parameter to the function 1125 // The result of that expression is returned an unsigned 64 bit int, via the result* paramter. 1126 // Function returns true on success, and false on failure 1127 bool 1128 RenderScriptRuntime::EvalRSExpression(const char* expression, StackFrame* frame_ptr, uint64_t* result) 1129 { 1130 Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 1131 if (log) 1132 log->Printf("RenderScriptRuntime::EvalRSExpression(%s)", expression); 1133 1134 ValueObjectSP expr_result; 1135 // Perform the actual expression evaluation 1136 GetProcess()->GetTarget().EvaluateExpression(expression, frame_ptr, expr_result); 1137 1138 if (!expr_result) 1139 { 1140 if (log) 1141 log->Printf("RenderScriptRuntime::EvalRSExpression - Error: Couldn't evaluate expression"); 1142 return false; 1143 } 1144 1145 // The result of the expression is invalid 1146 if (!expr_result->GetError().Success()) 1147 { 1148 Error err = expr_result->GetError(); 1149 if (err.GetError() == UserExpression::kNoResult) // Expression returned void, so this is actually a success 1150 { 1151 if (log) 1152 log->Printf("RenderScriptRuntime::EvalRSExpression - Expression returned void"); 1153 1154 result = nullptr; 1155 return true; 1156 } 1157 1158 if (log) 1159 log->Printf("RenderScriptRuntime::EvalRSExpression - Error evaluating expression result: %s", err.AsCString()); 1160 return false; 1161 } 1162 1163 bool success = false; 1164 *result = expr_result->GetValueAsUnsigned(0, &success); // We only read the result as an unsigned int. 1165 1166 if (!success) 1167 { 1168 if (log) 1169 log->Printf("RenderScriptRuntime::EvalRSExpression - Error: Couldn't convert expression result to unsigned int"); 1170 return false; 1171 } 1172 1173 return true; 1174 } 1175 1176 namespace // anonymous 1177 { 1178 // max length of an expanded expression 1179 const int jit_max_expr_size = 768; 1180 1181 // Format strings containing the expressions we may need to evaluate. 1182 const char runtimeExpressions[][256] = 1183 { 1184 // Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap) 1185 "(int*)_Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocationCubemapFace(0x%lx, %u, %u, %u, 0, 0)", 1186 1187 // Type* rsaAllocationGetType(Context*, Allocation*) 1188 "(void*)rsaAllocationGetType(0x%lx, 0x%lx)", 1189 1190 // rsaTypeGetNativeData(Context*, Type*, void* typeData, size) 1191 // Pack the data in the following way mHal.state.dimX; mHal.state.dimY; mHal.state.dimZ; 1192 // mHal.state.lodCount; mHal.state.faces; mElement; into typeData 1193 // Need to specify 32 or 64 bit for uint_t since this differs between devices 1194 "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[0]", // X dim 1195 "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[1]", // Y dim 1196 "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[2]", // Z dim 1197 "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[5]", // Element ptr 1198 1199 // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size) 1200 // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into elemData 1201 "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%lx, 0x%lx, data, 5); data[0]", // Type 1202 "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%lx, 0x%lx, data, 5); data[1]", // Kind 1203 "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%lx, 0x%lx, data, 5); data[3]", // Vector Size 1204 "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%lx, 0x%lx, data, 5); data[4]", // Field Count 1205 1206 // rsaElementGetSubElements(RsContext con, RsElement elem, uintptr_t *ids, const char **names, 1207 // size_t *arraySizes, uint32_t dataSize) 1208 // Needed for Allocations of structs to gather details about fields/Subelements 1209 "void* ids[%u]; const char* names[%u]; size_t arr_size[%u];" 1210 "(void*)rsaElementGetSubElements(0x%lx, 0x%lx, ids, names, arr_size, %u); ids[%u]", // Element* of field 1211 1212 "void* ids[%u]; const char* names[%u]; size_t arr_size[%u];" 1213 "(void*)rsaElementGetSubElements(0x%lx, 0x%lx, ids, names, arr_size, %u); names[%u]", // Name of field 1214 1215 "void* ids[%u]; const char* names[%u]; size_t arr_size[%u];" 1216 "(void*)rsaElementGetSubElements(0x%lx, 0x%lx, ids, names, arr_size, %u); arr_size[%u]" // Array size of field 1217 }; 1218 1219 1220 // Temporary workaround for MIPS, until the compiler emits the JAL instruction when invoking directly the function. 1221 // At the moment, when evaluating an expression involving a function call, the LLVM codegen for Mips emits a JAL 1222 // instruction, which is able to jump in the range +/- 128MB with respect to the current program counter ($pc). If 1223 // the requested function happens to reside outside the above region, the function address will be truncated and the 1224 // function invocation will fail. This is a problem in the RS plugin as we rely on the RS API to probe the number and 1225 // the nature of allocations. A proper solution in the MIPS compiler is currently being investigated. As temporary 1226 // work around for this context, we'll invoke the RS API through function pointers, which cause the compiler to emit a 1227 // register based JALR instruction. 1228 const char runtimeExpressions_mips[][512] = 1229 { 1230 // Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap) 1231 "int* (*f) (void*, int, int, int, int, int) = (int* (*) (void*, int, int, int, int, int)) " 1232 "_Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocationCubemapFace; " 1233 "(int*) f((void*) 0x%lx, %u, %u, %u, 0, 0)", 1234 1235 // Type* rsaAllocationGetType(Context*, Allocation*) 1236 "void* (*f) (void*, void*) = (void* (*) (void*, void*)) rsaAllocationGetType; (void*) f((void*) 0x%lx, (void*) 0x%lx)", 1237 1238 // rsaTypeGetNativeData(Context*, Type*, void* typeData, size) 1239 // Pack the data in the following way mHal.state.dimX; mHal.state.dimY; mHal.state.dimZ; 1240 // mHal.state.lodCount; mHal.state.faces; mElement; into typeData 1241 // Need to specify 32 or 64 bit for uint_t since this differs between devices 1242 "uint%u_t data[6]; void* (*f)(void*, void*, uintptr_t*, uint32_t) = (void* (*)(void*, void*, uintptr_t*, uint32_t)) " 1243 "rsaTypeGetNativeData; (void*) f((void*) 0x%lx, (void*) 0x%lx, data, 6); data[0]", 1244 "uint%u_t data[6]; void* (*f)(void*, void*, uintptr_t*, uint32_t) = (void* (*)(void*, void*, uintptr_t*, uint32_t)) " 1245 "rsaTypeGetNativeData; (void*) f((void*) 0x%lx, (void*) 0x%lx, data, 6); data[1]", 1246 "uint%u_t data[6]; void* (*f)(void*, void*, uintptr_t*, uint32_t) = (void* (*)(void*, void*, uintptr_t*, uint32_t)) " 1247 "rsaTypeGetNativeData; (void*) f((void*) 0x%lx, (void*) 0x%lx, data, 6); data[2]", 1248 "uint%u_t data[6]; void* (*f)(void*, void*, uintptr_t*, uint32_t) = (void* (*)(void*, void*, uintptr_t*, uint32_t)) " 1249 "rsaTypeGetNativeData; (void*) f((void*) 0x%lx, (void*) 0x%lx, data, 6); data[5]", 1250 1251 // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size) 1252 // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into elemData 1253 "uint32_t data[5]; void* (*f)(void*, void*, uint32_t*, uint32_t) = (void* (*)(void*, void*, uint32_t*, uint32_t)) " 1254 "rsaElementGetNativeData; (void*) f((void*) 0x%lx, (void*) 0x%lx, data, 5); data[0]", // Type 1255 "uint32_t data[5]; void* (*f)(void*, void*, uint32_t*, uint32_t) = (void* (*)(void*, void*, uint32_t*, uint32_t)) " 1256 "rsaElementGetNativeData; (void*) f((void*) 0x%lx, (void*) 0x%lx, data, 5); data[1]", // Kind 1257 "uint32_t data[5]; void* (*f)(void*, void*, uint32_t*, uint32_t) = (void* (*)(void*, void*, uint32_t*, uint32_t)) " 1258 "rsaElementGetNativeData; (void*) f((void*) 0x%lx, (void*) 0x%lx, data, 5); data[3]", // Vector size 1259 "uint32_t data[5]; void* (*f)(void*, void*, uint32_t*, uint32_t) = (void* (*)(void*, void*, uint32_t*, uint32_t)) " 1260 "rsaElementGetNativeData; (void*) f((void*) 0x%lx, (void*) 0x%lx, data, 5); data[4]", // Field count 1261 1262 // rsaElementGetSubElements(RsContext con, RsElement elem, uintptr_t *ids, const char **names, 1263 // size_t *arraySizes, uint32_t dataSize) 1264 // Needed for Allocations of structs to gather details about fields/Subelements 1265 "void* ids[%u]; const char* names[%u]; size_t arr_size[%u];" 1266 "void* (*f) (void*, void*, uintptr_t*, const char**, size_t*, uint32_t) = " 1267 "(void* (*) (void*, void*, uintptr_t*, const char**, size_t*, uint32_t)) rsaElementGetSubElements;" 1268 "(void*) f((void*) 0x%lx, (void*) 0x%lx, (uintptr_t*) ids, names, arr_size, (uint32_t) %u);" 1269 "ids[%u]", // Element* of field 1270 "void* ids[%u]; const char* names[%u]; size_t arr_size[%u];" 1271 "void* (*f) (void*, void*, uintptr_t*, const char**, size_t*, uint32_t) = " 1272 "(void* (*) (void*, void*, uintptr_t*, const char**, size_t*, uint32_t)) rsaElementGetSubElements;" 1273 "(void*) f((void*) 0x%lx, (void*) 0x%lx, (uintptr_t*) ids, names, arr_size, (uint32_t) %u);" 1274 "names[%u]", // Name of field 1275 "void* ids[%u]; const char* names[%u]; size_t arr_size[%u];" 1276 "void* (*f) (void*, void*, uintptr_t*, const char**, size_t*, uint32_t) = " 1277 "(void* (*) (void*, void*, uintptr_t*, const char**, size_t*, uint32_t)) rsaElementGetSubElements;" 1278 "(void*) f((void*) 0x%lx, (void*) 0x%lx, (uintptr_t*) ids, names, arr_size, (uint32_t) %u);" 1279 "arr_size[%u]" // Array size of field 1280 }; 1281 1282 } // end of the anonymous namespace 1283 1284 1285 // Retrieve the string to JIT for the given expression 1286 const char* 1287 RenderScriptRuntime::JITTemplate(ExpressionStrings e) 1288 { 1289 // be nice to your Mips friend when adding new expression strings 1290 static_assert(sizeof(runtimeExpressions)/sizeof(runtimeExpressions[0]) == 1291 sizeof(runtimeExpressions_mips)/sizeof(runtimeExpressions_mips[0]), 1292 "#runtimeExpressions != #runtimeExpressions_mips"); 1293 1294 assert((e >= eExprGetOffsetPtr && e <= eExprSubelementsArrSize) && 1295 "Expression string out of bounds"); 1296 1297 llvm::Triple::ArchType arch = GetTargetRef().GetArchitecture().GetMachine(); 1298 1299 // mips JAL workaround 1300 if(arch == llvm::Triple::ArchType::mips64el || arch == llvm::Triple::ArchType::mipsel) 1301 return runtimeExpressions_mips[e]; 1302 else 1303 return runtimeExpressions[e]; 1304 } 1305 1306 1307 // JITs the RS runtime for the internal data pointer of an allocation. 1308 // Is passed x,y,z coordinates for the pointer to a specific element. 1309 // Then sets the data_ptr member in Allocation with the result. 1310 // Returns true on success, false otherwise 1311 bool 1312 RenderScriptRuntime::JITDataPointer(AllocationDetails* allocation, StackFrame* frame_ptr, 1313 unsigned int x, unsigned int y, unsigned int z) 1314 { 1315 Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 1316 1317 if (!allocation->address.isValid()) 1318 { 1319 if (log) 1320 log->Printf("RenderScriptRuntime::JITDataPointer - Failed to find allocation details"); 1321 return false; 1322 } 1323 1324 const char* expr_cstr = JITTemplate(eExprGetOffsetPtr); 1325 char buffer[jit_max_expr_size]; 1326 1327 int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->address.get(), x, y, z); 1328 if (chars_written < 0) 1329 { 1330 if (log) 1331 log->Printf("RenderScriptRuntime::JITDataPointer - Encoding error in snprintf()"); 1332 return false; 1333 } 1334 else if (chars_written >= jit_max_expr_size) 1335 { 1336 if (log) 1337 log->Printf("RenderScriptRuntime::JITDataPointer - Expression too long"); 1338 return false; 1339 } 1340 1341 uint64_t result = 0; 1342 if (!EvalRSExpression(buffer, frame_ptr, &result)) 1343 return false; 1344 1345 addr_t mem_ptr = static_cast<lldb::addr_t>(result); 1346 allocation->data_ptr = mem_ptr; 1347 1348 return true; 1349 } 1350 1351 // JITs the RS runtime for the internal pointer to the RS Type of an allocation 1352 // Then sets the type_ptr member in Allocation with the result. 1353 // Returns true on success, false otherwise 1354 bool 1355 RenderScriptRuntime::JITTypePointer(AllocationDetails* allocation, StackFrame* frame_ptr) 1356 { 1357 Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 1358 1359 if (!allocation->address.isValid() || !allocation->context.isValid()) 1360 { 1361 if (log) 1362 log->Printf("RenderScriptRuntime::JITTypePointer - Failed to find allocation details"); 1363 return false; 1364 } 1365 1366 const char* expr_cstr = JITTemplate(eExprAllocGetType); 1367 char buffer[jit_max_expr_size]; 1368 1369 int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->context.get(), *allocation->address.get()); 1370 if (chars_written < 0) 1371 { 1372 if (log) 1373 log->Printf("RenderScriptRuntime::JITDataPointer - Encoding error in snprintf()"); 1374 return false; 1375 } 1376 else if (chars_written >= jit_max_expr_size) 1377 { 1378 if (log) 1379 log->Printf("RenderScriptRuntime::JITTypePointer - Expression too long"); 1380 return false; 1381 } 1382 1383 uint64_t result = 0; 1384 if (!EvalRSExpression(buffer, frame_ptr, &result)) 1385 return false; 1386 1387 addr_t type_ptr = static_cast<lldb::addr_t>(result); 1388 allocation->type_ptr = type_ptr; 1389 1390 return true; 1391 } 1392 1393 // JITs the RS runtime for information about the dimensions and type of an allocation 1394 // Then sets dimension and element_ptr members in Allocation with the result. 1395 // Returns true on success, false otherwise 1396 bool 1397 RenderScriptRuntime::JITTypePacked(AllocationDetails* allocation, StackFrame* frame_ptr) 1398 { 1399 Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 1400 1401 if (!allocation->type_ptr.isValid() || !allocation->context.isValid()) 1402 { 1403 if (log) 1404 log->Printf("RenderScriptRuntime::JITTypePacked - Failed to find allocation details"); 1405 return false; 1406 } 1407 1408 // Expression is different depending on if device is 32 or 64 bit 1409 uint32_t archByteSize = GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize(); 1410 const unsigned int bits = archByteSize == 4 ? 32 : 64; 1411 1412 // We want 4 elements from packed data 1413 const unsigned int num_exprs = 4; 1414 assert(num_exprs == (eExprTypeElemPtr - eExprTypeDimX + 1) && "Invalid number of expressions"); 1415 1416 char buffer[num_exprs][jit_max_expr_size]; 1417 uint64_t results[num_exprs]; 1418 1419 for (unsigned int i = 0; i < num_exprs; ++i) 1420 { 1421 const char* expr_cstr = JITTemplate((ExpressionStrings) (eExprTypeDimX + i)); 1422 int chars_written = snprintf(buffer[i], jit_max_expr_size, expr_cstr, bits, 1423 *allocation->context.get(), *allocation->type_ptr.get()); 1424 if (chars_written < 0) 1425 { 1426 if (log) 1427 log->Printf("RenderScriptRuntime::JITDataPointer - Encoding error in snprintf()"); 1428 return false; 1429 } 1430 else if (chars_written >= jit_max_expr_size) 1431 { 1432 if (log) 1433 log->Printf("RenderScriptRuntime::JITTypePacked - Expression too long"); 1434 return false; 1435 } 1436 1437 // Perform expression evaluation 1438 if (!EvalRSExpression(buffer[i], frame_ptr, &results[i])) 1439 return false; 1440 } 1441 1442 // Assign results to allocation members 1443 AllocationDetails::Dimension dims; 1444 dims.dim_1 = static_cast<uint32_t>(results[0]); 1445 dims.dim_2 = static_cast<uint32_t>(results[1]); 1446 dims.dim_3 = static_cast<uint32_t>(results[2]); 1447 allocation->dimension = dims; 1448 1449 addr_t elem_ptr = static_cast<lldb::addr_t>(results[3]); 1450 allocation->element.element_ptr = elem_ptr; 1451 1452 if (log) 1453 log->Printf("RenderScriptRuntime::JITTypePacked - dims (%u, %u, %u) Element*: 0x%" PRIx64, 1454 dims.dim_1, dims.dim_2, dims.dim_3, elem_ptr); 1455 1456 return true; 1457 } 1458 1459 // JITs the RS runtime for information about the Element of an allocation 1460 // Then sets type, type_vec_size, field_count and type_kind members in Element with the result. 1461 // Returns true on success, false otherwise 1462 bool 1463 RenderScriptRuntime::JITElementPacked(Element& elem, const lldb::addr_t context, StackFrame* frame_ptr) 1464 { 1465 Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 1466 1467 if (!elem.element_ptr.isValid()) 1468 { 1469 if (log) 1470 log->Printf("RenderScriptRuntime::JITElementPacked - Failed to find allocation details"); 1471 return false; 1472 } 1473 1474 // We want 4 elements from packed data 1475 const unsigned int num_exprs = 4; 1476 assert(num_exprs == (eExprElementFieldCount - eExprElementType + 1) && "Invalid number of expressions"); 1477 1478 char buffer[num_exprs][jit_max_expr_size]; 1479 uint64_t results[num_exprs]; 1480 1481 for (unsigned int i = 0; i < num_exprs; i++) 1482 { 1483 const char* expr_cstr = JITTemplate((ExpressionStrings) (eExprElementType + i)); 1484 int chars_written = snprintf(buffer[i], jit_max_expr_size, expr_cstr, context, *elem.element_ptr.get()); 1485 if (chars_written < 0) 1486 { 1487 if (log) 1488 log->Printf("RenderScriptRuntime::JITElementPacked - Encoding error in snprintf()"); 1489 return false; 1490 } 1491 else if (chars_written >= jit_max_expr_size) 1492 { 1493 if (log) 1494 log->Printf("RenderScriptRuntime::JITElementPacked - Expression too long"); 1495 return false; 1496 } 1497 1498 // Perform expression evaluation 1499 if (!EvalRSExpression(buffer[i], frame_ptr, &results[i])) 1500 return false; 1501 } 1502 1503 // Assign results to allocation members 1504 elem.type = static_cast<RenderScriptRuntime::Element::DataType>(results[0]); 1505 elem.type_kind = static_cast<RenderScriptRuntime::Element::DataKind>(results[1]); 1506 elem.type_vec_size = static_cast<uint32_t>(results[2]); 1507 elem.field_count = static_cast<uint32_t>(results[3]); 1508 1509 if (log) 1510 log->Printf("RenderScriptRuntime::JITElementPacked - data type %u, pixel type %u, vector size %u, field count %u", 1511 *elem.type.get(), *elem.type_kind.get(), *elem.type_vec_size.get(), *elem.field_count.get()); 1512 1513 // If this Element has subelements then JIT rsaElementGetSubElements() for details about its fields 1514 if (*elem.field_count.get() > 0 && !JITSubelements(elem, context, frame_ptr)) 1515 return false; 1516 1517 return true; 1518 } 1519 1520 // JITs the RS runtime for information about the subelements/fields of a struct allocation 1521 // This is necessary for infering the struct type so we can pretty print the allocation's contents. 1522 // Returns true on success, false otherwise 1523 bool 1524 RenderScriptRuntime::JITSubelements(Element& elem, const lldb::addr_t context, StackFrame* frame_ptr) 1525 { 1526 Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 1527 1528 if (!elem.element_ptr.isValid() || !elem.field_count.isValid()) 1529 { 1530 if (log) 1531 log->Printf("RenderScriptRuntime::JITSubelements - Failed to find allocation details"); 1532 return false; 1533 } 1534 1535 const short num_exprs = 3; 1536 assert(num_exprs == (eExprSubelementsArrSize - eExprSubelementsId + 1) && "Invalid number of expressions"); 1537 1538 char expr_buffer[jit_max_expr_size]; 1539 uint64_t results; 1540 1541 // Iterate over struct fields. 1542 const uint32_t field_count = *elem.field_count.get(); 1543 for (unsigned int field_index = 0; field_index < field_count; ++field_index) 1544 { 1545 Element child; 1546 for (unsigned int expr_index = 0; expr_index < num_exprs; ++expr_index) 1547 { 1548 const char* expr_cstr = JITTemplate((ExpressionStrings) (eExprSubelementsId + expr_index)); 1549 int chars_written = snprintf(expr_buffer, jit_max_expr_size, expr_cstr, 1550 field_count, field_count, field_count, 1551 context, *elem.element_ptr.get(), field_count, field_index); 1552 if (chars_written < 0) 1553 { 1554 if (log) 1555 log->Printf("RenderScriptRuntime::JITSubelements - Encoding error in snprintf()"); 1556 return false; 1557 } 1558 else if (chars_written >= jit_max_expr_size) 1559 { 1560 if (log) 1561 log->Printf("RenderScriptRuntime::JITSubelements - Expression too long"); 1562 return false; 1563 } 1564 1565 // Perform expression evaluation 1566 if (!EvalRSExpression(expr_buffer, frame_ptr, &results)) 1567 return false; 1568 1569 if (log) 1570 log->Printf("RenderScriptRuntime::JITSubelements - Expr result 0x%" PRIx64, results); 1571 1572 switch(expr_index) 1573 { 1574 case 0: // Element* of child 1575 child.element_ptr = static_cast<addr_t>(results); 1576 break; 1577 case 1: // Name of child 1578 { 1579 lldb::addr_t address = static_cast<addr_t>(results); 1580 Error err; 1581 std::string name; 1582 GetProcess()->ReadCStringFromMemory(address, name, err); 1583 if (!err.Fail()) 1584 child.type_name = ConstString(name); 1585 else 1586 { 1587 if (log) 1588 log->Printf("RenderScriptRuntime::JITSubelements - Warning: Couldn't read field name"); 1589 } 1590 break; 1591 } 1592 case 2: // Array size of child 1593 child.array_size = static_cast<uint32_t>(results); 1594 break; 1595 } 1596 } 1597 1598 // We need to recursively JIT each Element field of the struct since 1599 // structs can be nested inside structs. 1600 if (!JITElementPacked(child, context, frame_ptr)) 1601 return false; 1602 elem.children.push_back(child); 1603 } 1604 1605 // Try to infer the name of the struct type so we can pretty print the allocation contents. 1606 FindStructTypeName(elem, frame_ptr); 1607 1608 return true; 1609 } 1610 1611 // JITs the RS runtime for the address of the last element in the allocation. 1612 // The `elem_size` paramter represents the size of a single element, including padding. 1613 // Which is needed as an offset from the last element pointer. 1614 // Using this offset minus the starting address we can calculate the size of the allocation. 1615 // Returns true on success, false otherwise 1616 bool 1617 RenderScriptRuntime::JITAllocationSize(AllocationDetails* allocation, StackFrame* frame_ptr) 1618 { 1619 Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 1620 1621 if (!allocation->address.isValid() || !allocation->dimension.isValid() 1622 || !allocation->data_ptr.isValid() || !allocation->element.datum_size.isValid()) 1623 { 1624 if (log) 1625 log->Printf("RenderScriptRuntime::JITAllocationSize - Failed to find allocation details"); 1626 return false; 1627 } 1628 1629 // Find dimensions 1630 unsigned int dim_x = allocation->dimension.get()->dim_1; 1631 unsigned int dim_y = allocation->dimension.get()->dim_2; 1632 unsigned int dim_z = allocation->dimension.get()->dim_3; 1633 1634 // Our plan of jitting the last element address doesn't seem to work for struct Allocations 1635 // Instead try to infer the size ourselves without any inter element padding. 1636 if (allocation->element.children.size() > 0) 1637 { 1638 if (dim_x == 0) dim_x = 1; 1639 if (dim_y == 0) dim_y = 1; 1640 if (dim_z == 0) dim_z = 1; 1641 1642 allocation->size = dim_x * dim_y * dim_z * *allocation->element.datum_size.get(); 1643 1644 if (log) 1645 log->Printf("RenderScriptRuntime::JITAllocationSize - Infered size of struct allocation %u", *allocation->size.get()); 1646 1647 return true; 1648 } 1649 1650 const char* expr_cstr = JITTemplate(eExprGetOffsetPtr); 1651 char buffer[jit_max_expr_size]; 1652 1653 // Calculate last element 1654 dim_x = dim_x == 0 ? 0 : dim_x - 1; 1655 dim_y = dim_y == 0 ? 0 : dim_y - 1; 1656 dim_z = dim_z == 0 ? 0 : dim_z - 1; 1657 1658 int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->address.get(), 1659 dim_x, dim_y, dim_z); 1660 if (chars_written < 0) 1661 { 1662 if (log) 1663 log->Printf("RenderScriptRuntime::JITAllocationSize - Encoding error in snprintf()"); 1664 return false; 1665 } 1666 else if (chars_written >= jit_max_expr_size) 1667 { 1668 if (log) 1669 log->Printf("RenderScriptRuntime::JITAllocationSize - Expression too long"); 1670 return false; 1671 } 1672 1673 uint64_t result = 0; 1674 if (!EvalRSExpression(buffer, frame_ptr, &result)) 1675 return false; 1676 1677 addr_t mem_ptr = static_cast<lldb::addr_t>(result); 1678 // Find pointer to last element and add on size of an element 1679 allocation->size = static_cast<uint32_t>(mem_ptr - *allocation->data_ptr.get()) + *allocation->element.datum_size.get(); 1680 1681 return true; 1682 } 1683 1684 // JITs the RS runtime for information about the stride between rows in the allocation. 1685 // This is done to detect padding, since allocated memory is 16-byte aligned. 1686 // Returns true on success, false otherwise 1687 bool 1688 RenderScriptRuntime::JITAllocationStride(AllocationDetails* allocation, StackFrame* frame_ptr) 1689 { 1690 Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 1691 1692 if (!allocation->address.isValid() || !allocation->data_ptr.isValid()) 1693 { 1694 if (log) 1695 log->Printf("RenderScriptRuntime::JITAllocationStride - Failed to find allocation details"); 1696 return false; 1697 } 1698 1699 const char* expr_cstr = JITTemplate(eExprGetOffsetPtr); 1700 char buffer[jit_max_expr_size]; 1701 1702 int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->address.get(), 1703 0, 1, 0); 1704 if (chars_written < 0) 1705 { 1706 if (log) 1707 log->Printf("RenderScriptRuntime::JITAllocationStride - Encoding error in snprintf()"); 1708 return false; 1709 } 1710 else if (chars_written >= jit_max_expr_size) 1711 { 1712 if (log) 1713 log->Printf("RenderScriptRuntime::JITAllocationStride - Expression too long"); 1714 return false; 1715 } 1716 1717 uint64_t result = 0; 1718 if (!EvalRSExpression(buffer, frame_ptr, &result)) 1719 return false; 1720 1721 addr_t mem_ptr = static_cast<lldb::addr_t>(result); 1722 allocation->stride = static_cast<uint32_t>(mem_ptr - *allocation->data_ptr.get()); 1723 1724 return true; 1725 } 1726 1727 // JIT all the current runtime info regarding an allocation 1728 bool 1729 RenderScriptRuntime::RefreshAllocation(AllocationDetails* allocation, StackFrame* frame_ptr) 1730 { 1731 // GetOffsetPointer() 1732 if (!JITDataPointer(allocation, frame_ptr)) 1733 return false; 1734 1735 // rsaAllocationGetType() 1736 if (!JITTypePointer(allocation, frame_ptr)) 1737 return false; 1738 1739 // rsaTypeGetNativeData() 1740 if (!JITTypePacked(allocation, frame_ptr)) 1741 return false; 1742 1743 // rsaElementGetNativeData() 1744 if (!JITElementPacked(allocation->element, *allocation->context.get(), frame_ptr)) 1745 return false; 1746 1747 // Sets the datum_size member in Element 1748 SetElementSize(allocation->element); 1749 1750 // Use GetOffsetPointer() to infer size of the allocation 1751 if (!JITAllocationSize(allocation, frame_ptr)) 1752 return false; 1753 1754 return true; 1755 } 1756 1757 // Function attempts to set the type_name member of the paramaterised Element object. 1758 // This string should be the name of the struct type the Element represents. 1759 // We need this string for pretty printing the Element to users. 1760 void 1761 RenderScriptRuntime::FindStructTypeName(Element& elem, StackFrame* frame_ptr) 1762 { 1763 Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 1764 1765 if (!elem.type_name.IsEmpty()) // Name already set 1766 return; 1767 else 1768 elem.type_name = Element::GetFallbackStructName(); // Default type name if we don't succeed 1769 1770 // Find all the global variables from the script rs modules 1771 VariableList variable_list; 1772 for (auto module_sp : m_rsmodules) 1773 module_sp->m_module->FindGlobalVariables(RegularExpression("."), true, UINT32_MAX, variable_list); 1774 1775 // Iterate over all the global variables looking for one with a matching type to the Element. 1776 // We make the assumption a match exists since there needs to be a global variable to reflect the 1777 // struct type back into java host code. 1778 for (uint32_t var_index = 0; var_index < variable_list.GetSize(); ++var_index) 1779 { 1780 const VariableSP var_sp(variable_list.GetVariableAtIndex(var_index)); 1781 if (!var_sp) 1782 continue; 1783 1784 ValueObjectSP valobj_sp = ValueObjectVariable::Create(frame_ptr, var_sp); 1785 if (!valobj_sp) 1786 continue; 1787 1788 // Find the number of variable fields. 1789 // If it has no fields, or more fields than our Element, then it can't be the struct we're looking for. 1790 // Don't check for equality since RS can add extra struct members for padding. 1791 size_t num_children = valobj_sp->GetNumChildren(); 1792 if (num_children > elem.children.size() || num_children == 0) 1793 continue; 1794 1795 // Iterate over children looking for members with matching field names. 1796 // If all the field names match, this is likely the struct we want. 1797 // 1798 // TODO: This could be made more robust by also checking children data sizes, or array size 1799 bool found = true; 1800 for (size_t child_index = 0; child_index < num_children; ++child_index) 1801 { 1802 ValueObjectSP child = valobj_sp->GetChildAtIndex(child_index, true); 1803 if (!child || (child->GetName() != elem.children[child_index].type_name)) 1804 { 1805 found = false; 1806 break; 1807 } 1808 } 1809 1810 // RS can add extra struct members for padding in the format '#rs_padding_[0-9]+' 1811 if (found && num_children < elem.children.size()) 1812 { 1813 const unsigned int size_diff = elem.children.size() - num_children; 1814 if (log) 1815 log->Printf("RenderScriptRuntime::FindStructTypeName - %u padding struct entries", size_diff); 1816 1817 for (unsigned int padding_index = 0; padding_index < size_diff; ++padding_index) 1818 { 1819 const ConstString& name = elem.children[num_children + padding_index].type_name; 1820 if (strcmp(name.AsCString(), "#rs_padding") < 0) 1821 found = false; 1822 } 1823 } 1824 1825 // We've found a global var with matching type 1826 if (found) 1827 { 1828 // Dereference since our Element type isn't a pointer. 1829 if (valobj_sp->IsPointerType()) 1830 { 1831 Error err; 1832 ValueObjectSP deref_valobj = valobj_sp->Dereference(err); 1833 if (!err.Fail()) 1834 valobj_sp = deref_valobj; 1835 } 1836 1837 // Save name of variable in Element. 1838 elem.type_name = valobj_sp->GetTypeName(); 1839 if (log) 1840 log->Printf("RenderScriptRuntime::FindStructTypeName - Element name set to %s", elem.type_name.AsCString()); 1841 1842 return; 1843 } 1844 } 1845 } 1846 1847 // Function sets the datum_size member of Element. Representing the size of a single instance including padding. 1848 // Assumes the relevant allocation information has already been jitted. 1849 void 1850 RenderScriptRuntime::SetElementSize(Element& elem) 1851 { 1852 Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 1853 const Element::DataType type = *elem.type.get(); 1854 assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_BOOLEAN 1855 && "Invalid allocation type"); 1856 1857 const unsigned int vec_size = *elem.type_vec_size.get(); 1858 unsigned int data_size = 0; 1859 const unsigned int padding = vec_size == 3 ? AllocationDetails::RSTypeToFormat[type][eElementSize] : 0; 1860 1861 // Element is of a struct type, calculate size recursively. 1862 if ((type == Element::RS_TYPE_NONE) && (elem.children.size() > 0)) 1863 { 1864 for (Element& child : elem.children) 1865 { 1866 SetElementSize(child); 1867 const unsigned int array_size = child.array_size.isValid() ? *child.array_size.get() : 1; 1868 data_size += *child.datum_size.get() * array_size; 1869 } 1870 } 1871 else 1872 data_size = vec_size * AllocationDetails::RSTypeToFormat[type][eElementSize]; 1873 1874 elem.padding = padding; 1875 elem.datum_size = data_size + padding; 1876 if (log) 1877 log->Printf("RenderScriptRuntime::SetElementSize - element size set to %u", data_size + padding); 1878 } 1879 1880 // Given an allocation, this function copies the allocation contents from device into a buffer on the heap. 1881 // Returning a shared pointer to the buffer containing the data. 1882 std::shared_ptr<uint8_t> 1883 RenderScriptRuntime::GetAllocationData(AllocationDetails* allocation, StackFrame* frame_ptr) 1884 { 1885 Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 1886 1887 // JIT all the allocation details 1888 if (allocation->shouldRefresh()) 1889 { 1890 if (log) 1891 log->Printf("RenderScriptRuntime::GetAllocationData - Allocation details not calculated yet, jitting info"); 1892 1893 if (!RefreshAllocation(allocation, frame_ptr)) 1894 { 1895 if (log) 1896 log->Printf("RenderScriptRuntime::GetAllocationData - Couldn't JIT allocation details"); 1897 return nullptr; 1898 } 1899 } 1900 1901 assert(allocation->data_ptr.isValid() && allocation->element.type.isValid() && allocation->element.type_vec_size.isValid() 1902 && allocation->size.isValid() && "Allocation information not available"); 1903 1904 // Allocate a buffer to copy data into 1905 const unsigned int size = *allocation->size.get(); 1906 std::shared_ptr<uint8_t> buffer(new uint8_t[size]); 1907 if (!buffer) 1908 { 1909 if (log) 1910 log->Printf("RenderScriptRuntime::GetAllocationData - Couldn't allocate a %u byte buffer", size); 1911 return nullptr; 1912 } 1913 1914 // Read the inferior memory 1915 Error error; 1916 lldb::addr_t data_ptr = *allocation->data_ptr.get(); 1917 GetProcess()->ReadMemory(data_ptr, buffer.get(), size, error); 1918 if (error.Fail()) 1919 { 1920 if (log) 1921 log->Printf("RenderScriptRuntime::GetAllocationData - '%s' Couldn't read %u bytes of allocation data from 0x%" PRIx64, 1922 error.AsCString(), size, data_ptr); 1923 return nullptr; 1924 } 1925 1926 return buffer; 1927 } 1928 1929 // Function copies data from a binary file into an allocation. 1930 // There is a header at the start of the file, FileHeader, before the data content itself. 1931 // Information from this header is used to display warnings to the user about incompatabilities 1932 bool 1933 RenderScriptRuntime::LoadAllocation(Stream &strm, const uint32_t alloc_id, const char* filename, StackFrame* frame_ptr) 1934 { 1935 Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 1936 1937 // Find allocation with the given id 1938 AllocationDetails* alloc = FindAllocByID(strm, alloc_id); 1939 if (!alloc) 1940 return false; 1941 1942 if (log) 1943 log->Printf("RenderScriptRuntime::LoadAllocation - Found allocation 0x%" PRIx64, *alloc->address.get()); 1944 1945 // JIT all the allocation details 1946 if (alloc->shouldRefresh()) 1947 { 1948 if (log) 1949 log->Printf("RenderScriptRuntime::LoadAllocation - Allocation details not calculated yet, jitting info"); 1950 1951 if (!RefreshAllocation(alloc, frame_ptr)) 1952 { 1953 if (log) 1954 log->Printf("RenderScriptRuntime::LoadAllocation - Couldn't JIT allocation details"); 1955 return false; 1956 } 1957 } 1958 1959 assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() && alloc->element.type_vec_size.isValid() 1960 && alloc->size.isValid() && alloc->element.datum_size.isValid() && "Allocation information not available"); 1961 1962 // Check we can read from file 1963 FileSpec file(filename, true); 1964 if (!file.Exists()) 1965 { 1966 strm.Printf("Error: File %s does not exist", filename); 1967 strm.EOL(); 1968 return false; 1969 } 1970 1971 if (!file.Readable()) 1972 { 1973 strm.Printf("Error: File %s does not have readable permissions", filename); 1974 strm.EOL(); 1975 return false; 1976 } 1977 1978 // Read file into data buffer 1979 DataBufferSP data_sp(file.ReadFileContents()); 1980 1981 // Cast start of buffer to FileHeader and use pointer to read metadata 1982 void* file_buffer = data_sp->GetBytes(); 1983 const AllocationDetails::FileHeader* head = static_cast<AllocationDetails::FileHeader*>(file_buffer); 1984 1985 // Advance buffer past header 1986 file_buffer = static_cast<uint8_t*>(file_buffer) + head->hdr_size; 1987 1988 if (log) 1989 log->Printf("RenderScriptRuntime::LoadAllocation - header type %u, element size %u", 1990 head->type, head->element_size); 1991 1992 // Check if the target allocation and file both have the same number of bytes for an Element 1993 if (*alloc->element.datum_size.get() != head->element_size) 1994 { 1995 strm.Printf("Warning: Mismatched Element sizes - file %u bytes, allocation %u bytes", 1996 head->element_size, *alloc->element.datum_size.get()); 1997 strm.EOL(); 1998 } 1999 2000 // Check if the target allocation and file both have the same integral type 2001 const unsigned int type = static_cast<unsigned int>(*alloc->element.type.get()); 2002 if (type != head->type) 2003 { 2004 const char* file_type_cstr = AllocationDetails::RsDataTypeToString[head->type][0]; 2005 const char* alloc_type_cstr = AllocationDetails::RsDataTypeToString[type][0]; 2006 2007 strm.Printf("Warning: Mismatched Types - file '%s' type, allocation '%s' type", 2008 file_type_cstr, alloc_type_cstr); 2009 strm.EOL(); 2010 } 2011 2012 // Calculate size of allocation data in file 2013 size_t length = data_sp->GetByteSize() - head->hdr_size; 2014 2015 // Check if the target allocation and file both have the same total data size. 2016 const unsigned int alloc_size = *alloc->size.get(); 2017 if (alloc_size != length) 2018 { 2019 strm.Printf("Warning: Mismatched allocation sizes - file 0x%" PRIx64 " bytes, allocation 0x%x bytes", 2020 (uint64_t) length, alloc_size); 2021 strm.EOL(); 2022 length = alloc_size < length ? alloc_size : length; // Set length to copy to minimum 2023 } 2024 2025 // Copy file data from our buffer into the target allocation. 2026 lldb::addr_t alloc_data = *alloc->data_ptr.get(); 2027 Error error; 2028 size_t bytes_written = GetProcess()->WriteMemory(alloc_data, file_buffer, length, error); 2029 if (!error.Success() || bytes_written != length) 2030 { 2031 strm.Printf("Error: Couldn't write data to allocation %s", error.AsCString()); 2032 strm.EOL(); 2033 return false; 2034 } 2035 2036 strm.Printf("Contents of file '%s' read into allocation %u", filename, alloc->id); 2037 strm.EOL(); 2038 2039 return true; 2040 } 2041 2042 // Function copies allocation contents into a binary file. 2043 // This file can then be loaded later into a different allocation. 2044 // There is a header, FileHeader, before the allocation data containing meta-data. 2045 bool 2046 RenderScriptRuntime::SaveAllocation(Stream &strm, const uint32_t alloc_id, const char* filename, StackFrame* frame_ptr) 2047 { 2048 Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 2049 2050 // Find allocation with the given id 2051 AllocationDetails* alloc = FindAllocByID(strm, alloc_id); 2052 if (!alloc) 2053 return false; 2054 2055 if (log) 2056 log->Printf("RenderScriptRuntime::SaveAllocation - Found allocation 0x%" PRIx64, *alloc->address.get()); 2057 2058 // JIT all the allocation details 2059 if (alloc->shouldRefresh()) 2060 { 2061 if (log) 2062 log->Printf("RenderScriptRuntime::SaveAllocation - Allocation details not calculated yet, jitting info"); 2063 2064 if (!RefreshAllocation(alloc, frame_ptr)) 2065 { 2066 if (log) 2067 log->Printf("RenderScriptRuntime::SaveAllocation - Couldn't JIT allocation details"); 2068 return false; 2069 } 2070 } 2071 2072 assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() && alloc->element.type_vec_size.isValid() && alloc->element.datum_size.get() 2073 && alloc->element.type_kind.isValid() && alloc->dimension.isValid() && "Allocation information not available"); 2074 2075 // Check we can create writable file 2076 FileSpec file_spec(filename, true); 2077 File file(file_spec, File::eOpenOptionWrite | File::eOpenOptionCanCreate | File::eOpenOptionTruncate); 2078 if (!file) 2079 { 2080 strm.Printf("Error: Failed to open '%s' for writing", filename); 2081 strm.EOL(); 2082 return false; 2083 } 2084 2085 // Read allocation into buffer of heap memory 2086 const std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr); 2087 if (!buffer) 2088 { 2089 strm.Printf("Error: Couldn't read allocation data into buffer"); 2090 strm.EOL(); 2091 return false; 2092 } 2093 2094 // Create the file header 2095 AllocationDetails::FileHeader head; 2096 head.ident[0] = 'R'; head.ident[1] = 'S'; head.ident[2] = 'A'; head.ident[3] = 'D'; 2097 head.hdr_size = static_cast<uint16_t>(sizeof(AllocationDetails::FileHeader)); 2098 head.type = static_cast<uint16_t>(*alloc->element.type.get()); 2099 head.kind = static_cast<uint32_t>(*alloc->element.type_kind.get()); 2100 head.dims[0] = static_cast<uint32_t>(alloc->dimension.get()->dim_1); 2101 head.dims[1] = static_cast<uint32_t>(alloc->dimension.get()->dim_2); 2102 head.dims[2] = static_cast<uint32_t>(alloc->dimension.get()->dim_3); 2103 head.element_size = static_cast<uint32_t>(*alloc->element.datum_size.get()); 2104 2105 // Write the file header 2106 size_t num_bytes = sizeof(AllocationDetails::FileHeader); 2107 Error err = file.Write(static_cast<const void*>(&head), num_bytes); 2108 if (!err.Success()) 2109 { 2110 strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), filename); 2111 strm.EOL(); 2112 return false; 2113 } 2114 2115 // Write allocation data to file 2116 num_bytes = static_cast<size_t>(*alloc->size.get()); 2117 if (log) 2118 log->Printf("RenderScriptRuntime::SaveAllocation - Writing 0x%" PRIx64 " bytes from %p", (uint64_t) num_bytes, buffer.get()); 2119 2120 err = file.Write(buffer.get(), num_bytes); 2121 if (!err.Success()) 2122 { 2123 strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), filename); 2124 strm.EOL(); 2125 return false; 2126 } 2127 2128 strm.Printf("Allocation written to file '%s'", filename); 2129 strm.EOL(); 2130 return true; 2131 } 2132 2133 bool 2134 RenderScriptRuntime::LoadModule(const lldb::ModuleSP &module_sp) 2135 { 2136 Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 2137 2138 if (module_sp) 2139 { 2140 for (const auto &rs_module : m_rsmodules) 2141 { 2142 if (rs_module->m_module == module_sp) 2143 { 2144 // Check if the user has enabled automatically breaking on 2145 // all RS kernels. 2146 if (m_breakAllKernels) 2147 BreakOnModuleKernels(rs_module); 2148 2149 return false; 2150 } 2151 } 2152 bool module_loaded = false; 2153 switch (GetModuleKind(module_sp)) 2154 { 2155 case eModuleKindKernelObj: 2156 { 2157 RSModuleDescriptorSP module_desc; 2158 module_desc.reset(new RSModuleDescriptor(module_sp)); 2159 if (module_desc->ParseRSInfo()) 2160 { 2161 m_rsmodules.push_back(module_desc); 2162 module_loaded = true; 2163 } 2164 if (module_loaded) 2165 { 2166 FixupScriptDetails(module_desc); 2167 } 2168 break; 2169 } 2170 case eModuleKindDriver: 2171 { 2172 if (!m_libRSDriver) 2173 { 2174 m_libRSDriver = module_sp; 2175 LoadRuntimeHooks(m_libRSDriver, RenderScriptRuntime::eModuleKindDriver); 2176 } 2177 break; 2178 } 2179 case eModuleKindImpl: 2180 { 2181 m_libRSCpuRef = module_sp; 2182 break; 2183 } 2184 case eModuleKindLibRS: 2185 { 2186 if (!m_libRS) 2187 { 2188 m_libRS = module_sp; 2189 static ConstString gDbgPresentStr("gDebuggerPresent"); 2190 const Symbol* debug_present = m_libRS->FindFirstSymbolWithNameAndType(gDbgPresentStr, eSymbolTypeData); 2191 if (debug_present) 2192 { 2193 Error error; 2194 uint32_t flag = 0x00000001U; 2195 Target &target = GetProcess()->GetTarget(); 2196 addr_t addr = debug_present->GetLoadAddress(&target); 2197 GetProcess()->WriteMemory(addr, &flag, sizeof(flag), error); 2198 if(error.Success()) 2199 { 2200 if (log) 2201 log->Printf ("RenderScriptRuntime::LoadModule - Debugger present flag set on debugee"); 2202 2203 m_debuggerPresentFlagged = true; 2204 } 2205 else if (log) 2206 { 2207 log->Printf ("RenderScriptRuntime::LoadModule - Error writing debugger present flags '%s' ", error.AsCString()); 2208 } 2209 } 2210 else if (log) 2211 { 2212 log->Printf ("RenderScriptRuntime::LoadModule - Error writing debugger present flags - symbol not found"); 2213 } 2214 } 2215 break; 2216 } 2217 default: 2218 break; 2219 } 2220 if (module_loaded) 2221 Update(); 2222 return module_loaded; 2223 } 2224 return false; 2225 } 2226 2227 void 2228 RenderScriptRuntime::Update() 2229 { 2230 if (m_rsmodules.size() > 0) 2231 { 2232 if (!m_initiated) 2233 { 2234 Initiate(); 2235 } 2236 } 2237 } 2238 2239 // The maximum line length of an .rs.info packet 2240 #define MAXLINE 500 2241 2242 // The .rs.info symbol in renderscript modules contains a string which needs to be parsed. 2243 // The string is basic and is parsed on a line by line basis. 2244 bool 2245 RSModuleDescriptor::ParseRSInfo() 2246 { 2247 const Symbol *info_sym = m_module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData); 2248 if (info_sym) 2249 { 2250 const addr_t addr = info_sym->GetAddressRef().GetFileAddress(); 2251 const addr_t size = info_sym->GetByteSize(); 2252 const FileSpec fs = m_module->GetFileSpec(); 2253 2254 DataBufferSP buffer = fs.ReadFileContents(addr, size); 2255 2256 if (!buffer) 2257 return false; 2258 2259 std::string info((const char *)buffer->GetBytes()); 2260 2261 std::vector<std::string> info_lines; 2262 size_t lpos = info.find('\n'); 2263 while (lpos != std::string::npos) 2264 { 2265 info_lines.push_back(info.substr(0, lpos)); 2266 info = info.substr(lpos + 1); 2267 lpos = info.find('\n'); 2268 } 2269 size_t offset = 0; 2270 while (offset < info_lines.size()) 2271 { 2272 std::string line = info_lines[offset]; 2273 // Parse directives 2274 uint32_t numDefns = 0; 2275 if (sscanf(line.c_str(), "exportVarCount: %u", &numDefns) == 1) 2276 { 2277 while (numDefns--) 2278 m_globals.push_back(RSGlobalDescriptor(this, info_lines[++offset].c_str())); 2279 } 2280 else if (sscanf(line.c_str(), "exportFuncCount: %u", &numDefns) == 1) 2281 { 2282 } 2283 else if (sscanf(line.c_str(), "exportForEachCount: %u", &numDefns) == 1) 2284 { 2285 char name[MAXLINE]; 2286 while (numDefns--) 2287 { 2288 uint32_t slot = 0; 2289 name[0] = '\0'; 2290 if (sscanf(info_lines[++offset].c_str(), "%u - %s", &slot, &name[0]) == 2) 2291 { 2292 m_kernels.push_back(RSKernelDescriptor(this, name, slot)); 2293 } 2294 } 2295 } 2296 else if (sscanf(line.c_str(), "pragmaCount: %u", &numDefns) == 1) 2297 { 2298 char name[MAXLINE]; 2299 char value[MAXLINE]; 2300 while (numDefns--) 2301 { 2302 name[0] = '\0'; 2303 value[0] = '\0'; 2304 if (sscanf(info_lines[++offset].c_str(), "%s - %s", &name[0], &value[0]) != 0 2305 && (name[0] != '\0')) 2306 { 2307 m_pragmas[std::string(name)] = value; 2308 } 2309 } 2310 } 2311 else if (sscanf(line.c_str(), "objectSlotCount: %u", &numDefns) == 1) 2312 { 2313 } 2314 2315 offset++; 2316 } 2317 return m_kernels.size() > 0; 2318 } 2319 return false; 2320 } 2321 2322 bool 2323 RenderScriptRuntime::ProbeModules(const ModuleList module_list) 2324 { 2325 bool rs_found = false; 2326 size_t num_modules = module_list.GetSize(); 2327 for (size_t i = 0; i < num_modules; i++) 2328 { 2329 auto module = module_list.GetModuleAtIndex(i); 2330 rs_found |= LoadModule(module); 2331 } 2332 return rs_found; 2333 } 2334 2335 void 2336 RenderScriptRuntime::Status(Stream &strm) const 2337 { 2338 if (m_libRS) 2339 { 2340 strm.Printf("Runtime Library discovered."); 2341 strm.EOL(); 2342 } 2343 if (m_libRSDriver) 2344 { 2345 strm.Printf("Runtime Driver discovered."); 2346 strm.EOL(); 2347 } 2348 if (m_libRSCpuRef) 2349 { 2350 strm.Printf("CPU Reference Implementation discovered."); 2351 strm.EOL(); 2352 } 2353 2354 if (m_runtimeHooks.size()) 2355 { 2356 strm.Printf("Runtime functions hooked:"); 2357 strm.EOL(); 2358 for (auto b : m_runtimeHooks) 2359 { 2360 strm.Indent(b.second->defn->name); 2361 strm.EOL(); 2362 } 2363 } 2364 else 2365 { 2366 strm.Printf("Runtime is not hooked."); 2367 strm.EOL(); 2368 } 2369 } 2370 2371 void 2372 RenderScriptRuntime::DumpContexts(Stream &strm) const 2373 { 2374 strm.Printf("Inferred RenderScript Contexts:"); 2375 strm.EOL(); 2376 strm.IndentMore(); 2377 2378 std::map<addr_t, uint64_t> contextReferences; 2379 2380 // Iterate over all of the currently discovered scripts. 2381 // Note: We cant push or pop from m_scripts inside this loop or it may invalidate script. 2382 for (const auto & script : m_scripts) 2383 { 2384 if (!script->context.isValid()) 2385 continue; 2386 lldb::addr_t context = *script->context; 2387 2388 if (contextReferences.find(context) != contextReferences.end()) 2389 { 2390 contextReferences[context]++; 2391 } 2392 else 2393 { 2394 contextReferences[context] = 1; 2395 } 2396 } 2397 2398 for (const auto& cRef : contextReferences) 2399 { 2400 strm.Printf("Context 0x%" PRIx64 ": %" PRIu64 " script instances", cRef.first, cRef.second); 2401 strm.EOL(); 2402 } 2403 strm.IndentLess(); 2404 } 2405 2406 void 2407 RenderScriptRuntime::DumpKernels(Stream &strm) const 2408 { 2409 strm.Printf("RenderScript Kernels:"); 2410 strm.EOL(); 2411 strm.IndentMore(); 2412 for (const auto &module : m_rsmodules) 2413 { 2414 strm.Printf("Resource '%s':",module->m_resname.c_str()); 2415 strm.EOL(); 2416 for (const auto &kernel : module->m_kernels) 2417 { 2418 strm.Indent(kernel.m_name.AsCString()); 2419 strm.EOL(); 2420 } 2421 } 2422 strm.IndentLess(); 2423 } 2424 2425 RenderScriptRuntime::AllocationDetails* 2426 RenderScriptRuntime::FindAllocByID(Stream &strm, const uint32_t alloc_id) 2427 { 2428 AllocationDetails* alloc = nullptr; 2429 2430 // See if we can find allocation using id as an index; 2431 if (alloc_id <= m_allocations.size() && alloc_id != 0 2432 && m_allocations[alloc_id-1]->id == alloc_id) 2433 { 2434 alloc = m_allocations[alloc_id-1].get(); 2435 return alloc; 2436 } 2437 2438 // Fallback to searching 2439 for (const auto & a : m_allocations) 2440 { 2441 if (a->id == alloc_id) 2442 { 2443 alloc = a.get(); 2444 break; 2445 } 2446 } 2447 2448 if (alloc == nullptr) 2449 { 2450 strm.Printf("Error: Couldn't find allocation with id matching %u", alloc_id); 2451 strm.EOL(); 2452 } 2453 2454 return alloc; 2455 } 2456 2457 // Prints the contents of an allocation to the output stream, which may be a file 2458 bool 2459 RenderScriptRuntime::DumpAllocation(Stream &strm, StackFrame* frame_ptr, const uint32_t id) 2460 { 2461 Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 2462 2463 // Check we can find the desired allocation 2464 AllocationDetails* alloc = FindAllocByID(strm, id); 2465 if (!alloc) 2466 return false; // FindAllocByID() will print error message for us here 2467 2468 if (log) 2469 log->Printf("RenderScriptRuntime::DumpAllocation - Found allocation 0x%" PRIx64, *alloc->address.get()); 2470 2471 // Check we have information about the allocation, if not calculate it 2472 if (alloc->shouldRefresh()) 2473 { 2474 if (log) 2475 log->Printf("RenderScriptRuntime::DumpAllocation - Allocation details not calculated yet, jitting info"); 2476 2477 // JIT all the allocation information 2478 if (!RefreshAllocation(alloc, frame_ptr)) 2479 { 2480 strm.Printf("Error: Couldn't JIT allocation details"); 2481 strm.EOL(); 2482 return false; 2483 } 2484 } 2485 2486 // Establish format and size of each data element 2487 const unsigned int vec_size = *alloc->element.type_vec_size.get(); 2488 const Element::DataType type = *alloc->element.type.get(); 2489 2490 assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_BOOLEAN 2491 && "Invalid allocation type"); 2492 2493 lldb::Format format = vec_size == 1 ? static_cast<lldb::Format>(AllocationDetails::RSTypeToFormat[type][eFormatSingle]) 2494 : static_cast<lldb::Format>(AllocationDetails::RSTypeToFormat[type][eFormatVector]); 2495 2496 const unsigned int data_size = *alloc->element.datum_size.get(); 2497 2498 if (log) 2499 log->Printf("RenderScriptRuntime::DumpAllocation - Element size %u bytes, including padding", data_size); 2500 2501 // Allocate a buffer to copy data into 2502 std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr); 2503 if (!buffer) 2504 { 2505 strm.Printf("Error: Couldn't allocate a read allocation data into memory"); 2506 strm.EOL(); 2507 return false; 2508 } 2509 2510 // Calculate stride between rows as there may be padding at end of rows since 2511 // allocated memory is 16-byte aligned 2512 if (!alloc->stride.isValid()) 2513 { 2514 if (alloc->dimension.get()->dim_2 == 0) // We only have one dimension 2515 alloc->stride = 0; 2516 else if (!JITAllocationStride(alloc, frame_ptr)) 2517 { 2518 strm.Printf("Error: Couldn't calculate allocation row stride"); 2519 strm.EOL(); 2520 return false; 2521 } 2522 } 2523 const unsigned int stride = *alloc->stride.get(); 2524 const unsigned int size = *alloc->size.get(); // Size of whole allocation 2525 const unsigned int padding = alloc->element.padding.isValid() ? *alloc->element.padding.get() : 0; 2526 if (log) 2527 log->Printf("RenderScriptRuntime::DumpAllocation - stride %u bytes, size %u bytes, padding %u", stride, size, padding); 2528 2529 // Find dimensions used to index loops, so need to be non-zero 2530 unsigned int dim_x = alloc->dimension.get()->dim_1; 2531 dim_x = dim_x == 0 ? 1 : dim_x; 2532 2533 unsigned int dim_y = alloc->dimension.get()->dim_2; 2534 dim_y = dim_y == 0 ? 1 : dim_y; 2535 2536 unsigned int dim_z = alloc->dimension.get()->dim_3; 2537 dim_z = dim_z == 0 ? 1 : dim_z; 2538 2539 // Use data extractor to format output 2540 const uint32_t archByteSize = GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize(); 2541 DataExtractor alloc_data(buffer.get(), size, GetProcess()->GetByteOrder(), archByteSize); 2542 2543 unsigned int offset = 0; // Offset in buffer to next element to be printed 2544 unsigned int prev_row = 0; // Offset to the start of the previous row 2545 2546 // Iterate over allocation dimensions, printing results to user 2547 strm.Printf("Data (X, Y, Z):"); 2548 for (unsigned int z = 0; z < dim_z; ++z) 2549 { 2550 for (unsigned int y = 0; y < dim_y; ++y) 2551 { 2552 // Use stride to index start of next row. 2553 if (!(y==0 && z==0)) 2554 offset = prev_row + stride; 2555 prev_row = offset; 2556 2557 // Print each element in the row individually 2558 for (unsigned int x = 0; x < dim_x; ++x) 2559 { 2560 strm.Printf("\n(%u, %u, %u) = ", x, y, z); 2561 if ((type == Element::RS_TYPE_NONE) && (alloc->element.children.size() > 0) && 2562 (alloc->element.type_name != Element::GetFallbackStructName())) 2563 { 2564 // Here we are dumping an Element of struct type. 2565 // This is done using expression evaluation with the name of the struct type and pointer to element. 2566 2567 // Don't print the name of the resulting expression, since this will be '$[0-9]+' 2568 DumpValueObjectOptions expr_options; 2569 expr_options.SetHideName(true); 2570 2571 // Setup expression as derefrencing a pointer cast to element address. 2572 char expr_char_buffer[jit_max_expr_size]; 2573 int chars_written = snprintf(expr_char_buffer, jit_max_expr_size, "*(%s*) 0x%" PRIx64, 2574 alloc->element.type_name.AsCString(), *alloc->data_ptr.get() + offset); 2575 2576 if (chars_written < 0 || chars_written >= jit_max_expr_size) 2577 { 2578 if (log) 2579 log->Printf("RenderScriptRuntime::DumpAllocation- Error in snprintf()"); 2580 continue; 2581 } 2582 2583 // Evaluate expression 2584 ValueObjectSP expr_result; 2585 GetProcess()->GetTarget().EvaluateExpression(expr_char_buffer, frame_ptr, expr_result); 2586 2587 // Print the results to our stream. 2588 expr_result->Dump(strm, expr_options); 2589 } 2590 else 2591 { 2592 alloc_data.Dump(&strm, offset, format, data_size - padding, 1, 1, LLDB_INVALID_ADDRESS, 0, 0); 2593 } 2594 offset += data_size; 2595 } 2596 } 2597 } 2598 strm.EOL(); 2599 2600 return true; 2601 } 2602 2603 // Prints infomation regarding all the currently loaded allocations. 2604 // These details are gathered by jitting the runtime, which has as latency. 2605 void 2606 RenderScriptRuntime::ListAllocations(Stream &strm, StackFrame* frame_ptr, bool recompute) 2607 { 2608 strm.Printf("RenderScript Allocations:"); 2609 strm.EOL(); 2610 strm.IndentMore(); 2611 2612 for (auto &alloc : m_allocations) 2613 { 2614 // JIT the allocation info if we haven't done it, or the user forces us to. 2615 bool do_refresh = alloc->shouldRefresh() || recompute; 2616 2617 // JIT current allocation information 2618 if (do_refresh && !RefreshAllocation(alloc.get(), frame_ptr)) 2619 { 2620 strm.Printf("Error: Couldn't evaluate details for allocation %u\n", alloc->id); 2621 continue; 2622 } 2623 2624 strm.Printf("%u:\n",alloc->id); 2625 strm.IndentMore(); 2626 2627 strm.Indent("Context: "); 2628 if (!alloc->context.isValid()) 2629 strm.Printf("unknown\n"); 2630 else 2631 strm.Printf("0x%" PRIx64 "\n", *alloc->context.get()); 2632 2633 strm.Indent("Address: "); 2634 if (!alloc->address.isValid()) 2635 strm.Printf("unknown\n"); 2636 else 2637 strm.Printf("0x%" PRIx64 "\n", *alloc->address.get()); 2638 2639 strm.Indent("Data pointer: "); 2640 if (!alloc->data_ptr.isValid()) 2641 strm.Printf("unknown\n"); 2642 else 2643 strm.Printf("0x%" PRIx64 "\n", *alloc->data_ptr.get()); 2644 2645 strm.Indent("Dimensions: "); 2646 if (!alloc->dimension.isValid()) 2647 strm.Printf("unknown\n"); 2648 else 2649 strm.Printf("(%d, %d, %d)\n", alloc->dimension.get()->dim_1, 2650 alloc->dimension.get()->dim_2, 2651 alloc->dimension.get()->dim_3); 2652 2653 strm.Indent("Data Type: "); 2654 if (!alloc->element.type.isValid() || !alloc->element.type_vec_size.isValid()) 2655 strm.Printf("unknown\n"); 2656 else 2657 { 2658 const int vector_size = *alloc->element.type_vec_size.get(); 2659 const Element::DataType type = *alloc->element.type.get(); 2660 2661 if (!alloc->element.type_name.IsEmpty()) 2662 strm.Printf("%s\n", alloc->element.type_name.AsCString()); 2663 else if (vector_size > 4 || vector_size < 1 || 2664 type < Element::RS_TYPE_NONE || type > Element::RS_TYPE_BOOLEAN) 2665 strm.Printf("invalid type\n"); 2666 else 2667 strm.Printf("%s\n", AllocationDetails::RsDataTypeToString[static_cast<unsigned int>(type)][vector_size-1]); 2668 } 2669 2670 strm.Indent("Data Kind: "); 2671 if (!alloc->element.type_kind.isValid()) 2672 strm.Printf("unknown\n"); 2673 else 2674 { 2675 const Element::DataKind kind = *alloc->element.type_kind.get(); 2676 if (kind < Element::RS_KIND_USER || kind > Element::RS_KIND_PIXEL_YUV) 2677 strm.Printf("invalid kind\n"); 2678 else 2679 strm.Printf("%s\n", AllocationDetails::RsDataKindToString[static_cast<unsigned int>(kind)]); 2680 } 2681 2682 strm.EOL(); 2683 strm.IndentLess(); 2684 } 2685 strm.IndentLess(); 2686 } 2687 2688 // Set breakpoints on every kernel found in RS module 2689 void 2690 RenderScriptRuntime::BreakOnModuleKernels(const RSModuleDescriptorSP rsmodule_sp) 2691 { 2692 for (const auto &kernel : rsmodule_sp->m_kernels) 2693 { 2694 // Don't set breakpoint on 'root' kernel 2695 if (strcmp(kernel.m_name.AsCString(), "root") == 0) 2696 continue; 2697 2698 CreateKernelBreakpoint(kernel.m_name); 2699 } 2700 } 2701 2702 // Method is internally called by the 'kernel breakpoint all' command to 2703 // enable or disable breaking on all kernels. 2704 // 2705 // When do_break is true we want to enable this functionality. 2706 // When do_break is false we want to disable it. 2707 void 2708 RenderScriptRuntime::SetBreakAllKernels(bool do_break, TargetSP target) 2709 { 2710 Log* log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS)); 2711 2712 InitSearchFilter(target); 2713 2714 // Set breakpoints on all the kernels 2715 if (do_break && !m_breakAllKernels) 2716 { 2717 m_breakAllKernels = true; 2718 2719 for (const auto &module : m_rsmodules) 2720 BreakOnModuleKernels(module); 2721 2722 if (log) 2723 log->Printf("RenderScriptRuntime::SetBreakAllKernels(True)" 2724 "- breakpoints set on all currently loaded kernels"); 2725 } 2726 else if (!do_break && m_breakAllKernels) // Breakpoints won't be set on any new kernels. 2727 { 2728 m_breakAllKernels = false; 2729 2730 if (log) 2731 log->Printf("RenderScriptRuntime::SetBreakAllKernels(False) - breakpoints no longer automatically set"); 2732 } 2733 } 2734 2735 // Given the name of a kernel this function creates a breakpoint using our 2736 // own breakpoint resolver, and returns the Breakpoint shared pointer. 2737 BreakpointSP 2738 RenderScriptRuntime::CreateKernelBreakpoint(const ConstString& name) 2739 { 2740 Log* log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS)); 2741 2742 if (!m_filtersp) 2743 { 2744 if (log) 2745 log->Printf("RenderScriptRuntime::CreateKernelBreakpoint - Error: No breakpoint search filter set"); 2746 return nullptr; 2747 } 2748 2749 BreakpointResolverSP resolver_sp(new RSBreakpointResolver(nullptr, name)); 2750 BreakpointSP bp = GetProcess()->GetTarget().CreateBreakpoint(m_filtersp, resolver_sp, false, false, false); 2751 2752 // Give RS breakpoints a specific name, so the user can manipulate them as a group. 2753 Error err; 2754 if (!bp->AddName("RenderScriptKernel", err) && log) 2755 log->Printf("RenderScriptRuntime::CreateKernelBreakpoint: Error setting break name, %s", err.AsCString()); 2756 2757 return bp; 2758 } 2759 2760 // Given an expression for a variable this function tries to calculate the variable's value. 2761 // If this is possible it returns true and sets the uint64_t parameter to the variables unsigned value. 2762 // Otherwise function returns false. 2763 bool 2764 RenderScriptRuntime::GetFrameVarAsUnsigned(const StackFrameSP frame_sp, const char* var_name, uint64_t& val) 2765 { 2766 Log* log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE)); 2767 Error error; 2768 VariableSP var_sp; 2769 2770 // Find variable in stack frame 2771 ValueObjectSP value_sp(frame_sp->GetValueForVariableExpressionPath(var_name, 2772 eNoDynamicValues, 2773 StackFrame::eExpressionPathOptionCheckPtrVsMember | 2774 StackFrame::eExpressionPathOptionsAllowDirectIVarAccess, 2775 var_sp, 2776 error)); 2777 if (!error.Success()) 2778 { 2779 if (log) 2780 log->Printf("RenderScriptRuntime::GetFrameVarAsUnsigned - Error, couldn't find '%s' in frame", var_name); 2781 2782 return false; 2783 } 2784 2785 // Find the unsigned int value for the variable 2786 bool success = false; 2787 val = value_sp->GetValueAsUnsigned(0, &success); 2788 if (!success) 2789 { 2790 if (log) 2791 log->Printf("RenderScriptRuntime::GetFrameVarAsUnsigned - Error, couldn't parse '%s' as an unsigned int", var_name); 2792 2793 return false; 2794 } 2795 2796 return true; 2797 } 2798 2799 // Callback when a kernel breakpoint hits and we're looking for a specific coordinate. 2800 // Baton parameter contains a pointer to the target coordinate we want to break on. 2801 // Function then checks the .expand frame for the current coordinate and breaks to user if it matches. 2802 // Parameter 'break_id' is the id of the Breakpoint which made the callback. 2803 // Parameter 'break_loc_id' is the id for the BreakpointLocation which was hit, 2804 // a single logical breakpoint can have multiple addresses. 2805 bool 2806 RenderScriptRuntime::KernelBreakpointHit(void *baton, StoppointCallbackContext *ctx, 2807 user_id_t break_id, user_id_t break_loc_id) 2808 { 2809 Log* log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS)); 2810 2811 assert(baton && "Error: null baton in conditional kernel breakpoint callback"); 2812 2813 // Coordinate we want to stop on 2814 const int* target_coord = static_cast<const int*>(baton); 2815 2816 if (log) 2817 log->Printf("RenderScriptRuntime::KernelBreakpointHit - Break ID %" PRIu64 ", target coord (%d, %d, %d)", 2818 break_id, target_coord[0], target_coord[1], target_coord[2]); 2819 2820 // Go up one stack frame to .expand kernel 2821 ExecutionContext context(ctx->exe_ctx_ref); 2822 ThreadSP thread_sp = context.GetThreadSP(); 2823 if (!thread_sp->SetSelectedFrameByIndex(1)) 2824 { 2825 if (log) 2826 log->Printf("RenderScriptRuntime::KernelBreakpointHit - Error, couldn't go up stack frame"); 2827 2828 return false; 2829 } 2830 2831 StackFrameSP frame_sp = thread_sp->GetSelectedFrame(); 2832 if (!frame_sp) 2833 { 2834 if (log) 2835 log->Printf("RenderScriptRuntime::KernelBreakpointHit - Error, couldn't select .expand stack frame"); 2836 2837 return false; 2838 } 2839 2840 // Get values for variables in .expand frame that tell us the current kernel invocation 2841 const char* coord_expressions[] = {"rsIndex", "p->current.y", "p->current.z"}; 2842 uint64_t current_coord[3] = {0, 0, 0}; 2843 2844 for(int i = 0; i < 3; ++i) 2845 { 2846 if (!GetFrameVarAsUnsigned(frame_sp, coord_expressions[i], current_coord[i])) 2847 return false; 2848 2849 if (log) 2850 log->Printf("RenderScriptRuntime::KernelBreakpointHit, %s = %" PRIu64, coord_expressions[i], current_coord[i]); 2851 } 2852 2853 // Check if the current kernel invocation coordinate matches our target coordinate 2854 if (current_coord[0] == static_cast<uint64_t>(target_coord[0]) && 2855 current_coord[1] == static_cast<uint64_t>(target_coord[1]) && 2856 current_coord[2] == static_cast<uint64_t>(target_coord[2])) 2857 { 2858 if (log) 2859 log->Printf("RenderScriptRuntime::KernelBreakpointHit, BREAKING %" PRIu64 ", %" PRIu64 ", %" PRIu64, 2860 current_coord[0], current_coord[1], current_coord[2]); 2861 2862 BreakpointSP breakpoint_sp = context.GetTargetPtr()->GetBreakpointByID(break_id); 2863 assert(breakpoint_sp != nullptr && "Error: Couldn't find breakpoint matching break id for callback"); 2864 breakpoint_sp->SetEnabled(false); // Optimise since conditional breakpoint should only be hit once. 2865 return true; 2866 } 2867 2868 // No match on coordinate 2869 return false; 2870 } 2871 2872 // Tries to set a breakpoint on the start of a kernel, resolved using the kernel name. 2873 // Argument 'coords', represents a three dimensional coordinate which can be used to specify 2874 // a single kernel instance to break on. If this is set then we add a callback to the breakpoint. 2875 void 2876 RenderScriptRuntime::PlaceBreakpointOnKernel(Stream &strm, const char* name, const std::array<int,3> coords, 2877 Error& error, TargetSP target) 2878 { 2879 if (!name) 2880 { 2881 error.SetErrorString("invalid kernel name"); 2882 return; 2883 } 2884 2885 InitSearchFilter(target); 2886 2887 ConstString kernel_name(name); 2888 BreakpointSP bp = CreateKernelBreakpoint(kernel_name); 2889 2890 // We have a conditional breakpoint on a specific coordinate 2891 if (coords[0] != -1) 2892 { 2893 strm.Printf("Conditional kernel breakpoint on coordinate %d, %d, %d", coords[0], coords[1], coords[2]); 2894 strm.EOL(); 2895 2896 // Allocate memory for the baton, and copy over coordinate 2897 int* baton = new int[3]; 2898 baton[0] = coords[0]; baton[1] = coords[1]; baton[2] = coords[2]; 2899 2900 // Create a callback that will be invoked everytime the breakpoint is hit. 2901 // The baton object passed to the handler is the target coordinate we want to break on. 2902 bp->SetCallback(KernelBreakpointHit, baton, true); 2903 2904 // Store a shared pointer to the baton, so the memory will eventually be cleaned up after destruction 2905 m_conditional_breaks[bp->GetID()] = std::shared_ptr<int>(baton); 2906 } 2907 2908 if (bp) 2909 bp->GetDescription(&strm, lldb::eDescriptionLevelInitial, false); 2910 } 2911 2912 void 2913 RenderScriptRuntime::DumpModules(Stream &strm) const 2914 { 2915 strm.Printf("RenderScript Modules:"); 2916 strm.EOL(); 2917 strm.IndentMore(); 2918 for (const auto &module : m_rsmodules) 2919 { 2920 module->Dump(strm); 2921 } 2922 strm.IndentLess(); 2923 } 2924 2925 RenderScriptRuntime::ScriptDetails* 2926 RenderScriptRuntime::LookUpScript(addr_t address, bool create) 2927 { 2928 for (const auto & s : m_scripts) 2929 { 2930 if (s->script.isValid()) 2931 if (*s->script == address) 2932 return s.get(); 2933 } 2934 if (create) 2935 { 2936 std::unique_ptr<ScriptDetails> s(new ScriptDetails); 2937 s->script = address; 2938 m_scripts.push_back(std::move(s)); 2939 return m_scripts.back().get(); 2940 } 2941 return nullptr; 2942 } 2943 2944 RenderScriptRuntime::AllocationDetails* 2945 RenderScriptRuntime::LookUpAllocation(addr_t address, bool create) 2946 { 2947 for (const auto & a : m_allocations) 2948 { 2949 if (a->address.isValid()) 2950 if (*a->address == address) 2951 return a.get(); 2952 } 2953 if (create) 2954 { 2955 std::unique_ptr<AllocationDetails> a(new AllocationDetails); 2956 a->address = address; 2957 m_allocations.push_back(std::move(a)); 2958 return m_allocations.back().get(); 2959 } 2960 return nullptr; 2961 } 2962 2963 void 2964 RSModuleDescriptor::Dump(Stream &strm) const 2965 { 2966 strm.Indent(); 2967 m_module->GetFileSpec().Dump(&strm); 2968 if(m_module->GetNumCompileUnits()) 2969 { 2970 strm.Indent("Debug info loaded."); 2971 } 2972 else 2973 { 2974 strm.Indent("Debug info does not exist."); 2975 } 2976 strm.EOL(); 2977 strm.IndentMore(); 2978 strm.Indent(); 2979 strm.Printf("Globals: %" PRIu64, static_cast<uint64_t>(m_globals.size())); 2980 strm.EOL(); 2981 strm.IndentMore(); 2982 for (const auto &global : m_globals) 2983 { 2984 global.Dump(strm); 2985 } 2986 strm.IndentLess(); 2987 strm.Indent(); 2988 strm.Printf("Kernels: %" PRIu64, static_cast<uint64_t>(m_kernels.size())); 2989 strm.EOL(); 2990 strm.IndentMore(); 2991 for (const auto &kernel : m_kernels) 2992 { 2993 kernel.Dump(strm); 2994 } 2995 strm.Printf("Pragmas: %" PRIu64 , static_cast<uint64_t>(m_pragmas.size())); 2996 strm.EOL(); 2997 strm.IndentMore(); 2998 for (const auto &key_val : m_pragmas) 2999 { 3000 strm.Printf("%s: %s", key_val.first.c_str(), key_val.second.c_str()); 3001 strm.EOL(); 3002 } 3003 strm.IndentLess(4); 3004 } 3005 3006 void 3007 RSGlobalDescriptor::Dump(Stream &strm) const 3008 { 3009 strm.Indent(m_name.AsCString()); 3010 VariableList var_list; 3011 m_module->m_module->FindGlobalVariables(m_name, nullptr, true, 1U, var_list); 3012 if (var_list.GetSize() == 1) 3013 { 3014 auto var = var_list.GetVariableAtIndex(0); 3015 auto type = var->GetType(); 3016 if(type) 3017 { 3018 strm.Printf(" - "); 3019 type->DumpTypeName(&strm); 3020 } 3021 else 3022 { 3023 strm.Printf(" - Unknown Type"); 3024 } 3025 } 3026 else 3027 { 3028 strm.Printf(" - variable identified, but not found in binary"); 3029 const Symbol* s = m_module->m_module->FindFirstSymbolWithNameAndType(m_name, eSymbolTypeData); 3030 if (s) 3031 { 3032 strm.Printf(" (symbol exists) "); 3033 } 3034 } 3035 3036 strm.EOL(); 3037 } 3038 3039 void 3040 RSKernelDescriptor::Dump(Stream &strm) const 3041 { 3042 strm.Indent(m_name.AsCString()); 3043 strm.EOL(); 3044 } 3045 3046 class CommandObjectRenderScriptRuntimeModuleProbe : public CommandObjectParsed 3047 { 3048 public: 3049 CommandObjectRenderScriptRuntimeModuleProbe(CommandInterpreter &interpreter) 3050 : CommandObjectParsed(interpreter, "renderscript module probe", 3051 "Initiates a Probe of all loaded modules for kernels and other renderscript objects.", 3052 "renderscript module probe", 3053 eCommandRequiresTarget | eCommandRequiresProcess | eCommandProcessMustBeLaunched) 3054 { 3055 } 3056 3057 ~CommandObjectRenderScriptRuntimeModuleProbe() override = default; 3058 3059 bool 3060 DoExecute(Args &command, CommandReturnObject &result) override 3061 { 3062 const size_t argc = command.GetArgumentCount(); 3063 if (argc == 0) 3064 { 3065 Target *target = m_exe_ctx.GetTargetPtr(); 3066 RenderScriptRuntime *runtime = 3067 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript); 3068 auto module_list = target->GetImages(); 3069 bool new_rs_details = runtime->ProbeModules(module_list); 3070 if (new_rs_details) 3071 { 3072 result.AppendMessage("New renderscript modules added to runtime model."); 3073 } 3074 result.SetStatus(eReturnStatusSuccessFinishResult); 3075 return true; 3076 } 3077 3078 result.AppendErrorWithFormat("'%s' takes no arguments", m_cmd_name.c_str()); 3079 result.SetStatus(eReturnStatusFailed); 3080 return false; 3081 } 3082 }; 3083 3084 class CommandObjectRenderScriptRuntimeModuleDump : public CommandObjectParsed 3085 { 3086 public: 3087 CommandObjectRenderScriptRuntimeModuleDump(CommandInterpreter &interpreter) 3088 : CommandObjectParsed(interpreter, "renderscript module dump", 3089 "Dumps renderscript specific information for all modules.", "renderscript module dump", 3090 eCommandRequiresProcess | eCommandProcessMustBeLaunched) 3091 { 3092 } 3093 3094 ~CommandObjectRenderScriptRuntimeModuleDump() override = default; 3095 3096 bool 3097 DoExecute(Args &command, CommandReturnObject &result) override 3098 { 3099 RenderScriptRuntime *runtime = 3100 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript); 3101 runtime->DumpModules(result.GetOutputStream()); 3102 result.SetStatus(eReturnStatusSuccessFinishResult); 3103 return true; 3104 } 3105 }; 3106 3107 class CommandObjectRenderScriptRuntimeModule : public CommandObjectMultiword 3108 { 3109 public: 3110 CommandObjectRenderScriptRuntimeModule(CommandInterpreter &interpreter) 3111 : CommandObjectMultiword(interpreter, "renderscript module", "Commands that deal with renderscript modules.", 3112 NULL) 3113 { 3114 LoadSubCommand("probe", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleProbe(interpreter))); 3115 LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleDump(interpreter))); 3116 } 3117 3118 ~CommandObjectRenderScriptRuntimeModule() override = default; 3119 }; 3120 3121 class CommandObjectRenderScriptRuntimeKernelList : public CommandObjectParsed 3122 { 3123 public: 3124 CommandObjectRenderScriptRuntimeKernelList(CommandInterpreter &interpreter) 3125 : CommandObjectParsed(interpreter, "renderscript kernel list", 3126 "Lists renderscript kernel names and associated script resources.", "renderscript kernel list", 3127 eCommandRequiresProcess | eCommandProcessMustBeLaunched) 3128 { 3129 } 3130 3131 ~CommandObjectRenderScriptRuntimeKernelList() override = default; 3132 3133 bool 3134 DoExecute(Args &command, CommandReturnObject &result) override 3135 { 3136 RenderScriptRuntime *runtime = 3137 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript); 3138 runtime->DumpKernels(result.GetOutputStream()); 3139 result.SetStatus(eReturnStatusSuccessFinishResult); 3140 return true; 3141 } 3142 }; 3143 3144 class CommandObjectRenderScriptRuntimeKernelBreakpointSet : public CommandObjectParsed 3145 { 3146 public: 3147 CommandObjectRenderScriptRuntimeKernelBreakpointSet(CommandInterpreter &interpreter) 3148 : CommandObjectParsed(interpreter, "renderscript kernel breakpoint set", 3149 "Sets a breakpoint on a renderscript kernel.", "renderscript kernel breakpoint set <kernel_name> [-c x,y,z]", 3150 eCommandRequiresProcess | eCommandProcessMustBeLaunched | eCommandProcessMustBePaused), m_options(interpreter) 3151 { 3152 } 3153 3154 ~CommandObjectRenderScriptRuntimeKernelBreakpointSet() override = default; 3155 3156 Options* 3157 GetOptions() override 3158 { 3159 return &m_options; 3160 } 3161 3162 class CommandOptions : public Options 3163 { 3164 public: 3165 CommandOptions(CommandInterpreter &interpreter) : Options(interpreter) 3166 { 3167 } 3168 3169 ~CommandOptions() override = default; 3170 3171 Error 3172 SetOptionValue(uint32_t option_idx, const char *option_arg) override 3173 { 3174 Error error; 3175 const int short_option = m_getopt_table[option_idx].val; 3176 3177 switch (short_option) 3178 { 3179 case 'c': 3180 if (!ParseCoordinate(option_arg)) 3181 error.SetErrorStringWithFormat("Couldn't parse coordinate '%s', should be in format 'x,y,z'.", option_arg); 3182 break; 3183 default: 3184 error.SetErrorStringWithFormat("unrecognized option '%c'", short_option); 3185 break; 3186 } 3187 return error; 3188 } 3189 3190 // -c takes an argument of the form 'num[,num][,num]'. 3191 // Where 'id_cstr' is this argument with the whitespace trimmed. 3192 // Missing coordinates are defaulted to zero. 3193 bool 3194 ParseCoordinate(const char* id_cstr) 3195 { 3196 RegularExpression regex; 3197 RegularExpression::Match regex_match(3); 3198 3199 bool matched = false; 3200 if(regex.Compile("^([0-9]+),([0-9]+),([0-9]+)$") && regex.Execute(id_cstr, ®ex_match)) 3201 matched = true; 3202 else if(regex.Compile("^([0-9]+),([0-9]+)$") && regex.Execute(id_cstr, ®ex_match)) 3203 matched = true; 3204 else if(regex.Compile("^([0-9]+)$") && regex.Execute(id_cstr, ®ex_match)) 3205 matched = true; 3206 for(uint32_t i = 0; i < 3; i++) 3207 { 3208 std::string group; 3209 if(regex_match.GetMatchAtIndex(id_cstr, i + 1, group)) 3210 m_coord[i] = (uint32_t)strtoul(group.c_str(), NULL, 0); 3211 else 3212 m_coord[i] = 0; 3213 } 3214 return matched; 3215 } 3216 3217 void 3218 OptionParsingStarting() override 3219 { 3220 // -1 means the -c option hasn't been set 3221 m_coord[0] = -1; 3222 m_coord[1] = -1; 3223 m_coord[2] = -1; 3224 } 3225 3226 const OptionDefinition* 3227 GetDefinitions() override 3228 { 3229 return g_option_table; 3230 } 3231 3232 static OptionDefinition g_option_table[]; 3233 std::array<int,3> m_coord; 3234 }; 3235 3236 bool 3237 DoExecute(Args &command, CommandReturnObject &result) override 3238 { 3239 const size_t argc = command.GetArgumentCount(); 3240 if (argc < 1) 3241 { 3242 result.AppendErrorWithFormat("'%s' takes 1 argument of kernel name, and an optional coordinate.", m_cmd_name.c_str()); 3243 result.SetStatus(eReturnStatusFailed); 3244 return false; 3245 } 3246 3247 RenderScriptRuntime *runtime = 3248 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript); 3249 3250 Error error; 3251 runtime->PlaceBreakpointOnKernel(result.GetOutputStream(), command.GetArgumentAtIndex(0), m_options.m_coord, 3252 error, m_exe_ctx.GetTargetSP()); 3253 3254 if (error.Success()) 3255 { 3256 result.AppendMessage("Breakpoint(s) created"); 3257 result.SetStatus(eReturnStatusSuccessFinishResult); 3258 return true; 3259 } 3260 result.SetStatus(eReturnStatusFailed); 3261 result.AppendErrorWithFormat("Error: %s", error.AsCString()); 3262 return false; 3263 } 3264 3265 private: 3266 CommandOptions m_options; 3267 }; 3268 3269 OptionDefinition 3270 CommandObjectRenderScriptRuntimeKernelBreakpointSet::CommandOptions::g_option_table[] = 3271 { 3272 { LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeValue, 3273 "Set a breakpoint on a single invocation of the kernel with specified coordinate.\n" 3274 "Coordinate takes the form 'x[,y][,z] where x,y,z are positive integers representing kernel dimensions. " 3275 "Any unset dimensions will be defaulted to zero."}, 3276 { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL } 3277 }; 3278 3279 class CommandObjectRenderScriptRuntimeKernelBreakpointAll : public CommandObjectParsed 3280 { 3281 public: 3282 CommandObjectRenderScriptRuntimeKernelBreakpointAll(CommandInterpreter &interpreter) 3283 : CommandObjectParsed(interpreter, "renderscript kernel breakpoint all", 3284 "Automatically sets a breakpoint on all renderscript kernels that are or will be loaded.\n" 3285 "Disabling option means breakpoints will no longer be set on any kernels loaded in the future, " 3286 "but does not remove currently set breakpoints.", 3287 "renderscript kernel breakpoint all <enable/disable>", 3288 eCommandRequiresProcess | eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) 3289 { 3290 } 3291 3292 ~CommandObjectRenderScriptRuntimeKernelBreakpointAll() override = default; 3293 3294 bool 3295 DoExecute(Args &command, CommandReturnObject &result) override 3296 { 3297 const size_t argc = command.GetArgumentCount(); 3298 if (argc != 1) 3299 { 3300 result.AppendErrorWithFormat("'%s' takes 1 argument of 'enable' or 'disable'", m_cmd_name.c_str()); 3301 result.SetStatus(eReturnStatusFailed); 3302 return false; 3303 } 3304 3305 RenderScriptRuntime *runtime = 3306 static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript)); 3307 3308 bool do_break = false; 3309 const char* argument = command.GetArgumentAtIndex(0); 3310 if (strcmp(argument, "enable") == 0) 3311 { 3312 do_break = true; 3313 result.AppendMessage("Breakpoints will be set on all kernels."); 3314 } 3315 else if (strcmp(argument, "disable") == 0) 3316 { 3317 do_break = false; 3318 result.AppendMessage("Breakpoints will not be set on any new kernels."); 3319 } 3320 else 3321 { 3322 result.AppendErrorWithFormat("Argument must be either 'enable' or 'disable'"); 3323 result.SetStatus(eReturnStatusFailed); 3324 return false; 3325 } 3326 3327 runtime->SetBreakAllKernels(do_break, m_exe_ctx.GetTargetSP()); 3328 3329 result.SetStatus(eReturnStatusSuccessFinishResult); 3330 return true; 3331 } 3332 }; 3333 3334 class CommandObjectRenderScriptRuntimeKernelBreakpoint : public CommandObjectMultiword 3335 { 3336 public: 3337 CommandObjectRenderScriptRuntimeKernelBreakpoint(CommandInterpreter &interpreter) 3338 : CommandObjectMultiword(interpreter, "renderscript kernel", "Commands that generate breakpoints on renderscript kernels.", 3339 nullptr) 3340 { 3341 LoadSubCommand("set", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointSet(interpreter))); 3342 LoadSubCommand("all", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointAll(interpreter))); 3343 } 3344 3345 ~CommandObjectRenderScriptRuntimeKernelBreakpoint() override = default; 3346 }; 3347 3348 class CommandObjectRenderScriptRuntimeKernel : public CommandObjectMultiword 3349 { 3350 public: 3351 CommandObjectRenderScriptRuntimeKernel(CommandInterpreter &interpreter) 3352 : CommandObjectMultiword(interpreter, "renderscript kernel", "Commands that deal with renderscript kernels.", 3353 NULL) 3354 { 3355 LoadSubCommand("list", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelList(interpreter))); 3356 LoadSubCommand("breakpoint", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpoint(interpreter))); 3357 } 3358 3359 ~CommandObjectRenderScriptRuntimeKernel() override = default; 3360 }; 3361 3362 class CommandObjectRenderScriptRuntimeContextDump : public CommandObjectParsed 3363 { 3364 public: 3365 CommandObjectRenderScriptRuntimeContextDump(CommandInterpreter &interpreter) 3366 : CommandObjectParsed(interpreter, "renderscript context dump", 3367 "Dumps renderscript context information.", "renderscript context dump", 3368 eCommandRequiresProcess | eCommandProcessMustBeLaunched) 3369 { 3370 } 3371 3372 ~CommandObjectRenderScriptRuntimeContextDump() override = default; 3373 3374 bool 3375 DoExecute(Args &command, CommandReturnObject &result) override 3376 { 3377 RenderScriptRuntime *runtime = 3378 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript); 3379 runtime->DumpContexts(result.GetOutputStream()); 3380 result.SetStatus(eReturnStatusSuccessFinishResult); 3381 return true; 3382 } 3383 }; 3384 3385 class CommandObjectRenderScriptRuntimeContext : public CommandObjectMultiword 3386 { 3387 public: 3388 CommandObjectRenderScriptRuntimeContext(CommandInterpreter &interpreter) 3389 : CommandObjectMultiword(interpreter, "renderscript context", "Commands that deal with renderscript contexts.", 3390 NULL) 3391 { 3392 LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeContextDump(interpreter))); 3393 } 3394 3395 ~CommandObjectRenderScriptRuntimeContext() override = default; 3396 }; 3397 3398 class CommandObjectRenderScriptRuntimeAllocationDump : public CommandObjectParsed 3399 { 3400 public: 3401 CommandObjectRenderScriptRuntimeAllocationDump(CommandInterpreter &interpreter) 3402 : CommandObjectParsed(interpreter, "renderscript allocation dump", 3403 "Displays the contents of a particular allocation", "renderscript allocation dump <ID>", 3404 eCommandRequiresProcess | eCommandProcessMustBeLaunched), m_options(interpreter) 3405 { 3406 } 3407 3408 ~CommandObjectRenderScriptRuntimeAllocationDump() override = default; 3409 3410 Options* 3411 GetOptions() override 3412 { 3413 return &m_options; 3414 } 3415 3416 class CommandOptions : public Options 3417 { 3418 public: 3419 CommandOptions(CommandInterpreter &interpreter) : Options(interpreter) 3420 { 3421 } 3422 3423 ~CommandOptions() override = default; 3424 3425 Error 3426 SetOptionValue(uint32_t option_idx, const char *option_arg) override 3427 { 3428 Error error; 3429 const int short_option = m_getopt_table[option_idx].val; 3430 3431 switch (short_option) 3432 { 3433 case 'f': 3434 m_outfile.SetFile(option_arg, true); 3435 if (m_outfile.Exists()) 3436 { 3437 m_outfile.Clear(); 3438 error.SetErrorStringWithFormat("file already exists: '%s'", option_arg); 3439 } 3440 break; 3441 default: 3442 error.SetErrorStringWithFormat("unrecognized option '%c'", short_option); 3443 break; 3444 } 3445 return error; 3446 } 3447 3448 void 3449 OptionParsingStarting() override 3450 { 3451 m_outfile.Clear(); 3452 } 3453 3454 const OptionDefinition* 3455 GetDefinitions() override 3456 { 3457 return g_option_table; 3458 } 3459 3460 static OptionDefinition g_option_table[]; 3461 FileSpec m_outfile; 3462 }; 3463 3464 bool 3465 DoExecute(Args &command, CommandReturnObject &result) override 3466 { 3467 const size_t argc = command.GetArgumentCount(); 3468 if (argc < 1) 3469 { 3470 result.AppendErrorWithFormat("'%s' takes 1 argument, an allocation ID. As well as an optional -f argument", 3471 m_cmd_name.c_str()); 3472 result.SetStatus(eReturnStatusFailed); 3473 return false; 3474 } 3475 3476 RenderScriptRuntime *runtime = 3477 static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript)); 3478 3479 const char* id_cstr = command.GetArgumentAtIndex(0); 3480 bool convert_complete = false; 3481 const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete); 3482 if (!convert_complete) 3483 { 3484 result.AppendErrorWithFormat("invalid allocation id argument '%s'", id_cstr); 3485 result.SetStatus(eReturnStatusFailed); 3486 return false; 3487 } 3488 3489 Stream* output_strm = nullptr; 3490 StreamFile outfile_stream; 3491 const FileSpec &outfile_spec = m_options.m_outfile; // Dump allocation to file instead 3492 if (outfile_spec) 3493 { 3494 // Open output file 3495 char path[256]; 3496 outfile_spec.GetPath(path, sizeof(path)); 3497 if (outfile_stream.GetFile().Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate).Success()) 3498 { 3499 output_strm = &outfile_stream; 3500 result.GetOutputStream().Printf("Results written to '%s'", path); 3501 result.GetOutputStream().EOL(); 3502 } 3503 else 3504 { 3505 result.AppendErrorWithFormat("Couldn't open file '%s'", path); 3506 result.SetStatus(eReturnStatusFailed); 3507 return false; 3508 } 3509 } 3510 else 3511 output_strm = &result.GetOutputStream(); 3512 3513 assert(output_strm != nullptr); 3514 bool success = runtime->DumpAllocation(*output_strm, m_exe_ctx.GetFramePtr(), id); 3515 3516 if (success) 3517 result.SetStatus(eReturnStatusSuccessFinishResult); 3518 else 3519 result.SetStatus(eReturnStatusFailed); 3520 3521 return true; 3522 } 3523 3524 private: 3525 CommandOptions m_options; 3526 }; 3527 3528 OptionDefinition 3529 CommandObjectRenderScriptRuntimeAllocationDump::CommandOptions::g_option_table[] = 3530 { 3531 { LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, 3532 "Print results to specified file instead of command line."}, 3533 { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL } 3534 }; 3535 3536 class CommandObjectRenderScriptRuntimeAllocationList : public CommandObjectParsed 3537 { 3538 public: 3539 CommandObjectRenderScriptRuntimeAllocationList(CommandInterpreter &interpreter) 3540 : CommandObjectParsed(interpreter, "renderscript allocation list", 3541 "List renderscript allocations and their information.", "renderscript allocation list", 3542 eCommandRequiresProcess | eCommandProcessMustBeLaunched), m_options(interpreter) 3543 { 3544 } 3545 3546 ~CommandObjectRenderScriptRuntimeAllocationList() override = default; 3547 3548 Options* 3549 GetOptions() override 3550 { 3551 return &m_options; 3552 } 3553 3554 class CommandOptions : public Options 3555 { 3556 public: 3557 CommandOptions(CommandInterpreter &interpreter) : Options(interpreter), m_refresh(false) 3558 { 3559 } 3560 3561 ~CommandOptions() override = default; 3562 3563 Error 3564 SetOptionValue(uint32_t option_idx, const char *option_arg) override 3565 { 3566 Error error; 3567 const int short_option = m_getopt_table[option_idx].val; 3568 3569 switch (short_option) 3570 { 3571 case 'r': 3572 m_refresh = true; 3573 break; 3574 default: 3575 error.SetErrorStringWithFormat("unrecognized option '%c'", short_option); 3576 break; 3577 } 3578 return error; 3579 } 3580 3581 void 3582 OptionParsingStarting() override 3583 { 3584 m_refresh = false; 3585 } 3586 3587 const OptionDefinition* 3588 GetDefinitions() override 3589 { 3590 return g_option_table; 3591 } 3592 3593 static OptionDefinition g_option_table[]; 3594 bool m_refresh; 3595 }; 3596 3597 bool 3598 DoExecute(Args &command, CommandReturnObject &result) override 3599 { 3600 RenderScriptRuntime *runtime = 3601 static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript)); 3602 runtime->ListAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr(), m_options.m_refresh); 3603 result.SetStatus(eReturnStatusSuccessFinishResult); 3604 return true; 3605 } 3606 3607 private: 3608 CommandOptions m_options; 3609 }; 3610 3611 OptionDefinition 3612 CommandObjectRenderScriptRuntimeAllocationList::CommandOptions::g_option_table[] = 3613 { 3614 { LLDB_OPT_SET_1, false, "refresh", 'r', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone, 3615 "Recompute allocation details."}, 3616 { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL } 3617 }; 3618 3619 class CommandObjectRenderScriptRuntimeAllocationLoad : public CommandObjectParsed 3620 { 3621 public: 3622 CommandObjectRenderScriptRuntimeAllocationLoad(CommandInterpreter &interpreter) 3623 : CommandObjectParsed(interpreter, "renderscript allocation load", 3624 "Loads renderscript allocation contents from a file.", "renderscript allocation load <ID> <filename>", 3625 eCommandRequiresProcess | eCommandProcessMustBeLaunched) 3626 { 3627 } 3628 3629 ~CommandObjectRenderScriptRuntimeAllocationLoad() override = default; 3630 3631 bool 3632 DoExecute(Args &command, CommandReturnObject &result) override 3633 { 3634 const size_t argc = command.GetArgumentCount(); 3635 if (argc != 2) 3636 { 3637 result.AppendErrorWithFormat("'%s' takes 2 arguments, an allocation ID and filename to read from.", m_cmd_name.c_str()); 3638 result.SetStatus(eReturnStatusFailed); 3639 return false; 3640 } 3641 3642 RenderScriptRuntime *runtime = 3643 static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript)); 3644 3645 const char* id_cstr = command.GetArgumentAtIndex(0); 3646 bool convert_complete = false; 3647 const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete); 3648 if (!convert_complete) 3649 { 3650 result.AppendErrorWithFormat ("invalid allocation id argument '%s'", id_cstr); 3651 result.SetStatus (eReturnStatusFailed); 3652 return false; 3653 } 3654 3655 const char* filename = command.GetArgumentAtIndex(1); 3656 bool success = runtime->LoadAllocation(result.GetOutputStream(), id, filename, m_exe_ctx.GetFramePtr()); 3657 3658 if (success) 3659 result.SetStatus(eReturnStatusSuccessFinishResult); 3660 else 3661 result.SetStatus(eReturnStatusFailed); 3662 3663 return true; 3664 } 3665 }; 3666 3667 class CommandObjectRenderScriptRuntimeAllocationSave : public CommandObjectParsed 3668 { 3669 public: 3670 CommandObjectRenderScriptRuntimeAllocationSave(CommandInterpreter &interpreter) 3671 : CommandObjectParsed(interpreter, "renderscript allocation save", 3672 "Write renderscript allocation contents to a file.", "renderscript allocation save <ID> <filename>", 3673 eCommandRequiresProcess | eCommandProcessMustBeLaunched) 3674 { 3675 } 3676 3677 ~CommandObjectRenderScriptRuntimeAllocationSave() override = default; 3678 3679 bool 3680 DoExecute(Args &command, CommandReturnObject &result) override 3681 { 3682 const size_t argc = command.GetArgumentCount(); 3683 if (argc != 2) 3684 { 3685 result.AppendErrorWithFormat("'%s' takes 2 arguments, an allocation ID and filename to read from.", m_cmd_name.c_str()); 3686 result.SetStatus(eReturnStatusFailed); 3687 return false; 3688 } 3689 3690 RenderScriptRuntime *runtime = 3691 static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript)); 3692 3693 const char* id_cstr = command.GetArgumentAtIndex(0); 3694 bool convert_complete = false; 3695 const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete); 3696 if (!convert_complete) 3697 { 3698 result.AppendErrorWithFormat ("invalid allocation id argument '%s'", id_cstr); 3699 result.SetStatus (eReturnStatusFailed); 3700 return false; 3701 } 3702 3703 const char* filename = command.GetArgumentAtIndex(1); 3704 bool success = runtime->SaveAllocation(result.GetOutputStream(), id, filename, m_exe_ctx.GetFramePtr()); 3705 3706 if (success) 3707 result.SetStatus(eReturnStatusSuccessFinishResult); 3708 else 3709 result.SetStatus(eReturnStatusFailed); 3710 3711 return true; 3712 } 3713 }; 3714 3715 class CommandObjectRenderScriptRuntimeAllocation : public CommandObjectMultiword 3716 { 3717 public: 3718 CommandObjectRenderScriptRuntimeAllocation(CommandInterpreter &interpreter) 3719 : CommandObjectMultiword(interpreter, "renderscript allocation", "Commands that deal with renderscript allocations.", 3720 NULL) 3721 { 3722 LoadSubCommand("list", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationList(interpreter))); 3723 LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationDump(interpreter))); 3724 LoadSubCommand("save", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationSave(interpreter))); 3725 LoadSubCommand("load", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationLoad(interpreter))); 3726 } 3727 3728 ~CommandObjectRenderScriptRuntimeAllocation() override = default; 3729 }; 3730 3731 class CommandObjectRenderScriptRuntimeStatus : public CommandObjectParsed 3732 { 3733 public: 3734 CommandObjectRenderScriptRuntimeStatus(CommandInterpreter &interpreter) 3735 : CommandObjectParsed(interpreter, "renderscript status", 3736 "Displays current renderscript runtime status.", "renderscript status", 3737 eCommandRequiresProcess | eCommandProcessMustBeLaunched) 3738 { 3739 } 3740 3741 ~CommandObjectRenderScriptRuntimeStatus() override = default; 3742 3743 bool 3744 DoExecute(Args &command, CommandReturnObject &result) override 3745 { 3746 RenderScriptRuntime *runtime = 3747 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript); 3748 runtime->Status(result.GetOutputStream()); 3749 result.SetStatus(eReturnStatusSuccessFinishResult); 3750 return true; 3751 } 3752 }; 3753 3754 class CommandObjectRenderScriptRuntime : public CommandObjectMultiword 3755 { 3756 public: 3757 CommandObjectRenderScriptRuntime(CommandInterpreter &interpreter) 3758 : CommandObjectMultiword(interpreter, "renderscript", "A set of commands for operating on renderscript.", 3759 "renderscript <subcommand> [<subcommand-options>]") 3760 { 3761 LoadSubCommand("module", CommandObjectSP(new CommandObjectRenderScriptRuntimeModule(interpreter))); 3762 LoadSubCommand("status", CommandObjectSP(new CommandObjectRenderScriptRuntimeStatus(interpreter))); 3763 LoadSubCommand("kernel", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernel(interpreter))); 3764 LoadSubCommand("context", CommandObjectSP(new CommandObjectRenderScriptRuntimeContext(interpreter))); 3765 LoadSubCommand("allocation", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocation(interpreter))); 3766 } 3767 3768 ~CommandObjectRenderScriptRuntime() override = default; 3769 }; 3770 3771 void 3772 RenderScriptRuntime::Initiate() 3773 { 3774 assert(!m_initiated); 3775 } 3776 3777 RenderScriptRuntime::RenderScriptRuntime(Process *process) 3778 : lldb_private::CPPLanguageRuntime(process), m_initiated(false), m_debuggerPresentFlagged(false), 3779 m_breakAllKernels(false) 3780 { 3781 ModulesDidLoad(process->GetTarget().GetImages()); 3782 } 3783 3784 lldb::CommandObjectSP 3785 RenderScriptRuntime::GetCommandObject(lldb_private::CommandInterpreter& interpreter) 3786 { 3787 static CommandObjectSP command_object; 3788 if(!command_object) 3789 { 3790 command_object.reset(new CommandObjectRenderScriptRuntime(interpreter)); 3791 } 3792 return command_object; 3793 } 3794 3795 RenderScriptRuntime::~RenderScriptRuntime() = default; 3796