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 
10222b937cSEugene Zelenko // C Includes
11222b937cSEugene Zelenko // C++ Includes
12222b937cSEugene Zelenko // Other libraries and framework includes
13222b937cSEugene 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"
218b244e21SEwan Crawford #include "lldb/Core/ValueObjectVariable.h"
22018f5a7eSEwan Crawford #include "lldb/Core/RegularExpression.h"
238b244e21SEwan Crawford #include "lldb/DataFormatters/DumpValueObjectOptions.h"
24a0f08674SEwan Crawford #include "lldb/Host/StringConvert.h"
255ec532a9SColin Riley #include "lldb/Symbol/Symbol.h"
264640cde1SColin Riley #include "lldb/Symbol/Type.h"
275ec532a9SColin Riley #include "lldb/Target/Process.h"
285ec532a9SColin Riley #include "lldb/Target/Target.h"
29018f5a7eSEwan Crawford #include "lldb/Target/Thread.h"
305ec532a9SColin Riley #include "lldb/Interpreter/Args.h"
315ec532a9SColin Riley #include "lldb/Interpreter/Options.h"
325ec532a9SColin Riley #include "lldb/Interpreter/CommandInterpreter.h"
335ec532a9SColin Riley #include "lldb/Interpreter/CommandReturnObject.h"
345ec532a9SColin Riley #include "lldb/Interpreter/CommandObjectMultiword.h"
354640cde1SColin Riley #include "lldb/Breakpoint/StoppointCallbackContext.h"
364640cde1SColin Riley #include "lldb/Target/RegisterContext.h"
3715f2bd95SEwan Crawford #include "lldb/Expression/UserExpression.h"
384640cde1SColin Riley #include "lldb/Symbol/VariableList.h"
395ec532a9SColin Riley 
405ec532a9SColin Riley using namespace lldb;
415ec532a9SColin Riley using namespace lldb_private;
4298156583SEwan Crawford using namespace lldb_renderscript;
435ec532a9SColin Riley 
4478f339d1SEwan Crawford namespace {
4578f339d1SEwan Crawford 
4678f339d1SEwan Crawford // The empirical_type adds a basic level of validation to arbitrary data
4778f339d1SEwan Crawford // allowing us to track if data has been discovered and stored or not.
4878f339d1SEwan Crawford // An empirical_type will be marked as valid only if it has been explicitly assigned to.
4978f339d1SEwan Crawford template <typename type_t>
5078f339d1SEwan Crawford class empirical_type
5178f339d1SEwan Crawford {
5278f339d1SEwan Crawford public:
5378f339d1SEwan Crawford     // Ctor. Contents is invalid when constructed.
5478f339d1SEwan Crawford     empirical_type()
5578f339d1SEwan Crawford         : valid(false)
5678f339d1SEwan Crawford     {}
5778f339d1SEwan Crawford 
5878f339d1SEwan Crawford     // Return true and copy contents to out if valid, else return false.
5978f339d1SEwan Crawford     bool get(type_t& out) const
6078f339d1SEwan Crawford     {
6178f339d1SEwan Crawford         if (valid)
6278f339d1SEwan Crawford             out = data;
6378f339d1SEwan Crawford         return valid;
6478f339d1SEwan Crawford     }
6578f339d1SEwan Crawford 
6678f339d1SEwan Crawford     // Return a pointer to the contents or nullptr if it was not valid.
6778f339d1SEwan Crawford     const type_t* get() const
6878f339d1SEwan Crawford     {
6978f339d1SEwan Crawford         return valid ? &data : nullptr;
7078f339d1SEwan Crawford     }
7178f339d1SEwan Crawford 
7278f339d1SEwan Crawford     // Assign data explicitly.
7378f339d1SEwan Crawford     void set(const type_t in)
7478f339d1SEwan Crawford     {
7578f339d1SEwan Crawford         data = in;
7678f339d1SEwan Crawford         valid = true;
7778f339d1SEwan Crawford     }
7878f339d1SEwan Crawford 
7978f339d1SEwan Crawford     // Mark contents as invalid.
8078f339d1SEwan Crawford     void invalidate()
8178f339d1SEwan Crawford     {
8278f339d1SEwan Crawford         valid = false;
8378f339d1SEwan Crawford     }
8478f339d1SEwan Crawford 
8578f339d1SEwan Crawford     // Returns true if this type contains valid data.
8678f339d1SEwan Crawford     bool isValid() const
8778f339d1SEwan Crawford     {
8878f339d1SEwan Crawford         return valid;
8978f339d1SEwan Crawford     }
9078f339d1SEwan Crawford 
9178f339d1SEwan Crawford     // Assignment operator.
9278f339d1SEwan Crawford     empirical_type<type_t>& operator = (const type_t in)
9378f339d1SEwan Crawford     {
9478f339d1SEwan Crawford         set(in);
9578f339d1SEwan Crawford         return *this;
9678f339d1SEwan Crawford     }
9778f339d1SEwan Crawford 
9878f339d1SEwan Crawford     // Dereference operator returns contents.
9978f339d1SEwan Crawford     // Warning: Will assert if not valid so use only when you know data is valid.
10078f339d1SEwan Crawford     const type_t& operator * () const
10178f339d1SEwan Crawford     {
10278f339d1SEwan Crawford         assert(valid);
10378f339d1SEwan Crawford         return data;
10478f339d1SEwan Crawford     }
10578f339d1SEwan Crawford 
10678f339d1SEwan Crawford protected:
10778f339d1SEwan Crawford     bool valid;
10878f339d1SEwan Crawford     type_t data;
10978f339d1SEwan Crawford };
11078f339d1SEwan Crawford 
111222b937cSEugene Zelenko } // anonymous namespace
11278f339d1SEwan Crawford 
11378f339d1SEwan Crawford // The ScriptDetails class collects data associated with a single script instance.
11478f339d1SEwan Crawford struct RenderScriptRuntime::ScriptDetails
11578f339d1SEwan Crawford {
116222b937cSEugene Zelenko     ~ScriptDetails() = default;
11778f339d1SEwan Crawford 
11878f339d1SEwan Crawford     enum ScriptType
11978f339d1SEwan Crawford     {
12078f339d1SEwan Crawford         eScript,
12178f339d1SEwan Crawford         eScriptC
12278f339d1SEwan Crawford     };
12378f339d1SEwan Crawford 
12478f339d1SEwan Crawford     // The derived type of the script.
12578f339d1SEwan Crawford     empirical_type<ScriptType> type;
12678f339d1SEwan Crawford     // The name of the original source file.
12778f339d1SEwan Crawford     empirical_type<std::string> resName;
12878f339d1SEwan Crawford     // Path to script .so file on the device.
12978f339d1SEwan Crawford     empirical_type<std::string> scriptDyLib;
13078f339d1SEwan Crawford     // Directory where kernel objects are cached on device.
13178f339d1SEwan Crawford     empirical_type<std::string> cacheDir;
13278f339d1SEwan Crawford     // Pointer to the context which owns this script.
13378f339d1SEwan Crawford     empirical_type<lldb::addr_t> context;
13478f339d1SEwan Crawford     // Pointer to the script object itself.
13578f339d1SEwan Crawford     empirical_type<lldb::addr_t> script;
13678f339d1SEwan Crawford };
13778f339d1SEwan Crawford 
1388b244e21SEwan Crawford // This Element class represents the Element object in RS,
1398b244e21SEwan Crawford // defining the type associated with an Allocation.
1408b244e21SEwan Crawford struct RenderScriptRuntime::Element
14178f339d1SEwan Crawford {
14215f2bd95SEwan Crawford     // Taken from rsDefines.h
14315f2bd95SEwan Crawford     enum DataKind
14415f2bd95SEwan Crawford     {
14515f2bd95SEwan Crawford         RS_KIND_USER,
14615f2bd95SEwan Crawford         RS_KIND_PIXEL_L = 7,
14715f2bd95SEwan Crawford         RS_KIND_PIXEL_A,
14815f2bd95SEwan Crawford         RS_KIND_PIXEL_LA,
14915f2bd95SEwan Crawford         RS_KIND_PIXEL_RGB,
15015f2bd95SEwan Crawford         RS_KIND_PIXEL_RGBA,
15115f2bd95SEwan Crawford         RS_KIND_PIXEL_DEPTH,
15215f2bd95SEwan Crawford         RS_KIND_PIXEL_YUV,
15315f2bd95SEwan Crawford         RS_KIND_INVALID = 100
15415f2bd95SEwan Crawford     };
15578f339d1SEwan Crawford 
15615f2bd95SEwan Crawford     // Taken from rsDefines.h
15778f339d1SEwan Crawford     enum DataType
15878f339d1SEwan Crawford     {
15915f2bd95SEwan Crawford         RS_TYPE_NONE = 0,
16015f2bd95SEwan Crawford         RS_TYPE_FLOAT_16,
16115f2bd95SEwan Crawford         RS_TYPE_FLOAT_32,
16215f2bd95SEwan Crawford         RS_TYPE_FLOAT_64,
16315f2bd95SEwan Crawford         RS_TYPE_SIGNED_8,
16415f2bd95SEwan Crawford         RS_TYPE_SIGNED_16,
16515f2bd95SEwan Crawford         RS_TYPE_SIGNED_32,
16615f2bd95SEwan Crawford         RS_TYPE_SIGNED_64,
16715f2bd95SEwan Crawford         RS_TYPE_UNSIGNED_8,
16815f2bd95SEwan Crawford         RS_TYPE_UNSIGNED_16,
16915f2bd95SEwan Crawford         RS_TYPE_UNSIGNED_32,
17015f2bd95SEwan Crawford         RS_TYPE_UNSIGNED_64,
17115f2bd95SEwan Crawford         RS_TYPE_BOOLEAN
17278f339d1SEwan Crawford     };
17378f339d1SEwan Crawford 
1748b244e21SEwan Crawford     std::vector<Element> children;                       // Child Element fields for structs
1758b244e21SEwan Crawford     empirical_type<lldb::addr_t> element_ptr;            // Pointer to the RS Element of the Type
1768b244e21SEwan Crawford     empirical_type<DataType> type;                       // Type of each data pointer stored by the allocation
1778b244e21SEwan Crawford     empirical_type<DataKind> type_kind;                  // Defines pixel type if Allocation is created from an image
1788b244e21SEwan Crawford     empirical_type<uint32_t> type_vec_size;              // Vector size of each data point, e.g '4' for uchar4
1798b244e21SEwan Crawford     empirical_type<uint32_t> field_count;                // Number of Subelements
1808b244e21SEwan Crawford     empirical_type<uint32_t> datum_size;                 // Size of a single Element with padding
1818b244e21SEwan Crawford     empirical_type<uint32_t> padding;                    // Number of padding bytes
1828b244e21SEwan Crawford     empirical_type<uint32_t> array_size;                 // Number of items in array, only needed for strucrs
1838b244e21SEwan Crawford     ConstString type_name;                               // Name of type, only needed for structs
1848b244e21SEwan Crawford 
185fe06b5adSAdrian McCarthy     static const ConstString &GetFallbackStructName();   // Print this as the type name of a struct Element
1868b244e21SEwan Crawford                                                          // If we can't resolve the actual struct name
187*8b59062aSEwan Crawford 
188*8b59062aSEwan Crawford     bool shouldRefresh() const
189*8b59062aSEwan Crawford     {
190*8b59062aSEwan Crawford         const bool valid_ptr = element_ptr.isValid() && *element_ptr.get() != 0x0;
191*8b59062aSEwan Crawford         const bool valid_type = type.isValid() && type_vec_size.isValid() && type_kind.isValid();
192*8b59062aSEwan Crawford         return !valid_ptr || !valid_type || !datum_size.isValid();
193*8b59062aSEwan Crawford     }
1948b244e21SEwan Crawford };
1958b244e21SEwan Crawford 
1968b244e21SEwan Crawford // This AllocationDetails class collects data associated with a single
1978b244e21SEwan Crawford // allocation instance.
1988b244e21SEwan Crawford struct RenderScriptRuntime::AllocationDetails
1998b244e21SEwan Crawford {
20015f2bd95SEwan Crawford     struct Dimension
20178f339d1SEwan Crawford     {
20215f2bd95SEwan Crawford         uint32_t dim_1;
20315f2bd95SEwan Crawford         uint32_t dim_2;
20415f2bd95SEwan Crawford         uint32_t dim_3;
20515f2bd95SEwan Crawford         uint32_t cubeMap;
20615f2bd95SEwan Crawford 
20715f2bd95SEwan Crawford         Dimension()
20815f2bd95SEwan Crawford         {
20915f2bd95SEwan Crawford              dim_1 = 0;
21015f2bd95SEwan Crawford              dim_2 = 0;
21115f2bd95SEwan Crawford              dim_3 = 0;
21215f2bd95SEwan Crawford              cubeMap = 0;
21315f2bd95SEwan Crawford         }
21478f339d1SEwan Crawford     };
21578f339d1SEwan Crawford 
21655232f09SEwan Crawford     // Header for reading and writing allocation contents
21755232f09SEwan Crawford     // to a binary file.
21855232f09SEwan Crawford     struct FileHeader
21955232f09SEwan Crawford     {
22055232f09SEwan Crawford         uint8_t ident[4];      // ASCII 'RSAD' identifying the file
22155232f09SEwan Crawford         uint16_t hdr_size;     // Header size in bytes, for backwards compatability
22255232f09SEwan Crawford         uint16_t type;         // DataType enum
22355232f09SEwan Crawford         uint32_t kind;         // DataKind enum
22455232f09SEwan Crawford         uint32_t dims[3];      // Dimensions
22555232f09SEwan Crawford         uint32_t element_size; // Size of a single element, including padding
22655232f09SEwan Crawford     };
22755232f09SEwan Crawford 
22815f2bd95SEwan Crawford     // Monotonically increasing from 1
22915f2bd95SEwan Crawford     static unsigned int ID;
23015f2bd95SEwan Crawford 
23115f2bd95SEwan Crawford     // Maps Allocation DataType enum and vector size to printable strings
23215f2bd95SEwan Crawford     // using mapping from RenderScript numerical types summary documentation
23315f2bd95SEwan Crawford     static const char* RsDataTypeToString[][4];
23415f2bd95SEwan Crawford 
23515f2bd95SEwan Crawford     // Maps Allocation DataKind enum to printable strings
23615f2bd95SEwan Crawford     static const char* RsDataKindToString[];
23715f2bd95SEwan Crawford 
238a0f08674SEwan Crawford     // Maps allocation types to format sizes for printing.
239a0f08674SEwan Crawford     static const unsigned int RSTypeToFormat[][3];
240a0f08674SEwan Crawford 
24115f2bd95SEwan Crawford     // Give each allocation an ID as a way
24215f2bd95SEwan Crawford     // for commands to reference it.
24315f2bd95SEwan Crawford     const unsigned int id;
24415f2bd95SEwan Crawford 
2458b244e21SEwan Crawford     RenderScriptRuntime::Element element;     // Allocation Element type
24615f2bd95SEwan Crawford     empirical_type<Dimension> dimension;      // Dimensions of the Allocation
24715f2bd95SEwan Crawford     empirical_type<lldb::addr_t> address;     // Pointer to address of the RS Allocation
24815f2bd95SEwan Crawford     empirical_type<lldb::addr_t> data_ptr;    // Pointer to the data held by the Allocation
24915f2bd95SEwan Crawford     empirical_type<lldb::addr_t> type_ptr;    // Pointer to the RS Type of the Allocation
25015f2bd95SEwan Crawford     empirical_type<lldb::addr_t> context;     // Pointer to the RS Context of the Allocation
251a0f08674SEwan Crawford     empirical_type<uint32_t> size;            // Size of the allocation
252a0f08674SEwan Crawford     empirical_type<uint32_t> stride;          // Stride between rows of the allocation
25315f2bd95SEwan Crawford 
25415f2bd95SEwan Crawford     // Give each allocation an id, so we can reference it in user commands.
25515f2bd95SEwan Crawford     AllocationDetails(): id(ID++)
25615f2bd95SEwan Crawford     {
25715f2bd95SEwan Crawford     }
258*8b59062aSEwan Crawford 
259*8b59062aSEwan Crawford     bool shouldRefresh() const
260*8b59062aSEwan Crawford     {
261*8b59062aSEwan Crawford         bool valid_ptrs = data_ptr.isValid() && *data_ptr.get() != 0x0;
262*8b59062aSEwan Crawford         valid_ptrs = valid_ptrs && type_ptr.isValid() && *type_ptr.get() != 0x0;
263*8b59062aSEwan Crawford         return !valid_ptrs || !dimension.isValid() || !size.isValid() || element.shouldRefresh();
264*8b59062aSEwan Crawford     }
26515f2bd95SEwan Crawford };
26615f2bd95SEwan Crawford 
267fe06b5adSAdrian McCarthy 
268fe06b5adSAdrian McCarthy const ConstString &
269fe06b5adSAdrian McCarthy RenderScriptRuntime::Element::GetFallbackStructName()
270fe06b5adSAdrian McCarthy {
271fe06b5adSAdrian McCarthy     static const ConstString FallbackStructName("struct");
272fe06b5adSAdrian McCarthy     return FallbackStructName;
273fe06b5adSAdrian McCarthy }
2748b244e21SEwan Crawford 
27515f2bd95SEwan Crawford unsigned int RenderScriptRuntime::AllocationDetails::ID = 1;
27615f2bd95SEwan Crawford 
27715f2bd95SEwan Crawford const char* RenderScriptRuntime::AllocationDetails::RsDataKindToString[] =
27815f2bd95SEwan Crawford {
27915f2bd95SEwan Crawford    "User",
28015f2bd95SEwan Crawford    "Undefined", "Undefined", "Undefined", // Enum jumps from 0 to 7
28115f2bd95SEwan Crawford    "Undefined", "Undefined", "Undefined",
28215f2bd95SEwan Crawford    "L Pixel",
28315f2bd95SEwan Crawford    "A Pixel",
28415f2bd95SEwan Crawford    "LA Pixel",
28515f2bd95SEwan Crawford    "RGB Pixel",
28615f2bd95SEwan Crawford    "RGBA Pixel",
28715f2bd95SEwan Crawford    "Pixel Depth",
28815f2bd95SEwan Crawford    "YUV Pixel"
28915f2bd95SEwan Crawford };
29015f2bd95SEwan Crawford 
29115f2bd95SEwan Crawford const char* RenderScriptRuntime::AllocationDetails::RsDataTypeToString[][4] =
29215f2bd95SEwan Crawford {
29315f2bd95SEwan Crawford     {"None", "None", "None", "None"},
29415f2bd95SEwan Crawford     {"half", "half2", "half3", "half4"},
29515f2bd95SEwan Crawford     {"float", "float2", "float3", "float4"},
29615f2bd95SEwan Crawford     {"double", "double2", "double3", "double4"},
29715f2bd95SEwan Crawford     {"char", "char2", "char3", "char4"},
29815f2bd95SEwan Crawford     {"short", "short2", "short3", "short4"},
29915f2bd95SEwan Crawford     {"int", "int2", "int3", "int4"},
30015f2bd95SEwan Crawford     {"long", "long2", "long3", "long4"},
30115f2bd95SEwan Crawford     {"uchar", "uchar2", "uchar3", "uchar4"},
30215f2bd95SEwan Crawford     {"ushort", "ushort2", "ushort3", "ushort4"},
30315f2bd95SEwan Crawford     {"uint", "uint2", "uint3", "uint4"},
30415f2bd95SEwan Crawford     {"ulong", "ulong2", "ulong3", "ulong4"},
30515f2bd95SEwan Crawford     {"bool", "bool2", "bool3", "bool4"}
30678f339d1SEwan Crawford };
30778f339d1SEwan Crawford 
308a0f08674SEwan Crawford // Used as an index into the RSTypeToFormat array elements
309a0f08674SEwan Crawford enum TypeToFormatIndex {
310a0f08674SEwan Crawford    eFormatSingle = 0,
311a0f08674SEwan Crawford    eFormatVector,
312a0f08674SEwan Crawford    eElementSize
313a0f08674SEwan Crawford };
314a0f08674SEwan Crawford 
315a0f08674SEwan Crawford // { format enum of single element, format enum of element vector, size of element}
316a0f08674SEwan Crawford const unsigned int RenderScriptRuntime::AllocationDetails::RSTypeToFormat[][3] =
317a0f08674SEwan Crawford {
318a0f08674SEwan Crawford     {eFormatHex, eFormatHex, 1}, // RS_TYPE_NONE
319a0f08674SEwan Crawford     {eFormatFloat, eFormatVectorOfFloat16, 2}, // RS_TYPE_FLOAT_16
320a0f08674SEwan Crawford     {eFormatFloat, eFormatVectorOfFloat32, sizeof(float)}, // RS_TYPE_FLOAT_32
321a0f08674SEwan Crawford     {eFormatFloat, eFormatVectorOfFloat64, sizeof(double)}, // RS_TYPE_FLOAT_64
322a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfSInt8, sizeof(int8_t)}, // RS_TYPE_SIGNED_8
323a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfSInt16, sizeof(int16_t)}, // RS_TYPE_SIGNED_16
324a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfSInt32, sizeof(int32_t)}, // RS_TYPE_SIGNED_32
325a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfSInt64, sizeof(int64_t)}, // RS_TYPE_SIGNED_64
326a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfUInt8, sizeof(uint8_t)}, // RS_TYPE_UNSIGNED_8
327a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfUInt16, sizeof(uint16_t)}, // RS_TYPE_UNSIGNED_16
328a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfUInt32, sizeof(uint32_t)}, // RS_TYPE_UNSIGNED_32
329a0f08674SEwan Crawford     {eFormatDecimal, eFormatVectorOfUInt64, sizeof(uint64_t)}, // RS_TYPE_UNSIGNED_64
330a0f08674SEwan Crawford     {eFormatBoolean, eFormatBoolean, sizeof(bool)} // RS_TYPE_BOOL
331a0f08674SEwan Crawford };
332a0f08674SEwan Crawford 
3335ec532a9SColin Riley //------------------------------------------------------------------
3345ec532a9SColin Riley // Static Functions
3355ec532a9SColin Riley //------------------------------------------------------------------
3365ec532a9SColin Riley LanguageRuntime *
3375ec532a9SColin Riley RenderScriptRuntime::CreateInstance(Process *process, lldb::LanguageType language)
3385ec532a9SColin Riley {
3395ec532a9SColin Riley 
3405ec532a9SColin Riley     if (language == eLanguageTypeExtRenderScript)
3415ec532a9SColin Riley         return new RenderScriptRuntime(process);
3425ec532a9SColin Riley     else
3435ec532a9SColin Riley         return NULL;
3445ec532a9SColin Riley }
3455ec532a9SColin Riley 
34698156583SEwan Crawford // Callback with a module to search for matching symbols.
34798156583SEwan Crawford // We first check that the module contains RS kernels.
34898156583SEwan Crawford // Then look for a symbol which matches our kernel name.
34998156583SEwan Crawford // The breakpoint address is finally set using the address of this symbol.
35098156583SEwan Crawford Searcher::CallbackReturn
35198156583SEwan Crawford RSBreakpointResolver::SearchCallback(SearchFilter &filter,
35298156583SEwan Crawford                                      SymbolContext &context,
35398156583SEwan Crawford                                      Address*,
35498156583SEwan Crawford                                      bool)
35598156583SEwan Crawford {
35698156583SEwan Crawford     ModuleSP module = context.module_sp;
35798156583SEwan Crawford 
35898156583SEwan Crawford     if (!module)
35998156583SEwan Crawford         return Searcher::eCallbackReturnContinue;
36098156583SEwan Crawford 
36198156583SEwan Crawford     // Is this a module containing renderscript kernels?
36298156583SEwan Crawford     if (nullptr == module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData))
36398156583SEwan Crawford         return Searcher::eCallbackReturnContinue;
36498156583SEwan Crawford 
36598156583SEwan Crawford     // Attempt to set a breakpoint on the kernel name symbol within the module library.
36698156583SEwan Crawford     // If it's not found, it's likely debug info is unavailable - try to set a
36798156583SEwan Crawford     // breakpoint on <name>.expand.
36898156583SEwan Crawford 
36998156583SEwan Crawford     const Symbol* kernel_sym = module->FindFirstSymbolWithNameAndType(m_kernel_name, eSymbolTypeCode);
37098156583SEwan Crawford     if (!kernel_sym)
37198156583SEwan Crawford     {
37298156583SEwan Crawford         std::string kernel_name_expanded(m_kernel_name.AsCString());
37398156583SEwan Crawford         kernel_name_expanded.append(".expand");
37498156583SEwan Crawford         kernel_sym = module->FindFirstSymbolWithNameAndType(ConstString(kernel_name_expanded.c_str()), eSymbolTypeCode);
37598156583SEwan Crawford     }
37698156583SEwan Crawford 
37798156583SEwan Crawford     if (kernel_sym)
37898156583SEwan Crawford     {
37998156583SEwan Crawford         Address bp_addr = kernel_sym->GetAddress();
38098156583SEwan Crawford         if (filter.AddressPasses(bp_addr))
38198156583SEwan Crawford             m_breakpoint->AddLocation(bp_addr);
38298156583SEwan Crawford     }
38398156583SEwan Crawford 
38498156583SEwan Crawford     return Searcher::eCallbackReturnContinue;
38598156583SEwan Crawford }
38698156583SEwan Crawford 
3875ec532a9SColin Riley void
3885ec532a9SColin Riley RenderScriptRuntime::Initialize()
3895ec532a9SColin Riley {
3904640cde1SColin Riley     PluginManager::RegisterPlugin(GetPluginNameStatic(), "RenderScript language support", CreateInstance, GetCommandObject);
3915ec532a9SColin Riley }
3925ec532a9SColin Riley 
3935ec532a9SColin Riley void
3945ec532a9SColin Riley RenderScriptRuntime::Terminate()
3955ec532a9SColin Riley {
3965ec532a9SColin Riley     PluginManager::UnregisterPlugin(CreateInstance);
3975ec532a9SColin Riley }
3985ec532a9SColin Riley 
3995ec532a9SColin Riley lldb_private::ConstString
4005ec532a9SColin Riley RenderScriptRuntime::GetPluginNameStatic()
4015ec532a9SColin Riley {
4025ec532a9SColin Riley     static ConstString g_name("renderscript");
4035ec532a9SColin Riley     return g_name;
4045ec532a9SColin Riley }
4055ec532a9SColin Riley 
406ef20b08fSColin Riley RenderScriptRuntime::ModuleKind
407ef20b08fSColin Riley RenderScriptRuntime::GetModuleKind(const lldb::ModuleSP &module_sp)
408ef20b08fSColin Riley {
409ef20b08fSColin Riley     if (module_sp)
410ef20b08fSColin Riley     {
411ef20b08fSColin Riley         // Is this a module containing renderscript kernels?
412ef20b08fSColin Riley         const Symbol *info_sym = module_sp->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData);
413ef20b08fSColin Riley         if (info_sym)
414ef20b08fSColin Riley         {
415ef20b08fSColin Riley             return eModuleKindKernelObj;
416ef20b08fSColin Riley         }
4174640cde1SColin Riley 
4184640cde1SColin Riley         // Is this the main RS runtime library
4194640cde1SColin Riley         const ConstString rs_lib("libRS.so");
4204640cde1SColin Riley         if (module_sp->GetFileSpec().GetFilename() == rs_lib)
4214640cde1SColin Riley         {
4224640cde1SColin Riley             return eModuleKindLibRS;
4234640cde1SColin Riley         }
4244640cde1SColin Riley 
4254640cde1SColin Riley         const ConstString rs_driverlib("libRSDriver.so");
4264640cde1SColin Riley         if (module_sp->GetFileSpec().GetFilename() == rs_driverlib)
4274640cde1SColin Riley         {
4284640cde1SColin Riley             return eModuleKindDriver;
4294640cde1SColin Riley         }
4304640cde1SColin Riley 
43115f2bd95SEwan Crawford         const ConstString rs_cpureflib("libRSCpuRef.so");
4324640cde1SColin Riley         if (module_sp->GetFileSpec().GetFilename() == rs_cpureflib)
4334640cde1SColin Riley         {
4344640cde1SColin Riley             return eModuleKindImpl;
4354640cde1SColin Riley         }
4364640cde1SColin Riley 
437ef20b08fSColin Riley     }
438ef20b08fSColin Riley     return eModuleKindIgnored;
439ef20b08fSColin Riley }
440ef20b08fSColin Riley 
441ef20b08fSColin Riley bool
442ef20b08fSColin Riley RenderScriptRuntime::IsRenderScriptModule(const lldb::ModuleSP &module_sp)
443ef20b08fSColin Riley {
444ef20b08fSColin Riley     return GetModuleKind(module_sp) != eModuleKindIgnored;
445ef20b08fSColin Riley }
446ef20b08fSColin Riley 
447ef20b08fSColin Riley void
448ef20b08fSColin Riley RenderScriptRuntime::ModulesDidLoad(const ModuleList &module_list )
449ef20b08fSColin Riley {
450ef20b08fSColin Riley     Mutex::Locker locker (module_list.GetMutex ());
451ef20b08fSColin Riley 
452ef20b08fSColin Riley     size_t num_modules = module_list.GetSize();
453ef20b08fSColin Riley     for (size_t i = 0; i < num_modules; i++)
454ef20b08fSColin Riley     {
455ef20b08fSColin Riley         auto mod = module_list.GetModuleAtIndex (i);
456ef20b08fSColin Riley         if (IsRenderScriptModule (mod))
457ef20b08fSColin Riley         {
458ef20b08fSColin Riley             LoadModule(mod);
459ef20b08fSColin Riley         }
460ef20b08fSColin Riley     }
461ef20b08fSColin Riley }
462ef20b08fSColin Riley 
4635ec532a9SColin Riley //------------------------------------------------------------------
4645ec532a9SColin Riley // PluginInterface protocol
4655ec532a9SColin Riley //------------------------------------------------------------------
4665ec532a9SColin Riley lldb_private::ConstString
4675ec532a9SColin Riley RenderScriptRuntime::GetPluginName()
4685ec532a9SColin Riley {
4695ec532a9SColin Riley     return GetPluginNameStatic();
4705ec532a9SColin Riley }
4715ec532a9SColin Riley 
4725ec532a9SColin Riley uint32_t
4735ec532a9SColin Riley RenderScriptRuntime::GetPluginVersion()
4745ec532a9SColin Riley {
4755ec532a9SColin Riley     return 1;
4765ec532a9SColin Riley }
4775ec532a9SColin Riley 
4785ec532a9SColin Riley bool
4795ec532a9SColin Riley RenderScriptRuntime::IsVTableName(const char *name)
4805ec532a9SColin Riley {
4815ec532a9SColin Riley     return false;
4825ec532a9SColin Riley }
4835ec532a9SColin Riley 
4845ec532a9SColin Riley bool
4855ec532a9SColin Riley RenderScriptRuntime::GetDynamicTypeAndAddress(ValueObject &in_value, lldb::DynamicValueType use_dynamic,
4860b6003f3SEnrico Granata                                               TypeAndOrName &class_type_or_name, Address &address,
4870b6003f3SEnrico Granata                                               Value::ValueType &value_type)
4885ec532a9SColin Riley {
4895ec532a9SColin Riley     return false;
4905ec532a9SColin Riley }
4915ec532a9SColin Riley 
492c74275bcSEnrico Granata TypeAndOrName
493c74275bcSEnrico Granata RenderScriptRuntime::FixUpDynamicType (const TypeAndOrName& type_and_or_name,
4947eed4877SEnrico Granata                                        ValueObject& static_value)
495c74275bcSEnrico Granata {
496c74275bcSEnrico Granata     return type_and_or_name;
497c74275bcSEnrico Granata }
498c74275bcSEnrico Granata 
4995ec532a9SColin Riley bool
5005ec532a9SColin Riley RenderScriptRuntime::CouldHaveDynamicValue(ValueObject &in_value)
5015ec532a9SColin Riley {
5025ec532a9SColin Riley     return false;
5035ec532a9SColin Riley }
5045ec532a9SColin Riley 
5055ec532a9SColin Riley lldb::BreakpointResolverSP
5065ec532a9SColin Riley RenderScriptRuntime::CreateExceptionResolver(Breakpoint *bkpt, bool catch_bp, bool throw_bp)
5075ec532a9SColin Riley {
5085ec532a9SColin Riley     BreakpointResolverSP resolver_sp;
5095ec532a9SColin Riley     return resolver_sp;
5105ec532a9SColin Riley }
5115ec532a9SColin Riley 
5124640cde1SColin Riley const RenderScriptRuntime::HookDefn RenderScriptRuntime::s_runtimeHookDefns[] =
5134640cde1SColin Riley {
5144640cde1SColin Riley     //rsdScript
51582780287SAidan Dodds     {
51682780287SAidan Dodds         "rsdScriptInit", //name
51782780287SAidan Dodds         "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_7ScriptCEPKcS7_PKhjj", // symbol name 32 bit
51882780287SAidan Dodds         "_Z13rsdScriptInitPKN7android12renderscript7ContextEPNS0_7ScriptCEPKcS7_PKhmj", // symbol name 64 bit
51982780287SAidan Dodds         0, // version
52082780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
52182780287SAidan Dodds         &lldb_private::RenderScriptRuntime::CaptureScriptInit1 // handler
52282780287SAidan Dodds     },
52382780287SAidan Dodds     {
52482780287SAidan Dodds         "rsdScriptInvokeForEach", // name
52582780287SAidan Dodds         "_Z22rsdScriptInvokeForEachPKN7android12renderscript7ContextEPNS0_6ScriptEjPKNS0_10AllocationEPS6_PKvjPK12RsScriptCall", // symbol name 32bit
52682780287SAidan Dodds         "_Z22rsdScriptInvokeForEachPKN7android12renderscript7ContextEPNS0_6ScriptEjPKNS0_10AllocationEPS6_PKvmPK12RsScriptCall", // symbol name 64bit
52782780287SAidan Dodds         0, // version
52882780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
52982780287SAidan Dodds         nullptr // handler
53082780287SAidan Dodds     },
53182780287SAidan Dodds     {
53282780287SAidan Dodds         "rsdScriptInvokeForEachMulti", // name
53382780287SAidan Dodds         "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0_6ScriptEjPPKNS0_10AllocationEjPS6_PKvjPK12RsScriptCall", // symbol name 32bit
53482780287SAidan Dodds         "_Z27rsdScriptInvokeForEachMultiPKN7android12renderscript7ContextEPNS0_6ScriptEjPPKNS0_10AllocationEmPS6_PKvmPK12RsScriptCall", // symbol name 64bit
53582780287SAidan Dodds         0, // version
53682780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
53782780287SAidan Dodds         nullptr // handler
53882780287SAidan Dodds     },
53982780287SAidan Dodds     {
54082780287SAidan Dodds         "rsdScriptInvokeFunction", // name
54182780287SAidan Dodds         "_Z23rsdScriptInvokeFunctionPKN7android12renderscript7ContextEPNS0_6ScriptEjPKvj", // symbol name 32bit
54282780287SAidan Dodds         "_Z23rsdScriptInvokeFunctionPKN7android12renderscript7ContextEPNS0_6ScriptEjPKvm", // symbol name 64bit
54382780287SAidan Dodds         0, // version
54482780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
54582780287SAidan Dodds         nullptr // handler
54682780287SAidan Dodds     },
54782780287SAidan Dodds     {
54882780287SAidan Dodds         "rsdScriptSetGlobalVar", // name
54982780287SAidan Dodds         "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_6ScriptEjPvj", // symbol name 32bit
55082780287SAidan Dodds         "_Z21rsdScriptSetGlobalVarPKN7android12renderscript7ContextEPKNS0_6ScriptEjPvm", // symbol name 64bit
55182780287SAidan Dodds         0, // version
55282780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
55382780287SAidan Dodds         &lldb_private::RenderScriptRuntime::CaptureSetGlobalVar1 // handler
55482780287SAidan Dodds     },
5554640cde1SColin Riley 
5564640cde1SColin Riley     //rsdAllocation
55782780287SAidan Dodds     {
55882780287SAidan Dodds         "rsdAllocationInit", // name
55982780287SAidan Dodds         "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_10AllocationEb", // symbol name 32bit
56082780287SAidan Dodds         "_Z17rsdAllocationInitPKN7android12renderscript7ContextEPNS0_10AllocationEb", // symbol name 64bit
56182780287SAidan Dodds         0, // version
56282780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
56382780287SAidan Dodds         &lldb_private::RenderScriptRuntime::CaptureAllocationInit1 // handler
56482780287SAidan Dodds     },
56582780287SAidan Dodds     {
56682780287SAidan Dodds         "rsdAllocationRead2D", //name
56782780287SAidan Dodds         "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_10AllocationEjjj23RsAllocationCubemapFacejjPvjj", // symbol name 32bit
56882780287SAidan Dodds         "_Z19rsdAllocationRead2DPKN7android12renderscript7ContextEPKNS0_10AllocationEjjj23RsAllocationCubemapFacejjPvmm", // symbol name 64bit
56982780287SAidan Dodds         0, // version
57082780287SAidan Dodds         RenderScriptRuntime::eModuleKindDriver, // type
57182780287SAidan Dodds         nullptr // handler
57282780287SAidan Dodds     },
573e69df382SEwan Crawford     {
574e69df382SEwan Crawford         "rsdAllocationDestroy", // name
575e69df382SEwan Crawford         "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_10AllocationE", // symbol name 32bit
576e69df382SEwan Crawford         "_Z20rsdAllocationDestroyPKN7android12renderscript7ContextEPNS0_10AllocationE", // symbol name 64bit
577e69df382SEwan Crawford         0, // version
578e69df382SEwan Crawford         RenderScriptRuntime::eModuleKindDriver, // type
579e69df382SEwan Crawford         &lldb_private::RenderScriptRuntime::CaptureAllocationDestroy // handler
580e69df382SEwan Crawford     },
5814640cde1SColin Riley };
5824640cde1SColin Riley 
583222b937cSEugene Zelenko const size_t RenderScriptRuntime::s_runtimeHookCount = sizeof(s_runtimeHookDefns)/sizeof(s_runtimeHookDefns[0]);
5844640cde1SColin Riley 
5854640cde1SColin Riley bool
5864640cde1SColin Riley RenderScriptRuntime::HookCallback(void *baton, StoppointCallbackContext *ctx, lldb::user_id_t break_id, lldb::user_id_t break_loc_id)
5874640cde1SColin Riley {
5884640cde1SColin Riley     RuntimeHook* hook_info = (RuntimeHook*)baton;
5894640cde1SColin Riley     ExecutionContext context(ctx->exe_ctx_ref);
5904640cde1SColin Riley 
5914640cde1SColin Riley     RenderScriptRuntime *lang_rt = (RenderScriptRuntime *)context.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
5924640cde1SColin Riley 
5934640cde1SColin Riley     lang_rt->HookCallback(hook_info, context);
5944640cde1SColin Riley 
5954640cde1SColin Riley     return false;
5964640cde1SColin Riley }
5974640cde1SColin Riley 
5984640cde1SColin Riley void
5994640cde1SColin Riley RenderScriptRuntime::HookCallback(RuntimeHook* hook_info, ExecutionContext& context)
6004640cde1SColin Riley {
6014640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
6024640cde1SColin Riley 
6034640cde1SColin Riley     if (log)
6044640cde1SColin Riley         log->Printf ("RenderScriptRuntime::HookCallback - '%s' .", hook_info->defn->name);
6054640cde1SColin Riley 
6064640cde1SColin Riley     if (hook_info->defn->grabber)
6074640cde1SColin Riley     {
6084640cde1SColin Riley         (this->*(hook_info->defn->grabber))(hook_info, context);
6094640cde1SColin Riley     }
6104640cde1SColin Riley }
6114640cde1SColin Riley 
6124640cde1SColin Riley bool
61382780287SAidan Dodds RenderScriptRuntime::GetArgSimple(ExecutionContext &context, uint32_t arg, uint64_t *data)
6144640cde1SColin Riley {
6154640cde1SColin Riley     if (!data)
6164640cde1SColin Riley         return false;
6174640cde1SColin Riley 
61882780287SAidan Dodds     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
6194640cde1SColin Riley     Error error;
6204640cde1SColin Riley     RegisterContext* reg_ctx = context.GetRegisterContext();
6214640cde1SColin Riley     Process* process = context.GetProcessPtr();
62282780287SAidan Dodds     bool success = false; // return value
6234640cde1SColin Riley 
62482780287SAidan Dodds     if (!context.GetTargetPtr())
62582780287SAidan Dodds     {
62682780287SAidan Dodds         if (log)
62782780287SAidan Dodds             log->Printf("RenderScriptRuntime::GetArgSimple - Invalid target");
62882780287SAidan Dodds 
62982780287SAidan Dodds         return false;
63082780287SAidan Dodds     }
63182780287SAidan Dodds 
63282780287SAidan Dodds     switch (context.GetTargetPtr()->GetArchitecture().GetMachine())
63382780287SAidan Dodds     {
63482780287SAidan Dodds         case llvm::Triple::ArchType::x86:
6354640cde1SColin Riley         {
6364640cde1SColin Riley             uint64_t sp = reg_ctx->GetSP();
6374640cde1SColin Riley             uint32_t offset = (1 + arg) * sizeof(uint32_t);
63882780287SAidan Dodds             uint32_t result = 0;
63982780287SAidan Dodds             process->ReadMemory(sp + offset, &result, sizeof(uint32_t), error);
6404640cde1SColin Riley             if (error.Fail())
6414640cde1SColin Riley             {
6424640cde1SColin Riley                 if (log)
64382780287SAidan Dodds                     log->Printf ("RenderScriptRuntime:: GetArgSimple - error reading X86 stack: %s.", error.AsCString());
6444640cde1SColin Riley             }
64582780287SAidan Dodds             else
6464640cde1SColin Riley             {
64782780287SAidan Dodds                 *data = result;
64882780287SAidan Dodds                 success = true;
64982780287SAidan Dodds             }
65082780287SAidan Dodds 
65182780287SAidan Dodds             break;
65282780287SAidan Dodds         }
65382780287SAidan Dodds         case llvm::Triple::ArchType::arm:
65482780287SAidan Dodds         {
65582780287SAidan Dodds             // arm 32 bit
6564640cde1SColin Riley             if (arg < 4)
6574640cde1SColin Riley             {
6584640cde1SColin Riley                 const RegisterInfo* rArg = reg_ctx->GetRegisterInfoAtIndex(arg);
6594640cde1SColin Riley                 RegisterValue rVal;
66002f1c5d1SEwan Crawford                 success = reg_ctx->ReadRegister(rArg, rVal);
66102f1c5d1SEwan Crawford                 if (success)
66202f1c5d1SEwan Crawford                 {
6634640cde1SColin Riley                     (*data) = rVal.GetAsUInt32();
66402f1c5d1SEwan Crawford                 }
66502f1c5d1SEwan Crawford                 else
66602f1c5d1SEwan Crawford                 {
66702f1c5d1SEwan Crawford                     if (log)
66802f1c5d1SEwan Crawford                         log->Printf ("RenderScriptRuntime:: GetArgSimple - error reading ARM register: %d.", arg);
66902f1c5d1SEwan Crawford                 }
6704640cde1SColin Riley             }
6714640cde1SColin Riley             else
6724640cde1SColin Riley             {
6734640cde1SColin Riley                 uint64_t sp = reg_ctx->GetSP();
6744640cde1SColin Riley                 uint32_t offset = (arg-4) * sizeof(uint32_t);
6754640cde1SColin Riley                 process->ReadMemory(sp + offset, &data, sizeof(uint32_t), error);
6764640cde1SColin Riley                 if (error.Fail())
6774640cde1SColin Riley                 {
6784640cde1SColin Riley                     if (log)
67982780287SAidan Dodds                         log->Printf ("RenderScriptRuntime:: GetArgSimple - error reading ARM stack: %s.", error.AsCString());
68082780287SAidan Dodds                 }
68182780287SAidan Dodds                 else
68282780287SAidan Dodds                 {
68382780287SAidan Dodds                     success = true;
6844640cde1SColin Riley                 }
6854640cde1SColin Riley             }
68682780287SAidan Dodds 
68782780287SAidan Dodds             break;
6884640cde1SColin Riley         }
68982780287SAidan Dodds         case llvm::Triple::ArchType::aarch64:
69082780287SAidan Dodds         {
69182780287SAidan Dodds             // arm 64 bit
69282780287SAidan Dodds             // first 8 arguments are in the registers
69382780287SAidan Dodds             if (arg < 8)
69482780287SAidan Dodds             {
69582780287SAidan Dodds                 const RegisterInfo* rArg = reg_ctx->GetRegisterInfoAtIndex(arg);
69682780287SAidan Dodds                 RegisterValue rVal;
69782780287SAidan Dodds                 success = reg_ctx->ReadRegister(rArg, rVal);
69882780287SAidan Dodds                 if (success)
69982780287SAidan Dodds                 {
70082780287SAidan Dodds                     *data = rVal.GetAsUInt64();
70182780287SAidan Dodds                 }
70282780287SAidan Dodds                 else
70382780287SAidan Dodds                 {
70482780287SAidan Dodds                     if (log)
70582780287SAidan Dodds                         log->Printf("RenderScriptRuntime::GetArgSimple() - AARCH64 - Error while reading the argument #%d", arg);
70682780287SAidan Dodds                 }
70782780287SAidan Dodds             }
70882780287SAidan Dodds             else
70982780287SAidan Dodds             {
71082780287SAidan Dodds                 // @TODO: need to find the argument in the stack
71182780287SAidan Dodds                 if (log)
71282780287SAidan Dodds                     log->Printf("RenderScriptRuntime::GetArgSimple - AARCH64 - FOR #ARG >= 8 NOT IMPLEMENTED YET. Argument number: %d", arg);
71382780287SAidan Dodds             }
71482780287SAidan Dodds             break;
71582780287SAidan Dodds         }
71674b396d9SAidan Dodds         case llvm::Triple::ArchType::mipsel:
71774b396d9SAidan Dodds         {
71874b396d9SAidan Dodds 
71974b396d9SAidan Dodds             // read from the registers
72074b396d9SAidan Dodds             if (arg < 4){
72174b396d9SAidan Dodds                 const RegisterInfo* rArg = reg_ctx->GetRegisterInfoAtIndex(arg + 4);
72274b396d9SAidan Dodds                 RegisterValue rVal;
72374b396d9SAidan Dodds                 success = reg_ctx->ReadRegister(rArg, rVal);
72474b396d9SAidan Dodds                 if (success)
72574b396d9SAidan Dodds                 {
72674b396d9SAidan Dodds                     *data = rVal.GetAsUInt64();
72774b396d9SAidan Dodds                 }
72874b396d9SAidan Dodds                 else
72974b396d9SAidan Dodds                 {
73074b396d9SAidan Dodds                     if (log)
73174b396d9SAidan Dodds                         log->Printf("RenderScriptRuntime::GetArgSimple() - Mips - Error while reading the argument #%d", arg);
73274b396d9SAidan Dodds                 }
73374b396d9SAidan Dodds 
73474b396d9SAidan Dodds             }
73574b396d9SAidan Dodds 
73674b396d9SAidan Dodds             // read from the stack
73774b396d9SAidan Dodds             else
73874b396d9SAidan Dodds             {
73974b396d9SAidan Dodds                 uint64_t sp = reg_ctx->GetSP();
74074b396d9SAidan Dodds                 uint32_t offset = arg * sizeof(uint32_t);
74174b396d9SAidan Dodds                 process->ReadMemory(sp + offset, &data, sizeof(uint32_t), error);
74274b396d9SAidan Dodds                 if (error.Fail())
74374b396d9SAidan Dodds                 {
74474b396d9SAidan Dodds                     if (log)
74574b396d9SAidan Dodds                         log->Printf ("RenderScriptRuntime::GetArgSimple - error reading Mips stack: %s.", error.AsCString());
74674b396d9SAidan Dodds                 }
74774b396d9SAidan Dodds                 else
74874b396d9SAidan Dodds                 {
74974b396d9SAidan Dodds                     success = true;
75074b396d9SAidan Dodds                 }
75174b396d9SAidan Dodds             }
75274b396d9SAidan Dodds 
75374b396d9SAidan Dodds             break;
75474b396d9SAidan Dodds         }
75502f1c5d1SEwan Crawford         case llvm::Triple::ArchType::mips64el:
75602f1c5d1SEwan Crawford         {
75702f1c5d1SEwan Crawford             // read from the registers
75802f1c5d1SEwan Crawford             if (arg < 8)
75902f1c5d1SEwan Crawford             {
76002f1c5d1SEwan Crawford                 const RegisterInfo* rArg = reg_ctx->GetRegisterInfoAtIndex(arg + 4);
76102f1c5d1SEwan Crawford                 RegisterValue rVal;
76202f1c5d1SEwan Crawford                 success = reg_ctx->ReadRegister(rArg, rVal);
76302f1c5d1SEwan Crawford                 if (success)
76402f1c5d1SEwan Crawford                 {
76502f1c5d1SEwan Crawford                     (*data) = rVal.GetAsUInt64();
76602f1c5d1SEwan Crawford                 }
76702f1c5d1SEwan Crawford                 else
76802f1c5d1SEwan Crawford                 {
76902f1c5d1SEwan Crawford                     if (log)
77002f1c5d1SEwan Crawford                         log->Printf("RenderScriptRuntime::GetArgSimple - Mips64 - Error reading the argument #%d", arg);
77102f1c5d1SEwan Crawford                 }
77202f1c5d1SEwan Crawford             }
77302f1c5d1SEwan Crawford 
77402f1c5d1SEwan Crawford             // read from the stack
77502f1c5d1SEwan Crawford             else
77602f1c5d1SEwan Crawford             {
77702f1c5d1SEwan Crawford                 uint64_t sp = reg_ctx->GetSP();
77802f1c5d1SEwan Crawford                 uint32_t offset = (arg - 8) * sizeof(uint64_t);
77902f1c5d1SEwan Crawford                 process->ReadMemory(sp + offset, &data, sizeof(uint64_t), error);
78002f1c5d1SEwan Crawford                 if (error.Fail())
78102f1c5d1SEwan Crawford                 {
78202f1c5d1SEwan Crawford                     if (log)
78302f1c5d1SEwan Crawford                         log->Printf ("RenderScriptRuntime::GetArgSimple - Mips64 - Error reading Mips64 stack: %s.", error.AsCString());
78402f1c5d1SEwan Crawford                 }
78502f1c5d1SEwan Crawford                 else
78602f1c5d1SEwan Crawford                 {
78702f1c5d1SEwan Crawford                     success = true;
78802f1c5d1SEwan Crawford                 }
78902f1c5d1SEwan Crawford             }
79002f1c5d1SEwan Crawford 
79102f1c5d1SEwan Crawford             break;
79202f1c5d1SEwan Crawford         }
79382780287SAidan Dodds         default:
79482780287SAidan Dodds         {
79582780287SAidan Dodds             // invalid architecture
79682780287SAidan Dodds             if (log)
79782780287SAidan Dodds                 log->Printf("RenderScriptRuntime::GetArgSimple - Architecture not supported");
79882780287SAidan Dodds 
79982780287SAidan Dodds         }
80082780287SAidan Dodds     }
80182780287SAidan Dodds 
80282780287SAidan Dodds     return success;
8034640cde1SColin Riley }
8044640cde1SColin Riley 
8054640cde1SColin Riley void
8064640cde1SColin Riley RenderScriptRuntime::CaptureSetGlobalVar1(RuntimeHook* hook_info, ExecutionContext& context)
8074640cde1SColin Riley {
8084640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
8094640cde1SColin Riley 
8104640cde1SColin Riley     //Context, Script, int, data, length
8114640cde1SColin Riley 
81282780287SAidan Dodds     uint64_t rs_context_u64 = 0U;
81382780287SAidan Dodds     uint64_t rs_script_u64 = 0U;
81482780287SAidan Dodds     uint64_t rs_id_u64 = 0U;
81582780287SAidan Dodds     uint64_t rs_data_u64 = 0U;
81682780287SAidan Dodds     uint64_t rs_length_u64 = 0U;
8174640cde1SColin Riley 
81882780287SAidan Dodds     bool success =
81982780287SAidan Dodds         GetArgSimple(context, 0, &rs_context_u64) &&
82082780287SAidan Dodds         GetArgSimple(context, 1, &rs_script_u64) &&
82182780287SAidan Dodds         GetArgSimple(context, 2, &rs_id_u64) &&
82282780287SAidan Dodds         GetArgSimple(context, 3, &rs_data_u64) &&
82382780287SAidan Dodds         GetArgSimple(context, 4, &rs_length_u64);
8244640cde1SColin Riley 
82582780287SAidan Dodds     if (!success)
82682780287SAidan Dodds     {
82782780287SAidan Dodds         if (log)
82882780287SAidan Dodds             log->Printf("RenderScriptRuntime::CaptureSetGlobalVar1 - Error while reading the function parameters");
82982780287SAidan Dodds         return;
83082780287SAidan Dodds     }
8314640cde1SColin Riley 
8324640cde1SColin Riley     if (log)
8334640cde1SColin Riley     {
8344640cde1SColin Riley         log->Printf ("RenderScriptRuntime::CaptureSetGlobalVar1 - 0x%" PRIx64 ",0x%" PRIx64 " slot %" PRIu64 " = 0x%" PRIx64 ":%" PRIu64 "bytes.",
83582780287SAidan Dodds                         rs_context_u64, rs_script_u64, rs_id_u64, rs_data_u64, rs_length_u64);
8364640cde1SColin Riley 
83782780287SAidan Dodds         addr_t script_addr =  (addr_t)rs_script_u64;
8384640cde1SColin Riley         if (m_scriptMappings.find( script_addr ) != m_scriptMappings.end())
8394640cde1SColin Riley         {
8404640cde1SColin Riley             auto rsm = m_scriptMappings[script_addr];
84182780287SAidan Dodds             if (rs_id_u64 < rsm->m_globals.size())
8424640cde1SColin Riley             {
84382780287SAidan Dodds                 auto rsg = rsm->m_globals[rs_id_u64];
8444640cde1SColin Riley                 log->Printf ("RenderScriptRuntime::CaptureSetGlobalVar1 - Setting of '%s' within '%s' inferred", rsg.m_name.AsCString(),
8454640cde1SColin Riley                                 rsm->m_module->GetFileSpec().GetFilename().AsCString());
8464640cde1SColin Riley             }
8474640cde1SColin Riley         }
8484640cde1SColin Riley     }
8494640cde1SColin Riley }
8504640cde1SColin Riley 
8514640cde1SColin Riley void
8524640cde1SColin Riley RenderScriptRuntime::CaptureAllocationInit1(RuntimeHook* hook_info, ExecutionContext& context)
8534640cde1SColin Riley {
8544640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
8554640cde1SColin Riley 
8564640cde1SColin Riley     //Context, Alloc, bool
8574640cde1SColin Riley 
85882780287SAidan Dodds     uint64_t rs_context_u64 = 0U;
85982780287SAidan Dodds     uint64_t rs_alloc_u64 = 0U;
86082780287SAidan Dodds     uint64_t rs_forceZero_u64 = 0U;
8614640cde1SColin Riley 
86282780287SAidan Dodds     bool success =
86382780287SAidan Dodds         GetArgSimple(context, 0, &rs_context_u64) &&
86482780287SAidan Dodds         GetArgSimple(context, 1, &rs_alloc_u64) &&
86582780287SAidan Dodds         GetArgSimple(context, 2, &rs_forceZero_u64);
86682780287SAidan Dodds     if (!success) // error case
86782780287SAidan Dodds     {
86882780287SAidan Dodds         if (log)
86982780287SAidan Dodds             log->Printf("RenderScriptRuntime::CaptureAllocationInit1 - Error while reading the function parameters");
87082780287SAidan Dodds         return; // abort
87182780287SAidan Dodds     }
8724640cde1SColin Riley 
8734640cde1SColin Riley     if (log)
8744640cde1SColin Riley         log->Printf ("RenderScriptRuntime::CaptureAllocationInit1 - 0x%" PRIx64 ",0x%" PRIx64 ",0x%" PRIx64 " .",
87582780287SAidan Dodds                         rs_context_u64, rs_alloc_u64, rs_forceZero_u64);
87678f339d1SEwan Crawford 
87778f339d1SEwan Crawford     AllocationDetails* alloc = LookUpAllocation(rs_alloc_u64, true);
87878f339d1SEwan Crawford     if (alloc)
87978f339d1SEwan Crawford         alloc->context = rs_context_u64;
8804640cde1SColin Riley }
8814640cde1SColin Riley 
8824640cde1SColin Riley void
883e69df382SEwan Crawford RenderScriptRuntime::CaptureAllocationDestroy(RuntimeHook* hook_info, ExecutionContext& context)
884e69df382SEwan Crawford {
885e69df382SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
886e69df382SEwan Crawford 
887e69df382SEwan Crawford     // Context, Alloc
888e69df382SEwan Crawford     uint64_t rs_context_u64 = 0U;
889e69df382SEwan Crawford     uint64_t rs_alloc_u64 = 0U;
890e69df382SEwan Crawford 
891e69df382SEwan Crawford     bool success = GetArgSimple(context, 0, &rs_context_u64) && GetArgSimple(context, 1, &rs_alloc_u64);
892e69df382SEwan Crawford     if (!success) // error case
893e69df382SEwan Crawford     {
894e69df382SEwan Crawford         if (log)
895e69df382SEwan Crawford             log->Printf("RenderScriptRuntime::CaptureAllocationDestroy - Error while reading the function parameters");
896e69df382SEwan Crawford         return; // abort
897e69df382SEwan Crawford     }
898e69df382SEwan Crawford 
899e69df382SEwan Crawford     if (log)
900e69df382SEwan Crawford         log->Printf("RenderScriptRuntime::CaptureAllocationDestroy - 0x%" PRIx64 ", 0x%" PRIx64 ".",
901e69df382SEwan Crawford                     rs_context_u64, rs_alloc_u64);
902e69df382SEwan Crawford 
903e69df382SEwan Crawford     for (auto iter = m_allocations.begin(); iter != m_allocations.end(); ++iter)
904e69df382SEwan Crawford     {
905e69df382SEwan Crawford         auto& allocation_ap = *iter; // get the unique pointer
906e69df382SEwan Crawford         if (allocation_ap->address.isValid() && *allocation_ap->address.get() == rs_alloc_u64)
907e69df382SEwan Crawford         {
908e69df382SEwan Crawford             m_allocations.erase(iter);
909e69df382SEwan Crawford             if (log)
910e69df382SEwan Crawford                 log->Printf("RenderScriptRuntime::CaptureAllocationDestroy - Deleted allocation entry");
911e69df382SEwan Crawford             return;
912e69df382SEwan Crawford         }
913e69df382SEwan Crawford     }
914e69df382SEwan Crawford 
915e69df382SEwan Crawford     if (log)
916e69df382SEwan Crawford         log->Printf("RenderScriptRuntime::CaptureAllocationDestroy - Couldn't find destroyed allocation");
917e69df382SEwan Crawford }
918e69df382SEwan Crawford 
919e69df382SEwan Crawford void
9204640cde1SColin Riley RenderScriptRuntime::CaptureScriptInit1(RuntimeHook* hook_info, ExecutionContext& context)
9214640cde1SColin Riley {
9224640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
9234640cde1SColin Riley 
9244640cde1SColin Riley     //Context, Script, resname Str, cachedir Str
9254640cde1SColin Riley     Error error;
9264640cde1SColin Riley     Process* process = context.GetProcessPtr();
9274640cde1SColin Riley 
92882780287SAidan Dodds     uint64_t rs_context_u64 = 0U;
92982780287SAidan Dodds     uint64_t rs_script_u64 = 0U;
93082780287SAidan Dodds     uint64_t rs_resnameptr_u64 = 0U;
93182780287SAidan Dodds     uint64_t rs_cachedirptr_u64 = 0U;
9324640cde1SColin Riley 
9334640cde1SColin Riley     std::string resname;
9344640cde1SColin Riley     std::string cachedir;
9354640cde1SColin Riley 
93682780287SAidan Dodds     // read the function parameters
93782780287SAidan Dodds     bool success =
93882780287SAidan Dodds         GetArgSimple(context, 0, &rs_context_u64) &&
93982780287SAidan Dodds         GetArgSimple(context, 1, &rs_script_u64) &&
94082780287SAidan Dodds         GetArgSimple(context, 2, &rs_resnameptr_u64) &&
94182780287SAidan Dodds         GetArgSimple(context, 3, &rs_cachedirptr_u64);
9424640cde1SColin Riley 
94382780287SAidan Dodds     if (!success)
94482780287SAidan Dodds     {
94582780287SAidan Dodds         if (log)
94682780287SAidan Dodds             log->Printf("RenderScriptRuntime::CaptureScriptInit1 - Error while reading the function parameters");
94782780287SAidan Dodds         return;
94882780287SAidan Dodds     }
94982780287SAidan Dodds 
95082780287SAidan Dodds     process->ReadCStringFromMemory((lldb::addr_t)rs_resnameptr_u64, resname, error);
9514640cde1SColin Riley     if (error.Fail())
9524640cde1SColin Riley     {
9534640cde1SColin Riley         if (log)
9544640cde1SColin Riley             log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - error reading resname: %s.", error.AsCString());
9554640cde1SColin Riley 
9564640cde1SColin Riley     }
9574640cde1SColin Riley 
95882780287SAidan Dodds     process->ReadCStringFromMemory((lldb::addr_t)rs_cachedirptr_u64, cachedir, error);
9594640cde1SColin Riley     if (error.Fail())
9604640cde1SColin Riley     {
9614640cde1SColin Riley         if (log)
9624640cde1SColin Riley             log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - error reading cachedir: %s.", error.AsCString());
9634640cde1SColin Riley     }
9644640cde1SColin Riley 
9654640cde1SColin Riley     if (log)
9664640cde1SColin Riley         log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - 0x%" PRIx64 ",0x%" PRIx64 " => '%s' at '%s' .",
96782780287SAidan Dodds                      rs_context_u64, rs_script_u64, resname.c_str(), cachedir.c_str());
9684640cde1SColin Riley 
9694640cde1SColin Riley     if (resname.size() > 0)
9704640cde1SColin Riley     {
9714640cde1SColin Riley         StreamString strm;
9724640cde1SColin Riley         strm.Printf("librs.%s.so", resname.c_str());
9734640cde1SColin Riley 
97478f339d1SEwan Crawford         ScriptDetails* script = LookUpScript(rs_script_u64, true);
97578f339d1SEwan Crawford         if (script)
97678f339d1SEwan Crawford         {
97778f339d1SEwan Crawford             script->type = ScriptDetails::eScriptC;
97878f339d1SEwan Crawford             script->cacheDir = cachedir;
97978f339d1SEwan Crawford             script->resName = resname;
98078f339d1SEwan Crawford             script->scriptDyLib = strm.GetData();
98178f339d1SEwan Crawford             script->context = addr_t(rs_context_u64);
98278f339d1SEwan Crawford         }
9834640cde1SColin Riley 
9844640cde1SColin Riley         if (log)
9854640cde1SColin Riley             log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - '%s' tagged with context 0x%" PRIx64 " and script 0x%" PRIx64 ".",
98682780287SAidan Dodds                          strm.GetData(), rs_context_u64, rs_script_u64);
9874640cde1SColin Riley     }
9884640cde1SColin Riley     else if (log)
9894640cde1SColin Riley     {
9904640cde1SColin Riley         log->Printf ("RenderScriptRuntime::CaptureScriptInit1 - resource name invalid, Script not tagged");
9914640cde1SColin Riley     }
9924640cde1SColin Riley }
9934640cde1SColin Riley 
9944640cde1SColin Riley void
9954640cde1SColin Riley RenderScriptRuntime::LoadRuntimeHooks(lldb::ModuleSP module, ModuleKind kind)
9964640cde1SColin Riley {
9974640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
9984640cde1SColin Riley 
9994640cde1SColin Riley     if (!module)
10004640cde1SColin Riley     {
10014640cde1SColin Riley         return;
10024640cde1SColin Riley     }
10034640cde1SColin Riley 
100482780287SAidan Dodds     Target &target = GetProcess()->GetTarget();
100582780287SAidan Dodds     llvm::Triple::ArchType targetArchType = target.GetArchitecture().GetMachine();
100682780287SAidan Dodds 
100782780287SAidan Dodds     if (targetArchType != llvm::Triple::ArchType::x86
100882780287SAidan Dodds         && targetArchType != llvm::Triple::ArchType::arm
100902f1c5d1SEwan Crawford         && targetArchType != llvm::Triple::ArchType::aarch64
101074b396d9SAidan Dodds         && targetArchType != llvm::Triple::ArchType::mipsel
101102f1c5d1SEwan Crawford         && targetArchType != llvm::Triple::ArchType::mips64el
101202f1c5d1SEwan Crawford     )
10134640cde1SColin Riley     {
10144640cde1SColin Riley         if (log)
101574b396d9SAidan Dodds             log->Printf ("RenderScriptRuntime::LoadRuntimeHooks - Unable to hook runtime. Only X86, ARM, Mips supported currently.");
10164640cde1SColin Riley 
10174640cde1SColin Riley         return;
10184640cde1SColin Riley     }
10194640cde1SColin Riley 
102082780287SAidan Dodds     uint32_t archByteSize = target.GetArchitecture().GetAddressByteSize();
10214640cde1SColin Riley 
10224640cde1SColin Riley     for (size_t idx = 0; idx < s_runtimeHookCount; idx++)
10234640cde1SColin Riley     {
10244640cde1SColin Riley         const HookDefn* hook_defn = &s_runtimeHookDefns[idx];
10254640cde1SColin Riley         if (hook_defn->kind != kind) {
10264640cde1SColin Riley             continue;
10274640cde1SColin Riley         }
10284640cde1SColin Riley 
102982780287SAidan Dodds         const char* symbol_name = (archByteSize == 4) ? hook_defn->symbol_name_m32 : hook_defn->symbol_name_m64;
103082780287SAidan Dodds 
103182780287SAidan Dodds         const Symbol *sym = module->FindFirstSymbolWithNameAndType(ConstString(symbol_name), eSymbolTypeCode);
103282780287SAidan Dodds         if (!sym){
103382780287SAidan Dodds             if (log){
103482780287SAidan Dodds                 log->Printf("RenderScriptRuntime::LoadRuntimeHooks - ERROR: Symbol '%s' related to the function %s not found", symbol_name, hook_defn->name);
103582780287SAidan Dodds             }
103682780287SAidan Dodds             continue;
103782780287SAidan Dodds         }
10384640cde1SColin Riley 
1039358cf1eaSGreg Clayton         addr_t addr = sym->GetLoadAddress(&target);
10404640cde1SColin Riley         if (addr == LLDB_INVALID_ADDRESS)
10414640cde1SColin Riley         {
10424640cde1SColin Riley             if (log)
10434640cde1SColin Riley                 log->Printf ("RenderScriptRuntime::LoadRuntimeHooks - Unable to resolve the address of hook function '%s' with symbol '%s'.",
104482780287SAidan Dodds                              hook_defn->name, symbol_name);
10454640cde1SColin Riley             continue;
10464640cde1SColin Riley         }
104782780287SAidan Dodds         else
104882780287SAidan Dodds         {
104982780287SAidan Dodds             if (log)
105082780287SAidan Dodds                 log->Printf("RenderScriptRuntime::LoadRuntimeHooks - Function %s, address resolved at 0x%" PRIx64, hook_defn->name, addr);
105182780287SAidan Dodds         }
10524640cde1SColin Riley 
10534640cde1SColin Riley         RuntimeHookSP hook(new RuntimeHook());
10544640cde1SColin Riley         hook->address = addr;
10554640cde1SColin Riley         hook->defn = hook_defn;
10564640cde1SColin Riley         hook->bp_sp = target.CreateBreakpoint(addr, true, false);
10574640cde1SColin Riley         hook->bp_sp->SetCallback(HookCallback, hook.get(), true);
10584640cde1SColin Riley         m_runtimeHooks[addr] = hook;
10594640cde1SColin Riley         if (log)
10604640cde1SColin Riley         {
10614640cde1SColin Riley             log->Printf ("RenderScriptRuntime::LoadRuntimeHooks - Successfully hooked '%s' in '%s' version %" PRIu64 " at 0x%" PRIx64 ".",
10624640cde1SColin Riley                 hook_defn->name, module->GetFileSpec().GetFilename().AsCString(), (uint64_t)hook_defn->version, (uint64_t)addr);
10634640cde1SColin Riley         }
10644640cde1SColin Riley     }
10654640cde1SColin Riley }
10664640cde1SColin Riley 
10674640cde1SColin Riley void
10684640cde1SColin Riley RenderScriptRuntime::FixupScriptDetails(RSModuleDescriptorSP rsmodule_sp)
10694640cde1SColin Riley {
10704640cde1SColin Riley     if (!rsmodule_sp)
10714640cde1SColin Riley         return;
10724640cde1SColin Riley 
10734640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
10744640cde1SColin Riley 
10754640cde1SColin Riley     const ModuleSP module = rsmodule_sp->m_module;
10764640cde1SColin Riley     const FileSpec& file = module->GetPlatformFileSpec();
10774640cde1SColin Riley 
107878f339d1SEwan Crawford     // Iterate over all of the scripts that we currently know of.
107978f339d1SEwan Crawford     // Note: We cant push or pop to m_scripts here or it may invalidate rs_script.
10804640cde1SColin Riley     for (const auto & rs_script : m_scripts)
10814640cde1SColin Riley     {
108278f339d1SEwan Crawford         // Extract the expected .so file path for this script.
108378f339d1SEwan Crawford         std::string dylib;
108478f339d1SEwan Crawford         if (!rs_script->scriptDyLib.get(dylib))
108578f339d1SEwan Crawford             continue;
108678f339d1SEwan Crawford 
108778f339d1SEwan Crawford         // Only proceed if the module that has loaded corresponds to this script.
108878f339d1SEwan Crawford         if (file.GetFilename() != ConstString(dylib.c_str()))
108978f339d1SEwan Crawford             continue;
109078f339d1SEwan Crawford 
109178f339d1SEwan Crawford         // Obtain the script address which we use as a key.
109278f339d1SEwan Crawford         lldb::addr_t script;
109378f339d1SEwan Crawford         if (!rs_script->script.get(script))
109478f339d1SEwan Crawford             continue;
109578f339d1SEwan Crawford 
109678f339d1SEwan Crawford         // If we have a script mapping for the current script.
109778f339d1SEwan Crawford         if (m_scriptMappings.find(script) != m_scriptMappings.end())
10984640cde1SColin Riley         {
109978f339d1SEwan Crawford             // if the module we have stored is different to the one we just received.
110078f339d1SEwan Crawford             if (m_scriptMappings[script] != rsmodule_sp)
11014640cde1SColin Riley             {
11024640cde1SColin Riley                 if (log)
11034640cde1SColin Riley                     log->Printf ("RenderScriptRuntime::FixupScriptDetails - Error: script %" PRIx64 " wants reassigned to new rsmodule '%s'.",
110478f339d1SEwan Crawford                                     (uint64_t)script, rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
11054640cde1SColin Riley             }
11064640cde1SColin Riley         }
110778f339d1SEwan Crawford         // We don't have a script mapping for the current script.
11084640cde1SColin Riley         else
11094640cde1SColin Riley         {
111078f339d1SEwan Crawford             // Obtain the script resource name.
111178f339d1SEwan Crawford             std::string resName;
111278f339d1SEwan Crawford             if (rs_script->resName.get(resName))
111378f339d1SEwan Crawford                 // Set the modules resource name.
111478f339d1SEwan Crawford                 rsmodule_sp->m_resname = resName;
111578f339d1SEwan Crawford             // Add Script/Module pair to map.
111678f339d1SEwan Crawford             m_scriptMappings[script] = rsmodule_sp;
11174640cde1SColin Riley             if (log)
11184640cde1SColin Riley                 log->Printf ("RenderScriptRuntime::FixupScriptDetails - script %" PRIx64 " associated with rsmodule '%s'.",
111978f339d1SEwan Crawford                                 (uint64_t)script, rsmodule_sp->m_module->GetFileSpec().GetFilename().AsCString());
11204640cde1SColin Riley         }
11214640cde1SColin Riley     }
11224640cde1SColin Riley }
11234640cde1SColin Riley 
112415f2bd95SEwan Crawford // Uses the Target API to evaluate the expression passed as a parameter to the function
112515f2bd95SEwan Crawford // The result of that expression is returned an unsigned 64 bit int, via the result* paramter.
112615f2bd95SEwan Crawford // Function returns true on success, and false on failure
112715f2bd95SEwan Crawford bool
112815f2bd95SEwan Crawford RenderScriptRuntime::EvalRSExpression(const char* expression, StackFrame* frame_ptr, uint64_t* result)
112915f2bd95SEwan Crawford {
113015f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
113115f2bd95SEwan Crawford     if (log)
113215f2bd95SEwan Crawford         log->Printf("RenderScriptRuntime::EvalRSExpression(%s)", expression);
113315f2bd95SEwan Crawford 
113415f2bd95SEwan Crawford     ValueObjectSP expr_result;
113515f2bd95SEwan Crawford     // Perform the actual expression evaluation
113615f2bd95SEwan Crawford     GetProcess()->GetTarget().EvaluateExpression(expression, frame_ptr, expr_result);
113715f2bd95SEwan Crawford 
113815f2bd95SEwan Crawford     if (!expr_result)
113915f2bd95SEwan Crawford     {
114015f2bd95SEwan Crawford        if (log)
114115f2bd95SEwan Crawford            log->Printf("RenderScriptRuntime::EvalRSExpression -  Error: Couldn't evaluate expression");
114215f2bd95SEwan Crawford        return false;
114315f2bd95SEwan Crawford     }
114415f2bd95SEwan Crawford 
114515f2bd95SEwan Crawford     // The result of the expression is invalid
114615f2bd95SEwan Crawford     if (!expr_result->GetError().Success())
114715f2bd95SEwan Crawford     {
114815f2bd95SEwan Crawford         Error err = expr_result->GetError();
114915f2bd95SEwan Crawford         if (err.GetError() == UserExpression::kNoResult) // Expression returned void, so this is actually a success
115015f2bd95SEwan Crawford         {
115115f2bd95SEwan Crawford             if (log)
115215f2bd95SEwan Crawford                 log->Printf("RenderScriptRuntime::EvalRSExpression - Expression returned void");
115315f2bd95SEwan Crawford 
115415f2bd95SEwan Crawford             result = nullptr;
115515f2bd95SEwan Crawford             return true;
115615f2bd95SEwan Crawford         }
115715f2bd95SEwan Crawford 
115815f2bd95SEwan Crawford         if (log)
115915f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::EvalRSExpression - Error evaluating expression result: %s", err.AsCString());
116015f2bd95SEwan Crawford         return false;
116115f2bd95SEwan Crawford     }
116215f2bd95SEwan Crawford 
116315f2bd95SEwan Crawford     bool success = false;
116415f2bd95SEwan Crawford     *result = expr_result->GetValueAsUnsigned(0, &success); // We only read the result as an unsigned int.
116515f2bd95SEwan Crawford 
116615f2bd95SEwan Crawford     if (!success)
116715f2bd95SEwan Crawford     {
116815f2bd95SEwan Crawford        if (log)
116915f2bd95SEwan Crawford            log->Printf("RenderScriptRuntime::EvalRSExpression -  Error: Couldn't convert expression result to unsigned int");
117015f2bd95SEwan Crawford        return false;
117115f2bd95SEwan Crawford     }
117215f2bd95SEwan Crawford 
117315f2bd95SEwan Crawford     return true;
117415f2bd95SEwan Crawford }
117515f2bd95SEwan Crawford 
1176b1651b8dSEwan Crawford namespace // anonymous
117715f2bd95SEwan Crawford {
1178b1651b8dSEwan Crawford     // max length of an expanded expression
1179b1651b8dSEwan Crawford     const int jit_max_expr_size = 768;
118015f2bd95SEwan Crawford 
118115f2bd95SEwan Crawford     // Format strings containing the expressions we may need to evaluate.
118215f2bd95SEwan Crawford     const char runtimeExpressions[][256] =
118315f2bd95SEwan Crawford     {
118415f2bd95SEwan Crawford      // Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap)
118515f2bd95SEwan Crawford      "(int*)_Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocationCubemapFace(0x%lx, %u, %u, %u, 0, 0)",
118615f2bd95SEwan Crawford 
118715f2bd95SEwan Crawford      // Type* rsaAllocationGetType(Context*, Allocation*)
118815f2bd95SEwan Crawford      "(void*)rsaAllocationGetType(0x%lx, 0x%lx)",
118915f2bd95SEwan Crawford 
119015f2bd95SEwan Crawford      // rsaTypeGetNativeData(Context*, Type*, void* typeData, size)
119115f2bd95SEwan Crawford      // Pack the data in the following way mHal.state.dimX; mHal.state.dimY; mHal.state.dimZ;
119215f2bd95SEwan Crawford      // mHal.state.lodCount; mHal.state.faces; mElement; into typeData
119315f2bd95SEwan Crawford      // Need to specify 32 or 64 bit for uint_t since this differs between devices
119415f2bd95SEwan Crawford      "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[0]", // X dim
119515f2bd95SEwan Crawford      "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[1]", // Y dim
119615f2bd95SEwan Crawford      "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[2]", // Z dim
119715f2bd95SEwan Crawford      "uint%u_t data[6]; (void*)rsaTypeGetNativeData(0x%lx, 0x%lx, data, 6); data[5]", // Element ptr
119815f2bd95SEwan Crawford 
119915f2bd95SEwan Crawford      // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size)
120015f2bd95SEwan Crawford      // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into elemData
12018b244e21SEwan Crawford      "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%lx, 0x%lx, data, 5); data[0]", // Type
12028b244e21SEwan Crawford      "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%lx, 0x%lx, data, 5); data[1]", // Kind
12038b244e21SEwan Crawford      "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%lx, 0x%lx, data, 5); data[3]", // Vector Size
12048b244e21SEwan Crawford      "uint32_t data[5]; (void*)rsaElementGetNativeData(0x%lx, 0x%lx, data, 5); data[4]", // Field Count
12058b244e21SEwan Crawford 
12068b244e21SEwan Crawford       // rsaElementGetSubElements(RsContext con, RsElement elem, uintptr_t *ids, const char **names,
12078b244e21SEwan Crawford       // size_t *arraySizes, uint32_t dataSize)
12088b244e21SEwan Crawford       // Needed for Allocations of structs to gather details about fields/Subelements
12098b244e21SEwan Crawford      "void* ids[%u]; const char* names[%u]; size_t arr_size[%u];"
12108b244e21SEwan Crawford      "(void*)rsaElementGetSubElements(0x%lx, 0x%lx, ids, names, arr_size, %u); ids[%u]",     // Element* of field
12118b244e21SEwan Crawford 
12128b244e21SEwan Crawford      "void* ids[%u]; const char* names[%u]; size_t arr_size[%u];"
12138b244e21SEwan Crawford      "(void*)rsaElementGetSubElements(0x%lx, 0x%lx, ids, names, arr_size, %u); names[%u]",   // Name of field
12148b244e21SEwan Crawford 
12158b244e21SEwan Crawford      "void* ids[%u]; const char* names[%u]; size_t arr_size[%u];"
12168b244e21SEwan Crawford      "(void*)rsaElementGetSubElements(0x%lx, 0x%lx, ids, names, arr_size, %u); arr_size[%u]" // Array size of field
121715f2bd95SEwan Crawford     };
121815f2bd95SEwan Crawford 
1219b1651b8dSEwan Crawford 
1220b1651b8dSEwan Crawford     // Temporary workaround for MIPS, until the compiler emits the JAL instruction when invoking directly the function.
1221b1651b8dSEwan Crawford     // At the moment, when evaluating an expression involving a function call, the LLVM codegen for Mips  emits a JAL
1222b1651b8dSEwan Crawford     // instruction, which is able to jump in the range +/- 128MB with respect to the current program counter ($pc). If
1223b1651b8dSEwan Crawford     // the requested function happens to reside outside the above region, the function address will be truncated and the
1224b1651b8dSEwan Crawford     // function invocation will fail. This is a problem in the RS plugin as we rely on the RS API to probe the number and
1225b1651b8dSEwan Crawford     // the nature of allocations. A proper solution in the MIPS compiler is currently being investigated. As temporary
1226b1651b8dSEwan Crawford     // work around for this context, we'll invoke the RS API through function pointers, which cause the compiler to emit a
1227b1651b8dSEwan Crawford     // register based JALR instruction.
1228b1651b8dSEwan Crawford     const char runtimeExpressions_mips[][512] =
1229b1651b8dSEwan Crawford     {
1230b1651b8dSEwan Crawford     // Mangled GetOffsetPointer(Allocation*, xoff, yoff, zoff, lod, cubemap)
1231b1651b8dSEwan Crawford     "int* (*f) (void*, int, int, int, int, int) = (int* (*) (void*, int, int, int, int, int)) "
1232b1651b8dSEwan Crawford         "_Z12GetOffsetPtrPKN7android12renderscript10AllocationEjjjj23RsAllocationCubemapFace; "
1233b1651b8dSEwan Crawford         "(int*) f((void*) 0x%lx, %u, %u, %u, 0, 0)",
1234b1651b8dSEwan Crawford 
1235b1651b8dSEwan Crawford     // Type* rsaAllocationGetType(Context*, Allocation*)
1236b1651b8dSEwan Crawford     "void* (*f) (void*, void*) = (void* (*) (void*, void*)) rsaAllocationGetType; (void*) f((void*) 0x%lx, (void*) 0x%lx)",
1237b1651b8dSEwan Crawford 
1238b1651b8dSEwan Crawford     // rsaTypeGetNativeData(Context*, Type*, void* typeData, size)
1239b1651b8dSEwan Crawford     // Pack the data in the following way mHal.state.dimX; mHal.state.dimY; mHal.state.dimZ;
1240b1651b8dSEwan Crawford     // mHal.state.lodCount; mHal.state.faces; mElement; into typeData
1241b1651b8dSEwan Crawford     // Need to specify 32 or 64 bit for uint_t since this differs between devices
1242b1651b8dSEwan Crawford     "uint%u_t data[6]; void* (*f)(void*, void*, uintptr_t*, uint32_t) = (void* (*)(void*, void*, uintptr_t*, uint32_t)) "
1243b1651b8dSEwan Crawford         "rsaTypeGetNativeData; (void*) f((void*) 0x%lx, (void*) 0x%lx, data, 6); data[0]",
1244b1651b8dSEwan Crawford     "uint%u_t data[6]; void* (*f)(void*, void*, uintptr_t*, uint32_t) = (void* (*)(void*, void*, uintptr_t*, uint32_t)) "
1245b1651b8dSEwan Crawford         "rsaTypeGetNativeData; (void*) f((void*) 0x%lx, (void*) 0x%lx, data, 6); data[1]",
1246b1651b8dSEwan Crawford     "uint%u_t data[6]; void* (*f)(void*, void*, uintptr_t*, uint32_t) = (void* (*)(void*, void*, uintptr_t*, uint32_t)) "
1247b1651b8dSEwan Crawford         "rsaTypeGetNativeData; (void*) f((void*) 0x%lx, (void*) 0x%lx, data, 6); data[2]",
1248b1651b8dSEwan Crawford     "uint%u_t data[6]; void* (*f)(void*, void*, uintptr_t*, uint32_t) = (void* (*)(void*, void*, uintptr_t*, uint32_t)) "
1249b1651b8dSEwan Crawford         "rsaTypeGetNativeData; (void*) f((void*) 0x%lx, (void*) 0x%lx, data, 6); data[5]",
1250b1651b8dSEwan Crawford 
1251b1651b8dSEwan Crawford     // rsaElementGetNativeData(Context*, Element*, uint32_t* elemData,size)
1252b1651b8dSEwan Crawford     // Pack mType; mKind; mNormalized; mVectorSize; NumSubElements into elemData
1253b1651b8dSEwan Crawford     "uint32_t data[5]; void* (*f)(void*, void*, uint32_t*, uint32_t) = (void* (*)(void*, void*, uint32_t*, uint32_t)) "
1254b1651b8dSEwan Crawford         "rsaElementGetNativeData; (void*) f((void*) 0x%lx, (void*) 0x%lx, data, 5); data[0]", // Type
1255b1651b8dSEwan Crawford     "uint32_t data[5]; void* (*f)(void*, void*, uint32_t*, uint32_t) = (void* (*)(void*, void*, uint32_t*, uint32_t)) "
1256b1651b8dSEwan Crawford         "rsaElementGetNativeData; (void*) f((void*) 0x%lx, (void*) 0x%lx, data, 5); data[1]", // Kind
1257b1651b8dSEwan Crawford     "uint32_t data[5]; void* (*f)(void*, void*, uint32_t*, uint32_t) = (void* (*)(void*, void*, uint32_t*, uint32_t)) "
1258b1651b8dSEwan Crawford         "rsaElementGetNativeData; (void*) f((void*) 0x%lx, (void*) 0x%lx, data, 5); data[3]", // Vector size
1259b1651b8dSEwan Crawford     "uint32_t data[5]; void* (*f)(void*, void*, uint32_t*, uint32_t) = (void* (*)(void*, void*, uint32_t*, uint32_t)) "
1260b1651b8dSEwan Crawford         "rsaElementGetNativeData; (void*) f((void*) 0x%lx, (void*) 0x%lx, data, 5); data[4]", // Field count
1261b1651b8dSEwan Crawford 
1262b1651b8dSEwan Crawford     // rsaElementGetSubElements(RsContext con, RsElement elem, uintptr_t *ids, const char **names,
1263b1651b8dSEwan Crawford     // size_t *arraySizes, uint32_t dataSize)
1264b1651b8dSEwan Crawford     // Needed for Allocations of structs to gather details about fields/Subelements
1265b1651b8dSEwan Crawford    "void* ids[%u]; const char* names[%u]; size_t arr_size[%u];"
1266b1651b8dSEwan Crawford         "void* (*f) (void*, void*, uintptr_t*, const char**, size_t*, uint32_t) = "
1267b1651b8dSEwan Crawford         "(void* (*) (void*, void*, uintptr_t*, const char**, size_t*, uint32_t)) rsaElementGetSubElements;"
1268b1651b8dSEwan Crawford         "(void*) f((void*) 0x%lx, (void*) 0x%lx, (uintptr_t*) ids, names, arr_size, (uint32_t) %u);"
1269b1651b8dSEwan Crawford         "ids[%u]", // Element* of field
1270b1651b8dSEwan Crawford    "void* ids[%u]; const char* names[%u]; size_t arr_size[%u];"
1271b1651b8dSEwan Crawford         "void* (*f) (void*, void*, uintptr_t*, const char**, size_t*, uint32_t) = "
1272b1651b8dSEwan Crawford         "(void* (*) (void*, void*, uintptr_t*, const char**, size_t*, uint32_t)) rsaElementGetSubElements;"
1273b1651b8dSEwan Crawford         "(void*) f((void*) 0x%lx, (void*) 0x%lx, (uintptr_t*) ids, names, arr_size, (uint32_t) %u);"
1274b1651b8dSEwan Crawford         "names[%u]", // Name of field
1275b1651b8dSEwan Crawford    "void* ids[%u]; const char* names[%u]; size_t arr_size[%u];"
1276b1651b8dSEwan Crawford         "void* (*f) (void*, void*, uintptr_t*, const char**, size_t*, uint32_t) = "
1277b1651b8dSEwan Crawford         "(void* (*) (void*, void*, uintptr_t*, const char**, size_t*, uint32_t)) rsaElementGetSubElements;"
1278b1651b8dSEwan Crawford         "(void*) f((void*) 0x%lx, (void*) 0x%lx, (uintptr_t*) ids, names, arr_size, (uint32_t) %u);"
1279b1651b8dSEwan Crawford         "arr_size[%u]" // Array size of field
1280b1651b8dSEwan Crawford     };
1281b1651b8dSEwan Crawford 
1282b1651b8dSEwan Crawford } // end of the anonymous namespace
1283b1651b8dSEwan Crawford 
1284b1651b8dSEwan Crawford 
1285b1651b8dSEwan Crawford // Retrieve the string to JIT for the given expression
1286b1651b8dSEwan Crawford const char*
1287b1651b8dSEwan Crawford RenderScriptRuntime::JITTemplate(ExpressionStrings e)
1288b1651b8dSEwan Crawford {
1289b1651b8dSEwan Crawford     // be nice to your Mips friend when adding new expression strings
1290b1651b8dSEwan Crawford     static_assert(sizeof(runtimeExpressions)/sizeof(runtimeExpressions[0]) ==
1291b1651b8dSEwan Crawford             sizeof(runtimeExpressions_mips)/sizeof(runtimeExpressions_mips[0]),
1292b1651b8dSEwan Crawford             "#runtimeExpressions != #runtimeExpressions_mips");
1293b1651b8dSEwan Crawford 
1294b1651b8dSEwan Crawford     assert((e >= eExprGetOffsetPtr && e <= eExprSubelementsArrSize) &&
1295b1651b8dSEwan Crawford            "Expression string out of bounds");
1296b1651b8dSEwan Crawford 
1297b1651b8dSEwan Crawford     llvm::Triple::ArchType arch = GetTargetRef().GetArchitecture().GetMachine();
1298b1651b8dSEwan Crawford 
1299b1651b8dSEwan Crawford     // mips JAL workaround
1300b1651b8dSEwan Crawford     if(arch == llvm::Triple::ArchType::mips64el || arch == llvm::Triple::ArchType::mipsel)
1301b1651b8dSEwan Crawford         return runtimeExpressions_mips[e];
1302b1651b8dSEwan Crawford     else
1303b1651b8dSEwan Crawford         return runtimeExpressions[e];
1304b1651b8dSEwan Crawford }
1305b1651b8dSEwan Crawford 
1306b1651b8dSEwan Crawford 
130715f2bd95SEwan Crawford // JITs the RS runtime for the internal data pointer of an allocation.
130815f2bd95SEwan Crawford // Is passed x,y,z coordinates for the pointer to a specific element.
130915f2bd95SEwan Crawford // Then sets the data_ptr member in Allocation with the result.
131015f2bd95SEwan Crawford // Returns true on success, false otherwise
131115f2bd95SEwan Crawford bool
131215f2bd95SEwan Crawford RenderScriptRuntime::JITDataPointer(AllocationDetails* allocation, StackFrame* frame_ptr,
131315f2bd95SEwan Crawford                                     unsigned int x, unsigned int y, unsigned int z)
131415f2bd95SEwan Crawford {
131515f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
131615f2bd95SEwan Crawford 
131715f2bd95SEwan Crawford     if (!allocation->address.isValid())
131815f2bd95SEwan Crawford     {
131915f2bd95SEwan Crawford         if (log)
132015f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITDataPointer - Failed to find allocation details");
132115f2bd95SEwan Crawford         return false;
132215f2bd95SEwan Crawford     }
132315f2bd95SEwan Crawford 
1324b1651b8dSEwan Crawford     const char* expr_cstr = JITTemplate(eExprGetOffsetPtr);
1325b1651b8dSEwan Crawford     char buffer[jit_max_expr_size];
132615f2bd95SEwan Crawford 
1327b1651b8dSEwan Crawford     int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->address.get(), x, y, z);
132815f2bd95SEwan Crawford     if (chars_written < 0)
132915f2bd95SEwan Crawford     {
133015f2bd95SEwan Crawford         if (log)
133115f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITDataPointer - Encoding error in snprintf()");
133215f2bd95SEwan Crawford         return false;
133315f2bd95SEwan Crawford     }
1334b1651b8dSEwan Crawford     else if (chars_written >= jit_max_expr_size)
133515f2bd95SEwan Crawford     {
133615f2bd95SEwan Crawford         if (log)
133715f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITDataPointer - Expression too long");
133815f2bd95SEwan Crawford         return false;
133915f2bd95SEwan Crawford     }
134015f2bd95SEwan Crawford 
134115f2bd95SEwan Crawford     uint64_t result = 0;
134215f2bd95SEwan Crawford     if (!EvalRSExpression(buffer, frame_ptr, &result))
134315f2bd95SEwan Crawford         return false;
134415f2bd95SEwan Crawford 
134515f2bd95SEwan Crawford     addr_t mem_ptr = static_cast<lldb::addr_t>(result);
134615f2bd95SEwan Crawford     allocation->data_ptr = mem_ptr;
134715f2bd95SEwan Crawford 
134815f2bd95SEwan Crawford     return true;
134915f2bd95SEwan Crawford }
135015f2bd95SEwan Crawford 
135115f2bd95SEwan Crawford // JITs the RS runtime for the internal pointer to the RS Type of an allocation
135215f2bd95SEwan Crawford // Then sets the type_ptr member in Allocation with the result.
135315f2bd95SEwan Crawford // Returns true on success, false otherwise
135415f2bd95SEwan Crawford bool
135515f2bd95SEwan Crawford RenderScriptRuntime::JITTypePointer(AllocationDetails* allocation, StackFrame* frame_ptr)
135615f2bd95SEwan Crawford {
135715f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
135815f2bd95SEwan Crawford 
135915f2bd95SEwan Crawford     if (!allocation->address.isValid() || !allocation->context.isValid())
136015f2bd95SEwan Crawford     {
136115f2bd95SEwan Crawford         if (log)
136215f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITTypePointer - Failed to find allocation details");
136315f2bd95SEwan Crawford         return false;
136415f2bd95SEwan Crawford     }
136515f2bd95SEwan Crawford 
1366b1651b8dSEwan Crawford     const char* expr_cstr = JITTemplate(eExprAllocGetType);
1367b1651b8dSEwan Crawford     char buffer[jit_max_expr_size];
136815f2bd95SEwan Crawford 
1369b1651b8dSEwan Crawford     int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->context.get(), *allocation->address.get());
137015f2bd95SEwan Crawford     if (chars_written < 0)
137115f2bd95SEwan Crawford     {
137215f2bd95SEwan Crawford         if (log)
137315f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITDataPointer - Encoding error in snprintf()");
137415f2bd95SEwan Crawford         return false;
137515f2bd95SEwan Crawford     }
1376b1651b8dSEwan Crawford     else if (chars_written >= jit_max_expr_size)
137715f2bd95SEwan Crawford     {
137815f2bd95SEwan Crawford         if (log)
137915f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITTypePointer - Expression too long");
138015f2bd95SEwan Crawford         return false;
138115f2bd95SEwan Crawford     }
138215f2bd95SEwan Crawford 
138315f2bd95SEwan Crawford     uint64_t result = 0;
138415f2bd95SEwan Crawford     if (!EvalRSExpression(buffer, frame_ptr, &result))
138515f2bd95SEwan Crawford         return false;
138615f2bd95SEwan Crawford 
138715f2bd95SEwan Crawford     addr_t type_ptr = static_cast<lldb::addr_t>(result);
138815f2bd95SEwan Crawford     allocation->type_ptr = type_ptr;
138915f2bd95SEwan Crawford 
139015f2bd95SEwan Crawford     return true;
139115f2bd95SEwan Crawford }
139215f2bd95SEwan Crawford 
139315f2bd95SEwan Crawford // JITs the RS runtime for information about the dimensions and type of an allocation
139415f2bd95SEwan Crawford // Then sets dimension and element_ptr members in Allocation with the result.
139515f2bd95SEwan Crawford // Returns true on success, false otherwise
139615f2bd95SEwan Crawford bool
139715f2bd95SEwan Crawford RenderScriptRuntime::JITTypePacked(AllocationDetails* allocation, StackFrame* frame_ptr)
139815f2bd95SEwan Crawford {
139915f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
140015f2bd95SEwan Crawford 
140115f2bd95SEwan Crawford     if (!allocation->type_ptr.isValid() || !allocation->context.isValid())
140215f2bd95SEwan Crawford     {
140315f2bd95SEwan Crawford         if (log)
140415f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITTypePacked - Failed to find allocation details");
140515f2bd95SEwan Crawford         return false;
140615f2bd95SEwan Crawford     }
140715f2bd95SEwan Crawford 
140815f2bd95SEwan Crawford     // Expression is different depending on if device is 32 or 64 bit
140915f2bd95SEwan Crawford     uint32_t archByteSize = GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
141015f2bd95SEwan Crawford     const unsigned int bits = archByteSize == 4 ? 32 : 64;
141115f2bd95SEwan Crawford 
141215f2bd95SEwan Crawford     // We want 4 elements from packed data
141315f2bd95SEwan Crawford     const unsigned int num_exprs = 4;
141415f2bd95SEwan Crawford     assert(num_exprs == (eExprTypeElemPtr - eExprTypeDimX + 1) && "Invalid number of expressions");
141515f2bd95SEwan Crawford 
1416b1651b8dSEwan Crawford     char buffer[num_exprs][jit_max_expr_size];
141715f2bd95SEwan Crawford     uint64_t results[num_exprs];
141815f2bd95SEwan Crawford 
141915f2bd95SEwan Crawford     for (unsigned int i = 0; i < num_exprs; ++i)
142015f2bd95SEwan Crawford     {
1421b1651b8dSEwan Crawford         const char* expr_cstr = JITTemplate((ExpressionStrings) (eExprTypeDimX + i));
1422b1651b8dSEwan Crawford         int chars_written = snprintf(buffer[i], jit_max_expr_size, expr_cstr, bits,
142315f2bd95SEwan Crawford                                      *allocation->context.get(), *allocation->type_ptr.get());
142415f2bd95SEwan Crawford         if (chars_written < 0)
142515f2bd95SEwan Crawford         {
142615f2bd95SEwan Crawford             if (log)
142715f2bd95SEwan Crawford                 log->Printf("RenderScriptRuntime::JITDataPointer - Encoding error in snprintf()");
142815f2bd95SEwan Crawford             return false;
142915f2bd95SEwan Crawford         }
1430b1651b8dSEwan Crawford         else if (chars_written >= jit_max_expr_size)
143115f2bd95SEwan Crawford         {
143215f2bd95SEwan Crawford             if (log)
143315f2bd95SEwan Crawford                 log->Printf("RenderScriptRuntime::JITTypePacked - Expression too long");
143415f2bd95SEwan Crawford             return false;
143515f2bd95SEwan Crawford         }
143615f2bd95SEwan Crawford 
143715f2bd95SEwan Crawford         // Perform expression evaluation
143815f2bd95SEwan Crawford         if (!EvalRSExpression(buffer[i], frame_ptr, &results[i]))
143915f2bd95SEwan Crawford             return false;
144015f2bd95SEwan Crawford     }
144115f2bd95SEwan Crawford 
144215f2bd95SEwan Crawford     // Assign results to allocation members
144315f2bd95SEwan Crawford     AllocationDetails::Dimension dims;
144415f2bd95SEwan Crawford     dims.dim_1 = static_cast<uint32_t>(results[0]);
144515f2bd95SEwan Crawford     dims.dim_2 = static_cast<uint32_t>(results[1]);
144615f2bd95SEwan Crawford     dims.dim_3 = static_cast<uint32_t>(results[2]);
144715f2bd95SEwan Crawford     allocation->dimension = dims;
144815f2bd95SEwan Crawford 
144915f2bd95SEwan Crawford     addr_t elem_ptr = static_cast<lldb::addr_t>(results[3]);
14508b244e21SEwan Crawford     allocation->element.element_ptr = elem_ptr;
145115f2bd95SEwan Crawford 
145215f2bd95SEwan Crawford     if (log)
145315f2bd95SEwan Crawford         log->Printf("RenderScriptRuntime::JITTypePacked - dims (%u, %u, %u) Element*: 0x%" PRIx64,
145415f2bd95SEwan Crawford                     dims.dim_1, dims.dim_2, dims.dim_3, elem_ptr);
145515f2bd95SEwan Crawford 
145615f2bd95SEwan Crawford     return true;
145715f2bd95SEwan Crawford }
145815f2bd95SEwan Crawford 
145915f2bd95SEwan Crawford // JITs the RS runtime for information about the Element of an allocation
14608b244e21SEwan Crawford // Then sets type, type_vec_size, field_count and type_kind members in Element with the result.
146115f2bd95SEwan Crawford // Returns true on success, false otherwise
146215f2bd95SEwan Crawford bool
14638b244e21SEwan Crawford RenderScriptRuntime::JITElementPacked(Element& elem, const lldb::addr_t context, StackFrame* frame_ptr)
146415f2bd95SEwan Crawford {
146515f2bd95SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
146615f2bd95SEwan Crawford 
14678b244e21SEwan Crawford     if (!elem.element_ptr.isValid())
146815f2bd95SEwan Crawford     {
146915f2bd95SEwan Crawford         if (log)
147015f2bd95SEwan Crawford             log->Printf("RenderScriptRuntime::JITElementPacked - Failed to find allocation details");
147115f2bd95SEwan Crawford         return false;
147215f2bd95SEwan Crawford     }
147315f2bd95SEwan Crawford 
14748b244e21SEwan Crawford     // We want 4 elements from packed data
14758b244e21SEwan Crawford     const unsigned int num_exprs = 4;
14768b244e21SEwan Crawford     assert(num_exprs == (eExprElementFieldCount - eExprElementType + 1) && "Invalid number of expressions");
147715f2bd95SEwan Crawford 
1478b1651b8dSEwan Crawford     char buffer[num_exprs][jit_max_expr_size];
147915f2bd95SEwan Crawford     uint64_t results[num_exprs];
148015f2bd95SEwan Crawford 
148115f2bd95SEwan Crawford     for (unsigned int i = 0; i < num_exprs; i++)
148215f2bd95SEwan Crawford     {
1483b1651b8dSEwan Crawford         const char* expr_cstr = JITTemplate((ExpressionStrings) (eExprElementType + i));
1484b1651b8dSEwan Crawford         int chars_written = snprintf(buffer[i], jit_max_expr_size, expr_cstr, context, *elem.element_ptr.get());
148515f2bd95SEwan Crawford         if (chars_written < 0)
148615f2bd95SEwan Crawford         {
148715f2bd95SEwan Crawford             if (log)
14888b244e21SEwan Crawford                 log->Printf("RenderScriptRuntime::JITElementPacked - Encoding error in snprintf()");
148915f2bd95SEwan Crawford             return false;
149015f2bd95SEwan Crawford         }
1491b1651b8dSEwan Crawford         else if (chars_written >= jit_max_expr_size)
149215f2bd95SEwan Crawford         {
149315f2bd95SEwan Crawford             if (log)
149415f2bd95SEwan Crawford                 log->Printf("RenderScriptRuntime::JITElementPacked - Expression too long");
149515f2bd95SEwan Crawford             return false;
149615f2bd95SEwan Crawford         }
149715f2bd95SEwan Crawford 
149815f2bd95SEwan Crawford         // Perform expression evaluation
149915f2bd95SEwan Crawford         if (!EvalRSExpression(buffer[i], frame_ptr, &results[i]))
150015f2bd95SEwan Crawford             return false;
150115f2bd95SEwan Crawford     }
150215f2bd95SEwan Crawford 
150315f2bd95SEwan Crawford     // Assign results to allocation members
15048b244e21SEwan Crawford     elem.type = static_cast<RenderScriptRuntime::Element::DataType>(results[0]);
15058b244e21SEwan Crawford     elem.type_kind = static_cast<RenderScriptRuntime::Element::DataKind>(results[1]);
15068b244e21SEwan Crawford     elem.type_vec_size = static_cast<uint32_t>(results[2]);
15078b244e21SEwan Crawford     elem.field_count = static_cast<uint32_t>(results[3]);
150815f2bd95SEwan Crawford 
150915f2bd95SEwan Crawford     if (log)
15108b244e21SEwan Crawford         log->Printf("RenderScriptRuntime::JITElementPacked - data type %u, pixel type %u, vector size %u, field count %u",
15118b244e21SEwan Crawford                     *elem.type.get(), *elem.type_kind.get(), *elem.type_vec_size.get(), *elem.field_count.get());
15128b244e21SEwan Crawford 
15138b244e21SEwan Crawford     // If this Element has subelements then JIT rsaElementGetSubElements() for details about its fields
15148b244e21SEwan Crawford     if (*elem.field_count.get() > 0 && !JITSubelements(elem, context, frame_ptr))
15158b244e21SEwan Crawford         return false;
15168b244e21SEwan Crawford 
15178b244e21SEwan Crawford     return true;
15188b244e21SEwan Crawford }
15198b244e21SEwan Crawford 
15208b244e21SEwan Crawford // JITs the RS runtime for information about the subelements/fields of a struct allocation
15218b244e21SEwan Crawford // This is necessary for infering the struct type so we can pretty print the allocation's contents.
15228b244e21SEwan Crawford // Returns true on success, false otherwise
15238b244e21SEwan Crawford bool
15248b244e21SEwan Crawford RenderScriptRuntime::JITSubelements(Element& elem, const lldb::addr_t context, StackFrame* frame_ptr)
15258b244e21SEwan Crawford {
15268b244e21SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
15278b244e21SEwan Crawford 
15288b244e21SEwan Crawford     if (!elem.element_ptr.isValid() || !elem.field_count.isValid())
15298b244e21SEwan Crawford     {
15308b244e21SEwan Crawford         if (log)
15318b244e21SEwan Crawford             log->Printf("RenderScriptRuntime::JITSubelements - Failed to find allocation details");
15328b244e21SEwan Crawford         return false;
15338b244e21SEwan Crawford     }
15348b244e21SEwan Crawford 
15358b244e21SEwan Crawford     const short num_exprs = 3;
15368b244e21SEwan Crawford     assert(num_exprs == (eExprSubelementsArrSize - eExprSubelementsId + 1) && "Invalid number of expressions");
15378b244e21SEwan Crawford 
1538b1651b8dSEwan Crawford     char expr_buffer[jit_max_expr_size];
15398b244e21SEwan Crawford     uint64_t results;
15408b244e21SEwan Crawford 
15418b244e21SEwan Crawford     // Iterate over struct fields.
15428b244e21SEwan Crawford     const uint32_t field_count = *elem.field_count.get();
15438b244e21SEwan Crawford     for (unsigned int field_index = 0; field_index < field_count; ++field_index)
15448b244e21SEwan Crawford     {
15458b244e21SEwan Crawford         Element child;
15468b244e21SEwan Crawford         for (unsigned int expr_index = 0; expr_index < num_exprs; ++expr_index)
15478b244e21SEwan Crawford         {
1548b1651b8dSEwan Crawford             const char* expr_cstr = JITTemplate((ExpressionStrings) (eExprSubelementsId + expr_index));
1549b1651b8dSEwan Crawford             int chars_written = snprintf(expr_buffer, jit_max_expr_size, expr_cstr,
15508b244e21SEwan Crawford                                          field_count, field_count, field_count,
15518b244e21SEwan Crawford                                          context, *elem.element_ptr.get(), field_count, field_index);
15528b244e21SEwan Crawford             if (chars_written < 0)
15538b244e21SEwan Crawford             {
15548b244e21SEwan Crawford                 if (log)
15558b244e21SEwan Crawford                     log->Printf("RenderScriptRuntime::JITSubelements - Encoding error in snprintf()");
15568b244e21SEwan Crawford                 return false;
15578b244e21SEwan Crawford             }
1558b1651b8dSEwan Crawford             else if (chars_written >= jit_max_expr_size)
15598b244e21SEwan Crawford             {
15608b244e21SEwan Crawford                 if (log)
15618b244e21SEwan Crawford                     log->Printf("RenderScriptRuntime::JITSubelements - Expression too long");
15628b244e21SEwan Crawford                 return false;
15638b244e21SEwan Crawford             }
15648b244e21SEwan Crawford 
15658b244e21SEwan Crawford             // Perform expression evaluation
15668b244e21SEwan Crawford             if (!EvalRSExpression(expr_buffer, frame_ptr, &results))
15678b244e21SEwan Crawford                 return false;
15688b244e21SEwan Crawford 
15698b244e21SEwan Crawford             if (log)
15708b244e21SEwan Crawford                 log->Printf("RenderScriptRuntime::JITSubelements - Expr result 0x%" PRIx64, results);
15718b244e21SEwan Crawford 
15728b244e21SEwan Crawford             switch(expr_index)
15738b244e21SEwan Crawford             {
15748b244e21SEwan Crawford                 case 0: // Element* of child
15758b244e21SEwan Crawford                     child.element_ptr = static_cast<addr_t>(results);
15768b244e21SEwan Crawford                     break;
15778b244e21SEwan Crawford                 case 1: // Name of child
15788b244e21SEwan Crawford                 {
15798b244e21SEwan Crawford                     lldb::addr_t address = static_cast<addr_t>(results);
15808b244e21SEwan Crawford                     Error err;
15818b244e21SEwan Crawford                     std::string name;
15828b244e21SEwan Crawford                     GetProcess()->ReadCStringFromMemory(address, name, err);
15838b244e21SEwan Crawford                     if (!err.Fail())
15848b244e21SEwan Crawford                         child.type_name = ConstString(name);
15858b244e21SEwan Crawford                     else
15868b244e21SEwan Crawford                     {
15878b244e21SEwan Crawford                         if (log)
15888b244e21SEwan Crawford                             log->Printf("RenderScriptRuntime::JITSubelements - Warning: Couldn't read field name");
15898b244e21SEwan Crawford                     }
15908b244e21SEwan Crawford                     break;
15918b244e21SEwan Crawford                 }
15928b244e21SEwan Crawford                 case 2: // Array size of child
15938b244e21SEwan Crawford                     child.array_size = static_cast<uint32_t>(results);
15948b244e21SEwan Crawford                     break;
15958b244e21SEwan Crawford             }
15968b244e21SEwan Crawford         }
15978b244e21SEwan Crawford 
15988b244e21SEwan Crawford         // We need to recursively JIT each Element field of the struct since
15998b244e21SEwan Crawford         // structs can be nested inside structs.
16008b244e21SEwan Crawford         if (!JITElementPacked(child, context, frame_ptr))
16018b244e21SEwan Crawford             return false;
16028b244e21SEwan Crawford         elem.children.push_back(child);
16038b244e21SEwan Crawford     }
16048b244e21SEwan Crawford 
16058b244e21SEwan Crawford     // Try to infer the name of the struct type so we can pretty print the allocation contents.
16068b244e21SEwan Crawford     FindStructTypeName(elem, frame_ptr);
160715f2bd95SEwan Crawford 
160815f2bd95SEwan Crawford     return true;
160915f2bd95SEwan Crawford }
161015f2bd95SEwan Crawford 
1611a0f08674SEwan Crawford // JITs the RS runtime for the address of the last element in the allocation.
1612a0f08674SEwan Crawford // The `elem_size` paramter represents the size of a single element, including padding.
1613a0f08674SEwan Crawford // Which is needed as an offset from the last element pointer.
1614a0f08674SEwan Crawford // Using this offset minus the starting address we can calculate the size of the allocation.
1615a0f08674SEwan Crawford // Returns true on success, false otherwise
1616a0f08674SEwan Crawford bool
16178b244e21SEwan Crawford RenderScriptRuntime::JITAllocationSize(AllocationDetails* allocation, StackFrame* frame_ptr)
1618a0f08674SEwan Crawford {
1619a0f08674SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1620a0f08674SEwan Crawford 
1621a0f08674SEwan Crawford     if (!allocation->address.isValid() || !allocation->dimension.isValid()
16228b244e21SEwan Crawford         || !allocation->data_ptr.isValid() || !allocation->element.datum_size.isValid())
1623a0f08674SEwan Crawford     {
1624a0f08674SEwan Crawford         if (log)
1625a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationSize - Failed to find allocation details");
1626a0f08674SEwan Crawford         return false;
1627a0f08674SEwan Crawford     }
1628a0f08674SEwan Crawford 
1629a0f08674SEwan Crawford     // Find dimensions
1630a0f08674SEwan Crawford     unsigned int dim_x = allocation->dimension.get()->dim_1;
1631a0f08674SEwan Crawford     unsigned int dim_y = allocation->dimension.get()->dim_2;
1632a0f08674SEwan Crawford     unsigned int dim_z = allocation->dimension.get()->dim_3;
1633a0f08674SEwan Crawford 
16348b244e21SEwan Crawford     // Our plan of jitting the last element address doesn't seem to work for struct Allocations
16358b244e21SEwan Crawford     // Instead try to infer the size ourselves without any inter element padding.
16368b244e21SEwan Crawford     if (allocation->element.children.size() > 0)
16378b244e21SEwan Crawford     {
16388b244e21SEwan Crawford         if (dim_x == 0) dim_x = 1;
16398b244e21SEwan Crawford         if (dim_y == 0) dim_y = 1;
16408b244e21SEwan Crawford         if (dim_z == 0) dim_z = 1;
16418b244e21SEwan Crawford 
16428b244e21SEwan Crawford         allocation->size = dim_x * dim_y * dim_z * *allocation->element.datum_size.get();
16438b244e21SEwan Crawford 
16448b244e21SEwan Crawford         if (log)
16458b244e21SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationSize - Infered size of struct allocation %u", *allocation->size.get());
16468b244e21SEwan Crawford 
16478b244e21SEwan Crawford         return true;
16488b244e21SEwan Crawford     }
16498b244e21SEwan Crawford 
1650b1651b8dSEwan Crawford     const char* expr_cstr = JITTemplate(eExprGetOffsetPtr);
1651b1651b8dSEwan Crawford     char buffer[jit_max_expr_size];
16528b244e21SEwan Crawford 
1653a0f08674SEwan Crawford     // Calculate last element
1654a0f08674SEwan Crawford     dim_x = dim_x == 0 ? 0 : dim_x - 1;
1655a0f08674SEwan Crawford     dim_y = dim_y == 0 ? 0 : dim_y - 1;
1656a0f08674SEwan Crawford     dim_z = dim_z == 0 ? 0 : dim_z - 1;
1657a0f08674SEwan Crawford 
1658b1651b8dSEwan Crawford     int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->address.get(),
1659a0f08674SEwan Crawford                                  dim_x, dim_y, dim_z);
1660a0f08674SEwan Crawford     if (chars_written < 0)
1661a0f08674SEwan Crawford     {
1662a0f08674SEwan Crawford         if (log)
1663a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationSize - Encoding error in snprintf()");
1664a0f08674SEwan Crawford         return false;
1665a0f08674SEwan Crawford     }
1666b1651b8dSEwan Crawford     else if (chars_written >= jit_max_expr_size)
1667a0f08674SEwan Crawford     {
1668a0f08674SEwan Crawford         if (log)
1669a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationSize - Expression too long");
1670a0f08674SEwan Crawford         return false;
1671a0f08674SEwan Crawford     }
1672a0f08674SEwan Crawford 
1673a0f08674SEwan Crawford     uint64_t result = 0;
1674a0f08674SEwan Crawford     if (!EvalRSExpression(buffer, frame_ptr, &result))
1675a0f08674SEwan Crawford         return false;
1676a0f08674SEwan Crawford 
1677a0f08674SEwan Crawford     addr_t mem_ptr = static_cast<lldb::addr_t>(result);
1678a0f08674SEwan Crawford     // Find pointer to last element and add on size of an element
16798b244e21SEwan Crawford     allocation->size = static_cast<uint32_t>(mem_ptr - *allocation->data_ptr.get()) + *allocation->element.datum_size.get();
1680a0f08674SEwan Crawford 
1681a0f08674SEwan Crawford     return true;
1682a0f08674SEwan Crawford }
1683a0f08674SEwan Crawford 
1684a0f08674SEwan Crawford // JITs the RS runtime for information about the stride between rows in the allocation.
1685a0f08674SEwan Crawford // This is done to detect padding, since allocated memory is 16-byte aligned.
1686a0f08674SEwan Crawford // Returns true on success, false otherwise
1687a0f08674SEwan Crawford bool
1688a0f08674SEwan Crawford RenderScriptRuntime::JITAllocationStride(AllocationDetails* allocation, StackFrame* frame_ptr)
1689a0f08674SEwan Crawford {
1690a0f08674SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
1691a0f08674SEwan Crawford 
1692a0f08674SEwan Crawford     if (!allocation->address.isValid() || !allocation->data_ptr.isValid())
1693a0f08674SEwan Crawford     {
1694a0f08674SEwan Crawford         if (log)
1695a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationStride - Failed to find allocation details");
1696a0f08674SEwan Crawford         return false;
1697a0f08674SEwan Crawford     }
1698a0f08674SEwan Crawford 
1699b1651b8dSEwan Crawford     const char* expr_cstr = JITTemplate(eExprGetOffsetPtr);
1700b1651b8dSEwan Crawford     char buffer[jit_max_expr_size];
1701a0f08674SEwan Crawford 
1702b1651b8dSEwan Crawford     int chars_written = snprintf(buffer, jit_max_expr_size, expr_cstr, *allocation->address.get(),
1703a0f08674SEwan Crawford                                  0, 1, 0);
1704a0f08674SEwan Crawford     if (chars_written < 0)
1705a0f08674SEwan Crawford     {
1706a0f08674SEwan Crawford         if (log)
1707a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationStride - Encoding error in snprintf()");
1708a0f08674SEwan Crawford         return false;
1709a0f08674SEwan Crawford     }
1710b1651b8dSEwan Crawford     else if (chars_written >= jit_max_expr_size)
1711a0f08674SEwan Crawford     {
1712a0f08674SEwan Crawford         if (log)
1713a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::JITAllocationStride - Expression too long");
1714a0f08674SEwan Crawford         return false;
1715a0f08674SEwan Crawford     }
1716a0f08674SEwan Crawford 
1717a0f08674SEwan Crawford     uint64_t result = 0;
1718a0f08674SEwan Crawford     if (!EvalRSExpression(buffer, frame_ptr, &result))
1719a0f08674SEwan Crawford         return false;
1720a0f08674SEwan Crawford 
1721a0f08674SEwan Crawford     addr_t mem_ptr = static_cast<lldb::addr_t>(result);
1722a0f08674SEwan Crawford     allocation->stride = static_cast<uint32_t>(mem_ptr - *allocation->data_ptr.get());
1723a0f08674SEwan Crawford 
1724a0f08674SEwan Crawford     return true;
1725a0f08674SEwan Crawford }
1726a0f08674SEwan Crawford 
172715f2bd95SEwan Crawford // JIT all the current runtime info regarding an allocation
172815f2bd95SEwan Crawford bool
172915f2bd95SEwan Crawford RenderScriptRuntime::RefreshAllocation(AllocationDetails* allocation, StackFrame* frame_ptr)
173015f2bd95SEwan Crawford {
173115f2bd95SEwan Crawford     // GetOffsetPointer()
173215f2bd95SEwan Crawford     if (!JITDataPointer(allocation, frame_ptr))
173315f2bd95SEwan Crawford         return false;
173415f2bd95SEwan Crawford 
173515f2bd95SEwan Crawford     // rsaAllocationGetType()
173615f2bd95SEwan Crawford     if (!JITTypePointer(allocation, frame_ptr))
173715f2bd95SEwan Crawford         return false;
173815f2bd95SEwan Crawford 
173915f2bd95SEwan Crawford     // rsaTypeGetNativeData()
174015f2bd95SEwan Crawford     if (!JITTypePacked(allocation, frame_ptr))
174115f2bd95SEwan Crawford         return false;
174215f2bd95SEwan Crawford 
174315f2bd95SEwan Crawford     // rsaElementGetNativeData()
17448b244e21SEwan Crawford     if (!JITElementPacked(allocation->element, *allocation->context.get(), frame_ptr))
174515f2bd95SEwan Crawford         return false;
174615f2bd95SEwan Crawford 
17478b244e21SEwan Crawford     // Sets the datum_size member in Element
17488b244e21SEwan Crawford     SetElementSize(allocation->element);
17498b244e21SEwan Crawford 
175055232f09SEwan Crawford     // Use GetOffsetPointer() to infer size of the allocation
17518b244e21SEwan Crawford     if (!JITAllocationSize(allocation, frame_ptr))
175255232f09SEwan Crawford         return false;
175355232f09SEwan Crawford 
175455232f09SEwan Crawford     return true;
175555232f09SEwan Crawford }
175655232f09SEwan Crawford 
17578b244e21SEwan Crawford // Function attempts to set the type_name member of the paramaterised Element object.
17588b244e21SEwan Crawford // This string should be the name of the struct type the Element represents.
17598b244e21SEwan Crawford // We need this string for pretty printing the Element to users.
17608b244e21SEwan Crawford void
17618b244e21SEwan Crawford RenderScriptRuntime::FindStructTypeName(Element& elem, StackFrame* frame_ptr)
176255232f09SEwan Crawford {
17638b244e21SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
17648b244e21SEwan Crawford 
17658b244e21SEwan Crawford     if (!elem.type_name.IsEmpty()) // Name already set
17668b244e21SEwan Crawford         return;
17678b244e21SEwan Crawford     else
1768fe06b5adSAdrian McCarthy         elem.type_name = Element::GetFallbackStructName(); // Default type name if we don't succeed
17698b244e21SEwan Crawford 
17708b244e21SEwan Crawford     // Find all the global variables from the script rs modules
17718b244e21SEwan Crawford     VariableList variable_list;
17728b244e21SEwan Crawford     for (auto module_sp : m_rsmodules)
17738b244e21SEwan Crawford         module_sp->m_module->FindGlobalVariables(RegularExpression("."), true, UINT32_MAX, variable_list);
17748b244e21SEwan Crawford 
17758b244e21SEwan Crawford     // Iterate over all the global variables looking for one with a matching type to the Element.
17768b244e21SEwan Crawford     // We make the assumption a match exists since there needs to be a global variable to reflect the
17778b244e21SEwan Crawford     // struct type back into java host code.
17788b244e21SEwan Crawford     for (uint32_t var_index = 0; var_index < variable_list.GetSize(); ++var_index)
17798b244e21SEwan Crawford     {
17808b244e21SEwan Crawford         const VariableSP var_sp(variable_list.GetVariableAtIndex(var_index));
17818b244e21SEwan Crawford         if (!var_sp)
17828b244e21SEwan Crawford            continue;
17838b244e21SEwan Crawford 
17848b244e21SEwan Crawford         ValueObjectSP valobj_sp = ValueObjectVariable::Create(frame_ptr, var_sp);
17858b244e21SEwan Crawford         if (!valobj_sp)
17868b244e21SEwan Crawford             continue;
17878b244e21SEwan Crawford 
17888b244e21SEwan Crawford         // Find the number of variable fields.
17898b244e21SEwan Crawford         // If it has no fields, or more fields than our Element, then it can't be the struct we're looking for.
17908b244e21SEwan Crawford         // Don't check for equality since RS can add extra struct members for padding.
17918b244e21SEwan Crawford         size_t num_children = valobj_sp->GetNumChildren();
17928b244e21SEwan Crawford         if (num_children > elem.children.size() || num_children == 0)
17938b244e21SEwan Crawford             continue;
17948b244e21SEwan Crawford 
17958b244e21SEwan Crawford         // Iterate over children looking for members with matching field names.
17968b244e21SEwan Crawford         // If all the field names match, this is likely the struct we want.
17978b244e21SEwan Crawford         //
17988b244e21SEwan Crawford         //   TODO: This could be made more robust by also checking children data sizes, or array size
17998b244e21SEwan Crawford         bool found = true;
18008b244e21SEwan Crawford         for (size_t child_index = 0; child_index < num_children; ++child_index)
18018b244e21SEwan Crawford         {
18028b244e21SEwan Crawford             ValueObjectSP child = valobj_sp->GetChildAtIndex(child_index, true);
18038b244e21SEwan Crawford             if (!child || (child->GetName() != elem.children[child_index].type_name))
18048b244e21SEwan Crawford             {
18058b244e21SEwan Crawford                 found = false;
18068b244e21SEwan Crawford                 break;
18078b244e21SEwan Crawford             }
18088b244e21SEwan Crawford         }
18098b244e21SEwan Crawford 
18108b244e21SEwan Crawford         // RS can add extra struct members for padding in the format '#rs_padding_[0-9]+'
18118b244e21SEwan Crawford         if (found && num_children < elem.children.size())
18128b244e21SEwan Crawford         {
18138b244e21SEwan Crawford             const unsigned int size_diff = elem.children.size() - num_children;
18148b244e21SEwan Crawford             if (log)
18158b244e21SEwan Crawford                 log->Printf("RenderScriptRuntime::FindStructTypeName - %u padding struct entries", size_diff);
18168b244e21SEwan Crawford 
18178b244e21SEwan Crawford             for (unsigned int padding_index = 0; padding_index < size_diff; ++padding_index)
18188b244e21SEwan Crawford             {
18198b244e21SEwan Crawford                 const ConstString& name = elem.children[num_children + padding_index].type_name;
18208b244e21SEwan Crawford                 if (strcmp(name.AsCString(), "#rs_padding") < 0)
18218b244e21SEwan Crawford                     found = false;
18228b244e21SEwan Crawford             }
18238b244e21SEwan Crawford         }
18248b244e21SEwan Crawford 
18258b244e21SEwan Crawford         // We've found a global var with matching type
18268b244e21SEwan Crawford         if (found)
18278b244e21SEwan Crawford         {
18288b244e21SEwan Crawford             // Dereference since our Element type isn't a pointer.
18298b244e21SEwan Crawford             if (valobj_sp->IsPointerType())
18308b244e21SEwan Crawford             {
18318b244e21SEwan Crawford                 Error err;
18328b244e21SEwan Crawford                 ValueObjectSP deref_valobj = valobj_sp->Dereference(err);
18338b244e21SEwan Crawford                 if (!err.Fail())
18348b244e21SEwan Crawford                     valobj_sp = deref_valobj;
18358b244e21SEwan Crawford             }
18368b244e21SEwan Crawford 
18378b244e21SEwan Crawford             // Save name of variable in Element.
18388b244e21SEwan Crawford             elem.type_name = valobj_sp->GetTypeName();
18398b244e21SEwan Crawford             if (log)
18408b244e21SEwan Crawford                 log->Printf("RenderScriptRuntime::FindStructTypeName - Element name set to %s", elem.type_name.AsCString());
18418b244e21SEwan Crawford 
18428b244e21SEwan Crawford             return;
18438b244e21SEwan Crawford         }
18448b244e21SEwan Crawford     }
18458b244e21SEwan Crawford }
18468b244e21SEwan Crawford 
18478b244e21SEwan Crawford // Function sets the datum_size member of Element. Representing the size of a single instance including padding.
18488b244e21SEwan Crawford // Assumes the relevant allocation information has already been jitted.
18498b244e21SEwan Crawford void
18508b244e21SEwan Crawford RenderScriptRuntime::SetElementSize(Element& elem)
18518b244e21SEwan Crawford {
18528b244e21SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
18538b244e21SEwan Crawford     const Element::DataType type = *elem.type.get();
18548b244e21SEwan Crawford     assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_BOOLEAN
185555232f09SEwan Crawford                                                    && "Invalid allocation type");
185655232f09SEwan Crawford 
18578b244e21SEwan Crawford     const unsigned int vec_size = *elem.type_vec_size.get();
18588b244e21SEwan Crawford     unsigned int data_size = 0;
185955232f09SEwan Crawford     const unsigned int padding = vec_size == 3 ? AllocationDetails::RSTypeToFormat[type][eElementSize] : 0;
186055232f09SEwan Crawford 
18618b244e21SEwan Crawford     // Element is of a struct type, calculate size recursively.
18628b244e21SEwan Crawford     if ((type == Element::RS_TYPE_NONE) && (elem.children.size() > 0))
18638b244e21SEwan Crawford     {
18648b244e21SEwan Crawford         for (Element& child : elem.children)
18658b244e21SEwan Crawford         {
18668b244e21SEwan Crawford             SetElementSize(child);
18678b244e21SEwan Crawford             const unsigned int array_size = child.array_size.isValid() ? *child.array_size.get() : 1;
18688b244e21SEwan Crawford             data_size += *child.datum_size.get() * array_size;
18698b244e21SEwan Crawford         }
18708b244e21SEwan Crawford     }
18718b244e21SEwan Crawford     else
18728b244e21SEwan Crawford         data_size = vec_size * AllocationDetails::RSTypeToFormat[type][eElementSize];
18738b244e21SEwan Crawford 
18748b244e21SEwan Crawford     elem.padding = padding;
18758b244e21SEwan Crawford     elem.datum_size = data_size + padding;
18768b244e21SEwan Crawford     if (log)
18778b244e21SEwan Crawford         log->Printf("RenderScriptRuntime::SetElementSize - element size set to %u", data_size + padding);
187855232f09SEwan Crawford }
187955232f09SEwan Crawford 
188055232f09SEwan Crawford // Given an allocation, this function copies the allocation contents from device into a buffer on the heap.
188155232f09SEwan Crawford // Returning a shared pointer to the buffer containing the data.
188255232f09SEwan Crawford std::shared_ptr<uint8_t>
188355232f09SEwan Crawford RenderScriptRuntime::GetAllocationData(AllocationDetails* allocation, StackFrame* frame_ptr)
188455232f09SEwan Crawford {
188555232f09SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
188655232f09SEwan Crawford 
188755232f09SEwan Crawford     // JIT all the allocation details
1888*8b59062aSEwan Crawford     if (allocation->shouldRefresh())
188955232f09SEwan Crawford     {
189055232f09SEwan Crawford         if (log)
189155232f09SEwan Crawford             log->Printf("RenderScriptRuntime::GetAllocationData - Allocation details not calculated yet, jitting info");
189255232f09SEwan Crawford 
189355232f09SEwan Crawford         if (!RefreshAllocation(allocation, frame_ptr))
189455232f09SEwan Crawford         {
189555232f09SEwan Crawford             if (log)
189655232f09SEwan Crawford                 log->Printf("RenderScriptRuntime::GetAllocationData - Couldn't JIT allocation details");
189755232f09SEwan Crawford             return nullptr;
189855232f09SEwan Crawford         }
189955232f09SEwan Crawford     }
190055232f09SEwan Crawford 
19018b244e21SEwan Crawford     assert(allocation->data_ptr.isValid() && allocation->element.type.isValid() && allocation->element.type_vec_size.isValid()
190255232f09SEwan Crawford            && allocation->size.isValid() && "Allocation information not available");
190355232f09SEwan Crawford 
190455232f09SEwan Crawford     // Allocate a buffer to copy data into
190555232f09SEwan Crawford     const unsigned int size = *allocation->size.get();
190655232f09SEwan Crawford     std::shared_ptr<uint8_t> buffer(new uint8_t[size]);
190755232f09SEwan Crawford     if (!buffer)
190855232f09SEwan Crawford     {
190955232f09SEwan Crawford         if (log)
191055232f09SEwan Crawford             log->Printf("RenderScriptRuntime::GetAllocationData - Couldn't allocate a %u byte buffer", size);
191155232f09SEwan Crawford         return nullptr;
191255232f09SEwan Crawford     }
191355232f09SEwan Crawford 
191455232f09SEwan Crawford     // Read the inferior memory
191555232f09SEwan Crawford     Error error;
191655232f09SEwan Crawford     lldb::addr_t data_ptr = *allocation->data_ptr.get();
191755232f09SEwan Crawford     GetProcess()->ReadMemory(data_ptr, buffer.get(), size, error);
191855232f09SEwan Crawford     if (error.Fail())
191955232f09SEwan Crawford     {
192055232f09SEwan Crawford         if (log)
192155232f09SEwan Crawford             log->Printf("RenderScriptRuntime::GetAllocationData - '%s' Couldn't read %u bytes of allocation data from 0x%" PRIx64,
192255232f09SEwan Crawford                         error.AsCString(), size, data_ptr);
192355232f09SEwan Crawford         return nullptr;
192455232f09SEwan Crawford     }
192555232f09SEwan Crawford 
192655232f09SEwan Crawford     return buffer;
192755232f09SEwan Crawford }
192855232f09SEwan Crawford 
192955232f09SEwan Crawford // Function copies data from a binary file into an allocation.
193055232f09SEwan Crawford // There is a header at the start of the file, FileHeader, before the data content itself.
193155232f09SEwan Crawford // Information from this header is used to display warnings to the user about incompatabilities
193255232f09SEwan Crawford bool
193355232f09SEwan Crawford RenderScriptRuntime::LoadAllocation(Stream &strm, const uint32_t alloc_id, const char* filename, StackFrame* frame_ptr)
193455232f09SEwan Crawford {
193555232f09SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
193655232f09SEwan Crawford 
193755232f09SEwan Crawford     // Find allocation with the given id
193855232f09SEwan Crawford     AllocationDetails* alloc = FindAllocByID(strm, alloc_id);
193955232f09SEwan Crawford     if (!alloc)
194055232f09SEwan Crawford         return false;
194155232f09SEwan Crawford 
194255232f09SEwan Crawford     if (log)
194355232f09SEwan Crawford         log->Printf("RenderScriptRuntime::LoadAllocation - Found allocation 0x%" PRIx64, *alloc->address.get());
194455232f09SEwan Crawford 
194555232f09SEwan Crawford     // JIT all the allocation details
1946*8b59062aSEwan Crawford     if (alloc->shouldRefresh())
194755232f09SEwan Crawford     {
194855232f09SEwan Crawford         if (log)
194955232f09SEwan Crawford             log->Printf("RenderScriptRuntime::LoadAllocation - Allocation details not calculated yet, jitting info");
195055232f09SEwan Crawford 
195155232f09SEwan Crawford         if (!RefreshAllocation(alloc, frame_ptr))
195255232f09SEwan Crawford         {
195355232f09SEwan Crawford             if (log)
195455232f09SEwan Crawford                 log->Printf("RenderScriptRuntime::LoadAllocation - Couldn't JIT allocation details");
19554cfc9198SSylvestre Ledru             return false;
195655232f09SEwan Crawford         }
195755232f09SEwan Crawford     }
195855232f09SEwan Crawford 
19598b244e21SEwan Crawford     assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() && alloc->element.type_vec_size.isValid()
19608b244e21SEwan Crawford            && alloc->size.isValid() && alloc->element.datum_size.isValid() && "Allocation information not available");
196155232f09SEwan Crawford 
196255232f09SEwan Crawford     // Check we can read from file
196355232f09SEwan Crawford     FileSpec file(filename, true);
196455232f09SEwan Crawford     if (!file.Exists())
196555232f09SEwan Crawford     {
196655232f09SEwan Crawford         strm.Printf("Error: File %s does not exist", filename);
196755232f09SEwan Crawford         strm.EOL();
196855232f09SEwan Crawford         return false;
196955232f09SEwan Crawford     }
197055232f09SEwan Crawford 
197155232f09SEwan Crawford     if (!file.Readable())
197255232f09SEwan Crawford     {
197355232f09SEwan Crawford         strm.Printf("Error: File %s does not have readable permissions", filename);
197455232f09SEwan Crawford         strm.EOL();
197555232f09SEwan Crawford         return false;
197655232f09SEwan Crawford     }
197755232f09SEwan Crawford 
197855232f09SEwan Crawford     // Read file into data buffer
197955232f09SEwan Crawford     DataBufferSP data_sp(file.ReadFileContents());
198055232f09SEwan Crawford 
198155232f09SEwan Crawford     // Cast start of buffer to FileHeader and use pointer to read metadata
198255232f09SEwan Crawford     void* file_buffer = data_sp->GetBytes();
198355232f09SEwan Crawford     const AllocationDetails::FileHeader* head = static_cast<AllocationDetails::FileHeader*>(file_buffer);
198455232f09SEwan Crawford 
198555232f09SEwan Crawford     // Advance buffer past header
198655232f09SEwan Crawford     file_buffer = static_cast<uint8_t*>(file_buffer) + head->hdr_size;
198755232f09SEwan Crawford 
198855232f09SEwan Crawford     if (log)
198955232f09SEwan Crawford         log->Printf("RenderScriptRuntime::LoadAllocation - header type %u, element size %u",
199055232f09SEwan Crawford                     head->type, head->element_size);
199155232f09SEwan Crawford 
199255232f09SEwan Crawford     // Check if the target allocation and file both have the same number of bytes for an Element
19938b244e21SEwan Crawford     if (*alloc->element.datum_size.get() != head->element_size)
199455232f09SEwan Crawford     {
199555232f09SEwan Crawford         strm.Printf("Warning: Mismatched Element sizes - file %u bytes, allocation %u bytes",
19968b244e21SEwan Crawford                     head->element_size, *alloc->element.datum_size.get());
199755232f09SEwan Crawford         strm.EOL();
199855232f09SEwan Crawford     }
199955232f09SEwan Crawford 
200055232f09SEwan Crawford     // Check if the target allocation and file both have the same integral type
20018b244e21SEwan Crawford     const unsigned int type = static_cast<unsigned int>(*alloc->element.type.get());
200255232f09SEwan Crawford     if (type != head->type)
200355232f09SEwan Crawford     {
200455232f09SEwan Crawford         const char* file_type_cstr = AllocationDetails::RsDataTypeToString[head->type][0];
200555232f09SEwan Crawford         const char* alloc_type_cstr = AllocationDetails::RsDataTypeToString[type][0];
200655232f09SEwan Crawford 
200755232f09SEwan Crawford         strm.Printf("Warning: Mismatched Types - file '%s' type, allocation '%s' type",
200855232f09SEwan Crawford                     file_type_cstr, alloc_type_cstr);
200955232f09SEwan Crawford         strm.EOL();
201055232f09SEwan Crawford     }
201155232f09SEwan Crawford 
201255232f09SEwan Crawford     // Calculate size of allocation data in file
201355232f09SEwan Crawford     size_t length = data_sp->GetByteSize() - head->hdr_size;
201455232f09SEwan Crawford 
201555232f09SEwan Crawford     // Check if the target allocation and file both have the same total data size.
201655232f09SEwan Crawford     const unsigned int alloc_size = *alloc->size.get();
201755232f09SEwan Crawford     if (alloc_size != length)
201855232f09SEwan Crawford     {
201955232f09SEwan Crawford         strm.Printf("Warning: Mismatched allocation sizes - file 0x%" PRIx64 " bytes, allocation 0x%x bytes",
2020eba832beSJason Molenda                     (uint64_t) length, alloc_size);
202155232f09SEwan Crawford         strm.EOL();
202255232f09SEwan Crawford         length = alloc_size < length ? alloc_size : length; // Set length to copy to minimum
202355232f09SEwan Crawford     }
202455232f09SEwan Crawford 
202555232f09SEwan Crawford     // Copy file data from our buffer into the target allocation.
202655232f09SEwan Crawford     lldb::addr_t alloc_data = *alloc->data_ptr.get();
202755232f09SEwan Crawford     Error error;
202855232f09SEwan Crawford     size_t bytes_written = GetProcess()->WriteMemory(alloc_data, file_buffer, length, error);
202955232f09SEwan Crawford     if (!error.Success() || bytes_written != length)
203055232f09SEwan Crawford     {
203155232f09SEwan Crawford         strm.Printf("Error: Couldn't write data to allocation %s", error.AsCString());
203255232f09SEwan Crawford         strm.EOL();
203355232f09SEwan Crawford         return false;
203455232f09SEwan Crawford     }
203555232f09SEwan Crawford 
203655232f09SEwan Crawford     strm.Printf("Contents of file '%s' read into allocation %u", filename, alloc->id);
203755232f09SEwan Crawford     strm.EOL();
203855232f09SEwan Crawford 
203955232f09SEwan Crawford     return true;
204055232f09SEwan Crawford }
204155232f09SEwan Crawford 
204255232f09SEwan Crawford // Function copies allocation contents into a binary file.
204355232f09SEwan Crawford // This file can then be loaded later into a different allocation.
204455232f09SEwan Crawford // There is a header, FileHeader, before the allocation data containing meta-data.
204555232f09SEwan Crawford bool
204655232f09SEwan Crawford RenderScriptRuntime::SaveAllocation(Stream &strm, const uint32_t alloc_id, const char* filename, StackFrame* frame_ptr)
204755232f09SEwan Crawford {
204855232f09SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
204955232f09SEwan Crawford 
205055232f09SEwan Crawford     // Find allocation with the given id
205155232f09SEwan Crawford     AllocationDetails* alloc = FindAllocByID(strm, alloc_id);
205255232f09SEwan Crawford     if (!alloc)
205355232f09SEwan Crawford         return false;
205455232f09SEwan Crawford 
205555232f09SEwan Crawford     if (log)
205655232f09SEwan Crawford         log->Printf("RenderScriptRuntime::SaveAllocation - Found allocation 0x%" PRIx64, *alloc->address.get());
205755232f09SEwan Crawford 
205855232f09SEwan Crawford      // JIT all the allocation details
2059*8b59062aSEwan Crawford     if (alloc->shouldRefresh())
206055232f09SEwan Crawford     {
206155232f09SEwan Crawford         if (log)
206255232f09SEwan Crawford             log->Printf("RenderScriptRuntime::SaveAllocation - Allocation details not calculated yet, jitting info");
206355232f09SEwan Crawford 
206455232f09SEwan Crawford         if (!RefreshAllocation(alloc, frame_ptr))
206555232f09SEwan Crawford         {
206655232f09SEwan Crawford             if (log)
206755232f09SEwan Crawford                 log->Printf("RenderScriptRuntime::SaveAllocation - Couldn't JIT allocation details");
20684cfc9198SSylvestre Ledru             return false;
206955232f09SEwan Crawford         }
207055232f09SEwan Crawford     }
207155232f09SEwan Crawford 
20728b244e21SEwan Crawford     assert(alloc->data_ptr.isValid() && alloc->element.type.isValid() && alloc->element.type_vec_size.isValid() && alloc->element.datum_size.get()
20738b244e21SEwan Crawford            && alloc->element.type_kind.isValid() && alloc->dimension.isValid() && "Allocation information not available");
207455232f09SEwan Crawford 
207555232f09SEwan Crawford     // Check we can create writable file
207655232f09SEwan Crawford     FileSpec file_spec(filename, true);
207755232f09SEwan Crawford     File file(file_spec, File::eOpenOptionWrite | File::eOpenOptionCanCreate | File::eOpenOptionTruncate);
207855232f09SEwan Crawford     if (!file)
207955232f09SEwan Crawford     {
208055232f09SEwan Crawford         strm.Printf("Error: Failed to open '%s' for writing", filename);
208155232f09SEwan Crawford         strm.EOL();
208255232f09SEwan Crawford         return false;
208355232f09SEwan Crawford     }
208455232f09SEwan Crawford 
208555232f09SEwan Crawford     // Read allocation into buffer of heap memory
208655232f09SEwan Crawford     const std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
208755232f09SEwan Crawford     if (!buffer)
208855232f09SEwan Crawford     {
208955232f09SEwan Crawford         strm.Printf("Error: Couldn't read allocation data into buffer");
209055232f09SEwan Crawford         strm.EOL();
209155232f09SEwan Crawford         return false;
209255232f09SEwan Crawford     }
209355232f09SEwan Crawford 
209455232f09SEwan Crawford     // Create the file header
209555232f09SEwan Crawford     AllocationDetails::FileHeader head;
209655232f09SEwan Crawford     head.ident[0] = 'R'; head.ident[1] = 'S'; head.ident[2] = 'A'; head.ident[3] = 'D';
209755232f09SEwan Crawford     head.hdr_size = static_cast<uint16_t>(sizeof(AllocationDetails::FileHeader));
20988b244e21SEwan Crawford     head.type = static_cast<uint16_t>(*alloc->element.type.get());
20998b244e21SEwan Crawford     head.kind = static_cast<uint32_t>(*alloc->element.type_kind.get());
21002d62328aSEwan Crawford     head.dims[0] = static_cast<uint32_t>(alloc->dimension.get()->dim_1);
21012d62328aSEwan Crawford     head.dims[1] = static_cast<uint32_t>(alloc->dimension.get()->dim_2);
21022d62328aSEwan Crawford     head.dims[2] = static_cast<uint32_t>(alloc->dimension.get()->dim_3);
21038b244e21SEwan Crawford     head.element_size = static_cast<uint32_t>(*alloc->element.datum_size.get());
210455232f09SEwan Crawford 
210555232f09SEwan Crawford     // Write the file header
210655232f09SEwan Crawford     size_t num_bytes = sizeof(AllocationDetails::FileHeader);
210755232f09SEwan Crawford     Error err = file.Write(static_cast<const void*>(&head), num_bytes);
210855232f09SEwan Crawford     if (!err.Success())
210955232f09SEwan Crawford     {
211055232f09SEwan Crawford         strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), filename);
211155232f09SEwan Crawford         strm.EOL();
211255232f09SEwan Crawford         return false;
211355232f09SEwan Crawford     }
211455232f09SEwan Crawford 
211555232f09SEwan Crawford     // Write allocation data to file
211655232f09SEwan Crawford     num_bytes = static_cast<size_t>(*alloc->size.get());
211755232f09SEwan Crawford     if (log)
2118eba832beSJason Molenda         log->Printf("RenderScriptRuntime::SaveAllocation - Writing 0x%" PRIx64 " bytes from %p", (uint64_t) num_bytes, buffer.get());
211955232f09SEwan Crawford 
212055232f09SEwan Crawford     err = file.Write(buffer.get(), num_bytes);
212155232f09SEwan Crawford     if (!err.Success())
212255232f09SEwan Crawford     {
212355232f09SEwan Crawford         strm.Printf("Error: '%s' when writing to file '%s'", err.AsCString(), filename);
212455232f09SEwan Crawford         strm.EOL();
212555232f09SEwan Crawford         return false;
212655232f09SEwan Crawford     }
212755232f09SEwan Crawford 
212855232f09SEwan Crawford     strm.Printf("Allocation written to file '%s'", filename);
212955232f09SEwan Crawford     strm.EOL();
213015f2bd95SEwan Crawford     return true;
213115f2bd95SEwan Crawford }
213215f2bd95SEwan Crawford 
21335ec532a9SColin Riley bool
21345ec532a9SColin Riley RenderScriptRuntime::LoadModule(const lldb::ModuleSP &module_sp)
21355ec532a9SColin Riley {
21364640cde1SColin Riley     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
21374640cde1SColin Riley 
21385ec532a9SColin Riley     if (module_sp)
21395ec532a9SColin Riley     {
21405ec532a9SColin Riley         for (const auto &rs_module : m_rsmodules)
21415ec532a9SColin Riley         {
21424640cde1SColin Riley             if (rs_module->m_module == module_sp)
21437dc7771cSEwan Crawford             {
21447dc7771cSEwan Crawford                 // Check if the user has enabled automatically breaking on
21457dc7771cSEwan Crawford                 // all RS kernels.
21467dc7771cSEwan Crawford                 if (m_breakAllKernels)
21477dc7771cSEwan Crawford                     BreakOnModuleKernels(rs_module);
21487dc7771cSEwan Crawford 
21495ec532a9SColin Riley                 return false;
21505ec532a9SColin Riley             }
21517dc7771cSEwan Crawford         }
2152ef20b08fSColin Riley         bool module_loaded = false;
2153ef20b08fSColin Riley         switch (GetModuleKind(module_sp))
2154ef20b08fSColin Riley         {
2155ef20b08fSColin Riley             case eModuleKindKernelObj:
2156ef20b08fSColin Riley             {
21574640cde1SColin Riley                 RSModuleDescriptorSP module_desc;
21584640cde1SColin Riley                 module_desc.reset(new RSModuleDescriptor(module_sp));
21594640cde1SColin Riley                 if (module_desc->ParseRSInfo())
21605ec532a9SColin Riley                 {
21615ec532a9SColin Riley                     m_rsmodules.push_back(module_desc);
2162ef20b08fSColin Riley                     module_loaded = true;
21635ec532a9SColin Riley                 }
21644640cde1SColin Riley                 if (module_loaded)
21654640cde1SColin Riley                 {
21664640cde1SColin Riley                     FixupScriptDetails(module_desc);
21674640cde1SColin Riley                 }
2168ef20b08fSColin Riley                 break;
2169ef20b08fSColin Riley             }
2170ef20b08fSColin Riley             case eModuleKindDriver:
21714640cde1SColin Riley             {
21724640cde1SColin Riley                 if (!m_libRSDriver)
21734640cde1SColin Riley                 {
21744640cde1SColin Riley                     m_libRSDriver = module_sp;
21754640cde1SColin Riley                     LoadRuntimeHooks(m_libRSDriver, RenderScriptRuntime::eModuleKindDriver);
21764640cde1SColin Riley                 }
21774640cde1SColin Riley                 break;
21784640cde1SColin Riley             }
2179ef20b08fSColin Riley             case eModuleKindImpl:
21804640cde1SColin Riley             {
21814640cde1SColin Riley                 m_libRSCpuRef = module_sp;
21824640cde1SColin Riley                 break;
21834640cde1SColin Riley             }
2184ef20b08fSColin Riley             case eModuleKindLibRS:
21854640cde1SColin Riley             {
21864640cde1SColin Riley                 if (!m_libRS)
21874640cde1SColin Riley                 {
21884640cde1SColin Riley                     m_libRS = module_sp;
21894640cde1SColin Riley                     static ConstString gDbgPresentStr("gDebuggerPresent");
21904640cde1SColin Riley                     const Symbol* debug_present = m_libRS->FindFirstSymbolWithNameAndType(gDbgPresentStr, eSymbolTypeData);
21914640cde1SColin Riley                     if (debug_present)
21924640cde1SColin Riley                     {
21934640cde1SColin Riley                         Error error;
21944640cde1SColin Riley                         uint32_t flag = 0x00000001U;
21954640cde1SColin Riley                         Target &target = GetProcess()->GetTarget();
2196358cf1eaSGreg Clayton                         addr_t addr = debug_present->GetLoadAddress(&target);
21974640cde1SColin Riley                         GetProcess()->WriteMemory(addr, &flag, sizeof(flag), error);
21984640cde1SColin Riley                         if(error.Success())
21994640cde1SColin Riley                         {
22004640cde1SColin Riley                             if (log)
22014640cde1SColin Riley                                 log->Printf ("RenderScriptRuntime::LoadModule - Debugger present flag set on debugee");
22024640cde1SColin Riley 
22034640cde1SColin Riley                             m_debuggerPresentFlagged = true;
22044640cde1SColin Riley                         }
22054640cde1SColin Riley                         else if (log)
22064640cde1SColin Riley                         {
22074640cde1SColin Riley                             log->Printf ("RenderScriptRuntime::LoadModule - Error writing debugger present flags '%s' ", error.AsCString());
22084640cde1SColin Riley                         }
22094640cde1SColin Riley                     }
22104640cde1SColin Riley                     else if (log)
22114640cde1SColin Riley                     {
22124640cde1SColin Riley                         log->Printf ("RenderScriptRuntime::LoadModule - Error writing debugger present flags - symbol not found");
22134640cde1SColin Riley                     }
22144640cde1SColin Riley                 }
22154640cde1SColin Riley                 break;
22164640cde1SColin Riley             }
2217ef20b08fSColin Riley             default:
2218ef20b08fSColin Riley                 break;
2219ef20b08fSColin Riley         }
2220ef20b08fSColin Riley         if (module_loaded)
2221ef20b08fSColin Riley             Update();
2222ef20b08fSColin Riley         return module_loaded;
22235ec532a9SColin Riley     }
22245ec532a9SColin Riley     return false;
22255ec532a9SColin Riley }
22265ec532a9SColin Riley 
2227ef20b08fSColin Riley void
2228ef20b08fSColin Riley RenderScriptRuntime::Update()
2229ef20b08fSColin Riley {
2230ef20b08fSColin Riley     if (m_rsmodules.size() > 0)
2231ef20b08fSColin Riley     {
2232ef20b08fSColin Riley         if (!m_initiated)
2233ef20b08fSColin Riley         {
2234ef20b08fSColin Riley             Initiate();
2235ef20b08fSColin Riley         }
2236ef20b08fSColin Riley     }
2237ef20b08fSColin Riley }
2238ef20b08fSColin Riley 
22395ec532a9SColin Riley // The maximum line length of an .rs.info packet
22405ec532a9SColin Riley #define MAXLINE 500
22415ec532a9SColin Riley 
22425ec532a9SColin Riley // The .rs.info symbol in renderscript modules contains a string which needs to be parsed.
22435ec532a9SColin Riley // The string is basic and is parsed on a line by line basis.
22445ec532a9SColin Riley bool
22455ec532a9SColin Riley RSModuleDescriptor::ParseRSInfo()
22465ec532a9SColin Riley {
22475ec532a9SColin Riley     const Symbol *info_sym = m_module->FindFirstSymbolWithNameAndType(ConstString(".rs.info"), eSymbolTypeData);
22485ec532a9SColin Riley     if (info_sym)
22495ec532a9SColin Riley     {
2250358cf1eaSGreg Clayton         const addr_t addr = info_sym->GetAddressRef().GetFileAddress();
22515ec532a9SColin Riley         const addr_t size = info_sym->GetByteSize();
22525ec532a9SColin Riley         const FileSpec fs = m_module->GetFileSpec();
22535ec532a9SColin Riley 
22545ec532a9SColin Riley         DataBufferSP buffer = fs.ReadFileContents(addr, size);
22555ec532a9SColin Riley 
22565ec532a9SColin Riley         if (!buffer)
22575ec532a9SColin Riley             return false;
22585ec532a9SColin Riley 
22595ec532a9SColin Riley         std::string info((const char *)buffer->GetBytes());
22605ec532a9SColin Riley 
22615ec532a9SColin Riley         std::vector<std::string> info_lines;
2262e8433cc1SBruce Mitchener         size_t lpos = info.find('\n');
22635ec532a9SColin Riley         while (lpos != std::string::npos)
22645ec532a9SColin Riley         {
22655ec532a9SColin Riley             info_lines.push_back(info.substr(0, lpos));
22665ec532a9SColin Riley             info = info.substr(lpos + 1);
2267e8433cc1SBruce Mitchener             lpos = info.find('\n');
22685ec532a9SColin Riley         }
22695ec532a9SColin Riley         size_t offset = 0;
22705ec532a9SColin Riley         while (offset < info_lines.size())
22715ec532a9SColin Riley         {
22725ec532a9SColin Riley             std::string line = info_lines[offset];
22735ec532a9SColin Riley             // Parse directives
22745ec532a9SColin Riley             uint32_t numDefns = 0;
22755ec532a9SColin Riley             if (sscanf(line.c_str(), "exportVarCount: %u", &numDefns) == 1)
22765ec532a9SColin Riley             {
22775ec532a9SColin Riley                 while (numDefns--)
22784640cde1SColin Riley                     m_globals.push_back(RSGlobalDescriptor(this, info_lines[++offset].c_str()));
22795ec532a9SColin Riley             }
22805ec532a9SColin Riley             else if (sscanf(line.c_str(), "exportFuncCount: %u", &numDefns) == 1)
22815ec532a9SColin Riley             {
22825ec532a9SColin Riley             }
22835ec532a9SColin Riley             else if (sscanf(line.c_str(), "exportForEachCount: %u", &numDefns) == 1)
22845ec532a9SColin Riley             {
22855ec532a9SColin Riley                 char name[MAXLINE];
22865ec532a9SColin Riley                 while (numDefns--)
22875ec532a9SColin Riley                 {
22885ec532a9SColin Riley                     uint32_t slot = 0;
22895ec532a9SColin Riley                     name[0] = '\0';
22905ec532a9SColin Riley                     if (sscanf(info_lines[++offset].c_str(), "%u - %s", &slot, &name[0]) == 2)
22915ec532a9SColin Riley                     {
22924640cde1SColin Riley                         m_kernels.push_back(RSKernelDescriptor(this, name, slot));
22934640cde1SColin Riley                     }
22944640cde1SColin Riley                 }
22954640cde1SColin Riley             }
22964640cde1SColin Riley             else if (sscanf(line.c_str(), "pragmaCount: %u", &numDefns) == 1)
22974640cde1SColin Riley             {
22984640cde1SColin Riley                 char name[MAXLINE];
22994640cde1SColin Riley                 char value[MAXLINE];
23004640cde1SColin Riley                 while (numDefns--)
23014640cde1SColin Riley                 {
23024640cde1SColin Riley                     name[0] = '\0';
23034640cde1SColin Riley                     value[0] = '\0';
23044640cde1SColin Riley                     if (sscanf(info_lines[++offset].c_str(), "%s - %s", &name[0], &value[0]) != 0
23054640cde1SColin Riley                         && (name[0] != '\0'))
23064640cde1SColin Riley                     {
23074640cde1SColin Riley                         m_pragmas[std::string(name)] = value;
23085ec532a9SColin Riley                     }
23095ec532a9SColin Riley                 }
23105ec532a9SColin Riley             }
23115ec532a9SColin Riley             else if (sscanf(line.c_str(), "objectSlotCount: %u", &numDefns) == 1)
23125ec532a9SColin Riley             {
23135ec532a9SColin Riley             }
23145ec532a9SColin Riley 
23155ec532a9SColin Riley             offset++;
23165ec532a9SColin Riley         }
23175ec532a9SColin Riley         return m_kernels.size() > 0;
23185ec532a9SColin Riley     }
23195ec532a9SColin Riley     return false;
23205ec532a9SColin Riley }
23215ec532a9SColin Riley 
23225ec532a9SColin Riley bool
23235ec532a9SColin Riley RenderScriptRuntime::ProbeModules(const ModuleList module_list)
23245ec532a9SColin Riley {
23255ec532a9SColin Riley     bool rs_found = false;
23265ec532a9SColin Riley     size_t num_modules = module_list.GetSize();
23275ec532a9SColin Riley     for (size_t i = 0; i < num_modules; i++)
23285ec532a9SColin Riley     {
23295ec532a9SColin Riley         auto module = module_list.GetModuleAtIndex(i);
23305ec532a9SColin Riley         rs_found |= LoadModule(module);
23315ec532a9SColin Riley     }
23325ec532a9SColin Riley     return rs_found;
23335ec532a9SColin Riley }
23345ec532a9SColin Riley 
23355ec532a9SColin Riley void
23364640cde1SColin Riley RenderScriptRuntime::Status(Stream &strm) const
23374640cde1SColin Riley {
23384640cde1SColin Riley     if (m_libRS)
23394640cde1SColin Riley     {
23404640cde1SColin Riley         strm.Printf("Runtime Library discovered.");
23414640cde1SColin Riley         strm.EOL();
23424640cde1SColin Riley     }
23434640cde1SColin Riley     if (m_libRSDriver)
23444640cde1SColin Riley     {
23454640cde1SColin Riley         strm.Printf("Runtime Driver discovered.");
23464640cde1SColin Riley         strm.EOL();
23474640cde1SColin Riley     }
23484640cde1SColin Riley     if (m_libRSCpuRef)
23494640cde1SColin Riley     {
23504640cde1SColin Riley         strm.Printf("CPU Reference Implementation discovered.");
23514640cde1SColin Riley         strm.EOL();
23524640cde1SColin Riley     }
23534640cde1SColin Riley 
23544640cde1SColin Riley     if (m_runtimeHooks.size())
23554640cde1SColin Riley     {
23564640cde1SColin Riley         strm.Printf("Runtime functions hooked:");
23574640cde1SColin Riley         strm.EOL();
23584640cde1SColin Riley         for (auto b : m_runtimeHooks)
23594640cde1SColin Riley         {
23604640cde1SColin Riley             strm.Indent(b.second->defn->name);
23614640cde1SColin Riley             strm.EOL();
23624640cde1SColin Riley         }
23634640cde1SColin Riley     }
23644640cde1SColin Riley     else
23654640cde1SColin Riley     {
23664640cde1SColin Riley         strm.Printf("Runtime is not hooked.");
23674640cde1SColin Riley         strm.EOL();
23684640cde1SColin Riley     }
23694640cde1SColin Riley }
23704640cde1SColin Riley 
23714640cde1SColin Riley void
23724640cde1SColin Riley RenderScriptRuntime::DumpContexts(Stream &strm) const
23734640cde1SColin Riley {
23744640cde1SColin Riley     strm.Printf("Inferred RenderScript Contexts:");
23754640cde1SColin Riley     strm.EOL();
23764640cde1SColin Riley     strm.IndentMore();
23774640cde1SColin Riley 
23784640cde1SColin Riley     std::map<addr_t, uint64_t> contextReferences;
23794640cde1SColin Riley 
238078f339d1SEwan Crawford     // Iterate over all of the currently discovered scripts.
238178f339d1SEwan Crawford     // Note: We cant push or pop from m_scripts inside this loop or it may invalidate script.
23824640cde1SColin Riley     for (const auto & script : m_scripts)
23834640cde1SColin Riley     {
238478f339d1SEwan Crawford         if (!script->context.isValid())
238578f339d1SEwan Crawford             continue;
238678f339d1SEwan Crawford         lldb::addr_t context = *script->context;
238778f339d1SEwan Crawford 
238878f339d1SEwan Crawford         if (contextReferences.find(context) != contextReferences.end())
23894640cde1SColin Riley         {
239078f339d1SEwan Crawford             contextReferences[context]++;
23914640cde1SColin Riley         }
23924640cde1SColin Riley         else
23934640cde1SColin Riley         {
239478f339d1SEwan Crawford             contextReferences[context] = 1;
23954640cde1SColin Riley         }
23964640cde1SColin Riley     }
23974640cde1SColin Riley 
23984640cde1SColin Riley     for (const auto& cRef : contextReferences)
23994640cde1SColin Riley     {
24004640cde1SColin Riley         strm.Printf("Context 0x%" PRIx64 ": %" PRIu64 " script instances", cRef.first, cRef.second);
24014640cde1SColin Riley         strm.EOL();
24024640cde1SColin Riley     }
24034640cde1SColin Riley     strm.IndentLess();
24044640cde1SColin Riley }
24054640cde1SColin Riley 
24064640cde1SColin Riley void
24074640cde1SColin Riley RenderScriptRuntime::DumpKernels(Stream &strm) const
24084640cde1SColin Riley {
24094640cde1SColin Riley     strm.Printf("RenderScript Kernels:");
24104640cde1SColin Riley     strm.EOL();
24114640cde1SColin Riley     strm.IndentMore();
24124640cde1SColin Riley     for (const auto &module : m_rsmodules)
24134640cde1SColin Riley     {
24144640cde1SColin Riley         strm.Printf("Resource '%s':",module->m_resname.c_str());
24154640cde1SColin Riley         strm.EOL();
24164640cde1SColin Riley         for (const auto &kernel : module->m_kernels)
24174640cde1SColin Riley         {
24184640cde1SColin Riley             strm.Indent(kernel.m_name.AsCString());
24194640cde1SColin Riley             strm.EOL();
24204640cde1SColin Riley         }
24214640cde1SColin Riley     }
24224640cde1SColin Riley     strm.IndentLess();
24234640cde1SColin Riley }
24244640cde1SColin Riley 
2425a0f08674SEwan Crawford RenderScriptRuntime::AllocationDetails*
2426a0f08674SEwan Crawford RenderScriptRuntime::FindAllocByID(Stream &strm, const uint32_t alloc_id)
2427a0f08674SEwan Crawford {
2428a0f08674SEwan Crawford     AllocationDetails* alloc = nullptr;
2429a0f08674SEwan Crawford 
2430a0f08674SEwan Crawford     // See if we can find allocation using id as an index;
2431a0f08674SEwan Crawford     if (alloc_id <= m_allocations.size() && alloc_id != 0
2432a0f08674SEwan Crawford         && m_allocations[alloc_id-1]->id == alloc_id)
2433a0f08674SEwan Crawford     {
2434a0f08674SEwan Crawford         alloc = m_allocations[alloc_id-1].get();
2435a0f08674SEwan Crawford         return alloc;
2436a0f08674SEwan Crawford     }
2437a0f08674SEwan Crawford 
2438a0f08674SEwan Crawford     // Fallback to searching
2439a0f08674SEwan Crawford     for (const auto & a : m_allocations)
2440a0f08674SEwan Crawford     {
2441a0f08674SEwan Crawford        if (a->id == alloc_id)
2442a0f08674SEwan Crawford        {
2443a0f08674SEwan Crawford            alloc = a.get();
2444a0f08674SEwan Crawford            break;
2445a0f08674SEwan Crawford        }
2446a0f08674SEwan Crawford     }
2447a0f08674SEwan Crawford 
2448a0f08674SEwan Crawford     if (alloc == nullptr)
2449a0f08674SEwan Crawford     {
2450a0f08674SEwan Crawford         strm.Printf("Error: Couldn't find allocation with id matching %u", alloc_id);
2451a0f08674SEwan Crawford         strm.EOL();
2452a0f08674SEwan Crawford     }
2453a0f08674SEwan Crawford 
2454a0f08674SEwan Crawford     return alloc;
2455a0f08674SEwan Crawford }
2456a0f08674SEwan Crawford 
2457a0f08674SEwan Crawford // Prints the contents of an allocation to the output stream, which may be a file
2458a0f08674SEwan Crawford bool
2459a0f08674SEwan Crawford RenderScriptRuntime::DumpAllocation(Stream &strm, StackFrame* frame_ptr, const uint32_t id)
2460a0f08674SEwan Crawford {
2461a0f08674SEwan Crawford     Log* log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2462a0f08674SEwan Crawford 
2463a0f08674SEwan Crawford     // Check we can find the desired allocation
2464a0f08674SEwan Crawford     AllocationDetails* alloc = FindAllocByID(strm, id);
2465a0f08674SEwan Crawford     if (!alloc)
2466a0f08674SEwan Crawford         return false; // FindAllocByID() will print error message for us here
2467a0f08674SEwan Crawford 
2468a0f08674SEwan Crawford     if (log)
2469a0f08674SEwan Crawford         log->Printf("RenderScriptRuntime::DumpAllocation - Found allocation 0x%" PRIx64, *alloc->address.get());
2470a0f08674SEwan Crawford 
2471a0f08674SEwan Crawford     // Check we have information about the allocation, if not calculate it
2472*8b59062aSEwan Crawford     if (alloc->shouldRefresh())
2473a0f08674SEwan Crawford     {
2474a0f08674SEwan Crawford         if (log)
2475a0f08674SEwan Crawford             log->Printf("RenderScriptRuntime::DumpAllocation - Allocation details not calculated yet, jitting info");
2476a0f08674SEwan Crawford 
2477a0f08674SEwan Crawford         // JIT all the allocation information
2478a0f08674SEwan Crawford         if (!RefreshAllocation(alloc, frame_ptr))
2479a0f08674SEwan Crawford         {
2480a0f08674SEwan Crawford             strm.Printf("Error: Couldn't JIT allocation details");
2481a0f08674SEwan Crawford             strm.EOL();
2482a0f08674SEwan Crawford             return false;
2483a0f08674SEwan Crawford         }
2484a0f08674SEwan Crawford     }
2485a0f08674SEwan Crawford 
2486a0f08674SEwan Crawford     // Establish format and size of each data element
24878b244e21SEwan Crawford     const unsigned int vec_size = *alloc->element.type_vec_size.get();
24888b244e21SEwan Crawford     const Element::DataType type = *alloc->element.type.get();
2489a0f08674SEwan Crawford 
24908b244e21SEwan Crawford     assert(type >= Element::RS_TYPE_NONE && type <= Element::RS_TYPE_BOOLEAN
2491a0f08674SEwan Crawford                                                    && "Invalid allocation type");
2492a0f08674SEwan Crawford 
2493a0f08674SEwan Crawford     lldb::Format format = vec_size == 1 ? static_cast<lldb::Format>(AllocationDetails::RSTypeToFormat[type][eFormatSingle])
2494a0f08674SEwan Crawford                                         : static_cast<lldb::Format>(AllocationDetails::RSTypeToFormat[type][eFormatVector]);
2495a0f08674SEwan Crawford 
24968b244e21SEwan Crawford     const unsigned int data_size = *alloc->element.datum_size.get();
2497a0f08674SEwan Crawford 
2498a0f08674SEwan Crawford     if (log)
24998b244e21SEwan Crawford         log->Printf("RenderScriptRuntime::DumpAllocation - Element size %u bytes, including padding", data_size);
2500a0f08674SEwan Crawford 
250155232f09SEwan Crawford     // Allocate a buffer to copy data into
250255232f09SEwan Crawford     std::shared_ptr<uint8_t> buffer = GetAllocationData(alloc, frame_ptr);
250355232f09SEwan Crawford     if (!buffer)
250455232f09SEwan Crawford     {
250555232f09SEwan Crawford         strm.Printf("Error: Couldn't allocate a read allocation data into memory");
250655232f09SEwan Crawford         strm.EOL();
250755232f09SEwan Crawford         return false;
250855232f09SEwan Crawford     }
250955232f09SEwan Crawford 
2510a0f08674SEwan Crawford     // Calculate stride between rows as there may be padding at end of rows since
2511a0f08674SEwan Crawford     // allocated memory is 16-byte aligned
2512a0f08674SEwan Crawford     if (!alloc->stride.isValid())
2513a0f08674SEwan Crawford     {
2514a0f08674SEwan Crawford         if (alloc->dimension.get()->dim_2 == 0) // We only have one dimension
2515a0f08674SEwan Crawford             alloc->stride = 0;
2516a0f08674SEwan Crawford         else if (!JITAllocationStride(alloc, frame_ptr))
2517a0f08674SEwan Crawford         {
2518a0f08674SEwan Crawford             strm.Printf("Error: Couldn't calculate allocation row stride");
2519a0f08674SEwan Crawford             strm.EOL();
2520a0f08674SEwan Crawford             return false;
2521a0f08674SEwan Crawford         }
2522a0f08674SEwan Crawford     }
2523a0f08674SEwan Crawford     const unsigned int stride = *alloc->stride.get();
25248b244e21SEwan Crawford     const unsigned int size = *alloc->size.get(); // Size of whole allocation
25258b244e21SEwan Crawford     const unsigned int padding = alloc->element.padding.isValid() ? *alloc->element.padding.get() : 0;
2526a0f08674SEwan Crawford     if (log)
25278b244e21SEwan Crawford         log->Printf("RenderScriptRuntime::DumpAllocation - stride %u bytes, size %u bytes, padding %u", stride, size, padding);
2528a0f08674SEwan Crawford 
2529a0f08674SEwan Crawford     // Find dimensions used to index loops, so need to be non-zero
2530a0f08674SEwan Crawford     unsigned int dim_x = alloc->dimension.get()->dim_1;
2531a0f08674SEwan Crawford     dim_x = dim_x == 0 ? 1 : dim_x;
2532a0f08674SEwan Crawford 
2533a0f08674SEwan Crawford     unsigned int dim_y = alloc->dimension.get()->dim_2;
2534a0f08674SEwan Crawford     dim_y = dim_y == 0 ? 1 : dim_y;
2535a0f08674SEwan Crawford 
2536a0f08674SEwan Crawford     unsigned int dim_z = alloc->dimension.get()->dim_3;
2537a0f08674SEwan Crawford     dim_z = dim_z == 0 ? 1 : dim_z;
2538a0f08674SEwan Crawford 
253955232f09SEwan Crawford     // Use data extractor to format output
254055232f09SEwan Crawford     const uint32_t archByteSize = GetProcess()->GetTarget().GetArchitecture().GetAddressByteSize();
254155232f09SEwan Crawford     DataExtractor alloc_data(buffer.get(), size, GetProcess()->GetByteOrder(), archByteSize);
254255232f09SEwan Crawford 
2543a0f08674SEwan Crawford     unsigned int offset = 0;   // Offset in buffer to next element to be printed
2544a0f08674SEwan Crawford     unsigned int prev_row = 0; // Offset to the start of the previous row
2545a0f08674SEwan Crawford 
2546a0f08674SEwan Crawford     // Iterate over allocation dimensions, printing results to user
2547a0f08674SEwan Crawford     strm.Printf("Data (X, Y, Z):");
2548a0f08674SEwan Crawford     for (unsigned int z = 0; z < dim_z; ++z)
2549a0f08674SEwan Crawford     {
2550a0f08674SEwan Crawford         for (unsigned int y = 0; y < dim_y; ++y)
2551a0f08674SEwan Crawford         {
2552a0f08674SEwan Crawford             // Use stride to index start of next row.
2553a0f08674SEwan Crawford             if (!(y==0 && z==0))
2554a0f08674SEwan Crawford                 offset = prev_row + stride;
2555a0f08674SEwan Crawford             prev_row = offset;
2556a0f08674SEwan Crawford 
2557a0f08674SEwan Crawford             // Print each element in the row individually
2558a0f08674SEwan Crawford             for (unsigned int x = 0; x < dim_x; ++x)
2559a0f08674SEwan Crawford             {
2560a0f08674SEwan Crawford                 strm.Printf("\n(%u, %u, %u) = ", x, y, z);
25618b244e21SEwan Crawford                 if ((type == Element::RS_TYPE_NONE) && (alloc->element.children.size() > 0) &&
2562fe06b5adSAdrian McCarthy                     (alloc->element.type_name != Element::GetFallbackStructName()))
25638b244e21SEwan Crawford                 {
25648b244e21SEwan Crawford                     // Here we are dumping an Element of struct type.
25658b244e21SEwan Crawford                     // This is done using expression evaluation with the name of the struct type and pointer to element.
25668b244e21SEwan Crawford 
25678b244e21SEwan Crawford                     // Don't print the name of the resulting expression, since this will be '$[0-9]+'
25688b244e21SEwan Crawford                     DumpValueObjectOptions expr_options;
25698b244e21SEwan Crawford                     expr_options.SetHideName(true);
25708b244e21SEwan Crawford 
25718b244e21SEwan Crawford                     // Setup expression as derefrencing a pointer cast to element address.
2572b1651b8dSEwan Crawford                     char expr_char_buffer[jit_max_expr_size];
2573b1651b8dSEwan Crawford                     int chars_written = snprintf(expr_char_buffer, jit_max_expr_size, "*(%s*) 0x%" PRIx64,
25748b244e21SEwan Crawford                                         alloc->element.type_name.AsCString(), *alloc->data_ptr.get() + offset);
25758b244e21SEwan Crawford 
2576b1651b8dSEwan Crawford                     if (chars_written < 0 || chars_written >= jit_max_expr_size)
25778b244e21SEwan Crawford                     {
25788b244e21SEwan Crawford                         if (log)
25798b244e21SEwan Crawford                             log->Printf("RenderScriptRuntime::DumpAllocation- Error in snprintf()");
25808b244e21SEwan Crawford                         continue;
25818b244e21SEwan Crawford                     }
25828b244e21SEwan Crawford 
25838b244e21SEwan Crawford                     // Evaluate expression
25848b244e21SEwan Crawford                     ValueObjectSP expr_result;
25858b244e21SEwan Crawford                     GetProcess()->GetTarget().EvaluateExpression(expr_char_buffer, frame_ptr, expr_result);
25868b244e21SEwan Crawford 
25878b244e21SEwan Crawford                     // Print the results to our stream.
25888b244e21SEwan Crawford                     expr_result->Dump(strm, expr_options);
25898b244e21SEwan Crawford                 }
25908b244e21SEwan Crawford                 else
25918b244e21SEwan Crawford                 {
25928b244e21SEwan Crawford                     alloc_data.Dump(&strm, offset, format, data_size - padding, 1, 1, LLDB_INVALID_ADDRESS, 0, 0);
25938b244e21SEwan Crawford                 }
25948b244e21SEwan Crawford                 offset += data_size;
2595a0f08674SEwan Crawford             }
2596a0f08674SEwan Crawford         }
2597a0f08674SEwan Crawford     }
2598a0f08674SEwan Crawford     strm.EOL();
2599a0f08674SEwan Crawford 
2600a0f08674SEwan Crawford     return true;
2601a0f08674SEwan Crawford }
2602a0f08674SEwan Crawford 
260315f2bd95SEwan Crawford // Prints infomation regarding all the currently loaded allocations.
260415f2bd95SEwan Crawford // These details are gathered by jitting the runtime, which has as latency.
260515f2bd95SEwan Crawford void
260615f2bd95SEwan Crawford RenderScriptRuntime::ListAllocations(Stream &strm, StackFrame* frame_ptr, bool recompute)
260715f2bd95SEwan Crawford {
260815f2bd95SEwan Crawford     strm.Printf("RenderScript Allocations:");
260915f2bd95SEwan Crawford     strm.EOL();
261015f2bd95SEwan Crawford     strm.IndentMore();
261115f2bd95SEwan Crawford 
261215f2bd95SEwan Crawford     for (auto &alloc : m_allocations)
261315f2bd95SEwan Crawford     {
261415f2bd95SEwan Crawford         // JIT the allocation info if we haven't done it, or the user forces us to.
2615*8b59062aSEwan Crawford         bool do_refresh = alloc->shouldRefresh() || recompute;
261615f2bd95SEwan Crawford 
261715f2bd95SEwan Crawford         // JIT current allocation information
261815f2bd95SEwan Crawford         if (do_refresh && !RefreshAllocation(alloc.get(), frame_ptr))
261915f2bd95SEwan Crawford         {
262015f2bd95SEwan Crawford             strm.Printf("Error: Couldn't evaluate details for allocation %u\n", alloc->id);
262115f2bd95SEwan Crawford             continue;
262215f2bd95SEwan Crawford         }
262315f2bd95SEwan Crawford 
262415f2bd95SEwan Crawford         strm.Printf("%u:\n",alloc->id);
262515f2bd95SEwan Crawford         strm.IndentMore();
262615f2bd95SEwan Crawford 
262715f2bd95SEwan Crawford         strm.Indent("Context: ");
262815f2bd95SEwan Crawford         if (!alloc->context.isValid())
262915f2bd95SEwan Crawford             strm.Printf("unknown\n");
263015f2bd95SEwan Crawford         else
263115f2bd95SEwan Crawford             strm.Printf("0x%" PRIx64 "\n", *alloc->context.get());
263215f2bd95SEwan Crawford 
263315f2bd95SEwan Crawford         strm.Indent("Address: ");
263415f2bd95SEwan Crawford         if (!alloc->address.isValid())
263515f2bd95SEwan Crawford             strm.Printf("unknown\n");
263615f2bd95SEwan Crawford         else
263715f2bd95SEwan Crawford             strm.Printf("0x%" PRIx64 "\n", *alloc->address.get());
263815f2bd95SEwan Crawford 
263915f2bd95SEwan Crawford         strm.Indent("Data pointer: ");
264015f2bd95SEwan Crawford         if (!alloc->data_ptr.isValid())
264115f2bd95SEwan Crawford             strm.Printf("unknown\n");
264215f2bd95SEwan Crawford         else
264315f2bd95SEwan Crawford             strm.Printf("0x%" PRIx64 "\n", *alloc->data_ptr.get());
264415f2bd95SEwan Crawford 
264515f2bd95SEwan Crawford         strm.Indent("Dimensions: ");
264615f2bd95SEwan Crawford         if (!alloc->dimension.isValid())
264715f2bd95SEwan Crawford             strm.Printf("unknown\n");
264815f2bd95SEwan Crawford         else
264915f2bd95SEwan Crawford             strm.Printf("(%d, %d, %d)\n", alloc->dimension.get()->dim_1,
265015f2bd95SEwan Crawford                                           alloc->dimension.get()->dim_2,
265115f2bd95SEwan Crawford                                           alloc->dimension.get()->dim_3);
265215f2bd95SEwan Crawford 
265315f2bd95SEwan Crawford         strm.Indent("Data Type: ");
26548b244e21SEwan Crawford         if (!alloc->element.type.isValid() || !alloc->element.type_vec_size.isValid())
265515f2bd95SEwan Crawford             strm.Printf("unknown\n");
265615f2bd95SEwan Crawford         else
265715f2bd95SEwan Crawford         {
26588b244e21SEwan Crawford             const int vector_size = *alloc->element.type_vec_size.get();
26598b244e21SEwan Crawford             const Element::DataType type = *alloc->element.type.get();
266015f2bd95SEwan Crawford 
26618b244e21SEwan Crawford             if (!alloc->element.type_name.IsEmpty())
26628b244e21SEwan Crawford                 strm.Printf("%s\n", alloc->element.type_name.AsCString());
26638b244e21SEwan Crawford             else if (vector_size > 4 || vector_size < 1 ||
26648b244e21SEwan Crawford                 type < Element::RS_TYPE_NONE || type > Element::RS_TYPE_BOOLEAN)
266515f2bd95SEwan Crawford                 strm.Printf("invalid type\n");
266615f2bd95SEwan Crawford             else
266715f2bd95SEwan Crawford                 strm.Printf("%s\n", AllocationDetails::RsDataTypeToString[static_cast<unsigned int>(type)][vector_size-1]);
266815f2bd95SEwan Crawford         }
266915f2bd95SEwan Crawford 
267015f2bd95SEwan Crawford         strm.Indent("Data Kind: ");
26718b244e21SEwan Crawford         if (!alloc->element.type_kind.isValid())
267215f2bd95SEwan Crawford             strm.Printf("unknown\n");
267315f2bd95SEwan Crawford         else
267415f2bd95SEwan Crawford         {
26758b244e21SEwan Crawford             const Element::DataKind kind = *alloc->element.type_kind.get();
26768b244e21SEwan Crawford             if (kind < Element::RS_KIND_USER || kind > Element::RS_KIND_PIXEL_YUV)
267715f2bd95SEwan Crawford                 strm.Printf("invalid kind\n");
267815f2bd95SEwan Crawford             else
267915f2bd95SEwan Crawford                 strm.Printf("%s\n", AllocationDetails::RsDataKindToString[static_cast<unsigned int>(kind)]);
268015f2bd95SEwan Crawford         }
268115f2bd95SEwan Crawford 
268215f2bd95SEwan Crawford         strm.EOL();
268315f2bd95SEwan Crawford         strm.IndentLess();
268415f2bd95SEwan Crawford     }
268515f2bd95SEwan Crawford     strm.IndentLess();
268615f2bd95SEwan Crawford }
268715f2bd95SEwan Crawford 
26887dc7771cSEwan Crawford // Set breakpoints on every kernel found in RS module
26897dc7771cSEwan Crawford void
26907dc7771cSEwan Crawford RenderScriptRuntime::BreakOnModuleKernels(const RSModuleDescriptorSP rsmodule_sp)
26917dc7771cSEwan Crawford {
26927dc7771cSEwan Crawford     for (const auto &kernel : rsmodule_sp->m_kernels)
26937dc7771cSEwan Crawford     {
26947dc7771cSEwan Crawford         // Don't set breakpoint on 'root' kernel
26957dc7771cSEwan Crawford         if (strcmp(kernel.m_name.AsCString(), "root") == 0)
26967dc7771cSEwan Crawford             continue;
26977dc7771cSEwan Crawford 
26987dc7771cSEwan Crawford         CreateKernelBreakpoint(kernel.m_name);
26997dc7771cSEwan Crawford     }
27007dc7771cSEwan Crawford }
27017dc7771cSEwan Crawford 
27027dc7771cSEwan Crawford // Method is internally called by the 'kernel breakpoint all' command to
27037dc7771cSEwan Crawford // enable or disable breaking on all kernels.
27047dc7771cSEwan Crawford //
27057dc7771cSEwan Crawford // When do_break is true we want to enable this functionality.
27067dc7771cSEwan Crawford // When do_break is false we want to disable it.
27077dc7771cSEwan Crawford void
27087dc7771cSEwan Crawford RenderScriptRuntime::SetBreakAllKernels(bool do_break, TargetSP target)
27097dc7771cSEwan Crawford {
271054782db7SEwan Crawford     Log* log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
27117dc7771cSEwan Crawford 
27127dc7771cSEwan Crawford     InitSearchFilter(target);
27137dc7771cSEwan Crawford 
27147dc7771cSEwan Crawford     // Set breakpoints on all the kernels
27157dc7771cSEwan Crawford     if (do_break && !m_breakAllKernels)
27167dc7771cSEwan Crawford     {
27177dc7771cSEwan Crawford         m_breakAllKernels = true;
27187dc7771cSEwan Crawford 
27197dc7771cSEwan Crawford         for (const auto &module : m_rsmodules)
27207dc7771cSEwan Crawford             BreakOnModuleKernels(module);
27217dc7771cSEwan Crawford 
27227dc7771cSEwan Crawford         if (log)
27237dc7771cSEwan Crawford             log->Printf("RenderScriptRuntime::SetBreakAllKernels(True)"
27247dc7771cSEwan Crawford                         "- breakpoints set on all currently loaded kernels");
27257dc7771cSEwan Crawford     }
27267dc7771cSEwan Crawford     else if (!do_break && m_breakAllKernels) // Breakpoints won't be set on any new kernels.
27277dc7771cSEwan Crawford     {
27287dc7771cSEwan Crawford         m_breakAllKernels = false;
27297dc7771cSEwan Crawford 
27307dc7771cSEwan Crawford         if (log)
27317dc7771cSEwan Crawford             log->Printf("RenderScriptRuntime::SetBreakAllKernels(False) - breakpoints no longer automatically set");
27327dc7771cSEwan Crawford     }
27337dc7771cSEwan Crawford }
27347dc7771cSEwan Crawford 
27357dc7771cSEwan Crawford // Given the name of a kernel this function creates a breakpoint using our
27367dc7771cSEwan Crawford // own breakpoint resolver, and returns the Breakpoint shared pointer.
27377dc7771cSEwan Crawford BreakpointSP
27387dc7771cSEwan Crawford RenderScriptRuntime::CreateKernelBreakpoint(const ConstString& name)
27397dc7771cSEwan Crawford {
274054782db7SEwan Crawford     Log* log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
27417dc7771cSEwan Crawford 
27427dc7771cSEwan Crawford     if (!m_filtersp)
27437dc7771cSEwan Crawford     {
27447dc7771cSEwan Crawford         if (log)
27457dc7771cSEwan Crawford             log->Printf("RenderScriptRuntime::CreateKernelBreakpoint - Error: No breakpoint search filter set");
27467dc7771cSEwan Crawford         return nullptr;
27477dc7771cSEwan Crawford     }
27487dc7771cSEwan Crawford 
27497dc7771cSEwan Crawford     BreakpointResolverSP resolver_sp(new RSBreakpointResolver(nullptr, name));
27507dc7771cSEwan Crawford     BreakpointSP bp = GetProcess()->GetTarget().CreateBreakpoint(m_filtersp, resolver_sp, false, false, false);
27517dc7771cSEwan Crawford 
275254782db7SEwan Crawford     // Give RS breakpoints a specific name, so the user can manipulate them as a group.
275354782db7SEwan Crawford     Error err;
275454782db7SEwan Crawford     if (!bp->AddName("RenderScriptKernel", err) && log)
275554782db7SEwan Crawford         log->Printf("RenderScriptRuntime::CreateKernelBreakpoint: Error setting break name, %s", err.AsCString());
275654782db7SEwan Crawford 
27577dc7771cSEwan Crawford     return bp;
27587dc7771cSEwan Crawford }
27597dc7771cSEwan Crawford 
2760018f5a7eSEwan Crawford // Given an expression for a variable this function tries to calculate the variable's value.
2761018f5a7eSEwan Crawford // If this is possible it returns true and sets the uint64_t parameter to the variables unsigned value.
2762018f5a7eSEwan Crawford // Otherwise function returns false.
2763018f5a7eSEwan Crawford bool
2764018f5a7eSEwan Crawford RenderScriptRuntime::GetFrameVarAsUnsigned(const StackFrameSP frame_sp, const char* var_name, uint64_t& val)
2765018f5a7eSEwan Crawford {
2766018f5a7eSEwan Crawford     Log* log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE));
2767018f5a7eSEwan Crawford     Error error;
2768018f5a7eSEwan Crawford     VariableSP var_sp;
2769018f5a7eSEwan Crawford 
2770018f5a7eSEwan Crawford     // Find variable in stack frame
2771018f5a7eSEwan Crawford     ValueObjectSP value_sp(frame_sp->GetValueForVariableExpressionPath(var_name,
2772018f5a7eSEwan Crawford                                                                        eNoDynamicValues,
2773018f5a7eSEwan Crawford                                                                        StackFrame::eExpressionPathOptionCheckPtrVsMember |
2774018f5a7eSEwan Crawford                                                                        StackFrame::eExpressionPathOptionsAllowDirectIVarAccess,
2775018f5a7eSEwan Crawford                                                                        var_sp,
2776018f5a7eSEwan Crawford                                                                        error));
2777018f5a7eSEwan Crawford     if (!error.Success())
2778018f5a7eSEwan Crawford     {
2779018f5a7eSEwan Crawford         if (log)
2780018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::GetFrameVarAsUnsigned - Error, couldn't find '%s' in frame", var_name);
2781018f5a7eSEwan Crawford 
2782018f5a7eSEwan Crawford         return false;
2783018f5a7eSEwan Crawford     }
2784018f5a7eSEwan Crawford 
2785018f5a7eSEwan Crawford     // Find the unsigned int value for the variable
2786018f5a7eSEwan Crawford     bool success = false;
2787018f5a7eSEwan Crawford     val = value_sp->GetValueAsUnsigned(0, &success);
2788018f5a7eSEwan Crawford     if (!success)
2789018f5a7eSEwan Crawford     {
2790018f5a7eSEwan Crawford         if (log)
2791018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::GetFrameVarAsUnsigned - Error, couldn't parse '%s' as an unsigned int", var_name);
2792018f5a7eSEwan Crawford 
2793018f5a7eSEwan Crawford         return false;
2794018f5a7eSEwan Crawford     }
2795018f5a7eSEwan Crawford 
2796018f5a7eSEwan Crawford     return true;
2797018f5a7eSEwan Crawford }
2798018f5a7eSEwan Crawford 
2799018f5a7eSEwan Crawford // Callback when a kernel breakpoint hits and we're looking for a specific coordinate.
2800018f5a7eSEwan Crawford // Baton parameter contains a pointer to the target coordinate we want to break on.
2801018f5a7eSEwan Crawford // Function then checks the .expand frame for the current coordinate and breaks to user if it matches.
2802018f5a7eSEwan Crawford // Parameter 'break_id' is the id of the Breakpoint which made the callback.
2803018f5a7eSEwan Crawford // Parameter 'break_loc_id' is the id for the BreakpointLocation which was hit,
2804018f5a7eSEwan Crawford // a single logical breakpoint can have multiple addresses.
2805018f5a7eSEwan Crawford bool
2806018f5a7eSEwan Crawford RenderScriptRuntime::KernelBreakpointHit(void *baton, StoppointCallbackContext *ctx,
2807018f5a7eSEwan Crawford                                          user_id_t break_id, user_id_t break_loc_id)
2808018f5a7eSEwan Crawford {
2809018f5a7eSEwan Crawford     Log* log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_LANGUAGE | LIBLLDB_LOG_BREAKPOINTS));
2810018f5a7eSEwan Crawford 
2811018f5a7eSEwan Crawford     assert(baton && "Error: null baton in conditional kernel breakpoint callback");
2812018f5a7eSEwan Crawford 
2813018f5a7eSEwan Crawford     // Coordinate we want to stop on
2814018f5a7eSEwan Crawford     const int* target_coord = static_cast<const int*>(baton);
2815018f5a7eSEwan Crawford 
2816018f5a7eSEwan Crawford     if (log)
2817018f5a7eSEwan Crawford         log->Printf("RenderScriptRuntime::KernelBreakpointHit - Break ID %" PRIu64 ", target coord (%d, %d, %d)",
2818018f5a7eSEwan Crawford                     break_id, target_coord[0], target_coord[1], target_coord[2]);
2819018f5a7eSEwan Crawford 
2820018f5a7eSEwan Crawford     // Go up one stack frame to .expand kernel
2821018f5a7eSEwan Crawford     ExecutionContext context(ctx->exe_ctx_ref);
2822018f5a7eSEwan Crawford     ThreadSP thread_sp = context.GetThreadSP();
2823018f5a7eSEwan Crawford     if (!thread_sp->SetSelectedFrameByIndex(1))
2824018f5a7eSEwan Crawford     {
2825018f5a7eSEwan Crawford         if (log)
2826018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::KernelBreakpointHit - Error, couldn't go up stack frame");
2827018f5a7eSEwan Crawford 
2828018f5a7eSEwan Crawford        return false;
2829018f5a7eSEwan Crawford     }
2830018f5a7eSEwan Crawford 
2831018f5a7eSEwan Crawford     StackFrameSP frame_sp = thread_sp->GetSelectedFrame();
2832018f5a7eSEwan Crawford     if (!frame_sp)
2833018f5a7eSEwan Crawford     {
2834018f5a7eSEwan Crawford         if (log)
2835018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::KernelBreakpointHit - Error, couldn't select .expand stack frame");
2836018f5a7eSEwan Crawford 
2837018f5a7eSEwan Crawford         return false;
2838018f5a7eSEwan Crawford     }
2839018f5a7eSEwan Crawford 
2840018f5a7eSEwan Crawford     // Get values for variables in .expand frame that tell us the current kernel invocation
2841018f5a7eSEwan Crawford     const char* coord_expressions[] = {"rsIndex", "p->current.y", "p->current.z"};
2842018f5a7eSEwan Crawford     uint64_t current_coord[3] = {0, 0, 0};
2843018f5a7eSEwan Crawford 
2844018f5a7eSEwan Crawford     for(int i = 0; i < 3; ++i)
2845018f5a7eSEwan Crawford     {
2846018f5a7eSEwan Crawford         if (!GetFrameVarAsUnsigned(frame_sp, coord_expressions[i], current_coord[i]))
2847018f5a7eSEwan Crawford             return false;
2848018f5a7eSEwan Crawford 
2849018f5a7eSEwan Crawford         if (log)
2850018f5a7eSEwan Crawford             log->Printf("RenderScriptRuntime::KernelBreakpointHit, %s = %" PRIu64, coord_expressions[i], current_coord[i]);
2851018f5a7eSEwan Crawford     }
2852018f5a7eSEwan Crawford 
2853018f5a7eSEwan Crawford     // Check if the current kernel invocation coordinate matches our target coordinate
2854018f5a7eSEwan Crawford     if (current_coord[0] == static_cast<uint64_t>(target_coord[0]) &&
2855018f5a7eSEwan Crawford         current_coord[1] == static_cast<uint64_t>(target_coord[1]) &&
2856018f5a7eSEwan Crawford         current_coord[2] == static_cast<uint64_t>(target_coord[2]))
2857018f5a7eSEwan Crawford     {
2858018f5a7eSEwan Crawford         if (log)
2859018f5a7eSEwan Crawford              log->Printf("RenderScriptRuntime::KernelBreakpointHit, BREAKING %" PRIu64 ", %" PRIu64 ", %" PRIu64,
2860018f5a7eSEwan Crawford                          current_coord[0], current_coord[1], current_coord[2]);
2861018f5a7eSEwan Crawford 
2862018f5a7eSEwan Crawford         BreakpointSP breakpoint_sp = context.GetTargetPtr()->GetBreakpointByID(break_id);
2863018f5a7eSEwan Crawford         assert(breakpoint_sp != nullptr && "Error: Couldn't find breakpoint matching break id for callback");
2864018f5a7eSEwan Crawford         breakpoint_sp->SetEnabled(false); // Optimise since conditional breakpoint should only be hit once.
2865018f5a7eSEwan Crawford         return true;
2866018f5a7eSEwan Crawford     }
2867018f5a7eSEwan Crawford 
2868018f5a7eSEwan Crawford     // No match on coordinate
2869018f5a7eSEwan Crawford     return false;
2870018f5a7eSEwan Crawford }
2871018f5a7eSEwan Crawford 
2872018f5a7eSEwan Crawford // Tries to set a breakpoint on the start of a kernel, resolved using the kernel name.
2873018f5a7eSEwan Crawford // Argument 'coords', represents a three dimensional coordinate which can be used to specify
2874018f5a7eSEwan Crawford // a single kernel instance to break on. If this is set then we add a callback to the breakpoint.
28754640cde1SColin Riley void
2876018f5a7eSEwan Crawford RenderScriptRuntime::PlaceBreakpointOnKernel(Stream &strm, const char* name, const std::array<int,3> coords,
2877018f5a7eSEwan Crawford                                              Error& error, TargetSP target)
28784640cde1SColin Riley {
28794640cde1SColin Riley     if (!name)
28804640cde1SColin Riley     {
28814640cde1SColin Riley         error.SetErrorString("invalid kernel name");
28824640cde1SColin Riley         return;
28834640cde1SColin Riley     }
28844640cde1SColin Riley 
28857dc7771cSEwan Crawford     InitSearchFilter(target);
288698156583SEwan Crawford 
28874640cde1SColin Riley     ConstString kernel_name(name);
28887dc7771cSEwan Crawford     BreakpointSP bp = CreateKernelBreakpoint(kernel_name);
2889018f5a7eSEwan Crawford 
2890018f5a7eSEwan Crawford     // We have a conditional breakpoint on a specific coordinate
2891018f5a7eSEwan Crawford     if (coords[0] != -1)
2892018f5a7eSEwan Crawford     {
2893018f5a7eSEwan Crawford         strm.Printf("Conditional kernel breakpoint on coordinate %d, %d, %d", coords[0], coords[1], coords[2]);
2894018f5a7eSEwan Crawford         strm.EOL();
2895018f5a7eSEwan Crawford 
2896018f5a7eSEwan Crawford         // Allocate memory for the baton, and copy over coordinate
2897018f5a7eSEwan Crawford         int* baton = new int[3];
2898018f5a7eSEwan Crawford         baton[0] = coords[0]; baton[1] = coords[1]; baton[2] = coords[2];
2899018f5a7eSEwan Crawford 
2900018f5a7eSEwan Crawford         // Create a callback that will be invoked everytime the breakpoint is hit.
2901018f5a7eSEwan Crawford         // The baton object passed to the handler is the target coordinate we want to break on.
2902018f5a7eSEwan Crawford         bp->SetCallback(KernelBreakpointHit, baton, true);
2903018f5a7eSEwan Crawford 
2904018f5a7eSEwan Crawford         // Store a shared pointer to the baton, so the memory will eventually be cleaned up after destruction
2905018f5a7eSEwan Crawford         m_conditional_breaks[bp->GetID()] = std::shared_ptr<int>(baton);
2906018f5a7eSEwan Crawford     }
2907018f5a7eSEwan Crawford 
290898156583SEwan Crawford     if (bp)
290998156583SEwan Crawford         bp->GetDescription(&strm, lldb::eDescriptionLevelInitial, false);
29104640cde1SColin Riley }
29114640cde1SColin Riley 
29124640cde1SColin Riley void
29135ec532a9SColin Riley RenderScriptRuntime::DumpModules(Stream &strm) const
29145ec532a9SColin Riley {
29155ec532a9SColin Riley     strm.Printf("RenderScript Modules:");
29165ec532a9SColin Riley     strm.EOL();
29175ec532a9SColin Riley     strm.IndentMore();
29185ec532a9SColin Riley     for (const auto &module : m_rsmodules)
29195ec532a9SColin Riley     {
29204640cde1SColin Riley         module->Dump(strm);
29215ec532a9SColin Riley     }
29225ec532a9SColin Riley     strm.IndentLess();
29235ec532a9SColin Riley }
29245ec532a9SColin Riley 
292578f339d1SEwan Crawford RenderScriptRuntime::ScriptDetails*
292678f339d1SEwan Crawford RenderScriptRuntime::LookUpScript(addr_t address, bool create)
292778f339d1SEwan Crawford {
292878f339d1SEwan Crawford     for (const auto & s : m_scripts)
292978f339d1SEwan Crawford     {
293078f339d1SEwan Crawford         if (s->script.isValid())
293178f339d1SEwan Crawford             if (*s->script == address)
293278f339d1SEwan Crawford                 return s.get();
293378f339d1SEwan Crawford     }
293478f339d1SEwan Crawford     if (create)
293578f339d1SEwan Crawford     {
293678f339d1SEwan Crawford         std::unique_ptr<ScriptDetails> s(new ScriptDetails);
293778f339d1SEwan Crawford         s->script = address;
293878f339d1SEwan Crawford         m_scripts.push_back(std::move(s));
2939d10ca9deSEwan Crawford         return m_scripts.back().get();
294078f339d1SEwan Crawford     }
294178f339d1SEwan Crawford     return nullptr;
294278f339d1SEwan Crawford }
294378f339d1SEwan Crawford 
294478f339d1SEwan Crawford RenderScriptRuntime::AllocationDetails*
294578f339d1SEwan Crawford RenderScriptRuntime::LookUpAllocation(addr_t address, bool create)
294678f339d1SEwan Crawford {
294778f339d1SEwan Crawford     for (const auto & a : m_allocations)
294878f339d1SEwan Crawford     {
294978f339d1SEwan Crawford         if (a->address.isValid())
295078f339d1SEwan Crawford             if (*a->address == address)
295178f339d1SEwan Crawford                 return a.get();
295278f339d1SEwan Crawford     }
295378f339d1SEwan Crawford     if (create)
295478f339d1SEwan Crawford     {
295578f339d1SEwan Crawford         std::unique_ptr<AllocationDetails> a(new AllocationDetails);
295678f339d1SEwan Crawford         a->address = address;
295778f339d1SEwan Crawford         m_allocations.push_back(std::move(a));
2958d10ca9deSEwan Crawford         return m_allocations.back().get();
295978f339d1SEwan Crawford     }
296078f339d1SEwan Crawford     return nullptr;
296178f339d1SEwan Crawford }
296278f339d1SEwan Crawford 
29635ec532a9SColin Riley void
29645ec532a9SColin Riley RSModuleDescriptor::Dump(Stream &strm) const
29655ec532a9SColin Riley {
29665ec532a9SColin Riley     strm.Indent();
29675ec532a9SColin Riley     m_module->GetFileSpec().Dump(&strm);
29684640cde1SColin Riley     if(m_module->GetNumCompileUnits())
29694640cde1SColin Riley     {
29704640cde1SColin Riley         strm.Indent("Debug info loaded.");
29714640cde1SColin Riley     }
29724640cde1SColin Riley     else
29734640cde1SColin Riley     {
29744640cde1SColin Riley         strm.Indent("Debug info does not exist.");
29754640cde1SColin Riley     }
29765ec532a9SColin Riley     strm.EOL();
29775ec532a9SColin Riley     strm.IndentMore();
29785ec532a9SColin Riley     strm.Indent();
2979189598edSColin Riley     strm.Printf("Globals: %" PRIu64, static_cast<uint64_t>(m_globals.size()));
29805ec532a9SColin Riley     strm.EOL();
29815ec532a9SColin Riley     strm.IndentMore();
29825ec532a9SColin Riley     for (const auto &global : m_globals)
29835ec532a9SColin Riley     {
29845ec532a9SColin Riley         global.Dump(strm);
29855ec532a9SColin Riley     }
29865ec532a9SColin Riley     strm.IndentLess();
29875ec532a9SColin Riley     strm.Indent();
2988189598edSColin Riley     strm.Printf("Kernels: %" PRIu64, static_cast<uint64_t>(m_kernels.size()));
29895ec532a9SColin Riley     strm.EOL();
29905ec532a9SColin Riley     strm.IndentMore();
29915ec532a9SColin Riley     for (const auto &kernel : m_kernels)
29925ec532a9SColin Riley     {
29935ec532a9SColin Riley         kernel.Dump(strm);
29945ec532a9SColin Riley     }
29954640cde1SColin Riley     strm.Printf("Pragmas: %"  PRIu64 , static_cast<uint64_t>(m_pragmas.size()));
29964640cde1SColin Riley     strm.EOL();
29974640cde1SColin Riley     strm.IndentMore();
29984640cde1SColin Riley     for (const auto &key_val : m_pragmas)
29994640cde1SColin Riley     {
30004640cde1SColin Riley         strm.Printf("%s: %s", key_val.first.c_str(), key_val.second.c_str());
30014640cde1SColin Riley         strm.EOL();
30024640cde1SColin Riley     }
30035ec532a9SColin Riley     strm.IndentLess(4);
30045ec532a9SColin Riley }
30055ec532a9SColin Riley 
30065ec532a9SColin Riley void
30075ec532a9SColin Riley RSGlobalDescriptor::Dump(Stream &strm) const
30085ec532a9SColin Riley {
30095ec532a9SColin Riley     strm.Indent(m_name.AsCString());
30104640cde1SColin Riley     VariableList var_list;
30114640cde1SColin Riley     m_module->m_module->FindGlobalVariables(m_name, nullptr, true, 1U, var_list);
30124640cde1SColin Riley     if (var_list.GetSize() == 1)
30134640cde1SColin Riley     {
30144640cde1SColin Riley         auto var = var_list.GetVariableAtIndex(0);
30154640cde1SColin Riley         auto type = var->GetType();
30164640cde1SColin Riley         if(type)
30174640cde1SColin Riley         {
30184640cde1SColin Riley             strm.Printf(" - ");
30194640cde1SColin Riley             type->DumpTypeName(&strm);
30204640cde1SColin Riley         }
30214640cde1SColin Riley         else
30224640cde1SColin Riley         {
30234640cde1SColin Riley             strm.Printf(" - Unknown Type");
30244640cde1SColin Riley         }
30254640cde1SColin Riley     }
30264640cde1SColin Riley     else
30274640cde1SColin Riley     {
30284640cde1SColin Riley         strm.Printf(" - variable identified, but not found in binary");
30294640cde1SColin Riley         const Symbol* s = m_module->m_module->FindFirstSymbolWithNameAndType(m_name, eSymbolTypeData);
30304640cde1SColin Riley         if (s)
30314640cde1SColin Riley         {
30324640cde1SColin Riley             strm.Printf(" (symbol exists) ");
30334640cde1SColin Riley         }
30344640cde1SColin Riley     }
30354640cde1SColin Riley 
30365ec532a9SColin Riley     strm.EOL();
30375ec532a9SColin Riley }
30385ec532a9SColin Riley 
30395ec532a9SColin Riley void
30405ec532a9SColin Riley RSKernelDescriptor::Dump(Stream &strm) const
30415ec532a9SColin Riley {
30425ec532a9SColin Riley     strm.Indent(m_name.AsCString());
30435ec532a9SColin Riley     strm.EOL();
30445ec532a9SColin Riley }
30455ec532a9SColin Riley 
30465ec532a9SColin Riley class CommandObjectRenderScriptRuntimeModuleProbe : public CommandObjectParsed
30475ec532a9SColin Riley {
30485ec532a9SColin Riley public:
30495ec532a9SColin Riley     CommandObjectRenderScriptRuntimeModuleProbe(CommandInterpreter &interpreter)
30505ec532a9SColin Riley         : CommandObjectParsed(interpreter, "renderscript module probe",
30515ec532a9SColin Riley                               "Initiates a Probe of all loaded modules for kernels and other renderscript objects.",
30525ec532a9SColin Riley                               "renderscript module probe",
3053e87764f2SEnrico Granata                               eCommandRequiresTarget | eCommandRequiresProcess | eCommandProcessMustBeLaunched)
30545ec532a9SColin Riley     {
30555ec532a9SColin Riley     }
30565ec532a9SColin Riley 
3057222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeModuleProbe() override = default;
30585ec532a9SColin Riley 
30595ec532a9SColin Riley     bool
3060222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
30615ec532a9SColin Riley     {
30625ec532a9SColin Riley         const size_t argc = command.GetArgumentCount();
30635ec532a9SColin Riley         if (argc == 0)
30645ec532a9SColin Riley         {
30655ec532a9SColin Riley             Target *target = m_exe_ctx.GetTargetPtr();
30665ec532a9SColin Riley             RenderScriptRuntime *runtime =
30675ec532a9SColin Riley                 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
30685ec532a9SColin Riley             auto module_list = target->GetImages();
30695ec532a9SColin Riley             bool new_rs_details = runtime->ProbeModules(module_list);
30705ec532a9SColin Riley             if (new_rs_details)
30715ec532a9SColin Riley             {
30725ec532a9SColin Riley                 result.AppendMessage("New renderscript modules added to runtime model.");
30735ec532a9SColin Riley             }
30745ec532a9SColin Riley             result.SetStatus(eReturnStatusSuccessFinishResult);
30755ec532a9SColin Riley             return true;
30765ec532a9SColin Riley         }
30775ec532a9SColin Riley 
30785ec532a9SColin Riley         result.AppendErrorWithFormat("'%s' takes no arguments", m_cmd_name.c_str());
30795ec532a9SColin Riley         result.SetStatus(eReturnStatusFailed);
30805ec532a9SColin Riley         return false;
30815ec532a9SColin Riley     }
30825ec532a9SColin Riley };
30835ec532a9SColin Riley 
30845ec532a9SColin Riley class CommandObjectRenderScriptRuntimeModuleDump : public CommandObjectParsed
30855ec532a9SColin Riley {
30865ec532a9SColin Riley public:
30875ec532a9SColin Riley     CommandObjectRenderScriptRuntimeModuleDump(CommandInterpreter &interpreter)
30885ec532a9SColin Riley         : CommandObjectParsed(interpreter, "renderscript module dump",
30895ec532a9SColin Riley                               "Dumps renderscript specific information for all modules.", "renderscript module dump",
3090e87764f2SEnrico Granata                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
30915ec532a9SColin Riley     {
30925ec532a9SColin Riley     }
30935ec532a9SColin Riley 
3094222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeModuleDump() override = default;
30955ec532a9SColin Riley 
30965ec532a9SColin Riley     bool
3097222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
30985ec532a9SColin Riley     {
30995ec532a9SColin Riley         RenderScriptRuntime *runtime =
31005ec532a9SColin Riley             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
31015ec532a9SColin Riley         runtime->DumpModules(result.GetOutputStream());
31025ec532a9SColin Riley         result.SetStatus(eReturnStatusSuccessFinishResult);
31035ec532a9SColin Riley         return true;
31045ec532a9SColin Riley     }
31055ec532a9SColin Riley };
31065ec532a9SColin Riley 
31075ec532a9SColin Riley class CommandObjectRenderScriptRuntimeModule : public CommandObjectMultiword
31085ec532a9SColin Riley {
31095ec532a9SColin Riley public:
31105ec532a9SColin Riley     CommandObjectRenderScriptRuntimeModule(CommandInterpreter &interpreter)
31115ec532a9SColin Riley         : CommandObjectMultiword(interpreter, "renderscript module", "Commands that deal with renderscript modules.",
31125ec532a9SColin Riley                                  NULL)
31135ec532a9SColin Riley     {
31145ec532a9SColin Riley         LoadSubCommand("probe", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleProbe(interpreter)));
31155ec532a9SColin Riley         LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeModuleDump(interpreter)));
31165ec532a9SColin Riley     }
31175ec532a9SColin Riley 
3118222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeModule() override = default;
31195ec532a9SColin Riley };
31205ec532a9SColin Riley 
31214640cde1SColin Riley class CommandObjectRenderScriptRuntimeKernelList : public CommandObjectParsed
31224640cde1SColin Riley {
31234640cde1SColin Riley public:
31244640cde1SColin Riley     CommandObjectRenderScriptRuntimeKernelList(CommandInterpreter &interpreter)
31254640cde1SColin Riley         : CommandObjectParsed(interpreter, "renderscript kernel list",
31264640cde1SColin Riley                               "Lists renderscript kernel names and associated script resources.", "renderscript kernel list",
31274640cde1SColin Riley                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
31284640cde1SColin Riley     {
31294640cde1SColin Riley     }
31304640cde1SColin Riley 
3131222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernelList() override = default;
31324640cde1SColin Riley 
31334640cde1SColin Riley     bool
3134222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
31354640cde1SColin Riley     {
31364640cde1SColin Riley         RenderScriptRuntime *runtime =
31374640cde1SColin Riley             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
31384640cde1SColin Riley         runtime->DumpKernels(result.GetOutputStream());
31394640cde1SColin Riley         result.SetStatus(eReturnStatusSuccessFinishResult);
31404640cde1SColin Riley         return true;
31414640cde1SColin Riley     }
31424640cde1SColin Riley };
31434640cde1SColin Riley 
31447dc7771cSEwan Crawford class CommandObjectRenderScriptRuntimeKernelBreakpointSet : public CommandObjectParsed
31454640cde1SColin Riley {
31464640cde1SColin Riley public:
31477dc7771cSEwan Crawford     CommandObjectRenderScriptRuntimeKernelBreakpointSet(CommandInterpreter &interpreter)
31487dc7771cSEwan Crawford         : CommandObjectParsed(interpreter, "renderscript kernel breakpoint set",
3149018f5a7eSEwan Crawford                               "Sets a breakpoint on a renderscript kernel.", "renderscript kernel breakpoint set <kernel_name> [-c x,y,z]",
3150018f5a7eSEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched | eCommandProcessMustBePaused), m_options(interpreter)
31514640cde1SColin Riley     {
31524640cde1SColin Riley     }
31534640cde1SColin Riley 
3154222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernelBreakpointSet() override = default;
3155222b937cSEugene Zelenko 
3156222b937cSEugene Zelenko     Options*
3157222b937cSEugene Zelenko     GetOptions() override
3158018f5a7eSEwan Crawford     {
3159018f5a7eSEwan Crawford         return &m_options;
3160018f5a7eSEwan Crawford     }
3161018f5a7eSEwan Crawford 
3162018f5a7eSEwan Crawford     class CommandOptions : public Options
3163018f5a7eSEwan Crawford     {
3164018f5a7eSEwan Crawford     public:
3165018f5a7eSEwan Crawford         CommandOptions(CommandInterpreter &interpreter) : Options(interpreter)
3166018f5a7eSEwan Crawford         {
3167018f5a7eSEwan Crawford         }
3168018f5a7eSEwan Crawford 
3169222b937cSEugene Zelenko         ~CommandOptions() override = default;
3170018f5a7eSEwan Crawford 
3171222b937cSEugene Zelenko         Error
3172222b937cSEugene Zelenko         SetOptionValue(uint32_t option_idx, const char *option_arg) override
3173018f5a7eSEwan Crawford         {
3174018f5a7eSEwan Crawford             Error error;
3175018f5a7eSEwan Crawford             const int short_option = m_getopt_table[option_idx].val;
3176018f5a7eSEwan Crawford 
3177018f5a7eSEwan Crawford             switch (short_option)
3178018f5a7eSEwan Crawford             {
3179018f5a7eSEwan Crawford                 case 'c':
3180018f5a7eSEwan Crawford                     if (!ParseCoordinate(option_arg))
3181018f5a7eSEwan Crawford                         error.SetErrorStringWithFormat("Couldn't parse coordinate '%s', should be in format 'x,y,z'.", option_arg);
3182018f5a7eSEwan Crawford                     break;
3183018f5a7eSEwan Crawford                 default:
3184018f5a7eSEwan Crawford                     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
3185018f5a7eSEwan Crawford                     break;
3186018f5a7eSEwan Crawford             }
3187018f5a7eSEwan Crawford             return error;
3188018f5a7eSEwan Crawford         }
3189018f5a7eSEwan Crawford 
3190018f5a7eSEwan Crawford         // -c takes an argument of the form 'num[,num][,num]'.
3191018f5a7eSEwan Crawford         // Where 'id_cstr' is this argument with the whitespace trimmed.
3192018f5a7eSEwan Crawford         // Missing coordinates are defaulted to zero.
3193018f5a7eSEwan Crawford         bool
3194018f5a7eSEwan Crawford         ParseCoordinate(const char* id_cstr)
3195018f5a7eSEwan Crawford         {
3196018f5a7eSEwan Crawford             RegularExpression regex;
3197018f5a7eSEwan Crawford             RegularExpression::Match regex_match(3);
3198018f5a7eSEwan Crawford 
3199018f5a7eSEwan Crawford             bool matched = false;
3200018f5a7eSEwan Crawford             if(regex.Compile("^([0-9]+),([0-9]+),([0-9]+)$") && regex.Execute(id_cstr, &regex_match))
3201018f5a7eSEwan Crawford                 matched = true;
3202018f5a7eSEwan Crawford             else if(regex.Compile("^([0-9]+),([0-9]+)$") && regex.Execute(id_cstr, &regex_match))
3203018f5a7eSEwan Crawford                 matched = true;
3204018f5a7eSEwan Crawford             else if(regex.Compile("^([0-9]+)$") && regex.Execute(id_cstr, &regex_match))
3205018f5a7eSEwan Crawford                 matched = true;
3206018f5a7eSEwan Crawford             for(uint32_t i = 0; i < 3; i++)
3207018f5a7eSEwan Crawford             {
3208018f5a7eSEwan Crawford                 std::string group;
3209018f5a7eSEwan Crawford                 if(regex_match.GetMatchAtIndex(id_cstr, i + 1, group))
3210018f5a7eSEwan Crawford                     m_coord[i] = (uint32_t)strtoul(group.c_str(), NULL, 0);
3211018f5a7eSEwan Crawford                 else
3212018f5a7eSEwan Crawford                     m_coord[i] = 0;
3213018f5a7eSEwan Crawford             }
3214018f5a7eSEwan Crawford             return matched;
3215018f5a7eSEwan Crawford         }
3216018f5a7eSEwan Crawford 
3217018f5a7eSEwan Crawford         void
3218222b937cSEugene Zelenko         OptionParsingStarting() override
3219018f5a7eSEwan Crawford         {
3220018f5a7eSEwan Crawford             // -1 means the -c option hasn't been set
3221018f5a7eSEwan Crawford             m_coord[0] = -1;
3222018f5a7eSEwan Crawford             m_coord[1] = -1;
3223018f5a7eSEwan Crawford             m_coord[2] = -1;
3224018f5a7eSEwan Crawford         }
3225018f5a7eSEwan Crawford 
3226018f5a7eSEwan Crawford         const OptionDefinition*
3227222b937cSEugene Zelenko         GetDefinitions() override
3228018f5a7eSEwan Crawford         {
3229018f5a7eSEwan Crawford             return g_option_table;
3230018f5a7eSEwan Crawford         }
3231018f5a7eSEwan Crawford 
3232018f5a7eSEwan Crawford         static OptionDefinition g_option_table[];
3233018f5a7eSEwan Crawford         std::array<int,3> m_coord;
3234018f5a7eSEwan Crawford     };
3235018f5a7eSEwan Crawford 
32364640cde1SColin Riley     bool
3237222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
32384640cde1SColin Riley     {
32394640cde1SColin Riley         const size_t argc = command.GetArgumentCount();
3240018f5a7eSEwan Crawford         if (argc < 1)
32414640cde1SColin Riley         {
3242018f5a7eSEwan Crawford             result.AppendErrorWithFormat("'%s' takes 1 argument of kernel name, and an optional coordinate.", m_cmd_name.c_str());
3243018f5a7eSEwan Crawford             result.SetStatus(eReturnStatusFailed);
3244018f5a7eSEwan Crawford             return false;
3245018f5a7eSEwan Crawford         }
3246018f5a7eSEwan Crawford 
32474640cde1SColin Riley         RenderScriptRuntime *runtime =
32484640cde1SColin Riley                 (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
32494640cde1SColin Riley 
32504640cde1SColin Riley         Error error;
3251018f5a7eSEwan Crawford         runtime->PlaceBreakpointOnKernel(result.GetOutputStream(), command.GetArgumentAtIndex(0), m_options.m_coord,
325298156583SEwan Crawford                                          error, m_exe_ctx.GetTargetSP());
32534640cde1SColin Riley 
32544640cde1SColin Riley         if (error.Success())
32554640cde1SColin Riley         {
32564640cde1SColin Riley             result.AppendMessage("Breakpoint(s) created");
32574640cde1SColin Riley             result.SetStatus(eReturnStatusSuccessFinishResult);
32584640cde1SColin Riley             return true;
32594640cde1SColin Riley         }
32604640cde1SColin Riley         result.SetStatus(eReturnStatusFailed);
32614640cde1SColin Riley         result.AppendErrorWithFormat("Error: %s", error.AsCString());
32624640cde1SColin Riley         return false;
32634640cde1SColin Riley     }
32644640cde1SColin Riley 
3265018f5a7eSEwan Crawford private:
3266018f5a7eSEwan Crawford     CommandOptions m_options;
32674640cde1SColin Riley };
32684640cde1SColin Riley 
3269018f5a7eSEwan Crawford OptionDefinition
3270018f5a7eSEwan Crawford CommandObjectRenderScriptRuntimeKernelBreakpointSet::CommandOptions::g_option_table[] =
3271018f5a7eSEwan Crawford {
3272018f5a7eSEwan Crawford     { LLDB_OPT_SET_1, false, "coordinate", 'c', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeValue,
3273018f5a7eSEwan Crawford       "Set a breakpoint on a single invocation of the kernel with specified coordinate.\n"
3274018f5a7eSEwan Crawford       "Coordinate takes the form 'x[,y][,z] where x,y,z are positive integers representing kernel dimensions. "
3275018f5a7eSEwan Crawford       "Any unset dimensions will be defaulted to zero."},
3276018f5a7eSEwan Crawford     { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
3277018f5a7eSEwan Crawford };
3278018f5a7eSEwan Crawford 
32797dc7771cSEwan Crawford class CommandObjectRenderScriptRuntimeKernelBreakpointAll : public CommandObjectParsed
32807dc7771cSEwan Crawford {
32817dc7771cSEwan Crawford public:
32827dc7771cSEwan Crawford     CommandObjectRenderScriptRuntimeKernelBreakpointAll(CommandInterpreter &interpreter)
32837dc7771cSEwan Crawford         : CommandObjectParsed(interpreter, "renderscript kernel breakpoint all",
32847dc7771cSEwan Crawford                               "Automatically sets a breakpoint on all renderscript kernels that are or will be loaded.\n"
32857dc7771cSEwan Crawford                               "Disabling option means breakpoints will no longer be set on any kernels loaded in the future, "
32867dc7771cSEwan Crawford                               "but does not remove currently set breakpoints.",
32877dc7771cSEwan Crawford                               "renderscript kernel breakpoint all <enable/disable>",
32887dc7771cSEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched | eCommandProcessMustBePaused)
32897dc7771cSEwan Crawford     {
32907dc7771cSEwan Crawford     }
32917dc7771cSEwan Crawford 
3292222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernelBreakpointAll() override = default;
32937dc7771cSEwan Crawford 
32947dc7771cSEwan Crawford     bool
3295222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
32967dc7771cSEwan Crawford     {
32977dc7771cSEwan Crawford         const size_t argc = command.GetArgumentCount();
32987dc7771cSEwan Crawford         if (argc != 1)
32997dc7771cSEwan Crawford         {
33007dc7771cSEwan Crawford             result.AppendErrorWithFormat("'%s' takes 1 argument of 'enable' or 'disable'", m_cmd_name.c_str());
33017dc7771cSEwan Crawford             result.SetStatus(eReturnStatusFailed);
33027dc7771cSEwan Crawford             return false;
33037dc7771cSEwan Crawford         }
33047dc7771cSEwan Crawford 
33057dc7771cSEwan Crawford         RenderScriptRuntime *runtime =
33067dc7771cSEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
33077dc7771cSEwan Crawford 
33087dc7771cSEwan Crawford         bool do_break = false;
33097dc7771cSEwan Crawford         const char* argument = command.GetArgumentAtIndex(0);
33107dc7771cSEwan Crawford         if (strcmp(argument, "enable") == 0)
33117dc7771cSEwan Crawford         {
33127dc7771cSEwan Crawford             do_break = true;
33137dc7771cSEwan Crawford             result.AppendMessage("Breakpoints will be set on all kernels.");
33147dc7771cSEwan Crawford         }
33157dc7771cSEwan Crawford         else if (strcmp(argument, "disable") == 0)
33167dc7771cSEwan Crawford         {
33177dc7771cSEwan Crawford             do_break = false;
33187dc7771cSEwan Crawford             result.AppendMessage("Breakpoints will not be set on any new kernels.");
33197dc7771cSEwan Crawford         }
33207dc7771cSEwan Crawford         else
33217dc7771cSEwan Crawford         {
33227dc7771cSEwan Crawford             result.AppendErrorWithFormat("Argument must be either 'enable' or 'disable'");
33237dc7771cSEwan Crawford             result.SetStatus(eReturnStatusFailed);
33247dc7771cSEwan Crawford             return false;
33257dc7771cSEwan Crawford         }
33267dc7771cSEwan Crawford 
33277dc7771cSEwan Crawford         runtime->SetBreakAllKernels(do_break, m_exe_ctx.GetTargetSP());
33287dc7771cSEwan Crawford 
33297dc7771cSEwan Crawford         result.SetStatus(eReturnStatusSuccessFinishResult);
33307dc7771cSEwan Crawford         return true;
33317dc7771cSEwan Crawford     }
33327dc7771cSEwan Crawford };
33337dc7771cSEwan Crawford 
33347dc7771cSEwan Crawford class CommandObjectRenderScriptRuntimeKernelBreakpoint : public CommandObjectMultiword
33357dc7771cSEwan Crawford {
33367dc7771cSEwan Crawford public:
33377dc7771cSEwan Crawford     CommandObjectRenderScriptRuntimeKernelBreakpoint(CommandInterpreter &interpreter)
33387dc7771cSEwan Crawford         : CommandObjectMultiword(interpreter, "renderscript kernel", "Commands that generate breakpoints on renderscript kernels.",
33397dc7771cSEwan Crawford                                  nullptr)
33407dc7771cSEwan Crawford     {
33417dc7771cSEwan Crawford         LoadSubCommand("set", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointSet(interpreter)));
33427dc7771cSEwan Crawford         LoadSubCommand("all", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpointAll(interpreter)));
33437dc7771cSEwan Crawford     }
33447dc7771cSEwan Crawford 
3345222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernelBreakpoint() override = default;
33467dc7771cSEwan Crawford };
33477dc7771cSEwan Crawford 
33484640cde1SColin Riley class CommandObjectRenderScriptRuntimeKernel : public CommandObjectMultiword
33494640cde1SColin Riley {
33504640cde1SColin Riley public:
33514640cde1SColin Riley     CommandObjectRenderScriptRuntimeKernel(CommandInterpreter &interpreter)
33524640cde1SColin Riley         : CommandObjectMultiword(interpreter, "renderscript kernel", "Commands that deal with renderscript kernels.",
33534640cde1SColin Riley                                  NULL)
33544640cde1SColin Riley     {
33554640cde1SColin Riley         LoadSubCommand("list", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelList(interpreter)));
33564640cde1SColin Riley         LoadSubCommand("breakpoint", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernelBreakpoint(interpreter)));
33574640cde1SColin Riley     }
33584640cde1SColin Riley 
3359222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeKernel() override = default;
33604640cde1SColin Riley };
33614640cde1SColin Riley 
33624640cde1SColin Riley class CommandObjectRenderScriptRuntimeContextDump : public CommandObjectParsed
33634640cde1SColin Riley {
33644640cde1SColin Riley public:
33654640cde1SColin Riley     CommandObjectRenderScriptRuntimeContextDump(CommandInterpreter &interpreter)
33664640cde1SColin Riley         : CommandObjectParsed(interpreter, "renderscript context dump",
33674640cde1SColin Riley                               "Dumps renderscript context information.", "renderscript context dump",
33684640cde1SColin Riley                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
33694640cde1SColin Riley     {
33704640cde1SColin Riley     }
33714640cde1SColin Riley 
3372222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeContextDump() override = default;
33734640cde1SColin Riley 
33744640cde1SColin Riley     bool
3375222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
33764640cde1SColin Riley     {
33774640cde1SColin Riley         RenderScriptRuntime *runtime =
33784640cde1SColin Riley             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
33794640cde1SColin Riley         runtime->DumpContexts(result.GetOutputStream());
33804640cde1SColin Riley         result.SetStatus(eReturnStatusSuccessFinishResult);
33814640cde1SColin Riley         return true;
33824640cde1SColin Riley     }
33834640cde1SColin Riley };
33844640cde1SColin Riley 
33854640cde1SColin Riley class CommandObjectRenderScriptRuntimeContext : public CommandObjectMultiword
33864640cde1SColin Riley {
33874640cde1SColin Riley public:
33884640cde1SColin Riley     CommandObjectRenderScriptRuntimeContext(CommandInterpreter &interpreter)
33894640cde1SColin Riley         : CommandObjectMultiword(interpreter, "renderscript context", "Commands that deal with renderscript contexts.",
33904640cde1SColin Riley                                  NULL)
33914640cde1SColin Riley     {
33924640cde1SColin Riley         LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeContextDump(interpreter)));
33934640cde1SColin Riley     }
33944640cde1SColin Riley 
3395222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeContext() override = default;
33964640cde1SColin Riley };
33974640cde1SColin Riley 
3398a0f08674SEwan Crawford class CommandObjectRenderScriptRuntimeAllocationDump : public CommandObjectParsed
3399a0f08674SEwan Crawford {
3400a0f08674SEwan Crawford public:
3401a0f08674SEwan Crawford     CommandObjectRenderScriptRuntimeAllocationDump(CommandInterpreter &interpreter)
3402a0f08674SEwan Crawford         : CommandObjectParsed(interpreter, "renderscript allocation dump",
3403a0f08674SEwan Crawford                               "Displays the contents of a particular allocation", "renderscript allocation dump <ID>",
3404a0f08674SEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched), m_options(interpreter)
3405a0f08674SEwan Crawford     {
3406a0f08674SEwan Crawford     }
3407a0f08674SEwan Crawford 
3408222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocationDump() override = default;
3409222b937cSEugene Zelenko 
3410222b937cSEugene Zelenko     Options*
3411222b937cSEugene Zelenko     GetOptions() override
3412a0f08674SEwan Crawford     {
3413a0f08674SEwan Crawford         return &m_options;
3414a0f08674SEwan Crawford     }
3415a0f08674SEwan Crawford 
3416a0f08674SEwan Crawford     class CommandOptions : public Options
3417a0f08674SEwan Crawford     {
3418a0f08674SEwan Crawford     public:
3419a0f08674SEwan Crawford         CommandOptions(CommandInterpreter &interpreter) : Options(interpreter)
3420a0f08674SEwan Crawford         {
3421a0f08674SEwan Crawford         }
3422a0f08674SEwan Crawford 
3423222b937cSEugene Zelenko         ~CommandOptions() override = default;
3424a0f08674SEwan Crawford 
3425222b937cSEugene Zelenko         Error
3426222b937cSEugene Zelenko         SetOptionValue(uint32_t option_idx, const char *option_arg) override
3427a0f08674SEwan Crawford         {
3428a0f08674SEwan Crawford             Error error;
3429a0f08674SEwan Crawford             const int short_option = m_getopt_table[option_idx].val;
3430a0f08674SEwan Crawford 
3431a0f08674SEwan Crawford             switch (short_option)
3432a0f08674SEwan Crawford             {
3433a0f08674SEwan Crawford                 case 'f':
3434a0f08674SEwan Crawford                     m_outfile.SetFile(option_arg, true);
3435a0f08674SEwan Crawford                     if (m_outfile.Exists())
3436a0f08674SEwan Crawford                     {
3437a0f08674SEwan Crawford                         m_outfile.Clear();
3438a0f08674SEwan Crawford                         error.SetErrorStringWithFormat("file already exists: '%s'", option_arg);
3439a0f08674SEwan Crawford                     }
3440a0f08674SEwan Crawford                     break;
3441a0f08674SEwan Crawford                 default:
3442a0f08674SEwan Crawford                     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
3443a0f08674SEwan Crawford                     break;
3444a0f08674SEwan Crawford             }
3445a0f08674SEwan Crawford             return error;
3446a0f08674SEwan Crawford         }
3447a0f08674SEwan Crawford 
3448a0f08674SEwan Crawford         void
3449222b937cSEugene Zelenko         OptionParsingStarting() override
3450a0f08674SEwan Crawford         {
3451a0f08674SEwan Crawford             m_outfile.Clear();
3452a0f08674SEwan Crawford         }
3453a0f08674SEwan Crawford 
3454a0f08674SEwan Crawford         const OptionDefinition*
3455222b937cSEugene Zelenko         GetDefinitions() override
3456a0f08674SEwan Crawford         {
3457a0f08674SEwan Crawford             return g_option_table;
3458a0f08674SEwan Crawford         }
3459a0f08674SEwan Crawford 
3460a0f08674SEwan Crawford         static OptionDefinition g_option_table[];
3461a0f08674SEwan Crawford         FileSpec m_outfile;
3462a0f08674SEwan Crawford     };
3463a0f08674SEwan Crawford 
3464a0f08674SEwan Crawford     bool
3465222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
3466a0f08674SEwan Crawford     {
3467a0f08674SEwan Crawford         const size_t argc = command.GetArgumentCount();
3468a0f08674SEwan Crawford         if (argc < 1)
3469a0f08674SEwan Crawford         {
3470a0f08674SEwan Crawford             result.AppendErrorWithFormat("'%s' takes 1 argument, an allocation ID. As well as an optional -f argument",
3471a0f08674SEwan Crawford                                          m_cmd_name.c_str());
3472a0f08674SEwan Crawford             result.SetStatus(eReturnStatusFailed);
3473a0f08674SEwan Crawford             return false;
3474a0f08674SEwan Crawford         }
3475a0f08674SEwan Crawford 
3476a0f08674SEwan Crawford         RenderScriptRuntime *runtime =
3477a0f08674SEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
3478a0f08674SEwan Crawford 
3479a0f08674SEwan Crawford         const char* id_cstr = command.GetArgumentAtIndex(0);
3480a0f08674SEwan Crawford         bool convert_complete = false;
3481a0f08674SEwan Crawford         const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
3482a0f08674SEwan Crawford         if (!convert_complete)
3483a0f08674SEwan Crawford         {
3484a0f08674SEwan Crawford             result.AppendErrorWithFormat("invalid allocation id argument '%s'", id_cstr);
3485a0f08674SEwan Crawford             result.SetStatus(eReturnStatusFailed);
3486a0f08674SEwan Crawford             return false;
3487a0f08674SEwan Crawford         }
3488a0f08674SEwan Crawford 
3489a0f08674SEwan Crawford         Stream* output_strm = nullptr;
3490a0f08674SEwan Crawford         StreamFile outfile_stream;
3491a0f08674SEwan Crawford         const FileSpec &outfile_spec = m_options.m_outfile; // Dump allocation to file instead
3492a0f08674SEwan Crawford         if (outfile_spec)
3493a0f08674SEwan Crawford         {
3494a0f08674SEwan Crawford             // Open output file
3495a0f08674SEwan Crawford             char path[256];
3496a0f08674SEwan Crawford             outfile_spec.GetPath(path, sizeof(path));
3497a0f08674SEwan Crawford             if (outfile_stream.GetFile().Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate).Success())
3498a0f08674SEwan Crawford             {
3499a0f08674SEwan Crawford                 output_strm = &outfile_stream;
3500a0f08674SEwan Crawford                 result.GetOutputStream().Printf("Results written to '%s'", path);
3501a0f08674SEwan Crawford                 result.GetOutputStream().EOL();
3502a0f08674SEwan Crawford             }
3503a0f08674SEwan Crawford             else
3504a0f08674SEwan Crawford             {
3505a0f08674SEwan Crawford                 result.AppendErrorWithFormat("Couldn't open file '%s'", path);
3506a0f08674SEwan Crawford                 result.SetStatus(eReturnStatusFailed);
3507a0f08674SEwan Crawford                 return false;
3508a0f08674SEwan Crawford             }
3509a0f08674SEwan Crawford         }
3510a0f08674SEwan Crawford         else
3511a0f08674SEwan Crawford             output_strm = &result.GetOutputStream();
3512a0f08674SEwan Crawford 
3513a0f08674SEwan Crawford         assert(output_strm != nullptr);
3514a0f08674SEwan Crawford         bool success = runtime->DumpAllocation(*output_strm, m_exe_ctx.GetFramePtr(), id);
3515a0f08674SEwan Crawford 
3516a0f08674SEwan Crawford         if (success)
3517a0f08674SEwan Crawford             result.SetStatus(eReturnStatusSuccessFinishResult);
3518a0f08674SEwan Crawford         else
3519a0f08674SEwan Crawford             result.SetStatus(eReturnStatusFailed);
3520a0f08674SEwan Crawford 
3521a0f08674SEwan Crawford         return true;
3522a0f08674SEwan Crawford     }
3523a0f08674SEwan Crawford 
3524a0f08674SEwan Crawford private:
3525a0f08674SEwan Crawford     CommandOptions m_options;
3526a0f08674SEwan Crawford };
3527a0f08674SEwan Crawford 
3528a0f08674SEwan Crawford OptionDefinition
3529a0f08674SEwan Crawford CommandObjectRenderScriptRuntimeAllocationDump::CommandOptions::g_option_table[] =
3530a0f08674SEwan Crawford {
3531a0f08674SEwan Crawford     { LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename,
3532a0f08674SEwan Crawford       "Print results to specified file instead of command line."},
3533a0f08674SEwan Crawford     { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
3534a0f08674SEwan Crawford };
3535a0f08674SEwan Crawford 
353615f2bd95SEwan Crawford class CommandObjectRenderScriptRuntimeAllocationList : public CommandObjectParsed
353715f2bd95SEwan Crawford {
353815f2bd95SEwan Crawford public:
353915f2bd95SEwan Crawford     CommandObjectRenderScriptRuntimeAllocationList(CommandInterpreter &interpreter)
354015f2bd95SEwan Crawford         : CommandObjectParsed(interpreter, "renderscript allocation list",
354115f2bd95SEwan Crawford                               "List renderscript allocations and their information.", "renderscript allocation list",
354215f2bd95SEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched), m_options(interpreter)
354315f2bd95SEwan Crawford     {
354415f2bd95SEwan Crawford     }
354515f2bd95SEwan Crawford 
3546222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocationList() override = default;
3547222b937cSEugene Zelenko 
3548222b937cSEugene Zelenko     Options*
3549222b937cSEugene Zelenko     GetOptions() override
355015f2bd95SEwan Crawford     {
355115f2bd95SEwan Crawford         return &m_options;
355215f2bd95SEwan Crawford     }
355315f2bd95SEwan Crawford 
355415f2bd95SEwan Crawford     class CommandOptions : public Options
355515f2bd95SEwan Crawford     {
355615f2bd95SEwan Crawford     public:
355715f2bd95SEwan Crawford         CommandOptions(CommandInterpreter &interpreter) : Options(interpreter), m_refresh(false)
355815f2bd95SEwan Crawford         {
355915f2bd95SEwan Crawford         }
356015f2bd95SEwan Crawford 
3561222b937cSEugene Zelenko         ~CommandOptions() override = default;
356215f2bd95SEwan Crawford 
3563222b937cSEugene Zelenko         Error
3564222b937cSEugene Zelenko         SetOptionValue(uint32_t option_idx, const char *option_arg) override
356515f2bd95SEwan Crawford         {
356615f2bd95SEwan Crawford             Error error;
356715f2bd95SEwan Crawford             const int short_option = m_getopt_table[option_idx].val;
356815f2bd95SEwan Crawford 
356915f2bd95SEwan Crawford             switch (short_option)
357015f2bd95SEwan Crawford             {
357115f2bd95SEwan Crawford                 case 'r':
357215f2bd95SEwan Crawford                     m_refresh = true;
357315f2bd95SEwan Crawford                     break;
357415f2bd95SEwan Crawford                 default:
357515f2bd95SEwan Crawford                     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
357615f2bd95SEwan Crawford                     break;
357715f2bd95SEwan Crawford             }
357815f2bd95SEwan Crawford             return error;
357915f2bd95SEwan Crawford         }
358015f2bd95SEwan Crawford 
358115f2bd95SEwan Crawford         void
3582222b937cSEugene Zelenko         OptionParsingStarting() override
358315f2bd95SEwan Crawford         {
358415f2bd95SEwan Crawford             m_refresh = false;
358515f2bd95SEwan Crawford         }
358615f2bd95SEwan Crawford 
358715f2bd95SEwan Crawford         const OptionDefinition*
3588222b937cSEugene Zelenko         GetDefinitions() override
358915f2bd95SEwan Crawford         {
359015f2bd95SEwan Crawford             return g_option_table;
359115f2bd95SEwan Crawford         }
359215f2bd95SEwan Crawford 
359315f2bd95SEwan Crawford         static OptionDefinition g_option_table[];
359415f2bd95SEwan Crawford         bool m_refresh;
359515f2bd95SEwan Crawford     };
359615f2bd95SEwan Crawford 
359715f2bd95SEwan Crawford     bool
3598222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
359915f2bd95SEwan Crawford     {
360015f2bd95SEwan Crawford         RenderScriptRuntime *runtime =
360115f2bd95SEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
360215f2bd95SEwan Crawford         runtime->ListAllocations(result.GetOutputStream(), m_exe_ctx.GetFramePtr(), m_options.m_refresh);
360315f2bd95SEwan Crawford         result.SetStatus(eReturnStatusSuccessFinishResult);
360415f2bd95SEwan Crawford         return true;
360515f2bd95SEwan Crawford     }
360615f2bd95SEwan Crawford 
360715f2bd95SEwan Crawford private:
360815f2bd95SEwan Crawford     CommandOptions m_options;
360915f2bd95SEwan Crawford };
361015f2bd95SEwan Crawford 
361115f2bd95SEwan Crawford OptionDefinition
361215f2bd95SEwan Crawford CommandObjectRenderScriptRuntimeAllocationList::CommandOptions::g_option_table[] =
361315f2bd95SEwan Crawford {
361415f2bd95SEwan Crawford     { LLDB_OPT_SET_1, false, "refresh", 'r', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone,
361515f2bd95SEwan Crawford       "Recompute allocation details."},
361615f2bd95SEwan Crawford     { 0, false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
361715f2bd95SEwan Crawford };
361815f2bd95SEwan Crawford 
361955232f09SEwan Crawford class CommandObjectRenderScriptRuntimeAllocationLoad : public CommandObjectParsed
362055232f09SEwan Crawford {
362155232f09SEwan Crawford public:
362255232f09SEwan Crawford     CommandObjectRenderScriptRuntimeAllocationLoad(CommandInterpreter &interpreter)
362355232f09SEwan Crawford         : CommandObjectParsed(interpreter, "renderscript allocation load",
362455232f09SEwan Crawford                               "Loads renderscript allocation contents from a file.", "renderscript allocation load <ID> <filename>",
362555232f09SEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
362655232f09SEwan Crawford     {
362755232f09SEwan Crawford     }
362855232f09SEwan Crawford 
3629222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocationLoad() override = default;
363055232f09SEwan Crawford 
363155232f09SEwan Crawford     bool
3632222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
363355232f09SEwan Crawford     {
363455232f09SEwan Crawford         const size_t argc = command.GetArgumentCount();
363555232f09SEwan Crawford         if (argc != 2)
363655232f09SEwan Crawford         {
363755232f09SEwan Crawford             result.AppendErrorWithFormat("'%s' takes 2 arguments, an allocation ID and filename to read from.", m_cmd_name.c_str());
363855232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
363955232f09SEwan Crawford             return false;
364055232f09SEwan Crawford         }
364155232f09SEwan Crawford 
364255232f09SEwan Crawford         RenderScriptRuntime *runtime =
364355232f09SEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
364455232f09SEwan Crawford 
364555232f09SEwan Crawford         const char* id_cstr = command.GetArgumentAtIndex(0);
364655232f09SEwan Crawford         bool convert_complete = false;
364755232f09SEwan Crawford         const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
364855232f09SEwan Crawford         if (!convert_complete)
364955232f09SEwan Crawford         {
365055232f09SEwan Crawford             result.AppendErrorWithFormat ("invalid allocation id argument '%s'", id_cstr);
365155232f09SEwan Crawford             result.SetStatus (eReturnStatusFailed);
365255232f09SEwan Crawford             return false;
365355232f09SEwan Crawford         }
365455232f09SEwan Crawford 
365555232f09SEwan Crawford         const char* filename = command.GetArgumentAtIndex(1);
365655232f09SEwan Crawford         bool success = runtime->LoadAllocation(result.GetOutputStream(), id, filename, m_exe_ctx.GetFramePtr());
365755232f09SEwan Crawford 
365855232f09SEwan Crawford         if (success)
365955232f09SEwan Crawford             result.SetStatus(eReturnStatusSuccessFinishResult);
366055232f09SEwan Crawford         else
366155232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
366255232f09SEwan Crawford 
366355232f09SEwan Crawford         return true;
366455232f09SEwan Crawford     }
366555232f09SEwan Crawford };
366655232f09SEwan Crawford 
366755232f09SEwan Crawford class CommandObjectRenderScriptRuntimeAllocationSave : public CommandObjectParsed
366855232f09SEwan Crawford {
366955232f09SEwan Crawford public:
367055232f09SEwan Crawford     CommandObjectRenderScriptRuntimeAllocationSave(CommandInterpreter &interpreter)
367155232f09SEwan Crawford         : CommandObjectParsed(interpreter, "renderscript allocation save",
367255232f09SEwan Crawford                               "Write renderscript allocation contents to a file.", "renderscript allocation save <ID> <filename>",
367355232f09SEwan Crawford                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
367455232f09SEwan Crawford     {
367555232f09SEwan Crawford     }
367655232f09SEwan Crawford 
3677222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocationSave() override = default;
367855232f09SEwan Crawford 
367955232f09SEwan Crawford     bool
3680222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
368155232f09SEwan Crawford     {
368255232f09SEwan Crawford         const size_t argc = command.GetArgumentCount();
368355232f09SEwan Crawford         if (argc != 2)
368455232f09SEwan Crawford         {
368555232f09SEwan Crawford             result.AppendErrorWithFormat("'%s' takes 2 arguments, an allocation ID and filename to read from.", m_cmd_name.c_str());
368655232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
368755232f09SEwan Crawford             return false;
368855232f09SEwan Crawford         }
368955232f09SEwan Crawford 
369055232f09SEwan Crawford         RenderScriptRuntime *runtime =
369155232f09SEwan Crawford           static_cast<RenderScriptRuntime *>(m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript));
369255232f09SEwan Crawford 
369355232f09SEwan Crawford         const char* id_cstr = command.GetArgumentAtIndex(0);
369455232f09SEwan Crawford         bool convert_complete = false;
369555232f09SEwan Crawford         const uint32_t id = StringConvert::ToUInt32(id_cstr, UINT32_MAX, 0, &convert_complete);
369655232f09SEwan Crawford         if (!convert_complete)
369755232f09SEwan Crawford         {
369855232f09SEwan Crawford             result.AppendErrorWithFormat ("invalid allocation id argument '%s'", id_cstr);
369955232f09SEwan Crawford             result.SetStatus (eReturnStatusFailed);
370055232f09SEwan Crawford             return false;
370155232f09SEwan Crawford         }
370255232f09SEwan Crawford 
370355232f09SEwan Crawford         const char* filename = command.GetArgumentAtIndex(1);
370455232f09SEwan Crawford         bool success = runtime->SaveAllocation(result.GetOutputStream(), id, filename, m_exe_ctx.GetFramePtr());
370555232f09SEwan Crawford 
370655232f09SEwan Crawford         if (success)
370755232f09SEwan Crawford             result.SetStatus(eReturnStatusSuccessFinishResult);
370855232f09SEwan Crawford         else
370955232f09SEwan Crawford             result.SetStatus(eReturnStatusFailed);
371055232f09SEwan Crawford 
371155232f09SEwan Crawford         return true;
371255232f09SEwan Crawford     }
371355232f09SEwan Crawford };
371455232f09SEwan Crawford 
371515f2bd95SEwan Crawford class CommandObjectRenderScriptRuntimeAllocation : public CommandObjectMultiword
371615f2bd95SEwan Crawford {
371715f2bd95SEwan Crawford public:
371815f2bd95SEwan Crawford     CommandObjectRenderScriptRuntimeAllocation(CommandInterpreter &interpreter)
371915f2bd95SEwan Crawford         : CommandObjectMultiword(interpreter, "renderscript allocation", "Commands that deal with renderscript allocations.",
372015f2bd95SEwan Crawford                                  NULL)
372115f2bd95SEwan Crawford     {
372215f2bd95SEwan Crawford         LoadSubCommand("list", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationList(interpreter)));
3723a0f08674SEwan Crawford         LoadSubCommand("dump", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationDump(interpreter)));
372455232f09SEwan Crawford         LoadSubCommand("save", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationSave(interpreter)));
372555232f09SEwan Crawford         LoadSubCommand("load", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocationLoad(interpreter)));
372615f2bd95SEwan Crawford     }
372715f2bd95SEwan Crawford 
3728222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeAllocation() override = default;
372915f2bd95SEwan Crawford };
373015f2bd95SEwan Crawford 
37314640cde1SColin Riley class CommandObjectRenderScriptRuntimeStatus : public CommandObjectParsed
37324640cde1SColin Riley {
37334640cde1SColin Riley public:
37344640cde1SColin Riley     CommandObjectRenderScriptRuntimeStatus(CommandInterpreter &interpreter)
37354640cde1SColin Riley         : CommandObjectParsed(interpreter, "renderscript status",
37364640cde1SColin Riley                               "Displays current renderscript runtime status.", "renderscript status",
37374640cde1SColin Riley                               eCommandRequiresProcess | eCommandProcessMustBeLaunched)
37384640cde1SColin Riley     {
37394640cde1SColin Riley     }
37404640cde1SColin Riley 
3741222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntimeStatus() override = default;
37424640cde1SColin Riley 
37434640cde1SColin Riley     bool
3744222b937cSEugene Zelenko     DoExecute(Args &command, CommandReturnObject &result) override
37454640cde1SColin Riley     {
37464640cde1SColin Riley         RenderScriptRuntime *runtime =
37474640cde1SColin Riley             (RenderScriptRuntime *)m_exe_ctx.GetProcessPtr()->GetLanguageRuntime(eLanguageTypeExtRenderScript);
37484640cde1SColin Riley         runtime->Status(result.GetOutputStream());
37494640cde1SColin Riley         result.SetStatus(eReturnStatusSuccessFinishResult);
37504640cde1SColin Riley         return true;
37514640cde1SColin Riley     }
37524640cde1SColin Riley };
37534640cde1SColin Riley 
37545ec532a9SColin Riley class CommandObjectRenderScriptRuntime : public CommandObjectMultiword
37555ec532a9SColin Riley {
37565ec532a9SColin Riley public:
37575ec532a9SColin Riley     CommandObjectRenderScriptRuntime(CommandInterpreter &interpreter)
37585ec532a9SColin Riley         : CommandObjectMultiword(interpreter, "renderscript", "A set of commands for operating on renderscript.",
37595ec532a9SColin Riley                                  "renderscript <subcommand> [<subcommand-options>]")
37605ec532a9SColin Riley     {
37615ec532a9SColin Riley         LoadSubCommand("module", CommandObjectSP(new CommandObjectRenderScriptRuntimeModule(interpreter)));
37624640cde1SColin Riley         LoadSubCommand("status", CommandObjectSP(new CommandObjectRenderScriptRuntimeStatus(interpreter)));
37634640cde1SColin Riley         LoadSubCommand("kernel", CommandObjectSP(new CommandObjectRenderScriptRuntimeKernel(interpreter)));
37644640cde1SColin Riley         LoadSubCommand("context", CommandObjectSP(new CommandObjectRenderScriptRuntimeContext(interpreter)));
376515f2bd95SEwan Crawford         LoadSubCommand("allocation", CommandObjectSP(new CommandObjectRenderScriptRuntimeAllocation(interpreter)));
37665ec532a9SColin Riley     }
37675ec532a9SColin Riley 
3768222b937cSEugene Zelenko     ~CommandObjectRenderScriptRuntime() override = default;
37695ec532a9SColin Riley };
3770ef20b08fSColin Riley 
3771ef20b08fSColin Riley void
3772ef20b08fSColin Riley RenderScriptRuntime::Initiate()
37735ec532a9SColin Riley {
3774ef20b08fSColin Riley     assert(!m_initiated);
37755ec532a9SColin Riley }
3776ef20b08fSColin Riley 
3777ef20b08fSColin Riley RenderScriptRuntime::RenderScriptRuntime(Process *process)
37787dc7771cSEwan Crawford     : lldb_private::CPPLanguageRuntime(process), m_initiated(false), m_debuggerPresentFlagged(false),
37797dc7771cSEwan Crawford       m_breakAllKernels(false)
3780ef20b08fSColin Riley {
37814640cde1SColin Riley     ModulesDidLoad(process->GetTarget().GetImages());
3782ef20b08fSColin Riley }
37834640cde1SColin Riley 
37844640cde1SColin Riley lldb::CommandObjectSP
37854640cde1SColin Riley RenderScriptRuntime::GetCommandObject(lldb_private::CommandInterpreter& interpreter)
37864640cde1SColin Riley {
37874640cde1SColin Riley     static CommandObjectSP command_object;
37884640cde1SColin Riley     if(!command_object)
37894640cde1SColin Riley     {
37904640cde1SColin Riley         command_object.reset(new CommandObjectRenderScriptRuntime(interpreter));
37914640cde1SColin Riley     }
37924640cde1SColin Riley     return command_object;
37934640cde1SColin Riley }
37944640cde1SColin Riley 
379578f339d1SEwan Crawford RenderScriptRuntime::~RenderScriptRuntime() = default;
3796