15ec532a9SColin Riley //===-- RenderScriptRuntime.cpp ---------------------------------*- C++ -*-===//
25ec532a9SColin Riley //
35ec532a9SColin Riley //                     The LLVM Compiler Infrastructure
45ec532a9SColin Riley //
55ec532a9SColin Riley // This file is distributed under the University of Illinois Open Source
65ec532a9SColin Riley // License. See LICENSE.TXT for details.
75ec532a9SColin Riley //
85ec532a9SColin Riley //===----------------------------------------------------------------------===//
95ec532a9SColin Riley 
10*222b937cSEugene Zelenko // C Includes
11*222b937cSEugene Zelenko // C++ Includes
12*222b937cSEugene Zelenko // Other libraries and framework includes
13*222b937cSEugene Zelenko // Project includes
145ec532a9SColin Riley #include "RenderScriptRuntime.h"
155ec532a9SColin Riley 
165ec532a9SColin Riley #include "lldb/Core/ConstString.h"
175ec532a9SColin Riley #include "lldb/Core/Debugger.h"
185ec532a9SColin Riley #include "lldb/Core/Error.h"
195ec532a9SColin Riley #include "lldb/Core/Log.h"
205ec532a9SColin Riley #include "lldb/Core/PluginManager.h"
21018f5a7eSEwan Crawford #include "lldb/Core/RegularExpression.h"
22a0f08674SEwan Crawford #include "lldb/Host/StringConvert.h"
235ec532a9SColin Riley #include "lldb/Symbol/Symbol.h"
244640cde1SColin Riley #include "lldb/Symbol/Type.h"
255ec532a9SColin Riley #include "lldb/Target/Process.h"
265ec532a9SColin Riley #include "lldb/Target/Target.h"
27018f5a7eSEwan Crawford #include "lldb/Target/Thread.h"
285ec532a9SColin Riley #include "lldb/Interpreter/Args.h"
295ec532a9SColin Riley #include "lldb/Interpreter/Options.h"
305ec532a9SColin Riley #include "lldb/Interpreter/CommandInterpreter.h"
315ec532a9SColin Riley #include "lldb/Interpreter/CommandReturnObject.h"
325ec532a9SColin Riley #include "lldb/Interpreter/CommandObjectMultiword.h"
334640cde1SColin Riley #include "lldb/Breakpoint/StoppointCallbackContext.h"
344640cde1SColin Riley #include "lldb/Target/RegisterContext.h"
3515f2bd95SEwan Crawford #include "lldb/Expression/UserExpression.h"
364640cde1SColin Riley #include "lldb/Symbol/VariableList.h"
375ec532a9SColin Riley 
385ec532a9SColin Riley using namespace lldb;
395ec532a9SColin Riley using namespace lldb_private;
4098156583SEwan Crawford using namespace lldb_renderscript;
415ec532a9SColin Riley 
4278f339d1SEwan Crawford namespace {
4378f339d1SEwan Crawford 
4478f339d1SEwan Crawford // The empirical_type adds a basic level of validation to arbitrary data
4578f339d1SEwan Crawford // allowing us to track if data has been discovered and stored or not.
4678f339d1SEwan Crawford // An empirical_type will be marked as valid only if it has been explicitly assigned to.
4778f339d1SEwan Crawford template <typename type_t>
4878f339d1SEwan Crawford class empirical_type
4978f339d1SEwan Crawford {
5078f339d1SEwan Crawford public:
5178f339d1SEwan Crawford     // Ctor. Contents is invalid when constructed.
5278f339d1SEwan Crawford     empirical_type()
5378f339d1SEwan Crawford         : valid(false)
5478f339d1SEwan Crawford     {}
5578f339d1SEwan Crawford 
5678f339d1SEwan Crawford     // Return true and copy contents to out if valid, else return false.
5778f339d1SEwan Crawford     bool get(type_t& out) const
5878f339d1SEwan Crawford     {
5978f339d1SEwan Crawford         if (valid)
6078f339d1SEwan Crawford             out = data;
6178f339d1SEwan Crawford         return valid;
6278f339d1SEwan Crawford     }
6378f339d1SEwan Crawford 
6478f339d1SEwan Crawford     // Return a pointer to the contents or nullptr if it was not valid.
6578f339d1SEwan Crawford     const type_t* get() const
6678f339d1SEwan Crawford     {
6778f339d1SEwan Crawford         return valid ? &data : nullptr;
6878f339d1SEwan Crawford     }
6978f339d1SEwan Crawford 
7078f339d1SEwan Crawford     // Assign data explicitly.
7178f339d1SEwan Crawford     void set(const type_t in)
7278f339d1SEwan Crawford     {
7378f339d1SEwan Crawford         data = in;
7478f339d1SEwan Crawford         valid = true;
7578f339d1SEwan Crawford     }
7678f339d1SEwan Crawford 
7778f339d1SEwan Crawford     // Mark contents as invalid.
7878f339d1SEwan Crawford     void invalidate()
7978f339d1SEwan Crawford     {
8078f339d1SEwan Crawford         valid = false;
8178f339d1SEwan Crawford     }
8278f339d1SEwan Crawford 
8378f339d1SEwan Crawford     // Returns true if this type contains valid data.
8478f339d1SEwan Crawford     bool isValid() const
8578f339d1SEwan Crawford     {
8678f339d1SEwan Crawford         return valid;
8778f339d1SEwan Crawford     }
8878f339d1SEwan Crawford 
8978f339d1SEwan Crawford     // Assignment operator.
9078f339d1SEwan Crawford     empirical_type<type_t>& operator = (const type_t in)
9178f339d1SEwan Crawford     {
9278f339d1SEwan Crawford         set(in);
9378f339d1SEwan Crawford         return *this;
9478f339d1SEwan Crawford     }
9578f339d1SEwan Crawford 
9678f339d1SEwan Crawford     // Dereference operator returns contents.
9778f339d1SEwan Crawford     // Warning: Will assert if not valid so use only when you know data is valid.
9878f339d1SEwan Crawford     const type_t& operator * () const
9978f339d1SEwan Crawford     {
10078f339d1SEwan Crawford         assert(valid);
10178f339d1SEwan Crawford         return data;
10278f339d1SEwan Crawford     }
10378f339d1SEwan Crawford 
10478f339d1SEwan Crawford protected:
10578f339d1SEwan Crawford     bool valid;
10678f339d1SEwan Crawford     type_t data;
10778f339d1SEwan Crawford };
10878f339d1SEwan Crawford 
109*222b937cSEugene Zelenko } // anonymous namespace
11078f339d1SEwan Crawford 
11178f339d1SEwan Crawford // The ScriptDetails class collects data associated with a single script instance.
11278f339d1SEwan Crawford struct RenderScriptRuntime::ScriptDetails
11378f339d1SEwan Crawford {
114*222b937cSEugene Zelenko     ~ScriptDetails() = default;
11578f339d1SEwan Crawford 
11678f339d1SEwan Crawford     enum ScriptType
11778f339d1SEwan Crawford     {
11878f339d1SEwan Crawford         eScript,
11978f339d1SEwan Crawford         eScriptC
12078f339d1SEwan Crawford     };
12178f339d1SEwan Crawford 
12278f339d1SEwan Crawford     // The derived type of the script.
12378f339d1SEwan Crawford     empirical_type<ScriptType> type;
12478f339d1SEwan Crawford     // The name of the original source file.
12578f339d1SEwan Crawford     empirical_type<std::string> resName;
12678f339d1SEwan Crawford     // Path to script .so file on the device.
12778f339d1SEwan Crawford     empirical_type<std::string> scriptDyLib;
12878f339d1SEwan Crawford     // Directory where kernel objects are cached on device.
12978f339d1SEwan Crawford     empirical_type<std::string> cacheDir;
13078f339d1SEwan Crawford     // Pointer to the context which owns this script.
13178f339d1SEwan Crawford     empirical_type<lldb::addr_t> context;
13278f339d1SEwan Crawford     // Pointer to the script object itself.
13378f339d1SEwan Crawford     empirical_type<lldb::addr_t> script;
13478f339d1SEwan Crawford };
13578f339d1SEwan Crawford 
13678f339d1SEwan Crawford // This AllocationDetails class collects data associated with a single
13778f339d1SEwan Crawford // allocation instance.
13878f339d1SEwan Crawford struct RenderScriptRuntime::AllocationDetails
13978f339d1SEwan Crawford {
14015f2bd95SEwan Crawford    // Taken from rsDefines.h
14115f2bd95SEwan Crawford    enum DataKind
14215f2bd95SEwan Crawford    {
14315f2bd95SEwan Crawford        RS_KIND_USER,
14415f2bd95SEwan Crawford        RS_KIND_PIXEL_L = 7,
14515f2bd95SEwan Crawford        RS_KIND_PIXEL_A,
14615f2bd95SEwan Crawford        RS_KIND_PIXEL_LA,
14715f2bd95SEwan Crawford        RS_KIND_PIXEL_RGB,
14815f2bd95SEwan Crawford        RS_KIND_PIXEL_RGBA,
14915f2bd95SEwan Crawford        RS_KIND_PIXEL_DEPTH,
15015f2bd95SEwan Crawford        RS_KIND_PIXEL_YUV,
15115f2bd95SEwan Crawford        RS_KIND_INVALID = 100
15215f2bd95SEwan Crawford    };
15378f339d1SEwan Crawford 
15415f2bd95SEwan Crawford    // Taken from rsDefines.h
15578f339d1SEwan Crawford    enum DataType
15678f339d1SEwan Crawford    {
15715f2bd95SEwan Crawford        RS_TYPE_NONE = 0,
15815f2bd95SEwan Crawford        RS_TYPE_FLOAT_16,
15915f2bd95SEwan Crawford        RS_TYPE_FLOAT_32,
16015f2bd95SEwan Crawford        RS_TYPE_FLOAT_64,
16115f2bd95SEwan Crawford        RS_TYPE_SIGNED_8,
16215f2bd95SEwan Crawford        RS_TYPE_SIGNED_16,
16315f2bd95SEwan Crawford        RS_TYPE_SIGNED_32,
16415f2bd95SEwan Crawford        RS_TYPE_SIGNED_64,
16515f2bd95SEwan Crawford        RS_TYPE_UNSIGNED_8,
16615f2bd95SEwan Crawford        RS_TYPE_UNSIGNED_16,
16715f2bd95SEwan Crawford        RS_TYPE_UNSIGNED_32,
16815f2bd95SEwan Crawford        RS_TYPE_UNSIGNED_64,
16915f2bd95SEwan Crawford        RS_TYPE_BOOLEAN
17078f339d1SEwan Crawford     };
17178f339d1SEwan Crawford 
17215f2bd95SEwan Crawford     struct Dimension
17378f339d1SEwan Crawford     {
17415f2bd95SEwan Crawford         uint32_t dim_1;
17515f2bd95SEwan Crawford         uint32_t dim_2;
17615f2bd95SEwan Crawford         uint32_t dim_3;
17715f2bd95SEwan Crawford         uint32_t cubeMap;
17815f2bd95SEwan Crawford 
17915f2bd95SEwan Crawford         Dimension()
18015f2bd95SEwan Crawford         {
18115f2bd95SEwan Crawford              dim_1 = 0;
18215f2bd95SEwan Crawford              dim_2 = 0;
18315f2bd95SEwan Crawford              dim_3 = 0;
18415f2bd95SEwan Crawford              cubeMap = 0;
18515f2bd95SEwan Crawford         }
18678f339d1SEwan Crawford     };
18778f339d1SEwan Crawford 
18855232f09SEwan Crawford     // Header for reading and writing allocation contents
18955232f09SEwan Crawford     // to a binary file.
19055232f09SEwan Crawford     struct FileHeader
19155232f09SEwan Crawford     {
19255232f09SEwan Crawford         uint8_t ident[4];      // ASCII 'RSAD' identifying the file
19355232f09SEwan Crawford         uint16_t hdr_size;     // Header size in bytes, for backwards compatability
19455232f09SEwan Crawford         uint16_t type;         // DataType enum
19555232f09SEwan Crawford         uint32_t kind;         // DataKind enum
19655232f09SEwan Crawford         uint32_t dims[3];      // Dimensions
19755232f09SEwan Crawford         uint32_t element_size; // Size of a single element, including padding
19855232f09SEwan Crawford     };
19955232f09SEwan Crawford 
20015f2bd95SEwan Crawford     // Monotonically increasing from 1
20115f2bd95SEwan Crawford     static unsigned int ID;
20215f2bd95SEwan Crawford 
20315f2bd95SEwan Crawford     // Maps Allocation DataType enum and vector size to printable strings
20415f2bd95SEwan Crawford     // using mapping from RenderScript numerical types summary documentation
20515f2bd95SEwan Crawford     static const char* RsDataTypeToString[][4];
20615f2bd95SEwan Crawford 
20715f2bd95SEwan Crawford     // Maps Allocation DataKind enum to printable strings
20815f2bd95SEwan Crawford     static const char* RsDataKindToString[];
20915f2bd95SEwan Crawford 
210a0f08674SEwan Crawford     // Maps allocation types to format sizes for printing.
211a0f08674SEwan Crawford     static const unsigned int RSTypeToFormat[][3];
212a0f08674SEwan Crawford 
21315f2bd95SEwan Crawford     // Give each allocation an ID as a way
21415f2bd95SEwan Crawford     // for commands to reference it.
21515f2bd95SEwan Crawford     const unsigned int id;
21615f2bd95SEwan Crawford 
21715f2bd95SEwan Crawford     empirical_type<DataType> type;            // Type of each data pointer stored by the allocation
21815f2bd95SEwan Crawford     empirical_type<DataKind> type_kind;       // Defines pixel type if Allocation is created from an image
21915f2bd95SEwan Crawford     empirical_type<uint32_t> type_vec_size;   // Vector size of each data point, e.g '4' for uchar4
22015f2bd95SEwan Crawford     empirical_type<Dimension> dimension;      // Dimensions of the Allocation
22115f2bd95SEwan Crawford     empirical_type<lldb::addr_t> address;     // Pointer to address of the RS Allocation
22215f2bd95SEwan Crawford     empirical_type<lldb::addr_t> data_ptr;    // Pointer to the data held by the Allocation
22315f2bd95SEwan Crawford     empirical_type<lldb::addr_t> type_ptr;    // Pointer to the RS Type of the Allocation
22415f2bd95SEwan Crawford     empirical_type<lldb::addr_t> element_ptr; // Pointer to the RS Element of the Type
22515f2bd95SEwan Crawford     empirical_type<lldb::addr_t> context;     // Pointer to the RS Context of the Allocation
226a0f08674SEwan Crawford     empirical_type<uint32_t> size;            // Size of the allocation
227a0f08674SEwan Crawford     empirical_type<uint32_t> stride;          // Stride between rows of the allocation
22815f2bd95SEwan Crawford 
22915f2bd95SEwan Crawford     // Give each allocation an id, so we can reference it in user commands.
23015f2bd95SEwan Crawford     AllocationDetails(): id(ID++)
23115f2bd95SEwan Crawford     {
23215f2bd95SEwan Crawford     }
23315f2bd95SEwan Crawford };
23415f2bd95SEwan Crawford 
23515f2bd95SEwan Crawford unsigned int RenderScriptRuntime::AllocationDetails::ID = 1;
23615f2bd95SEwan Crawford 
23715f2bd95SEwan Crawford const char* RenderScriptRuntime::AllocationDetails::RsDataKindToString[] =
23815f2bd95SEwan Crawford {
23915f2bd95SEwan Crawford    "User",
24015f2bd95SEwan Crawford    "Undefined", "Undefined", "Undefined", // Enum jumps from 0 to 7
24115f2bd95SEwan Crawford    "Undefined", "Undefined", "Undefined",
24215f2bd95SEwan Crawford    "L Pixel",
24315f2bd95SEwan Crawford    "A Pixel",
24415f2bd95SEwan Crawford    "LA Pixel",
24515f2bd95SEwan Crawford    "RGB Pixel",
24615f2bd95SEwan Crawford    "RGBA Pixel",
24715f2bd95SEwan Crawford    "Pixel Depth",
24815f2bd95SEwan Crawford    "YUV Pixel"
24915f2bd95SEwan Crawford };
25015f2bd95SEwan Crawford 
25115f2bd95SEwan Crawford const char* RenderScriptRuntime::AllocationDetails::RsDataTypeToString[][4] =
25215f2bd95SEwan Crawford {
25315f2bd95SEwan Crawford     {"None", "None", "None", "None"},
25415f2bd95SEwan Crawford     {"half", "half2", "half3", "half4"},
25515f2bd95SEwan Crawford     {"float", "float2", "float3", "float4"},
25615f2bd95SEwan Crawford     {"double", "double2", "double3", "double4"},
25715f2bd95SEwan Crawford     {"char", "char2", "char3", "char4"},
25815f2bd95SEwan Crawford     {"short", "short2", "short3", "short4"},
25915f2bd95SEwan Crawford     {"int", "int2", "int3", "int4"},
26015f2bd95SEwan Crawford     {"long", "long2", "long3", "long4"},
26115f2bd95SEwan Crawford     {"uchar", "uchar2", "uchar3", "uchar4"},
26215f2bd95SEwan Crawford     {"ushort", "ushort2", "ushort3", "ushort4"},
26315f2bd95SEwan Crawford     {"uint", "uint2", "uint3", "uint4"},
26415f2bd95SEwan Crawford     {"ulong", "ulong2", "ulong3", "ulong4"},
26515f2bd95SEwan Crawford     {"bool", "bool2", "bool3", "bool4"}
26678f339d1SEwan Crawford };
26778f339d1SEwan Crawford 
268a0f08674SEwan Crawford // Used as an index into the RSTypeToFormat array elements
269a0f08674SEwan Crawford enum TypeToFormatIndex {
270a0f08674SEwan Crawford    eFormatSingle = 0,
271a0f08674SEwan Crawford    eFormatVector,
272a0f08674SEwan Crawford    eElementSize
273a0f08674SEwan Crawford };
274a0f08674SEwan Crawford 
275a0f08674SEwan Crawford // { format enum of single element, format enum of element vector, size of element}
276a0f08674SEwan Crawford const unsigned int RenderScriptRuntime::AllocationDetails::RSTypeToFormat[][3] =
277a0f08674SEwan Crawford {
278a0f08674SEwan Crawford     {eFormatHex, eFormatHex, 1}, // RS_TYPE_NONE
279a0f08674SEwan Crawford     {eFormatFloat, eFormatVectorOfFloat16, 2}, // RS_TYPE_FLOAT_16
280a0f08674SEwan Crawford     {eFormatFloat, eFormatVectorOfFloat32, sizeof(float)}, // RS_TYPE_FLOAT_32
281a0f08674SEwan Crawford     {eFormatFloat, eFormatVectorOfFloat64, sizeof(double)}, // RS_TYPE_FLOAT_64
282a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfSInt8, sizeof(int8_t)}, // RS_TYPE_SIGNED_8
283a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfSInt16, sizeof(int16_t)}, // RS_TYPE_SIGNED_16
284a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfSInt32, sizeof(int32_t)}, // RS_TYPE_SIGNED_32
285a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfSInt64, sizeof(int64_t)}, // RS_TYPE_SIGNED_64
286a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfUInt8, sizeof(uint8_t)}, // RS_TYPE_UNSIGNED_8
287a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfUInt16, sizeof(uint16_t)}, // RS_TYPE_UNSIGNED_16
288a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfUInt32, sizeof(uint32_t)}, // RS_TYPE_UNSIGNED_32
289a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfUInt64, sizeof(uint64_t)}, // RS_TYPE_UNSIGNED_64
290a0f08674SEwan Crawford     {eFormatBoolean, eFormatBoolean, sizeof(bool)} // RS_TYPE_BOOL
291a0f08674SEwan Crawford };
292a0f08674SEwan Crawford 
2935ec532a9SColin Riley //------------------------------------------------------------------
2945ec532a9SColin Riley // Static Functions
2955ec532a9SColin Riley //------------------------------------------------------------------
2965ec532a9SColin Riley LanguageRuntime *
2975ec532a9SColin Riley RenderScriptRuntime::CreateInstance(Process *process, lldb::LanguageType language)
2985ec532a9SColin Riley {
2995ec532a9SColin Riley 
3005ec532a9SColin Riley     if (language == eLanguageTypeExtRenderScript)
3015ec532a9SColin Riley         return new RenderScriptRuntime(process);
3025ec532a9SColin Riley     else
3035ec532a9SColin Riley         return NULL;
3045ec532a9SColin Riley }
3055ec532a9SColin Riley 
30698156583SEwan Crawford // Callback with a module to search for matching symbols.
30798156583SEwan Crawford // We first check that the module contains RS kernels.
30898156583SEwan Crawford // Then look for a symbol which matches our kernel name.
30998156583SEwan Crawford // The breakpoint address is finally set using the address of this symbol.
31098156583SEwan Crawford Searcher::CallbackReturn
31198156583SEwan Crawford RSBreakpointResolver::SearchCallback(SearchFilter &filter,
31298156583SEwan Crawford                                      SymbolContext &context,
31398156583SEwan Crawford                                      Address*,
31498156583SEwan Crawford                                      bool)
31598156583SEwan Crawford {
31698156583SEwan Crawford     ModuleSP module = context.module_sp;
31798156583SEwan Crawford 
31898156583SEwan Crawford     if (!module)
31998156583SEwan Crawford         return Searcher::eCallbackReturnContinue;
32098156583SEwan Crawford 
32198156583SEwan Crawford     // Is this a module containing renderscript kernels?
32298156583SEwan Crawford     if (nullptr == module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData))
32398156583SEwan Crawford         return Searcher::eCallbackReturnContinue;
32498156583SEwan Crawford 
32598156583SEwan Crawford     // Attempt to set a breakpoint on the kernel name symbol within the module library.
32698156583SEwan Crawford     // If it's not found, it's likely debug info is unavailable - try to set a
32798156583SEwan Crawford     // breakpoint on <name>.expand.
32898156583SEwan Crawford 
32998156583SEwan Crawford     const Symbol* kernel_sym = module->FindFirstSymbolWithNameAndType(m_kernel_name, eSymbolTypeCode);
33098156583SEwan Crawford     if (!kernel_sym)
33198156583SEwan Crawford     {
33298156583SEwan Crawford         std::string kernel_name_expanded(m_kernel_name.AsCString());
33398156583SEwan Crawford         kernel_name_expanded.append(".expand");
33498156583SEwan Crawford         kernel_sym = module->FindFirstSymbolWithNameAndType(ConstString(kernel_name_expanded.c_str()), eSymbolTypeCode);
33598156583SEwan Crawford     }
33698156583SEwan Crawford 
33798156583SEwan Crawford     if (kernel_sym)
33898156583SEwan Crawford     {
33998156583SEwan Crawford         Address bp_addr = kernel_sym->GetAddress();
34098156583SEwan Crawford         if (filter.AddressPasses(bp_addr))
34198156583SEwan Crawford             m_breakpoint->AddLocation(bp_addr);
34298156583SEwan Crawford     }
34398156583SEwan Crawford 
34498156583SEwan Crawford     return Searcher::eCallbackReturnContinue;
34598156583SEwan Crawford }
34698156583SEwan Crawford 
3475ec532a9SColin Riley void
3485ec532a9SColin Riley RenderScriptRuntime::Initialize()
3495ec532a9SColin Riley {
3504640cde1SColin Riley     PluginManager::RegisterPlugin(GetPluginNameStatic(), "RenderScript language support", CreateInstance, GetCommandObject);
3515ec532a9SColin Riley }
3525ec532a9SColin Riley 
3535ec532a9SColin Riley void
3545ec532a9SColin Riley RenderScriptRuntime::Terminate()
3555ec532a9SColin Riley {
3565ec532a9SColin Riley     PluginManager::UnregisterPlugin(CreateInstance);
3575ec532a9SColin Riley }
3585ec532a9SColin Riley 
3595ec532a9SColin Riley lldb_private::ConstString
3605ec532a9SColin Riley RenderScriptRuntime::GetPluginNameStatic()
3615ec532a9SColin Riley {
3625ec532a9SColin Riley     static ConstString g_name("renderscript");
3635ec532a9SColin Riley     return g_name;
3645ec532a9SColin Riley }
3655ec532a9SColin Riley 
366ef20b08fSColin Riley RenderScriptRuntime::ModuleKind
367ef20b08fSColin Riley RenderScriptRuntime::GetModuleKind(const lldb::ModuleSP &module_sp)
368ef20b08fSColin Riley {
369ef20b08fSColin Riley     if (module_sp)
370ef20b08fSColin Riley     {
371ef20b08fSColin Riley         // Is this a module containing renderscript kernels?
372ef20b08fSColin Riley         const Symbol *info_sym = module_sp->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData);
373ef20b08fSColin Riley         if (info_sym)
374ef20b08fSColin Riley         {
375ef20b08fSColin Riley             return eModuleKindKernelObj;
376ef20b08fSColin Riley         }
3774640cde1SColin Riley 
3784640cde1SColin Riley         // Is this the main RS runtime library
3794640cde1SColin Riley         const ConstString rs_lib("libRS.so");
3804640cde1SColin Riley         if (module_sp->GetFileSpec().GetFilename() == rs_lib)
3814640cde1SColin Riley         {
3824640cde1SColin Riley             return eModuleKindLibRS;
3834640cde1SColin Riley         }
3844640cde1SColin Riley 
3854640cde1SColin Riley         const ConstString rs_driverlib("libRSDriver.so");
3864640cde1SColin Riley         if (module_sp->GetFileSpec().GetFilename() == rs_driverlib)
3874640cde1SColin Riley         {
3884640cde1SColin Riley             return eModuleKindDriver;
3894640cde1SColin Riley         }
3904640cde1SColin Riley 
39115f2bd95SEwan Crawford         const ConstString rs_cpureflib("libRSCpuRef.so");
3924640cde1SColin Riley         if (module_sp->GetFileSpec().GetFilename() == rs_cpureflib)
3934640cde1SColin Riley         {
3944640cde1SColin Riley             return eModuleKindImpl;
3954640cde1SColin Riley         }
3964640cde1SColin Riley 
397ef20b08fSColin Riley     }
398ef20b08fSColin Riley     return eModuleKindIgnored;
399ef20b08fSColin Riley }
400ef20b08fSColin Riley 
401ef20b08fSColin Riley bool
402ef20b08fSColin Riley RenderScriptRuntime::IsRenderScriptModule(const lldb::ModuleSP &module_sp)
403ef20b08fSColin Riley {
404ef20b08fSColin Riley     return GetModuleKind(module_sp) != eModuleKindIgnored;
405ef20b08fSColin Riley }
406ef20b08fSColin Riley 
407ef20b08fSColin Riley void
408ef20b08fSColin Riley RenderScriptRuntime::ModulesDidLoad(const ModuleList &module_list )
409ef20b08fSColin Riley {
410ef20b08fSColin Riley     Mutex::Locker locker (module_list.GetMutex ());
411ef20b08fSColin Riley 
412ef20b08fSColin Riley     size_t num_modules = module_list.GetSize();
413ef20b08fSColin Riley     for (size_t i = 0; i < num_modules; i++)
414ef20b08fSColin Riley     {
415ef20b08fSColin Riley         auto mod = module_list.GetModuleAtIndex (i);
416ef20b08fSColin Riley         if (IsRenderScriptModule (mod))
417ef20b08fSColin Riley         {
418ef20b08fSColin Riley             LoadModule(mod);
419ef20b08fSColin Riley         }
420ef20b08fSColin Riley     }
421ef20b08fSColin Riley }
422ef20b08fSColin Riley 
4235ec532a9SColin Riley //------------------------------------------------------------------
4245ec532a9SColin Riley // PluginInterface protocol
4255ec532a9SColin Riley //------------------------------------------------------------------
4265ec532a9SColin Riley lldb_private::ConstString
4275ec532a9SColin Riley RenderScriptRuntime::GetPluginName()
4285ec532a9SColin Riley {
4295ec532a9SColin Riley     return GetPluginNameStatic();
4305ec532a9SColin Riley }
4315ec532a9SColin Riley 
4325ec532a9SColin Riley uint32_t
4335ec532a9SColin Riley RenderScriptRuntime::GetPluginVersion()
4345ec532a9SColin Riley {
4355ec532a9SColin Riley     return 1;
4365ec532a9SColin Riley }
4375ec532a9SColin Riley 
4385ec532a9SColin Riley bool
4395ec532a9SColin Riley RenderScriptRuntime::IsVTableName(const char *name)
4405ec532a9SColin Riley {
4415ec532a9SColin Riley     return false;
4425ec532a9SColin Riley }
4435ec532a9SColin Riley 
4445ec532a9SColin Riley bool
4455ec532a9SColin Riley RenderScriptRuntime::GetDynamicTypeAndAddress(ValueObject &in_value, lldb::DynamicValueType use_dynamic,
4460b6003f3SEnrico Granata                                               TypeAndOrName &class_type_or_name, Address &address,
4470b6003f3SEnrico Granata                                               Value::ValueType &value_type)
4485ec532a9SColin Riley {
4495ec532a9SColin Riley     return false;
4505ec532a9SColin Riley }
4515ec532a9SColin Riley 
452c74275bcSEnrico Granata TypeAndOrName
453c74275bcSEnrico Granata RenderScriptRuntime::FixUpDynamicType (const TypeAndOrName& type_and_or_name,
4547eed4877SEnrico Granata                                        ValueObject& static_value)
455c74275bcSEnrico Granata {
456c74275bcSEnrico Granata     return type_and_or_name;
457c74275bcSEnrico Granata }
458c74275bcSEnrico Granata 
4595ec532a9SColin Riley bool
4605ec532a9SColin Riley RenderScriptRuntime::CouldHaveDynamicValue(ValueObject &in_value)
4615ec532a9SColin Riley {
4625ec532a9SColin Riley     return false;
4635ec532a9SColin Riley }
4645ec532a9SColin Riley 
4655ec532a9SColin Riley lldb::BreakpointResolverSP
4665ec532a9SColin Riley RenderScriptRuntime::CreateExceptionResolver(Breakpoint *bkpt, bool catch_bp, bool throw_bp)
4675ec532a9SColin Riley {
4685ec532a9SColin Riley     BreakpointResolverSP resolver_sp;
4695ec532a9SColin Riley     return resolver_sp;
4705ec532a9SColin Riley }
4715ec532a9SColin Riley 
4724640cde1SColin Riley const RenderScriptRuntime::HookDefn RenderScriptRuntime::s_runtimeHookDefns[] =
4734640cde1SColin Riley {
4744640cde1SColin Riley     //rsdScript
47582780287SAidan Dodds     {
47682780287SAidan Dodds         "rsdScriptInit", //name
47782780287SAidan Dodds         "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_7ScriptCEPKcS7_PKhjj", // symbol name 32 bit
47882780287SAidan Dodds         "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_7ScriptCEPKcS7_PKhmj", // symbol name 64 bit
47982780287SAidan Dodds         0, // version
48082780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
48182780287SAidan Dodds         &lldb_private::RenderScriptRuntime::CaptureScriptInit1 // handler
48282780287SAidan Dodds     },
48382780287SAidan Dodds     {
48482780287SAidan Dodds         "rsdScriptInvokeForEach", // name
48582780287SAidan Dodds         "_Z22rsdScriptInvokeForEachPKN7android12renderscript7ContextEPNS0_6ScriptEjPKNS0_10AllocationEPS6_PKvjPK12RsScriptCall", // symbol name 32bit
48682780287SAidan Dodds         "_Z22rsdScriptInvokeForEachPKN7android12renderscript7ContextEPNS0_6ScriptEjPKNS0_10AllocationEPS6_PKvmPK12RsScriptCall", // symbol name 64bit
48782780287SAidan Dodds         0, // version
48882780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
48982780287SAidan Dodds         nullptr // handler
49082780287SAidan Dodds     },
49182780287SAidan Dodds     {
49282780287SAidan Dodds         "rsdScriptInvokeForEachMulti", // name
49382780287SAidan Dodds         "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0_6ScriptEjPPKNS0_10AllocationEjPS6_PKvjPK12RsScriptCall", // symbol name 32bit
49482780287SAidan Dodds         "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0_6ScriptEjPPKNS0_10AllocationEmPS6_PKvmPK12RsScriptCall", // symbol name 64bit
49582780287SAidan Dodds         0, // version
49682780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
49782780287SAidan Dodds         nullptr // handler
49882780287SAidan Dodds     },
49982780287SAidan Dodds     {
50082780287SAidan Dodds         "rsdScriptInvokeFunction", // name
50182780287SAidan Dodds         "_Z23rsdScriptInvokeFunctionPKN7android12renderscript7ContextEPNS0_6ScriptEjPKvj", // symbol name 32bit
50282780287SAidan Dodds         "_Z23rsdScriptInvokeFunctionPKN7android12renderscript7ContextEPNS0_6ScriptEjPKvm", // symbol name 64bit
50382780287SAidan Dodds         0, // version
50482780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
50582780287SAidan Dodds         nullptr // handler
50682780287SAidan Dodds     },
50782780287SAidan Dodds     {
50882780287SAidan Dodds         "rsdScriptSetGlobalVar", // name
50982780287SAidan Dodds         "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_6ScriptEjPvj", // symbol name 32bit
51082780287SAidan Dodds         "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_6ScriptEjPvm", // symbol name 64bit
51182780287SAidan Dodds         0, // version
51282780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
51382780287SAidan Dodds         &lldb_private::RenderScriptRuntime::CaptureSetGlobalVar1 // handler
51482780287SAidan Dodds     },
5154640cde1SColin Riley 
5164640cde1SColin Riley     //rsdAllocation
51782780287SAidan Dodds     {
51882780287SAidan Dodds         "rsdAllocationInit", // name
51982780287SAidan Dodds         "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_10AllocationEb", // symbol name 32bit
52082780287SAidan Dodds         "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_10AllocationEb", // symbol name 64bit
52182780287SAidan Dodds         0, // version
52282780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
52382780287SAidan Dodds         &lldb_private::RenderScriptRuntime::CaptureAllocationInit1 // handler
52482780287SAidan Dodds     },
52582780287SAidan Dodds     {
52682780287SAidan Dodds         "rsdAllocationRead2D", //name
52782780287SAidan Dodds         "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_10AllocationEjjj23RsAllocationCubemapFacejjPvjj", // symbol name 32bit
52882780287SAidan Dodds         "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_10AllocationEjjj23RsAllocationCubemapFacejjPvmm", // symbol name 64bit
52982780287SAidan Dodds         0, // version
53082780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
53182780287SAidan Dodds         nullptr // handler
53282780287SAidan Dodds     },
5334640cde1SColin Riley };
5344640cde1SColin Riley 
535*222b937cSEugene Zelenko const size_t RenderScriptRuntime::s_runtimeHookCount = sizeof(s_runtimeHookDefns)/sizeof(s_runtimeHookDefns[0]);
5364640cde1SColin Riley 
5374640cde1SColin Riley bool
5384640cde1SColin Riley RenderScriptRuntime::HookCallback(void *baton, StoppointCallbackContext *ctx, lldb::user_id_t break_id, lldb::user_id_t break_loc_id)
5394640cde1SColin Riley {
5404640cde1SColin Riley     RuntimeHook* hook_info = (RuntimeHook*)baton;
5414640cde1SColin Riley     ExecutionContext context(ctx->exe_ctx_ref);
5424640cde1SColin Riley 
5434640cde1SColin Riley     RenderScriptRuntime *lang_rt = (RenderScriptRuntime *)context.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
5444640cde1SColin Riley 
5454640cde1SColin Riley     lang_rt->HookCallback(hook_info, context);
5464640cde1SColin Riley 
5474640cde1SColin Riley     return false;
5484640cde1SColin Riley }
5494640cde1SColin Riley 
5504640cde1SColin Riley void
5514640cde1SColin Riley RenderScriptRuntime::HookCallback(RuntimeHook* hook_info, ExecutionContext& context)
5524640cde1SColin Riley {
5534640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
5544640cde1SColin Riley 
5554640cde1SColin Riley     if (log)
5564640cde1SColin Riley         log->Printf ("RenderScriptRuntime::HookCallback - '%s' .", hook_info->defn->name);
5574640cde1SColin Riley 
5584640cde1SColin Riley     if (hook_info->defn->grabber)
5594640cde1SColin Riley     {
5604640cde1SColin Riley         (this->*(hook_info->defn->grabber))(hook_info, context);
5614640cde1SColin Riley     }
5624640cde1SColin Riley }
5634640cde1SColin Riley 
5644640cde1SColin Riley bool
56582780287SAidan Dodds RenderScriptRuntime::GetArgSimple(ExecutionContext &context, uint32_t arg, uint64_t *data)
5664640cde1SColin Riley {
5674640cde1SColin Riley     if (!data)
5684640cde1SColin Riley         return false;
5694640cde1SColin Riley 
57082780287SAidan Dodds     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
5714640cde1SColin Riley     Error error;
5724640cde1SColin Riley     RegisterContext* reg_ctx = context.GetRegisterContext();
5734640cde1SColin Riley     Process* process = context.GetProcessPtr();
57482780287SAidan Dodds     bool success = false; // return value
5754640cde1SColin Riley 
57682780287SAidan Dodds     if (!context.GetTargetPtr())
57782780287SAidan Dodds     {
57882780287SAidan Dodds         if (log)
57982780287SAidan Dodds             log->Printf("RenderScriptRuntime::GetArgSimple - Invalid target");
58082780287SAidan Dodds 
58182780287SAidan Dodds         return false;
58282780287SAidan Dodds     }
58382780287SAidan Dodds 
58482780287SAidan Dodds     switch (context.GetTargetPtr()->GetArchitecture().GetMachine())
58582780287SAidan Dodds     {
58682780287SAidan Dodds         case llvm::Triple::ArchType::x86:
5874640cde1SColin Riley         {
5884640cde1SColin Riley             uint64_t sp = reg_ctx->GetSP();
5894640cde1SColin Riley             uint32_t offset = (1 + arg) * sizeof(uint32_t);
59082780287SAidan Dodds             uint32_t result = 0;
59182780287SAidan Dodds             process->ReadMemory(sp + offset, &result, sizeof(uint32_t), error);
5924640cde1SColin Riley             if (error.Fail())
5934640cde1SColin Riley             {
5944640cde1SColin Riley                 if (log)
59582780287SAidan Dodds                     log->Printf ("RenderScriptRuntime:: GetArgSimple - error reading X86 stack: %s.", error.AsCString());
5964640cde1SColin Riley             }
59782780287SAidan Dodds             else
5984640cde1SColin Riley             {
59982780287SAidan Dodds                 *data = result;
60082780287SAidan Dodds                 success = true;
60182780287SAidan Dodds             }
60282780287SAidan Dodds 
60382780287SAidan Dodds             break;
60482780287SAidan Dodds         }
60582780287SAidan Dodds         case llvm::Triple::ArchType::arm:
60682780287SAidan Dodds         {
60782780287SAidan Dodds             // arm 32 bit
6084640cde1SColin Riley             if (arg < 4)
6094640cde1SColin Riley             {
6104640cde1SColin Riley                 const RegisterInfo* rArg = reg_ctx->GetRegisterInfoAtIndex(arg);
6114640cde1SColin Riley                 RegisterValue rVal;
61202f1c5d1SEwan Crawford                 success = reg_ctx->ReadRegister(rArg, rVal);
61302f1c5d1SEwan Crawford                 if (success)
61402f1c5d1SEwan Crawford                 {
6154640cde1SColin Riley                     (*data) = rVal.GetAsUInt32();
61602f1c5d1SEwan Crawford                 }
61702f1c5d1SEwan Crawford                 else
61802f1c5d1SEwan Crawford                 {
61902f1c5d1SEwan Crawford                     if (log)
62002f1c5d1SEwan Crawford                         log->Printf ("RenderScriptRuntime:: GetArgSimple - error reading ARM register: %d.", arg);
62102f1c5d1SEwan Crawford                 }
6224640cde1SColin Riley             }
6234640cde1SColin Riley             else
6244640cde1SColin Riley             {
6254640cde1SColin Riley                 uint64_t sp = reg_ctx->GetSP();
6264640cde1SColin Riley                 uint32_t offset = (arg-4) * sizeof(uint32_t);
6274640cde1SColin Riley                 process->ReadMemory(sp + offset, &data, sizeof(uint32_t), error);
6284640cde1SColin Riley                 if (error.Fail())
6294640cde1SColin Riley                 {
6304640cde1SColin Riley                     if (log)
63182780287SAidan Dodds                         log->Printf ("RenderScriptRuntime:: GetArgSimple - error reading ARM stack: %s.", error.AsCString());
63282780287SAidan Dodds                 }
63382780287SAidan Dodds                 else
63482780287SAidan Dodds                 {
63582780287SAidan Dodds                     success = true;
6364640cde1SColin Riley                 }
6374640cde1SColin Riley             }
63882780287SAidan Dodds 
63982780287SAidan Dodds             break;
6404640cde1SColin Riley         }
64182780287SAidan Dodds         case llvm::Triple::ArchType::aarch64:
64282780287SAidan Dodds         {
64382780287SAidan Dodds             // arm 64 bit
64482780287SAidan Dodds             // first 8 arguments are in the registers
64582780287SAidan Dodds             if (arg < 8)
64682780287SAidan Dodds             {
64782780287SAidan Dodds                 const RegisterInfo* rArg = reg_ctx->GetRegisterInfoAtIndex(arg);
64882780287SAidan Dodds                 RegisterValue rVal;
64982780287SAidan Dodds                 success = reg_ctx->ReadRegister(rArg, rVal);
65082780287SAidan Dodds                 if (success)
65182780287SAidan Dodds                 {
65282780287SAidan Dodds                     *data = rVal.GetAsUInt64();
65382780287SAidan Dodds                 }
65482780287SAidan Dodds                 else
65582780287SAidan Dodds                 {
65682780287SAidan Dodds                     if (log)
65782780287SAidan Dodds                         log->Printf("RenderScriptRuntime::GetArgSimple() - AARCH64 - Error while reading the argument #%d", arg);
65882780287SAidan Dodds                 }
65982780287SAidan Dodds             }
66082780287SAidan Dodds             else
66182780287SAidan Dodds             {
66282780287SAidan Dodds                 // @TODO: need to find the argument in the stack
66382780287SAidan Dodds                 if (log)
66482780287SAidan Dodds                     log->Printf("RenderScriptRuntime::GetArgSimple - AARCH64 - FOR #ARG >= 8 NOT IMPLEMENTED YET. Argument number: %d", arg);
66582780287SAidan Dodds             }
66682780287SAidan Dodds             break;
66782780287SAidan Dodds         }
66802f1c5d1SEwan Crawford         case llvm::Triple::ArchType::mips64el:
66902f1c5d1SEwan Crawford         {
67002f1c5d1SEwan Crawford             // read from the registers
67102f1c5d1SEwan Crawford             if (arg < 8)
67202f1c5d1SEwan Crawford             {
67302f1c5d1SEwan Crawford                 const RegisterInfo* rArg = reg_ctx->GetRegisterInfoAtIndex(arg + 4);
67402f1c5d1SEwan Crawford                 RegisterValue rVal;
67502f1c5d1SEwan Crawford                 success = reg_ctx->ReadRegister(rArg, rVal);
67602f1c5d1SEwan Crawford                 if (success)
67702f1c5d1SEwan Crawford                 {
67802f1c5d1SEwan Crawford                     (*data) = rVal.GetAsUInt64();
67902f1c5d1SEwan Crawford                 }
68002f1c5d1SEwan Crawford                 else
68102f1c5d1SEwan Crawford                 {
68202f1c5d1SEwan Crawford                     if (log)
68302f1c5d1SEwan Crawford                         log->Printf("RenderScriptRuntime::GetArgSimple - Mips64 - Error reading the argument #%d", arg);
68402f1c5d1SEwan Crawford                 }
68502f1c5d1SEwan Crawford             }
68602f1c5d1SEwan Crawford 
68702f1c5d1SEwan Crawford             // read from the stack
68802f1c5d1SEwan Crawford             else
68902f1c5d1SEwan Crawford             {
69002f1c5d1SEwan Crawford                 uint64_t sp = reg_ctx->GetSP();
69102f1c5d1SEwan Crawford                 uint32_t offset = (arg - 8) * sizeof(uint64_t);
69202f1c5d1SEwan Crawford                 process->ReadMemory(sp + offset, &data, sizeof(uint64_t), error);
69302f1c5d1SEwan Crawford                 if (error.Fail())
69402f1c5d1SEwan Crawford                 {
69502f1c5d1SEwan Crawford                     if (log)
69602f1c5d1SEwan Crawford                         log->Printf ("RenderScriptRuntime::GetArgSimple - Mips64 - Error reading Mips64 stack: %s.", error.AsCString());
69702f1c5d1SEwan Crawford                 }
69802f1c5d1SEwan Crawford                 else
69902f1c5d1SEwan Crawford                 {
70002f1c5d1SEwan Crawford                     success = true;
70102f1c5d1SEwan Crawford                 }
70202f1c5d1SEwan Crawford             }
70302f1c5d1SEwan Crawford 
70402f1c5d1SEwan Crawford             break;
70502f1c5d1SEwan Crawford         }
70682780287SAidan Dodds         default:
70782780287SAidan Dodds         {
70882780287SAidan Dodds             // invalid architecture
70982780287SAidan Dodds             if (log)
71082780287SAidan Dodds                 log->Printf("RenderScriptRuntime::GetArgSimple - Architecture not supported");
71182780287SAidan Dodds 
71282780287SAidan Dodds         }
71382780287SAidan Dodds     }
71482780287SAidan Dodds 
71582780287SAidan Dodds     return success;
7164640cde1SColin Riley }
7174640cde1SColin Riley 
7184640cde1SColin Riley void
7194640cde1SColin Riley RenderScriptRuntime::CaptureSetGlobalVar1(RuntimeHook* hook_info, ExecutionContext& context)
7204640cde1SColin Riley {
7214640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
7224640cde1SColin Riley 
7234640cde1SColin Riley     //Context, Script, int, data, length
7244640cde1SColin Riley 
72582780287SAidan Dodds     uint64_t rs_context_u64 = 0U;
72682780287SAidan Dodds     uint64_t rs_script_u64 = 0U;
72782780287SAidan Dodds     uint64_t rs_id_u64 = 0U;
72882780287SAidan Dodds     uint64_t rs_data_u64 = 0U;
72982780287SAidan Dodds     uint64_t rs_length_u64 = 0U;
7304640cde1SColin Riley 
73182780287SAidan Dodds     bool success =
73282780287SAidan Dodds         GetArgSimple(context, 0, &rs_context_u64) &&
73382780287SAidan Dodds         GetArgSimple(context, 1, &rs_script_u64) &&
73482780287SAidan Dodds         GetArgSimple(context, 2, &rs_id_u64) &&
73582780287SAidan Dodds         GetArgSimple(context, 3, &rs_data_u64) &&
73682780287SAidan Dodds         GetArgSimple(context, 4, &rs_length_u64);
7374640cde1SColin Riley 
73882780287SAidan Dodds     if (!success)
73982780287SAidan Dodds     {
74082780287SAidan Dodds         if (log)
74182780287SAidan Dodds             log->Printf("RenderScriptRuntime::CaptureSetGlobalVar1 - Error while reading the function parameters");
74282780287SAidan Dodds         return;
74382780287SAidan Dodds     }
7444640cde1SColin Riley 
7454640cde1SColin Riley     if (log)
7464640cde1SColin Riley     {
7474640cde1SColin Riley         log->Printf ("RenderScriptRuntime::CaptureSetGlobalVar1 - 0x%" PRIx64 ",0x%" PRIx64 " slot %" PRIu64 " = 0x%" PRIx64 ":%" PRIu64 "bytes.",
74882780287SAidan Dodds                         rs_context_u64, rs_script_u64, rs_id_u64, rs_data_u64, rs_length_u64);
7494640cde1SColin Riley 
75082780287SAidan Dodds         addr_t script_addr =  (addr_t)rs_script_u64;
7514640cde1SColin Riley         if (m_scriptMappings.find( script_addr ) != m_scriptMappings.end())
7524640cde1SColin Riley         {
7534640cde1SColin Riley             auto rsm = m_scriptMappings[script_addr];
75482780287SAidan Dodds             if (rs_id_u64 < rsm->m_globals.size())
7554640cde1SColin Riley             {
75682780287SAidan Dodds                 auto rsg = rsm->m_globals[rs_id_u64];
7574640cde1SColin Riley                 log->Printf ("RenderScriptRuntime::CaptureSetGlobalVar1 - Setting of '%s' within '%s' inferred", rsg.m_name.AsCString(),
7584640cde1SColin Riley                                 rsm->m_module->GetFileSpec().GetFilename().AsCString());
7594640cde1SColin Riley             }
7604640cde1SColin Riley         }
7614640cde1SColin Riley     }
7624640cde1SColin Riley }
7634640cde1SColin Riley 
7644640cde1SColin Riley void
7654640cde1SColin Riley RenderScriptRuntime::CaptureAllocationInit1(RuntimeHook* hook_info, ExecutionContext& context)
7664640cde1SColin Riley {
7674640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
7684640cde1SColin Riley 
7694640cde1SColin Riley     //Context, Alloc, bool
7704640cde1SColin Riley 
77182780287SAidan Dodds     uint64_t rs_context_u64 = 0U;
77282780287SAidan Dodds     uint64_t rs_alloc_u64 = 0U;
77382780287SAidan Dodds     uint64_t rs_forceZero_u64 = 0U;
7744640cde1SColin Riley 
77582780287SAidan Dodds     bool success =
77682780287SAidan Dodds         GetArgSimple(context, 0, &rs_context_u64) &&
77782780287SAidan Dodds         GetArgSimple(context, 1, &rs_alloc_u64) &&
77882780287SAidan Dodds         GetArgSimple(context, 2, &rs_forceZero_u64);
77982780287SAidan Dodds     if (!success) // error case
78082780287SAidan Dodds     {
78182780287SAidan Dodds         if (log)
78282780287SAidan Dodds             log->Printf("RenderScriptRuntime::CaptureAllocationInit1 - Error while reading the function parameters");
78382780287SAidan Dodds         return; // abort
78482780287SAidan Dodds     }
7854640cde1SColin Riley 
7864640cde1SColin Riley     if (log)
7874640cde1SColin Riley         log->Printf ("RenderScriptRuntime::CaptureAllocationInit1 - 0x%" PRIx64 ",0x%" PRIx64 ",0x%" PRIx64 " .",
78882780287SAidan Dodds                         rs_context_u64, rs_alloc_u64, rs_forceZero_u64);
78978f339d1SEwan Crawford 
79078f339d1SEwan Crawford     AllocationDetails* alloc = LookUpAllocation(rs_alloc_u64, true);
79178f339d1SEwan Crawford     if (alloc)
79278f339d1SEwan Crawford         alloc->context = rs_context_u64;
7934640cde1SColin Riley }
7944640cde1SColin Riley 
7954640cde1SColin Riley void
7964640cde1SColin Riley RenderScriptRuntime::CaptureScriptInit1(RuntimeHook* hook_info, ExecutionContext& context)
7974640cde1SColin Riley {
7984640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
7994640cde1SColin Riley 
8004640cde1SColin Riley     //Context, Script, resname Str, cachedir Str
8014640cde1SColin Riley     Error error;
8024640cde1SColin Riley     Process* process = context.GetProcessPtr();
8034640cde1SColin Riley 
80482780287SAidan Dodds     uint64_t rs_context_u64 = 0U;
80582780287SAidan Dodds     uint64_t rs_script_u64 = 0U;
80682780287SAidan Dodds     uint64_t rs_resnameptr_u64 = 0U;
80782780287SAidan Dodds     uint64_t rs_cachedirptr_u64 = 0U;
8084640cde1SColin Riley 
8094640cde1SColin Riley     std::string resname;
8104640cde1SColin Riley     std::string cachedir;
8114640cde1SColin Riley 
81282780287SAidan Dodds     // read the function parameters
81382780287SAidan Dodds     bool success =
81482780287SAidan Dodds         GetArgSimple(context, 0, &rs_context_u64) &&
81582780287SAidan Dodds         GetArgSimple(context, 1, &rs_script_u64) &&
81682780287SAidan Dodds         GetArgSimple(context, 2, &rs_resnameptr_u64) &&
81782780287SAidan Dodds         GetArgSimple(context, 3, &rs_cachedirptr_u64);
8184640cde1SColin Riley 
81982780287SAidan Dodds     if (!success)
82082780287SAidan Dodds     {
82182780287SAidan Dodds         if (log)
82282780287SAidan Dodds             log->Printf("RenderScriptRuntime::CaptureScriptInit1 - Error while reading the function parameters");
82382780287SAidan Dodds         return;
82482780287SAidan Dodds     }
82582780287SAidan Dodds 
82682780287SAidan Dodds     process->ReadCStringFromMemory((lldb::addr_t)rs_resnameptr_u64, resname, error);
8274640cde1SColin Riley     if (error.Fail())
8284640cde1SColin Riley     {
8294640cde1SColin Riley         if (log)
8304640cde1SColin Riley             log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - error reading resname: %s.", error.AsCString());
8314640cde1SColin Riley 
8324640cde1SColin Riley     }
8334640cde1SColin Riley 
83482780287SAidan Dodds     process->ReadCStringFromMemory((lldb::addr_t)rs_cachedirptr_u64, cachedir, error);
8354640cde1SColin Riley     if (error.Fail())
8364640cde1SColin Riley     {
8374640cde1SColin Riley         if (log)
8384640cde1SColin Riley             log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - error reading cachedir: %s.", error.AsCString());
8394640cde1SColin Riley     }
8404640cde1SColin Riley 
8414640cde1SColin Riley     if (log)
8424640cde1SColin Riley         log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - 0x%" PRIx64 ",0x%" PRIx64 " => '%s' at '%s' .",
84382780287SAidan Dodds                      rs_context_u64, rs_script_u64, resname.c_str(), cachedir.c_str());
8444640cde1SColin Riley 
8454640cde1SColin Riley     if (resname.size() > 0)
8464640cde1SColin Riley     {
8474640cde1SColin Riley         StreamString strm;
8484640cde1SColin Riley         strm.Printf("librs.%s.so", resname.c_str());
8494640cde1SColin Riley 
85078f339d1SEwan Crawford         ScriptDetails* script = LookUpScript(rs_script_u64, true);
85178f339d1SEwan Crawford         if (script)
85278f339d1SEwan Crawford         {
85378f339d1SEwan Crawford             script->type = ScriptDetails::eScriptC;
85478f339d1SEwan Crawford             script->cacheDir = cachedir;
85578f339d1SEwan Crawford             script->resName = resname;
85678f339d1SEwan Crawford             script->scriptDyLib = strm.GetData();
85778f339d1SEwan Crawford             script->context = addr_t(rs_context_u64);
85878f339d1SEwan Crawford         }
8594640cde1SColin Riley 
8604640cde1SColin Riley         if (log)
8614640cde1SColin Riley             log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - '%s' tagged with context 0x%" PRIx64 " and script 0x%" PRIx64 ".",
86282780287SAidan Dodds                          strm.GetData(), rs_context_u64, rs_script_u64);
8634640cde1SColin Riley     }
8644640cde1SColin Riley     else if (log)
8654640cde1SColin Riley     {
8664640cde1SColin Riley         log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - resource name invalid, Script not tagged");
8674640cde1SColin Riley     }
8684640cde1SColin Riley }
8694640cde1SColin Riley 
8704640cde1SColin Riley void
8714640cde1SColin Riley RenderScriptRuntime::LoadRuntimeHooks(lldb::ModuleSP module, ModuleKind kind)
8724640cde1SColin Riley {
8734640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
8744640cde1SColin Riley 
8754640cde1SColin Riley     if (!module)
8764640cde1SColin Riley     {
8774640cde1SColin Riley         return;
8784640cde1SColin Riley     }
8794640cde1SColin Riley 
88082780287SAidan Dodds     Target &target = GetProcess()->GetTarget();
88182780287SAidan Dodds     llvm::Triple::ArchType targetArchType = target.GetArchitecture().GetMachine();
88282780287SAidan Dodds 
88382780287SAidan Dodds     if (targetArchType != llvm::Triple::ArchType::x86
88482780287SAidan Dodds         && targetArchType != llvm::Triple::ArchType::arm
88502f1c5d1SEwan Crawford         && targetArchType != llvm::Triple::ArchType::aarch64
88602f1c5d1SEwan Crawford         && targetArchType != llvm::Triple::ArchType::mips64el
88702f1c5d1SEwan Crawford     )
8884640cde1SColin Riley     {
8894640cde1SColin Riley         if (log)
89002f1c5d1SEwan Crawford             log->Printf ("RenderScriptRuntime::LoadRuntimeHooks - Unable to hook runtime. Only X86, ARM, Mips64 supported currently.");
8914640cde1SColin Riley 
8924640cde1SColin Riley         return;
8934640cde1SColin Riley     }
8944640cde1SColin Riley 
89582780287SAidan Dodds     uint32_t archByteSize = target.GetArchitecture().GetAddressByteSize();
8964640cde1SColin Riley 
8974640cde1SColin Riley     for (size_t idx = 0; idx < s_runtimeHookCount; idx++)
8984640cde1SColin Riley     {
8994640cde1SColin Riley         const HookDefn* hook_defn = &s_runtimeHookDefns[idx];
9004640cde1SColin Riley         if (hook_defn->kind != kind) {
9014640cde1SColin Riley             continue;
9024640cde1SColin Riley         }
9034640cde1SColin Riley 
90482780287SAidan Dodds         const char* symbol_name = (archByteSize == 4) ? hook_defn->symbol_name_m32 : hook_defn->symbol_name_m64;
90582780287SAidan Dodds 
90682780287SAidan Dodds         const Symbol *sym = module->FindFirstSymbolWithNameAndType(ConstString(symbol_name), eSymbolTypeCode);
90782780287SAidan Dodds         if (!sym){
90882780287SAidan Dodds             if (log){
90982780287SAidan Dodds                 log->Printf("RenderScriptRuntime::LoadRuntimeHooks - ERROR: Symbol '%s' related to the function %s not found", symbol_name, hook_defn->name);
91082780287SAidan Dodds             }
91182780287SAidan Dodds             continue;
91282780287SAidan Dodds         }
9134640cde1SColin Riley 
914358cf1eaSGreg Clayton         addr_t addr = sym->GetLoadAddress(&target);
9154640cde1SColin Riley         if (addr == LLDB_INVALID_ADDRESS)
9164640cde1SColin Riley         {
9174640cde1SColin Riley             if (log)
9184640cde1SColin Riley                 log->Printf ("RenderScriptRuntime::LoadRuntimeHooks - Unable to resolve the address of hook function '%s' with symbol '%s'.",
91982780287SAidan Dodds                              hook_defn->name, symbol_name);
9204640cde1SColin Riley             continue;
9214640cde1SColin Riley         }
92282780287SAidan Dodds         else
92382780287SAidan Dodds         {
92482780287SAidan Dodds             if (log)
92582780287SAidan Dodds                 log->Printf("RenderScriptRuntime::LoadRuntimeHooks - Function %s, address resolved at 0x%" PRIx64, hook_defn->name, addr);
92682780287SAidan Dodds         }
9274640cde1SColin Riley 
9284640cde1SColin Riley         RuntimeHookSP hook(new RuntimeHook());
9294640cde1SColin Riley         hook->address = addr;
9304640cde1SColin Riley         hook->defn = hook_defn;
9314640cde1SColin Riley         hook->bp_sp = target.CreateBreakpoint(addr, true, false);
9324640cde1SColin Riley         hook->bp_sp->SetCallback(HookCallback, hook.get(), true);
9334640cde1SColin Riley         m_runtimeHooks[addr] = hook;
9344640cde1SColin Riley         if (log)
9354640cde1SColin Riley         {
9364640cde1SColin Riley             log->Printf ("RenderScriptRuntime::LoadRuntimeHooks - Successfully hooked '%s' in '%s' version %" PRIu64 " at 0x%" PRIx64 ".",
9374640cde1SColin Riley                 hook_defn->name, module->GetFileSpec().GetFilename().AsCString(), (uint64_t)hook_defn->version, (uint64_t)addr);
9384640cde1SColin Riley         }
9394640cde1SColin Riley     }
9404640cde1SColin Riley }
9414640cde1SColin Riley 
9424640cde1SColin Riley void
9434640cde1SColin Riley RenderScriptRuntime::FixupScriptDetails(RSModuleDescriptorSP rsmodule_sp)
9444640cde1SColin Riley {
9454640cde1SColin Riley     if (!rsmodule_sp)
9464640cde1SColin Riley         return;
9474640cde1SColin Riley 
9484640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
9494640cde1SColin Riley 
9504640cde1SColin Riley     const ModuleSP module = rsmodule_sp->m_module;
9514640cde1SColin Riley     const FileSpec& file = module->GetPlatformFileSpec();
9524640cde1SColin Riley 
95378f339d1SEwan Crawford     // Iterate over all of the scripts that we currently know of.
95478f339d1SEwan Crawford     // Note: We cant push or pop to m_scripts here or it may invalidate rs_script.
9554640cde1SColin Riley     for (const auto & rs_script : m_scripts)
9564640cde1SColin Riley     {
95778f339d1SEwan Crawford         // Extract the expected .so file path for this script.
95878f339d1SEwan Crawford         std::string dylib;
95978f339d1SEwan Crawford         if (!rs_script->scriptDyLib.get(dylib))
96078f339d1SEwan Crawford             continue;
96178f339d1SEwan Crawford 
96278f339d1SEwan Crawford         // Only proceed if the module that has loaded corresponds to this script.
96378f339d1SEwan Crawford         if (file.GetFilename() != ConstString(dylib.c_str()))
96478f339d1SEwan Crawford             continue;
96578f339d1SEwan Crawford 
96678f339d1SEwan Crawford         // Obtain the script address which we use as a key.
96778f339d1SEwan Crawford         lldb::addr_t script;
96878f339d1SEwan Crawford         if (!rs_script->script.get(script))
96978f339d1SEwan Crawford             continue;
97078f339d1SEwan Crawford 
97178f339d1SEwan Crawford         // If we have a script mapping for the current script.
97278f339d1SEwan Crawford         if (m_scriptMappings.find(script) != m_scriptMappings.end())
9734640cde1SColin Riley         {
97478f339d1SEwan Crawford             // if the module we have stored is different to the one we just received.
97578f339d1SEwan Crawford             if (m_scriptMappings[script] != rsmodule_sp)
9764640cde1SColin Riley             {
9774640cde1SColin Riley                 if (log)
9784640cde1SColin Riley                     log->Printf ("RenderScriptRuntime::FixupScriptDetails - Error: script %" PRIx64 " wants reassigned to new rsmodule '%s'.",
97978f339d1SEwan Crawford                                     (uint64_t)script, rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
9804640cde1SColin Riley             }
9814640cde1SColin Riley         }
98278f339d1SEwan Crawford         // We don't have a script mapping for the current script.
9834640cde1SColin Riley         else
9844640cde1SColin Riley         {
98578f339d1SEwan Crawford             // Obtain the script resource name.
98678f339d1SEwan Crawford             std::string resName;
98778f339d1SEwan Crawford             if (rs_script->resName.get(resName))
98878f339d1SEwan Crawford                 // Set the modules resource name.
98978f339d1SEwan Crawford                 rsmodule_sp->m_resname = resName;
99078f339d1SEwan Crawford             // Add Script/Module pair to map.
99178f339d1SEwan Crawford             m_scriptMappings[script] = rsmodule_sp;
9924640cde1SColin Riley             if (log)
9934640cde1SColin Riley                 log->Printf ("RenderScriptRuntime::FixupScriptDetails - script %" PRIx64 " associated with rsmodule '%s'.",
99478f339d1SEwan Crawford                                 (uint64_t)script, rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
9954640cde1SColin Riley         }
9964640cde1SColin Riley     }
9974640cde1SColin Riley }
9984640cde1SColin Riley 
99915f2bd95SEwan Crawford // Uses the Target API to evaluate the expression passed as a parameter to the function
100015f2bd95SEwan Crawford // The result of that expression is returned an unsigned 64 bit int, via the result* paramter.
100115f2bd95SEwan Crawford // Function returns true on success, and false on failure
100215f2bd95SEwan Crawford bool
100315f2bd95SEwan Crawford RenderScriptRuntime::EvalRSExpression(const char* expression, StackFrame* frame_ptr, uint64_t* result)
100415f2bd95SEwan Crawford {
100515f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
100615f2bd95SEwan Crawford     if (log)
100715f2bd95SEwan Crawford         log->Printf("RenderScriptRuntime::EvalRSExpression(%s)", expression);
100815f2bd95SEwan Crawford 
100915f2bd95SEwan Crawford     ValueObjectSP expr_result;
101015f2bd95SEwan Crawford     // Perform the actual expression evaluation
101115f2bd95SEwan Crawford     GetProcess()->GetTarget().EvaluateExpression(expression, frame_ptr, expr_result);
101215f2bd95SEwan Crawford 
101315f2bd95SEwan Crawford     if (!expr_result)
101415f2bd95SEwan Crawford     {
101515f2bd95SEwan Crawford        if (log)
101615f2bd95SEwan Crawford            log->Printf("RenderScriptRuntime::EvalRSExpression -  Error: Couldn't evaluate expression");
101715f2bd95SEwan Crawford        return false;
101815f2bd95SEwan Crawford     }
101915f2bd95SEwan Crawford 
102015f2bd95SEwan Crawford     // The result of the expression is invalid
102115f2bd95SEwan Crawford     if (!expr_result->GetError().Success())
102215f2bd95SEwan Crawford     {
102315f2bd95SEwan Crawford         Error err = expr_result->GetError();
102415f2bd95SEwan Crawford         if (err.GetError() == UserExpression::kNoResult) // Expression returned void, so this is actually a success
102515f2bd95SEwan Crawford         {
102615f2bd95SEwan Crawford             if (log)
102715f2bd95SEwan Crawford                 log->Printf("RenderScriptRuntime::EvalRSExpression - Expression returned void");
102815f2bd95SEwan Crawford 
102915f2bd95SEwan Crawford             result = nullptr;
103015f2bd95SEwan Crawford             return true;
103115f2bd95SEwan Crawford         }
103215f2bd95SEwan Crawford 
103315f2bd95SEwan Crawford         if (log)
103415f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::EvalRSExpression - Error evaluating expression result: %s", err.AsCString());
103515f2bd95SEwan Crawford         return false;
103615f2bd95SEwan Crawford     }
103715f2bd95SEwan Crawford 
103815f2bd95SEwan Crawford     bool success = false;
103915f2bd95SEwan Crawford     *result = expr_result->GetValueAsUnsigned(0, &success); // We only read the result as an unsigned int.
104015f2bd95SEwan Crawford 
104115f2bd95SEwan Crawford     if (!success)
104215f2bd95SEwan Crawford     {
104315f2bd95SEwan Crawford        if (log)
104415f2bd95SEwan Crawford            log->Printf("RenderScriptRuntime::EvalRSExpression -  Error: Couldn't convert expression result to unsigned int");
104515f2bd95SEwan Crawford        return false;
104615f2bd95SEwan Crawford     }
104715f2bd95SEwan Crawford 
104815f2bd95SEwan Crawford     return true;
104915f2bd95SEwan Crawford }
105015f2bd95SEwan Crawford 
105115f2bd95SEwan Crawford // Used to index expression format strings
105215f2bd95SEwan Crawford enum ExpressionStrings
105315f2bd95SEwan Crawford {
105415f2bd95SEwan Crawford    eExprGetOffsetPtr = 0,
105515f2bd95SEwan Crawford    eExprAllocGetType,
105615f2bd95SEwan Crawford    eExprTypeDimX,
105715f2bd95SEwan Crawford    eExprTypeDimY,
105815f2bd95SEwan Crawford    eExprTypeDimZ,
105915f2bd95SEwan Crawford    eExprTypeElemPtr,
106015f2bd95SEwan Crawford    eExprElementType,
106115f2bd95SEwan Crawford    eExprElementKind,
106215f2bd95SEwan Crawford    eExprElementVec
106315f2bd95SEwan Crawford };
106415f2bd95SEwan Crawford 
106515f2bd95SEwan Crawford // Format strings containing the expressions we may need to evaluate.
106615f2bd95SEwan Crawford const char runtimeExpressions[][256] =
106715f2bd95SEwan Crawford {
106815f2bd95SEwan Crawford  // Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap)
106915f2bd95SEwan Crawford  "(int*)_Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocationCubemapFace(0x%lx, %u, %u, %u, 0, 0)",
107015f2bd95SEwan Crawford 
107115f2bd95SEwan Crawford  // Type* rsaAllocationGetType(Context*, Allocation*)
107215f2bd95SEwan Crawford  "(void*)rsaAllocationGetType(0x%lx, 0x%lx)",
107315f2bd95SEwan Crawford 
107415f2bd95SEwan Crawford  // rsaTypeGetNativeData(Context*, Type*, void* typeData, size)
107515f2bd95SEwan Crawford  // Pack the data in the following way mHal.state.dimX; mHal.state.dimY; mHal.state.dimZ;
107615f2bd95SEwan Crawford  // mHal.state.lodCount; mHal.state.faces; mElement; into typeData
107715f2bd95SEwan Crawford  // Need to specify 32 or 64 bit for uint_t since this differs between devices
107815f2bd95SEwan Crawford  "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[0]", // X dim
107915f2bd95SEwan Crawford  "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[1]", // Y dim
108015f2bd95SEwan Crawford  "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[2]", // Z dim
108115f2bd95SEwan Crawford  "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[5]", // Element ptr
108215f2bd95SEwan Crawford 
108315f2bd95SEwan Crawford  // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size)
108415f2bd95SEwan Crawford  // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into elemData
108515f2bd95SEwan Crawford  "uint32_t data[6]; (void*)rsaElementGetNativeData(0x%lx, 0x%lx, data, 5); data[0]", // Type
108615f2bd95SEwan Crawford  "uint32_t data[6]; (void*)rsaElementGetNativeData(0x%lx, 0x%lx, data, 5); data[1]", // Kind
108715f2bd95SEwan Crawford  "uint32_t data[6]; (void*)rsaElementGetNativeData(0x%lx, 0x%lx, data, 5); data[3]"  // Vector Size
108815f2bd95SEwan Crawford };
108915f2bd95SEwan Crawford 
109015f2bd95SEwan Crawford // JITs the RS runtime for the internal data pointer of an allocation.
109115f2bd95SEwan Crawford // Is passed x,y,z coordinates for the pointer to a specific element.
109215f2bd95SEwan Crawford // Then sets the data_ptr member in Allocation with the result.
109315f2bd95SEwan Crawford // Returns true on success, false otherwise
109415f2bd95SEwan Crawford bool
109515f2bd95SEwan Crawford RenderScriptRuntime::JITDataPointer(AllocationDetails* allocation, StackFrame* frame_ptr,
109615f2bd95SEwan Crawford                                     unsigned int x, unsigned int y, unsigned int z)
109715f2bd95SEwan Crawford {
109815f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
109915f2bd95SEwan Crawford 
110015f2bd95SEwan Crawford     if (!allocation->address.isValid())
110115f2bd95SEwan Crawford     {
110215f2bd95SEwan Crawford         if (log)
110315f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITDataPointer - Failed to find allocation details");
110415f2bd95SEwan Crawford         return false;
110515f2bd95SEwan Crawford     }
110615f2bd95SEwan Crawford 
110715f2bd95SEwan Crawford     const char* expr_cstr = runtimeExpressions[eExprGetOffsetPtr];
110815f2bd95SEwan Crawford     const int max_expr_size = 512; // Max expression size
110915f2bd95SEwan Crawford     char buffer[max_expr_size];
111015f2bd95SEwan Crawford 
111115f2bd95SEwan Crawford     int chars_written = snprintf(buffer, max_expr_size, expr_cstr, *allocation->address.get(), x, y, z);
111215f2bd95SEwan Crawford     if (chars_written < 0)
111315f2bd95SEwan Crawford     {
111415f2bd95SEwan Crawford         if (log)
111515f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITDataPointer - Encoding error in snprintf()");
111615f2bd95SEwan Crawford         return false;
111715f2bd95SEwan Crawford     }
111815f2bd95SEwan Crawford     else if (chars_written >= max_expr_size)
111915f2bd95SEwan Crawford     {
112015f2bd95SEwan Crawford         if (log)
112115f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITDataPointer - Expression too long");
112215f2bd95SEwan Crawford         return false;
112315f2bd95SEwan Crawford     }
112415f2bd95SEwan Crawford 
112515f2bd95SEwan Crawford     uint64_t result = 0;
112615f2bd95SEwan Crawford     if (!EvalRSExpression(buffer, frame_ptr, &result))
112715f2bd95SEwan Crawford         return false;
112815f2bd95SEwan Crawford 
112915f2bd95SEwan Crawford     addr_t mem_ptr = static_cast<lldb::addr_t>(result);
113015f2bd95SEwan Crawford     allocation->data_ptr = mem_ptr;
113115f2bd95SEwan Crawford 
113215f2bd95SEwan Crawford     return true;
113315f2bd95SEwan Crawford }
113415f2bd95SEwan Crawford 
113515f2bd95SEwan Crawford // JITs the RS runtime for the internal pointer to the RS Type of an allocation
113615f2bd95SEwan Crawford // Then sets the type_ptr member in Allocation with the result.
113715f2bd95SEwan Crawford // Returns true on success, false otherwise
113815f2bd95SEwan Crawford bool
113915f2bd95SEwan Crawford RenderScriptRuntime::JITTypePointer(AllocationDetails* allocation, StackFrame* frame_ptr)
114015f2bd95SEwan Crawford {
114115f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
114215f2bd95SEwan Crawford 
114315f2bd95SEwan Crawford     if (!allocation->address.isValid() || !allocation->context.isValid())
114415f2bd95SEwan Crawford     {
114515f2bd95SEwan Crawford         if (log)
114615f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITTypePointer - Failed to find allocation details");
114715f2bd95SEwan Crawford         return false;
114815f2bd95SEwan Crawford     }
114915f2bd95SEwan Crawford 
115015f2bd95SEwan Crawford     const char* expr_cstr = runtimeExpressions[eExprAllocGetType];
115115f2bd95SEwan Crawford     const int max_expr_size = 512; // Max expression size
115215f2bd95SEwan Crawford     char buffer[max_expr_size];
115315f2bd95SEwan Crawford 
115415f2bd95SEwan Crawford     int chars_written = snprintf(buffer, max_expr_size, expr_cstr, *allocation->context.get(), *allocation->address.get());
115515f2bd95SEwan Crawford     if (chars_written < 0)
115615f2bd95SEwan Crawford     {
115715f2bd95SEwan Crawford         if (log)
115815f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITDataPointer - Encoding error in snprintf()");
115915f2bd95SEwan Crawford         return false;
116015f2bd95SEwan Crawford     }
116115f2bd95SEwan Crawford     else if (chars_written >= max_expr_size)
116215f2bd95SEwan Crawford     {
116315f2bd95SEwan Crawford         if (log)
116415f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITTypePointer - Expression too long");
116515f2bd95SEwan Crawford         return false;
116615f2bd95SEwan Crawford     }
116715f2bd95SEwan Crawford 
116815f2bd95SEwan Crawford     uint64_t result = 0;
116915f2bd95SEwan Crawford     if (!EvalRSExpression(buffer, frame_ptr, &result))
117015f2bd95SEwan Crawford         return false;
117115f2bd95SEwan Crawford 
117215f2bd95SEwan Crawford     addr_t type_ptr = static_cast<lldb::addr_t>(result);
117315f2bd95SEwan Crawford     allocation->type_ptr = type_ptr;
117415f2bd95SEwan Crawford 
117515f2bd95SEwan Crawford     return true;
117615f2bd95SEwan Crawford }
117715f2bd95SEwan Crawford 
117815f2bd95SEwan Crawford // JITs the RS runtime for information about the dimensions and type of an allocation
117915f2bd95SEwan Crawford // Then sets dimension and element_ptr members in Allocation with the result.
118015f2bd95SEwan Crawford // Returns true on success, false otherwise
118115f2bd95SEwan Crawford bool
118215f2bd95SEwan Crawford RenderScriptRuntime::JITTypePacked(AllocationDetails* allocation, StackFrame* frame_ptr)
118315f2bd95SEwan Crawford {
118415f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
118515f2bd95SEwan Crawford 
118615f2bd95SEwan Crawford     if (!allocation->type_ptr.isValid() || !allocation->context.isValid())
118715f2bd95SEwan Crawford     {
118815f2bd95SEwan Crawford         if (log)
118915f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITTypePacked - Failed to find allocation details");
119015f2bd95SEwan Crawford         return false;
119115f2bd95SEwan Crawford     }
119215f2bd95SEwan Crawford 
119315f2bd95SEwan Crawford     // Expression is different depending on if device is 32 or 64 bit
119415f2bd95SEwan Crawford     uint32_t archByteSize = GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
119515f2bd95SEwan Crawford     const unsigned int bits = archByteSize == 4 ? 32 : 64;
119615f2bd95SEwan Crawford 
119715f2bd95SEwan Crawford     // We want 4 elements from packed data
119815f2bd95SEwan Crawford     const unsigned int num_exprs = 4;
119915f2bd95SEwan Crawford     assert(num_exprs == (eExprTypeElemPtr - eExprTypeDimX + 1) && "Invalid number of expressions");
120015f2bd95SEwan Crawford 
120115f2bd95SEwan Crawford     const int max_expr_size = 512; // Max expression size
120215f2bd95SEwan Crawford     char buffer[num_exprs][max_expr_size];
120315f2bd95SEwan Crawford     uint64_t results[num_exprs];
120415f2bd95SEwan Crawford 
120515f2bd95SEwan Crawford     for (unsigned int i = 0; i < num_exprs; ++i)
120615f2bd95SEwan Crawford     {
120715f2bd95SEwan Crawford         int chars_written = snprintf(buffer[i], max_expr_size, runtimeExpressions[eExprTypeDimX + i], bits,
120815f2bd95SEwan Crawford                                      *allocation->context.get(), *allocation->type_ptr.get());
120915f2bd95SEwan Crawford         if (chars_written < 0)
121015f2bd95SEwan Crawford         {
121115f2bd95SEwan Crawford             if (log)
121215f2bd95SEwan Crawford                 log->Printf("RenderScriptRuntime::JITDataPointer - Encoding error in snprintf()");
121315f2bd95SEwan Crawford             return false;
121415f2bd95SEwan Crawford         }
121515f2bd95SEwan Crawford         else if (chars_written >= max_expr_size)
121615f2bd95SEwan Crawford         {
121715f2bd95SEwan Crawford             if (log)
121815f2bd95SEwan Crawford                 log->Printf("RenderScriptRuntime::JITTypePacked - Expression too long");
121915f2bd95SEwan Crawford             return false;
122015f2bd95SEwan Crawford         }
122115f2bd95SEwan Crawford 
122215f2bd95SEwan Crawford         // Perform expression evaluation
122315f2bd95SEwan Crawford         if (!EvalRSExpression(buffer[i], frame_ptr, &results[i]))
122415f2bd95SEwan Crawford             return false;
122515f2bd95SEwan Crawford     }
122615f2bd95SEwan Crawford 
122715f2bd95SEwan Crawford     // Assign results to allocation members
122815f2bd95SEwan Crawford     AllocationDetails::Dimension dims;
122915f2bd95SEwan Crawford     dims.dim_1 = static_cast<uint32_t>(results[0]);
123015f2bd95SEwan Crawford     dims.dim_2 = static_cast<uint32_t>(results[1]);
123115f2bd95SEwan Crawford     dims.dim_3 = static_cast<uint32_t>(results[2]);
123215f2bd95SEwan Crawford     allocation->dimension = dims;
123315f2bd95SEwan Crawford 
123415f2bd95SEwan Crawford     addr_t elem_ptr = static_cast<lldb::addr_t>(results[3]);
123515f2bd95SEwan Crawford     allocation->element_ptr = elem_ptr;
123615f2bd95SEwan Crawford 
123715f2bd95SEwan Crawford     if (log)
123815f2bd95SEwan Crawford         log->Printf("RenderScriptRuntime::JITTypePacked - dims (%u, %u, %u) Element*: 0x%" PRIx64,
123915f2bd95SEwan Crawford                     dims.dim_1, dims.dim_2, dims.dim_3, elem_ptr);
124015f2bd95SEwan Crawford 
124115f2bd95SEwan Crawford     return true;
124215f2bd95SEwan Crawford }
124315f2bd95SEwan Crawford 
124415f2bd95SEwan Crawford // JITs the RS runtime for information about the Element of an allocation
124515f2bd95SEwan Crawford // Then sets type, type_vec_size, and type_kind members in Allocation with the result.
124615f2bd95SEwan Crawford // Returns true on success, false otherwise
124715f2bd95SEwan Crawford bool
124815f2bd95SEwan Crawford RenderScriptRuntime::JITElementPacked(AllocationDetails* allocation, StackFrame* frame_ptr)
124915f2bd95SEwan Crawford {
125015f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
125115f2bd95SEwan Crawford 
125215f2bd95SEwan Crawford     if (!allocation->element_ptr.isValid() || !allocation->context.isValid())
125315f2bd95SEwan Crawford     {
125415f2bd95SEwan Crawford         if (log)
125515f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITElementPacked - Failed to find allocation details");
125615f2bd95SEwan Crawford         return false;
125715f2bd95SEwan Crawford     }
125815f2bd95SEwan Crawford 
125915f2bd95SEwan Crawford     // We want 3 elements from packed data
126015f2bd95SEwan Crawford     const unsigned int num_exprs = 3;
126115f2bd95SEwan Crawford     assert(num_exprs == (eExprElementVec - eExprElementType + 1) && "Invalid number of expressions");
126215f2bd95SEwan Crawford 
126315f2bd95SEwan Crawford     const int max_expr_size = 512; // Max expression size
126415f2bd95SEwan Crawford     char buffer[num_exprs][max_expr_size];
126515f2bd95SEwan Crawford     uint64_t results[num_exprs];
126615f2bd95SEwan Crawford 
126715f2bd95SEwan Crawford     for (unsigned int i = 0; i < num_exprs; i++)
126815f2bd95SEwan Crawford     {
126915f2bd95SEwan Crawford         int chars_written = snprintf(buffer[i], max_expr_size, runtimeExpressions[eExprElementType + i], *allocation->context.get(), *allocation->element_ptr.get());
127015f2bd95SEwan Crawford         if (chars_written < 0)
127115f2bd95SEwan Crawford         {
127215f2bd95SEwan Crawford             if (log)
127315f2bd95SEwan Crawford                 log->Printf("RenderScriptRuntime::JITDataPointer - Encoding error in snprintf()");
127415f2bd95SEwan Crawford             return false;
127515f2bd95SEwan Crawford         }
127615f2bd95SEwan Crawford         else if (chars_written >= max_expr_size)
127715f2bd95SEwan Crawford         {
127815f2bd95SEwan Crawford             if (log)
127915f2bd95SEwan Crawford                 log->Printf("RenderScriptRuntime::JITElementPacked - Expression too long");
128015f2bd95SEwan Crawford             return false;
128115f2bd95SEwan Crawford         }
128215f2bd95SEwan Crawford 
128315f2bd95SEwan Crawford         // Perform expression evaluation
128415f2bd95SEwan Crawford         if (!EvalRSExpression(buffer[i], frame_ptr, &results[i]))
128515f2bd95SEwan Crawford             return false;
128615f2bd95SEwan Crawford     }
128715f2bd95SEwan Crawford 
128815f2bd95SEwan Crawford     // Assign results to allocation members
128915f2bd95SEwan Crawford     allocation->type = static_cast<RenderScriptRuntime::AllocationDetails::DataType>(results[0]);
129015f2bd95SEwan Crawford     allocation->type_kind = static_cast<RenderScriptRuntime::AllocationDetails::DataKind>(results[1]);
129115f2bd95SEwan Crawford     allocation->type_vec_size = static_cast<uint32_t>(results[2]);
129215f2bd95SEwan Crawford 
129315f2bd95SEwan Crawford     if (log)
129415f2bd95SEwan Crawford         log->Printf("RenderScriptRuntime::JITElementPacked - data type %u, pixel type %u, vector size %u",
129515f2bd95SEwan Crawford                     *allocation->type.get(), *allocation->type_kind.get(), *allocation->type_vec_size.get());
129615f2bd95SEwan Crawford 
129715f2bd95SEwan Crawford     return true;
129815f2bd95SEwan Crawford }
129915f2bd95SEwan Crawford 
1300a0f08674SEwan Crawford // JITs the RS runtime for the address of the last element in the allocation.
1301a0f08674SEwan Crawford // The `elem_size` paramter represents the size of a single element, including padding.
1302a0f08674SEwan Crawford // Which is needed as an offset from the last element pointer.
1303a0f08674SEwan Crawford // Using this offset minus the starting address we can calculate the size of the allocation.
1304a0f08674SEwan Crawford // Returns true on success, false otherwise
1305a0f08674SEwan Crawford bool
1306a0f08674SEwan Crawford RenderScriptRuntime::JITAllocationSize(AllocationDetails* allocation, StackFrame* frame_ptr,
1307a0f08674SEwan Crawford                                        const uint32_t elem_size)
1308a0f08674SEwan Crawford {
1309a0f08674SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1310a0f08674SEwan Crawford 
1311a0f08674SEwan Crawford     if (!allocation->address.isValid() || !allocation->dimension.isValid()
1312a0f08674SEwan Crawford         || !allocation->data_ptr.isValid())
1313a0f08674SEwan Crawford     {
1314a0f08674SEwan Crawford         if (log)
1315a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationSize - Failed to find allocation details");
1316a0f08674SEwan Crawford         return false;
1317a0f08674SEwan Crawford     }
1318a0f08674SEwan Crawford 
1319a0f08674SEwan Crawford     const char* expr_cstr = runtimeExpressions[eExprGetOffsetPtr];
1320a0f08674SEwan Crawford     const int max_expr_size = 512; // Max expression size
1321a0f08674SEwan Crawford     char buffer[max_expr_size];
1322a0f08674SEwan Crawford 
1323a0f08674SEwan Crawford     // Find dimensions
1324a0f08674SEwan Crawford     unsigned int dim_x = allocation->dimension.get()->dim_1;
1325a0f08674SEwan Crawford     unsigned int dim_y = allocation->dimension.get()->dim_2;
1326a0f08674SEwan Crawford     unsigned int dim_z = allocation->dimension.get()->dim_3;
1327a0f08674SEwan Crawford 
1328a0f08674SEwan Crawford     // Calculate last element
1329a0f08674SEwan Crawford     dim_x = dim_x == 0 ? 0 : dim_x - 1;
1330a0f08674SEwan Crawford     dim_y = dim_y == 0 ? 0 : dim_y - 1;
1331a0f08674SEwan Crawford     dim_z = dim_z == 0 ? 0 : dim_z - 1;
1332a0f08674SEwan Crawford 
1333a0f08674SEwan Crawford     int chars_written = snprintf(buffer, max_expr_size, expr_cstr, *allocation->address.get(),
1334a0f08674SEwan Crawford                                  dim_x, dim_y, dim_z);
1335a0f08674SEwan Crawford     if (chars_written < 0)
1336a0f08674SEwan Crawford     {
1337a0f08674SEwan Crawford         if (log)
1338a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationSize - Encoding error in snprintf()");
1339a0f08674SEwan Crawford         return false;
1340a0f08674SEwan Crawford     }
1341a0f08674SEwan Crawford     else if (chars_written >= max_expr_size)
1342a0f08674SEwan Crawford     {
1343a0f08674SEwan Crawford         if (log)
1344a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationSize - Expression too long");
1345a0f08674SEwan Crawford         return false;
1346a0f08674SEwan Crawford     }
1347a0f08674SEwan Crawford 
1348a0f08674SEwan Crawford     uint64_t result = 0;
1349a0f08674SEwan Crawford     if (!EvalRSExpression(buffer, frame_ptr, &result))
1350a0f08674SEwan Crawford         return false;
1351a0f08674SEwan Crawford 
1352a0f08674SEwan Crawford     addr_t mem_ptr = static_cast<lldb::addr_t>(result);
1353a0f08674SEwan Crawford     // Find pointer to last element and add on size of an element
1354a0f08674SEwan Crawford     allocation->size = static_cast<uint32_t>(mem_ptr - *allocation->data_ptr.get()) + elem_size;
1355a0f08674SEwan Crawford 
1356a0f08674SEwan Crawford     return true;
1357a0f08674SEwan Crawford }
1358a0f08674SEwan Crawford 
1359a0f08674SEwan Crawford // JITs the RS runtime for information about the stride between rows in the allocation.
1360a0f08674SEwan Crawford // This is done to detect padding, since allocated memory is 16-byte aligned.
1361a0f08674SEwan Crawford // Returns true on success, false otherwise
1362a0f08674SEwan Crawford bool
1363a0f08674SEwan Crawford RenderScriptRuntime::JITAllocationStride(AllocationDetails* allocation, StackFrame* frame_ptr)
1364a0f08674SEwan Crawford {
1365a0f08674SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1366a0f08674SEwan Crawford 
1367a0f08674SEwan Crawford     if (!allocation->address.isValid() || !allocation->data_ptr.isValid())
1368a0f08674SEwan Crawford     {
1369a0f08674SEwan Crawford         if (log)
1370a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationStride - Failed to find allocation details");
1371a0f08674SEwan Crawford         return false;
1372a0f08674SEwan Crawford     }
1373a0f08674SEwan Crawford 
1374a0f08674SEwan Crawford     const char* expr_cstr = runtimeExpressions[eExprGetOffsetPtr];
1375a0f08674SEwan Crawford     const int max_expr_size = 512; // Max expression size
1376a0f08674SEwan Crawford     char buffer[max_expr_size];
1377a0f08674SEwan Crawford 
1378a0f08674SEwan Crawford     int chars_written = snprintf(buffer, max_expr_size, expr_cstr, *allocation->address.get(),
1379a0f08674SEwan Crawford                                  0, 1, 0);
1380a0f08674SEwan Crawford     if (chars_written < 0)
1381a0f08674SEwan Crawford     {
1382a0f08674SEwan Crawford         if (log)
1383a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationStride - Encoding error in snprintf()");
1384a0f08674SEwan Crawford         return false;
1385a0f08674SEwan Crawford     }
1386a0f08674SEwan Crawford     else if (chars_written >= max_expr_size)
1387a0f08674SEwan Crawford     {
1388a0f08674SEwan Crawford         if (log)
1389a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationStride - Expression too long");
1390a0f08674SEwan Crawford         return false;
1391a0f08674SEwan Crawford     }
1392a0f08674SEwan Crawford 
1393a0f08674SEwan Crawford     uint64_t result = 0;
1394a0f08674SEwan Crawford     if (!EvalRSExpression(buffer, frame_ptr, &result))
1395a0f08674SEwan Crawford         return false;
1396a0f08674SEwan Crawford 
1397a0f08674SEwan Crawford     addr_t mem_ptr = static_cast<lldb::addr_t>(result);
1398a0f08674SEwan Crawford     allocation->stride = static_cast<uint32_t>(mem_ptr - *allocation->data_ptr.get());
1399a0f08674SEwan Crawford 
1400a0f08674SEwan Crawford     return true;
1401a0f08674SEwan Crawford }
1402a0f08674SEwan Crawford 
140315f2bd95SEwan Crawford // JIT all the current runtime info regarding an allocation
140415f2bd95SEwan Crawford bool
140515f2bd95SEwan Crawford RenderScriptRuntime::RefreshAllocation(AllocationDetails* allocation, StackFrame* frame_ptr)
140615f2bd95SEwan Crawford {
140715f2bd95SEwan Crawford     // GetOffsetPointer()
140815f2bd95SEwan Crawford     if (!JITDataPointer(allocation, frame_ptr))
140915f2bd95SEwan Crawford         return false;
141015f2bd95SEwan Crawford 
141115f2bd95SEwan Crawford     // rsaAllocationGetType()
141215f2bd95SEwan Crawford     if (!JITTypePointer(allocation, frame_ptr))
141315f2bd95SEwan Crawford         return false;
141415f2bd95SEwan Crawford 
141515f2bd95SEwan Crawford     // rsaTypeGetNativeData()
141615f2bd95SEwan Crawford     if (!JITTypePacked(allocation, frame_ptr))
141715f2bd95SEwan Crawford         return false;
141815f2bd95SEwan Crawford 
141915f2bd95SEwan Crawford     // rsaElementGetNativeData()
142015f2bd95SEwan Crawford     if (!JITElementPacked(allocation, frame_ptr))
142115f2bd95SEwan Crawford         return false;
142215f2bd95SEwan Crawford 
142355232f09SEwan Crawford     // Use GetOffsetPointer() to infer size of the allocation
142455232f09SEwan Crawford     const unsigned int element_size = GetElementSize(allocation);
142555232f09SEwan Crawford     if (!JITAllocationSize(allocation, frame_ptr, element_size))
142655232f09SEwan Crawford         return false;
142755232f09SEwan Crawford 
142855232f09SEwan Crawford     return true;
142955232f09SEwan Crawford }
143055232f09SEwan Crawford 
143155232f09SEwan Crawford // Returns the size of a single allocation element including padding.
143255232f09SEwan Crawford // Assumes the relevant allocation information has already been jitted.
143355232f09SEwan Crawford unsigned int
143455232f09SEwan Crawford RenderScriptRuntime::GetElementSize(const AllocationDetails* allocation)
143555232f09SEwan Crawford {
143655232f09SEwan Crawford     const AllocationDetails::DataType type = *allocation->type.get();
143755232f09SEwan Crawford     assert(type >= AllocationDetails::RS_TYPE_NONE && type <= AllocationDetails::RS_TYPE_BOOLEAN
143855232f09SEwan Crawford                                                    && "Invalid allocation type");
143955232f09SEwan Crawford 
144055232f09SEwan Crawford     const unsigned int vec_size = *allocation->type_vec_size.get();
144155232f09SEwan Crawford     const unsigned int data_size = vec_size * AllocationDetails::RSTypeToFormat[type][eElementSize];
144255232f09SEwan Crawford     const unsigned int padding = vec_size == 3 ? AllocationDetails::RSTypeToFormat[type][eElementSize] : 0;
144355232f09SEwan Crawford 
144455232f09SEwan Crawford     return data_size + padding;
144555232f09SEwan Crawford }
144655232f09SEwan Crawford 
144755232f09SEwan Crawford // Given an allocation, this function copies the allocation contents from device into a buffer on the heap.
144855232f09SEwan Crawford // Returning a shared pointer to the buffer containing the data.
144955232f09SEwan Crawford std::shared_ptr<uint8_t>
145055232f09SEwan Crawford RenderScriptRuntime::GetAllocationData(AllocationDetails* allocation, StackFrame* frame_ptr)
145155232f09SEwan Crawford {
145255232f09SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
145355232f09SEwan Crawford 
145455232f09SEwan Crawford     // JIT all the allocation details
145555232f09SEwan Crawford     if (!allocation->data_ptr.isValid() || !allocation->type.isValid() || !allocation->type_vec_size.isValid()
145655232f09SEwan Crawford         || !allocation->size.isValid())
145755232f09SEwan Crawford     {
145855232f09SEwan Crawford         if (log)
145955232f09SEwan Crawford             log->Printf("RenderScriptRuntime::GetAllocationData - Allocation details not calculated yet, jitting info");
146055232f09SEwan Crawford 
146155232f09SEwan Crawford         if (!RefreshAllocation(allocation, frame_ptr))
146255232f09SEwan Crawford         {
146355232f09SEwan Crawford             if (log)
146455232f09SEwan Crawford                 log->Printf("RenderScriptRuntime::GetAllocationData - Couldn't JIT allocation details");
146555232f09SEwan Crawford             return nullptr;
146655232f09SEwan Crawford         }
146755232f09SEwan Crawford     }
146855232f09SEwan Crawford 
146955232f09SEwan Crawford     assert(allocation->data_ptr.isValid() && allocation->type.isValid() && allocation->type_vec_size.isValid()
147055232f09SEwan Crawford            && allocation->size.isValid() && "Allocation information not available");
147155232f09SEwan Crawford 
147255232f09SEwan Crawford     // Allocate a buffer to copy data into
147355232f09SEwan Crawford     const unsigned int size = *allocation->size.get();
147455232f09SEwan Crawford     std::shared_ptr<uint8_t> buffer(new uint8_t[size]);
147555232f09SEwan Crawford     if (!buffer)
147655232f09SEwan Crawford     {
147755232f09SEwan Crawford         if (log)
147855232f09SEwan Crawford             log->Printf("RenderScriptRuntime::GetAllocationData - Couldn't allocate a %u byte buffer", size);
147955232f09SEwan Crawford         return nullptr;
148055232f09SEwan Crawford     }
148155232f09SEwan Crawford 
148255232f09SEwan Crawford     // Read the inferior memory
148355232f09SEwan Crawford     Error error;
148455232f09SEwan Crawford     lldb::addr_t data_ptr = *allocation->data_ptr.get();
148555232f09SEwan Crawford     GetProcess()->ReadMemory(data_ptr, buffer.get(), size, error);
148655232f09SEwan Crawford     if (error.Fail())
148755232f09SEwan Crawford     {
148855232f09SEwan Crawford         if (log)
148955232f09SEwan Crawford             log->Printf("RenderScriptRuntime::GetAllocationData - '%s' Couldn't read %u bytes of allocation data from 0x%" PRIx64,
149055232f09SEwan Crawford                         error.AsCString(), size, data_ptr);
149155232f09SEwan Crawford         return nullptr;
149255232f09SEwan Crawford     }
149355232f09SEwan Crawford 
149455232f09SEwan Crawford     return buffer;
149555232f09SEwan Crawford }
149655232f09SEwan Crawford 
149755232f09SEwan Crawford // Function copies data from a binary file into an allocation.
149855232f09SEwan Crawford // There is a header at the start of the file, FileHeader, before the data content itself.
149955232f09SEwan Crawford // Information from this header is used to display warnings to the user about incompatabilities
150055232f09SEwan Crawford bool
150155232f09SEwan Crawford RenderScriptRuntime::LoadAllocation(Stream &strm, const uint32_t alloc_id, const char* filename, StackFrame* frame_ptr)
150255232f09SEwan Crawford {
150355232f09SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
150455232f09SEwan Crawford 
150555232f09SEwan Crawford     // Find allocation with the given id
150655232f09SEwan Crawford     AllocationDetails* alloc = FindAllocByID(strm, alloc_id);
150755232f09SEwan Crawford     if (!alloc)
150855232f09SEwan Crawford         return false;
150955232f09SEwan Crawford 
151055232f09SEwan Crawford     if (log)
151155232f09SEwan Crawford         log->Printf("RenderScriptRuntime::LoadAllocation - Found allocation 0x%" PRIx64, *alloc->address.get());
151255232f09SEwan Crawford 
151355232f09SEwan Crawford     // JIT all the allocation details
151455232f09SEwan Crawford     if (!alloc->data_ptr.isValid() || !alloc->type.isValid() || !alloc->type_vec_size.isValid() || !alloc->size.isValid())
151555232f09SEwan Crawford     {
151655232f09SEwan Crawford         if (log)
151755232f09SEwan Crawford             log->Printf("RenderScriptRuntime::LoadAllocation - Allocation details not calculated yet, jitting info");
151855232f09SEwan Crawford 
151955232f09SEwan Crawford         if (!RefreshAllocation(alloc, frame_ptr))
152055232f09SEwan Crawford         {
152155232f09SEwan Crawford             if (log)
152255232f09SEwan Crawford                 log->Printf("RenderScriptRuntime::LoadAllocation - Couldn't JIT allocation details");
15234cfc9198SSylvestre Ledru             return false;
152455232f09SEwan Crawford         }
152555232f09SEwan Crawford     }
152655232f09SEwan Crawford 
152755232f09SEwan Crawford     assert(alloc->data_ptr.isValid() && alloc->type.isValid() && alloc->type_vec_size.isValid() && alloc->size.isValid()
152855232f09SEwan Crawford            && "Allocation information not available");
152955232f09SEwan Crawford 
153055232f09SEwan Crawford     // Check we can read from file
153155232f09SEwan Crawford     FileSpec file(filename, true);
153255232f09SEwan Crawford     if (!file.Exists())
153355232f09SEwan Crawford     {
153455232f09SEwan Crawford         strm.Printf("Error: File %s does not exist", filename);
153555232f09SEwan Crawford         strm.EOL();
153655232f09SEwan Crawford         return false;
153755232f09SEwan Crawford     }
153855232f09SEwan Crawford 
153955232f09SEwan Crawford     if (!file.Readable())
154055232f09SEwan Crawford     {
154155232f09SEwan Crawford         strm.Printf("Error: File %s does not have readable permissions", filename);
154255232f09SEwan Crawford         strm.EOL();
154355232f09SEwan Crawford         return false;
154455232f09SEwan Crawford     }
154555232f09SEwan Crawford 
154655232f09SEwan Crawford     // Read file into data buffer
154755232f09SEwan Crawford     DataBufferSP data_sp(file.ReadFileContents());
154855232f09SEwan Crawford 
154955232f09SEwan Crawford     // Cast start of buffer to FileHeader and use pointer to read metadata
155055232f09SEwan Crawford     void* file_buffer = data_sp->GetBytes();
155155232f09SEwan Crawford     const AllocationDetails::FileHeader* head = static_cast<AllocationDetails::FileHeader*>(file_buffer);
155255232f09SEwan Crawford 
155355232f09SEwan Crawford     // Advance buffer past header
155455232f09SEwan Crawford     file_buffer = static_cast<uint8_t*>(file_buffer) + head->hdr_size;
155555232f09SEwan Crawford 
155655232f09SEwan Crawford     if (log)
155755232f09SEwan Crawford         log->Printf("RenderScriptRuntime::LoadAllocation - header type %u, element size %u",
155855232f09SEwan Crawford                     head->type, head->element_size);
155955232f09SEwan Crawford 
156055232f09SEwan Crawford     // Check if the target allocation and file both have the same number of bytes for an Element
156155232f09SEwan Crawford     const unsigned int elem_size = GetElementSize(alloc);
156255232f09SEwan Crawford     if (elem_size != head->element_size)
156355232f09SEwan Crawford     {
156455232f09SEwan Crawford         strm.Printf("Warning: Mismatched Element sizes - file %u bytes, allocation %u bytes",
156555232f09SEwan Crawford                     head->element_size, elem_size);
156655232f09SEwan Crawford         strm.EOL();
156755232f09SEwan Crawford     }
156855232f09SEwan Crawford 
156955232f09SEwan Crawford     // Check if the target allocation and file both have the same integral type
157055232f09SEwan Crawford     const unsigned int type = static_cast<unsigned int>(*alloc->type.get());
157155232f09SEwan Crawford     if (type != head->type)
157255232f09SEwan Crawford     {
157355232f09SEwan Crawford         const char* file_type_cstr = AllocationDetails::RsDataTypeToString[head->type][0];
157455232f09SEwan Crawford         const char* alloc_type_cstr = AllocationDetails::RsDataTypeToString[type][0];
157555232f09SEwan Crawford 
157655232f09SEwan Crawford         strm.Printf("Warning: Mismatched Types - file '%s' type, allocation '%s' type",
157755232f09SEwan Crawford                     file_type_cstr, alloc_type_cstr);
157855232f09SEwan Crawford         strm.EOL();
157955232f09SEwan Crawford     }
158055232f09SEwan Crawford 
158155232f09SEwan Crawford     // Calculate size of allocation data in file
158255232f09SEwan Crawford     size_t length = data_sp->GetByteSize() - head->hdr_size;
158355232f09SEwan Crawford 
158455232f09SEwan Crawford     // Check if the target allocation and file both have the same total data size.
158555232f09SEwan Crawford     const unsigned int alloc_size = *alloc->size.get();
158655232f09SEwan Crawford     if (alloc_size != length)
158755232f09SEwan Crawford     {
158855232f09SEwan Crawford         strm.Printf("Warning: Mismatched allocation sizes - file 0x%" PRIx64 " bytes, allocation 0x%x bytes",
158955232f09SEwan Crawford                     length, alloc_size);
159055232f09SEwan Crawford         strm.EOL();
159155232f09SEwan Crawford         length = alloc_size < length ? alloc_size : length; // Set length to copy to minimum
159255232f09SEwan Crawford     }
159355232f09SEwan Crawford 
159455232f09SEwan Crawford     // Copy file data from our buffer into the target allocation.
159555232f09SEwan Crawford     lldb::addr_t alloc_data = *alloc->data_ptr.get();
159655232f09SEwan Crawford     Error error;
159755232f09SEwan Crawford     size_t bytes_written = GetProcess()->WriteMemory(alloc_data, file_buffer, length, error);
159855232f09SEwan Crawford     if (!error.Success() || bytes_written != length)
159955232f09SEwan Crawford     {
160055232f09SEwan Crawford         strm.Printf("Error: Couldn't write data to allocation %s", error.AsCString());
160155232f09SEwan Crawford         strm.EOL();
160255232f09SEwan Crawford         return false;
160355232f09SEwan Crawford     }
160455232f09SEwan Crawford 
160555232f09SEwan Crawford     strm.Printf("Contents of file '%s' read into allocation %u", filename, alloc->id);
160655232f09SEwan Crawford     strm.EOL();
160755232f09SEwan Crawford 
160855232f09SEwan Crawford     return true;
160955232f09SEwan Crawford }
161055232f09SEwan Crawford 
161155232f09SEwan Crawford // Function copies allocation contents into a binary file.
161255232f09SEwan Crawford // This file can then be loaded later into a different allocation.
161355232f09SEwan Crawford // There is a header, FileHeader, before the allocation data containing meta-data.
161455232f09SEwan Crawford bool
161555232f09SEwan Crawford RenderScriptRuntime::SaveAllocation(Stream &strm, const uint32_t alloc_id, const char* filename, StackFrame* frame_ptr)
161655232f09SEwan Crawford {
161755232f09SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
161855232f09SEwan Crawford 
161955232f09SEwan Crawford     // Find allocation with the given id
162055232f09SEwan Crawford     AllocationDetails* alloc = FindAllocByID(strm, alloc_id);
162155232f09SEwan Crawford     if (!alloc)
162255232f09SEwan Crawford         return false;
162355232f09SEwan Crawford 
162455232f09SEwan Crawford     if (log)
162555232f09SEwan Crawford         log->Printf("RenderScriptRuntime::SaveAllocation - Found allocation 0x%" PRIx64, *alloc->address.get());
162655232f09SEwan Crawford 
162755232f09SEwan Crawford      // JIT all the allocation details
162855232f09SEwan Crawford     if (!alloc->data_ptr.isValid() || !alloc->type.isValid() || !alloc->type_vec_size.isValid()
162955232f09SEwan Crawford         || !alloc->type_kind.isValid() || !alloc->dimension.isValid())
163055232f09SEwan Crawford     {
163155232f09SEwan Crawford         if (log)
163255232f09SEwan Crawford             log->Printf("RenderScriptRuntime::SaveAllocation - Allocation details not calculated yet, jitting info");
163355232f09SEwan Crawford 
163455232f09SEwan Crawford         if (!RefreshAllocation(alloc, frame_ptr))
163555232f09SEwan Crawford         {
163655232f09SEwan Crawford             if (log)
163755232f09SEwan Crawford                 log->Printf("RenderScriptRuntime::SaveAllocation - Couldn't JIT allocation details");
16384cfc9198SSylvestre Ledru             return false;
163955232f09SEwan Crawford         }
164055232f09SEwan Crawford     }
164155232f09SEwan Crawford 
164255232f09SEwan Crawford     assert(alloc->data_ptr.isValid() && alloc->type.isValid() && alloc->type_vec_size.isValid() && alloc->type_kind.isValid()
164355232f09SEwan Crawford            && alloc->dimension.isValid() && "Allocation information not available");
164455232f09SEwan Crawford 
164555232f09SEwan Crawford     // Check we can create writable file
164655232f09SEwan Crawford     FileSpec file_spec(filename, true);
164755232f09SEwan Crawford     File file(file_spec, File::eOpenOptionWrite | File::eOpenOptionCanCreate | File::eOpenOptionTruncate);
164855232f09SEwan Crawford     if (!file)
164955232f09SEwan Crawford     {
165055232f09SEwan Crawford         strm.Printf("Error: Failed to open '%s' for writing", filename);
165155232f09SEwan Crawford         strm.EOL();
165255232f09SEwan Crawford         return false;
165355232f09SEwan Crawford     }
165455232f09SEwan Crawford 
165555232f09SEwan Crawford     // Read allocation into buffer of heap memory
165655232f09SEwan Crawford     const std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
165755232f09SEwan Crawford     if (!buffer)
165855232f09SEwan Crawford     {
165955232f09SEwan Crawford         strm.Printf("Error: Couldn't read allocation data into buffer");
166055232f09SEwan Crawford         strm.EOL();
166155232f09SEwan Crawford         return false;
166255232f09SEwan Crawford     }
166355232f09SEwan Crawford 
166455232f09SEwan Crawford     // Create the file header
166555232f09SEwan Crawford     AllocationDetails::FileHeader head;
166655232f09SEwan Crawford     head.ident[0] = 'R'; head.ident[1] = 'S'; head.ident[2] = 'A'; head.ident[3] = 'D';
166755232f09SEwan Crawford     head.hdr_size = static_cast<uint16_t>(sizeof(AllocationDetails::FileHeader));
166855232f09SEwan Crawford     head.type = static_cast<uint16_t>(*alloc->type.get());
166955232f09SEwan Crawford     head.kind = static_cast<uint32_t>(*alloc->type_kind.get());
16702d62328aSEwan Crawford     head.dims[0] = static_cast<uint32_t>(alloc->dimension.get()->dim_1);
16712d62328aSEwan Crawford     head.dims[1] = static_cast<uint32_t>(alloc->dimension.get()->dim_2);
16722d62328aSEwan Crawford     head.dims[2] = static_cast<uint32_t>(alloc->dimension.get()->dim_3);
167355232f09SEwan Crawford     head.element_size = static_cast<uint32_t>(GetElementSize(alloc));
167455232f09SEwan Crawford 
167555232f09SEwan Crawford     // Write the file header
167655232f09SEwan Crawford     size_t num_bytes = sizeof(AllocationDetails::FileHeader);
167755232f09SEwan Crawford     Error err = file.Write(static_cast<const void*>(&head), num_bytes);
167855232f09SEwan Crawford     if (!err.Success())
167955232f09SEwan Crawford     {
168055232f09SEwan Crawford         strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), filename);
168155232f09SEwan Crawford         strm.EOL();
168255232f09SEwan Crawford         return false;
168355232f09SEwan Crawford     }
168455232f09SEwan Crawford 
168555232f09SEwan Crawford     // Write allocation data to file
168655232f09SEwan Crawford     num_bytes = static_cast<size_t>(*alloc->size.get());
168755232f09SEwan Crawford     if (log)
168855232f09SEwan Crawford         log->Printf("RenderScriptRuntime::SaveAllocation - Writing %" PRIx64  "bytes from %p", num_bytes, buffer.get());
168955232f09SEwan Crawford 
169055232f09SEwan Crawford     err = file.Write(buffer.get(), num_bytes);
169155232f09SEwan Crawford     if (!err.Success())
169255232f09SEwan Crawford     {
169355232f09SEwan Crawford         strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), filename);
169455232f09SEwan Crawford         strm.EOL();
169555232f09SEwan Crawford         return false;
169655232f09SEwan Crawford     }
169755232f09SEwan Crawford 
169855232f09SEwan Crawford     strm.Printf("Allocation written to file '%s'", filename);
169955232f09SEwan Crawford     strm.EOL();
170015f2bd95SEwan Crawford     return true;
170115f2bd95SEwan Crawford }
170215f2bd95SEwan Crawford 
17035ec532a9SColin Riley bool
17045ec532a9SColin Riley RenderScriptRuntime::LoadModule(const lldb::ModuleSP &module_sp)
17055ec532a9SColin Riley {
17064640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
17074640cde1SColin Riley 
17085ec532a9SColin Riley     if (module_sp)
17095ec532a9SColin Riley     {
17105ec532a9SColin Riley         for (const auto &rs_module : m_rsmodules)
17115ec532a9SColin Riley         {
17124640cde1SColin Riley             if (rs_module->m_module == module_sp)
17137dc7771cSEwan Crawford             {
17147dc7771cSEwan Crawford                 // Check if the user has enabled automatically breaking on
17157dc7771cSEwan Crawford                 // all RS kernels.
17167dc7771cSEwan Crawford                 if (m_breakAllKernels)
17177dc7771cSEwan Crawford                     BreakOnModuleKernels(rs_module);
17187dc7771cSEwan Crawford 
17195ec532a9SColin Riley                 return false;
17205ec532a9SColin Riley             }
17217dc7771cSEwan Crawford         }
1722ef20b08fSColin Riley         bool module_loaded = false;
1723ef20b08fSColin Riley         switch (GetModuleKind(module_sp))
1724ef20b08fSColin Riley         {
1725ef20b08fSColin Riley             case eModuleKindKernelObj:
1726ef20b08fSColin Riley             {
17274640cde1SColin Riley                 RSModuleDescriptorSP module_desc;
17284640cde1SColin Riley                 module_desc.reset(new RSModuleDescriptor(module_sp));
17294640cde1SColin Riley                 if (module_desc->ParseRSInfo())
17305ec532a9SColin Riley                 {
17315ec532a9SColin Riley                     m_rsmodules.push_back(module_desc);
1732ef20b08fSColin Riley                     module_loaded = true;
17335ec532a9SColin Riley                 }
17344640cde1SColin Riley                 if (module_loaded)
17354640cde1SColin Riley                 {
17364640cde1SColin Riley                     FixupScriptDetails(module_desc);
17374640cde1SColin Riley                 }
1738ef20b08fSColin Riley                 break;
1739ef20b08fSColin Riley             }
1740ef20b08fSColin Riley             case eModuleKindDriver:
17414640cde1SColin Riley             {
17424640cde1SColin Riley                 if (!m_libRSDriver)
17434640cde1SColin Riley                 {
17444640cde1SColin Riley                     m_libRSDriver = module_sp;
17454640cde1SColin Riley                     LoadRuntimeHooks(m_libRSDriver, RenderScriptRuntime::eModuleKindDriver);
17464640cde1SColin Riley                 }
17474640cde1SColin Riley                 break;
17484640cde1SColin Riley             }
1749ef20b08fSColin Riley             case eModuleKindImpl:
17504640cde1SColin Riley             {
17514640cde1SColin Riley                 m_libRSCpuRef = module_sp;
17524640cde1SColin Riley                 break;
17534640cde1SColin Riley             }
1754ef20b08fSColin Riley             case eModuleKindLibRS:
17554640cde1SColin Riley             {
17564640cde1SColin Riley                 if (!m_libRS)
17574640cde1SColin Riley                 {
17584640cde1SColin Riley                     m_libRS = module_sp;
17594640cde1SColin Riley                     static ConstString gDbgPresentStr("gDebuggerPresent");
17604640cde1SColin Riley                     const Symbol* debug_present = m_libRS->FindFirstSymbolWithNameAndType(gDbgPresentStr, eSymbolTypeData);
17614640cde1SColin Riley                     if (debug_present)
17624640cde1SColin Riley                     {
17634640cde1SColin Riley                         Error error;
17644640cde1SColin Riley                         uint32_t flag = 0x00000001U;
17654640cde1SColin Riley                         Target &target = GetProcess()->GetTarget();
1766358cf1eaSGreg Clayton                         addr_t addr = debug_present->GetLoadAddress(&target);
17674640cde1SColin Riley                         GetProcess()->WriteMemory(addr, &flag, sizeof(flag), error);
17684640cde1SColin Riley                         if(error.Success())
17694640cde1SColin Riley                         {
17704640cde1SColin Riley                             if (log)
17714640cde1SColin Riley                                 log->Printf ("RenderScriptRuntime::LoadModule - Debugger present flag set on debugee");
17724640cde1SColin Riley 
17734640cde1SColin Riley                             m_debuggerPresentFlagged = true;
17744640cde1SColin Riley                         }
17754640cde1SColin Riley                         else if (log)
17764640cde1SColin Riley                         {
17774640cde1SColin Riley                             log->Printf ("RenderScriptRuntime::LoadModule - Error writing debugger present flags '%s' ", error.AsCString());
17784640cde1SColin Riley                         }
17794640cde1SColin Riley                     }
17804640cde1SColin Riley                     else if (log)
17814640cde1SColin Riley                     {
17824640cde1SColin Riley                         log->Printf ("RenderScriptRuntime::LoadModule - Error writing debugger present flags - symbol not found");
17834640cde1SColin Riley                     }
17844640cde1SColin Riley                 }
17854640cde1SColin Riley                 break;
17864640cde1SColin Riley             }
1787ef20b08fSColin Riley             default:
1788ef20b08fSColin Riley                 break;
1789ef20b08fSColin Riley         }
1790ef20b08fSColin Riley         if (module_loaded)
1791ef20b08fSColin Riley             Update();
1792ef20b08fSColin Riley         return module_loaded;
17935ec532a9SColin Riley     }
17945ec532a9SColin Riley     return false;
17955ec532a9SColin Riley }
17965ec532a9SColin Riley 
1797ef20b08fSColin Riley void
1798ef20b08fSColin Riley RenderScriptRuntime::Update()
1799ef20b08fSColin Riley {
1800ef20b08fSColin Riley     if (m_rsmodules.size() > 0)
1801ef20b08fSColin Riley     {
1802ef20b08fSColin Riley         if (!m_initiated)
1803ef20b08fSColin Riley         {
1804ef20b08fSColin Riley             Initiate();
1805ef20b08fSColin Riley         }
1806ef20b08fSColin Riley     }
1807ef20b08fSColin Riley }
1808ef20b08fSColin Riley 
18095ec532a9SColin Riley // The maximum line length of an .rs.info packet
18105ec532a9SColin Riley #define MAXLINE 500
18115ec532a9SColin Riley 
18125ec532a9SColin Riley // The .rs.info symbol in renderscript modules contains a string which needs to be parsed.
18135ec532a9SColin Riley // The string is basic and is parsed on a line by line basis.
18145ec532a9SColin Riley bool
18155ec532a9SColin Riley RSModuleDescriptor::ParseRSInfo()
18165ec532a9SColin Riley {
18175ec532a9SColin Riley     const Symbol *info_sym = m_module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData);
18185ec532a9SColin Riley     if (info_sym)
18195ec532a9SColin Riley     {
1820358cf1eaSGreg Clayton         const addr_t addr = info_sym->GetAddressRef().GetFileAddress();
18215ec532a9SColin Riley         const addr_t size = info_sym->GetByteSize();
18225ec532a9SColin Riley         const FileSpec fs = m_module->GetFileSpec();
18235ec532a9SColin Riley 
18245ec532a9SColin Riley         DataBufferSP buffer = fs.ReadFileContents(addr, size);
18255ec532a9SColin Riley 
18265ec532a9SColin Riley         if (!buffer)
18275ec532a9SColin Riley             return false;
18285ec532a9SColin Riley 
18295ec532a9SColin Riley         std::string info((const char *)buffer->GetBytes());
18305ec532a9SColin Riley 
18315ec532a9SColin Riley         std::vector<std::string> info_lines;
1832e8433cc1SBruce Mitchener         size_t lpos = info.find('\n');
18335ec532a9SColin Riley         while (lpos != std::string::npos)
18345ec532a9SColin Riley         {
18355ec532a9SColin Riley             info_lines.push_back(info.substr(0, lpos));
18365ec532a9SColin Riley             info = info.substr(lpos + 1);
1837e8433cc1SBruce Mitchener             lpos = info.find('\n');
18385ec532a9SColin Riley         }
18395ec532a9SColin Riley         size_t offset = 0;
18405ec532a9SColin Riley         while (offset < info_lines.size())
18415ec532a9SColin Riley         {
18425ec532a9SColin Riley             std::string line = info_lines[offset];
18435ec532a9SColin Riley             // Parse directives
18445ec532a9SColin Riley             uint32_t numDefns = 0;
18455ec532a9SColin Riley             if (sscanf(line.c_str(), "exportVarCount: %u", &numDefns) == 1)
18465ec532a9SColin Riley             {
18475ec532a9SColin Riley                 while (numDefns--)
18484640cde1SColin Riley                     m_globals.push_back(RSGlobalDescriptor(this, info_lines[++offset].c_str()));
18495ec532a9SColin Riley             }
18505ec532a9SColin Riley             else if (sscanf(line.c_str(), "exportFuncCount: %u", &numDefns) == 1)
18515ec532a9SColin Riley             {
18525ec532a9SColin Riley             }
18535ec532a9SColin Riley             else if (sscanf(line.c_str(), "exportForEachCount: %u", &numDefns) == 1)
18545ec532a9SColin Riley             {
18555ec532a9SColin Riley                 char name[MAXLINE];
18565ec532a9SColin Riley                 while (numDefns--)
18575ec532a9SColin Riley                 {
18585ec532a9SColin Riley                     uint32_t slot = 0;
18595ec532a9SColin Riley                     name[0] = '\0';
18605ec532a9SColin Riley                     if (sscanf(info_lines[++offset].c_str(), "%u - %s", &slot, &name[0]) == 2)
18615ec532a9SColin Riley                     {
18624640cde1SColin Riley                         m_kernels.push_back(RSKernelDescriptor(this, name, slot));
18634640cde1SColin Riley                     }
18644640cde1SColin Riley                 }
18654640cde1SColin Riley             }
18664640cde1SColin Riley             else if (sscanf(line.c_str(), "pragmaCount: %u", &numDefns) == 1)
18674640cde1SColin Riley             {
18684640cde1SColin Riley                 char name[MAXLINE];
18694640cde1SColin Riley                 char value[MAXLINE];
18704640cde1SColin Riley                 while (numDefns--)
18714640cde1SColin Riley                 {
18724640cde1SColin Riley                     name[0] = '\0';
18734640cde1SColin Riley                     value[0] = '\0';
18744640cde1SColin Riley                     if (sscanf(info_lines[++offset].c_str(), "%s - %s", &name[0], &value[0]) != 0
18754640cde1SColin Riley                         && (name[0] != '\0'))
18764640cde1SColin Riley                     {
18774640cde1SColin Riley                         m_pragmas[std::string(name)] = value;
18785ec532a9SColin Riley                     }
18795ec532a9SColin Riley                 }
18805ec532a9SColin Riley             }
18815ec532a9SColin Riley             else if (sscanf(line.c_str(), "objectSlotCount: %u", &numDefns) == 1)
18825ec532a9SColin Riley             {
18835ec532a9SColin Riley             }
18845ec532a9SColin Riley 
18855ec532a9SColin Riley             offset++;
18865ec532a9SColin Riley         }
18875ec532a9SColin Riley         return m_kernels.size() > 0;
18885ec532a9SColin Riley     }
18895ec532a9SColin Riley     return false;
18905ec532a9SColin Riley }
18915ec532a9SColin Riley 
18925ec532a9SColin Riley bool
18935ec532a9SColin Riley RenderScriptRuntime::ProbeModules(const ModuleList module_list)
18945ec532a9SColin Riley {
18955ec532a9SColin Riley     bool rs_found = false;
18965ec532a9SColin Riley     size_t num_modules = module_list.GetSize();
18975ec532a9SColin Riley     for (size_t i = 0; i < num_modules; i++)
18985ec532a9SColin Riley     {
18995ec532a9SColin Riley         auto module = module_list.GetModuleAtIndex(i);
19005ec532a9SColin Riley         rs_found |= LoadModule(module);
19015ec532a9SColin Riley     }
19025ec532a9SColin Riley     return rs_found;
19035ec532a9SColin Riley }
19045ec532a9SColin Riley 
19055ec532a9SColin Riley void
19064640cde1SColin Riley RenderScriptRuntime::Status(Stream &strm) const
19074640cde1SColin Riley {
19084640cde1SColin Riley     if (m_libRS)
19094640cde1SColin Riley     {
19104640cde1SColin Riley         strm.Printf("Runtime Library discovered.");
19114640cde1SColin Riley         strm.EOL();
19124640cde1SColin Riley     }
19134640cde1SColin Riley     if (m_libRSDriver)
19144640cde1SColin Riley     {
19154640cde1SColin Riley         strm.Printf("Runtime Driver discovered.");
19164640cde1SColin Riley         strm.EOL();
19174640cde1SColin Riley     }
19184640cde1SColin Riley     if (m_libRSCpuRef)
19194640cde1SColin Riley     {
19204640cde1SColin Riley         strm.Printf("CPU Reference Implementation discovered.");
19214640cde1SColin Riley         strm.EOL();
19224640cde1SColin Riley     }
19234640cde1SColin Riley 
19244640cde1SColin Riley     if (m_runtimeHooks.size())
19254640cde1SColin Riley     {
19264640cde1SColin Riley         strm.Printf("Runtime functions hooked:");
19274640cde1SColin Riley         strm.EOL();
19284640cde1SColin Riley         for (auto b : m_runtimeHooks)
19294640cde1SColin Riley         {
19304640cde1SColin Riley             strm.Indent(b.second->defn->name);
19314640cde1SColin Riley             strm.EOL();
19324640cde1SColin Riley         }
19334640cde1SColin Riley         strm.EOL();
19344640cde1SColin Riley     }
19354640cde1SColin Riley     else
19364640cde1SColin Riley     {
19374640cde1SColin Riley         strm.Printf("Runtime is not hooked.");
19384640cde1SColin Riley         strm.EOL();
19394640cde1SColin Riley     }
19404640cde1SColin Riley }
19414640cde1SColin Riley 
19424640cde1SColin Riley void
19434640cde1SColin Riley RenderScriptRuntime::DumpContexts(Stream &strm) const
19444640cde1SColin Riley {
19454640cde1SColin Riley     strm.Printf("Inferred RenderScript Contexts:");
19464640cde1SColin Riley     strm.EOL();
19474640cde1SColin Riley     strm.IndentMore();
19484640cde1SColin Riley 
19494640cde1SColin Riley     std::map<addr_t, uint64_t> contextReferences;
19504640cde1SColin Riley 
195178f339d1SEwan Crawford     // Iterate over all of the currently discovered scripts.
195278f339d1SEwan Crawford     // Note: We cant push or pop from m_scripts inside this loop or it may invalidate script.
19534640cde1SColin Riley     for (const auto & script : m_scripts)
19544640cde1SColin Riley     {
195578f339d1SEwan Crawford         if (!script->context.isValid())
195678f339d1SEwan Crawford             continue;
195778f339d1SEwan Crawford         lldb::addr_t context = *script->context;
195878f339d1SEwan Crawford 
195978f339d1SEwan Crawford         if (contextReferences.find(context) != contextReferences.end())
19604640cde1SColin Riley         {
196178f339d1SEwan Crawford             contextReferences[context]++;
19624640cde1SColin Riley         }
19634640cde1SColin Riley         else
19644640cde1SColin Riley         {
196578f339d1SEwan Crawford             contextReferences[context] = 1;
19664640cde1SColin Riley         }
19674640cde1SColin Riley     }
19684640cde1SColin Riley 
19694640cde1SColin Riley     for (const auto& cRef : contextReferences)
19704640cde1SColin Riley     {
19714640cde1SColin Riley         strm.Printf("Context 0x%" PRIx64 ": %" PRIu64 " script instances", cRef.first, cRef.second);
19724640cde1SColin Riley         strm.EOL();
19734640cde1SColin Riley     }
19744640cde1SColin Riley     strm.IndentLess();
19754640cde1SColin Riley }
19764640cde1SColin Riley 
19774640cde1SColin Riley void
19784640cde1SColin Riley RenderScriptRuntime::DumpKernels(Stream &strm) const
19794640cde1SColin Riley {
19804640cde1SColin Riley     strm.Printf("RenderScript Kernels:");
19814640cde1SColin Riley     strm.EOL();
19824640cde1SColin Riley     strm.IndentMore();
19834640cde1SColin Riley     for (const auto &module : m_rsmodules)
19844640cde1SColin Riley     {
19854640cde1SColin Riley         strm.Printf("Resource '%s':",module->m_resname.c_str());
19864640cde1SColin Riley         strm.EOL();
19874640cde1SColin Riley         for (const auto &kernel : module->m_kernels)
19884640cde1SColin Riley         {
19894640cde1SColin Riley             strm.Indent(kernel.m_name.AsCString());
19904640cde1SColin Riley             strm.EOL();
19914640cde1SColin Riley         }
19924640cde1SColin Riley     }
19934640cde1SColin Riley     strm.IndentLess();
19944640cde1SColin Riley }
19954640cde1SColin Riley 
1996a0f08674SEwan Crawford RenderScriptRuntime::AllocationDetails*
1997a0f08674SEwan Crawford RenderScriptRuntime::FindAllocByID(Stream &strm, const uint32_t alloc_id)
1998a0f08674SEwan Crawford {
1999a0f08674SEwan Crawford     AllocationDetails* alloc = nullptr;
2000a0f08674SEwan Crawford 
2001a0f08674SEwan Crawford     // See if we can find allocation using id as an index;
2002a0f08674SEwan Crawford     if (alloc_id <= m_allocations.size() && alloc_id != 0
2003a0f08674SEwan Crawford         && m_allocations[alloc_id-1]->id == alloc_id)
2004a0f08674SEwan Crawford     {
2005a0f08674SEwan Crawford         alloc = m_allocations[alloc_id-1].get();
2006a0f08674SEwan Crawford         return alloc;
2007a0f08674SEwan Crawford     }
2008a0f08674SEwan Crawford 
2009a0f08674SEwan Crawford     // Fallback to searching
2010a0f08674SEwan Crawford     for (const auto & a : m_allocations)
2011a0f08674SEwan Crawford     {
2012a0f08674SEwan Crawford        if (a->id == alloc_id)
2013a0f08674SEwan Crawford        {
2014a0f08674SEwan Crawford            alloc = a.get();
2015a0f08674SEwan Crawford            break;
2016a0f08674SEwan Crawford        }
2017a0f08674SEwan Crawford     }
2018a0f08674SEwan Crawford 
2019a0f08674SEwan Crawford     if (alloc == nullptr)
2020a0f08674SEwan Crawford     {
2021a0f08674SEwan Crawford         strm.Printf("Error: Couldn't find allocation with id matching %u", alloc_id);
2022a0f08674SEwan Crawford         strm.EOL();
2023a0f08674SEwan Crawford     }
2024a0f08674SEwan Crawford 
2025a0f08674SEwan Crawford     return alloc;
2026a0f08674SEwan Crawford }
2027a0f08674SEwan Crawford 
2028a0f08674SEwan Crawford // Prints the contents of an allocation to the output stream, which may be a file
2029a0f08674SEwan Crawford bool
2030a0f08674SEwan Crawford RenderScriptRuntime::DumpAllocation(Stream &strm, StackFrame* frame_ptr, const uint32_t id)
2031a0f08674SEwan Crawford {
2032a0f08674SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2033a0f08674SEwan Crawford 
2034a0f08674SEwan Crawford     // Check we can find the desired allocation
2035a0f08674SEwan Crawford     AllocationDetails* alloc = FindAllocByID(strm, id);
2036a0f08674SEwan Crawford     if (!alloc)
2037a0f08674SEwan Crawford         return false; // FindAllocByID() will print error message for us here
2038a0f08674SEwan Crawford 
2039a0f08674SEwan Crawford     if (log)
2040a0f08674SEwan Crawford         log->Printf("RenderScriptRuntime::DumpAllocation - Found allocation 0x%" PRIx64, *alloc->address.get());
2041a0f08674SEwan Crawford 
2042a0f08674SEwan Crawford     // Check we have information about the allocation, if not calculate it
2043a0f08674SEwan Crawford     if (!alloc->data_ptr.isValid() || !alloc->type.isValid() ||
2044a0f08674SEwan Crawford         !alloc->type_vec_size.isValid() || !alloc->dimension.isValid())
2045a0f08674SEwan Crawford     {
2046a0f08674SEwan Crawford         if (log)
2047a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::DumpAllocation - Allocation details not calculated yet, jitting info");
2048a0f08674SEwan Crawford 
2049a0f08674SEwan Crawford         // JIT all the allocation information
2050a0f08674SEwan Crawford         if (!RefreshAllocation(alloc, frame_ptr))
2051a0f08674SEwan Crawford         {
2052a0f08674SEwan Crawford             strm.Printf("Error: Couldn't JIT allocation details");
2053a0f08674SEwan Crawford             strm.EOL();
2054a0f08674SEwan Crawford             return false;
2055a0f08674SEwan Crawford         }
2056a0f08674SEwan Crawford     }
2057a0f08674SEwan Crawford 
2058a0f08674SEwan Crawford     // Establish format and size of each data element
2059a0f08674SEwan Crawford     const unsigned int vec_size = *alloc->type_vec_size.get();
2060a0f08674SEwan Crawford     const AllocationDetails::DataType type = *alloc->type.get();
2061a0f08674SEwan Crawford 
2062a0f08674SEwan Crawford     assert(type >= AllocationDetails::RS_TYPE_NONE && type <= AllocationDetails::RS_TYPE_BOOLEAN
2063a0f08674SEwan Crawford                                                    && "Invalid allocation type");
2064a0f08674SEwan Crawford 
2065a0f08674SEwan Crawford     lldb::Format format = vec_size == 1 ? static_cast<lldb::Format>(AllocationDetails::RSTypeToFormat[type][eFormatSingle])
2066a0f08674SEwan Crawford                                         : static_cast<lldb::Format>(AllocationDetails::RSTypeToFormat[type][eFormatVector]);
2067a0f08674SEwan Crawford 
2068a0f08674SEwan Crawford     const unsigned int data_size = vec_size * AllocationDetails::RSTypeToFormat[type][eElementSize];
2069a0f08674SEwan Crawford     // Renderscript pads vector 3 elements to vector 4
2070a0f08674SEwan Crawford     const unsigned int elem_padding = vec_size == 3 ? AllocationDetails::RSTypeToFormat[type][eElementSize] : 0;
2071a0f08674SEwan Crawford 
2072a0f08674SEwan Crawford     if (log)
2073a0f08674SEwan Crawford         log->Printf("RenderScriptRuntime::DumpAllocation - Element size %u bytes, element padding %u bytes",
2074a0f08674SEwan Crawford                     data_size, elem_padding);
2075a0f08674SEwan Crawford 
207655232f09SEwan Crawford     // Allocate a buffer to copy data into
207755232f09SEwan Crawford     std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
207855232f09SEwan Crawford     if (!buffer)
207955232f09SEwan Crawford     {
208055232f09SEwan Crawford         strm.Printf("Error: Couldn't allocate a read allocation data into memory");
208155232f09SEwan Crawford         strm.EOL();
208255232f09SEwan Crawford         return false;
208355232f09SEwan Crawford     }
208455232f09SEwan Crawford 
2085a0f08674SEwan Crawford     // Calculate stride between rows as there may be padding at end of rows since
2086a0f08674SEwan Crawford     // allocated memory is 16-byte aligned
2087a0f08674SEwan Crawford     if (!alloc->stride.isValid())
2088a0f08674SEwan Crawford     {
2089a0f08674SEwan Crawford         if (alloc->dimension.get()->dim_2 == 0) // We only have one dimension
2090a0f08674SEwan Crawford             alloc->stride = 0;
2091a0f08674SEwan Crawford         else if (!JITAllocationStride(alloc, frame_ptr))
2092a0f08674SEwan Crawford         {
2093a0f08674SEwan Crawford             strm.Printf("Error: Couldn't calculate allocation row stride");
2094a0f08674SEwan Crawford             strm.EOL();
2095a0f08674SEwan Crawford             return false;
2096a0f08674SEwan Crawford         }
2097a0f08674SEwan Crawford     }
2098a0f08674SEwan Crawford     const unsigned int stride = *alloc->stride.get();
2099a0f08674SEwan Crawford     const unsigned int size = *alloc->size.get(); //size of last element
2100a0f08674SEwan Crawford 
2101a0f08674SEwan Crawford     if (log)
2102a0f08674SEwan Crawford         log->Printf("RenderScriptRuntime::DumpAllocation - stride %u bytes, size %u bytes", stride, size);
2103a0f08674SEwan Crawford 
2104a0f08674SEwan Crawford     // Find dimensions used to index loops, so need to be non-zero
2105a0f08674SEwan Crawford     unsigned int dim_x = alloc->dimension.get()->dim_1;
2106a0f08674SEwan Crawford     dim_x = dim_x == 0 ? 1 : dim_x;
2107a0f08674SEwan Crawford 
2108a0f08674SEwan Crawford     unsigned int dim_y = alloc->dimension.get()->dim_2;
2109a0f08674SEwan Crawford     dim_y = dim_y == 0 ? 1 : dim_y;
2110a0f08674SEwan Crawford 
2111a0f08674SEwan Crawford     unsigned int dim_z = alloc->dimension.get()->dim_3;
2112a0f08674SEwan Crawford     dim_z = dim_z == 0 ? 1 : dim_z;
2113a0f08674SEwan Crawford 
211455232f09SEwan Crawford     // Use data extractor to format output
211555232f09SEwan Crawford     const uint32_t archByteSize = GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
211655232f09SEwan Crawford     DataExtractor alloc_data(buffer.get(), size, GetProcess()->GetByteOrder(), archByteSize);
211755232f09SEwan Crawford 
2118a0f08674SEwan Crawford     unsigned int offset = 0;   // Offset in buffer to next element to be printed
2119a0f08674SEwan Crawford     unsigned int prev_row = 0; // Offset to the start of the previous row
2120a0f08674SEwan Crawford 
2121a0f08674SEwan Crawford     // Iterate over allocation dimensions, printing results to user
2122a0f08674SEwan Crawford     strm.Printf("Data (X, Y, Z):");
2123a0f08674SEwan Crawford     for (unsigned int z = 0; z < dim_z; ++z)
2124a0f08674SEwan Crawford     {
2125a0f08674SEwan Crawford         for (unsigned int y = 0; y < dim_y; ++y)
2126a0f08674SEwan Crawford         {
2127a0f08674SEwan Crawford             // Use stride to index start of next row.
2128a0f08674SEwan Crawford             if (!(y==0 && z==0))
2129a0f08674SEwan Crawford                 offset = prev_row + stride;
2130a0f08674SEwan Crawford             prev_row = offset;
2131a0f08674SEwan Crawford 
2132a0f08674SEwan Crawford             // Print each element in the row individually
2133a0f08674SEwan Crawford             for (unsigned int x = 0; x < dim_x; ++x)
2134a0f08674SEwan Crawford             {
2135a0f08674SEwan Crawford                 strm.Printf("\n(%u, %u, %u) = ", x, y, z);
2136a0f08674SEwan Crawford                 alloc_data.Dump(&strm, offset, format, data_size, 1, 1, LLDB_INVALID_ADDRESS, 0, 0);
2137a0f08674SEwan Crawford                 offset += data_size + elem_padding;
2138a0f08674SEwan Crawford             }
2139a0f08674SEwan Crawford         }
2140a0f08674SEwan Crawford     }
2141a0f08674SEwan Crawford     strm.EOL();
2142a0f08674SEwan Crawford 
2143a0f08674SEwan Crawford     return true;
2144a0f08674SEwan Crawford }
2145a0f08674SEwan Crawford 
214615f2bd95SEwan Crawford // Prints infomation regarding all the currently loaded allocations.
214715f2bd95SEwan Crawford // These details are gathered by jitting the runtime, which has as latency.
214815f2bd95SEwan Crawford void
214915f2bd95SEwan Crawford RenderScriptRuntime::ListAllocations(Stream &strm, StackFrame* frame_ptr, bool recompute)
215015f2bd95SEwan Crawford {
215115f2bd95SEwan Crawford     strm.Printf("RenderScript Allocations:");
215215f2bd95SEwan Crawford     strm.EOL();
215315f2bd95SEwan Crawford     strm.IndentMore();
215415f2bd95SEwan Crawford 
215515f2bd95SEwan Crawford     for (auto &alloc : m_allocations)
215615f2bd95SEwan Crawford     {
215715f2bd95SEwan Crawford         // JIT the allocation info if we haven't done it, or the user forces us to.
215815f2bd95SEwan Crawford         bool do_refresh = !alloc->data_ptr.isValid() || recompute;
215915f2bd95SEwan Crawford 
216015f2bd95SEwan Crawford         // JIT current allocation information
216115f2bd95SEwan Crawford         if (do_refresh && !RefreshAllocation(alloc.get(), frame_ptr))
216215f2bd95SEwan Crawford         {
216315f2bd95SEwan Crawford             strm.Printf("Error: Couldn't evaluate details for allocation %u\n", alloc->id);
216415f2bd95SEwan Crawford             continue;
216515f2bd95SEwan Crawford         }
216615f2bd95SEwan Crawford 
216715f2bd95SEwan Crawford         strm.Printf("%u:\n",alloc->id);
216815f2bd95SEwan Crawford         strm.IndentMore();
216915f2bd95SEwan Crawford 
217015f2bd95SEwan Crawford         strm.Indent("Context: ");
217115f2bd95SEwan Crawford         if (!alloc->context.isValid())
217215f2bd95SEwan Crawford             strm.Printf("unknown\n");
217315f2bd95SEwan Crawford         else
217415f2bd95SEwan Crawford             strm.Printf("0x%" PRIx64 "\n", *alloc->context.get());
217515f2bd95SEwan Crawford 
217615f2bd95SEwan Crawford         strm.Indent("Address: ");
217715f2bd95SEwan Crawford         if (!alloc->address.isValid())
217815f2bd95SEwan Crawford             strm.Printf("unknown\n");
217915f2bd95SEwan Crawford         else
218015f2bd95SEwan Crawford             strm.Printf("0x%" PRIx64 "\n", *alloc->address.get());
218115f2bd95SEwan Crawford 
218215f2bd95SEwan Crawford         strm.Indent("Data pointer: ");
218315f2bd95SEwan Crawford         if (!alloc->data_ptr.isValid())
218415f2bd95SEwan Crawford             strm.Printf("unknown\n");
218515f2bd95SEwan Crawford         else
218615f2bd95SEwan Crawford             strm.Printf("0x%" PRIx64 "\n", *alloc->data_ptr.get());
218715f2bd95SEwan Crawford 
218815f2bd95SEwan Crawford         strm.Indent("Dimensions: ");
218915f2bd95SEwan Crawford         if (!alloc->dimension.isValid())
219015f2bd95SEwan Crawford             strm.Printf("unknown\n");
219115f2bd95SEwan Crawford         else
219215f2bd95SEwan Crawford             strm.Printf("(%d, %d, %d)\n", alloc->dimension.get()->dim_1,
219315f2bd95SEwan Crawford                                           alloc->dimension.get()->dim_2,
219415f2bd95SEwan Crawford                                           alloc->dimension.get()->dim_3);
219515f2bd95SEwan Crawford 
219615f2bd95SEwan Crawford         strm.Indent("Data Type: ");
219715f2bd95SEwan Crawford         if (!alloc->type.isValid() || !alloc->type_vec_size.isValid())
219815f2bd95SEwan Crawford             strm.Printf("unknown\n");
219915f2bd95SEwan Crawford         else
220015f2bd95SEwan Crawford         {
220115f2bd95SEwan Crawford             const int vector_size = *alloc->type_vec_size.get();
220215f2bd95SEwan Crawford             const AllocationDetails::DataType type = *alloc->type.get();
220315f2bd95SEwan Crawford 
220415f2bd95SEwan Crawford             if (vector_size > 4 || vector_size < 1 ||
220515f2bd95SEwan Crawford                 type < AllocationDetails::RS_TYPE_NONE || type > AllocationDetails::RS_TYPE_BOOLEAN)
220615f2bd95SEwan Crawford                 strm.Printf("invalid type\n");
220715f2bd95SEwan Crawford             else
220815f2bd95SEwan Crawford                 strm.Printf("%s\n", AllocationDetails::RsDataTypeToString[static_cast<unsigned int>(type)][vector_size-1]);
220915f2bd95SEwan Crawford         }
221015f2bd95SEwan Crawford 
221115f2bd95SEwan Crawford         strm.Indent("Data Kind: ");
221215f2bd95SEwan Crawford         if (!alloc->type_kind.isValid())
221315f2bd95SEwan Crawford             strm.Printf("unknown\n");
221415f2bd95SEwan Crawford         else
221515f2bd95SEwan Crawford         {
221615f2bd95SEwan Crawford             const AllocationDetails::DataKind kind = *alloc->type_kind.get();
221715f2bd95SEwan Crawford             if (kind < AllocationDetails::RS_KIND_USER || kind > AllocationDetails::RS_KIND_PIXEL_YUV)
221815f2bd95SEwan Crawford                 strm.Printf("invalid kind\n");
221915f2bd95SEwan Crawford             else
222015f2bd95SEwan Crawford                 strm.Printf("%s\n", AllocationDetails::RsDataKindToString[static_cast<unsigned int>(kind)]);
222115f2bd95SEwan Crawford         }
222215f2bd95SEwan Crawford 
222315f2bd95SEwan Crawford         strm.EOL();
222415f2bd95SEwan Crawford         strm.IndentLess();
222515f2bd95SEwan Crawford     }
222615f2bd95SEwan Crawford     strm.IndentLess();
222715f2bd95SEwan Crawford }
222815f2bd95SEwan Crawford 
22297dc7771cSEwan Crawford // Set breakpoints on every kernel found in RS module
22307dc7771cSEwan Crawford void
22317dc7771cSEwan Crawford RenderScriptRuntime::BreakOnModuleKernels(const RSModuleDescriptorSP rsmodule_sp)
22327dc7771cSEwan Crawford {
22337dc7771cSEwan Crawford     for (const auto &kernel : rsmodule_sp->m_kernels)
22347dc7771cSEwan Crawford     {
22357dc7771cSEwan Crawford         // Don't set breakpoint on 'root' kernel
22367dc7771cSEwan Crawford         if (strcmp(kernel.m_name.AsCString(), "root") == 0)
22377dc7771cSEwan Crawford             continue;
22387dc7771cSEwan Crawford 
22397dc7771cSEwan Crawford         CreateKernelBreakpoint(kernel.m_name);
22407dc7771cSEwan Crawford     }
22417dc7771cSEwan Crawford }
22427dc7771cSEwan Crawford 
22437dc7771cSEwan Crawford // Method is internally called by the 'kernel breakpoint all' command to
22447dc7771cSEwan Crawford // enable or disable breaking on all kernels.
22457dc7771cSEwan Crawford //
22467dc7771cSEwan Crawford // When do_break is true we want to enable this functionality.
22477dc7771cSEwan Crawford // When do_break is false we want to disable it.
22487dc7771cSEwan Crawford void
22497dc7771cSEwan Crawford RenderScriptRuntime::SetBreakAllKernels(bool do_break, TargetSP target)
22507dc7771cSEwan Crawford {
225154782db7SEwan Crawford     Log* log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
22527dc7771cSEwan Crawford 
22537dc7771cSEwan Crawford     InitSearchFilter(target);
22547dc7771cSEwan Crawford 
22557dc7771cSEwan Crawford     // Set breakpoints on all the kernels
22567dc7771cSEwan Crawford     if (do_break && !m_breakAllKernels)
22577dc7771cSEwan Crawford     {
22587dc7771cSEwan Crawford         m_breakAllKernels = true;
22597dc7771cSEwan Crawford 
22607dc7771cSEwan Crawford         for (const auto &module : m_rsmodules)
22617dc7771cSEwan Crawford             BreakOnModuleKernels(module);
22627dc7771cSEwan Crawford 
22637dc7771cSEwan Crawford         if (log)
22647dc7771cSEwan Crawford             log->Printf("RenderScriptRuntime::SetBreakAllKernels(True)"
22657dc7771cSEwan Crawford                         "- breakpoints set on all currently loaded kernels");
22667dc7771cSEwan Crawford     }
22677dc7771cSEwan Crawford     else if (!do_break && m_breakAllKernels) // Breakpoints won't be set on any new kernels.
22687dc7771cSEwan Crawford     {
22697dc7771cSEwan Crawford         m_breakAllKernels = false;
22707dc7771cSEwan Crawford 
22717dc7771cSEwan Crawford         if (log)
22727dc7771cSEwan Crawford             log->Printf("RenderScriptRuntime::SetBreakAllKernels(False) - breakpoints no longer automatically set");
22737dc7771cSEwan Crawford     }
22747dc7771cSEwan Crawford }
22757dc7771cSEwan Crawford 
22767dc7771cSEwan Crawford // Given the name of a kernel this function creates a breakpoint using our
22777dc7771cSEwan Crawford // own breakpoint resolver, and returns the Breakpoint shared pointer.
22787dc7771cSEwan Crawford BreakpointSP
22797dc7771cSEwan Crawford RenderScriptRuntime::CreateKernelBreakpoint(const ConstString& name)
22807dc7771cSEwan Crawford {
228154782db7SEwan Crawford     Log* log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
22827dc7771cSEwan Crawford 
22837dc7771cSEwan Crawford     if (!m_filtersp)
22847dc7771cSEwan Crawford     {
22857dc7771cSEwan Crawford         if (log)
22867dc7771cSEwan Crawford             log->Printf("RenderScriptRuntime::CreateKernelBreakpoint - Error: No breakpoint search filter set");
22877dc7771cSEwan Crawford         return nullptr;
22887dc7771cSEwan Crawford     }
22897dc7771cSEwan Crawford 
22907dc7771cSEwan Crawford     BreakpointResolverSP resolver_sp(new RSBreakpointResolver(nullptr, name));
22917dc7771cSEwan Crawford     BreakpointSP bp = GetProcess()->GetTarget().CreateBreakpoint(m_filtersp, resolver_sp, false, false, false);
22927dc7771cSEwan Crawford 
229354782db7SEwan Crawford     // Give RS breakpoints a specific name, so the user can manipulate them as a group.
229454782db7SEwan Crawford     Error err;
229554782db7SEwan Crawford     if (!bp->AddName("RenderScriptKernel", err) && log)
229654782db7SEwan Crawford         log->Printf("RenderScriptRuntime::CreateKernelBreakpoint: Error setting break name, %s", err.AsCString());
229754782db7SEwan Crawford 
22987dc7771cSEwan Crawford     return bp;
22997dc7771cSEwan Crawford }
23007dc7771cSEwan Crawford 
2301018f5a7eSEwan Crawford // Given an expression for a variable this function tries to calculate the variable's value.
2302018f5a7eSEwan Crawford // If this is possible it returns true and sets the uint64_t parameter to the variables unsigned value.
2303018f5a7eSEwan Crawford // Otherwise function returns false.
2304018f5a7eSEwan Crawford bool
2305018f5a7eSEwan Crawford RenderScriptRuntime::GetFrameVarAsUnsigned(const StackFrameSP frame_sp, const char* var_name, uint64_t& val)
2306018f5a7eSEwan Crawford {
2307018f5a7eSEwan Crawford     Log* log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2308018f5a7eSEwan Crawford     Error error;
2309018f5a7eSEwan Crawford     VariableSP var_sp;
2310018f5a7eSEwan Crawford 
2311018f5a7eSEwan Crawford     // Find variable in stack frame
2312018f5a7eSEwan Crawford     ValueObjectSP value_sp(frame_sp->GetValueForVariableExpressionPath(var_name,
2313018f5a7eSEwan Crawford                                                                        eNoDynamicValues,
2314018f5a7eSEwan Crawford                                                                        StackFrame::eExpressionPathOptionCheckPtrVsMember |
2315018f5a7eSEwan Crawford                                                                        StackFrame::eExpressionPathOptionsAllowDirectIVarAccess,
2316018f5a7eSEwan Crawford                                                                        var_sp,
2317018f5a7eSEwan Crawford                                                                        error));
2318018f5a7eSEwan Crawford     if (!error.Success())
2319018f5a7eSEwan Crawford     {
2320018f5a7eSEwan Crawford         if (log)
2321018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::GetFrameVarAsUnsigned - Error, couldn't find '%s' in frame", var_name);
2322018f5a7eSEwan Crawford 
2323018f5a7eSEwan Crawford         return false;
2324018f5a7eSEwan Crawford     }
2325018f5a7eSEwan Crawford 
2326018f5a7eSEwan Crawford     // Find the unsigned int value for the variable
2327018f5a7eSEwan Crawford     bool success = false;
2328018f5a7eSEwan Crawford     val = value_sp->GetValueAsUnsigned(0, &success);
2329018f5a7eSEwan Crawford     if (!success)
2330018f5a7eSEwan Crawford     {
2331018f5a7eSEwan Crawford         if (log)
2332018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::GetFrameVarAsUnsigned - Error, couldn't parse '%s' as an unsigned int", var_name);
2333018f5a7eSEwan Crawford 
2334018f5a7eSEwan Crawford         return false;
2335018f5a7eSEwan Crawford     }
2336018f5a7eSEwan Crawford 
2337018f5a7eSEwan Crawford     return true;
2338018f5a7eSEwan Crawford }
2339018f5a7eSEwan Crawford 
2340018f5a7eSEwan Crawford // Callback when a kernel breakpoint hits and we're looking for a specific coordinate.
2341018f5a7eSEwan Crawford // Baton parameter contains a pointer to the target coordinate we want to break on.
2342018f5a7eSEwan Crawford // Function then checks the .expand frame for the current coordinate and breaks to user if it matches.
2343018f5a7eSEwan Crawford // Parameter 'break_id' is the id of the Breakpoint which made the callback.
2344018f5a7eSEwan Crawford // Parameter 'break_loc_id' is the id for the BreakpointLocation which was hit,
2345018f5a7eSEwan Crawford // a single logical breakpoint can have multiple addresses.
2346018f5a7eSEwan Crawford bool
2347018f5a7eSEwan Crawford RenderScriptRuntime::KernelBreakpointHit(void *baton, StoppointCallbackContext *ctx,
2348018f5a7eSEwan Crawford                                          user_id_t break_id, user_id_t break_loc_id)
2349018f5a7eSEwan Crawford {
2350018f5a7eSEwan Crawford     Log* log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
2351018f5a7eSEwan Crawford 
2352018f5a7eSEwan Crawford     assert(baton && "Error: null baton in conditional kernel breakpoint callback");
2353018f5a7eSEwan Crawford 
2354018f5a7eSEwan Crawford     // Coordinate we want to stop on
2355018f5a7eSEwan Crawford     const int* target_coord = static_cast<const int*>(baton);
2356018f5a7eSEwan Crawford 
2357018f5a7eSEwan Crawford     if (log)
2358018f5a7eSEwan Crawford         log->Printf("RenderScriptRuntime::KernelBreakpointHit - Break ID %" PRIu64 ", target coord (%d, %d, %d)",
2359018f5a7eSEwan Crawford                     break_id, target_coord[0], target_coord[1], target_coord[2]);
2360018f5a7eSEwan Crawford 
2361018f5a7eSEwan Crawford     // Go up one stack frame to .expand kernel
2362018f5a7eSEwan Crawford     ExecutionContext context(ctx->exe_ctx_ref);
2363018f5a7eSEwan Crawford     ThreadSP thread_sp = context.GetThreadSP();
2364018f5a7eSEwan Crawford     if (!thread_sp->SetSelectedFrameByIndex(1))
2365018f5a7eSEwan Crawford     {
2366018f5a7eSEwan Crawford         if (log)
2367018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::KernelBreakpointHit - Error, couldn't go up stack frame");
2368018f5a7eSEwan Crawford 
2369018f5a7eSEwan Crawford        return false;
2370018f5a7eSEwan Crawford     }
2371018f5a7eSEwan Crawford 
2372018f5a7eSEwan Crawford     StackFrameSP frame_sp = thread_sp->GetSelectedFrame();
2373018f5a7eSEwan Crawford     if (!frame_sp)
2374018f5a7eSEwan Crawford     {
2375018f5a7eSEwan Crawford         if (log)
2376018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::KernelBreakpointHit - Error, couldn't select .expand stack frame");
2377018f5a7eSEwan Crawford 
2378018f5a7eSEwan Crawford         return false;
2379018f5a7eSEwan Crawford     }
2380018f5a7eSEwan Crawford 
2381018f5a7eSEwan Crawford     // Get values for variables in .expand frame that tell us the current kernel invocation
2382018f5a7eSEwan Crawford     const char* coord_expressions[] = {"rsIndex", "p->current.y", "p->current.z"};
2383018f5a7eSEwan Crawford     uint64_t current_coord[3] = {0, 0, 0};
2384018f5a7eSEwan Crawford 
2385018f5a7eSEwan Crawford     for(int i = 0; i < 3; ++i)
2386018f5a7eSEwan Crawford     {
2387018f5a7eSEwan Crawford         if (!GetFrameVarAsUnsigned(frame_sp, coord_expressions[i], current_coord[i]))
2388018f5a7eSEwan Crawford             return false;
2389018f5a7eSEwan Crawford 
2390018f5a7eSEwan Crawford         if (log)
2391018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::KernelBreakpointHit, %s = %" PRIu64, coord_expressions[i], current_coord[i]);
2392018f5a7eSEwan Crawford     }
2393018f5a7eSEwan Crawford 
2394018f5a7eSEwan Crawford     // Check if the current kernel invocation coordinate matches our target coordinate
2395018f5a7eSEwan Crawford     if (current_coord[0] == static_cast<uint64_t>(target_coord[0]) &&
2396018f5a7eSEwan Crawford         current_coord[1] == static_cast<uint64_t>(target_coord[1]) &&
2397018f5a7eSEwan Crawford         current_coord[2] == static_cast<uint64_t>(target_coord[2]))
2398018f5a7eSEwan Crawford     {
2399018f5a7eSEwan Crawford         if (log)
2400018f5a7eSEwan Crawford              log->Printf("RenderScriptRuntime::KernelBreakpointHit, BREAKING %" PRIu64 ", %" PRIu64 ", %" PRIu64,
2401018f5a7eSEwan Crawford                          current_coord[0], current_coord[1], current_coord[2]);
2402018f5a7eSEwan Crawford 
2403018f5a7eSEwan Crawford         BreakpointSP breakpoint_sp = context.GetTargetPtr()->GetBreakpointByID(break_id);
2404018f5a7eSEwan Crawford         assert(breakpoint_sp != nullptr && "Error: Couldn't find breakpoint matching break id for callback");
2405018f5a7eSEwan Crawford         breakpoint_sp->SetEnabled(false); // Optimise since conditional breakpoint should only be hit once.
2406018f5a7eSEwan Crawford         return true;
2407018f5a7eSEwan Crawford     }
2408018f5a7eSEwan Crawford 
2409018f5a7eSEwan Crawford     // No match on coordinate
2410018f5a7eSEwan Crawford     return false;
2411018f5a7eSEwan Crawford }
2412018f5a7eSEwan Crawford 
2413018f5a7eSEwan Crawford // Tries to set a breakpoint on the start of a kernel, resolved using the kernel name.
2414018f5a7eSEwan Crawford // Argument 'coords', represents a three dimensional coordinate which can be used to specify
2415018f5a7eSEwan Crawford // a single kernel instance to break on. If this is set then we add a callback to the breakpoint.
24164640cde1SColin Riley void
2417018f5a7eSEwan Crawford RenderScriptRuntime::PlaceBreakpointOnKernel(Stream &strm, const char* name, const std::array<int,3> coords,
2418018f5a7eSEwan Crawford                                              Error& error, TargetSP target)
24194640cde1SColin Riley {
24204640cde1SColin Riley     if (!name)
24214640cde1SColin Riley     {
24224640cde1SColin Riley         error.SetErrorString("invalid kernel name");
24234640cde1SColin Riley         return;
24244640cde1SColin Riley     }
24254640cde1SColin Riley 
24267dc7771cSEwan Crawford     InitSearchFilter(target);
242798156583SEwan Crawford 
24284640cde1SColin Riley     ConstString kernel_name(name);
24297dc7771cSEwan Crawford     BreakpointSP bp = CreateKernelBreakpoint(kernel_name);
2430018f5a7eSEwan Crawford 
2431018f5a7eSEwan Crawford     // We have a conditional breakpoint on a specific coordinate
2432018f5a7eSEwan Crawford     if (coords[0] != -1)
2433018f5a7eSEwan Crawford     {
2434018f5a7eSEwan Crawford         strm.Printf("Conditional kernel breakpoint on coordinate %d, %d, %d", coords[0], coords[1], coords[2]);
2435018f5a7eSEwan Crawford         strm.EOL();
2436018f5a7eSEwan Crawford 
2437018f5a7eSEwan Crawford         // Allocate memory for the baton, and copy over coordinate
2438018f5a7eSEwan Crawford         int* baton = new int[3];
2439018f5a7eSEwan Crawford         baton[0] = coords[0]; baton[1] = coords[1]; baton[2] = coords[2];
2440018f5a7eSEwan Crawford 
2441018f5a7eSEwan Crawford         // Create a callback that will be invoked everytime the breakpoint is hit.
2442018f5a7eSEwan Crawford         // The baton object passed to the handler is the target coordinate we want to break on.
2443018f5a7eSEwan Crawford         bp->SetCallback(KernelBreakpointHit, baton, true);
2444018f5a7eSEwan Crawford 
2445018f5a7eSEwan Crawford         // Store a shared pointer to the baton, so the memory will eventually be cleaned up after destruction
2446018f5a7eSEwan Crawford         m_conditional_breaks[bp->GetID()] = std::shared_ptr<int>(baton);
2447018f5a7eSEwan Crawford     }
2448018f5a7eSEwan Crawford 
244998156583SEwan Crawford     if (bp)
245098156583SEwan Crawford         bp->GetDescription(&strm, lldb::eDescriptionLevelInitial, false);
24514640cde1SColin Riley }
24524640cde1SColin Riley 
24534640cde1SColin Riley void
24545ec532a9SColin Riley RenderScriptRuntime::DumpModules(Stream &strm) const
24555ec532a9SColin Riley {
24565ec532a9SColin Riley     strm.Printf("RenderScript Modules:");
24575ec532a9SColin Riley     strm.EOL();
24585ec532a9SColin Riley     strm.IndentMore();
24595ec532a9SColin Riley     for (const auto &module : m_rsmodules)
24605ec532a9SColin Riley     {
24614640cde1SColin Riley         module->Dump(strm);
24625ec532a9SColin Riley     }
24635ec532a9SColin Riley     strm.IndentLess();
24645ec532a9SColin Riley }
24655ec532a9SColin Riley 
246678f339d1SEwan Crawford RenderScriptRuntime::ScriptDetails*
246778f339d1SEwan Crawford RenderScriptRuntime::LookUpScript(addr_t address, bool create)
246878f339d1SEwan Crawford {
246978f339d1SEwan Crawford     for (const auto & s : m_scripts)
247078f339d1SEwan Crawford     {
247178f339d1SEwan Crawford         if (s->script.isValid())
247278f339d1SEwan Crawford             if (*s->script == address)
247378f339d1SEwan Crawford                 return s.get();
247478f339d1SEwan Crawford     }
247578f339d1SEwan Crawford     if (create)
247678f339d1SEwan Crawford     {
247778f339d1SEwan Crawford         std::unique_ptr<ScriptDetails> s(new ScriptDetails);
247878f339d1SEwan Crawford         s->script = address;
247978f339d1SEwan Crawford         m_scripts.push_back(std::move(s));
2480d10ca9deSEwan Crawford         return m_scripts.back().get();
248178f339d1SEwan Crawford     }
248278f339d1SEwan Crawford     return nullptr;
248378f339d1SEwan Crawford }
248478f339d1SEwan Crawford 
248578f339d1SEwan Crawford RenderScriptRuntime::AllocationDetails*
248678f339d1SEwan Crawford RenderScriptRuntime::LookUpAllocation(addr_t address, bool create)
248778f339d1SEwan Crawford {
248878f339d1SEwan Crawford     for (const auto & a : m_allocations)
248978f339d1SEwan Crawford     {
249078f339d1SEwan Crawford         if (a->address.isValid())
249178f339d1SEwan Crawford             if (*a->address == address)
249278f339d1SEwan Crawford                 return a.get();
249378f339d1SEwan Crawford     }
249478f339d1SEwan Crawford     if (create)
249578f339d1SEwan Crawford     {
249678f339d1SEwan Crawford         std::unique_ptr<AllocationDetails> a(new AllocationDetails);
249778f339d1SEwan Crawford         a->address = address;
249878f339d1SEwan Crawford         m_allocations.push_back(std::move(a));
2499d10ca9deSEwan Crawford         return m_allocations.back().get();
250078f339d1SEwan Crawford     }
250178f339d1SEwan Crawford     return nullptr;
250278f339d1SEwan Crawford }
250378f339d1SEwan Crawford 
25045ec532a9SColin Riley void
25055ec532a9SColin Riley RSModuleDescriptor::Dump(Stream &strm) const
25065ec532a9SColin Riley {
25075ec532a9SColin Riley     strm.Indent();
25085ec532a9SColin Riley     m_module->GetFileSpec().Dump(&strm);
25094640cde1SColin Riley     if(m_module->GetNumCompileUnits())
25104640cde1SColin Riley     {
25114640cde1SColin Riley         strm.Indent("Debug info loaded.");
25124640cde1SColin Riley     }
25134640cde1SColin Riley     else
25144640cde1SColin Riley     {
25154640cde1SColin Riley         strm.Indent("Debug info does not exist.");
25164640cde1SColin Riley     }
25175ec532a9SColin Riley     strm.EOL();
25185ec532a9SColin Riley     strm.IndentMore();
25195ec532a9SColin Riley     strm.Indent();
2520189598edSColin Riley     strm.Printf("Globals: %" PRIu64, static_cast<uint64_t>(m_globals.size()));
25215ec532a9SColin Riley     strm.EOL();
25225ec532a9SColin Riley     strm.IndentMore();
25235ec532a9SColin Riley     for (const auto &global : m_globals)
25245ec532a9SColin Riley     {
25255ec532a9SColin Riley         global.Dump(strm);
25265ec532a9SColin Riley     }
25275ec532a9SColin Riley     strm.IndentLess();
25285ec532a9SColin Riley     strm.Indent();
2529189598edSColin Riley     strm.Printf("Kernels: %" PRIu64, static_cast<uint64_t>(m_kernels.size()));
25305ec532a9SColin Riley     strm.EOL();
25315ec532a9SColin Riley     strm.IndentMore();
25325ec532a9SColin Riley     for (const auto &kernel : m_kernels)
25335ec532a9SColin Riley     {
25345ec532a9SColin Riley         kernel.Dump(strm);
25355ec532a9SColin Riley     }
25364640cde1SColin Riley     strm.Printf("Pragmas: %"  PRIu64 , static_cast<uint64_t>(m_pragmas.size()));
25374640cde1SColin Riley     strm.EOL();
25384640cde1SColin Riley     strm.IndentMore();
25394640cde1SColin Riley     for (const auto &key_val : m_pragmas)
25404640cde1SColin Riley     {
25414640cde1SColin Riley         strm.Printf("%s: %s", key_val.first.c_str(), key_val.second.c_str());
25424640cde1SColin Riley         strm.EOL();
25434640cde1SColin Riley     }
25445ec532a9SColin Riley     strm.IndentLess(4);
25455ec532a9SColin Riley }
25465ec532a9SColin Riley 
25475ec532a9SColin Riley void
25485ec532a9SColin Riley RSGlobalDescriptor::Dump(Stream &strm) const
25495ec532a9SColin Riley {
25505ec532a9SColin Riley     strm.Indent(m_name.AsCString());
25514640cde1SColin Riley     VariableList var_list;
25524640cde1SColin Riley     m_module->m_module->FindGlobalVariables(m_name, nullptr, true, 1U, var_list);
25534640cde1SColin Riley     if (var_list.GetSize() == 1)
25544640cde1SColin Riley     {
25554640cde1SColin Riley         auto var = var_list.GetVariableAtIndex(0);
25564640cde1SColin Riley         auto type = var->GetType();
25574640cde1SColin Riley         if(type)
25584640cde1SColin Riley         {
25594640cde1SColin Riley             strm.Printf(" - ");
25604640cde1SColin Riley             type->DumpTypeName(&strm);
25614640cde1SColin Riley         }
25624640cde1SColin Riley         else
25634640cde1SColin Riley         {
25644640cde1SColin Riley             strm.Printf(" - Unknown Type");
25654640cde1SColin Riley         }
25664640cde1SColin Riley     }
25674640cde1SColin Riley     else
25684640cde1SColin Riley     {
25694640cde1SColin Riley         strm.Printf(" - variable identified, but not found in binary");
25704640cde1SColin Riley         const Symbol* s = m_module->m_module->FindFirstSymbolWithNameAndType(m_name, eSymbolTypeData);
25714640cde1SColin Riley         if (s)
25724640cde1SColin Riley         {
25734640cde1SColin Riley             strm.Printf(" (symbol exists) ");
25744640cde1SColin Riley         }
25754640cde1SColin Riley     }
25764640cde1SColin Riley 
25775ec532a9SColin Riley     strm.EOL();
25785ec532a9SColin Riley }
25795ec532a9SColin Riley 
25805ec532a9SColin Riley void
25815ec532a9SColin Riley RSKernelDescriptor::Dump(Stream &strm) const
25825ec532a9SColin Riley {
25835ec532a9SColin Riley     strm.Indent(m_name.AsCString());
25845ec532a9SColin Riley     strm.EOL();
25855ec532a9SColin Riley }
25865ec532a9SColin Riley 
25875ec532a9SColin Riley class CommandObjectRenderScriptRuntimeModuleProbe : public CommandObjectParsed
25885ec532a9SColin Riley {
25895ec532a9SColin Riley public:
25905ec532a9SColin Riley     CommandObjectRenderScriptRuntimeModuleProbe(CommandInterpreter &interpreter)
25915ec532a9SColin Riley         : CommandObjectParsed(interpreter, "renderscript module probe",
25925ec532a9SColin Riley                               "Initiates a Probe of all loaded modules for kernels and other renderscript objects.",
25935ec532a9SColin Riley                               "renderscript module probe",
2594e87764f2SEnrico Granata                               eCommandRequiresTarget | eCommandRequiresProcess | eCommandProcessMustBeLaunched)
25955ec532a9SColin Riley     {
25965ec532a9SColin Riley     }
25975ec532a9SColin Riley 
2598*222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeModuleProbe() override = default;
25995ec532a9SColin Riley 
26005ec532a9SColin Riley     bool
2601*222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
26025ec532a9SColin Riley     {
26035ec532a9SColin Riley         const size_t argc = command.GetArgumentCount();
26045ec532a9SColin Riley         if (argc == 0)
26055ec532a9SColin Riley         {
26065ec532a9SColin Riley             Target *target = m_exe_ctx.GetTargetPtr();
26075ec532a9SColin Riley             RenderScriptRuntime *runtime =
26085ec532a9SColin Riley                 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
26095ec532a9SColin Riley             auto module_list = target->GetImages();
26105ec532a9SColin Riley             bool new_rs_details = runtime->ProbeModules(module_list);
26115ec532a9SColin Riley             if (new_rs_details)
26125ec532a9SColin Riley             {
26135ec532a9SColin Riley                 result.AppendMessage("New renderscript modules added to runtime model.");
26145ec532a9SColin Riley             }
26155ec532a9SColin Riley             result.SetStatus(eReturnStatusSuccessFinishResult);
26165ec532a9SColin Riley             return true;
26175ec532a9SColin Riley         }
26185ec532a9SColin Riley 
26195ec532a9SColin Riley         result.AppendErrorWithFormat("'%s' takes no arguments", m_cmd_name.c_str());
26205ec532a9SColin Riley         result.SetStatus(eReturnStatusFailed);
26215ec532a9SColin Riley         return false;
26225ec532a9SColin Riley     }
26235ec532a9SColin Riley };
26245ec532a9SColin Riley 
26255ec532a9SColin Riley class CommandObjectRenderScriptRuntimeModuleDump : public CommandObjectParsed
26265ec532a9SColin Riley {
26275ec532a9SColin Riley public:
26285ec532a9SColin Riley     CommandObjectRenderScriptRuntimeModuleDump(CommandInterpreter &interpreter)
26295ec532a9SColin Riley         : CommandObjectParsed(interpreter, "renderscript module dump",
26305ec532a9SColin Riley                               "Dumps renderscript specific information for all modules.", "renderscript module dump",
2631e87764f2SEnrico Granata                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
26325ec532a9SColin Riley     {
26335ec532a9SColin Riley     }
26345ec532a9SColin Riley 
2635*222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeModuleDump() override = default;
26365ec532a9SColin Riley 
26375ec532a9SColin Riley     bool
2638*222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
26395ec532a9SColin Riley     {
26405ec532a9SColin Riley         RenderScriptRuntime *runtime =
26415ec532a9SColin Riley             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
26425ec532a9SColin Riley         runtime->DumpModules(result.GetOutputStream());
26435ec532a9SColin Riley         result.SetStatus(eReturnStatusSuccessFinishResult);
26445ec532a9SColin Riley         return true;
26455ec532a9SColin Riley     }
26465ec532a9SColin Riley };
26475ec532a9SColin Riley 
26485ec532a9SColin Riley class CommandObjectRenderScriptRuntimeModule : public CommandObjectMultiword
26495ec532a9SColin Riley {
26505ec532a9SColin Riley public:
26515ec532a9SColin Riley     CommandObjectRenderScriptRuntimeModule(CommandInterpreter &interpreter)
26525ec532a9SColin Riley         : CommandObjectMultiword(interpreter, "renderscript module", "Commands that deal with renderscript modules.",
26535ec532a9SColin Riley                                  NULL)
26545ec532a9SColin Riley     {
26555ec532a9SColin Riley         LoadSubCommand("probe", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleProbe(interpreter)));
26565ec532a9SColin Riley         LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleDump(interpreter)));
26575ec532a9SColin Riley     }
26585ec532a9SColin Riley 
2659*222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeModule() override = default;
26605ec532a9SColin Riley };
26615ec532a9SColin Riley 
26624640cde1SColin Riley class CommandObjectRenderScriptRuntimeKernelList : public CommandObjectParsed
26634640cde1SColin Riley {
26644640cde1SColin Riley public:
26654640cde1SColin Riley     CommandObjectRenderScriptRuntimeKernelList(CommandInterpreter &interpreter)
26664640cde1SColin Riley         : CommandObjectParsed(interpreter, "renderscript kernel list",
26674640cde1SColin Riley                               "Lists renderscript kernel names and associated script resources.", "renderscript kernel list",
26684640cde1SColin Riley                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
26694640cde1SColin Riley     {
26704640cde1SColin Riley     }
26714640cde1SColin Riley 
2672*222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernelList() override = default;
26734640cde1SColin Riley 
26744640cde1SColin Riley     bool
2675*222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
26764640cde1SColin Riley     {
26774640cde1SColin Riley         RenderScriptRuntime *runtime =
26784640cde1SColin Riley             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
26794640cde1SColin Riley         runtime->DumpKernels(result.GetOutputStream());
26804640cde1SColin Riley         result.SetStatus(eReturnStatusSuccessFinishResult);
26814640cde1SColin Riley         return true;
26824640cde1SColin Riley     }
26834640cde1SColin Riley };
26844640cde1SColin Riley 
26857dc7771cSEwan Crawford class CommandObjectRenderScriptRuntimeKernelBreakpointSet : public CommandObjectParsed
26864640cde1SColin Riley {
26874640cde1SColin Riley public:
26887dc7771cSEwan Crawford     CommandObjectRenderScriptRuntimeKernelBreakpointSet(CommandInterpreter &interpreter)
26897dc7771cSEwan Crawford         : CommandObjectParsed(interpreter, "renderscript kernel breakpoint set",
2690018f5a7eSEwan Crawford                               "Sets a breakpoint on a renderscript kernel.", "renderscript kernel breakpoint set <kernel_name> [-c x,y,z]",
2691018f5a7eSEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched | eCommandProcessMustBePaused), m_options(interpreter)
26924640cde1SColin Riley     {
26934640cde1SColin Riley     }
26944640cde1SColin Riley 
2695*222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernelBreakpointSet() override = default;
2696*222b937cSEugene Zelenko 
2697*222b937cSEugene Zelenko     Options*
2698*222b937cSEugene Zelenko     GetOptions() override
2699018f5a7eSEwan Crawford     {
2700018f5a7eSEwan Crawford         return &m_options;
2701018f5a7eSEwan Crawford     }
2702018f5a7eSEwan Crawford 
2703018f5a7eSEwan Crawford     class CommandOptions : public Options
2704018f5a7eSEwan Crawford     {
2705018f5a7eSEwan Crawford     public:
2706018f5a7eSEwan Crawford         CommandOptions(CommandInterpreter &interpreter) : Options(interpreter)
2707018f5a7eSEwan Crawford         {
2708018f5a7eSEwan Crawford         }
2709018f5a7eSEwan Crawford 
2710*222b937cSEugene Zelenko         ~CommandOptions() override = default;
2711018f5a7eSEwan Crawford 
2712*222b937cSEugene Zelenko         Error
2713*222b937cSEugene Zelenko         SetOptionValue(uint32_t option_idx, const char *option_arg) override
2714018f5a7eSEwan Crawford         {
2715018f5a7eSEwan Crawford             Error error;
2716018f5a7eSEwan Crawford             const int short_option = m_getopt_table[option_idx].val;
2717018f5a7eSEwan Crawford 
2718018f5a7eSEwan Crawford             switch (short_option)
2719018f5a7eSEwan Crawford             {
2720018f5a7eSEwan Crawford                 case 'c':
2721018f5a7eSEwan Crawford                     if (!ParseCoordinate(option_arg))
2722018f5a7eSEwan Crawford                         error.SetErrorStringWithFormat("Couldn't parse coordinate '%s', should be in format 'x,y,z'.", option_arg);
2723018f5a7eSEwan Crawford                     break;
2724018f5a7eSEwan Crawford                 default:
2725018f5a7eSEwan Crawford                     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
2726018f5a7eSEwan Crawford                     break;
2727018f5a7eSEwan Crawford             }
2728018f5a7eSEwan Crawford             return error;
2729018f5a7eSEwan Crawford         }
2730018f5a7eSEwan Crawford 
2731018f5a7eSEwan Crawford         // -c takes an argument of the form 'num[,num][,num]'.
2732018f5a7eSEwan Crawford         // Where 'id_cstr' is this argument with the whitespace trimmed.
2733018f5a7eSEwan Crawford         // Missing coordinates are defaulted to zero.
2734018f5a7eSEwan Crawford         bool
2735018f5a7eSEwan Crawford         ParseCoordinate(const char* id_cstr)
2736018f5a7eSEwan Crawford         {
2737018f5a7eSEwan Crawford             RegularExpression regex;
2738018f5a7eSEwan Crawford             RegularExpression::Match regex_match(3);
2739018f5a7eSEwan Crawford 
2740018f5a7eSEwan Crawford             bool matched = false;
2741018f5a7eSEwan Crawford             if(regex.Compile("^([0-9]+),([0-9]+),([0-9]+)$") && regex.Execute(id_cstr, &regex_match))
2742018f5a7eSEwan Crawford                 matched = true;
2743018f5a7eSEwan Crawford             else if(regex.Compile("^([0-9]+),([0-9]+)$") && regex.Execute(id_cstr, &regex_match))
2744018f5a7eSEwan Crawford                 matched = true;
2745018f5a7eSEwan Crawford             else if(regex.Compile("^([0-9]+)$") && regex.Execute(id_cstr, &regex_match))
2746018f5a7eSEwan Crawford                 matched = true;
2747018f5a7eSEwan Crawford             for(uint32_t i = 0; i < 3; i++)
2748018f5a7eSEwan Crawford             {
2749018f5a7eSEwan Crawford                 std::string group;
2750018f5a7eSEwan Crawford                 if(regex_match.GetMatchAtIndex(id_cstr, i + 1, group))
2751018f5a7eSEwan Crawford                     m_coord[i] = (uint32_t)strtoul(group.c_str(), NULL, 0);
2752018f5a7eSEwan Crawford                 else
2753018f5a7eSEwan Crawford                     m_coord[i] = 0;
2754018f5a7eSEwan Crawford             }
2755018f5a7eSEwan Crawford             return matched;
2756018f5a7eSEwan Crawford         }
2757018f5a7eSEwan Crawford 
2758018f5a7eSEwan Crawford         void
2759*222b937cSEugene Zelenko         OptionParsingStarting() override
2760018f5a7eSEwan Crawford         {
2761018f5a7eSEwan Crawford             // -1 means the -c option hasn't been set
2762018f5a7eSEwan Crawford             m_coord[0] = -1;
2763018f5a7eSEwan Crawford             m_coord[1] = -1;
2764018f5a7eSEwan Crawford             m_coord[2] = -1;
2765018f5a7eSEwan Crawford         }
2766018f5a7eSEwan Crawford 
2767018f5a7eSEwan Crawford         const OptionDefinition*
2768*222b937cSEugene Zelenko         GetDefinitions() override
2769018f5a7eSEwan Crawford         {
2770018f5a7eSEwan Crawford             return g_option_table;
2771018f5a7eSEwan Crawford         }
2772018f5a7eSEwan Crawford 
2773018f5a7eSEwan Crawford         static OptionDefinition g_option_table[];
2774018f5a7eSEwan Crawford         std::array<int,3> m_coord;
2775018f5a7eSEwan Crawford     };
2776018f5a7eSEwan Crawford 
27774640cde1SColin Riley     bool
2778*222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
27794640cde1SColin Riley     {
27804640cde1SColin Riley         const size_t argc = command.GetArgumentCount();
2781018f5a7eSEwan Crawford         if (argc < 1)
27824640cde1SColin Riley         {
2783018f5a7eSEwan Crawford             result.AppendErrorWithFormat("'%s' takes 1 argument of kernel name, and an optional coordinate.", m_cmd_name.c_str());
2784018f5a7eSEwan Crawford             result.SetStatus(eReturnStatusFailed);
2785018f5a7eSEwan Crawford             return false;
2786018f5a7eSEwan Crawford         }
2787018f5a7eSEwan Crawford 
27884640cde1SColin Riley         RenderScriptRuntime *runtime =
27894640cde1SColin Riley                 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
27904640cde1SColin Riley 
27914640cde1SColin Riley         Error error;
2792018f5a7eSEwan Crawford         runtime->PlaceBreakpointOnKernel(result.GetOutputStream(), command.GetArgumentAtIndex(0), m_options.m_coord,
279398156583SEwan Crawford                                          error, m_exe_ctx.GetTargetSP());
27944640cde1SColin Riley 
27954640cde1SColin Riley         if (error.Success())
27964640cde1SColin Riley         {
27974640cde1SColin Riley             result.AppendMessage("Breakpoint(s) created");
27984640cde1SColin Riley             result.SetStatus(eReturnStatusSuccessFinishResult);
27994640cde1SColin Riley             return true;
28004640cde1SColin Riley         }
28014640cde1SColin Riley         result.SetStatus(eReturnStatusFailed);
28024640cde1SColin Riley         result.AppendErrorWithFormat("Error: %s", error.AsCString());
28034640cde1SColin Riley         return false;
28044640cde1SColin Riley     }
28054640cde1SColin Riley 
2806018f5a7eSEwan Crawford private:
2807018f5a7eSEwan Crawford     CommandOptions m_options;
28084640cde1SColin Riley };
28094640cde1SColin Riley 
2810018f5a7eSEwan Crawford OptionDefinition
2811018f5a7eSEwan Crawford CommandObjectRenderScriptRuntimeKernelBreakpointSet::CommandOptions::g_option_table[] =
2812018f5a7eSEwan Crawford {
2813018f5a7eSEwan Crawford     { LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeValue,
2814018f5a7eSEwan Crawford       "Set a breakpoint on a single invocation of the kernel with specified coordinate.\n"
2815018f5a7eSEwan Crawford       "Coordinate takes the form 'x[,y][,z] where x,y,z are positive integers representing kernel dimensions. "
2816018f5a7eSEwan Crawford       "Any unset dimensions will be defaulted to zero."},
2817018f5a7eSEwan Crawford     { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
2818018f5a7eSEwan Crawford };
2819018f5a7eSEwan Crawford 
28207dc7771cSEwan Crawford class CommandObjectRenderScriptRuntimeKernelBreakpointAll : public CommandObjectParsed
28217dc7771cSEwan Crawford {
28227dc7771cSEwan Crawford public:
28237dc7771cSEwan Crawford     CommandObjectRenderScriptRuntimeKernelBreakpointAll(CommandInterpreter &interpreter)
28247dc7771cSEwan Crawford         : CommandObjectParsed(interpreter, "renderscript kernel breakpoint all",
28257dc7771cSEwan Crawford                               "Automatically sets a breakpoint on all renderscript kernels that are or will be loaded.\n"
28267dc7771cSEwan Crawford                               "Disabling option means breakpoints will no longer be set on any kernels loaded in the future, "
28277dc7771cSEwan Crawford                               "but does not remove currently set breakpoints.",
28287dc7771cSEwan Crawford                               "renderscript kernel breakpoint all <enable/disable>",
28297dc7771cSEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched | eCommandProcessMustBePaused)
28307dc7771cSEwan Crawford     {
28317dc7771cSEwan Crawford     }
28327dc7771cSEwan Crawford 
2833*222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernelBreakpointAll() override = default;
28347dc7771cSEwan Crawford 
28357dc7771cSEwan Crawford     bool
2836*222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
28377dc7771cSEwan Crawford     {
28387dc7771cSEwan Crawford         const size_t argc = command.GetArgumentCount();
28397dc7771cSEwan Crawford         if (argc != 1)
28407dc7771cSEwan Crawford         {
28417dc7771cSEwan Crawford             result.AppendErrorWithFormat("'%s' takes 1 argument of 'enable' or 'disable'", m_cmd_name.c_str());
28427dc7771cSEwan Crawford             result.SetStatus(eReturnStatusFailed);
28437dc7771cSEwan Crawford             return false;
28447dc7771cSEwan Crawford         }
28457dc7771cSEwan Crawford 
28467dc7771cSEwan Crawford         RenderScriptRuntime *runtime =
28477dc7771cSEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
28487dc7771cSEwan Crawford 
28497dc7771cSEwan Crawford         bool do_break = false;
28507dc7771cSEwan Crawford         const char* argument = command.GetArgumentAtIndex(0);
28517dc7771cSEwan Crawford         if (strcmp(argument, "enable") == 0)
28527dc7771cSEwan Crawford         {
28537dc7771cSEwan Crawford             do_break = true;
28547dc7771cSEwan Crawford             result.AppendMessage("Breakpoints will be set on all kernels.");
28557dc7771cSEwan Crawford         }
28567dc7771cSEwan Crawford         else if (strcmp(argument, "disable") == 0)
28577dc7771cSEwan Crawford         {
28587dc7771cSEwan Crawford             do_break = false;
28597dc7771cSEwan Crawford             result.AppendMessage("Breakpoints will not be set on any new kernels.");
28607dc7771cSEwan Crawford         }
28617dc7771cSEwan Crawford         else
28627dc7771cSEwan Crawford         {
28637dc7771cSEwan Crawford             result.AppendErrorWithFormat("Argument must be either 'enable' or 'disable'");
28647dc7771cSEwan Crawford             result.SetStatus(eReturnStatusFailed);
28657dc7771cSEwan Crawford             return false;
28667dc7771cSEwan Crawford         }
28677dc7771cSEwan Crawford 
28687dc7771cSEwan Crawford         runtime->SetBreakAllKernels(do_break, m_exe_ctx.GetTargetSP());
28697dc7771cSEwan Crawford 
28707dc7771cSEwan Crawford         result.SetStatus(eReturnStatusSuccessFinishResult);
28717dc7771cSEwan Crawford         return true;
28727dc7771cSEwan Crawford     }
28737dc7771cSEwan Crawford };
28747dc7771cSEwan Crawford 
28757dc7771cSEwan Crawford class CommandObjectRenderScriptRuntimeKernelBreakpoint : public CommandObjectMultiword
28767dc7771cSEwan Crawford {
28777dc7771cSEwan Crawford public:
28787dc7771cSEwan Crawford     CommandObjectRenderScriptRuntimeKernelBreakpoint(CommandInterpreter &interpreter)
28797dc7771cSEwan Crawford         : CommandObjectMultiword(interpreter, "renderscript kernel", "Commands that generate breakpoints on renderscript kernels.",
28807dc7771cSEwan Crawford                                  nullptr)
28817dc7771cSEwan Crawford     {
28827dc7771cSEwan Crawford         LoadSubCommand("set", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointSet(interpreter)));
28837dc7771cSEwan Crawford         LoadSubCommand("all", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointAll(interpreter)));
28847dc7771cSEwan Crawford     }
28857dc7771cSEwan Crawford 
2886*222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernelBreakpoint() override = default;
28877dc7771cSEwan Crawford };
28887dc7771cSEwan Crawford 
28894640cde1SColin Riley class CommandObjectRenderScriptRuntimeKernel : public CommandObjectMultiword
28904640cde1SColin Riley {
28914640cde1SColin Riley public:
28924640cde1SColin Riley     CommandObjectRenderScriptRuntimeKernel(CommandInterpreter &interpreter)
28934640cde1SColin Riley         : CommandObjectMultiword(interpreter, "renderscript kernel", "Commands that deal with renderscript kernels.",
28944640cde1SColin Riley                                  NULL)
28954640cde1SColin Riley     {
28964640cde1SColin Riley         LoadSubCommand("list", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelList(interpreter)));
28974640cde1SColin Riley         LoadSubCommand("breakpoint", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpoint(interpreter)));
28984640cde1SColin Riley     }
28994640cde1SColin Riley 
2900*222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernel() override = default;
29014640cde1SColin Riley };
29024640cde1SColin Riley 
29034640cde1SColin Riley class CommandObjectRenderScriptRuntimeContextDump : public CommandObjectParsed
29044640cde1SColin Riley {
29054640cde1SColin Riley public:
29064640cde1SColin Riley     CommandObjectRenderScriptRuntimeContextDump(CommandInterpreter &interpreter)
29074640cde1SColin Riley         : CommandObjectParsed(interpreter, "renderscript context dump",
29084640cde1SColin Riley                               "Dumps renderscript context information.", "renderscript context dump",
29094640cde1SColin Riley                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
29104640cde1SColin Riley     {
29114640cde1SColin Riley     }
29124640cde1SColin Riley 
2913*222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeContextDump() override = default;
29144640cde1SColin Riley 
29154640cde1SColin Riley     bool
2916*222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
29174640cde1SColin Riley     {
29184640cde1SColin Riley         RenderScriptRuntime *runtime =
29194640cde1SColin Riley             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
29204640cde1SColin Riley         runtime->DumpContexts(result.GetOutputStream());
29214640cde1SColin Riley         result.SetStatus(eReturnStatusSuccessFinishResult);
29224640cde1SColin Riley         return true;
29234640cde1SColin Riley     }
29244640cde1SColin Riley };
29254640cde1SColin Riley 
29264640cde1SColin Riley class CommandObjectRenderScriptRuntimeContext : public CommandObjectMultiword
29274640cde1SColin Riley {
29284640cde1SColin Riley public:
29294640cde1SColin Riley     CommandObjectRenderScriptRuntimeContext(CommandInterpreter &interpreter)
29304640cde1SColin Riley         : CommandObjectMultiword(interpreter, "renderscript context", "Commands that deal with renderscript contexts.",
29314640cde1SColin Riley                                  NULL)
29324640cde1SColin Riley     {
29334640cde1SColin Riley         LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeContextDump(interpreter)));
29344640cde1SColin Riley     }
29354640cde1SColin Riley 
2936*222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeContext() override = default;
29374640cde1SColin Riley };
29384640cde1SColin Riley 
2939a0f08674SEwan Crawford class CommandObjectRenderScriptRuntimeAllocationDump : public CommandObjectParsed
2940a0f08674SEwan Crawford {
2941a0f08674SEwan Crawford public:
2942a0f08674SEwan Crawford     CommandObjectRenderScriptRuntimeAllocationDump(CommandInterpreter &interpreter)
2943a0f08674SEwan Crawford         : CommandObjectParsed(interpreter, "renderscript allocation dump",
2944a0f08674SEwan Crawford                               "Displays the contents of a particular allocation", "renderscript allocation dump <ID>",
2945a0f08674SEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched), m_options(interpreter)
2946a0f08674SEwan Crawford     {
2947a0f08674SEwan Crawford     }
2948a0f08674SEwan Crawford 
2949*222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocationDump() override = default;
2950*222b937cSEugene Zelenko 
2951*222b937cSEugene Zelenko     Options*
2952*222b937cSEugene Zelenko     GetOptions() override
2953a0f08674SEwan Crawford     {
2954a0f08674SEwan Crawford         return &m_options;
2955a0f08674SEwan Crawford     }
2956a0f08674SEwan Crawford 
2957a0f08674SEwan Crawford     class CommandOptions : public Options
2958a0f08674SEwan Crawford     {
2959a0f08674SEwan Crawford     public:
2960a0f08674SEwan Crawford         CommandOptions(CommandInterpreter &interpreter) : Options(interpreter)
2961a0f08674SEwan Crawford         {
2962a0f08674SEwan Crawford         }
2963a0f08674SEwan Crawford 
2964*222b937cSEugene Zelenko         ~CommandOptions() override = default;
2965a0f08674SEwan Crawford 
2966*222b937cSEugene Zelenko         Error
2967*222b937cSEugene Zelenko         SetOptionValue(uint32_t option_idx, const char *option_arg) override
2968a0f08674SEwan Crawford         {
2969a0f08674SEwan Crawford             Error error;
2970a0f08674SEwan Crawford             const int short_option = m_getopt_table[option_idx].val;
2971a0f08674SEwan Crawford 
2972a0f08674SEwan Crawford             switch (short_option)
2973a0f08674SEwan Crawford             {
2974a0f08674SEwan Crawford                 case 'f':
2975a0f08674SEwan Crawford                     m_outfile.SetFile(option_arg, true);
2976a0f08674SEwan Crawford                     if (m_outfile.Exists())
2977a0f08674SEwan Crawford                     {
2978a0f08674SEwan Crawford                         m_outfile.Clear();
2979a0f08674SEwan Crawford                         error.SetErrorStringWithFormat("file already exists: '%s'", option_arg);
2980a0f08674SEwan Crawford                     }
2981a0f08674SEwan Crawford                     break;
2982a0f08674SEwan Crawford                 default:
2983a0f08674SEwan Crawford                     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
2984a0f08674SEwan Crawford                     break;
2985a0f08674SEwan Crawford             }
2986a0f08674SEwan Crawford             return error;
2987a0f08674SEwan Crawford         }
2988a0f08674SEwan Crawford 
2989a0f08674SEwan Crawford         void
2990*222b937cSEugene Zelenko         OptionParsingStarting() override
2991a0f08674SEwan Crawford         {
2992a0f08674SEwan Crawford             m_outfile.Clear();
2993a0f08674SEwan Crawford         }
2994a0f08674SEwan Crawford 
2995a0f08674SEwan Crawford         const OptionDefinition*
2996*222b937cSEugene Zelenko         GetDefinitions() override
2997a0f08674SEwan Crawford         {
2998a0f08674SEwan Crawford             return g_option_table;
2999a0f08674SEwan Crawford         }
3000a0f08674SEwan Crawford 
3001a0f08674SEwan Crawford         static OptionDefinition g_option_table[];
3002a0f08674SEwan Crawford         FileSpec m_outfile;
3003a0f08674SEwan Crawford     };
3004a0f08674SEwan Crawford 
3005a0f08674SEwan Crawford     bool
3006*222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
3007a0f08674SEwan Crawford     {
3008a0f08674SEwan Crawford         const size_t argc = command.GetArgumentCount();
3009a0f08674SEwan Crawford         if (argc < 1)
3010a0f08674SEwan Crawford         {
3011a0f08674SEwan Crawford             result.AppendErrorWithFormat("'%s' takes 1 argument, an allocation ID. As well as an optional -f argument",
3012a0f08674SEwan Crawford                                          m_cmd_name.c_str());
3013a0f08674SEwan Crawford             result.SetStatus(eReturnStatusFailed);
3014a0f08674SEwan Crawford             return false;
3015a0f08674SEwan Crawford         }
3016a0f08674SEwan Crawford 
3017a0f08674SEwan Crawford         RenderScriptRuntime *runtime =
3018a0f08674SEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
3019a0f08674SEwan Crawford 
3020a0f08674SEwan Crawford         const char* id_cstr = command.GetArgumentAtIndex(0);
3021a0f08674SEwan Crawford         bool convert_complete = false;
3022a0f08674SEwan Crawford         const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
3023a0f08674SEwan Crawford         if (!convert_complete)
3024a0f08674SEwan Crawford         {
3025a0f08674SEwan Crawford             result.AppendErrorWithFormat("invalid allocation id argument '%s'", id_cstr);
3026a0f08674SEwan Crawford             result.SetStatus(eReturnStatusFailed);
3027a0f08674SEwan Crawford             return false;
3028a0f08674SEwan Crawford         }
3029a0f08674SEwan Crawford 
3030a0f08674SEwan Crawford         Stream* output_strm = nullptr;
3031a0f08674SEwan Crawford         StreamFile outfile_stream;
3032a0f08674SEwan Crawford         const FileSpec &outfile_spec = m_options.m_outfile; // Dump allocation to file instead
3033a0f08674SEwan Crawford         if (outfile_spec)
3034a0f08674SEwan Crawford         {
3035a0f08674SEwan Crawford             // Open output file
3036a0f08674SEwan Crawford             char path[256];
3037a0f08674SEwan Crawford             outfile_spec.GetPath(path, sizeof(path));
3038a0f08674SEwan Crawford             if (outfile_stream.GetFile().Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate).Success())
3039a0f08674SEwan Crawford             {
3040a0f08674SEwan Crawford                 output_strm = &outfile_stream;
3041a0f08674SEwan Crawford                 result.GetOutputStream().Printf("Results written to '%s'", path);
3042a0f08674SEwan Crawford                 result.GetOutputStream().EOL();
3043a0f08674SEwan Crawford             }
3044a0f08674SEwan Crawford             else
3045a0f08674SEwan Crawford             {
3046a0f08674SEwan Crawford                 result.AppendErrorWithFormat("Couldn't open file '%s'", path);
3047a0f08674SEwan Crawford                 result.SetStatus(eReturnStatusFailed);
3048a0f08674SEwan Crawford                 return false;
3049a0f08674SEwan Crawford             }
3050a0f08674SEwan Crawford         }
3051a0f08674SEwan Crawford         else
3052a0f08674SEwan Crawford             output_strm = &result.GetOutputStream();
3053a0f08674SEwan Crawford 
3054a0f08674SEwan Crawford         assert(output_strm != nullptr);
3055a0f08674SEwan Crawford         bool success = runtime->DumpAllocation(*output_strm, m_exe_ctx.GetFramePtr(), id);
3056a0f08674SEwan Crawford 
3057a0f08674SEwan Crawford         if (success)
3058a0f08674SEwan Crawford             result.SetStatus(eReturnStatusSuccessFinishResult);
3059a0f08674SEwan Crawford         else
3060a0f08674SEwan Crawford             result.SetStatus(eReturnStatusFailed);
3061a0f08674SEwan Crawford 
3062a0f08674SEwan Crawford         return true;
3063a0f08674SEwan Crawford     }
3064a0f08674SEwan Crawford 
3065a0f08674SEwan Crawford private:
3066a0f08674SEwan Crawford     CommandOptions m_options;
3067a0f08674SEwan Crawford };
3068a0f08674SEwan Crawford 
3069a0f08674SEwan Crawford OptionDefinition
3070a0f08674SEwan Crawford CommandObjectRenderScriptRuntimeAllocationDump::CommandOptions::g_option_table[] =
3071a0f08674SEwan Crawford {
3072a0f08674SEwan Crawford     { LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename,
3073a0f08674SEwan Crawford       "Print results to specified file instead of command line."},
3074a0f08674SEwan Crawford     { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
3075a0f08674SEwan Crawford };
3076a0f08674SEwan Crawford 
307715f2bd95SEwan Crawford class CommandObjectRenderScriptRuntimeAllocationList : public CommandObjectParsed
307815f2bd95SEwan Crawford {
307915f2bd95SEwan Crawford public:
308015f2bd95SEwan Crawford     CommandObjectRenderScriptRuntimeAllocationList(CommandInterpreter &interpreter)
308115f2bd95SEwan Crawford         : CommandObjectParsed(interpreter, "renderscript allocation list",
308215f2bd95SEwan Crawford                               "List renderscript allocations and their information.", "renderscript allocation list",
308315f2bd95SEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched), m_options(interpreter)
308415f2bd95SEwan Crawford     {
308515f2bd95SEwan Crawford     }
308615f2bd95SEwan Crawford 
3087*222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocationList() override = default;
3088*222b937cSEugene Zelenko 
3089*222b937cSEugene Zelenko     Options*
3090*222b937cSEugene Zelenko     GetOptions() override
309115f2bd95SEwan Crawford     {
309215f2bd95SEwan Crawford         return &m_options;
309315f2bd95SEwan Crawford     }
309415f2bd95SEwan Crawford 
309515f2bd95SEwan Crawford     class CommandOptions : public Options
309615f2bd95SEwan Crawford     {
309715f2bd95SEwan Crawford     public:
309815f2bd95SEwan Crawford         CommandOptions(CommandInterpreter &interpreter) : Options(interpreter), m_refresh(false)
309915f2bd95SEwan Crawford         {
310015f2bd95SEwan Crawford         }
310115f2bd95SEwan Crawford 
3102*222b937cSEugene Zelenko         ~CommandOptions() override = default;
310315f2bd95SEwan Crawford 
3104*222b937cSEugene Zelenko         Error
3105*222b937cSEugene Zelenko         SetOptionValue(uint32_t option_idx, const char *option_arg) override
310615f2bd95SEwan Crawford         {
310715f2bd95SEwan Crawford             Error error;
310815f2bd95SEwan Crawford             const int short_option = m_getopt_table[option_idx].val;
310915f2bd95SEwan Crawford 
311015f2bd95SEwan Crawford             switch (short_option)
311115f2bd95SEwan Crawford             {
311215f2bd95SEwan Crawford                 case 'r':
311315f2bd95SEwan Crawford                     m_refresh = true;
311415f2bd95SEwan Crawford                     break;
311515f2bd95SEwan Crawford                 default:
311615f2bd95SEwan Crawford                     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
311715f2bd95SEwan Crawford                     break;
311815f2bd95SEwan Crawford             }
311915f2bd95SEwan Crawford             return error;
312015f2bd95SEwan Crawford         }
312115f2bd95SEwan Crawford 
312215f2bd95SEwan Crawford         void
3123*222b937cSEugene Zelenko         OptionParsingStarting() override
312415f2bd95SEwan Crawford         {
312515f2bd95SEwan Crawford             m_refresh = false;
312615f2bd95SEwan Crawford         }
312715f2bd95SEwan Crawford 
312815f2bd95SEwan Crawford         const OptionDefinition*
3129*222b937cSEugene Zelenko         GetDefinitions() override
313015f2bd95SEwan Crawford         {
313115f2bd95SEwan Crawford             return g_option_table;
313215f2bd95SEwan Crawford         }
313315f2bd95SEwan Crawford 
313415f2bd95SEwan Crawford         static OptionDefinition g_option_table[];
313515f2bd95SEwan Crawford         bool m_refresh;
313615f2bd95SEwan Crawford     };
313715f2bd95SEwan Crawford 
313815f2bd95SEwan Crawford     bool
3139*222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
314015f2bd95SEwan Crawford     {
314115f2bd95SEwan Crawford         RenderScriptRuntime *runtime =
314215f2bd95SEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
314315f2bd95SEwan Crawford         runtime->ListAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr(), m_options.m_refresh);
314415f2bd95SEwan Crawford         result.SetStatus(eReturnStatusSuccessFinishResult);
314515f2bd95SEwan Crawford         return true;
314615f2bd95SEwan Crawford     }
314715f2bd95SEwan Crawford 
314815f2bd95SEwan Crawford private:
314915f2bd95SEwan Crawford     CommandOptions m_options;
315015f2bd95SEwan Crawford };
315115f2bd95SEwan Crawford 
315215f2bd95SEwan Crawford OptionDefinition
315315f2bd95SEwan Crawford CommandObjectRenderScriptRuntimeAllocationList::CommandOptions::g_option_table[] =
315415f2bd95SEwan Crawford {
315515f2bd95SEwan Crawford     { LLDB_OPT_SET_1, false, "refresh", 'r', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone,
315615f2bd95SEwan Crawford       "Recompute allocation details."},
315715f2bd95SEwan Crawford     { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
315815f2bd95SEwan Crawford };
315915f2bd95SEwan Crawford 
316055232f09SEwan Crawford class CommandObjectRenderScriptRuntimeAllocationLoad : public CommandObjectParsed
316155232f09SEwan Crawford {
316255232f09SEwan Crawford public:
316355232f09SEwan Crawford     CommandObjectRenderScriptRuntimeAllocationLoad(CommandInterpreter &interpreter)
316455232f09SEwan Crawford         : CommandObjectParsed(interpreter, "renderscript allocation load",
316555232f09SEwan Crawford                               "Loads renderscript allocation contents from a file.", "renderscript allocation load <ID> <filename>",
316655232f09SEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
316755232f09SEwan Crawford     {
316855232f09SEwan Crawford     }
316955232f09SEwan Crawford 
3170*222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocationLoad() override = default;
317155232f09SEwan Crawford 
317255232f09SEwan Crawford     bool
3173*222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
317455232f09SEwan Crawford     {
317555232f09SEwan Crawford         const size_t argc = command.GetArgumentCount();
317655232f09SEwan Crawford         if (argc != 2)
317755232f09SEwan Crawford         {
317855232f09SEwan Crawford             result.AppendErrorWithFormat("'%s' takes 2 arguments, an allocation ID and filename to read from.", m_cmd_name.c_str());
317955232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
318055232f09SEwan Crawford             return false;
318155232f09SEwan Crawford         }
318255232f09SEwan Crawford 
318355232f09SEwan Crawford         RenderScriptRuntime *runtime =
318455232f09SEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
318555232f09SEwan Crawford 
318655232f09SEwan Crawford         const char* id_cstr = command.GetArgumentAtIndex(0);
318755232f09SEwan Crawford         bool convert_complete = false;
318855232f09SEwan Crawford         const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
318955232f09SEwan Crawford         if (!convert_complete)
319055232f09SEwan Crawford         {
319155232f09SEwan Crawford             result.AppendErrorWithFormat ("invalid allocation id argument '%s'", id_cstr);
319255232f09SEwan Crawford             result.SetStatus (eReturnStatusFailed);
319355232f09SEwan Crawford             return false;
319455232f09SEwan Crawford         }
319555232f09SEwan Crawford 
319655232f09SEwan Crawford         const char* filename = command.GetArgumentAtIndex(1);
319755232f09SEwan Crawford         bool success = runtime->LoadAllocation(result.GetOutputStream(), id, filename, m_exe_ctx.GetFramePtr());
319855232f09SEwan Crawford 
319955232f09SEwan Crawford         if (success)
320055232f09SEwan Crawford             result.SetStatus(eReturnStatusSuccessFinishResult);
320155232f09SEwan Crawford         else
320255232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
320355232f09SEwan Crawford 
320455232f09SEwan Crawford         return true;
320555232f09SEwan Crawford     }
320655232f09SEwan Crawford };
320755232f09SEwan Crawford 
320855232f09SEwan Crawford class CommandObjectRenderScriptRuntimeAllocationSave : public CommandObjectParsed
320955232f09SEwan Crawford {
321055232f09SEwan Crawford public:
321155232f09SEwan Crawford     CommandObjectRenderScriptRuntimeAllocationSave(CommandInterpreter &interpreter)
321255232f09SEwan Crawford         : CommandObjectParsed(interpreter, "renderscript allocation save",
321355232f09SEwan Crawford                               "Write renderscript allocation contents to a file.", "renderscript allocation save <ID> <filename>",
321455232f09SEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
321555232f09SEwan Crawford     {
321655232f09SEwan Crawford     }
321755232f09SEwan Crawford 
3218*222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocationSave() override = default;
321955232f09SEwan Crawford 
322055232f09SEwan Crawford     bool
3221*222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
322255232f09SEwan Crawford     {
322355232f09SEwan Crawford         const size_t argc = command.GetArgumentCount();
322455232f09SEwan Crawford         if (argc != 2)
322555232f09SEwan Crawford         {
322655232f09SEwan Crawford             result.AppendErrorWithFormat("'%s' takes 2 arguments, an allocation ID and filename to read from.", m_cmd_name.c_str());
322755232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
322855232f09SEwan Crawford             return false;
322955232f09SEwan Crawford         }
323055232f09SEwan Crawford 
323155232f09SEwan Crawford         RenderScriptRuntime *runtime =
323255232f09SEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
323355232f09SEwan Crawford 
323455232f09SEwan Crawford         const char* id_cstr = command.GetArgumentAtIndex(0);
323555232f09SEwan Crawford         bool convert_complete = false;
323655232f09SEwan Crawford         const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
323755232f09SEwan Crawford         if (!convert_complete)
323855232f09SEwan Crawford         {
323955232f09SEwan Crawford             result.AppendErrorWithFormat ("invalid allocation id argument '%s'", id_cstr);
324055232f09SEwan Crawford             result.SetStatus (eReturnStatusFailed);
324155232f09SEwan Crawford             return false;
324255232f09SEwan Crawford         }
324355232f09SEwan Crawford 
324455232f09SEwan Crawford         const char* filename = command.GetArgumentAtIndex(1);
324555232f09SEwan Crawford         bool success = runtime->SaveAllocation(result.GetOutputStream(), id, filename, m_exe_ctx.GetFramePtr());
324655232f09SEwan Crawford 
324755232f09SEwan Crawford         if (success)
324855232f09SEwan Crawford             result.SetStatus(eReturnStatusSuccessFinishResult);
324955232f09SEwan Crawford         else
325055232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
325155232f09SEwan Crawford 
325255232f09SEwan Crawford         return true;
325355232f09SEwan Crawford     }
325455232f09SEwan Crawford };
325555232f09SEwan Crawford 
325615f2bd95SEwan Crawford class CommandObjectRenderScriptRuntimeAllocation : public CommandObjectMultiword
325715f2bd95SEwan Crawford {
325815f2bd95SEwan Crawford public:
325915f2bd95SEwan Crawford     CommandObjectRenderScriptRuntimeAllocation(CommandInterpreter &interpreter)
326015f2bd95SEwan Crawford         : CommandObjectMultiword(interpreter, "renderscript allocation", "Commands that deal with renderscript allocations.",
326115f2bd95SEwan Crawford                                  NULL)
326215f2bd95SEwan Crawford     {
326315f2bd95SEwan Crawford         LoadSubCommand("list", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationList(interpreter)));
3264a0f08674SEwan Crawford         LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationDump(interpreter)));
326555232f09SEwan Crawford         LoadSubCommand("save", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationSave(interpreter)));
326655232f09SEwan Crawford         LoadSubCommand("load", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationLoad(interpreter)));
326715f2bd95SEwan Crawford     }
326815f2bd95SEwan Crawford 
3269*222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocation() override = default;
327015f2bd95SEwan Crawford };
327115f2bd95SEwan Crawford 
32724640cde1SColin Riley class CommandObjectRenderScriptRuntimeStatus : public CommandObjectParsed
32734640cde1SColin Riley {
32744640cde1SColin Riley public:
32754640cde1SColin Riley     CommandObjectRenderScriptRuntimeStatus(CommandInterpreter &interpreter)
32764640cde1SColin Riley         : CommandObjectParsed(interpreter, "renderscript status",
32774640cde1SColin Riley                               "Displays current renderscript runtime status.", "renderscript status",
32784640cde1SColin Riley                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
32794640cde1SColin Riley     {
32804640cde1SColin Riley     }
32814640cde1SColin Riley 
3282*222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeStatus() override = default;
32834640cde1SColin Riley 
32844640cde1SColin Riley     bool
3285*222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
32864640cde1SColin Riley     {
32874640cde1SColin Riley         RenderScriptRuntime *runtime =
32884640cde1SColin Riley             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
32894640cde1SColin Riley         runtime->Status(result.GetOutputStream());
32904640cde1SColin Riley         result.SetStatus(eReturnStatusSuccessFinishResult);
32914640cde1SColin Riley         return true;
32924640cde1SColin Riley     }
32934640cde1SColin Riley };
32944640cde1SColin Riley 
32955ec532a9SColin Riley class CommandObjectRenderScriptRuntime : public CommandObjectMultiword
32965ec532a9SColin Riley {
32975ec532a9SColin Riley public:
32985ec532a9SColin Riley     CommandObjectRenderScriptRuntime(CommandInterpreter &interpreter)
32995ec532a9SColin Riley         : CommandObjectMultiword(interpreter, "renderscript", "A set of commands for operating on renderscript.",
33005ec532a9SColin Riley                                  "renderscript <subcommand> [<subcommand-options>]")
33015ec532a9SColin Riley     {
33025ec532a9SColin Riley         LoadSubCommand("module", CommandObjectSP(new CommandObjectRenderScriptRuntimeModule(interpreter)));
33034640cde1SColin Riley         LoadSubCommand("status", CommandObjectSP(new CommandObjectRenderScriptRuntimeStatus(interpreter)));
33044640cde1SColin Riley         LoadSubCommand("kernel", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernel(interpreter)));
33054640cde1SColin Riley         LoadSubCommand("context", CommandObjectSP(new CommandObjectRenderScriptRuntimeContext(interpreter)));
330615f2bd95SEwan Crawford         LoadSubCommand("allocation", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocation(interpreter)));
33075ec532a9SColin Riley     }
33085ec532a9SColin Riley 
3309*222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntime() override = default;
33105ec532a9SColin Riley };
3311ef20b08fSColin Riley 
3312ef20b08fSColin Riley void
3313ef20b08fSColin Riley RenderScriptRuntime::Initiate()
33145ec532a9SColin Riley {
3315ef20b08fSColin Riley     assert(!m_initiated);
33165ec532a9SColin Riley }
3317ef20b08fSColin Riley 
3318ef20b08fSColin Riley RenderScriptRuntime::RenderScriptRuntime(Process *process)
33197dc7771cSEwan Crawford     : lldb_private::CPPLanguageRuntime(process), m_initiated(false), m_debuggerPresentFlagged(false),
33207dc7771cSEwan Crawford       m_breakAllKernels(false)
3321ef20b08fSColin Riley {
33224640cde1SColin Riley     ModulesDidLoad(process->GetTarget().GetImages());
3323ef20b08fSColin Riley }
33244640cde1SColin Riley 
33254640cde1SColin Riley lldb::CommandObjectSP
33264640cde1SColin Riley RenderScriptRuntime::GetCommandObject(lldb_private::CommandInterpreter& interpreter)
33274640cde1SColin Riley {
33284640cde1SColin Riley     static CommandObjectSP command_object;
33294640cde1SColin Riley     if(!command_object)
33304640cde1SColin Riley     {
33314640cde1SColin Riley         command_object.reset(new CommandObjectRenderScriptRuntime(interpreter));
33324640cde1SColin Riley     }
33334640cde1SColin Riley     return command_object;
33344640cde1SColin Riley }
33354640cde1SColin Riley 
333678f339d1SEwan Crawford RenderScriptRuntime::~RenderScriptRuntime() = default;
3337